Join GitHub today
Reusable hooking mechanism for Python code #3393
Reported by jteh on 2013-08-02 07:20
There are existing frameworks for this like PubSub. However, from what I've been able to find, they can publish and subscribe, but they can't really synchronously hook; e.g. changing speech output. Also, they tend to use arbitrary text strings and I tend to think some sort of object to register with for each hook is nicer.
The easiest implementation is to have an object for each hook which has methods to register and unregister hooks. However, that fails requirement 6.
Another option is to have a decorator which you use to implement a hook; e.g.
Unfortunately, doing this in a way that satisfies both requirements 5 and 6 is pretty tricky. I haven't come up with a way yet.
Comment 1 by ragb on 2013-08-02 09:11
Regarding requirement 6, I can imagine how one may unregister class-based hooks, with some metaclass or mix-ins stuff (Don't have a proper design though), however I don't know if it is possible to do that in module-based hooks (do we know when a module gets deleted in Python?).
Comment 2 by jteh (in reply to comment 1) on 2013-08-02 10:29
I should have been clearer. Requirement 6 can't be satisfied for modules, only for object instances. I was thinking of some sort of token that the module/instance holds. When the token is dropped, the hook is unregistered. That way, modules can just drop it if they want to unregister. Instances should just drop it when they get garbage collected. The trick is doing that without creating circular references and associated gc leaks.