Implementing chain of responsibility

koranthala koranthala at gmail.com
Mon Mar 9 02:53:18 EDT 2009


Hi,
    I want to implement chain of responsibility pattern in Python (for
a Django project)
    The problem that I see is a rather odd one - how to link the
subclasses with the super class.

Ex: Suppose the two child classes are as given below (A1, A2 child
classes of A)
class A:
   ...

class A1(A):
   ...

class A2(A):
   ...

    Now, I want to call A.method(x) and I want A1 and A2 to act on x.
The ways I could think of till now are
1. have a registry in A. A1 and A2 objects register to A's registry.
Then loop through the registry.
2. loop through A.__subclasses__ to invoke each subclass.

I am leaning towards option 1.

The problem is that A1 and A2 are in different modules from A. So, how
can I make A aware that A1 and A2 are there?
i.e.
The module structure is MA (contains class A), MA1 (contains class A1)
MA2 (contains class A2).
Where do I do import MA1 and MA2 etc so that the register methods of
MA1 and MA2 are hit?
Now, from the code (when I receive a HTTP request), I will be calling
MA.A.method(x) only. So there is no need of importing MA1 and MA2.

Is __init__.py used for this purpose - i.e. just import all the
modules inside __init__.py so that the code is it in each?



More information about the Python-list mailing list