Please explain this strange Python behaviour

John Posner jjposner at snet.net
Thu Apr 30 15:59:10 CEST 2009


Duncan Booth wrote:
> Tim Chase <python.list at tim.thechases.com> wrote:
>   
>> There _are_ cases where it's a useful behavior, but they're rare, 
>> so I don't advocate getting rid of it.  But it is enough of a 
>> beginner gotcha that it really should be in the Python FAQ at 
>> www.python.org/doc/faq/general/
> That's an excellent idea!
>
> So excellent in fact that it already is:
> http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
>   

A couple of minor quibbles:

* This writeup, and the virtually identical one at effbot.org that Diez 
referenced, address the *what* of default arguments, but don't really 
address the *why*, beyond the statement that "Default values are created 
exactly once, when the function is defined (by executing the *def* 
<http://effbot.org/pyref/def.htm> statement)". After all, if parameter 
values are supplied to a function when it is called, a newly minted set 
of default values could be supplied at that time, also. So *why* was 
Python designed one way instead of the other?

* I'd change this sentence near the beginning of the writeup, because 
it's just ambiguous enough in the exact area that the writeup is 
attempting to clarify:

from:

      The first time you call this function, D contains a single item.
      The second time, D contains two items ...

to:

      After the first call to this function, D contains a single item.
      After the second call, D contains two items ...

-John




More information about the Python-list mailing list