Mutable objects as default arguments of functions Medium

Default values in Python are created exactly once, when the function is defined. If that object is changed, subsequent calls to the function will refer to the changed object, leading to confusion. We recommend that you set the default value to None, then check inside the function if the parameter is None before creating the desired mutable object.

Detector ID
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1# Noncompliant: default arguments have mutable objects.
2def with_complex_default_value_noncompliant(self, index=1, mydict={},
3                                            mylist=[]):
4    mydict[index] = mylist[index]
5    return mydict

Compliant example

1# Compliant: default arguments are assigned to None or unmutable objects.
2def with_unmutable_objects_compliant(mydict=None, number=1, str="hi",
3                                     mytuple=(1, 2)):
4    print(mydict, number, str, mytuple)