# Calling functions

Martin McBride, 2018-01-27
Tags function, positional parameter, named parameter, optional parameter, unpacking
Categories python language, intermediate python
In section Python language

This tutorial looks at different ways to pass in parameters when you call a function.

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 argument 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 arguments 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 postional arguments. As of 3.5, the argument list can contain a mixture of positional arguments and unpacked sequences, in any order, including nultiple 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 arguments. As of 3.5, the argument list can contain a mixture of named arguments and unpacked dictionaries, in any order, including nultiple unpacked dictionaries.

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

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

<<Prev

#### Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip