Issue4098
Created on 2008-10-10 09:23 by trott, last changed 2022-04-11 14:56 by admin. 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) * | 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 |
| 2022-04-11 14:56:40 | admin | set | github: 48348 |
| 2008-10-10 11:21:21 | amaury.forgeotdarc | set | status: open -> closed resolution: not a bug messages: + msg74628 nosy: + amaury.forgeotdarc |
| 2008-10-10 10:19:28 | trott | set | messages: + msg74627 |
| 2008-10-10 10:04:58 | eckhardt | set | nosy:
+ eckhardt messages: + msg74626 |
| 2008-10-10 09:23:44 | trott | create | |