[New-bugs-announce] [issue42227] 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

Kaiyu Zheng report at bugs.python.org
Sun Nov 1 01:28:43 EDT 2020


New submission from Kaiyu Zheng <kaiyutony at 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 <report at bugs.python.org>
<https://bugs.python.org/issue42227>
_______________________________________


More information about the New-bugs-announce mailing list