accessing module global vars by name

Steven Bethard steven.bethard at gmail.com
Mon Dec 20 08:29:01 CET 2004


Martin Drautzburg wrote:
> IOW how can I write something like
> 
> # xxx.py
> 
> for varName in ("foo", "bar"):
>         magic.varName = 1
> 

I think you want to use the dict returned by globals().  Modifying this 
dict can add/remove names from the global scope.[1]

 >>> foo
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'foo' is not defined
 >>> bar
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'bar' is not defined
 >>> for var_name in ['foo', 'bar']:
... 	globals()[var_name] = True
... 	
 >>> foo
True
 >>> bar
True
 >>> del globals()['foo']
 >>> foo
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'foo' is not defined

Steve

[1] As an aside, be careful not to try the same thing with locals(). 
locals() returns a dict that won't modify names in the local scope.



More information about the Python-list mailing list