Assign a fallback value directly in the function signature (def greet(name: str, greeting: str = "Hello") -> str:) to make a parameter optional with a default value, placing all default parameters after required positional parameters and always using None (never a mutable [] or {}) when a parameter needs a fresh default container per call.
Basic Example
# 1. Recommended: Required arguments first, followed by optional arguments with defaults
def format_price(amount: float, currency: str = "USD", include_symbol: bool = True) -> str:
prefix = "$" if (include_symbol and currency == "USD") else f"{currency} "
return f"{prefix}{amount:,.2f}"
print(format_price(49.9)) # Output: $49.90
print(format_price(49.9, "EUR", False)) # Output: EUR 49.90
print(format_price(49.9, include_symbol=False)) # Output: USD 49.90
# 2. Recommended pattern for mutable default arguments (lists, dicts, sets):
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("python")) # Output: ['python']
print(add_tag("pandas")) # Output: ['pandas'] (fresh list every call!)
Key Details & Edge Cases
- Never use mutable objects (
[],{},set()) as default values:- Python evaluates default parameter expressions once at function definition time (
def), not on each function call, storing them infunc.__defaults__. Definingdef add_item(x, items=[]):causes every call withoutitemsto mutate and share the exact same list object across calls. Always default toNone(items: list | None = None) and instantiate a fresh container inside the function body.
- Python evaluates default parameter expressions once at function definition time (
- Parameter ordering rules (
SyntaxErrorif violated):- Every parameter with a default value (
b=2) must appear after all non-default parameters (def fn(a, b=2):, neverdef fn(a=1, b):). - When mixing positional-only (
/), standard,*args, keyword-only (*), and**kwargs, follow Python’s strict signature order:def fn(pos_only, /, standard, standard_opt=1, *args, kw_only, kw_only_opt=2, **kwargs):
- Every parameter with a default value (
- Enforcing keyword-only optional flags with
*(def connect(host, *, timeout=5.0, retry=True):):- Placing a bare
*before optional boolean or numeric flags prevents callers from passing confusing positional booleans likeconnect("db.local", 5.0, True), requiring explicit keyword arguments (connect("db.local", timeout=5.0)) while keeping the parameters optional.
- Placing a bare
- Distinguishing “argument omitted” from “
Noneexplicitly passed” (sentinel object pattern):- When
Noneitself is a valid argument value (for example, updating a database field toNULLvs. leaving it unchanged), create a private module-level sentinel object instead of defaulting toNone:_UNSET = object() def update_user(user_id: int, bio: str | None | object = _UNSET) -> None: if bio is not _UNSET: print(f"Updating bio to: {bio!r}")
- When
- Default expressions capture current values at
deftime:- Writing
def log(msg, ts=datetime.now()):freezeststo the exact timestamp when the module was imported. Compute dynamic defaults (datetime.now(), UUIDs, random numbers) inside the function body whenparam is None.
- Writing
Comparison of Optional Parameter Patterns in Python
| Pattern | Can Caller Pass Positionally? | Can Caller Pass by Keyword? | Safe for Lists / Dicts / Dynamic Values? | Best Used When |
|---|---|---|---|---|
def (a, ="default"): (Recommended) |
Yes | Yes | Only for immutable constants (str, int, bool, None) |
Standard optional parameters with static, immutable defaults. |
def fn(a, items: list | None = None): (Recommended for mutables) |
Yes | Yes | Yes (allocate items = [] inside body) |
Optional collections (list, dict, set) or runtime-computed defaults (datetime.now()). |
def fn(a, *, flag=False, retries=3): |
No (keyword-only after *) |
Yes | With immutable defaults or None guard |
Public APIs with multiple optional flags where positional calls hurt readability. |
def (a, =_UNSET): |
Yes | Yes | Yes | Patch/update functions that must distinguish omitted arguments from an explicit None. |
You must log in or register to comment.
