Default Value

Jussi Piitulainen jpiitula at ling.helsinki.fi
Wed Jun 19 15:35:38 EDT 2013


Ahmed Abdulshafy <abdulshafy at gmail.com> writes:

> I'm reading the Python.org tutorial right now, and I found this part
> rather strange and incomprehensible to me
> 
> 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
>
> def f(a, L=[]):
>     L.append(a)
>     return L
> 
> print(f(1))
> print(f(2))
> print(f(3))
> 
> This will print
> [1]
> [1, 2]
> [1, 2, 3]
> 
> How the list is retained between successive calls? And why?

Functions are objects with their own attributes. The default values
are computed and stored when the def statement is executed.

dir(f) will show the attributes of f. Their names start and end with a
double underscore, __. This indicates that they are not usually used
explicitly. Still, f.__defaults__ seems to be where the default value
is kept between (and during) calls.



More information about the Python-list mailing list