Course contents 04 / 22

04 / 22 · Getting Started

Functions

How Python functions work: def and return, how arguments are bound to parameters, defaults and the mutable-default trap, *args and **kwargs, keyword-only and positional-only parameters, the scope rule LEGB with global and nonlocal, recursion on the call stack, and docstrings.

Prerequisites

Control flow

On this page 12

The programs of the previous note already repeat themselves: the same loop over a different list, the same test written twice. A function gives a block of code a name and a list of inputs, so that it is written once and used many times, and so that a reader can understand a program one named piece at a time. This note states exactly how a call passes its arguments, which turns out to be the assignment rule of Values, types and names applied once more; where a function looks up a name; and what the interpreter keeps in memory while functions call each other, including themselves.

Baseline: copy and paste#

Without functions, computing the mean of two lists means writing the computation twice:

week1, week2 = [12, 15, 9], [7, 8]
total = 0
for v in week1:
    total += v
mean1 = total / len(week1)
total = 0
for v in week2:
    total += v
mean2 = total / len(week2)

Every copy is a place for a bug to differ, a fix has to be made in every copy, and the reader has to recognize that the blocks do the same thing. A function writes the computation once, names it, and makes the varying part, the list, an explicit input.

Defining and calling a function#

The rule. def name(parameters): followed by an indented block creates a function object and binds name to it. The block does not run yet. A call, name(arguments), runs the block with the parameters bound to the arguments. return expression ends the call and makes the value of the expression the value of the call. A function that ends without return, or with a bare return, returns None.

>>> def area(width, height):
...     return width * height
...
>>> area(3, 4)
12
>>> def greet(name):
...     print("hello,", name)
...
>>> r = greet("Ada")
hello, Ada
>>> print(r)
None

greet prints, which is a side effect, and returns nothing useful; area returns a value and prints nothing. Prefer functions of the second kind: a value can be printed, tested, stored or passed on, and a print can only be read.

The two words in the rule are different things. Parameters are the names in the definition, width and height. Arguments are the values in a call, 3 and 4. A call binds each parameter to an argument.

How arguments are bound to parameters#

The rule. A call creates a new namespace for the function’s local names and binds each parameter to an argument object, exactly as an assignment would: the object is not copied. Arguments are matched to parameters in two ways:

  • positional arguments, area(3, 4), fill the parameters from left to right;
  • keyword arguments, area(height=4, width=3), name the parameter they fill, in any order, after all positional ones.

Every parameter without a default must receive exactly one value, and no argument may be left over. Each violation has its own message:

>>> area(3)
Traceback (most recent call last):
  ...
TypeError: area() missing 1 required positional argument: 'height'
>>> area(3, 4, 5)
Traceback (most recent call last):
  ...
TypeError: area() takes 2 positional arguments but 3 were given
>>> area(3, width=4)
Traceback (most recent call last):
  ...
TypeError: area() got multiple values for argument 'width'
>>> area(3, depth=4)
Traceback (most recent call last):
  ...
TypeError: area() got an unexpected keyword argument 'depth'

In the third call, 3 fills width by position and then the keyword fills it again.

Why “not copied” matters. A parameter is one more name for the caller’s object. If the object is mutable, the function can change it, and the caller sees the change:

def add_total(numbers):
    numbers.append(sum(numbers))

values = [1, 2, 3]
add_total(values)
print(values)          # [1, 2, 3, 6]

Rebinding the parameter, numbers = [0], would change only the function’s local name and leave values alone. This rule is sometimes called call by sharing: neither “by value” (nothing is copied) nor “by reference” (the caller’s name cannot be rebound). A function that changes its argument should say so in its name or docstring; one that must not change it can work on a copy, list(numbers).

Default values#

A parameter can have a default, def power(base, exponent=2):, used when the call gives no argument for it. Parameters with defaults must come after those without.

>>> def power(base, exponent=2):
...     return base ** exponent
...
>>> power(5), power(5, 3), power(base=2, exponent=10)
(25, 125, 1024)
>>> power.__defaults__
(2,)

The rule that matters. A default value is evaluated once, when the def statement runs, and stored on the function object in __defaults__. Every call that omits the argument binds the parameter to that same stored object.

The mutable-default trap#

When the default is a mutable object, the rule above means that all calls share it:

>>> def add_item(item, bag=[]):
...     bag.append(item)
...     return bag
...
>>> add_item("apple")
['apple']
>>> add_item("pear")
['apple', 'pear']
>>> add_item.__defaults__
(['apple', 'pear'],)

