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

Jacob Smullyan smulloni at bracknell.smullyan.org
Tue Aug 3 23:00:53 EDT 2004


On 2004-08-03, Doug Rosser <da_rosser at yahoo.com> wrote:
> Thank you for your help Larry. Let me see if I've got this straight:
>
> 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.
>
> 2. If you need to access objects that won't have names until run-time
> (but you incidentally -KNOW- their names and want to reference them in
> a bit of code), encapsulate them in a container. This effectively
> creates a new not-really namespace, as the objects in the container
> become attributes.
>
> Well, all-in-all, I'd really still rather have #1, but I can live with
> #2.

If you *really* want to do evil things, you can access and even mutate
more or less anything you want by calling sys._getframe(n) where n is
the number of frames offset from the current frame:

>>> import sys
>>> def bestupid(v):
...     f=sys._getframe(1)
...     f.f_globals['STUPID']=v
... 
>>> bestupid(100)
>>> dir()
['STUPID', '__builtins__', '__doc__', '__name__', 'bestupid', 'sys']
>>> STUPID
100
>>> bestupid(0)
>>> STUPID
0

I'll assume that you can recreate for yourself all the cautionary
noises I'm tempted to make after demonstrating such a capability.

js
-- 
Jacob Smullyan



More information about the Python-list mailing list