π¦ ClawHub
Python Mutable Default Args
by @mvogt99
A Python function uses a mutable object (list, dict, set) as a default argument, sharing state across calls in a way that produces silent bugs.
TERMINAL
clawhub install python-mutable-default-argsπ About This Skill
name: python-mutable-default-args description: A Python function uses a mutable object (list, dict, set) as a default argument, sharing state across calls in a way that produces silent bugs. emoji: π metadata: clawdis: os: [macos, linux, windows] language: python
python-mutable-default-args
Python evaluates default argument values once at function definition time, not on each call. If the default is a mutable object β a list, dict, or set β that object is shared across every call that uses the default. Mutating it inside the function modifies the default for all future calls. The bug is invisible until the second or later call and produces state-dependent failures that are hard to trace.
Symptoms
def add_item(item, items=[]): # β shared list
items.append(item)
return itemsadd_item("a") # ["a"]
add_item("b") # ["a", "b"] β unexpected; second caller sees first caller's data
What to do
None as the default and initialize the mutable inside the function body:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
items gets a fresh list.dict, set, and any other mutable type. The rule is: never use a mutable as a default argument.=[], ={}, =set() as a heuristic for this pattern.W0102, ruff rule B006) will flag this automatically β enable them if the codebase doesn't already.