Line by line: def evaluated [] once and stored the list in __defaults__. The first call bound bag to that list and appended "apple". The second call bound bag to the same list, which already held "apple". The default is not “a new empty list each time”; it is one particular list, and it has been growing.

How to recognize it. A function returns more and more data on each call; or results depend on what earlier, unrelated calls did. Linters flag a mutable default, and __defaults__ shows the accumulated state.

The fix. Use None as the default and create the object inside the function, so that a new one is made on every call that needs one:

>>> def add_item(item, bag=None):
...     if bag is None:
...         bag = []
...     bag.append(item)
...     return bag
...
>>> add_item("apple"), add_item("pear")
(['apple'], ['pear'])

The same rule bites with any default computed from the state of the world: def stamp(t=time.time()): records the time at which the function was defined, and every call returns it.

Any number of arguments: *args and **kwargs#

The rule. A parameter written *args collects all positional arguments that no other parameter took into a tuple. A parameter written **kwargs collects all keyword arguments that no other parameter took into a dictionary. The names args and kwargs are a convention; the stars are the syntax.

>>> def total(*numbers):
...     print(type(numbers), numbers)
...     return sum(numbers)
...
>>> total(1, 2, 3)
<class 'tuple'> (1, 2, 3)
6
>>> def f(a, *args, **kwargs):
...     return a, args, kwargs
...
>>> f(1, 2, 3, x=4)
(1, (2, 3), {'x': 4})

The stars work in the other direction at a call: * unpacks a sequence into positional arguments and ** unpacks a dictionary into keyword arguments. Together they let a function pass on whatever it received, which is how wrappers are written:

>>> values = [3, 4]
>>> area(*values)
12
>>> area(**{"width": 2, "height": 5})
10
>>> def scaled_area(*args, scale=1, **kwargs):
...     return scale * area(*args, **kwargs)
...
>>> scaled_area(3, 4), scaled_area(3, height=4, scale=10)
(12, 120)

The decorators note builds on exactly this pattern. Libraries use **kwargs to forward options: a plotting function that accepts **kwargs and passes them to the function that draws the line is why Matplotlib calls accept so many keyword arguments (plotting).

Keyword-only and positional-only parameters#

Two markers in a parameter list restrict how arguments may be passed (PEP 3102, PEP 570):

  • Parameters after * (or after *args) are keyword-only: they can be given only by name.
  • Parameters before / are positional-only: they cannot be given by name.
>>> def connect(host, *, port=80, timeout=5.0):
...     return f"{host}:{port} (timeout {timeout})"
...
>>> connect("example.org", port=8080)
'example.org:8080 (timeout 5.0)'
>>> connect("example.org", 8080)
Traceback (most recent call last):
  ...
TypeError: connect() takes 1 positional argument but 2 were given
>>> def clamp(x, /, low=0.0, high=1.0):
...     return min(max(x, low), high)
...
>>> clamp(1.7), clamp(-3, low=-1)
(1.0, -1)
>>> clamp(x=0.5)
Traceback (most recent call last):
  ...
TypeError: clamp() got some positional-only arguments passed as keyword arguments: 'x'

Keyword-only parameters suit options, especially flags: connect("example.org", 8080) would be unclear at the call site, and fit(X, y, True) more so. Positional-only parameters suit arguments whose name means nothing to the caller, such as the x of clamp, and leave the author free to rename them later. The full order of a parameter list is: positional-only, /, ordinary, *args or *, keyword-only, **kwargs. The Code section uses all five kinds of parameter in one signature.

Functions are objects#

def binds a name to a function object, and that object can be used like any other: bound to another name, stored in a list, passed as an argument, returned from another function.

>>> def shout(text):
...     return text.upper() + "!"
...
>>> say = shout
>>> say("hi")
'HI!'
>>> words = ["kiwi", "fig", "banana"]
>>> sorted(words, key=len)
['fig', 'kiwi', 'banana']
>>> sorted(words, key=lambda w: w[-1])
['banana', 'fig', 'kiwi']

sorted calls the function given as key on each element and sorts by the results: by length, then by last letter. lambda w: w[-1] is a lambda, an expression that creates a small unnamed function whose body is a single expression; it saves a def for a one-off key. Passing functions as arguments runs through the machine-learning courses: an optimizer receives the loss function to minimize, a data loader receives the transformation to apply to each example.

Where a name is looked up: scope#

>>> x = "global"
>>> def outer():
...     x = "enclosing"
...     def inner():
...         return x
...     return inner()
...
>>> outer(), x
('enclosing', 'global')

inner has no local x, so the lookup goes on to the enclosing function outer and finds "enclosing". The assignment in outer created a local x of outer and left the global one alone. Reading a global name from a function needs nothing special; assignment is what creates a local name.

