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.

classification
Title: Initialization strange behavior
Type: Stage:
Components: Interpreter Core Versions: Python 3.3
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mark.dickinson, wdanilo
Priority: normal Keywords:

Created on 2012-10-31 14:18 by wdanilo, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
test.py wdanilo, 2012-10-31 14:18 Issue example
Messages (6)
msg174280 - (view) Author: Wojciech Danilo (wdanilo) Date: 2012-10-31 14:18
Hi!
I'm using Python for several years and now I'm writing in Python 3 for the first time. I think I found a strange bug in it. Lets concider the code in the attachement.
In the 33 line there is construction of new instance of class Result:
print('!!!',Result().value)
what is strange, the class is defined as:
class Result:
    def __init__(self, value=[], start=0, end=0):
        self.value = value
        ...

and what I get as a result is:
"!!! ['a', 'b']"

Where the array was somehow magically stored from previous initialization (take a look at the code for full listing).
msg174283 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-10-31 14:23
This is a feature, not a bug. :-)  See 

http://docs.python.org/2/faq/design.html#why-are-default-values-shared-between-objects

for more information.
msg174284 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-10-31 14:25
Actually, since you're using Python 3, I should have linked to the Python 3 documentation.  Try this one:

http://docs.python.org/3/faq/design.html#why-are-default-values-shared-between-objects
msg174324 - (view) Author: Wojciech Danilo (wdanilo) Date: 2012-10-31 16:43
Wow, I was using Python so long and I didn't know about it. Is there any paper discussing why this feature is better than storing "cache" as global variable / as class "private" parameter?
msg174327 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-10-31 16:56
There's plenty of discussion of this feature of Python around the web, but this isn't the place to rehash it. :-)  Google for "python mutable default argument".
msg174328 - (view) Author: Wojciech Danilo (wdanilo) Date: 2012-10-31 16:57
Thank you!
History
Date User Action Args
2022-04-11 14:57:37adminsetgithub: 60576
2012-10-31 16:57:20wdanilosetmessages: + msg174328
2012-10-31 16:56:36mark.dickinsonsetmessages: + msg174327
2012-10-31 16:43:53wdanilosetmessages: + msg174324
2012-10-31 14:25:01mark.dickinsonsetmessages: + msg174284
2012-10-31 14:23:35mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg174283

resolution: not a bug
2012-10-31 14:18:19wdanilocreate