简体   繁体   English

Python没有搜索本地名称空间

[英]Python is not searching the locals namespace

I'm trying to import a function from another module; 我正在尝试从另一个模块导入函数; however, I can't use import because the module's name needs looking up in a list. 但是,我不能使用import因为模块的名称需要在列表中查找。

If I try to call the imported function ExampleFunc normally I get: 如果我尝试正常调用导入的函数ExampleFunc得到:

NameError: global name 'ExampleFunc' is not defined

However; 然而; if I explicitly tell python to look in locals, it finds it. 如果我明确告诉python查找本地语言,它将找到它。


File module.py 文件module.py

def ExampleFunc(x):
    print x

File code.py 文件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")

The locals() dictionary is but a reflection of the actual locals array. locals()字典只是实际locals数组的反映 You cannot add new names to the locals through it, nor can you alter existing locals. 您不能通过它向本地人添加新名称,也不能更改现有本地人。

It is a dictionary created on demand from the actual frame locals, and is one-way only. 它是根据实际框架本地人按需创建的字典,并且仅是单向的。 From the locals() function documentation : locals()函数文档中

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. 更改可能不会影响解释器使用的局部变量和自由变量的值。

Function locals are highly optimised and determined at compile time, Python builds on not being able to alter the known locals dynamically at runtime. 函数局部变量经过高度优化,并在编译时确定,Python建立在无法在运行时动态更改已知局部变量的基础上。

Rather than try and stuff into locals directly, you can return the one object from the dynamic import. 您可以尝试从动态导入中返回一个对象,而不是直接将其塞入本地变量。 Use the importlib module rather than __import__ here: 在这里使用importlib模块而不是__import__

import importlib

def import_frm(module_name, name):
    module = importlib.import_module(module_name)
    return getattr(module, name)

then just assign to a local name: 然后只需分配一个本地名称:

def MainFunc(ary):
    ExampleFunc = import_from('module' , 'ExampleFunc')
    ExampleFunc(ary)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM