exec example - I don't understand

Peter Otten __peter__ at web.de
Tue Jun 29 08:41:52 EDT 2004


kepes.krisztian at peto.hu wrote:

> But I dont' understand that:
> exec "x = 3; print x" in a
> 
> So what this code do ?
> Why we need "in a" ?
> 
> This get same result !

First we make sure there's no variable x in the global namespace:
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined

Underneath, the global namespace is just a dictionary with the variable
names as keys and the objects as values.
>>> "x" in globals()
False

Now let's use our own dictionary d as the namespace for the exec statement:
>>> d = {}
>>> exec "x=1" in d

This leaves the global namespace unaffected:
>>> "x" in globals()
False

Instead 1 is stored under the key "x" in the dictionary we provided:
>>> "x" in d
True
>>> d["x"]
1

Now let's repeat the same exec statement without explicitly providing a
dictionary. Python will then use globals() as the default. Therefore a
variable x with the value 1 will "magically" appear:
>>> exec "x=1"
>>> "x" in globals()
True
>>> x
1

Peter




More information about the Python-list mailing list