How can I exec() in global?
Peter Otten
__peter__ at web.de
Sat Sep 11 14:32:54 EDT 2004
Jerald wrote:
> Is it possible to exec() from within a function so the exec'd
> code affects global?
>
> For example
>
> def foo():
> exec ('X=[1,2,3]')
>
> And I'd like 'X' to be a global variable.
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>> def foo():
... exec "x = [1, 2, 3]" in globals()
...
>>> foo()
>>> x
[1, 2, 3]
Peter
More information about the Python-list
mailing list