[Twisted-Python] How to hook onto or append functionality to a class (from another class)?

Einar S. Idsø einar.twisted at norsk-esport.no
Wed Sep 8 09:19:40 EDT 2010


Hi,

I am trying to make one class/service hook onto another class/service
to add to its functionality without disturbing the original
class/service.

My situation is this: I currently have a class which at specific
intervals queries one server per instance (via t.u.getProcessOutput())
for some basic information. Each instance has a method which analyses
its returned data and stores the result it to  ts internal data
structure. My dilemma is that I wish to leave this class alone, but I
also wish to be able to add functionality from external classes based
on the result of said method. For instance: If the method analysing
the result from getProcessOutput() discovers a certain user on the
server being queried, I wish to store the data to a mysql database.
Under other circumstances I wish to send a notification to myself over
MSN or via mail. I can easily envision myself wanting to respond to
the results with other actions as well in the future. How can this be
achieved?

I can of course modify the original class so that I pass an
adbapi.ConnectionPool as optional argument to __init__() and modify
the method to check for the existence of such an object before
querying the database. I would then also need to add another optional
argument which is whatever object needs to be passed to allow the
class to send a message to MSN, and still more optional arguments for
any such new service I'd like to add. However, as mentioned I'd rather
not modify the original class, and doing this seems like too much of a
hack. Or is it? Perhaps inheritance is the key, although that would
require me to modify existing methods which I know to be working just
to tack on some additional functionality at the end.

What are my options here? I took a look at t.p.hook, and it seems like
it is perfect for the job: After having instantiated my "global"
adbapi.ConnectionPool(), I can just add a pre- or post-hook to any
class's method from which I'd like to store data. That way I can make
a db-instance which hooks in to any part of my application and stores
any result imaginable from any method. However, it seems that t.p.hook
is very rarely used, so perhaps there is a better way of achieving
what I want?

I hope this was somewhat comprehensible, and that there is an elegant
solution out there. :)

Cheers,
Einar



More information about the Twisted-Python mailing list