Extending objects through methods' __call__

Hrvoje Niksic hniksic at srce.hr
Sun May 16 19:21:20 EDT 1999


Something appears to be lacking in Python's class interface.  If I
have a class X and its instance x, then I can customize what x() will
do (via X.__call__), what reading and assigning to x.foo will do (via
X.__getattr__ and X.__setattr__), what reading and assigning to x[foo]
will do (via X.__getitem__ and X.__setitem__) and a bunch of other
things, but...  I cannot tell what x.foo() will do, at least not
without knowing all the foo's in advance.  Or can I?

I think it would be very nice if I were able to specify something
like:

class my_class:
    def somemethod():
        ...
    def someothermethod():
        ...
    def __methcall__(self, method, *args, **kwargs):
        # Handle all the method calls that are not named otherwise.
        ...

The practical implication of this would be that it would become
trivial to write a wrapper around an intrinsic object.  UserDict could 
be written like this:

class UserDict:
    def __init__(self): self.data = {}
    def __methcall__(self, method, *args, **kwargs):
      return apply(self.data__methods__[method], args, kwargs)

Would such a scheme work?




More information about the Python-list mailing list