用lambda表达式编译python3.7可以';找不到闭覆盖函数
以下作品和印刷品42件,如预期:用lambda表达式编译python3.7可以';找不到闭覆盖函数,python,Python,以下作品和印刷品42件,如预期: import textwrap def test_compile(): code_str = """ def bump(x): return x + 1 print(); print(bump(41)) """ dedented_code_str = textwrap.dedent(code_str) code_obj = compil
import textwrap
def test_compile():
code_str = """
def bump(x):
return x + 1
print(); print(bump(41))
"""
dedented_code_str = textwrap.dedent(code_str)
code_obj = compile(dedented_code_str, filename='<string>', mode='exec')
exec(code_obj)
以下是令人不快的编译尝试:
import textwrap
def test_compile_with_lambda():
code_str = """
def bump(x):
return x + 1
debug_me = (lambda y: bump(y))(41)
print(); print(debug_me)
"""
dedented_code_str = textwrap.dedent(code_str)
code_obj = compile(dedented_code_str, filename='<string>', mode='exec')
exec(code_obj)
在我尝试过的所有其他环境或上下文中都能工作:在顶层,作为脚本;在普通调用函数内部(在普通调用函数内部或外部定义了bump
);正在测试中。为了节省空间,我不在这里重复这些例子,但直觉上认为有效的一切似乎都有效。我希望lambda表达式应该能够看到bump
,但编译器不同意
顺便说一句,如果主题代码被调用或编译,并且(关键的)在外部执行,但与test\u compile\u with_lambda
在同一个文件中,那么bump
在lambda表达式中定义,并且test\u compile\u with_lambda
起作用。假设,在这种情况下,lambda表达式引用的是一些bump
,而不是与其源代码字符串共存的表达式
我希望能够编译在我看来是合法的lambda表达式,这些表达式引用在附近上下文中适当定义的名称。有没有可能让我的
test\u compile\u与\u lambda
一起工作,而不以某种不自然的方式定义bump
?问题是lambda表达式创建了一个带有自由变量bump
的函数。这里不涉及结案
执行代码时,会在全局范围内查找bump
,但在全局范围内未定义bump
:它是在test\u compile\u的本地范围内定义的,使用\u lambda
要演示这一点,请将当前局部变量作为全局范围传递给exec
import textwrap
def test_compile_with_lambda():
code_str = """
def bump(x):
return x + 1
debug_me = (lambda y: bump(y))(41)
print(); print(debug_me)
"""
dedented_code_str = textwrap.dedent(code_str)
code_obj = compile(dedented_code_str, filename='', mode='exec')
exec(code_obj, locals())
导入文本包装
def test_compile_with_lambda():
代码_str=”“”
def通气(x):
返回x+1
debug_me=(λy:bump(y))(41)
打印();打印(调试)
"""
dedented\u code\u str=textwrap.dedent(code\u str)
代码\u obj=compile(dedented\u代码\u str,文件名='',模式='exec')
exec(code_obj,locals())
您将获得42的预期输出
def bump(x):
return x + 1
debug_me = (lambda y: bump(y))(41)
print(); print(debug_me)
import textwrap
def test_compile_with_lambda():
code_str = """
def bump(x):
return x + 1
debug_me = (lambda y: bump(y))(41)
print(); print(debug_me)
"""
dedented_code_str = textwrap.dedent(code_str)
code_obj = compile(dedented_code_str, filename='', mode='exec')
exec(code_obj, locals())