execfile (exec?) create non consistent locals() state

David Stanek dstanek at dstanek.com
Wed Apr 22 13:43:02 CEST 2009

>> I expected exec to work the same, but apparently I was wrong. Is there is a
>> way to exec a file "more" correctly? thus avoid the need to resort to
>> awkward solutions such as using the locals() dictionary?
> I don't know personally. Perhaps a kind soul will chime in.

Why not just exec into a dictionary like this:

eee0:~% cat execme.py
a = 0

def func():
    print a
eee0:~% python
Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {}
>>> execfile('execme.py', d, d)
>>> d['a']
>>> d['func']()

blog: http://www.traceback.org
twitter: http://twitter.com/dstanek

More information about the Python-list mailing list