Does python support multi prototype.

Peter Hansen peter at engcorp.com
Wed Aug 4 16:20:53 CEST 2004


Jorgen Grahn wrote:

> Yes, but that's not as elegant in cases where the arguments' types has to
> trigger very different processing. I can even imagine situations where
> foo(S) and a foo(T) do completely different things, and still 'foo' is the
> best name for both of them.
> 
> I miss overloading in Python from time to time, but I can live without it.
> It is, after all, closely tied to a type system which is desirable in C++
> and Java, but not in Python.

(untested code, may be minor bugs)

def _foo_S(arg):
     # do something with arg, which is an S

def _foo_T(arg):
     # do something with arg, which is a T

def _foo_whatever(arg):
     # do something with arg when it's a "whatever"

     # ad nauseum...

def foo(arg):
     '''generic dispatcher for foo() function'''
     try:
         func = globals()['_foo_%s' % type(arg).__name__]
     except KeyError:
         raise TypeError('invalid type for function foo', arg)
     else:
         func(arg)


If you _really_ miss it from time to time, then it's _really_
easy to add it so that it's available in a fairly elegant fashion
when you do need it.

The above won't handle old-style classes, but adding support
for them would be pretty trivial too.  (Just need to check for
the case where the type is "instance" and use arg.__class__
instead of type(arg).)

-Peter



More information about the Python-list mailing list