classification
Title: An array as attribute of an object is shared between instances
Type: behavior Stage: resolved
Components: Windows Versions: Python 3.7
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: paul.moore, plugin nieulq, steve.dower, tim.golden, zach.ware
Priority: normal Keywords:

Created on 2019-10-04 11:47 by plugin nieulq, last changed 2019-10-04 12:08 by plugin nieulq. This issue is now closed.

Messages (4)
msg353928 - (view) Author: plugin nieulq (plugin nieulq) Date: 2019-10-04 11:47
I am using this version on Windows :
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)].
When an attribute of an object is an array, the array is shared between instances as shown in my example.
When executed, the output generated by the script is:
Value1
Value2
Value3
Value4
--------------------------------
Value1
Value2
Value3
Value4

It should be :

Value1
Value2
--------------------------------
Value3
Value4
msg353929 - (view) Author: plugin nieulq (plugin nieulq) Date: 2019-10-04 11:50
I am using this version on Windows :
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)].
When an attribute of an object is an array, the array is shared between instances as shown in my example.

class AClass(object):
    def __init__(self, val=[]):
        self.contents = val

    def add_content(self, newcontent):
        self.contents.append(newcontent)
        return self

    def print(self):
        for val in self.contents:
            print(str(val))


if __name__ == '__main__':
    sc = AClass()
    sc = sc.add_content("Value1").add_content("Value2")

    sb = AClass()
    sb = sb.add_content("Value3").add_content("Value4")

    sc.print()
    print("--------------------------------")
    sb.print()


When executed, the output generated by the script is:
Value1
Value2
Value3
Value4
--------------------------------
Value1
Value2
Value3
Value4

It should be :

Value1
Value2
--------------------------------
Value3
Value4
msg353930 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2019-10-04 11:56
This is a common gotcha. Take a look at: https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects
msg353935 - (view) Author: plugin nieulq (plugin nieulq) Date: 2019-10-04 12:08
Ah ... Ok. My bad.
Thank you for pointing this out to me, Mark.
This is definitely a strange behavior.
History
Date User Action Args
2019-10-04 12:08:41plugin nieulqsetnosy: - mark.dickinson
resolution: not a bug ->
messages: + msg353935
2019-10-04 11:56:58mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg353930

resolution: not a bug
stage: resolved
2019-10-04 11:50:09plugin nieulqsetmessages: + msg353929
2019-10-04 11:47:21plugin nieulqcreate