[Python-Dev] Dinamically set __call__ method

Lie Ryan lie.1296 at gmail.com
Thu Nov 13 16:28:53 CET 2014

On 05/11/14 06:15, Roberto Martínez wrote:
> The thing with this is tricky. I need the change in the instance,
 > not in the class, because I have multiple instances and all of
 > them must have different implementations of __call__.

Why not just use functions with closure if that's what you need?

     def a(one):
         two = 'three'
         def mycall(self):
             nonlocal two
             print 'NEW'
         return mycall

Python functions are objects.

> The workaround of calling a different method inside __call__
 > is not valid for my case because I want to change the *signature*
 > of the function also -for introspection reasons.

This seems like they should be two totally separate classes. If the 
signature is different, then it violates the substitution principle. If 
it violates substitution, then there is no reason why they should be of 
the same class.

> This was my first approach, but it is not very informative to the user
> and I prefer to have arguments with descriptive names. We have to change
> __doc__ too, so this is not an ideal solution for me.
> I tried to implement __getattribute__, but is not called either. :(

Or you can use an factory function:

     def A(p):
         def xcall(self):
             return 'X'
         def ycall(self):
             return 'Y'

         class _A(object):
             __call__ = xcall if p == 'x' else ycall
         return _A

     >>> A('x')()(), A('y')()()
     ('X', 'Y')

or plain and simply just use inheritance if you want to pass an 
isinstance check:

     class A(object):
         def __call__(self):
             print 'OLD'

     class A1(A):
         def __call__(self):
             print 'NEW'

What exactly, are you trying to do?

More information about the Python-list mailing list