Default Value

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jun 20 20:17:12 EDT 2013


On Thu, 20 Jun 2013 09:19:48 -0400, Roy Smith wrote:

> In article
> <447dd1c6-1bb2-4276-a109-78d7a067b442 at d8g2000pbe.googlegroups.com>,
>  rusi <rustompmody at gmail.com> wrote:
> 
>> > > def f(a, L=[]):
>> > >     L.append(a)
>> > >     return L
> 
>> Every language has gotchas. This is one of python's.
> 
> One of our pre-interview screening questions for Python programmers at
> Songza is about this.  I haven't been keeping careful statistics, but
> I'd guess only about 50% of the candidates get this right.


What exactly is the question? Because it's not always a bug to use a 
mutable default, there are good uses for it:


def func(arg, cache={}):
    ...


Now you can pass your own cache as an argument, otherwise the function 
will use the default. The default cache is mutable, and so will remember 
values from one invocation to the next.


-- 
Steven



More information about the Python-list mailing list