Skip to content
BIASED

Functions

How functions work: def and return, binding arguments to parameters, defaults and their trap, *args and **kwargs, keyword-only and positional-only parameters, LEGB name lookup, recursion on the call stack, and docstrings.

Giving code a name

The topic Control flow ended with programs long enough to repeat themselves. Here is a typical case: the mean training loss and the mean validation loss, computed by the same loop written twice.

train = [0.9, 0.6, 0.3]
val = [1.2, 0.8]
total = 0
for loss in train:
    total += loss
train_mean = total / len(train)
total = 0
for loss in val:
    total += loss
val_mean = total / len(val)
print(train_mean, val_mean)
0.6 1.0

Every copy is a place for a bug to differ, and a fix has to be made in every copy. The reader also has to notice that the two blocks do the same thing. A function writes the computation once, gives it a name, and turns the part that varies, the list, into an input.

def mean(values):
    total = 0
    for v in values:
        total += v
    return total / len(values)
 
print(mean([0.9, 0.6, 0.3]), mean([1.2, 0.8]))
print(mean)
0.6 1.0
<function mean at 0x10acdf5e0>

The rule. def name(parameters): followed by an indented block creates a function object and binds the name to it, just as an assignment would. The body does not run yet. A call, mean([...]), runs the body. return expression ends the call, and the value of the expression becomes the value of the call. The last line shows that mean is an ordinary object; the hexadecimal number is its address in memory and changes from run to run.

The names in the definition, values, are parameters. The values in a call, the two lists, are arguments. A call binds each parameter to an argument.

A function that reaches the end of its body without return, or stops at a bare return, returns None:

def report(epoch, loss):
    print(f"epoch {epoch}: loss {loss}")
 
r = report(3, 0.45)
print(r)
epoch 3: loss 0.45
None

report has a side effect, printing, and returns nothing useful. mean returns a value and prints nothing. Prefer the second kind: a value can be printed, tested, stored or passed on, while a printed line can only be read.

How arguments reach parameters

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

  • positional arguments fill the parameters from left to right;
  • keyword arguments name the parameter they fill, in any order, after all positional ones.
def scale(value, factor):
    return value * factor
 
print(scale(0.5, 4), scale(factor=4, value=0.5))
2.0 2.0

Every parameter must receive exactly one value, and no argument may be left over. Each violation raises TypeError with its own message, on the last line of the traceback:

  • scale(0.5) gives TypeError: scale() missing 1 required positional argument: 'factor';
  • scale(0.5, 4, 2) gives TypeError: scale() takes 2 positional arguments but 3 were given;
  • scale(0.5, value=4) gives TypeError: scale() got multiple values for argument 'value';
  • scale(0.5, factr=4) gives TypeError: scale() got an unexpected keyword argument 'factr'. Did you mean 'factor'?

In the third call, 0.5 fills value by position, and then the keyword tries to fill it again.

Why "not copied" matters. The topic Values, types and names showed that assignment copies nothing. A parameter is therefore one more name for the caller's object. If that object is mutable, the function can change it, and the caller sees the change. Rebinding the parameter, on the other hand, moves only the local name:

def log_loss(history, loss):
    history.append(loss)
 
losses = [0.9, 0.6]
log_loss(losses, 0.3)
print(losses)
 
def reset(history):
    history = []
 
reset(losses)
print(losses)
[0.9, 0.6, 0.3]
[0.9, 0.6, 0.3]

This rule is called call by sharing. It is not "by value", since nothing is copied, and not "by reference", since the function cannot rebind the caller's name. 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(history).

Defaults are evaluated once

A parameter can have a default value, used when a call gives no argument for it. Parameters with defaults come after those without.

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

The rule that matters. A default 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.

With a number this is harmless. With a mutable default, all calls share one object:

def log_loss(loss, history=[]):
    history.append(loss)
    return history
 
print(log_loss(0.9))
print(log_loss(0.6))
print(log_loss.__defaults__)
[0.9]
[0.9, 0.6]
([0.9, 0.6],)

def evaluated [] once and stored that list. The first call appended 0.9 to it. The second call got the same list, which already held 0.9. The default is not "a new empty list each time". It is one particular list, and it keeps growing. The symptoms are a function that returns more and more data, or results that depend on earlier, unrelated calls. Linters flag mutable defaults.

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

def log_loss(loss, history=None):
    if history is None:
        history = []
    history.append(loss)
    return history
 
print(log_loss(0.9), log_loss(0.6))
[0.9] [0.6]

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

*args, **kwargs, * and /

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

def total(*numbers):
    print(type(numbers), numbers)
    return sum(numbers)
 
print(total(1, 2, 3))
 
def show(first, *args, **kwargs):
    return first, args, kwargs
 
print(show(1, 2, 3, lr=0.1, seed=0))
<class 'tuple'> (1, 2, 3)
6
(1, (2, 3), {'lr': 0.1, 'seed': 0})

At a call the stars work the other way: * unpacks a sequence into positional arguments and ** unpacks a dict into keyword arguments. Together they let a function pass on whatever it received. That is how wrappers are written, and the topic Closures and decorators builds on exactly this pattern.

def scale(value, factor):
    return value * factor
 
pair = [0.5, 4]
options = {"value": 0.5, "factor": 10}
print(scale(*pair), scale(**options))
 
def logged(*args, **kwargs):
    print("calling scale with", args, kwargs)
    return scale(*args, **kwargs)
 
print(logged(0.5, factor=3))
2.0 5.0
calling scale with (0.5,) {'factor': 3}
1.5

Two markers restrict how arguments may be passed. Parameters after * (or after *args) are keyword-only. Parameters before / are positional-only.

def train(model, *, epochs=10, verbose=False):
    return f"{model}: {epochs} epochs, verbose={verbose}"
 
