Skip to content

05. Functions — Cheat sheet

The essentials of module 05 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
define a function def name(params): + indented body def mean(values): ...
send a result back return value return total / count
return several results return a tuple, unpack at the call low, high = min_max(r)
make a parameter optional a default value def f(x, digits=1):
force callers to name an option * before it (keyword-only) def summarize(r, *, digits=1):
stop callers from naming a parameter / after it (positional-only) def mean(values, /):
accept any number of positional arguments *args (a tuple) def total(*quantities):
accept any keyword options **kwargs (a dict) def report(r, **options):
pass a list as separate arguments * in the call total(*order)
pass a dict as keyword arguments ** in the call LogisticRegression(**params)
forward options to another function **kwargs in, **kwargs out summarize(r, **options)
use a default list or dict safely default None, create in the body def f(x, seen=None):
change an enclosing variable nonlocal name counter closures
build a function from settings a factory that returns a closure make_range_check(1, 50)
sort by a field sorted(items, key=...) key=lambda p: p["price"]
sort by two fields, second descending tuple key with minus key=lambda p: (p["cat"], -p["price"])
sort text case-insensitively key=str.lower sorted(names, key=str.lower)
sort by two keys, text descending two stable sorts: second key first sorted(sorted(ps, key=price), key=cat, reverse=True)
find the item with the largest key max(items, key=...) max(products, key=margin_rate)
apply a named function to all items map(func, items) list(map(float, raw))
keep matching items comprehension with if [r for r in rs if r > 21.5]
walk nested JSON a recursive function find_values(obj, "amount")
see a function’s parameters inspect.signature(f) (values, /)
read a docstring inspect.getdoc(f) or help(f) inspect.getdoc(mean)
def line_revenue(unit_price, quantity=1, discount=0.0):
"""Return the revenue of one sales line, rounded to cents."""
return round(unit_price * quantity * (1 - discount), 2)
def min_max(values):
return min(values), max(values) # a tuple of two values
def show(values):
print(values) # no return -> the call gives None
print(line_revenue(249.00, discount=0.1), line_revenue(59.99, 4))
low, high = min_max([21.0, 22.9, 19.3])
print(low, high, show([1]))
Output
224.1 239.96
[1]
19.3 22.9 None
Rule Detail
def runs once it creates the function object; the body runs at each call
return ends the call code after it in the same block never runs
no return, or a bare return the call returns None
defaults after non-defaults def f(a, b=1) is valid; def f(a=1, b) is a SyntaxError; not required after *: def f(*, a=1, b) is valid
positional before keyword in a call f(1, b=2) is valid; f(b=2, 1) is a SyntaxError
a parameter names the caller’s object changing a list argument changes the caller’s list
prefer pure functions result depends only on arguments; no printing, no global changes
def f(a, /, b, *args, c, d=4, **kwargs):
│ │ │ │ │ └─ var-keyword: extra names → dict
│ │ │ └──┴─ keyword-only: after * or *args
│ │ └─ var-positional: extra positions → tuple
│ └─ positional-or-keyword
└─ positional-only: before /
def demo(a, /, b, *args, c, d=4, **kwargs):
return a, b, args, c, d, kwargs
print(demo(1, 2, 3, c=5, e=6))
print(demo(1, b=2, c=3))
Output
(1, 2, (3,), 5, 4, {'e': 6})
(1, 2, (), 3, 4, {})
Marker Effect Reason to use it Built-in example
* parameters after it are keyword-only options and flags explain themselves; two same-type parameters cannot be swapped; options can be added or reordered later sorted(iterable, /, *, key=None, reverse=False)
/ parameters before it are positional-only the name is an internal detail you may rename; frees the name for **kwargs len(obj, /), sum(iterable, /, start=0)
*args collects extra positions callers list values one by one print(*objects, sep=" ")
**kwargs collects extra names forward options; accept open-ended labels dict(**kwargs)
Wrong call Error (last traceback line)
missing argument TypeError: f() missing 1 required positional argument: 'quantity'
keyword-only passed by position TypeError: summarize() takes 1 positional argument but 2 were given
positional-only passed by name TypeError: mean() got some positional-only arguments passed as keyword arguments: 'values'
unknown keyword TypeError: summarize() got an unexpected keyword argument 'digit' (3.13+ adds Did you mean 'digits'?)
same parameter twice TypeError: f() got multiple values for argument 'x'
order = [4, 1, 25]
row = {"unit_price": 249.00, "quantity": 3, "discount": 0.1}
params = {"C": 1.0, "max_iter": 1000} # config["model"]["params"]
print(*order, sep=" + ") # * spreads a sequence into positions
print(line_revenue(**row)) # ** spreads a dict into keywords
print({**params, "max_iter": 200}) # merge dicts: later keys win
first, *rest = order # * in an assignment collects the remainder
print(first, rest)
Output
4 + 1 + 25
672.3
{'C': 1.0, 'max_iter': 200}
4 [1, 25]

Forwarding pattern:

def summarize(readings, *, digits=1):
return round(sum(readings) / len(readings), digits)
def sensor_report(sensor_id, readings, **summary_options):
return f"{sensor_id}: {summarize(readings, **summary_options)}"
shift = [19.5, 20.7, 20.1, 21.2]
print(sensor_report("S1", shift), sensor_report("S1", shift, digits=2))
Output
S1: 20.4 S1: 20.38
def bad(tag, tags=[]): # one list, created once, shared by every call
tags.append(tag)
return tags
def good(tag, tags=None): # None is immutable: safe
if tags is None:
tags = []
tags.append(tag)
return tags
print(bad("vip"), bad("student"))
print(good("vip"), good("student"))
Output
['vip', 'student'] ['vip', 'student']
['vip'] ['student']
Safe defaults Unsafe defaults (ruff B006, B008)
None, numbers, strings, True/False, tuples [], {}, set(), a call such as datetime.now()
Scope Holds Lifetime
Local parameters and names assigned in the function one call
Enclosing names of outer functions, seen from an inner function while a closure references them
Global names assigned at the top level of the module until the program ends
Built-in len, sum, print, max, ValueError, … always
unit = "°C" # global
def outer():
header = "S1" # enclosing for inner()
def inner(value): # value: local
return f"{header} {round(value, 1)} {unit}" # E, built-in, G
return inner(21.66)
print(outer())
Output
S1 21.7 °C
Statement Meaning Advice
(none) an assignment anywhere in a function makes the name local everywhere in it read outer names freely; do not assign them
nonlocal x assignments go to x of the nearest enclosing function for closures with state
global x assignments go to the module-level x avoid; return values instead
count = 0
def bump():
count += 1 # assignment -> count is local -> read before assignment
bump()
Output
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
def make_range_check(low, high):
def check(value):
return low <= value <= high # low and high are free variables
return check # the function, not check()
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
quantity_ok = make_range_check(1, 50)
tick = make_counter()
tick()
print(quantity_ok(25), quantity_ok(250), tick(), quantity_ok.__code__.co_freevars)
Output
True False 2 ('high', 'low')
Use Example
turn settings into a ready function make_range_check(cfg["min_quantity"], cfg["max_quantity"])
keep private state between calls counters, moving averages, caches
callbacks with parameters on_click=make_handler(row_id)
decorators (module 11) a wrapper closure around the decorated function
products = [
{"id": "P001", "category": "Electronics", "cost": 31.50, "price": 79.99},
{"id": "P008", "category": "Home", "cost": 48.00, "price": 129.95},
{"id": "P010", "category": "Home", "cost": 24.00, "price": 69.99},
{"id": "P014", "category": "Clothing", "cost": 4.20, "price": 14.99},
]
def margin_rate(p):
return (p["price"] - p["cost"]) / p["price"]
print([p["id"] for p in sorted(products, key=lambda p: p["price"])])
print([p["id"] for p in sorted(products, key=margin_rate, reverse=True)])
print([p["id"] for p in sorted(products, key=lambda p: (p["category"], -p["price"]))])
best = max(products, key=margin_rate)
print(best["id"], min(products, key=lambda p: p["cost"])["id"])
print(sorted(["boston", "Chicago", "Atlanta"], key=str.lower))
Output
['P014', 'P010', 'P001', 'P008']
['P014', 'P010', 'P008', 'P001']
['P014', 'P001', 'P008', 'P010']
P014 P014
['Atlanta', 'boston', 'Chicago']
Function Takes a function as Returns
sorted(items, key=f, reverse=False) sort key a new list
list.sort(key=f) sort key None (sorts in place)
both sorts stable: items with equal keys keep their input order so you can sort by several keys in several passes
min(items, key=f), max(items, key=f) comparison key the item itself
map(f, items) transformation a lazy iterator
filter(f, items) predicate (truthy = keep) a lazy iterator
filter(None, items) none: keeps truthy items drops 0, 0.0, "", None
Lambda rule Detail
syntax lambda params: expression
body one expression; no statements, no return, no annotations
use inline arguments: key=, callbacks
do not assign it to a name (ruff E731); write a def instead
raw = ["21.0", "21.9", "error", "21.4", "", "22.9"]
def is_number(text):
return text.strip().removeprefix("-").replace(".", "", 1).isdecimal()
print(list(map(float, filter(is_number, raw)))) # named functions: fine
print([float(t) for t in raw if is_number(t)]) # same, reads left to right
lazy = map(float, ["1", "2"])
print(list(lazy), list(lazy)) # an iterator is used up after one pass
Output
[21.0, 21.9, 21.4, 22.9]
[21.0, 21.9, 21.4, 22.9]
[1.0, 2.0] []
Situation Prefer
apply an existing named function map(func, items) or a comprehension
apply an expression or filter with a condition a comprehension
you would need a lambda inside map/filter a comprehension
you need the result twice list(...) once, then reuse the list
a huge input, one pass a generator expression (module 10)

Template:

def walk(obj):
if is_simplest(obj): # base case: answer directly, no call
return answer(obj)
return combine(walk(part) for part in split(obj)) # recursive case
def find_values(obj, key):
"""Return every value under key, at any depth of dicts and lists."""
found = []
if isinstance(obj, dict):
for k, v in obj.items():
if k == key:
found.append(v)
found.extend(find_values(v, key))
elif isinstance(obj, list):
for item in obj:
found.extend(find_values(item, key))
return found
def depth(obj):
"""Return the nesting depth of dicts and lists (0 for a leaf)."""
if isinstance(obj, dict):
return 1 + max((depth(v) for v in obj.values()), default=0)
if isinstance(obj, list):
return 1 + max((depth(v) for v in obj), default=0)
return 0
doc = {"customers": [{"id": "C1", "orders": [{"amount": 32.0}, {"amount": 24.5}]}]}
print(find_values(doc, "amount"), depth(doc), depth([]), depth(5))
Output
[32.0, 24.5] 5 1 0
Fact Detail
default depth limit sys.getrecursionlimit() is 1000
no reachable base case RecursionError: maximum recursion depth exceeded
forgot to use the recursive result the child’s work is lost; always return or extend it
use recursion for nested JSON, folder trees, HTML, any data of unknown depth
use a loop for flat sequences; very deep chains; speed
import inspect
def percent_change(*, old, new):
"""Return the change from old to new, in percent.
Args:
old: The earlier value. Must not be 0.
new: The later value.
Returns:
The relative change in percent: 100 * (new - old) / old.
Raises:
ZeroDivisionError: If old is 0.
"""
return (new - old) / old * 100
print(inspect.signature(percent_change))
print(inspect.getdoc(percent_change).splitlines()[0])
Output
(*, old, new)
Return the change from old to new, in percent.
Part Rule (PEP 257 and Google style)
quotes triple double quotes """ even for one line
summary line one line, imperative mood, ends with a period: “Return the mean.”
body blank line after the summary, then sections
Args: one entry per parameter: name: description; *args and **kwargs keep their stars
Returns: what comes back and its unit or shape
Raises: errors the function raises on purpose (module 06)
access f.__doc__, inspect.getdoc(f), help(f)
Style Section look Where you see it
Google Args: then indented entries applications, Google, mkdocstrings
NumPy Parameters + a ---------- underline NumPy, pandas, SciPy, scikit-learn
reST :param x: field lists older Sphinx projects
  • A function that prints but does not return gives the caller None.
  • return inside a loop ends the function on the first pass.
  • A mutable default ([], {}) is created once and shared by every call. Default to None.
  • Any assignment to a name inside a function makes it local in the whole function: UnboundLocalError. Use nonlocal in closures; return values instead of global.
  • A variable named sum, max, min, list, type or filter hides the built-in. The next call raises TypeError: ... object is not callable.
  • Pass the function, not its result: key=margin_rate, return check, not margin_rate() or check().
  • list.sort() returns None. Use sorted() for a new list.
  • map and filter are lazy and single-use. print(map(...)) shows <map object at 0x...>.
  • filter(None, values) drops real zeros along with None.
  • -p["category"] fails: the minus trick for descending order works only on numbers. Sort twice instead; sorting is stable.
  • "²".isdigit() is True, but float("²") fails. Test number text with isdecimal().
  • Lambdas built in a loop all see the loop variable’s last value (late binding, module 13). Use a factory function.
  • isinstance(True, int) is True: bool is a subtype of int. Use type(x) is int when a bool must be rejected.
  • f(options) passes one dict; f(**options) passes keyword arguments.
  • str.title() capitalizes after an apostrophe: "Chef's".title() is "Chef'S".
  • A recursive function without a reachable base case ends in RecursionError after about 1,000 calls.