Advantages of Default Factory in Dataclasses

David Lowry-Duda david at lowryduda.com
Tue Nov 16 18:00:05 EST 2021


On Tue, Nov 16, 2021 at 05:04:05PM +0400, Abdur-Rahmaan Janhangeer wrote:
> A simple question: why do we need field(default_factory ) in 
> dataclasses?

For the same reason that the following code doesn't do what some people 
might expect it to:

```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
```

Mutable attributes are created once, upon definition. Reusing the same 
function (or instantiating objects of the same class) and modifying this 
attribute can lead to possibly unexpected side effects as above.

- DLD


More information about the Python-list mailing list