0
a= {'message_id': '0b35dea6-23fe-44cc-a5a6-0f64a5eb382c', 'var_a': '8', 'var_b': 'False'}

Give the dictionary above, how do I convert the dictionary with string literal back to attribute types in dataclass?

I have a dataclass in MessageHeaders like below:

@dataclass
class MessageHeader:
    message_id: uuid.UUID
    var_a: int
    var_b: bool

This is how I convert dictionary to dataclass:

MessageHeader(**a)

However, it is not ideal as all the attributes would be in string (not in the attribute type)

What is the best approach to convert dictionary (string type) to the dataclass matching attribute type?

Unknown
  • 778
  • 1
  • 7
  • 16
  • Not reproducible - e.g. the attribute `var_a` is `int`, given the sample dict. – buran Jun 14 '22 at 08:54
  • @buran, I have fixed the dictionary string – Unknown Jun 14 '22 at 08:59
  • @RiccardoBucco, sorry I could not identify how your link solve my question. I do not want to use pydantic if possible – Unknown Jun 14 '22 at 09:06
  • "However, it is not ideal as all the attributes would be in string (not in the attribute type)". Attributes don't have types, they can refer to any type of object. You are responsible for writing code that validates and transforms data to your particular specifications - type hints **are hints**. Now, there exist libraries that help you do this, but in any case, the answer is "you have to write code that does that" – juanpa.arrivillaga Jun 14 '22 at 09:06
  • @Unknown then use another library. Or write your own code. It isn't clear what answer you are expecting. – juanpa.arrivillaga Jun 14 '22 at 09:07
  • @juanpa.arrivillaga, is there any cleaner way instead of manually converting from string to attribute type? – Unknown Jun 14 '22 at 09:08
  • @Unknown cleaner **than what**? Again, you must understand -- **attributes don't have types** -- . If you want to enforce they type hints - that's *your responsibility*. The duplicate shows you several approaches that are generic. And points to a library that implements a generic approach. whether using that is "cleaner" than maintaining your own version is not really something we can answer – juanpa.arrivillaga Jun 14 '22 at 09:11
  • there is a neat solution use pydantic package with "@validate_arguments" decorator – Zain Ul Abidin Jun 14 '22 at 09:13
  • you can get what you want easily with [dataclass-wizard](https://dataclass-wizard.readthedocs.io/). from there, it's as easy as: `instance = fromdict(MessageHeader, a)`. – rv.kvetch Jun 18 '22 at 04:13

0 Answers0