Overloaded functions in python?

By : Trcx
Source: Stackoverflow.com

Is it possible to have overloaded functions in Python? In C# I would do something like

void myfunction (int first, string second)
//some code
void myfunction (int first, string second , float third)
//some different code
// This maybe a little off, I haven't coded C# in a couple years

and then when I call the function it would differentiate between the two based on the number of arguments. Is it possible to do something similar in Python?

By : Trcx


Yes, it's possible. I wrote code below in Python 3.2.1:

def overload(*functions):
    return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)


myfunction=overload(no_arg_func, one_arg_func, two_arg_func)

Note that the lambda returned by the overload functions choose function to call depending on number of unnamed arguments.

The solution isn't perfect, but at the moment I can't write anything better.

Not possible directly. You can use explicit type checks on the arguments given though, although this is generally frowned upon.

Python is dynamic. If you are unsure what an object can do, just try: and call a method on it, then except: errors.

If you don't need to overload based on types but just on number of arguments, use keyword arguments.

This video can help you solving your question :)
By: admin