我正在阅读 http://docs.python.org/2/tutorial/modules.html#more-on-modules并想知道以下内容是否正确:
Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.
显然不是:
>>> def foo(): import sys
...
>>> foo()
>>> sys.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
参见 http://ideone.com/cLK09v用于在线演示。
那么,这是 Python 文档中的错误还是我不明白什么?
最佳答案
是的,这是文档错误。 import
语句将名称导入当前 命名空间。通常 import
在函数和类之外使用,但正如您所发现的,它确实在它们内部起作用。在您的示例函数中,当函数被调用时,模块被导入到函数的本地命名空间中。 (您没有这样做,但无论如何都不会使其在函数外部可用。)
global
关键字在这里确实有效,但是:
def foo():
global sys
import sys
foo()
sys.path
关于python - Python 文档中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283821/