Monkeypatching an object to become callable
pavlovevidence at gmail.com
Mon Aug 10 00:24:53 CEST 2009
On Aug 9, 12:02 pm, Nikolaus Rath <Nikol... at rath.org> wrote:
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
Override the class's __call__, and program it to call a certain method
(say _instancecall) on the object. Catch AttributeError and raise
TypeError so that it matches the behavior when no __call__ is defined.
func = self._instancecall
raise TypeError("'%s' object not callable" % self.__class__)
Note: don't call _instancecall inside the try clause; you don't want
to catch attribute errors raised inside the _instancecall method.
Then set _instancecall on any objects you want to be callable.
More information about the Python-list