What is a function parameter =[] for?

Ned Batchelder ned at nedbatchelder.com
Thu Nov 19 19:27:57 EST 2015


On Thursday, November 19, 2015 at 7:11:52 PM UTC-5, BartC wrote:
> On 19/11/2015 22:55, Michael Torrie wrote:
> > On 11/19/2015 02:21 PM, BartC wrote:
> >> (Python returns 42; so that means my languages are more dynamic than
> >> Python? That's hard to believe!)
> >
> > It tells me your language does late binding for default arguments, which
> > does mean the default argument can dynamically change at call time,
> > which would surprise me if I didn't know about it.  Either form of
> > binding is acceptable, and I don't think it makes a language more or
> > less dynamic.
> 
> You get the expression that is specified, which can give different 
> values at different times unless it involves only constants.
> 
> It can't be exactly the same as writing an identical expression in place 
> of the missing argument, as apparently different scopes come into play 
> if names are involved.
> 
> However I mainly use them for constant values. And [] is a constant 
> value in my opinion.
> 
> -- 
> Bartc

You are not alone in being surprised by how mutable default values work.
It is a topic that comes up in every "What's Bad About Python" discussion,
and is a common question from new users of the language.

I can understand how you would view [] as a constant value.  It's true that
it is an expression that produces a consistent value each time it is
evaluated.  But that value is a list, and lists are mutable.  The examples
here all use the .append() method on that value, which changes it.

Different languages work differently.  In Python, a default value expression
for a function argument is evaluated only once, when the function is defined.
That value (in this case, the actual list) is stored with the function. The
expression is not stored, the value of the expression is. That value (the
actual list) is supplied as the value of the argument if no other value is
supplied.  If you modify that value in the function, the value is modified,
and used again at the next function call.

Again, we understand why you are surprised by this, many people are. You'll
have to accept it, it's just the way Python works.  There have been many
discussions about alternatives, and they are considered to be either too
complicated, or have other undesirable behavior, or both.

--Ned.



More information about the Python-list mailing list