Mucking with the calling scripts namespace (For a good reason, honest!)
smulloni at bracknell.smullyan.org
Wed Aug 4 05:00:53 CEST 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
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):
['STUPID', '__builtins__', '__doc__', '__name__', 'bestupid', 'sys']
I'll assume that you can recreate for yourself all the cautionary
noises I'm tempted to make after demonstrating such a capability.
More information about the Python-list