Author ncoghlan
Recipients eamanu, ncoghlan, paul.moore, schperplata, steve.dower, terry.reedy, tim.golden, zach.ware
Date 2019-03-30.11:56:11
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1553946971.9.0.750795647303.issue36426@roundup.psfhosted.org>
In-reply-to
Content
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
```
History
Date User Action Args
2019-03-30 11:56:11ncoghlansetrecipients: + ncoghlan, terry.reedy, paul.moore, tim.golden, zach.ware, steve.dower, eamanu, schperplata
2019-03-30 11:56:11ncoghlansetmessageid: <1553946971.9.0.750795647303.issue36426@roundup.psfhosted.org>
2019-03-30 11:56:11ncoghlanlinkissue36426 messages
2019-03-30 11:56:11ncoghlancreate