The mistake: UnboundLocalError. A function that reads a global and then assigns to it fails on the read:

>>> count = 0
>>> def increment():
...     count += 1
...
>>> increment()
Traceback (most recent call last):
  ...
  File "<python-input-1>", line 2, in increment
    count += 1
    ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Why. The compiler decides scope once, for the whole function body, before it runs. It sees the assignment count += 1 and makes count local everywhere in increment, including on the right side of that same statement. When the call runs, the local count has not been bound yet, and reading it fails. The global count is never consulted. (The compiled code reads local names with the instruction LOAD_FAST from a fixed slot of the frame, and global names with LOAD_GLOBAL from the module’s dictionary; the decision is fixed in the bytecode.)

The same lookup order explains a quieter mistake: binding a global name that hides a built-in. After len = 5, the call len("abc") finds the global len first and fails with TypeError: 'int' object is not callable; del len removes the global and lets the lookup reach the built-in again. Avoid list, dict, str, sum, max and id as variable names.

global and nonlocal. global name inside a function makes assignments to name go to the module’s variable. nonlocal name makes them go to the variable of the nearest enclosing function:

>>> def make_counter():
...     n = 0
...     def step():
...         nonlocal n
...         n += 1
...         return n
...     return step
...
>>> c = make_counter()
>>> c(), c(), c()
(1, 2, 3)

make_counter has returned, yet its variable n lives on: step refers to it, and each call of c increments it. A function that keeps the variables of the function it was defined in is a closure; the variable is kept in a small object called a cell, visible as c.__closure__. Closures are the mechanism behind decorators, and the closures note treats them properly. Use global sparingly: a function that changes module state is harder to test and to reason about than one that takes inputs and returns a result.

Recursion and the call stack#

A function may call itself. Such a recursive function needs a base case that returns without calling itself, and every recursive call must move closer to it. The factorial n!=n⋅(n−1)!n! = n \cdot (n-1)! with 0!=10! = 1 translates directly:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

How can n be 3 and 2 and 1 at once? Each call has its own frame with its own n. The frames form a stack, the call stack: a call pushes a new frame on top, a return removes it and hands the value to the frame below, which continues from where it was waiting.

Figure

The call stack of factorial(3)

The frames of a recursive factorialFive rectangles stacked: at the bottom the module frame, above it the frames of factorial for n = 3, 2, 1 and 0. On the right, curved arrows from each frame to the one below, labelled with the returned values 1, 1, 2 and 6.the call stack: the newest frame on top<module>waits for factorial(3)1factorial(n=3)waits for factorial(2)2factorial(n=2)waits for factorial(1)3factorial(n=1)waits for factorial(0)4factorial(n=0)base case: return 15returns 16returns 1 × 1 = 17returns 2 × 1 = 28returns 3 × 2 = 69The frames of a recursive factorialFive rectangles stacked: at the bottom the module frame, above it the frames of factorial for n = 3, 2, 1 and 0. On the right, curved arrows from each frame to the one below, labelled with the returned values 1, 1, 2 and 6.the call stack: the newest frame on top<module>waits for factorial(3)1factorial(n=3)waits for factorial(2)2factorial(n=2)waits for factorial(1)3factorial(n=1)waits for factorial(0)4factorial(n=0)base case: return 15161 × 1 = 172 × 1 = 283 × 2 = 69
Each call of a function gets its own frame with its own local variables; the frames form a stack, the newest on top. factorial(3) calls factorial(2), which calls factorial(1), which calls factorial(0) (steps 1–5): four frames of one function, each with its own n. The base case n = 0 returns 1 without calling (6), and the stack unwinds: each frame multiplies its n by the value it receives and returns the result to the frame below (7–9), and is then discarded. The module receives 6.
  1. The module calls factorial(3), which gets a frame with n = 3.
  2. That frame reaches n * factorial(n - 1), calls factorial(2) and waits; a frame with n = 2 is pushed.
  3. The same happens again: a frame with n = 1.
  4. And again: a frame with n = 0.
  5. The frame with n = 0 takes the base case and makes no call.
  6. It returns 1, and its frame is discarded.
  7. The frame with n = 1 finishes its multiplication, 1⋅1=11 \cdot 1 = 1, and returns 1.
  8. The frame with n = 2 computes 2⋅1=22 \cdot 1 = 2 and returns 2.
  9. The frame with n = 3 computes 3⋅2=63 \cdot 2 = 6 and returns 6 to the module.

A version that prints on the way down and on the way up shows the same order:

