Back
+30 XP
Concept

Spot the Mutable Default Argument Trap

Python default arguments are evaluated only once when the function definition is executed, not at each call. Passing mutable defaults like lists or dicts creates a shared object across all invocations, leaking user data between calls. Use None as sentinel.

python
# Broken:
def add_item(item, items=[]):
    items.append(item)
    return items

# Fixed:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

# Spot the Mutable Default Argument Trap The mutable default argument is Pythonโ€™s most infamous production bug. If an engineer writes `def create_user_session(user_id, permissions=[])`, that list is allocated **once** when the module is imported. Every single user who logs in without explicit permissions gets appended to that exact same list in memory. ๐Ÿ’€๐Ÿ”“ When User 1 gets granted `["admin"]`, User 2 logs in and accidentally inherits `["admin"]` too. The idiomatic fix is to set the default to `None` and instantiate a fresh mutable container inside the function body. ```python # The Trap: def register(user, tags=[]): tags.append(user) return tags # The Fix: def register_safe(user, tags=None): if tags is None: tags = [] tags.append(user) return tags ``` ## Pop Quiz Why does `def append_record(record, log=[])` share the same log list across distinct invocations? - [ ] The default list object is created once at compile/definition time and stored on the function object's `__defaults__`. - [ ] Python reallocates mutable arguments to global process scope whenever they exceed 0 elements. - [ ] The interpreter merges function parameters with identical type annotations to save memory. - [ ] Because list references are cached by the operating system CPU instruction cache. ## Real-World Challenge Write `safe_session_tracker(user_id: str, tags: list = None) -> list`. If `tags` is not provided, return a fresh isolated list containing only this user's tags. Ensure that modifying the returned list in one call does not contaminate subsequent calls. <details> <summary>Solution</summary> ```python def safe_session_tracker(user_id: str, tags: list = None) -> list: if tags is None: tags = [] else: tags = list(tags) # Defensive shallow copy tags.append(f"user:{user_id}") return tags # Verification user1_tags = safe_session_tracker("alice") user1_tags.append("role:admin") user2_tags = safe_session_tracker("bob") assert user1_tags == ["user:alice", "role:admin"] assert user2_tags == ["user:bob"] assert "role:admin" not in user2_tags assert user1_tags is not user2_tags ``` </details>