This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients qpeter, steven.daprano
Date 2021-12-22.16:35:22
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1640190922.96.0.228794929531.issue46153@roundup.psfhosted.org>
In-reply-to
Content
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.
History
Date User Action Args
2021-12-22 16:35:23steven.dapranosetrecipients: + steven.daprano, qpeter
2021-12-22 16:35:22steven.dapranosetmessageid: <1640190922.96.0.228794929531.issue46153@roundup.psfhosted.org>
2021-12-22 16:35:22steven.dapranolinkissue46153 messages
2021-12-22 16:35:22steven.dapranocreate