Update dataclass fields from a dict in python
Asked Answered
E

3

11

How can I update the fields of a dataclass using a dict?

Example:

@dataclass
class Sample:
    field1: str
    field2: str
    field3: str
    field4: str

sample = Sample('field1_value1', 'field2_value1', 'field3_value1', 'field4_value1')
updated_values = {'field1': 'field1_value2', 'field3': 'field3_value2'}

I want to do something like

sample.update(updated_values)
Ebonyeboracum answered 25/4, 2020 at 13:16 Comment(1)
Does this answer your question? Update a field in a dataclass with a field name known only during runtimeMegan
T
10

One way is to make a small class and inherit from it:

class Updateable(object):
    def update(self, new):
        for key, value in new.items():
            if hasattr(self, key):
                setattr(self, key, value)

@dataclass
class Sample(Updateable):
    field1: str
    field2: str
    field3: str
    field4: str

You can read this if you want to learn more about getattr and setattr

Toxoplasmosis answered 25/4, 2020 at 13:26 Comment(0)
T
10

Updating the underlying __dict__ seems to work if you have a basic dataclass:

sample.__dict__.update({ 'field1': 'value1' })
Tagliatelle answered 19/5, 2021 at 9:49 Comment(0)
M
1

@DanStewart's solution seems to work but when you see members that start and end with __ you should avoid modifying them directly: since python does not have private/protected visibility, __ is the way to warn the programmer that those methods/variables are only for within class usage, not intended to be part of the interface.

A better method is to use replace as in this answer

from dataclasses import replace
sample = replace(sample, **updated_values)
Megan answered 3/4, 2024 at 11:13 Comment(1)
I prefer this answer since it gives me more control. For example, if my dataclass has a list attribute, I can modify the update function to append to the list instead of replacing the values. Nonetheless, this indeed looks like a better solution for normal cases where we want to replace the values. Thanks!Ebonyeboracum

© 2022 - 2025 — McMap. All rights reserved.