"Least Astonishment" and the Mutable Default Argument
@lebyy▲ 0 net votes
Problem: def foo(a=[]): a.append(5) return a Python novices expect this function called with no parameter to always return a list with only one element: [5] . The result is different and astonishing: >>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] >>> foo() [5, 5,… Fix (from the top answer): Actually, this is not a design flaw, and it is not because of internals or performance. It comes simply from the fact that functions in Python are first-class objects , and not only a piece of code. As soon as you think of it this way, then it completely makes sense: a function is an object being evaluated on its…