Sub topic 5
Giving parameters default values
This chapter assumes you can write a basic function with def, and that you know positional and keyword arguments. A default value lets a caller leave an argument out. The function then uses a value you chose in advance.
The basic syntax
Write = and a value after the parameter name in the def line.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada")) # Hello, Ada!
print(greet("Ada", "Welcome")) # Welcome, Ada!
print(greet("Ada", greeting="Hi")) # Hi, Ada!name has no default, so it is required. greeting has a default, so it is optional. Python fills in each missing argument from the parameter's default.
Defaults suit settings that are usually the same, such as a port number, a timeout, a separator or a flag. The common case becomes the shortest call. The rare case stays available.
Parameters with defaults must come last
In a plain parameter list, every parameter after the first default must also have a default. This is a syntax error:
try:
compile("def bad(a=1, b):\n pass", "<example>", "exec")
except SyntaxError as error:
print("SyntaxError:", error.msg) # the message wording varies by Python versionThe reason is how Python matches positional arguments. It assigns them left to right. If a had a default but b did not, the call bad(5) could not tell whether 5 was meant for a or for b.
The usual ordering is required parameters first, then optional ones, with the most commonly changed optional parameter first.
How a call fills in defaults
Python binds each parameter in this order:
- It assigns positional arguments from left to right.
- It assigns keyword arguments by name.
- For any parameter still unassigned, it uses the default.
- If an unassigned parameter has no default, it raises
TypeError.
Here is a function with several defaults, called in different ways:
def connect(host, port=5432, timeout=10.0):
return host, port, timeout
print(connect("db.local")) # ('db.local', 5432, 10.0)
print(connect("db.local", 6543)) # ('db.local', 6543, 10.0)
print(connect("db.local", timeout=3.0)) # ('db.local', 5432, 3.0)
print(connect(host="db.local", port=1)) # ('db.local', 1, 10.0)The third call changes timeout and skips port. You cannot skip a parameter positionally. To set timeout you must either pass port too or name timeout as a keyword. Parameters you are likely to override alone are better passed by keyword.
| Call | `host` | `port` | `timeout` |
|---|---|---|---|
| `connect("a")` | `"a"` | `5432` | `10.0` |
| `connect("a", 1)` | `"a"` | `1` | `10.0` |
| `connect("a", timeout=2.0)` | `"a"` | `5432` | `2.0` |
| `connect()` | `TypeError`, `host` is missing |
Defaults are evaluated once, at definition time
This is the most important fact about defaults. Python evaluates the default expression once, when it runs the def statement. It does not re-evaluate it on each call. The function object stores the result, and every call that omits the argument receives that same stored object.
You can inspect the stored values:
import inspect
def connect(host, port=5432, timeout=10.0):
return host, port, timeout
print(connect.__defaults__) # (5432, 10.0)
print(inspect.signature(connect)) # (host, port=5432, timeout=10.0)For immutable values such as numbers, strings, None and tuples of those, this makes no practical difference. For values that should differ per call, it causes bugs. A timestamp is a common example:
import time
def stamp(label, created=time.time()):
return label, created
first = stamp("a")
time.sleep(0.01)
second = stamp("b")
print(first[1] == second[1]) # True: both use the time the def rantime.time() ran once, when def executed. Both calls received that same number. The standard fix is the None pattern:
import time
def stamp(label, created=None):
if created is None:
created = time.time()
return label, created
first = stamp("a")
time.sleep(0.01)
second = stamp("b")
print(first[1] == second[1]) # FalseThe same timing rule explains a quieter surprise. A default that reads a variable captures that variable's value at definition time:
RATE = 0.2
def tax(price, rate=RATE):
return price * rate
RATE = 0.5
print(tax(100)) # 20.0, not 50.0Rebinding RATE later does not affect tax. If you want the function to see the current value, read the variable inside the body instead.
Defaults cannot refer to other parameters
A default expression runs when the function is defined, before any call exists. Other parameters do not exist yet, so this fails:
try:
exec("def rectangle(width, height=width):\n return width * height")
except NameError as error:
print("NameError:", error) # name 'width' is not definedUse None as a marker and compute the value in the body:
def rectangle(width, height=None):
if height is None:
height = width
return width * height
print(rectangle(4)) # 16
print(rectangle(4, 5)) # 20Choosing `None` or a sentinel
The None pattern has a weakness. It cannot tell "the caller passed nothing" from "the caller deliberately passed None". If None is itself a valid argument, create a unique marker object instead:
_MISSING = object()
def get(mapping, key, default=_MISSING):
if key in mapping:
return mapping[key]
if default is _MISSING:
raise KeyError(key)
return default
data = {"a": 1}
print(get(data, "a")) # 1
print(get(data, "b", None)) # None, the caller asked for None
try:
get(data, "b")
except KeyError as error:
print("KeyError:", error) # KeyError: 'b'Each object() is a distinct instance, so no caller can pass a value that is the marker by accident. Compare with is, not ==. Use this only when you need it. For most functions, None is simpler and clearer.
Common errors
- Required parameter after an optional one. The definition raises
SyntaxError. Reorder the parameters. - Calling without a required argument. Python raises
TypeError: connect() missing 1 required positional argument: 'host'. A default turns a required argument into an optional one. - Expecting a fresh value per call. Timestamps, random numbers and new containers need the
Nonepattern. - Passing the same argument twice.
connect("a", 1, port=2)raisesTypeError, because the second positional value already filledport. - Using
if not value:to detect a missing argument.0,""and[]are falsy but valid. Testvalue is None.
The last error looks like this:
def scale(x, factor=None):
if not factor: # wrong: treats 0 as "not provided"
factor = 1
return x * factor
def scale_fixed(x, factor=None):
if factor is None:
factor = 1
return x * factor
print(scale(10, 0)) # 10, surprising
print(scale_fixed(10, 0)) # 0Design guidance
- Pick a default that is safe and correct for most callers. A destructive option, such as overwriting a file, should default to off.
- Do not add a default just to shorten calls. A default that hides an important choice, such as which database to use, makes bugs harder to see.
- Changing a default value changes the behavior of every caller that omitted the argument. Treat it as a breaking change in a library.
- Document each default in the docstring when the value is not obvious from the signature.
Exercise
Predict the output of this code, then explain why. def label(text, prefix=">>"): return prefix + " " + text print(label("start")) print(label("end", "<<")) print(label(prefix="--", text="mid"))
Show answer
It prints ">> start", then "<< end", then "-- mid". The first call omits prefix, so the stored default ">>" is used. The second passes "<<" by position, which overrides the default. The third passes both arguments by keyword, so their order does not matter.
Exercise
This function should return the current time each time it is called without an argument, but every call returns the same value. Fix it. from datetime import datetime def log_line(message, when=datetime.now()): return f"{when.isoformat()} {message}"
Show answer
The default datetime.now() runs once, when def executes. Use None as the default and compute the time in the body: from datetime import datetime def log_line(message, when=None): if when is None: when = datetime.now() return f"{when.isoformat()} {message}"
Exercise
Why does def f(a, b=a): raise NameError, and what is the standard way to get that behavior?
Show answer
The default expression runs at definition time, when the parameter a has no value yet. Use b=None, then write "if b is None: b = a" inside the function body.