konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.76k stars 106 forks source link

default_factory does not create new instance of an object #223

Closed soapun closed 1 year ago

soapun commented 1 year ago

Describe the bug Default factory doesn't seem to create new instance of an object I have been using it in an inherited type. Recently found out all child objects to share the same instance as an attribute.

To Reproduce

from dataclasses import dataclass, field
from typing import Dict
import random
import dacite

def default_factory():
    print(random.randint(1, 10))
    return dict()    

@dataclass
class Dummy:

    name : str
    params : Dict = field(default_factory=default_factory)

if __name__ == "__main__":

    x = dacite.from_dict(data_class=Dummy, data={"name" : "x"})
    y = dacite.from_dict(data_class=Dummy, data={"name" : "y"})
    z = dacite.from_dict(data_class=Dummy, data={"name" : "z"})

    print(id(x.params), id(y.params), id(z.params))

Prints out

8
1905804998592 1905804998592 1905804998592

Expected behavior Expected to print 3 randints and 3 different ids. If fact only one randint is being printed and all ids are the same

Environment

Additional context Works in 1.7.0

vennahlot commented 1 year ago

+1 for the same issue after a version upgrade. Downgraded to 1.7.0 and things work again. (Python version 3.8.16, OS: macOS Ventura 13.2 on Apple M1)

sunmy2019 commented 1 year ago

duplicate of #215, already fixed

kwint commented 1 year ago

Same issue here, would be nice if the hotfix can be released soon!

mciszczon commented 1 year ago

Indeed a duplicate of #215, we'll make a fix release soon. Thanks for reporting and sorry for the delay!