exec "statement" VS. exec "statement" in globals(), locals()

James Henderson james at logicalprogression.net
Wed Jul 21 22:02:01 CEST 2004


tedsuzman wrote:
> -----
> def f():
> 	ret = 2
> 	exec "ret += 10"
> 	return ret
> 
> print f()
> -----
> 
> The above prints '12', as expected. However,
> 
> ------
> def f():
> 	ret = 2
> 	exec "ret += 10" in globals(), locals()
> 	return ret
> 
> print f()
> ------
> 
> prints '2'. According to http://docs.python.org/ref/exec.html, "In all
> cases, if the optional parts are omitted, the code is executed in the
> current scope." Don't globals() and locals() consist of the current
> scope? Why aren't the two examples above equivalent?

Hi,

I believe that in the second you are changing the value of "ret" inside 
the dictionary returned by locals(), which does not actually change the 
value of the local variable "ret".  Viz.:

 >>> def f():
...   ret = 2
...   l = locals()
...   exec "ret += 10" in globals(), l
...   print l
...   return ret
...
 >>> f()
{'ret': 12}
2


See the entry on locals() in 
http://docs.python.org/lib/built-in-funcs.html :

Update and return a dictionary representing the current local symbol 
table. Warning: The contents of this dictionary should not be modified; 
changes may not affect the values of local variables used by the 
interpreter.

HTH,
James





More information about the Python-list mailing list