You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee=Noneclosed_at=<Date2008-10-10.11:21:21.675>created_at=<Date2008-10-10.09:23:43.974>labels= ['type-bug', 'invalid', 'build']
title='surprised by default list parameter'updated_at=<Date2008-10-10.11:21:21.634>user='https://bugs.python.org/trott'
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?
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.
Activity
trott commentedon Oct 10, 2008
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?
eckhardt commentedon Oct 10, 2008
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__".
trott commentedon Oct 10, 2008
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.
amauryfa commentedon Oct 10, 2008
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.