Python没有搜索本地namesp

2024-04-25 03:57:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从另一个模块导入函数;但是,我不能使用import,因为需要在列表中查找该模块的名称。你知道吗

如果我尝试调用导入的函数ExampleFunc,通常会得到:

NameError: global name 'ExampleFunc' is not defined

但是,如果我显式地告诉python查找局部变量,它就会找到它。你知道吗


文件模块.py你知道吗

def ExampleFunc(x):
    print x

文件代码.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")

Tags: 模块文件key函数pyimportvaluedef
1条回答
网友
1楼 · 发布于 2024-04-25 03:57:46

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建立在运行时不能动态改变已知局部变量的基础上。你知道吗

您可以从动态导入中返回一个对象,而不是尝试直接填充到局部变量中。在这里使用^{} 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)

相关问题 更多 >