updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

Steven Bethard steven.bethard at gmail.com
Wed Dec 8 11:59:23 EST 2004


Peter Hansen wrote:
> Nick Coghlan wrote:
> 
>> Generally, altering the contents of the dicts returned by locals() and 
>> globals() is unreliable at best.
> 
> 
> Nick, could you please comment on why you say this about globals()?
> I've never heard of any possibility of "unreliability" in updating
> globals() and, as far as I know, a large body of code exists which
> does in fact rely on this -- much of mine included. ;-)

Updating locals() is unreliable.  Updating globals() is fine, AFAIK.

http://docs.python.org/lib/built-in-funcs.html

I believe that the only time that locals() is updatable is when locals() 
is globals():

 >>> locals() is globals()
True
 >>> x
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'x' is not defined
 >>> locals()['x'] = 3
 >>> x
3


 >>> def f():
...     print locals() is globals()
...     locals()['x'] = 3
...     print x
...
 >>> f()
False
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 4, in f
NameError: global name 'x' is not defined


Steve



More information about the Python-list mailing list