Mutable Default Arguments (& the Principle of “Least Astonishment”)
- function
- argument
- mutable
It’s something that surprises newbies and experts:
def cabbage(leaves=[]):
leaves.append("tasty leaf")
return leaves
When most people read that function definition, they expect that cabbage()
would return ['tasty leaf']
. However, this is not (always) the case:
>>> cabbage()
['tasty leaf']
>>> cabbage()
['tasty leaf', 'tasty leaf']
>>> cabbage()
['tasty leaf', 'tasty leaf', 'tasty leaf']
Although initially unintuitive, this occurs because the function itself is an object and the default values are stored and evaluated at run time. When you append to the list, it appends to the default value attached to the function.
See the questions link to get a comprehensive discussion on the subject matter: