Python __import__中的`globals`和`locals`参数用于? [英] What are `globals` and `locals` parameters in Python __import__ function for?
问题描述
__ import __
的一部分在Python文档中,我不明白:
There's a part of __import__
in Python documentation, which I don't understand:
__ import __(name [,globals [ ,本地人[,fromlist [,level]]]])
该函数导入模块 name
,可能使用给定的全局变量
和本地人
来确定如何解释名称
在包上下文中。标准实现根本不使用其本地
参数,并且仅使用其全局变量
来确定包的上下文导入语句。
The function imports the module name
, potentially using the given globals
and locals
to determine how to interpret the name
in a package context. The standard implementation does not use its locals
argument at all, and uses its globals
only to determine the package context of the import statement.
有关模块名称的解释是什么?什么是包上下文?
What is there to "interpret" about the module name? What is package context?
使用这些参数的示例调用如下所示:
An example call using those parameters looks like this:
spam = __import__('spam', globals(), locals(), [], -1)
为什么该示例为函数提供 globals()
和 localals()
?当我只提供 globals()
时会发生什么?还是没有?
Why does the example provide globals()
and locals()
to the function? What happens when I only provide globals()
? Or neither?
我可能缺少与导入模块有关的命名空间逻辑的一部分。你能指出一个解释这个/有例如 __ import __
函数的文章
I am probably missing some part of the namespace logic with relation to importing modules. Could you point me to an article that explains this/has examples with __import__
function?
推荐答案
标准实现根本不使用其
本地
参数,并使用其全局变量
仅用于确定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 )
我仍然不知道如何使用全局变量
什么全局变量可能会影响 import
语句的工作方式?
I still have no idea how globals
are used; what global variable can ever affect the way import
statement works?
编辑: / strong>在Python 2.5源代码中查看 import.c
后,我发现 __ import __
期望找到 __ name __
或 __ path __
在全局变量
中,以增加相对于按照这个顺序找到其中一个变量的路径。
After looking at import.c
in Python 2.5 source I found that __import__
expects to find either __name__
or __path__
in globals
in order to augment import search path relative to path(s) found in one of these variables, in that order.
这篇关于Python __import__中的`globals`和`locals`参数用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!