[Tutor] there might be something error in dataclasses.py

Roel Schroeven roel at roelschroeven.net
Thu Jul 8 07:24:04 EDT 2021


Op 8/07/2021 om 8:51 schreef LI Bonjour:
>>>> from dataclasses import dataclass
>>>> @dataclass
> ... class A:
> ...     a:list[str] = None
> ...
> ...
>>>> a = A()
>>>> a.a = []
>>>> b
Where does this 'b' come from? What is its value?
> [A(a=['1']), A(a=['1']), A(a=['1'])]
Oh, 'b' seems to be a list of instances of class A. But how is it 
constructed? That can make all the difference.
>>>> for x in b:
> ...     x.a.append('1')
> ...
>>>> b
> [A(a=['1', '1', '1', '1']), A(a=['1', '1', '1', '1']), A(a=['1', '1', '1', '1'])]
> I think it should be this below.
>   [A(a=['1','1']), A(a=['1','1']), A(a=['1','1'])]
> is there anything wrong here .
>
What probably happened is that all the elements of b refer to one single 
instance of A. If you then change that instance, that change becomes 
visible via all references to that instance.

If you don't want it, initialize b with something like

     b = [A() for _ in range(3)]

instead of e.g.

     b = [A()] * 3

-- 
"A common mistake that people make when trying to design something completely
foolproof is to underestimate the ingenuity of complete fools."
         -- Douglas Adams



More information about the Tutor mailing list