1.2.4. Defining functions Function definition

In [1]: def test():
...: print('in test function')
In [2]: test()
in test function


Function blocks must be indented as other control-flow blocks. Return statement

Functions can optionally return values.

In [3]: def disk_area(radius):
...: return 3.14 * radius * radius
In [4]: disk_area(1.5)
Out[4]: 7.0649999999999995


By default, functions return None.


Note the syntax to define a function:

  • the def keyword;

  • is followed by the function’s name, then

  • the arguments of the function are given between parentheses followed by a colon.

  • the function body;

  • and return object for optionally returning values. Parameters

Mandatory parameters (positional arguments)

In [5]: def double_it(x):
...: return x * 2
In [6]: double_it(3)
Out[6]: 6
In [7]: double_it()
TypeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 double_it()
TypeError: double_it() missing 1 required positional argument: 'x'

Optional parameters (keyword or named arguments)

In [8]: def double_it(x=2):
...: return x * 2
In [9]: double_it()
Out[9]: 4
In [10]: double_it(3)
Out[10]: 6

Keyword arguments allow you to specify default values.


Default values are evaluated when the function is defined, not when it is called. This can be problematic when using mutable types (e.g. dictionary or list) and modifying them in the function body, since the modifications will be persistent across invocations of the function.

Using an immutable type in a keyword argument:

In [11]: bigx = 10
In [12]: def double_it(x=bigx):
....: return x * 2
In [13]: bigx = 1e9 # Now really big
In [14]: double_it()
Out[14]: 20

Using an mutable type in a keyword argument (and modifying it inside the function body):

In [15]: def add_to_dict(args={'a': 1, 'b': 2}):
....: for i in args.keys():
....: args[i] += 1
....: print(args)
In [16]: add_to_dict
Out[16]: <function __main__.add_to_dict(args={'a': 1, 'b': 2})>
In [17]: add_to_dict()
{'a': 2, 'b': 3}
In [18]: add_to_dict()
{'a': 3, 'b': 4}
In [19]: add_to_dict()
{'a': 4, 'b': 5}


More involved example implementing python’s slicing:

In [20]: def slicer(seq, start=None, stop=None, step=None):
....: """Implement basic python slicing."""
....: return seq[start:stop:step]
In [21]: rhyme = 'one fish, two fish, red fish, blue fish'.split()
In [22]: rhyme
Out[22]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']
In [23]: slicer(rhyme)
Out[23]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']
In [24]: slicer(rhyme, step=2)
Out[24]: ['one', 'two', 'red', 'blue']
In [25]: slicer(rhyme, 1, step=2)
Out[25]: ['fish,', 'fish,', 'fish,', 'fish']
In [26]: slicer(rhyme, start=1, stop=4, step=2)
Out[26]: ['fish,', 'fish,']

The order of the keyword arguments does not matter:

In [27]: slicer(rhyme, step=2, start=1, stop=4)
Out[27]: ['fish,', 'fish,']

but it is good practice to use the same ordering as the function’s definition.

Keyword arguments are a very convenient feature for defining functions with a variable number of arguments, especially when default values are to be used in most calls to the function. Passing by value


Can you modify the value of a variable inside a function? Most languages (C, Java, …) distinguish “passing by value” and “passing by reference”. In Python, such a distinction is somewhat artificial, and it is a bit subtle whether your variables are going to be modified or not. Fortunately, there exist clear rules.

Parameters to functions are references to objects, which are passed by value. When you pass a variable to a function, python passes the reference to the object to which the variable refers (the value). Not the variable itself.

If the value passed in a function is immutable, the function does not modify the caller’s variable. If the value is mutable, the function may modify the caller’s variable in-place:

>>> def try_to_modify(x, y, z):
... x = 23
... y.append(42)
... z = [99] # new reference
... print(x)
... print(y)
... print(z)
>>> a = 77 # immutable variable
>>> b = [99] # mutable variable
>>> c = [28]
>>> try_to_modify(a, b, c)
[99, 42]
>>> print(a)
>>> print(b)
[99, 42]
>>> print(c)

Functions have a local variable table called a local namespace.

The variable x only exists within the function try_to_modify. Global variables

Variables declared outside the function can be referenced within the function:

In [28]: x = 5
In [29]: def addx(y):
....: return x + y
In [30]: addx(10)
Out[30]: 15

But these “global” variables cannot be modified within the function, unless declared global in the function.

This doesn’t work:

In [31]: def setx(y):
....: x = y
....: print('x is %d' % x)
In [32]: setx(10)
x is 10
In [33]: x
Out[33]: 5

This works:

In [34]: def setx(y):
....: global x
....: x = y
....: print('x is %d' % x)
In [35]: setx(10)
x is 10
In [36]: x
Out[36]: 10 Variable number of parameters

Special forms of parameters:
  • *args: any number of positional arguments packed into a tuple

  • **kwargs: any number of keyword arguments packed into a dictionary

In [37]: def variable_args(*args, **kwargs):
....: print('args is', args)
....: print('kwargs is', kwargs)
In [38]: variable_args('one', 'two', x=1, y=2, z=3)
args is ('one', 'two')
kwargs is {'x': 1, 'y': 2, 'z': 3} Docstrings

Documentation about what the function does and its parameters. General convention:

In [39]: def funcname(params):
....: """Concise one-line sentence describing the function.
....: Extended summary which can contain multiple paragraphs.
....: """
....: # function body
....: pass
In [40]: funcname?
Signature: funcname(params)
Concise one-line sentence describing the function.
Extended summary which can contain multiple paragraphs.
File: ~/src/scientific-python-lectures/<ipython-input-13-64e466df6d64>
Type: function


Docstring guidelines

For the sake of standardization, the Docstring Conventions webpage documents the semantics and conventions associated with Python docstrings.

Also, the NumPy and SciPy modules have defined a precise standard for documenting scientific functions, that you may want to follow for your own functions, with a Parameters section, an Examples section, etc. See https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard Functions are objects

Functions are first-class objects, which means they can be:
  • assigned to a variable

  • an item in a list (or any collection)

  • passed as an argument to another function.

In [41]: va = variable_args
In [42]: va('three', x=1, y=2)
args is ('three',)
kwargs is {'x': 1, 'y': 2} Methods

Methods are functions attached to objects. You’ve seen these in our examples on lists, dictionaries, strings, etc… Exercises

function quicksort(array)
var list less, greater
if length(array) < 2
return array
select and remove a pivot value pivot from array
for each x in array
if x < pivot + 1 then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))