[issue36426] exec() issue when used inside function
Nick Coghlan
report at bugs.python.org
Sat Mar 30 07:56:11 EDT 2019
Nick Coghlan <ncoghlan at gmail.com> added the comment:
This is not a bug - to enable function level optimisations, the compiler must be able to see all local variable names at compile time.
In Python 2.x the exec statement implementation included special code to allow even function local variables to be rebound, but that special-casing was removed as part of the Python 3 change to convert exec from a statement to a builtin function (as per https://www.python.org/dev/peps/pep-3100/#core-language )
This means that to use exec() and reliably see the changes it makes to a namespace, you have to supply a reliably read/write dictionary of your own.
Object instance dictionaries work well for this purpose, as you can then access the results as attributes on the instance:
```
>>> class Namespace:
... pass
...
>>> def f():
... ns = Namespace()
... exec("x = 1; y = 2", vars(ns))
... print(ns.x)
... print(ns.y)
...
>>> f()
1
2
```
----------
resolution: -> not a bug
stage: -> resolved
status: open -> closed
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36426>
_______________________________________
More information about the Python-bugs-list
mailing list