Skip to main content

Python Default Arguments

Satellite · Functions

Default Arguments

Defaults make APIs ergonomic—learn how they evaluate and how to avoid the infamous mutable-default bug.

Syntax

def connect(host="localhost", port=5432):
...

Defaults evaluate once at function definition time, not on every call.

Mutable defaults warning

def append_item(item, items=[]):
items.append(item)
return items

Each call shares the same list. Fix it by using None sentinel:

def append_item(item, items=None):
if items is None:
items = []
items.append(item)
return items

Ordering rules

Positional-only → positional/keyword → varargs (*args) → keyword-only → **kwargs. Defaults must follow required parameters.

Next up in your learning path