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”Description:
Section titled “Description:”Replaces use of default mutable arguments in a function
Before:
Section titled “Before:”def func(hats: list = []): change(hats)After:
Section titled “After:”def func(hats: list = None): if hats is None: hats = [] change(hats)Explanation:
Section titled “Explanation:”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.