Re: eval, exec and execfile dilemma
- From: Ethan Furman <ethan@xxxxxxxxxxxx>
- Date: Sat, 30 Jul 2011 14:22:36 -0700
Chris Angelico wrote:
On Sat, Jul 30, 2011 at 8:48 PM, Laszlo Nagy <gandalf@xxxxxxxxxxxx> 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:Traceback (most recent call last):exec "def foo():\n\tbar+=1\n\treturn 1\n"
bar=2
foo()
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~
.
- Prev by Date: Re: eval, exec and execfile dilemma
- Next by Date: Deeply nested dictionaries - should I look into a database or am I just doing it wrong?
- Previous by thread: Re: eval, exec and execfile dilemma
- Next by thread: Re: eval, exec and execfile dilemma
- Index(es):
Relevant Pages
|