Steven D'Aprano <steve+pyt...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue46153>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to