def clip(x, /, low=0.0, high=1.0):
    return min(max(x, low), high)
 
print(train("mlp", epochs=3))
print(clip(1.7), clip(-3, low=-1))
mlp: 3 epochs, verbose=False
1.0 -1

Now train("mlp", 3) fails with TypeError: train() takes 1 positional argument but 2 were given, and clip(x=0.5) fails with TypeError: clip() got some positional-only arguments passed as keyword arguments: 'x'. Keyword-only parameters suit options and flags: without the *, the call train("mlp", 3, True) would be legal and would tell the reader nothing. Positional-only parameters suit arguments whose name means nothing to the caller, and leave the author free to rename them later.

One signature can use every kind of parameter at once. Here data is positional-only, model is ordinary, extra collects extra positional arguments, epochs is keyword-only and options collects the rest:

def fit(data, /, model="linear", *extra, epochs=10, **options):
    return data, model, extra, epochs, options
 
print(fit([1, 2]))
print(fit([1, 2], "tree", 3, 4, epochs=5, seed=0))
([1, 2], 'linear', (), 10, {})
([1, 2], 'tree', (3, 4), 5, {'seed': 0})

Where a name is looked up

Key idea. Each call gets its own frame, with its own namespace of local names. Inside the body a name is looked up in four places, in order: Local (this call), Enclosing (the functions this one is defined inside), Global (the module) and Built-in (len, print, …). The first binding found wins. This order is called LEGB.

lr = 0.1                      # global
 
def outer():
    lr = 0.01                 # local to outer
    def inner():
        return lr, len("abc") # lr from outer, len from built-ins
    return inner()
 
print(outer(), lr)
(0.01, 3) 0.1

inner has no lr of its own, so the lookup moves on to outer and finds 0.01. The assignment in outer created a local lr and left the global one alone. Reading a global needs nothing special. Assignment is what makes a name local.

Which names are local is decided by the compiler, once, for the whole body, before it runs. A name that is assigned anywhere in the body is local everywhere in it. That explains a classic error:

step = 0
 
def advance():
    step += 1
 
advance()

The call fails, and the traceback ends with

UnboundLocalError: cannot access local variable 'step' where it is not associated with a value

step += 1 is an assignment, so step is local in advance, including on the right-hand side of that same line. When the call reads it, the local step is not bound yet. The global step is never consulted. The same order explains a quieter mistake: after len = 5 at module level, len("abc") finds the global first and fails with TypeError: 'int' object is not callable. Avoid list, dict, str, sum, max and id as variable names.

To assign to an outer variable, say so. global step sends assignments to the module's variable. nonlocal count sends them to the variable of the nearest enclosing function:

def make_counter():
    count = 0
    def tick():
        nonlocal count
        count += 1
        return count
    return tick
 
c = make_counter()
print(c(), c(), c())
1 2 3

make_counter has already returned, yet its count lives on, because tick still refers to it. A function that keeps the variables of the function it was defined in is a closure. The topic Closures and decorators explains how that works. Use global sparingly: a function that changes module state is harder to test 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, with n!=n⋅(n−1)!n! = n \cdot (n-1)! and 0!=10! = 1, translates directly:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)
 
print(factorial(5), factorial(20))
120 2432902008176640000

How can n be 3 and 2 and 1 at once? Each call has its own frame with its own n. The frames form 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. A version that prints on the way down and on the way up shows the 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
 
print(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, met in the topic Running Python, is a printout of this stack at the moment of an error, oldest frame first. The topic How CPython runs code shows what a frame holds inside.

Each frame costs memory, and a recursion that never reaches its base case would never stop. CPython counts the frames and raises RecursionError when the depth passes a limit, 1000 by default (sys.getrecursionlimit()). A script with def down(n): return down(n + 1) ends its traceback like this:

  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Python does not optimize tail calls, so a recursion 10510^5 levels deep, such as walking a chain of 10510^5 linked records, should be written as a loop. Recursion fits data that is itself recursive, such as a tree: a decision tree in the Machine Learning course is built by choosing a split and recursing into each child, and the depth stays far below the limit.

Docstrings, functions as objects and what comes next

A string literal as the first statement of a body is the function's docstring. It is stored on the function object as __doc__, and help(mean) and editors show it.

def mean(values):
    """Return the arithmetic mean of a non-empty list of numbers."""
    return sum(values) / len(values)
 
print(mean.__doc__)
Return the arithmetic mean of a non-empty list of numbers.

By convention (PEP 257), the first line says what the function does, in the imperative, and ends with a period. If needed, a blank line follows, then the arguments, the return value, the side effects and the errors. A docstring states the contract, so the caller need not read the body. Here "non-empty" tells the caller that mean([]) is their mistake. The topic Type hints writes the types of that contract in a form a checker can verify.

__doc__ and __defaults__ are attributes, because a function is an object like any other. It can be bound to another name, stored, passed as an argument:

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

sorted calls the function passed as key on each element and sorts by the results. lambda w: w[-1] is a lambda: an expression that makes a small unnamed function whose body is one expression. Passing functions around runs through the ML courses: an optimizer receives the loss to minimize, a data loader receives the transform to apply to each example. Functions that take and return functions are the subject of Closures and decorators.

Values, names, control flow and functions are the whole skeleton of a program. Notice what the examples here kept handling, though: names of runs, messages, words, a docstring. The most common data a program reads and writes is text. The next topic, Strings and text, shows what a Python string is, how it becomes bytes, and how to cut, clean and format it.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Function: calculate a discountoptional

    Real Python in your browser with result checks and a stop button. Device-local self-check; does not affect certificates.

    ~8 min · any device · Read this topic's notes.

    Open practice

Full notes

Answers are saved on the server and tied to this browser until you sign in.