Mucking with the calling scripts namespace (For a good reason, honest!)

Christopher T King squirrel at WPI.EDU
Tue Aug 3 21:52:34 CEST 2004

On 3 Aug 2004, Doug Rosser wrote:

> 1. Python doesn't provide an obvious way to modify the __main__
> namespace. You can peek at values with "global" but you can't treat it
> like a dictionary at runtime.

The globals() function returns just the dictionary you're looking for.
Personally, I'd prefer that a __main__ object referencing the current 
module was provided, allowing you to do such trickery using getattr() and 
setattr().  Something as simple as the following would suffice:

 class objifier(object):
      def __init__(self,d):
          self.__dict__ = d

 __main__ = objifier(globals())

Then you do stuff like:

>>> __main__.b = 6
>>> b
>>> b = 20
>>> __main__.b
>>> getattr(__main__,"b")
>>> setattr(__main__,"b",6)
>>> b

More information about the Python-list mailing list