有一部分__import__
在 Python 文档中,我不明白:
__import__(name[, globals[, locals[, fromlist[, level]]]])
The function imports the module
name
, potentially using the givenglobals
andlocals
to determine how to interpret thename
in a package context. The standard implementation does not use itslocals
argument at all, and uses itsglobals
only to determine the package context of the import statement.
模块名称有什么可“解释”的?什么是包上下文?
使用这些参数的示例调用如下所示:
spam = __import__('spam', globals(), locals(), [], -1)
为什么示例要为函数提供globals()
和locals()
?当我只提供 globals()
时会发生什么?或者两者都不是?
我可能遗漏了与导入模块相关的命名空间逻辑的某些部分。你能告诉我一篇解释这个/有 __import__
函数示例的文章吗?
最佳答案
The standard implementation does not use its
locals
argument at all, and uses itsglobals
only to determine the package context of theimport
statement.
(来自 docs.python.org)
我还是不知道怎么做globals
被使用;什么全局变量可以影响方式import
声明有效?
编辑:在查看 import.c
之后在 Python 2.5 源代码中,我发现 __import__
希望找到 __name__
或 __path__
在 globals
为了增加相对于在这些变量之一中找到的路径的导入搜索路径,按该顺序。
关于python - Python __import__ 函数中的 `globals` 和 `locals` 参数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4874342/