What is the cleanest way to for a module to access objects from the script that imports it?

robert no-spam at no-spam-no-spam.com
Sat Oct 28 07:53:46 EDT 2006


noamsml at gmail.com wrote:
> Hi,
> 
> I am new to python and am currently writing my first application. One
> of the problems I quickly ran into, however, is that python's imports
> are very different from php/C++ includes in the sense that they
> completely wrap the imported script in a module object. One of the
> problems with this was that a plugin system that I am making requires
> use of objects, classes and the such from the original script. Thus, on
> one hand, I am hesitant to use execfile(), since I *do* want to wrap
> the plugin up, but on the other hand, I want the plugin to be able to
> use functions from the original script. Any ideas?
> 

you can import __main__ in your module: import __main__; __main__.app_xfunc(y)

But for most cases I'd say your "problem" is an indication of weak design (thanks to Pythons clear module tech).

Maybe:

* if the funcs are tools, put them in an extra module

* if its about app-global parameters(tools), make a module "myglob" or so

* if the funcs have app-context, hand over/set them as "callback" functions or iterators like ..

def app_xfunc(par):pass
mody.set_xhandler(app_xfunc)
mody.yfunc(a,b,..., cbProgress=app_xfunc)
def app_xstepper():
    yield next
mody.yfunc2(a,b,..., step=app_xstepper)
...


* if you have 2 moduls on equal dependency level and each needs the other (sometimes) - thus you don't want to have one big module, then cross import them ..

#modx
import mody
def fx():
    mody.doy()
#mody
import modx
def fy():
    modx.dox()


Python allows everything most easy for that kind of problems of all langs I know of. Mainly the fact that a module is a real object in Python provides tremendous flexibility and self-similarity of techniques. Ruby for example is weired - even really bad - in this.

-robert



More information about the Python-list mailing list