自定义python模块中的分层名称空间

尝试搜索该站点,但找不到我的问题的答案:

可以说我有一个名为mymodule.py的模块,其中包含:

def a():
    return 3

def b():
    return 4 + a()

然后进行以下工作:

import mymodule
print(mymodule.b())

但是,当我尝试动态定义模块内容时:

import imp

my_code = '''
def a():
    return 3

def b():
    return 4 + a()
'''

mymodule = imp.new_module('mymodule')
exec(my_code, globals(), mymodule.__dict__)
print(mymodule.b())

然后它在函数b()中失败:

Traceback (most recent call last):
File "", line 13, in <module>
File "", line 6, in b
NameError: global name 'a' is not defined

我需要一种在模块中保留分层名称空间搜索的方法,除非模块驻留在磁盘上,否则这似乎会失败.

有什么区别的线索吗?

谢谢,
抢.

解决方法:

你近了您需要让exec像这样在其他名称空间中工作(请参阅底部的python 3.x注释):

exec my_code in mymodule.__dict__

完整示例:

import imp

my_code = '''
def a():
    return 3

def b():
    return 4 + a()
'''

mymodule = imp.new_module('mymodule')

exec my_code in mymodule.__dict__
print(mymodule.b())

这就是说,我以前没有使用过它,所以我不确定这是否有任何怪异的副作用,但是看起来对我有用.

另外,在这里的python文档中还有一个关于“ exec in …”的小问题:http://docs.python.org/reference/simple_stmts.html#the-exec-statement

更新资料

您最初的尝试无法正常工作的原因是您正在传递当前模块的globals()字典,该字典与新模块应使用的globals()不同.

此exec行也可以使用(但不如’exec in …’样式漂亮):

exec(my_code, mymodule.__dict__, mymodule.__dict__)

更新2:由于exec现在是python 3.x中的函数,它没有’exec in …’样式,因此必须使用上面的行.

上一篇:Linux安装Redis CentOS 8


下一篇:gdb 如何指定脚本执行