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

Doug Rosser da_rosser at yahoo.com
Wed Aug 4 14:38:17 EDT 2004


Christopher T King <squirrel at WPI.EDU> wrote in message news:<Pine.LNX.4.44.0408031540350.10945-100000 at ccc6.wpi.edu>...
> 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

/Me slaps his forehead. Python provides the functionality I'm looking
for already. After reading the Python 2.3 documentation for globals(),
I stumbled upon "exec". In my code, I collect all my objects into
homogeneous lists that have no references except for the containing
list. To add the references I'm looking for, I'm going to do something
like:

for server in myTest.servers:
    exec server.iniLabel +"="+ server in globaldict

The code hasn't been debugged...caveat emptor...

* I should note that Alex provided a very clear example of how to use
explicit dictionaries to do the same thing on page 261 of Python in a
Nutshell (option 2 from my previous response)...still debating the
merits of both approaches

da rosser



More information about the Python-list mailing list