>>> def factorial(n, depth=0):
...     print("  " * depth + f"call factorial({n})")
...     if n == 0:
...         result = 1
...     else:
...         result = n * factorial(n - 1, depth + 1)
...     print("  " * depth + f"factorial({n}) returns {result}")
...     return result
...
>>> factorial(3)
call factorial(3)
  call factorial(2)
    call factorial(1)
      call factorial(0)
      factorial(0) returns 1
    factorial(1) returns 1
  factorial(2) returns 2
factorial(3) returns 6
6

A traceback is a printout of this stack at the moment of the error, oldest frame first; the first note read one. The stack is the same idea that a processor implements in hardware for machine-code procedures (Procedures, the stack and calling conventions), with one difference: a CPython frame is a Python object holding the function’s local variables, its position in the bytecode and its own value stack. Since CPython 3.11, a call from Python code to a Python function does not grow the C stack; the interpreter sets up the new frame in memory it manages itself and continues in the same loop (What’s New in Python 3.11).

The recursion limit. Each frame costs memory, and a recursion without a reachable base case would never stop. CPython counts the frames and raises RecursionError when the depth exceeds a limit, 1000 by default:

>>> import sys
>>> sys.getrecursionlimit()
1000
>>> def down(n):
...     return down(n + 1)
...
>>> down(0)
Traceback (most recent call last):
  ...
  File "<python-input-0>", line 2, in down
    return down(n + 1)
  [Previous line repeated 992 more times]
RecursionError: maximum recursion depth exceeded

The traceback collapses the repeated frames into one line. sys.setrecursionlimit raises the limit, at the risk of a crash if the deeper stack does not fit in memory (sys documentation). Python does not optimize tail calls, so a recursion that is 10510^5 levels deep, such as walking a linked list of 10510^5 nodes, must be written as a loop. Recursion is natural for data that is itself recursive, such as a tree: the decision-tree note of the Machine Learning course builds a tree by choosing a split and recursing into each child, and the depth is the tree’s depth, far below the limit.

Docstrings#

A string literal as the first statement of a function body is its docstring. It is stored on the function object as __doc__ and shown by help() and by editors:

>>> def mean(xs):
...     """Return the arithmetic mean of a non-empty sequence of numbers."""
...     return sum(xs) / len(xs)
...
>>> mean.__doc__
'Return the arithmetic mean of a non-empty sequence of numbers.'
>>> help(mean)
Help on function mean:

mean(xs)
    Return the arithmetic mean of a non-empty sequence of numbers.

The convention (PEP 257) is one line that says what the function does, in the imperative, ending with a period; then, if needed, a blank line and a longer description of the arguments, the return value, side effects and the exceptions raised. A docstring states the contract, so that a caller does not need to read the body. Here the contract says “non-empty”, which tells the caller that mean([]) is their error. Type hints state the types of the contract in a form a checker can verify.

What changed#

Copy and paste (the baseline)Functions
A computation is writtenonce per useonce, and called by name
Inputsedited into each copyparameters bound to arguments, by position or by keyword
Passing data in—binding, not copying: a mutable argument can be changed by the function
Names insideshared with the whole programlocal to each call; lookup order local, enclosing, global, built-in
Repetition of the same structureloops onlyalso recursion, one frame per call, 1000 frames by default
Documentationcommentsa docstring on the function object

Limitations#

  • Closures and decorators are previewed. How a closure keeps its variables, the late-binding trap of closures created in a loop, and functions that wrap functions are in the closures and decorators note.
  • Annotations are postponed. Parameter and return annotations (def area(w: float, h: float) -> float:), and how 3.14 evaluates them lazily, are in the type hints note.
  • The cost of a call. A Python call allocates a frame and binds every argument, which costs far more than a call in C; when that matters and what to do about it is in Writing fast Python.
  • Generators and coroutines are functions that can pause in the middle of their frame; they come in the iteration and concurrency notes.

What you should remember#

  • def creates a function object and binds a name to it; a call runs the body with the parameters bound to the arguments; without return, the result is None.
  • Arguments are bound, not copied. A function can change a mutable argument, and the caller sees the change.
  • Defaults are evaluated once, at def time. Never use a mutable default; use None and create the object inside.
  • *args collects extra positional arguments into a tuple, **kwargs extra keyword arguments into a dictionary; at a call, * and ** unpack. Parameters after * are keyword-only, before / positional-only.
  • Name lookup is local, enclosing, global, built-in. Any assignment in a body makes the name local for the whole body; global and nonlocal redirect assignment.
  • Each call has its own frame on the call stack; recursion needs a base case and is limited to about 1000 levels by default.
  • A docstring states what the function does, for the caller.

