In C++ two functions with the same name can be created as long as the signature is different.
So for example myfunc(int x)
is different from myfunc(float x)
.
In python you cannot do this, so, do you need to define functions with different names, or is there a better way to handle this situation?
In Python3.4+ you can use the functools.singledispatch
decorator, which allows you to define a generic function and then register typed implementations against it.
From the docs
Generic function:
>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
... if verbose:
... print("Let me just say,", end=" ")
... print(arg)
Typed functions:
>>> @fun.register(int)
... def _(arg, verbose=False):
... if verbose:
... print("Strength in numbers, eh?", end=" ")
... print(arg)
...
>>> @fun.register(list)
... def _(arg, verbose=False):
... if verbose:
... print("Enumerate this:")
... for i, elem in enumerate(arg):
... print(i, elem)
There's no built-in solution for earlier releases of Python, but Guido van Rossum blogged about a solution for python2 using decorators. (Edit: there is also a backport of the 3.4 functionality for pythons 2.6 - 3.3 on pypi)
Edit: Of course, one of the advantages of using Python is that the the same code can often handle ints and floats without explicit dispatching on type, which is one of the reasons why the functionality has only recently been added.
Python doesn't really care whether an argument is an integer or a float. It's dynamically typed. You can do, for example, this:
def SquareMe(num):
return num**2
And you can call this function with any number (int
, float
, complex
, ...).
It's also possible to do this:
def MultMe(data):
return data*2
This will work with numbers, strings (!), lists (!!), NumPy arrays and anything that can be multiplied by a number (if some class provides a method for this).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With