[issue46153] function fails in exec when locals is given
Steven D'Aprano
report at bugs.python.org
Wed Dec 22 11:35:22 EST 2021
Steven D'Aprano <steve+python at pearwood.info> added the comment:
The function you use in exec is not a closure. The function:
def f():
return a
does not capture the top-level variable "a", it does a normal name lookup for a. You can check this yourself by looking at f.__closure__ which you will see is None. Or you can use the dis module to look at the disassembled bytecode.
To be a closure, you have to insert both the "a" and the `def f()` inside another function, and then run that:
code = """
def outer():
a = 1
def f():
return a
return f
f = outer()
print(f())
"""
exec(code, {}, {})
prints 1 as expected.
----------
components: +Interpreter Core
nosy: +steven.daprano
title: closure fails in exec when locals is given -> function fails in exec when locals is given
type: crash -> behavior
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46153>
_______________________________________
More information about the Python-bugs-list
mailing list