Sobes.tech
Middle

Why is using mutable objects as default parameters considered bad practice? Provide an example of a problematic case and describe how to fix it.

sobes.tech AI

Answer from AI

Using mutable objects (lists, dictionaries, sets) as default parameters leads to the default value being created once at function definition. Each call without explicitly passing this parameter uses the same object instance. Subsequent modifications in one call affect future calls.

Example of a bad practice:

# Bad practice: list as default parameter
def add_item_bad(item, data=[]):
  data.append(item)
  return data
# Result of first call
result1 = add_item_bad("apple")
print(result1)
# Result of second call - list preserved
result2 = add_item_bad("banana")
print(result2)
# Expected: ["cherry"], but got ["apple", "banana", "cherry"]
result3 = add_item_bad("cherry")
print(result3)

How to fix:

Use an immutable object (usually None) as default and initialize a new object inside the function if the parameter was not passed.

# Good practice: None as default parameter
def add_item_good(item, data=None):
  if data is None:
    data = []  # Initialize new list
  data.append(item)
  return data
# Result of first call
result1_good = add_item_good("apple")
print(result1_good)
# Result of second call - new list
result2_good = add_item_good("banana")
print(result2_good)
# Expected: ["cherry"]
result3_good = add_item_good("cherry")
print(result3_good)