Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function signature in python

Tags:

c++

python

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?

like image 776
user Avatar asked Sep 16 '25 21:09

user


2 Answers

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.

like image 195
snakecharmerb Avatar answered Sep 19 '25 09:09

snakecharmerb


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

like image 23
ForceBru Avatar answered Sep 19 '25 09:09

ForceBru