Are there module level variables in Python?
I am writing in a caller script:
from XXX import config
....
config.limit = limit
data.load_data()
where config.py
has
limit = None
inside and data.py
has
from .config import *
...
def load_data():
...
if limit is not None:
limit_data(limit)
I expected everyone to reference the same varibale limit
in config.py
. Unfortunately, during debugging, I see that I load_data
see the limit None
, despite the fact that it was set earlier.
Why?
source to share
When you execute from .config import *
, you import the copy limit
from config
into your own namespace. The object limit
that is in config
is not the same as the one you are importing. They are in their own namespaces and are independent of each other.
As a workaround for this, consider the following example:
A.py
foo = 5
def print_foo():
print(foo)
B.py
import A
A.foo = 10
A.print_foo()
Now the launch B.py
should give:
$ python B.py
10
Meaning, you can refer to the same variable by adding a namespace qualifier.
For relative imports, you would do something like this:
app/ __init__.py A.py B.py
In B.py
you call import app.A
. Then you must refer to the variable as app.A.limit
.
source to share