2013-06-24 25 views
0

我注意到globals()字典在模块内部包含与主脚本不同的数据。我看到的主要区别是'__builtins__'变量。'__builtins__'是否与main不同?

这是意想不到的,有人能解释为什么会发生这种情况吗?

$> cat main.py 
import foo 
print "From main", globals() 

$> cat foo.py 
print "From module:", globals() 

$> python main.py 
From module: {'__builtins__': {'bytearray': <type 'bytearray'>, 
'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 
'help': Type help() for interactive help, or help(object) for help about object. 
#...much more stuff 
From main {'__builtins__': <module '__builtin__' (built-in)>, 
'__file__': 'main.py', '__package__': None, '__name__': '__main__', 
'foo': <module 'foo' from '.../foo.pyc'>, '__doc__': None} 

我使用了Python版本2.6.6

$> python --version 
Python 2.6.6 
+1

这是为什么会出乎意料?也许如果我们知道你的期望,我们可以提供更好的答案... – mgilson

+0

我期待'globals()'在模块内部/外部是唯一的 – petrum

回答

1

之所以他们在the documentation描述不同。

globals()返回表示当前全局符号表 表的字典。这总是当前模块的字典(在 功能或方法中,这是定义它的模块,而不是调用它的 模块)。

+0

感谢您的快速回复! – petrum

相关问题