Once-only evaluation of default parameter values function definitions

Brian Gough bjg at network-theory.co.uk
Tue Apr 13 07:04:44 EDT 2004


Fred Ma <fma at doe.carleton.ca> writes:

> I'm looking at Python for the 1st time today, motivated by its clarity
> of syntax.  I've looked at the tutoarial at
> http://www.python.org/doc/current/tut/tut.html, particularly at the
> section about default arguments.  I've got some C++/STL under my belt,
> so I'm familiar with passing/returning by reference, by value, and by
> pointers.....
>
> The problem with this picture is that Example#2 should fail for the
> same reasons as Example#1.  That is, L will not get the value of None
> on the 2nd call to f() without a value specified for L.  Hence, L will
> not be reset to [].

Your explanation is correct up to this point, but the behavior of the
two cases is different.  When L=[] is in the body of the fuction, it
is like a local "automatic" variable in C/C++ and discarded at the
end of the function.  When L=[] is used in the parameter list, it is
like a "static" variable in C/C++ and persists on future calls.

HTH

-- 
Brian Gough

Network Theory Ltd,
Publishing Free Software Manuals --- http://www.network-theory.co.uk/



More information about the Python-list mailing list