Default Mutable Args in Python Functions: A Hidden Pitfall

Reusing code with default mutable arguments? You're setting yourself up for a nasty surprise. It's 2026, and this one still catches people. We had a 'convenience' function for logging events, complete with a default list of tags. Everybody loved it; made their calls look clean. Then we started seeing production logs with completely unrelated tags. Debugging this felt like chasing ghosts through a maze of microservices and shared libraries. Turns out, that shared `tags=[]` default was getting mutated. Every time someone called the function without providing their own tags, they were just appending to the *same list instance* from previous calls. Request A's tags showed up in Request B's logs. ❌ **The Trap:** `def log_event(message, tags=[]):` ✅ **The Reality:** `def log_event(message, tags=None):` then `tags = tags if tags is not None else []` Hidden state in seemingly stateless functions will burn you every time. Anyone else debugged this exact mess more times than they care to admit? #ProductionLogs #Python #FunctionsAndReusability #SoftwareEngineering

To view or add a comment, sign in

Explore content categories