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 eryksun
Recipients eryksun, qpeter, steven.daprano
Date 2021-12-23.15:04:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1640271867.48.0.436788691542.issue46153@roundup.psfhosted.org>
In-reply-to
Content
> You seem to be arguing that a description in the docs is "misleading", 
> not because it misleads, but because it don't describe a situation 
> which has nothing to do with the situation that the docs are describing.

To me it's misleading to say "the code will be executed as if it were embedded in a class definition" because that is not always the case. The example with print(a) shows that. One can take it another level to compare function definitions in a class definition compared to exec(). A function defined in an exec() is not compiled to bind its free variables to the outer lexical scope in the context of the exec() call, while a function defined in a class definition does. For example:

class:

    def f():
       a = 2
       class C:
           def g(): print(a)
       return C.g

    >>> a = 1
    >>> g = f()
    >>> g()
    2

exec():

    def f():
       a = 2
       l = {}
       exec('def g(): print(a)', globals(), l)
       return l['g']

    >>> a = 1
    >>> g = f()
    >>> g()
    1

You asked what I would say in its place, but I don't have a simple answer that can take the place of the one-liner in the docs. Here's something, but I'm sure you won't be happy with it:

The code will be executed in a manner that's similar to a class definition with regard to the use of separate locals and globals scopes. However, there can be significant differences in certain contexts with regard to how the same code is compiled for an exec() call compared to a class definition. In particular, code in a class definition is compiled to bind its free variables to the lexical scopes of outer function calls in the defining context, which isn't possible with exec(). Also, the top-level code in a class definition supports `nonlocal` declarations, which is a syntax error with exec().
History
Date User Action Args
2021-12-23 15:04:27eryksunsetrecipients: + eryksun, steven.daprano, qpeter
2021-12-23 15:04:27eryksunsetmessageid: <1640271867.48.0.436788691542.issue46153@roundup.psfhosted.org>
2021-12-23 15:04:27eryksunlinkissue46153 messages
2021-12-23 15:04:27eryksuncreate