Writing a function that works is the first step; the second is that other people (and you in a month) can use it without reading its code. This article gathers the practices that help the most.
Docstrings: documenting inside the function
A triple-quoted string right after the def line is the function's docstring. Python stores it in __doc__ and tools like help() display it. The first line is a short summary; if needed, a blank line follows and the parameters are explained.
def rectangle_area(base, height):
"""Computes the area of a rectangle.
base and height must be positive numbers.
"""
return base * height
print(rectangle_area.__doc__.splitlines()[0]) # Computes the area of a rectangle.
Default values and keyword arguments
A parameter with =value is optional. Parameters with a default value go after the required ones, and when calling they can be passed by position or by name (ending="."), which makes calls more readable.
def greet(name, greeting="Hello", ending="!"):
return f"{greeting}, {name}{ending}"
print(greet("Ann")) # Hello, Ann!
print(greet("Ann", "Good day")) # Good day, Ann!
print(greet("Ann", ending=".")) # Hello, Ann.
You practice it in Interest with default values.
The mutable default value trap
The default value is created only once, when the function is defined. If it is a list or a dictionary, it is shared across all calls. The usual solution is to use None as the default value and create the list inside.
def add(x, items=[]): # BAD! the list is created ONCE
items.append(x)
return items
print(add(1)) # [1]
print(add(2)) # [1, 2] <- ¡it is shared between calls!
def add_ok(x, items=None):
if items is None:
items = [] # a new list on every call
items.append(x)
return items
print(add_ok(1)) # [1]
print(add_ok(2)) # [2]
Returning several values
When a function computes several results, it returns a tuple and the caller unpacks it.
def divide(a, b):
return a // b, a % b # returns a tuple
quotient, remainder = divide(17, 5) # unpacked when calling
print(quotient, remainder) # 3 2
print(divide(17, 5)) # (3, 2)
You practice it in Seconds to hours and minutes.
Pure functions and functions with effects
A pure function always returns the same thing for the same arguments and changes nothing outside itself. It is the easiest to understand and to test. A function with effects changes global variables, prints, reads files or modifies its arguments: sometimes it is necessary, but it should be isolated and made obvious.
total = 0
def add_impure(x): # changes a variable from outside
global total
total += x
def add_pure(a, b): # depends only on its arguments
return a + b
add_impure(5); add_impure(5)
print(total) # 10 (the result depends on previous calls)
print(add_pure(5, 5)) # 10 (always the same with the same arguments)
Functions as values: composition
Since functions are values, they can be stored, passed and returned. Composing simple functions is a powerful way to build more complex ones.
def compose(*functions):
def apply(x):
for f in functions:
x = f(x)
return x
return apply
def double(x): return x * 2
def inc(x): return x + 1
f = compose(double, inc)
print(f(5)) # 11 (first double, then inc)
You practice it in Function composition.
- Give each function a single purpose and a name that says it (verb + object).
- Write at least a one-line docstring on functions that do not explain themselves.
- Prefer returning the result to printing it: that way it can be reused and tested.
- Do not use lists or dictionaries as default values: use
None. - Limit the number of parameters; if there are many, group them in a structure.