Interview Prep/Python for DevOps/Language essentials & functions

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.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions