Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Import Star Creating Hidden Namespace?

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.

like image 985
user65 Avatar asked Nov 24 '15 21:11

user65


People also ask

What import * means in Python?

In Python, you use the import keyword to make code in one module available in another.

What is the use of * asterisk with import in Python?

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.

What is the difference between import and import * in Python?

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.

What does __ all __ mean in Python?

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.


1 Answers

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.

like image 169
sorin Avatar answered Oct 15 '22 23:10

sorin