Calling functions


Martin McBride, 2021-10-09
Tags function positional parameter named parameter optional parameter unpacking
Categories python language intermediate python

This article looks at different ways to pass in parameters when you call a function. It follows on from the related article on declaring functions.

We will use this simple function for the first part of the tutorial. It has mandatory and optional parameters:

def fancy_print(s, before='[', after=']'):
    out = before + s + after
    print(out)

Positional parameters

Since the fancy_print function has one mandatory parameter (s) and two optional parameters, there are 3 simple ways to call it:

fancy_print('Hello')             # Prints '[Hello]'
fancy_print('Hello', '(')        # Prints '(Hello]'
fancy_print('Hello', '<', '>')   # Prints '<Hello>'

We must supply the first parameter. We can choose to supply the second parameter, or the second and third parameters, because they are optional. If we don't supply a parameter, it takes the default value from the declaration.

The parameters being passed in here are called positional parameters because we use the position of the parameter to identify it. The first parameter is s, the second is before, the third is after.

Named parameters

You can also pass parameters by name. As an example, suppose we wanted to change the after parameter while leaving the before parameter set to its default value. We can do this:

fancy_print('Hello', after='>')   # Prints '[Hello>'

Although the syntax for named parameters is similar to the syntax for optional parameters, you can mix and match. You could set the value of s by name:

fancy_print(after='>', s='Hello')   # Prints '[Hello>'

Notice that with named parameters, they can be in any order. This can be very useful if you have a function with a lot of parameters. The positional syntax means that you have to remember the parameter order to understand the function call. Using named parameters the calling code is almost self-documenting.

There are some rules about positional and named parameters:

  • All the positional parameters must appear before any named parameters.
  • Every mandatory parameter must be given a value, which can be by position or name.
  • No parameter can be given more than one value. There are two ways this could happen: either the parameter is given a positional value and a named value, or a parameter is named more than once. Neither case is allowed.

Unpacking parameter lists

You can unpack a sequence of values passed into a function, like this:

values = ('<', '>')

fancy_print('hello', *values) # prints <hello>

# Exactly the same as:
fancy_print('hello', '<', '>')

The values tuple is unpacked and provides 2 parameters to the function.

In 3.4 earlier versions of Python, only one unpacked sequence was permitted, and it had to be immediately after all the positional parameters. As of 3.5, the parameter list can contain a mixture of positional parameters and unpacked sequences, in any order, including multiple unpacked sequences.

You can also unpack a dictionary of named values passed into a function, like this:

dvalues = {'s': 'hello', 'before': '<', 'after': '>'}

fancy_print(**dvalues) # prints <hello>

# Exactly the same as:
fancy_print(s='hello', before='<', after='>')

In 3.4 earlier versions of Python, only one unpacked dictionary was permitted, and it had to be immediately after all the named parameters. As of 3.5, the parameter list can contain a mixture of named parameters and unpacked dictionaries, in any order, including multiple unpacked dictionaries.

As a general rule, all the positional parameters and unpacked sequences should come first, followed by all the named parameters and unpacked dictionaries.

If you found this article useful, you might be interested in the book Python Quick Start or other books by the same author.

Prev

Popular tags

2d arrays abstract data type alignment and animation arc array arrays behavioural pattern bezier curve built-in function callable object chain circle classes close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data types design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif gradient greyscale higher order function hsl html image image processing imagesurface immutable object index inner function input installing iter iterable iterator itertools l system lambda function len line linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path pattern permutations polygon positional parameter print pure function python standard library radial gradient range recipes rectangle recursion reduce repeat rgb rotation scaling sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle tuple turtle unpacking user space vectorisation webserver website while loop zip