classification
Title: surprised by default list parameter
Type: behavior Stage:
Components: Build Versions: Python 2.5.3, Python 2.6, Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: amaury.forgeotdarc, eckhardt, trott
Priority: normal Keywords:

Created on 2008-10-10 09:23 by trott, last changed 2008-10-10 11:21 by amaury.forgeotdarc. This issue is now closed.

Files
File name Uploaded Description Edit
p6.py trott, 2008-10-10 09:23 just run the example file "p6.py"
Messages (4)
msg74624 - (view) Author: Torsten Rottmann (trott) Date: 2008-10-10 09:23
The attached file produced the following result:

______________________
trott$ python2.5 p6.py
[]
[1234]
______________________

I expected both times the empty list since the print
statement prints just a defaulted parameter ("e") which
was defaulted to an empty list literal ("[]") and never set
by supplying an actual class parameter.

The object property "entries" appears to be shared by
both instances. Why?
msg74626 - (view) Author: Ulrich Eckhardt (eckhardt) Date: 2008-10-10 10:04
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

The same recently cropped up on the users mailinglist under the topic
"default value in __init__".
msg74627 - (view) Author: Torsten Rottmann (trott) Date: 2008-10-10 10:19
OK. I've read the Python Reference Manual 7.6 "Function Definition".
It "explains" why this happens.

BUT: Why can`t the compiler make a copy of the default object, if
it's mutable (e.g. a list)? This can't be that difficult.
msg74628 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) * (Python committer) Date: 2008-10-10 11:21
Yes, the default value expression could be evaluated each time the
function is called without the parameter. But it would be another language.
Default values are computed once, and this is a Python feature.

It can be useful, for example to cache computations, or to achieve
"early binding" in nested functions, as explained in the suggested FAQ.
History
Date User Action Args
2008-10-10 11:21:21amaury.forgeotdarcsetstatus: open -> closed
resolution: not a bug
messages: + msg74628
nosy: + amaury.forgeotdarc
2008-10-10 10:19:28trottsetmessages: + msg74627
2008-10-10 10:04:58eckhardtsetnosy: + eckhardt
messages: + msg74626
2008-10-10 09:23:44trottcreate