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

Christopher T King squirrel at WPI.EDU
Tue Aug 3 15:52:34 EDT 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
6
>>> b = 20
>>> __main__.b
20
>>> getattr(__main__,"b")
20
>>> setattr(__main__,"b",6)
>>> b
6




More information about the Python-list mailing list