Explain the mutable default argument bug and how to fix it.
IntermediateConceptLanguage essentials & functions
Answer
Default values are evaluated once, when the function is defined, not on each call. A mutable default is therefore shared across calls.
def add_tag(tag, tags=[]): # bug
tags.append(tag)
return tags
add_tag("a") # ['a']
add_tag("b") # ['a', 'b'] surprise
def add_tag(tag, tags=None): # fix
tags = [] if tags is None else tags
tags.append(tag)
return tags
ruff flags this as B006, which is one reason we run it in CI.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?BeginnerWhen do you choose a list, tuple, set or dict?Beginner