๐ Python Mistakes Everyone Makes ❌
Day 43: Mutating Arguments Passed to Functions
This is one of those bugs that looks harmless, works fine in small tests —
and then causes mysterious behavior later in production.
❌ The Mistake
Modifying a mutable argument (like a list or dictionary) inside a function.
def add_item(items):items.append("apple") # ❌ mutates the caller's listmy_list = []add_item(my_list)
print(my_list) # ['apple']
At first glance, this seems fine.
But the function silently changes data it does not own.
❌ Why This Is Dangerous
❌ Side effects are hidden
❌ Makes debugging extremely hard
❌ Breaks assumptions about data immutability
❌ Functions stop being predictable
❌ Reusing the function becomes risky
The caller didn’t explicitly ask for the list to be modified — but it happened anyway.
⚠️ A More Subtle Example
def process(data):
data["count"] += 1 # ❌ mutates shared state
If data is shared across multiple parts of your app, this change ripples everywhere.
✅ The Correct Way: Avoid Mutation
✔️ Option 1: Work on a copy
def add_item(items):new_items = items.copy()new_items.append("apple")return new_itemsmy_list = []
my_list = add_item(my_list)
Now the function is pure and predictable.
✔️ Option 2: Be explicit about mutation
If mutation is intentional, make it obvious:
def add_item_in_place(items):
items.append("apple")Clear naming prevents surprises.
๐ง Why This Matters
Functions should:
Do one thing
Have clear contracts
Avoid unexpected side effects
Predictable code is maintainable code.
๐ง Simple Rule to Remember
๐ง If a function mutates its arguments, make it explicit or avoid it.
When in doubt:
Return new data instead of modifying input.
๐ Final Takeaway
Hidden mutation is one of Python’s most common foot-guns.
Write functions that:
Are safe to reuse
Don’t surprise callers
Make data flow obvious
Your future self (and teammates) will thank you.


0 Comments:
Post a Comment