Explaining exec(globals, separate_locals)

Eryk Sun eryksun at gmail.com
Mon Sep 20 16:23:59 EDT 2021


On 9/20/21, Terry Reedy <tjreedy at udel.edu> wrote:
>
> "If exec gets two separate objects as globals and locals, the code will
> be executed as if it were embedded in a class definition."

Note that, unlike exec(), the body of a class definition can modify
closure variables in nonlocal function scopes. For example:

    >>> def f():
    ...     x = 'spam'
    ...     class C:
    ...         nonlocal x
    ...         x = 'eggs'
    ...     return x
    ...
    >>> f()
    'eggs'


More information about the Python-list mailing list