Default mutable parameters in functions

Ian Kelly ian.g.kelly at gmail.com
Thu Apr 3 17:32:42 EDT 2014


On Thu, Apr 3, 2014 at 12:49 PM,  <fbicknel at gmail.com> wrote:
> Now call it with a value:
> foo([ 3 ])
>
> as you might expect:
> It's a parrot, not a cheese: [3]
>
> But now go back to no parameter in the call:
> foo()
> foo()
> foo()
>
> It's a parrot, not a cheese: [46]
> It's a parrot, not a cheese: [47]
> It's a parrot, not a cheese: [48]
>
> it picks up where it left off.
>
> I was rather expecting it to start with 4!

You haven't replaced the default value; you've only substituted a
different value for that call.  In this function:

def foo(x=3):
    print(x)

You wouldn't expect a call of foo(27) to change the default value to
27, would you?



More information about the Python-list mailing list