How to convert Python dataclass to dictionary of string literal?

You can use dataclasses.asdict:

from dataclasses import dataclass, asdict

class MessageHeader(BaseModel):
    message_id: uuid.UUID

    def dict(self):
        return {k: str(v) for k, v in asdict(self).items()}

If you’re sure that your class only has string values, you can skip the dictionary comprehension entirely:

class MessageHeader(BaseModel):
    message_id: uuid.UUID

    dict = asdict

Leave a Comment

tech