Core Python·Lesson 10 of 67·intermediate
Functions, arguments and scope
Package behaviour behind a name — defaults, keyword-only arguments, *args and **kwargs, and the mutable-default bug that has broken more chat helpers than any other.
In this lesson · 18 min
- →Define functions that take positional, keyword and default arguments
- →Collect extra arguments with *args and **kwargs, and forward them on
- →Force callers to be explicit with keyword-only parameters
- →Explain what a name means inside a function, and what it does not
- →Avoid the mutable default argument trap
A function gives a piece of behaviour a name, a set of inputs and one output. Everything after this lesson — classes, decorators, an agent loop — is built from them.
def binds a name to a function object. return hands a value back. A function with no
return hands back None, which is a real value and a real source of confusion:
Arguments, positionally and by keyword
Defaults
A parameter with a default becomes optional:
Parameters with defaults must come after parameters without them, otherwise Python cannot work out which is which:
The mutable default trap
This is the single most common bug in hand-rolled chat helpers, and it is worth meeting once deliberately rather than at midnight in production:
The default value is evaluated once, when the def line runs — not once per call. Every
caller that omits history shares the same list, so conversations bleed into each other. The
fix is None plus a fresh object inside:
Collecting extra arguments
*args gathers leftover positional arguments into a tuple. **kwargs gathers leftover keyword
arguments into a dictionary:
The same two symbols run in reverse at a call site, unpacking a sequence or a dictionary into arguments. That is how you forward options through a wrapper:
Keyword-only arguments
A bare * in the parameter list means “everything after me must be passed by name”. It is the
cheapest readability win in Python:
Compare embed("hello", 256, False) with embed("hello", dimensions=256, normalise=False). Six
months later only one of them is readable.
Scope: what a name means inside a function
Names bound inside a function are local to it. They do not exist outside, and assigning to one does not touch anything above:
Reading is different from assigning. A function can read a name from the enclosing scope without doing anything special:
Python resolves a name by looking local → enclosing → global → builtins. The moment a function assigns to a name anywhere in its body, that name is local for the whole body — which produces this famous error:
If you really do mean the module-level name, say so with global. Usually the better answer is
to take it as an argument and return the new value:
Functions are values
A function is an ordinary object. You can put one in a variable, in a list, or pass it to another function:
A lambda is a one-expression function without a name. Use it for a throwaway key, not for
anything you would want to read twice:
Returning more than one value
return a, b builds a tuple, and the caller can unpack it:
Try it yourself
Write summarise(text, *, max_words=5, suffix='…'). Return the first max_words words joined by spaces, with suffix appended only if words were dropped.
Fix the shared-history bug. Each call without a history must start an empty conversation.
Check yourself
What does this print? def f(x, items=[]): items.append(x); return len(items) — then print(f(1), f(2))
Check yourself
Why write def embed(text, *, model='...') rather than def embed(text, model='...')?
Recap
defbinds a name to a function object; a function with noreturnreturnsNone.- Positional arguments go first; keyword arguments make a call site self-documenting.
- Defaults are evaluated once, at definition time — so never default to a list or a dict.
Use
Noneand build the real default inside. *argsand**kwargscollect extras; at a call site the same symbols unpack, which is how wrappers forward options they do not understand.- A bare
*makes every following parameter keyword-only. - Assigning to a name anywhere in a function makes it local everywhere in that function.
- Functions are values: store them, pass them, build pipelines out of them.