New submission from Kaiyu Zheng <kaiyut...@gmail.com>:
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 ---------- messages: 380115 nosy: kaiyutony priority: normal severity: normal status: open 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 versions: Python 3.7 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue42227> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com