简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM