How to define an arbitrary function in Python
Arbitrary function is the function that takes an unknown number of argument. This type of function can be defined in the in the Python program using a simple syntax.
Arbitrary function gives Python programmer means of working with more than one argument, and without specifying an exactly number of argument needed.
To declare an arbitrary function in Python we use the normal syntax that is used to declare function in Python. The only difference is in the argument which will hold the reference to our arbitrary object.
The argument will be of type tuple, which is the data type in Python that can store a sequential number of elements.
Arbitrary function declaration syntax and example
In our example we will crate a function that will take unknown number of arguments of integer type, and return the total of the passed argument.
Syntax of arbitrary function in Python:
def function_name (first, *args):
As you can see from the syntax above the declaration of arbitrary function is similar to the normal function declaration in Python. The different is in the argument declaration. As in our example above the argument is preceded with an asterisk (*) symbol.
To declare an argument to hold unknown number of arguments we use the asterisk symbol. Another thing to note from the syntax above is that the argument that will hold unknown number of arguments must be the last argument in the function declaration, and must be the only argument with an asterisk (*) symbol. You can't have two arguments with asterisk symbol, or python will raise an error.
Arbitrary function declaration example in Python:
Def summation( *args):
result = 0
for x in args:
result += args[x]
In the example above we take unknown number of arguments, and loop through them. The args argument can be looped through, because is of type tuple, and data are stored in sequential format.
Arbitrary function invocation example in Python:
summation(10,10,10) # this function will return 30 as the result
summation(10,10) # this function will return 20 as the result
summation(10) # this function will return 10 as the result
summation() #this function will return None
As you can see from our invocation example, the function summation can be invoked with any number of arguments even with non argument at all.
Arbitrary functions in Python can be applied to solve many problems that they have unknown number of variables or arguments. Example of arbitrary functions are sum and print functions of the Python standard library.