Closed alexferl closed 4 years ago
Id also be interested in this! Id like to be able to implement a from_dict method() that takes a dictionary and uses the values in a existing class instance. Basically id like to be able to call from_dict on an existing instance instead of creating a whole new one. Is this possible?
Hi @admiralobvious - thank you for this issue. You are right, it's not possible to call from_dict
with a data class instance.
As I understand you want to build some general solution, so data
can contain a set of any fields from a given dataclass. It sounds like a possible extension for dacite
(e.g. dacite.update_from_dict
) but TBH I want to keep dacite
API as small as possible.
It see two possible solutions for your problem.
data
and return new isntance of your model. def update(self, d: dict) -> BaseModel:
current = self.to_dict()
result = {**current, **d}
return dacite.from_dict(self.__class__, result)
update
methodSo instead of:
data = {"profile": {"profile_url": "some_url}
... transform your update data into:
data = {"profile": Profile(profile_url="some_url)}
... before you pass it to update
method. It looks like the best solution, because you are not mixing "raw" data with your "transfomed" models. After you load your model from database you should stay in "dataclass world" only.
Hello,
Thank you for the lib, I was about to make something similar to handle nested data and dataclasses but found yours instead.
That being said, I haven't found a way to do exactly what I want even after searching. Perhaps you can help me?
I have the following base dataclass that has some fields and methods that I want in all my other dataclasses:
Obviously the way I set the attributes in
_set_attrs
is very naive and won't support nested data so I was hopping to use dacite within that method to properly set them for me.The use case for this is the following: Consider the following dataclasses:
If I were to create a user I would do something like:
No problem there as there's no nested fields.
Now if I wanted to update a nested field:
As you know that's not gonna work,
profile
will be set to:{"profile_url": "some_url"}
Enter
dacite
. Ideally, I'd want to modify myBaseModel
'supdate()
method to something like this:but again, as you know, this won't work since
from_dict()
exceptsType[T]
not an instance.A very hacky workaround that seems like a bad idea is:
My question is, would you consider having
dacite
augment an existing instance instead of creating one? Or is there another way to do what I want?Cheers