Skip to content

Default Mutable Arguments

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: default-mutable-arg

Section titled “Sourcery refactoring id: default-mutable-arg”

Replaces use of default mutable arguments in a function

def func(hats: list = []):
change(hats)
def func(hats: list = None):
if hats is None:
hats = []
change(hats)

A common gotcha in Python involves default argument values which are mutable. These are evaluated only once at function definition time, so only one list, set or dictionary instance will be created. This means that if this list is mutated in one call to a function, those changes will show up in subsequent calls of that function. This is usually unintended behaviour, though it can be useful in limited circumstances for writing caches.