简体   繁体   English

Python Import Star创建隐藏的命名空间?

[英]Python Import Star Creating Hidden Namespace?

I recently ran into some unusual behavior. 我最近遇到了一些不寻常的行为。

foo.py 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. 我推断import *实际上是创建两个副本a -一个全局命名空间和一个里面foo不能访问模块。 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. 这似乎是import *的显着和意想不到的结果import *但由于某种原因,我以前从未见过它。

There is no such thing as a hidden namespace in Python and the described behaviour is the normal and expected one. 在Python中没有隐藏的命名空间,所描述的行为是正常的和预期的行为。

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. 您应该阅读https://docs.python.org/3/tutorial/modules.html#more-on-modules ,以便更好地了解全局变量的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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