custom plugin architecture: how to see parent namespace?

escalation746 escalation746 at yahoo.com
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 plugin.py with a couple of functions. The second
will obviously fail.

----
def Hello():
	print 'hello'

def ViewValuable():
	print VALUABLE
----

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

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

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

# 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 = """
Hello()
Plus()
Valuable()
"""
exec code in namespace
----

This code will echo the lines:
hello
plus

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

The question is: How do I get a function in plugin.py to see VALUABLE?
Using external storage of some sort is not viable since many different
instances of plugin.py, 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 plugin.py 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
namespace.

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

-- robin




More information about the Python-list mailing list