Monkeypatching an object to become callable

Nikolaus Rath Nikolaus at rath.org
Sun Aug 9 15:02:57 EDT 2009


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?


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C



More information about the Python-list mailing list