I recently ran into some unusual behavior.
foo.py
a = 0
def bar():
print (a)
Console:
>>> import foo
>>> foo.bar()
0
>>> foo.a = 10
>>> foo.bar()
10
Console:
>>> from foo import *
>>> bar()
0
>>> a
0
>>> a = 10
>>> a
10
>>> bar()
0
I'm inferring that import *
is actually creating two copies of a
- one in the global namespace and one inside the foo
module which cannot be accessed. Is this behavior explained/documented anywhere? I'm having trouble figuring out what to search for.
This seems like a notable and unexpected consequence of import *
but for some reason I've never seen it brought up before.
In Python, you use the import keyword to make code in one module available in another.
It imports everything (that is not a private variable, i.e.: variables whose names start with _ or __ ), and you should try not to use it according to "Properly importing modules in Python" to avoid polluting the local namespace.
The difference between import and from import in Python is: import imports an entire code library. from import imports a specific member or members of the library.
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
There is no such thing as a hidden namespace in Python and the described behaviour is the normal and expected one.
You should read https://docs.python.org/3/tutorial/modules.html#more-on-modules in order to understand better how the globals do do work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With