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: Unexpected sharing of list/set/dict between instances of the same class, when the list/set/dict is a default parameter value of the constructor
Type: behavior Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: kaiyutony, steven.daprano
Priority: normal Keywords:

Created on 2020-11-01 05:28 by kaiyutony, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg380115 - (view) Author: Kaiyu Zheng (kaiyutony) Date: 2020-11-01 05:28
In the following toy example, with Python 3.7.4

class Foo:
    def __init__(self, a=set()):
        self.a = a
foo1 = Foo()
foo2 = Foo()
foo1.a.add(1)
print(foo2.a)

This shows {1}. This means that modifying the .a field of foo1 changed that of foo2. I was not expecting this behavior, as I thought that when the constructor is called, an empty set is created for the parameter `a`. But instead, what seems to happen is that a set() is created, and then shared between instances of Foo. What is the reason for this? What is the benefit? It adds a lot of confusion
msg380117 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-11-01 06:24
Sorry, this is not a bug, but working as designed. Default values for functions and methods are only created once, when the function is created, not on every call.

This is a FAQ:

https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects
msg380118 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-11-01 06:34
See also my comment here:

https://bugs.python.org/msg361451
History
Date User Action Args
2022-04-11 14:59:37adminsetgithub: 86393
2020-11-01 06:34:38steven.dapranosetmessages: + msg380118
2020-11-01 06:24:35steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg380117

resolution: not a bug
stage: resolved
2020-11-01 05:28:43kaiyutonycreate