Default Mutable Arguments¶
Sourcery refactoring id: default-mutable-arg
¶
Description:¶
Replaces use of default mutable arguments in a function
Before:¶
def func(hats: list = []):
change(hats)
After:¶
def func(hats: list = None):
if hats is None:
hats = []
change(hats)
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.