multimethod (or rather overloading) in Python

A

anton muhin

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@A'


@overload(B)
def foo(_): print 'foo@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@A' % someInfo

@overload(B)
def _(_): print '%s: poorManOverloadedMethods@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.
 
A

anton muhin

anton muhin wrote:

Correction:
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.

Stupid me. Of course, name magling is impossible and unnecessary. Sorry.

Still the question remains.

with the best regards,
anton.
 
N

Nick Coghlan

A

anton muhin

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top