Monkeypatching an object to become callable

Carl Banks pavlovevidence at gmail.com
Sun Aug 9 18:24:53 EDT 2009


On Aug 9, 12:02 pm, Nikolaus Rath <Nikol... at rath.org> wrote:
> Hi,
>
> 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.


def __call__(self,*args,**kwargs):
    try:
        func = self._instancecall
    except AttributeError:
        raise TypeError("'%s' object not callable" % self.__class__)
    return func(*args,**kwargs)


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.


Carl Banks



More information about the Python-list mailing list