【发布时间】:2021-08-11 16:55:45
【问题描述】:
我写了一个函数def_function,它在运行时动态定义了另一个函数。
main.py
#!/usr/bin/python3
def def_function(name):
lines = list()
lines.append('global {}\n'.format(name))
lines.append('def {}():\n'.format(name))
lines.append(' print(\'{}() has been called!\')\n'.format(name))
code = ''.join(lines)
function = compile(code, '', 'exec')
exec(function)
def_function('foo')
foo()
运行 main.py 给出预期的输出:
foo() 已被调用!
现在我想将def_function 的定义移动到module.py 并从main.py 导入。
module.py
def def_function(name):
lines = list()
lines.append('global {}\n'.format(name))
lines.append('def {}():\n'.format(name))
lines.append(' print(\'{}() has been called!\')\n'.format(name))
code = ''.join(lines)
function = compile(code, '', 'exec')
exec(function)
main.py
#!/usr/bin/python3
from module import def_function
def_function('foo')
foo()
这会导致以下错误:
Traceback (most recent call last):
File "./main.py", line 6, in <module>
foo()
NameError: name 'foo' is not defined
我已经在 SO 上搜索了我的问题并阅读了各种问题,但我找不到解决方案。请帮帮我。
【问题讨论】:
-
你知道你可以在 Python 中编写嵌套函数定义吗?
-
我知道,但据我了解嵌套函数的代码无法在运行时生成。我的真实函数根据
def_function的进一步参数生成代码。 -
所有 Python 中的函数都是在运行时创建的! (除了没有用
def ...写的内置的)
标签: python-3.x function import exec