Beginner LevelPython
Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?
❓ Interview Prompt: Explain why default arguments are evaluated only once at function definition time, causing shared state bugs across calls.
In Python, default parameter expressions are evaluated only once, when the 'def' statement is executed at module import time — NOT every time the function is called! This means the exact same list object in memory is shared across every single invocation of the function that relies on the default value.
The Correct Solution:
Always use 'None' as the default parameter value for mutable types, and initialize a fresh new list or dictionary inside the function body using an 'if item is None:' check.
Code Implementation Example
python
# ❌ BUG: Mutable default argument shared across all function calls!
def add_item_bad(item, target_list=[]):
target_list.append(item)
return target_list
print(add_item_bad('Apple')) # ['Apple']
print(add_item_bad('Banana')) # ['Apple', 'Banana'] - Unexpected!
# ✅ ENTERPRISE SOLUTION: Use None as default
def add_item_good(item, target_list=None):
if target_list is None:
target_list = [] # Fresh list per invocation!
target_list.append(item)
return target_list💡The mutable default argument trap and the correct None initialization pattern.
🎯 Interview Key Takeaway
Never use [] or {} as default parameter values. Use None as the default and assign a new list or dict inside the function body.
#Functions#Default Arguments#Bugs#Beginner
Back to all Python Questions→