Default mutable parameters in functions

fbicknel at gmail.com fbicknel at gmail.com
Thu Apr 3 14:49:56 EDT 2014


Hi all,

So I was reading about default values for functions and spied this:

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. 

That's ok - guess I can get used to that.  So I did some experimenting and sure enough, immutables sort of behave "normally" in that they get the default value every time you call the function and don't specify the value for the parameter.

But mutables behave very strangely (imho).  Take this example:

def foo(bar=[ 42 ]):
    print "It's a parrot, not a cheese: {value}".format(value=bar)
    bar[0] += 1

Now call it like this:
foo()
foo()
foo()
foo()

and based on the "Important warning" above, you get something expected:
It's a parrot, not a cheese: [42]
It's a parrot, not a cheese: [43]
It's a parrot, not a cheese: [44]
It's a parrot, not a cheese: [45]

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!

I put this into pythontutor.com's code visualization tool (http://goo.gl/XOmMjR) and it makes more sense what's going on.

I thought this was interesting; thought I would share.



More information about the Python-list mailing list