stupid namespace tricks

David Rysdam drysdam at ll.mit.edu
Mon Sep 13 13:48:29 EDT 2004


I have a program called 'myDaemon'.  I want this program to run little 
'scriptlets' that I have written.  I want the scriptlets to be as small 
and dumb as possible, so I decided I could jettison some overhead by 
having them be python code fragments that are just exec()'d by myDaemon.

Inside of myDaemon, I first created functions like logError() that the 
fragment could call to handle common functionality.  An API, I guess you 
could call it.  But then I realized that for some members of that API, 
I'd want to call different versions of the function for different 
versions of the scriptlet.  Rather than a big ugly switch statement, I 
thought I'd just use the globals() parameter of exec() to cram the right 
callables into the global dictionary with the key being the generic name 
I wanted to call.

For instance:

globals['logError':logErrorV3]

(It's possible I'm being blinded by the coolness of Python and that I 
could do this some old stodgy way.  But I want to control myDaemon 
remotely, so I'd like as much as possible to be dynamic and data-driven 
so it can be changed on the fly.)

Now I have 3 files.

1) scriptlet.py imports nothing and calls logError().


2) function_defaults.py imports nothing, defines logError() and also 
sets up a default global like so:

dictGlobal = {'logError':logError}


3) And then in myDaemon I "import functions_default" and do this:

exec(body, functions_default.dictGlobal)

(where "body" is the body of the scriptlet)

This all works fine.  But I want each scriptlet to be logged to a 
separate file.  There's no reason the scriptlet should manage this, so I 
have an id assigned to each scriptlet at the myDaemon level.  I thought 
I could just cram that id into the globals() dict for the scriptlet and 
then logError would see it and be able to figure out what file to log to.

I added this to myDaemon.py ahead of the exec():

functions_default.dictGlobal['id'] = scriptlet['id']

But when I get to logError, 'id' isn't there.

Some googling has revealed that "global" means "at the module level", 
but since I'm cramming it in manually it doesn't seem like that 
shouldn't matter.  Can anyone tell me what's going on?

(I apologize if this is complicated.  If it's not clear what I'm doing I 
can try to create a stripped down version and just post that.)



More information about the Python-list mailing list