eval, exec and execfile dilemma

Ethan Furman ethan at stoneleaf.us
Sat Jul 30 17:22:36 EDT 2011


Chris Angelico wrote:
> On Sat, Jul 30, 2011 at 8:48 PM, Laszlo Nagy <gandalf at shopzeus.com> wrote:
>> the exec statement can be used to execute a def statement. However, I see no
>> way to change the globals, so I cannot use the exec statement.
> 
> A quick test in Python 2.4.5:
>>>> exec "def foo():\n\tbar+=1\n\treturn 1\n"
>>>> bar=2
>>>> foo()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 2, in foo
> UnboundLocalError: local variable 'bar' referenced before assignment

This works, though (at least it does on 2.7):

--> exec "def foo():\n\tglobal bar\n\tbar+=1\n\treturn 1\n"
--> bar = 9
--> foo()
1
--> bar
10

Laszlo, why do you think you can't use exec?

~Ethan~



More information about the Python-list mailing list