Default argument values
A parameter with a default value is optional: if you leave it out of the call, the function uses that value.
Used in 61 lessons of the course, from 00.02.
In a def, you write name=value to give a parameter a default. If the caller leaves it out, Python uses that value. If the caller passes one, theirs wins.
In the course line, def tool_version(tool: str, timeout_s: float = 15.0) -> str:, tool is required and timeout_s is optional. With a type hint, you write it with spaces: timeout_s: float = 15.0.
Parameters with defaults go after the required ones. Python rejects the opposite order.
The default is evaluated once, when the function is defined. So prefer values that don't change (numbers, strings, None) and avoid empty lists or dicts.
def greet(name, punct="!"):
return name + punct
Reach for it when: a parameter almost always has the same value and you want callers to be able to skip it, like a timeout.
Examples
Common mistake
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))Why: The default list is created once and shared by every call, so it keeps accumulating items.
How to write it: Use items=None and inside write if items is None: items = [].
Common mistake
def f(a=1, b):
return a + bWhy: A parameter without a default cannot come after one that has a default.
How to write it: Put required ones first: def f(b, a=1):.
