[Python tutorial] Chapter 59 variable parameters for advanced functions

Posted by geecu on Mon, 21 Feb 2022 11:08:01 +0100

In this article, we will learn how to use the * args parameter to define a variable function.

Tuple unpacking

The following example unpacks a tuple into two variables:

x, y = 10, 20

Element 10 is given variable x and element 20 is given variable y.

In fact, the parameters of the function are similar:

def add(x, y):
    return x + y


add(10, 20)

In the above example, element 10 is passed to variable x and element 20 is passed to variable y.

Similarly, the following example assigns element 10 to variable x, element 20 to variable y, and list [30, 40] to variable z:

x, y, *z = 10, 20, 30, 40

print(x)
print(y)
print(z)

Python function parameter passing also implements the same concept, for example:

def add(x, y, *args):
    total = x + y
    for arg in args:
        total += arg

    return total


result = add(10, 20, 30, 40)
print(result)

The function add accepts three parameters: x, y, and * args. Where args is a special parameter starting with an asterisk.

When we pass positional parameters 10, 20, 30, and 40, Python assigns element 10 to x, 20 to y, and tuple (30, 40) to args. Function parameters are similar to tuple unpacking, except that args is a tuple, not a list.

Variable parameter

When an asterisk (*) precedes a parameter of a function, it indicates that it can receive a variable number of parameter values. The user can pass zero, one or more values to the * args parameter.

In Python, parameters like * args are called variable parameters. Functions with variable parameters are called variable functions.

The argument args is not necessarily a variable name. We can use more explicit parameter names, such as * numbers, * strings, * lists, etc. By convention, * args is generally used as the name of the variable parameter.

Here is an example:

def add(*args):
    print(args)


add()

The output results are as follows:

()

The add function prints an empty tuple.

The following example shows the type and content of the args parameter:

def add(*args):
    print(type(args))
    print(args)

add()

The output results are as follows:

<class 'tuple'>
()

Since we didn't pass any parameters, the add() function outputs an empty tuple.

The following example passes three parameter values for the add() function:

def add(*args):
    print(args)


add(1,2,3)

The output results are as follows:

(1, 2, 3)

At this point, the args parameter contains three numbers. We can use subscripts to access each element:

def add(*args):
    print(args[0])
    print(args[1])
    print(args[2])


add(1, 2, 3)

In addition, we can also use the for loop to traverse the elements in the args tuple. The following example demonstrates how to sum elements in tuples:

def add(*args):
    total = 0
    for arg in args:
        total += arg
    return total


total = add(1, 2, 3)
print(total)

The output results are as follows:

6

Variable parameters and position parameters

If the * args parameter is used, no other location parameters can be specified. However, you can continue to use keyword parameters.

The following example returns an error because it uses a positional parameter after the * arg parameter:

def add(x, y, *args, z):
    return x + y + sum(args) + z


add(10, 20, 30, 40, 50)

The error message is as follows:

TypeError: add() missing 1 required keyword-only argument: 'z'

To solve this problem, we need to call the function with keyword parameters:

def add(x, y, *args, z):
    return x + y + sum(args) + z


add(10, 20, 30, 40, z=50)

In the above example, the number 10 is assigned to x, 20 is assigned to y, (30,40) is assigned to args, and the last 50 is assigned to z.

Parameter unpacking

The following point function receives two parameters and returns a coordinate point in string form:

def point(x, y):
    return f'({x},{y})'

If we pass a tuple as a parameter to the point function, an error will be returned:

a = (0, 0)
origin = point(a)
TypeError: point() missing 1 required positional argument: 'y'

Because tuple A is passed to x as a complete object, it will not be unpacked into two elements and passed to x and y respectively. So the parameter y is missing data.

To solve this problem, we need to add * operator in front of actual parameters, for example:

def point(x, y):
    return f'({x},{y})'


a = (0, 0)
origin = point(*a)
print(origin)

The output results are as follows:

(0,0)

At this point, the function unpacks tuple a and assigns two elements to x and y respectively.

summary

  • Python uses the * arg parameter to specify a variable number of parameters for the function, that is, to create a variable function.
  • *After args variable parameter, only keyword parameter can be used, and location parameter cannot be used.

Topics: Python function