Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10600 > unrolled thread

Re: eval, exec and execfile dilemma

Started byEthan Furman <ethan@stoneleaf.us>
First post2011-07-30 14:22 -0700
Last post2011-07-30 14:22 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: eval, exec and execfile dilemma Ethan Furman <ethan@stoneleaf.us> - 2011-07-30 14:22 -0700

#10600 — Re: eval, exec and execfile dilemma

FromEthan Furman <ethan@stoneleaf.us>
Date2011-07-30 14:22 -0700
SubjectRe: eval, exec and execfile dilemma
Message-ID<mailman.1675.1312061021.1164.python-list@python.org>
Chris Angelico wrote:
> On Sat, Jul 30, 2011 at 8:48 PM, Laszlo Nagy <gandalf@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~

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web