custom plugin architecture: how to see parent namespace?

escalation746 escalation746 at
Sun Jul 22 16:06:32 CEST 2007

I've got a namespace query that amounts to this: How can an imported
function see data in the parent custom namespace? I have read through
numerous posts which skirt this issue without answering it.

To illustrate, create with a couple of functions. The second
will obviously fail.

def Hello():
	print 'hello'

def ViewValuable():

Then create which loads the plugin at runtime, later running
various code fragments against it.

# location of plugin module
filespec = '/path/to/plugins/'
filepath, filename = os.path.split(filespec)
filename = os.path.splitext(filename)[0]

# add to system path
if filepath not in sys.path:

# import into our namespace
space = __import__(filename, globals(), locals(), [])
namespace = space.__dict__

# sometime later in the code... define a new function
def _plus():
	print 'plus'

# add that to our namespace
namespace.update({'Plus': _plus, 'VALUABLE': 'gold'})

# run custom code
code = """
exec code in namespace

This code will echo the lines:

Followed by a traceback for:
NameError: global name 'VALUABLE' is not defined

The question is: How do I get a function in to see VALUABLE?
Using external storage of some sort is not viable since many different
instances of, all with different values of VALUABLE, might
be running at once. (In fact VALUABLE is to be a key into a whole
whack of data stored in a separate module space.)

Extensive modifications to is also not a viable approach,
since that module will be created by users. Rather, I need to be able
to pass something at execution time to make this happen. Or create an
access function along the lines of _plus() that I can inject into the

Any help, please? I've been losing sleep over this one.

-- robin

More information about the Python-list mailing list