"Daniele" <d.co...@gmail.com> wrote

With module here I meant plug-in or extension: a piece of code written
by someone else that can be easily (and automaticallly) integrated
into my program.

OK, To do that you need to provide an intrerface in your code
that the plug-in can use. That is to say you must call a documented
set of functions/methods and then arrange your code such that the
plugin can replace the default code.

One way to do that in Python is to use a class which dedefines
a set of methods which you call. The plugin writer can then either
subclass that class or just write another class with the same interface.

You can then read the file name and import the file as a module
and assign the moduiles class to the class reference of your
interface. Remember that in Python classes are objects too.
Some pseudo-code

class MyInterface:
    def foo(self):
         pass

def getPluginName():
    # get it from a config file, a folder or whatever
    # or return None

plugIn = getPluginName():
if plugIn:
     p = imp.find_module(pth)  # you'll need more work here!
     imp.load_module(pg, p)
     thePlugIn = pg.getInterface()
else:
     thePlugin = MyInterface

theInterface = thePlugin()

theInterface.foo()     # use default or plugin


The plugin file looks like:

#class that implements MyInterface
class PlugIn:
   def foo(self):
        print ("i'm pluggged in")

def getInterface():
   return PlugIn


There are many more tricks etc that tyou can do to industrialize
that concept but it should be a start.

HTH,


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/




_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to