A problem with exec statement

TPJ tprimke at interia.pl
Fri Apr 14 02:36:02 EDT 2006


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

All works as intended, if the marked lines are commented out. I just
don't understand, why. (I suppose I don't understand, how the exec
statement works, or the way Python handles objects, their names and
namespaces...) In my opinion (according to my knowledge about Python),
with or without the marked lines commented, the code should work the
same. Well - I think I have to learn more about Python...

According to my knowledge, the most important are the namespaces: the
local ones, in this case. When Python calls the f function, its
namespace is created. This namespace contains only the g function.
Then the a variable is created (and the "a" name is added to the f
function namespace).

The next statement is the exec one. Since the statement "knows" the
local namespace (obtained from the locals() function), it should
replace the value of the a variable in the local namespace with the
value of the new string "B". I don't understand, why this is not done.

The situation in the g function is similar, the only difference is
that the local namespace contains the "a" name, that refers to a
different Python object.




More information about the Python-list mailing list