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 '[EMAIL PROTECTED]'


@overload(B) def foo(_): print '[EMAIL PROTECTED]'

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: [EMAIL PROTECTED]' % someInfo

  @overload(B)
  def _(_): print '%s: [EMAIL PROTECTED]' % 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.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to