eval, exec and execfile dilemma
Chris Angelico
rosuav at gmail.com
Sat Jul 30 16:43:32 EDT 2011
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.
You can't use:
exec "blah blah" in globals()
?
I've not used exec, nor its Python 3 equivalent exec(), much, so I
don't know enough about it to know why this wouldn't work. But it's
meant to be able to work with any dictionary for globals and/or
locals.
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
Is that the issue you're up against? I'm thinking here that the
solution might be the function's __globals__ attribute, but that only
exists in Python 3 (I think). Can you upgrade/migrate to version 3?
ChrisA
More information about the Python-list
mailing list