Mutable Default Arguments: Python's Favorite Gotcha
Every Python developer eventually writes a function like this, watches it misbehave in a way that makes no sense, and joins the club: def add_item(item, basket=[]): basket.append(item) return basket print(add_item("apple")) # ['apple'] print(add_item("banana")) # ['apple', 'banana'] <- wait, what? You expected ['banana']. Instead the second call remembers the first one. Nothing about the code looks wrong at a glance, which is exactly why this bites so many people, including plenty who’ve been writing Python for years. I’ve shipped this bug myself, in a function that collected validation errors, and didn’t notice until a support ticket showed one request’s errors leaking into an unrelated request. ...