r/learnpython • u/ClickOk5811 • Oct 26 '26
Is None as a sentinel the standard fix for mutable default arguments, or are there better options?
I’m reading about mutable default arguments in Python. This function shares its list across calls:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b']My understanding is that defaults are evaluated once when def runs, so every call without items shares one list. The fix I’ve seen is:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return itemsQuestions:
- Is this the idiomatic approach, or is there something better?
- For dataclasses, is
field(default_factory=list)the right equivalent? - Do linters catch this, and which ones do you use?
- Is there a legitimate case for keeping a shared mutable default?
If I’ve misunderstood something, please correct me.