Message409040
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. |
|
Date |
User |
Action |
Args |
2021-12-22 16:35:23 | steven.daprano | set | recipients:
+ steven.daprano, qpeter |
2021-12-22 16:35:22 | steven.daprano | set | messageid: <1640190922.96.0.228794929531.issue46153@roundup.psfhosted.org> |
2021-12-22 16:35:22 | steven.daprano | link | issue46153 messages |
2021-12-22 16:35:22 | steven.daprano | create | |
|