This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: surprised by default list parameter
Type: behavior Stage:
Components: Build Versions: Python 2.5.3, Python 2.6, Python 2.5
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 2022-04-11 14:56 by admin. This issue is now closed.

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

trott$ python2.5

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

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.
Date User Action Args
2022-04-11 14:56:40adminsetgithub: 48348
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