Advantages of Default Factory in Dataclasses
David Lowry-Duda
david at lowryduda.com
Thu Nov 18 10:43:10 EST 2021
On Tue, Nov 16, 2021 at 06:24:43PM -0500, Alan Bawden wrote:
> ```python
> def add_to(elem, inlist=[]):
> inlist.append(elem)
> return inlist
>
> list1 = add_to(1)
> list2 = add_to(2)
> print(list1) # prints [1]
> print(list2) # prints [1, 2], potentially confusing
> ```
>
> Not only does it not print what "most people" expect. It also doesn't
> print what _you_ expect! (But you made your point.)
Haha, you're right. I would guess that I reordered the statements when I
quickly checked this in the interpreter. But indeed, both list1 and
list2 point to inlist, and thus are the same. Whoops!
- DLD
More information about the Python-list
mailing list