Monkeypatching an object to become callable

Diez B. Roggisch deets at nospam.web.de
Sun Aug 9 16:28:29 EDT 2009


Nikolaus Rath schrieb:
> 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):
> 
>>>> class foo(object):
> ...   pass
> ... 
>>>> t = foo()
>>>> def test():
> ...   print 'bar'
> ... 
>>>> t()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'foo' object is not callable
>>>> t.__call__ = test
>>>> t()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'foo' object is not callable
>>>> t.__call__()
> bar
> 
> 
> Is there an additional trick to get it to work?

AFAIK special methods are always only evaluated on the class. But this 
works:

class Foo(object):

     pass

f = Foo()

def make_callable(f):
     class Callable(f.__class__):

         def __call__(self):
             print "foobar"

     f.__class__ = Callable

make_callable(f)
f()

Diez



More information about the Python-list mailing list