Good uses for mutable function argument default values?

default-arguments, python

Solution

Canonical answer is this page: http://effbot.org/zone/default-values.htm

It also mentions 3 "good" use cases for mutable default argument:

- binding local variable to current value of outer variable in a callback

- cache/memoization

- local rebinding of global names (for highly optimized code)

Problem

It is a common mistake in Python to set a mutable object as the default value of an argument in a function. Here's an example taken from this excellent write-up by David Goodger: ``` >>> def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list >>> print bad_append('one') ['one'] >>> print bad_append('two') ['one', 'two'] ``` The explanation why this happens is here. And now for my question: Is there a good use-case for this syntax? I mean, if everybody who encounters it makes the same mistake, debugs it, understands the issue and from thereon tries to avoid it, what use is there for such syntax?

Original source

Related problems