“Least Astonishment” and the Mutable Default Argument
问题 Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue: def foo(a=[]): a.append(5) return a Python novices would expect this function to always return a list with only one element: [5] . The result is instead very different, and very astonishing (for a novice): >>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] >>> foo() [5, 5, 5, 5] >>> foo() A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw"