Eryk Sun <eryk...@gmail.com> added the comment:

> 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().

----------

_______________________________________
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