Bizarre behavior with mutable default arguments

George Sakkis george.sakkis at gmail.com
Sun Dec 30 11:26:37 EST 2007


On Dec 29, 9:14 pm, bukzor <workithar... at gmail.com> wrote:
> Here's the answer to the question:http://www.python.org/doc/faq/general/#why-are-default-values-shared-...
>
> It looks like Guido disagrees with me, so the discussion is closed.

Note that the FAQ mainly explains *what* happens, not *why* was this
decision taken. Although it shows an example where "this feature can
be useful", it's neither the only way to do it nor is memoization as
common as wanting fresh default arguments on every call.

> For the record, I still think the following would be an improvement to
> py3k:
>
> In python25:
> def f(a=None):
>     if a is None: a = []
>     ...
>
> In py3k becomes:
> def f(a=[])
>     ...
>
> In python25 (this function from the FAQ linked above):
> def f(a, _cache={}):
>     # Callers will never provide a third parameter for this function.
> (then why is it an argument?)
>     ...
>
> In py3k becomes:
> _cache = {}
> def f(a):
>     global _cache
>     ...
>
> This follows the "explicit is better" and "one best way" principles of
> Python, and greatly improves the intuitiveness. Also since the first
> example is much more common, it reduces the overall verbosity of the
> language.

I'm with you on this one; IMHO it's one of the relatively few language
design missteps of Python, favoring the rare case as the default
instead of the common one. Unfortunately, many Pythoneers become so
immersed with the language and whatever the current status quo is that
they rarely question the rationale of the few counter-intuitive design
choices.

George



More information about the Python-list mailing list