Skip to content

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.

PythonPython not started

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:

PythonPython not started

Arguments, positionally and by keyword

PythonPython not started

Defaults

A parameter with a default becomes optional:

PythonPython not started

Parameters with defaults must come after parameters without them, otherwise Python cannot work out which is which:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

Collecting extra arguments

*args gathers leftover positional arguments into a tuple. **kwargs gathers leftover keyword arguments into a dictionary:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

Reading is different from assigning. A function can read a name from the enclosing scope without doing anything special:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

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:

PythonPython not started

Returning more than one value

return a, b builds a tuple, and the caller can unpack it:

PythonPython not started

Try it yourself

Exercise 1

Write summarise(text, *, max_words=5, suffix='…'). Return the first max_words words joined by spaces, with suffix appended only if words were dropped.

Your turnPython not started
Exercise 2

Fix the shared-history bug. Each call without a history must start an empty conversation.

Your turnPython not started

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

  • def binds a name to a function object; a function with no return returns None.
  • 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 None and build the real default inside.
  • *args and **kwargs collect 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.