import - Python extract variables from an imported file -


i've 3 files. 1 defining variables , other 2 contain required modules.

variable.py

my_var = "" 

test.py

import variable  def trial():     variable.my_var = "hello" 

main.py (not working)

from variable import * test import trial  if __name__ == "__main__":     trial()     print my_var 

and when run main.py, gives nothing. however, if change main.py this,

main.py (working)

import variable test import trial  if __name__ == "__main__":     trial()     print variable.my_var 

and gives me expected output i.e. hello.

that variable.py, in case, contains more variables , don't want use variable.<variable name> while accessing them. while modifying them, using variable.<variable name> not problem i'm gonna modify once depending on user's input , access them across multiple files multiple times rest of time.

now question is, there way extract variables in main.py after modified test.py , use them without prefix variable.?

what want achieve not possible. from module import * imports variables names , values namespace, not variables themselves. variables allocated in local namespace , changing value therefore not reflected onto origin. however, changes on mutable objects reflected because values import references instances.

that 1 of many reasons why unqualified imports using above construct not recommended. instead, should question program structure , design decisions took. working huge amount of module-level variables can become cumbersome , inconvenient in long term.

think using more structured approach application, example using classes.

again point out , give credits this thread which, in essence, addresses same problem.


edit sake of completeness. possible, approach not recommended. have re-import module every time apply modifications non-referential variables:

from variable import *  # optional test import trial  if __name__ == "__main__":     trial()     variable import *  # re-import variables...     print my_var 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -