Functions, scope and closures
How to define and call functions in Python: every parameter kind, how names are looked up (LEGB), closures, functions as values, key= functions for sorting, functools.partial, recursion and docstrings. Every runnable block is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| define a function | def name(params) -> type: |
def area(w: float, h: float) -> float: |
| return several values | return a tuple, unpack it | lo, hi = bounds(xs) |
| give a parameter a default | param=value |
def load(path, sep=","): |
| default to a new list or dict | None default, then create |
if items is None: items = [] |
| detect “argument not passed” | a sentinel object | _MISSING = object() |
| force keyword arguments | * in the signature |
def f(a, *, verbose=False): |
| force positional arguments | / in the signature |
def f(x, y, /): |
| accept any number of positional args | *args |
def total(*amounts): |
| accept any keyword args | **kwargs |
def tag(name, **attrs): |
| pass a list as separate arguments | * in the call |
f(*values) |
| pass a dict as keyword arguments | ** in the call |
f(**options) |
| forward all arguments | *args, **kwargs |
return func(*args, **kwargs) |
| change a global variable | global name (better: return the value) |
|
| change a variable of the enclosing function | nonlocal name |
counters in closures |
| make a function that remembers state | a closure | make_counter() |
| write a tiny inline function | lambda args: expr |
key=lambda r: r["revenue"] |
| sort by a field | sorted(xs, key=...) |
sorted(rows, key=itemgetter("city")) |
| sort by two fields, one descending | key returns a tuple; negate numbers | key=lambda r: (r["region"], -r["revenue"]) |
| sort case-insensitively | key=str.casefold |
sorted(names, key=str.casefold) |
| get the item with the largest value | max(xs, key=...) |
max(stores, key=lambda s: s["size"]) |
handle an empty input to min or max |
default= |
max([], default=0) |
| fix some arguments of a function | functools.partial |
parse_eu = partial(parse, dayfirst=True) |
| apply a function to every item | comprehension or map |
[f(x) for x in xs] |
| keep items that pass a test | comprehension or filter |
[x for x in xs if ok(x)] |
| fold a sequence into one value | functools.reduce (or a loop) |
reduce(operator.mul, xs, 1) |
| pick a function by name | a dict of functions (dispatch table) | handlers[command](args) |
| cache results of a pure function | @functools.cache |
see decorators |
| see a function’s parameters | inspect.signature(f) |
print(inspect.signature(f)) |
| document a function | docstring | """Return the mean of values.""" |
| read the documentation | help(f), f.__doc__ |
|
| raise the recursion limit | sys.setrecursionlimit(n) (with care) |
prefer a loop |
Parameter kinds
Section titled “Parameter kinds”def f(pos_only, /, standard, *args, kw_only, kw_default=1, **kwargs): ...# ^ before / ^ either ^ extra ^ after * or *args: keyword only# positional way positional ^ extra keywords| Kind | Declared | Called as | Inside the function |
|---|---|---|---|
| positional-only | before / |
f(1) only |
the name is private; callers cannot use it |
| positional or keyword | between / and * |
f(1) or f(x=1) |
|
| var-positional | *args |
any extra positional arguments | a tuple |
| keyword-only | after * or *args |
f(verbose=True) only |
|
| var-keyword | **kwargs |
any extra keyword arguments | a dict |
| default | name=value |
may be left out | value is computed once, at def time |
def report(store_id, /, metric, *extra, top=3, **options): print(store_id, metric, extra, top, options)
report("S01", "revenue")report("S01", metric="units", top=5)report("S02", "revenue", "q1", "q2", currency="USD", round_to=2)S01 revenue () 3 {}S01 units () 5 {}S02 revenue ('q1', 'q2') 3 {'currency': 'USD', 'round_to': 2}def report(store_id, /, metric, *extra, top=3, **options): print(store_id, metric, extra, top, options)
report(store_id="S01", metric="revenue") # positional-only passed by keywordTypeError: report() missing 1 required positional argument: 'store_id'| Call rule | Example | Error if broken |
|---|---|---|
| positional arguments come before keyword ones | f(1, b=2) |
SyntaxError: positional argument follows keyword argument |
| each parameter gets one value | f(1, a=1) |
TypeError: f() got multiple values for argument 'a' |
| required parameters need a value | f() |
TypeError: f() missing 1 required positional argument: 'a' |
no unknown keywords (without **kwargs) |
f(z=1) |
TypeError: f() got an unexpected keyword argument 'z' |
| in a signature, defaults come after required parameters | def f(a=1, b): |
SyntaxError (keyword-only parameters are exempt) |
Unpacking in calls
Section titled “Unpacking in calls”def describe(name, city, size_sqm=0): return f"{name} in {city}, {size_sqm:,} sqm"
row = ["S01", "Chicago", 2850]options = {"city": "Detroit", "size_sqm": 1420}print(describe(*row))print(describe("S03", **options))print(*["a", "b", "c"], sep=" | ") # spread a list into print()S01 in Chicago, 2,850 sqmS03 in Detroit, 1,420 sqma | b | cDefaults
Section titled “Defaults”def add_bad(item, bucket=[]): # one list, created once at def time bucket.append(item) return bucket
def add_good(item, bucket=None): if bucket is None: bucket = [] # a new list on every call bucket.append(item) return bucket
print(add_bad(1), add_bad(2))print(add_good(1), add_good(2))[1, 2] [1, 2][1] [2]_MISSING = object() # a unique sentinel: None may be a valid value
def lookup(d, key, default=_MISSING): if key in d: return d[key] if default is _MISSING: raise KeyError(key) return default
print(lookup({"a": None}, "a"), lookup({}, "b", None), lookup({}, "c", 0))None None 0Scope: LEGB
Section titled “Scope: LEGB”Python looks a name up in four scopes, in this order:
| Scope | Where | Example |
|---|---|---|
| Local | assigned inside the current function (parameters too) | total = 0 in the function |
| Enclosing | local names of outer functions | a closure’s free variables |
| Global | top level of the module | TAX_RATE = 0.2 |
| Built-in | the builtins module |
len, print, max |
| Rule | Detail |
|---|---|
| assignment makes a name local | anywhere in the function body, even after the first read |
| reading needs no declaration | functions can read globals and enclosing names freely |
global x |
assignments to x change the module-level name |
nonlocal x |
assignments change the nearest enclosing function’s x |
| blocks do not create scopes | if, for, with, try leak names (except the as name of an except clause, which is deleted); comprehensions and functions do not |
| shadowing a built-in | list = [1] hides list() for the rest of the module |
count = 10
def bump(): count += 1 # assignment makes count local, so the read fails return count
bump()UnboundLocalError: cannot access local variable 'count' where it is not associated with a valuecount = 10
def bump_global(): global count # rebind the module-level name count += 1
def make_counter(): n = 0
def increment(): nonlocal n # rebind the enclosing function's name n += 1 return n
return increment
bump_global()counter = make_counter()print(count, counter(), counter(), counter())for i in range(3): square = i * iprint("after the loop:", i, square) # for loops do not create a scope11 1 2 3after the loop: 2 4Closures and factories
Section titled “Closures and factories”A closure is an inner function that remembers names from the enclosing function after that function returns.
def make_scaler(factor): def scale(x): return x * factor # factor is a free variable
return scale
to_cents = make_scaler(100)print(to_cents(4.99), make_scaler(2)(21), to_cents.__closure__[0].cell_contents)499.0 42 100Closures capture variables, not values:
late = [lambda: i for i in range(3)] # all three see the final ibound = [lambda i=i: i for i in range(3)] # a default captures the current iprint([f() for f in late], [f() for f in bound])[2, 2, 2] [0, 1, 2]| Pattern | Use |
|---|---|
| factory function | make configured functions: make_validator(low, high) |
| counter or accumulator | keep state without a class (nonlocal) |
| decorator | wrap a function; see decorators |
| callback with context | button.on_click(make_handler(item)) |
| class instead | when state has several fields or methods |
Functions as values
Section titled “Functions as values”import operator
def mean(xs): return sum(xs) / len(xs)
stats = {"min": min, "max": max, "mean": mean} # dispatch tablevalues = [21.0, 21.9, 21.4]print({name: round(f(values), 2) for name, f in stats.items()})ops = {"+": operator.add, "*": operator.mul}print(ops["*"](6, 7), mean.__name__, callable(mean), callable(42)){'min': 21.0, 'max': 21.9, 'mean': 21.43}42 mean True Falselambda
Section titled “lambda”| Rule | Detail |
|---|---|
| syntax | lambda params: expression |
| one expression only | no statements, no assignments (:= works but hurts reading) |
| returns the expression | no return keyword |
| use it for | short key= and callback arguments |
| avoid | f = lambda x: x + 1; write def f(x): return x + 1 (ruff E731) |
Key functions: sorted, min, max
Section titled “Key functions: sorted, min, max”| Goal | Code |
|---|---|
| by a dict field | sorted(rows, key=lambda r: r["revenue"]) or key=itemgetter("revenue") |
| by an attribute | sorted(objs, key=attrgetter("city")) |
| by several fields | key=itemgetter("region", "city") or key=lambda r: (r["region"], r["city"]) |
| mixed directions | negate numbers: key=lambda r: (r["region"], -r["revenue"]) |
| mixed directions on text | two stable sorts: secondary first, then primary |
| case-insensitive | key=str.casefold |
| by length, then alphabetically | key=lambda s: (len(s), s) |
| largest value’s key in a dict | max(d, key=d.get) |
| empty input | max(xs, default=None) |
| N largest | heapq.nlargest(n, xs, key=...) |
| a method call as key | key=methodcaller("lower") |
from operator import itemgetter
stores = [ {"id": "S04", "region": "South", "size": 3100}, {"id": "S01", "region": "North", "size": 2850}, {"id": "S02", "region": "North", "size": 1950}, {"id": "S05", "region": "South", "size": 1950},]print([s["id"] for s in sorted(stores, key=itemgetter("size"))]) # stable for tiesprint([s["id"] for s in sorted(stores, key=lambda s: (s["region"], -s["size"]))])print(max(stores, key=itemgetter("size"))["id"], min([], default="none"))names = ["bob", "Anna", "carl", "al"]print(sorted(names), sorted(names, key=str.casefold)) # upper case sorts firstprint(sorted(names, key=lambda s: (len(s), s)))counts = {"a": 3, "b": 7, "c": 5}print(max(counts, key=counts.get))['S02', 'S05', 'S01', 'S04']['S01', 'S02', 'S04', 'S05']S04 none['Anna', 'al', 'bob', 'carl'] ['al', 'Anna', 'bob', 'carl']['al', 'bob', 'Anna', 'carl']bmap, filter, reduce and partial
Section titled “map, filter, reduce and partial”from functools import partial, reduceimport operator
lines = [" 21.0", "21.9 ", "", " 21.4"]print(list(map(str.strip, lines)), list(filter(None, map(str.strip, lines))))print(list(map(operator.add, [1, 2, 3], [10, 20, 30]))) # several iterablesprint(reduce(operator.mul, [1, 2, 3, 4], 1)) # ((1 * 1) * 2) * 3 * 4parse_hex = partial(int, base=16)print(parse_hex("ff"), parse_hex.func.__name__, parse_hex.keywords)round2 = partial(round, ndigits=2)print([round2(x) for x in (3.14159, 2.71828)])['21.0', '21.9', '', '21.4'] ['21.0', '21.9', '21.4'][11, 22, 33]24255 int {'base': 16}[3.14, 2.72]| Tool | Prefer | Note |
|---|---|---|
map(f, xs) |
[f(x) for x in xs] unless f already exists |
lazy iterator |
filter(pred, xs) |
[x for x in xs if pred(x)] |
filter(None, xs) drops falsy items |
reduce(f, xs, start) |
sum, math.prod, max, "".join, or a loop |
always pass a start value |
partial(f, *a, **kw) |
a lambda when you need to reorder arguments |
keeps func, args, keywords |
operator.itemgetter, attrgetter, methodcaller |
faster and clearer than tiny lambdas |
Recursion
Section titled “Recursion”import sysfrom functools import cache
def flatten(items): """Yield the leaves of nested lists.""" for item in items: if isinstance(item, list): yield from flatten(item) # recursive case else: yield item # base case
@cache # remember results: O(n) instead of O(2**n)def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)
print(list(flatten([1, [2, [3, [4]], 5]])), fib(80), sys.getrecursionlimit())[1, 2, 3, 4, 5] 23416728348467685 1000| Rule | Detail |
|---|---|
| base case first | a case that returns without calling itself |
| every call gets closer to the base case | smaller input each time |
| depth limit | about 1000 frames by default; RecursionError beyond it |
| no tail-call optimization | deep linear recursion should be a loop |
| good fits | trees, nested JSON, divide and conquer, backtracking |
| repeated sub-problems | @functools.cache |
Docstrings and introspection
Section titled “Docstrings and introspection”import inspect
def churn_rate(churned: int, total: int, *, as_percent: bool = False) -> float: """Return the share of customers who churned.
Args: churned: Number of customers who left. total: Number of customers at the start. as_percent: Return 0-100 instead of 0-1.
Returns: The churn rate.
Raises: ValueError: If total is not positive. """ if total <= 0: raise ValueError("total must be positive") rate = churned / total return rate * 100 if as_percent else rate
print(churn_rate(30, 200), churn_rate(30, 200, as_percent=True))print(inspect.signature(churn_rate))print(churn_rate.__doc__.splitlines()[0], churn_rate.__annotations__["return"])0.15 15.0(churned: int, total: int, *, as_percent: bool = False) -> floatReturn the share of customers who churned. <class 'float'>| Part | Content |
|---|---|
| first line | one sentence in the imperative: “Return …”, “Load …” |
Args: |
each parameter and its meaning (types live in the hints) |
Returns: / Yields: |
what comes back |
Raises: |
exceptions a caller should handle |
Example: |
optional; doctest-style >>> lines |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
mutable default def f(x=[]) |
the list grows across calls | x=None, then if x is None: x = [] |
default from a call def f(t=time.time()) |
the value is frozen at def time |
compute it inside the function |
UnboundLocalError |
assigning a name you also read from an outer scope | pass it in and return the new value; or nonlocal / global |
| lambdas in a loop | all return the last value | lambda i=i: ... or functools.partial |
forgetting return |
the function returns None |
return the value; ruff and type checkers help |
return inside a loop |
stops after the first item | return after the loop |
| calling instead of passing | key=len() is a TypeError; on_click(f()) runs now |
pass the function: key=len |
sorted(..., key=...) with reverse=True and mixed directions |
wrong order | negate numeric keys, or sort twice (stable) |
max([]) |
ValueError: max() iterable argument is empty |
max(xs, default=...) |
map and filter return iterators |
printing shows <map object at ...>; second pass is empty |
wrap in list(...) once |
global everywhere |
hidden coupling, hard tests | parameters in, return values out |
| shadowing built-ins | TypeError: 'list' object is not callable |
rename list, sum, max, id, type variables |
| deep recursion | RecursionError: maximum recursion depth exceeded |
rewrite as a loop with an explicit stack |
*args order |
def f(*args, x) makes x keyword-only |
intended; document it |
**kwargs typos |
verbos=True is silently accepted |
avoid **kwargs when you know the options |
f = lambda ... |
no useful name in tracebacks | def f(...) |
Learn more
Section titled “Learn more”- 05. Functions and its cheat sheet
- 09. Standard library for
functoolsandoperator - Decorators and context managers
- Iterators and generators