A problem with exec statement

Peter Otten __peter__ at web.de
Fri Apr 14 03:07:42 EDT 2006


TPJ wrote:

> I have the following code:
> 
> -----------------------------------
> def f():
> 
>   def g():
>     a = 'a'             # marked line 1
>     exec 'a = "b"' in globals(), locals()
>     print "g: a =", a
> 
>   a = 'A'               # marked line 2
>   exec 'a = "B"' in globals(), locals()
>   print "f: a =", a
>   g()
> 
> f()
> -----------------------------------
> 
> I don't understand, why its output is:
> 
> f: a = A
> g: a = a
> 
> instead of:
> 
> f: a = B
> g: a = b

Use the exec statement without the in-clause to get the desired effect:

>>> def f():
...     a = "a"
...     exec "a = 'B'"
...     print a
...
>>> f()
B

Inside a function locals() creates a new dictionary with name/value pairs of
the variables in the local namespace every time you call it. When that
dictionary is modified the local variables are *not* updated accordingly.

>>> def f():
...     a = "a"
...     d = locals()
...     exec "a = 'B'" in globals(), d
...     print a, d["a"]
...
>>> f()
a B

By the way, experiments on the module level are likely to confuse because
there locals() returns the same dictionary as globals().

Peter





More information about the Python-list mailing list