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


Groups > comp.lang.python > #10599

Re: eval, exec and execfile dilemma

References <4E346028.5000302@shopzeus.com>
Date 2011-07-30 21:43 +0100
Subject Re: eval, exec and execfile dilemma
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1674.1312058615.1164.python-list@python.org> (permalink)

Show all headers | View raw


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.

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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: eval, exec and execfile dilemma Chris Angelico <rosuav@gmail.com> - 2011-07-30 21:43 +0100

csiph-web