What is a function parameter =[] for?

Chris Angelico rosuav at gmail.com
Fri Nov 20 08:04:03 EST 2015


On Fri, Nov 20, 2015 at 11:39 PM, BartC <bc at freeuk.com> wrote:
> * The refusal to acknowledge that the def fn(a=[]) syntax is misleading.
> (What value will a have when you call fn()? The true answer is that you
> can't tell.)

It isn't misleading. The default value for the argument is set when
the function is defined, and it is set to the *object* that results
from evaluating the *expression* given. After that, the *object* is
the one you will always get (barring shenanigans) if the argument is
omitted. If the value of that object changes, it changes!

You keep expecting the *value* to be consistent. But what you actually
get is that the *object* is consistent. It's virtually impossible to
guarantee the former, in the face of mutable objects.

> * The persistent nonsense that somehow [] is mutable (what happens is that
> [] is assigned to a variable, and /that/ is mutable) (And I will probably
> get some flak now because 'assign' and 'variable' are meaningless in
> Python!)

What happens is that [] evaluates to an object, and *that object* is
mutable. Python does not store the syntactic element "[]" (empty
list-display), but instead stores (a reference to) the object. It's
exactly the same as:

def fn(a=list()):
    ...

def generate_list():
    return []
def fn(a=generate_list()):
    ...

initial_list = []
def fn(a=initial_list):
    ...

import sys
def fn(a=[x*3+424 for x in range(not sys)]):
    """how ridiculous would you like to go?"""

Every one of these constructs exactly one new list, *when it is
evaluated*, which is at function definition time.

ChrisA



More information about the Python-list mailing list