Sub topic 3
Giving parameters default values
This chapter assumes you can define and call functions, know the difference between positional and keyword arguments in a call, and can read a simple traceback. It covers what a default value is, how it affects argument binding, and which mistakes to expect. The timing of default evaluation and the mutable default bug get their own chapters. This chapter only points at them.
What a default value is
A default value is a value written in the def line with =. If the caller supplies no argument for that parameter, Python uses the default. If the caller does supply one, the default is ignored.
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
print(greet("Ada")) # Hello, Ada!
print(greet("Ada", "Hi")) # Hi, Ada!
print(greet("Ada", punctuation="?")) # Hello, Ada?
print(greet(name="Ada", greeting="Hey")) # Hey, Ada!name has no default, so it is required. greeting and punctuation are optional. Each call above supplies a different subset of arguments, and Python fills the rest from the defaults.
How binding works with defaults
When you call a function, Python binds arguments to parameters in this order:
- Positional arguments fill parameters from left to right.
- Keyword arguments fill parameters by name.
- Any parameter still unfilled takes its default.
- If a parameter is still unfilled and has no default, Python raises
TypeError.
The check is about whether an argument was passed, not about what its value is. Passing None, 0, "" or False explicitly counts as passing an argument, and the default is not used:
def label(text, prefix="item"):
return f"{prefix}: {text}"
print(label("x")) # item: x
print(label("x", prefix="")) # : x
print(label("x", prefix=None)) # None: xA common mistake is to write prefix = prefix or "item" inside the function. That replaces an intentional empty string with the default, which is rarely what you want.
Skipping parameters with keywords
Positional arguments fill parameters strictly left to right. If you want to override the third parameter and keep the second at its default, you cannot leave a gap. Use a keyword instead:
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
# greet("Ada", , "?") # SyntaxError: there is no way to skip a position
print(greet("Ada", punctuation="?")) # Hello, Ada?This is the main practical benefit of defaults combined with keywords. A function can have many options, and each call names only the ones it changes.
You can mix the two styles, but positional arguments must come first in the call. You also cannot supply the same parameter twice:
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
try:
greet("Ada", "Hi", greeting="Hey")
except TypeError as e:
print(e) # greet() got multiple values for argument 'greeting'Here "Hi" was bound to greeting by position, and then the keyword tried to bind it again.
Ordering rule: required before optional
In a plain parameter list, a parameter without a default cannot follow one that has a default. Python rejects the definition before any call happens:
# def bad(a, b=1, c): # SyntaxError
# ...The exact message depends on your Python version. Older versions say non-default argument follows default argument. Newer ones say parameter without a default follows parameter with a default.
The rule exists because positional binding is left to right. If c were required but sat after an optional b, a call such as bad(10, 20) would be ambiguous. Is 20 for b or for c? Python avoids the question by forbidding the layout.
The rule has one exception that this chapter only mentions. Keyword-only parameters, which come after a bare *, may be required or optional in any order, because they are never bound by position. The chapter on keyword-only parameters covers this.
What may be used as a default
A default can be any expression. Literals are the most common, but names, function calls, and arithmetic all work:
import math
DEFAULT_TIMEOUT = 30
def wait(seconds=DEFAULT_TIMEOUT):
return seconds
def circle_area(r, pi=math.pi):
return pi * r * r
def window(size=2 * 60):
return size
print(wait()) # 30
print(circle_area(1)) # 3.141592653589793
print(window()) # 120There is one restriction. A default cannot refer to an earlier parameter of the same function, because the expression is evaluated outside the function, before any call and before any parameter has a value:
def area(width, height=width): # NameError: name 'width' is not defined
return width * heightIf you want "height defaults to width", you need a different technique. The usual one is to use None as the default and resolve it inside the body:
def area(width, height=None):
if height is None:
height = width
return width * height
print(area(4)) # 16
print(area(4, 5)) # 20The None sentinel pattern is also the standard fix for the mutable default bug, and a later chapter treats it in full.
Defaults and the meaning of "optional"
A default makes a parameter optional for the caller. It also makes the default value part of the function's behavior, so choose it deliberately.
- Pick a default that is right for most callers. If every caller overrides it, it should probably be a required parameter.
- Prefer defaults that are immutable: numbers, strings, booleans, tuples,
None. Mutable defaults such as lists and dicts are shared between calls. Do not use them until you have read the chapter on that pitfall. - Do not use a default to hide a required decision. A
delete(path, force=True)function that destroys data unless told otherwise is a design problem, not a convenience. - Changing a default later changes behavior for every caller who relied on it. Treat it as a change to your public interface.
If None is a legitimate value that callers might pass on purpose, None cannot also mean "not provided". In that case a library often creates a private marker object to detect omission:
_MISSING = object()
def fetch(key, default=_MISSING):
data = {"a": 1}
if key in data:
return data[key]
if default is _MISSING:
raise KeyError(key)
return default
print(fetch("a")) # 1
print(fetch("b", None)) # None
try:
fetch("b")
except KeyError as e:
print("missing", e) # missing 'b'Here fetch("b", None) returns None because the caller explicitly passed it, while fetch("b") raises. A default of None could not tell these two calls apart.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Required parameter after an optional one | `SyntaxError` when the function is defined | Reorder the parameters, or make the later one keyword-only |
| Default referring to an earlier parameter | `NameError` at definition time, or a wrong value if the name exists in an outer scope | Use `None` and resolve it inside the body |
| Using `x = x or default` in the body | Falsy values such as `0` and `""` are silently replaced | Test with `is None` |
| Passing a positional argument and a keyword for the same parameter | `TypeError: got multiple values for argument` | Pass it only once |
| Omitting a required parameter | `TypeError: missing 1 required positional argument` | Supply it, or give it a default if it should be optional |
| Mutable default such as `[]` | State leaks between calls | See the later chapters on the pitfall and the fix |
Checking your understanding
Try predicting the output before you run each call in the exercise below. Reading a call by following the binding steps, one parameter at a time, is the skill that makes the later TypeError chapters easier.
Exercise
Given def box(width, height=1, depth=1): return width * height * depth, what does each call return or raise? (a) box(2) (b) box(2, depth=5) (c) box(2, 3, height=4) (d) box(height=3). Then explain why def bad(a=1, b): is rejected.
Show answer
(a) 2, because height and depth use their defaults of 1. (b) 10, because width is 2, height stays 1, and depth is 5. (c) It raises TypeError: box() got multiple values for argument 'height', because 3 was bound to height by position and the keyword binds it again. (d) It raises TypeError: box() missing 1 required positional argument: 'width', because width has no default and no argument was passed for it. def bad(a=1, b): is a SyntaxError because the required parameter b follows the optional a. Positional binding goes left to right, so a call like bad(5) would not say whether 5 was meant for a or for b.
Exercise
Write describe(name, title=None) that returns "Dr. Ada" when called as describe("Ada", "Dr."), and just "Ada" when the title is omitted. Why is if title: a weaker test than if title is not None: if an empty string might be a meaningful title?
Show answer
def describe(name, title=None):
if title is not None:
return f"{title} {name}"
return name
The test if title: treats every falsy value the same as "omitted". An explicitly passed empty string, 0, or False would be dropped, so the function could not tell "no title given" from "the caller deliberately passed an empty title". Using is not None checks only for omission, so every value the caller passes is honored.