A developer is writing a Python function that accepts a mutable default argument, such as `def add_item(item, items=[])`. A code reviewer flags this as a potential bug. Which statement best explains the issue and the recommended fix according to best practices?
In Python, default arguments are evaluated only once at function definition time. Using a mutable default like `[]` means the same list object is reused across all calls, leading to unintended persistence of data. The recommended fix is to use `None` as the default and then check `if items is None: items = []` inside the function. This ensures a fresh list is created for each call, avoiding shared state bugs.
Why this answer
Mutable default arguments are evaluated once at definition time, causing shared state across calls. The correct practice is to use `None` as a default and create a new mutable object inside the function. This avoids bugs where data unexpectedly persists.
Other options either misdiagnose the problem or propose ineffective solutions.
Exam trap
The trap here is thinking that default arguments are re-evaluated on each call, when they are actually evaluated once at function definition.