Python's idiom for function overloads

Stephen Thorne stephen.thorne at gmail.com
Wed Feb 2 17:56:35 EST 2005


On Wed, 02 Feb 2005 14:45:35 -0800 (PST), Simo Melenius
<firstname.lastname at iki.fi-spam> wrote:
> Philippe Fremy <phil at freehackers.org> writes:
> 
> > You can not reproduce the C++ overload idiom but you can get something
> > close with manual type testing.
> >
> >  > To in a
> >  > function do an if statement with the type() function?
> >
> > I am not aware of any other method.
> >
> > def a( arg1 ):
> >       if type(arg1) == types.IntType: return aWithInt(arg1)
> >       if type(arg1) == types.ListType: return aWithList(arg1)
> >       ...
> 
> Or:
> 
> def a_overloader (arg1):
>     return my_typed_a_func_dict[type (arg1)] (arg1)
> 
> Next I'd put my hands in automating the creation of these wrappers and
> the my_typed_a_func_dict map based on my implementation written so
> far. Then I'd think of parameterizing on any arbitrary destructuring
> of arguments like def foo ((a,b), c) and also on classes to which
> instance methods are bound to. At this point, a preprocessor might be
> handy to avoid seeing all the internals after which things would
> probably start looking sick enough to either switch languages or
> thinking of the right problem first and then come up with a pythonic
> solution to _that_.

Pah.

Use a decorator. 

Code is available here:
Jack Diederich posted a good multimethod snippet here, in response to
my own clumsy effort.

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5b50153e3fb84862
http://tinyurl.com/4awat

type(arg1) == types.IntType
def multi_type(t):
  return multi(lambda x:type(x) == t)

@multi_type(types.IntType)
def foo(x):
  return someOperationOnInt(x)

@multi_type(types.FloatType)
def foo(x):
  return someOperationOnFloat(x)

Regards,
Stephen Thorne.

"Just because it is possible doesn't make a good idea *wink*", 
-Jack Diederich, Aug 2004



More information about the Python-list mailing list