multimethod (or rather overloading) in Python

anton muhin antonmuhin at rambler.ru
Thu Feb 17 12:20:35 EST 2005


Dear pythonistas!

I'd like to emulate overloading in Python (like C++).

Let's consider an example:

class A(object): pass
class B(object): pass

Of course, there are some standard overloading implementations for 
Python. For example:

def overload(cls):
   def wrapper(f):
     gl = f.func_globals

     next = gl.get(f.func_name, failedOverload_(f.func_name))
     def _(obj, *args, **kwargs):
       if isinstance(obj, cls):
         return f(obj, *args, **kwargs)
       else:
         return next(obj, *args, **kwargs)
     return _

@overload(A)
def foo(_): print 'foo at A'


@overload(B)
def foo(_): print 'foo at B'

However, it obviously doesn't work for classes: I cannot overload 
instance methods with such a decorator.

The best way I found is closures. Unfortunatley, in this case I need a hack:

   gl = f.func_globals

turns into:

   gl = sys._getframe(1).f_locals

and with this hack one can make the following trick:

def poorManOverloadedMethods(someInfo):
   @overload(A)
   def _(_): print '%s: poorManOverloadedMethods at A' % someInfo

   @overload(B)
   def _(_): print '%s: poorManOverloadedMethods at B' % someInfo

   return _

PMOM = poorManOverloadedMethods('test')

...

Of course, I can imagine some metaclasses magic that would allow to code:

class MyClass(WithOverloading):
   @overloadMethod(A)
   def someMetod(self, _): ...

But it would rather convoluted: the best idea I have so far is to mangle 
  methods name in the manner most of C++ compilers do.

Is there better way? Can I unify both @overload and @overloadMethod?

with the best regards,
anton.



More information about the Python-list mailing list