Development #programming#python 5 min

Python: adding plug-ins support to our code

Translation of the original in Catalan. Read it in: CatalàCastellano

Sometimes when we are writing a program we are interested in our code being extendable without having to touch its structure; we may even be interested in this code being extended on some occasions and not on others. Another requirement we may have would also be that the one who extends it is not us. Often all this and much more is usually done with what we call Plug-ins; by the way, I have always found the Catalan translation of the word very amusing: 'afegitons'.

Well then, as I don't understand much about programming I asked Pau to help me understand the plug-ins models that some programs made with Python implemented, since I was interested in integrating this functionality into a series of codes I am developing. In this post I will try to explain how the plug-ins paradigm that Trac uses works.

First of all we have to bear in mind that Trac uses an object deployment pattern called Singleton, that is, all the instances of an object refer to the same instance. In fact, I can't say to what extent it is necessary for the code to follow this pattern in order to use the plug-ins system; although I would say that at least the parts of the code that want to be extended by Trac's plug-ins model have to follow it.

Trac's plug-ins have the following characteristics:

  • A Plug-in is a component that extends the functionality of another component

  • A Plug-in can extend another Plug-in

In order to incorporate the philosophy Trac has for supporting Plug-ins into our code we have to import the 'trac.core' component; from this component we will use the following:

  • trac.core.Interface (class) it is used to define what the contract that the plug-ins will have to follow is.

  • trac.core.ExtensionPoint (function) when we want a component to be extended it will use this function to retrieve the implementations of the contract. It defines the hook points our code has.

  • trac.core.implements (function) when a component uses this function it is to implement a contract, that is, the plug-ins that are built have to use it.

Before going on I will explain what is meant by contract. A contract is essentially a class of interface type (python does not have this model as such) that defines which methods (or other classes) can be extended inside the original component. That is, we must not only define what the contract on offer is but also document it as well as possible, explaining what the inputs and outputs expected from each of the methods/classes are.

So that all this is better understood Pau gave me the following example:

Let's imagine we have a class of type DNI that implements a database of DNIs, where it has a method that lets us enter DNIs into the database:

class DNI(trac.core.Component):
  dni_checks = trac.core.ExtensionPoint(IDNIInput)
  def __init__(self):
     self._dnis = []
  def add(self, dni):
     assert not dni in self._dnis, "DNI ja existeix"for dni_check in self.dni_checks:
     if dni_check.check(dni) is False:
       print "El dni %s  sembla no ser correcte" % ( dni )
       return
    self._dnis.append(dni)
  def llista(self):
    print self._dnis

We have to note that the line:

dni_checks = trac.core.ExtensionPoint(IDNIInput)

what it does is load the plug-ins that extend the functionality of the original code. We also have to note that the parameter the function uses is the class that defines the contract on which the plug-ins are made:

class IDNIInput(trac.core.Interface):
  def check(dni):
    """ Es cridada cada cop que s'entra un nou dni, espera que es retorni un valor boleà"""

As can be seen the contract only defines one method: 'check' which has to have an input parameter and expects a boolean output value.

We have to note that the DNI class every time it adds an element to the database (in this case a simple list), will call all the plug-ins that fulfil the contract in the order in which they have been instantiated (imported into the original code) through the following code.

for dni_check in self.dni_checks:
  if dni_check.check(dni) is False:
    print "El dni %s  sembla no ser correcte" % ( dni )
    return

An example of a plug-in on the previous code that fulfils the specified contract could be this one:

import trac.core
import dni
class ValidDNI(trac.core.Component):
  trac.core.implements(dni.IDNIInput)
  def check(self, dni):
    if type(dni) is not type("str"):
      return False
    if len(dni) != 9:
      return False
    return True

You can see how the class is an instance of 'trac.core.Component' (Singleton model) and implements the 'dni.IDNIInput' interface. Functionally what it does is quite simple, we check that it is a text string and that it has a length of 9 characters, if that is the case it returns a 'True' or otherwise a 'False'.

An example of what the main code would look like would be:

import trac.core                                                           

class IDNIInput(trac.core.Interface):
  def check(nom):
    """ Es cridada cada cop que s'entra un nou dni"""
class DNI(trac.core.Component):
  dni_checks = trac.core.ExtensionPoint(IDNIInput)
  def __init__(self):
    self._dnis = []
  def add(self, dni):
    assert not dni in self._dnis, "DNI ja existeix"
    for dni_check in self.dni_checks:
      if dni_check.check(dni) is False:
        print "El dni %s  sembla no ser correcte" % ( dni )
        return
    self._dnis.append(dni)
  def llista(self):
    print self._dnis

Examples of use:

>>> import trac.core
>>> from dni import DNI
>>>
>>> dni_bd = DNI(comp_mgr)
>>> dni_bd.add("38135009C")
>>> dni_bd.add("38135009")
>>> dni_bd.llista()
['38135009C', '38135009']

# importem el plug-in check_dni
>>> import check_dni
>>> dni_bd.add("11111111")
El dni 11111111  sembla no ser correcte
>>> dni_bd.add("11111111A")
>>> dni_bd.llista()
['38135009C', '38135009', '11111111A']

We define the 'log_dni' code which will be another plug-in:

import trac.core
import dni
class LogDNI(trac.core.Component):
  trac.core.implements(dni.IDNIInput)
  def check(self, dni):
    print "Nou dni entrat %s" % (dni)

We continue with the previous example:

# importem ara el plug-in 'log_dni'
>>> import log_dni
>>> dni_bd.add("22222222B")
Nou dni entrat 22222222B

At this point two plug-ins have already been loaded that work one after the other and it has been possible to appreciate the simplicity and power of the model. Obviously things can be missed, such as for example some element that defines the list of available plug-ins and that allows altering the order in which they are executed, but that should already be developed separately.

I hope to have described it in an understandable way and being as faithful as possible to Pau's explanations, whom I have to thank for the effort and dedication in explaining this Plug-ins model of Python to me.

1 comment

Comments from the old blog, as they were written. Comments are closed.

  1. pau

    Tot un paler, sort que tu mantens el blog viu !!! no com altres :P