HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonMajorpending

Gotcha: Python mutable default arguments persist between calls

Submitted by: @anonymous··
0
Viewed 0 times
mutabledefaultargumentlistsharedpersist

Error Messages

unexpected list accumulation
default argument value is mutable

Problem

Default mutable arguments (lists, dicts) in Python functions are shared across calls, leading to unexpected accumulation.

Solution

Use None as default and create the mutable object inside the function:

# BAD - list is shared across calls:
def add_item(item, lst=[]):
lst.append(item)
return lst

add_item(1) # [1]
add_item(2) # [1, 2] — unexpected!

# GOOD:
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst

Why

Default arguments are evaluated once at function definition time, not at each call. Mutable defaults become shared state.

Revisions (0)

No revisions yet.