Re: eval, exec and execfile dilemma



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:
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~
.



Relevant Pages

  • Re: How to understand this form (something) (param);
    ... but the assignment to window.onload is what makes it ... is necessary for the closure to be formed. ... When foo is executed, bar has foo's activation/variable object on its ...
    (comp.lang.javascript)
  • Re: C Interpreter and sizeof operator
    ... as a simple assignment foo = bar. ... need not evaluate to 0 following foo = bar. ... in structs are never used for anything and can never cause trap representations like padding bits in integers can. ... The question was whether assignment and memcpydid the same thing. ...
    (comp.lang.c)
  • Re: Strange syntax sugar
    ... There is a subtelty in the assignment that is hard to see at the first ... you *never* assign nil to foo. ...
    (comp.lang.ruby)
  • Re: Insert with response
    ... FooBar, there's no way and no need to put them in synch. ... column in the foo table to 250 calumns in the bar table. ... set statistics time off ...
    (microsoft.public.sqlserver.programming)
  • Re: Magic function
    ... processing objects created in root at depth 3 ... root obj2 at depth 3 ... processing objects created in foo at depth 2 ... processing objects created in bar at depth 0 ...
    (comp.lang.python)