Code#

The script exercises each rule of the note: one signature with all five kinds of parameter, inspected with inspect.signature; the mutable-default trap and its fix; an argument changed by a function; the scope rules, UnboundLocalError and nonlocal; the frames of a recursion counted from inside it, and the recursion limit; and a docstring. Run it with python -I functions.py; it uses only the standard library.

"""Functions: parameters, defaults, scope, recursion and frames (Python 3.14)."""
import inspect
import sys

# 1. Every kind of parameter in one signature
def fit(data, /, model="linear", *extra, epochs=10, verbose=False, **options):
    """Pretend to fit a model and report how the arguments were bound."""
    return f"data={data} model={model} extra={extra} epochs={epochs} verbose={verbose} options={options}"

print(fit([1, 2]))
print(fit([1, 2], "tree", 3, 4, epochs=5, seed=0))
for name, p in inspect.signature(fit).parameters.items():
    print(f"  {name:8} {p.kind.name}")
for bad in ("fit(data=[1])", "fit([1], 'tree', 3, model='x')"):   # data=[1] lands in **options
    try:
        eval(bad)
    except TypeError as err:
        print("TypeError:", err)

# 2. Defaults are evaluated once, when def runs
def append_to(item, bucket=[]):
    bucket.append(item)
    return bucket

print(append_to(1), append_to(2), append_to.__defaults__)   # both calls return the one default list

def append_to_fixed(item, bucket=None):
    if bucket is None:          # a new list on every call that needs one
        bucket = []
    bucket.append(item)
    return bucket

print(append_to_fixed(1), append_to_fixed(2))

# 3. Arguments are bound to parameters, not copied
def add_total(numbers):
    numbers.append(sum(numbers))

values = [1, 2, 3]
add_total(values)
print(values)

# 4. Scope: local, enclosing, global, built-in
x = "global"
def outer():
    x = "enclosing"
    def inner():
        return x, len("abc")    # x from the enclosing function, len from the built-ins
    return inner()
print(outer(), x)

counter = 0
def broken_increment():
    counter += 1                # assignment makes counter local to the whole function
try:
    broken_increment()
except UnboundLocalError as err:
    print("UnboundLocalError:", err)

def make_counter():
    count = 0
    def step():
        nonlocal count          # rebind the enclosing function's variable
        count += 1
        return count
    return step
c = make_counter()
print(c(), c(), c(), c.__code__.co_freevars)

# 5. Recursion: each call has its own frame on the call stack
def factorial(n):
    if n == 0:
        depth = 0
        frame = sys._getframe()
        while frame.f_code.co_name == "factorial":
            depth += 1
            frame = frame.f_back
        print("frames of factorial at the base case:", depth)
        return 1
    return n * factorial(n - 1)
print(factorial(5))

def depth(n):
    return depth(n + 1) if n < 10**6 else n
try:
    depth(0)
except RecursionError as err:
    print("RecursionError:", err, "| limit", sys.getrecursionlimit())

# 6. Docstrings are stored on the function object
print(fit.__doc__)

# Output with CPython 3.14.7 (the same on any platform):
# data=[1, 2] model=linear extra=() epochs=10 verbose=False options={}
# data=[1, 2] model=tree extra=(3, 4) epochs=5 verbose=False options={'seed': 0}
#   data     POSITIONAL_ONLY
#   model    POSITIONAL_OR_KEYWORD
#   extra    VAR_POSITIONAL
#   epochs   KEYWORD_ONLY
#   verbose  KEYWORD_ONLY
#   options  VAR_KEYWORD
# TypeError: fit() missing 1 required positional argument: 'data'
# TypeError: fit() got multiple values for argument 'model'
# [1, 2] [1, 2] ([1, 2],)
# [1] [2]
# [1, 2, 3, 6]
# ('enclosing', 3) global
# UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
# 1 2 3 ('count',)
# frames of factorial at the base case: 6
# 120
# RecursionError: maximum recursion depth exceeded | limit 1000
# Pretend to fit a model and report how the arguments were bound.

Two lines deserve a second look. fit(data=[1]) does not complain that data is positional-only: since fit has **options, the keyword data is collected there, and the positional data is then missing. And print(append_to(1), append_to(2), ...) shows [1, 2] twice because both calls return the same default list, which is printed after both have run.

Next#

Functions and control flow are the whole skeleton of a program; what remains of this section is the most common kind of data a program reads and writes. The next note treats text: a string as a sequence of Unicode code points, its encoding into bytes, slicing, the methods that clean and split text, f-strings, and the template strings new in 3.14.

References#