Python 未搜索本地命名空间
Python is not searching the locals namespace
我正在尝试从另一个模块导入函数;但是,我不能使用 import
,因为模块的名称需要在列表中查找。
如果我尝试正常调用导入函数 ExampleFunc
,我会得到:
NameError: global name 'ExampleFunc' is not defined
但是;如果我明确告诉 python 查看本地人,它会找到它。
文件module.py
def ExampleFunc(x):
print x
文件code.py
def imprt_frm(num,nam,scope):
for key, value in __import__(num,scope).__dict__.items():
if key==nam:
scope[key]=value
def imprt_nam(nam,scope):
imprt_frm("module",nam,scope)
def MainFunc(ary):
imprt_nam("ExampleFunc",locals())
#return ExampleFunc(ary) #fails
return locals()["ExampleFunc"](ary) #works
MainFunc("some input")
locals()
字典只是实际本地数组的 反映。您不能通过它向本地人添加新名称,也不能更改现有本地人。
它是根据实际框架局部变量按需创建的字典,并且是单向的。来自 locals()
function documentation:
Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
函数局部变量在编译时进行了高度优化和确定,Python 建立在无法在运行时动态更改已知局部变量的基础上。
您可以 return 动态导入中的一个对象,而不是直接尝试将其填充到局部变量中。在此处使用 importlib
module 而不是 __import__
:
import importlib
def import_frm(module_name, name):
module = importlib.import_module(module_name)
return getattr(module, name)
然后只分配给本地名称:
def MainFunc(ary):
ExampleFunc = import_from('module' , 'ExampleFunc')
ExampleFunc(ary)
我正在尝试从另一个模块导入函数;但是,我不能使用 import
,因为模块的名称需要在列表中查找。
如果我尝试正常调用导入函数 ExampleFunc
,我会得到:
NameError: global name 'ExampleFunc' is not defined
但是;如果我明确告诉 python 查看本地人,它会找到它。
文件module.py
def ExampleFunc(x):
print x
文件code.py
def imprt_frm(num,nam,scope):
for key, value in __import__(num,scope).__dict__.items():
if key==nam:
scope[key]=value
def imprt_nam(nam,scope):
imprt_frm("module",nam,scope)
def MainFunc(ary):
imprt_nam("ExampleFunc",locals())
#return ExampleFunc(ary) #fails
return locals()["ExampleFunc"](ary) #works
MainFunc("some input")
locals()
字典只是实际本地数组的 反映。您不能通过它向本地人添加新名称,也不能更改现有本地人。
它是根据实际框架局部变量按需创建的字典,并且是单向的。来自 locals()
function documentation:
Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
函数局部变量在编译时进行了高度优化和确定,Python 建立在无法在运行时动态更改已知局部变量的基础上。
您可以 return 动态导入中的一个对象,而不是直接尝试将其填充到局部变量中。在此处使用 importlib
module 而不是 __import__
:
import importlib
def import_frm(module_name, name):
module = importlib.import_module(module_name)
return getattr(module, name)
然后只分配给本地名称:
def MainFunc(ary):
ExampleFunc = import_from('module' , 'ExampleFunc')
ExampleFunc(ary)