Bizarre behavior with mutable default arguments

bukzor workitharder at gmail.com
Sat Dec 29 14:14:30 EST 2007


Here's the answer to the question:
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects

It looks like Guido disagrees with me, so the discussion is closed.




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.

Just my parting two cents,
--Buck



More information about the Python-list mailing list