Import functions in current namespace

Markus Schreyer markus.schreyer at gmail.com
Thu Jan 15 17:35:11 EST 2009


Hi,
we embedded python into our application via Swig. Now we like to wrap the
raw API functionality into a nicer more handleable module, but instead of
repeating every function in this wrapper i thought about importing them into
the namespace of the wrapper module. I like to give you an example of what
we like to achive.

Swig generates a file called "ppms.py" which contains the API classes and
functions.
Lets say the ppms.py contains a function called foo(). The wrapper.py should
now import the function foo() of the module ppms into the local namespace.

the swig module:

def foo():
    pass

def foo0():
    pass

One possibility would be to repeat the function in the wrapper.py like:

import ppms.py
def foo():
    return ppms.foo()
def foo0():
    return ppms.foo0()+1

Imho this is a little ugly. So I thought about importing the content of
ppms.py (the autgenerated one) into the namespace of the wrapper. Every
definition of a fuction in the wrapper should overwrite the function in the
imported module but a call to a function which is not defined in the wrapper
goes right through.

# wrapper.py - magic version
"magic_import" ppms.py

def foobar():
    return foo()  #calls foo of ppms.py

def foo0():
    return foo0()+1 #calls foo0 of ppms.py


Now using the magic version:

import wrapper

wrapper.foo() # looks in wrapper for foo() since it's not defined it falls
back to ppms.foo()
wrapper.foobar() # calls wrapper.foobar() calls ppms.foo()
wrapper.foo0() # calls wrapper.foo0() calls ppms.foo0()

Hopefully the idea is not to stupid.. ;)
Tnx for your help.

Markus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090115/d91a9199/attachment.html>


More information about the Python-list mailing list