Python

Lesson 03

Mutable default arguments

Avoid shared mutable defaults by creating fresh lists, dicts, or sets inside the function.

Good Code

tags.py
def add_review_tag(tag, tags=None):
    # Create a fresh list only when the caller omitted tags.
    if tags is None:
        tags = []

    tags.append(tag)
    return tags

Bad Code

tags.py
def add_review_tag(tag, tags=[]):
    # This default list is reused across every call.
    tags.append(tag)
    return tags

Review Notes

What to review

Good Code

The good version creates a new list only when the caller did not pass one.

Bad Code

The bad version shares the same default list across calls. Tags from one request or test can appear in the next call.

Takeaways

  • Default arguments are evaluated once, so mutable defaults can leak state between calls.