Python's idiom for function overloads

Simo Melenius firstname.lastname at iki.fi-spam
Wed Feb 2 17:31:47 EST 2005


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_.


br,
S



More information about the Python-list mailing list