exec and locals

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Feb 26 14:15:25 CET 2014

I have to dynamically generate some code inside a function using exec, 
but I'm not sure if it is working by accident or if I can rely on it.

Here is a trivial example:

py> def spam():
...     exec( """x = 23""" )
...     return x
py> spam()

(My real example is more complex than this.)

According to the documentation of exec, I don't think this should 
actually work, and yet it appears to. The documentation says:

    The default locals act as described for function locals() 
    below: modifications to the default locals dictionary should 
    not be attempted. Pass an explicit locals dictionary if you 
    need to see effects of the code on locals after function 
    exec() returns.


I *think* this means that if I want to guarantee that a local variable x 
is created by exec, I need to do this instead:

py> def eggs():
...     mylocals = {}
...     exec( """x = 23""", globals(), mylocals)
...     x = mylocals['x']
...     return x
py> eggs()

The fact that it works in spam() above is perhaps an accident of 
implementation? Yes no maybe?


More information about the Python-list mailing list