Python extract variables from an imported file

2019-07-07 04:49发布

问题:

I've 3 files. One is for defining the variables and other two contain the required modules.

variable.py

my_var = ""

test.py

import variable

def trial():
    variable.my_var = "Hello"

main.py (not working)

from variable import *
from test import trial

if __name__ == "__main__":
    trial()
    print my_var

And when I run main.py, it gives nothing. However, if I change main.py like this,

main.py (working)

import variable
from test import trial

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

And it gives me the expected output i.e. Hello.

That variable.py, in my case, contains more variables and I don't want to use variable.<variable name> while accessing them. While modifying them, using variable.<variable name> is not a problem as I'm gonna modify only once depending on the user's input and then access them across multiple files multiple times rest of the time.

Now my question is, is there a way to extract all the variables in main.py after they are modified by test.py and use them without the prefix variable.?

回答1:

What you want to achieve is not possible. from MODULE import * imports all the variables names and the values into your namespace, but not the variables themselves. The variables are allocated in your local namespace and changing their value is therefore not reflected onto their origin. However, changes on mutable objects are reflected because the values you import are basically the references to instances.

That is one of the many reasons why unqualified imports using the above construct are not recommended. Instead, you should question your program structure and the design decisions you took. Working with a huge amount of module-level variables can become cumbersome and very inconvenient in the long term.

Think about using a more structured approach to your application, for example by using classes.

Again I would like to point out and give credits to this thread which, in essence, addresses the same problem.


EDIT For the sake of completeness. It is possible, but this approach is not recommended. You would have to re-import the module every time you apply modifications to its non-referential variables:

from variable import *  # optional
from test import trial

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


标签: python import