Given a dataclass like below:
class MessageHeader(BaseModel):
message_id: uuid.UUID
def dict(self, **kwargs):
return json.loads(self.json())
I would like to get a dictionary of string literal when I call dict
on MessageHeader
The desired outcome of dictionary is like below:
{'message_id': '383b0bfc-743e-4738-8361-27e6a0753b5a'}
I want to avoid using 3rd party library like pydantic
& I do not want to use json.loads(self.json())
as there are extra round trips
Is there any better way to convert a dataclass to a dictionary with string literal like above?
CodePudding user response:
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
CodePudding user response:
Use dataclasses.fields to create a shallow copy of fields and values.
from dataclasses import dataclass, fields
import uuid
@dataclass
class MessageHeader:
message_id: uuid.UUID
other_string: str
def dict(self):
return {field.name: str(getattr(self, field.name)) for field in fields(self)}
message_header = MessageHeader(uuid.uuid4(), "test_str")
print(message_header.dict())
CodePudding user response:
Try using vars():
from dataclasses import dataclass
import uuid
@dataclass
class MessageHeader:
message_id: str
some_string: str
some_other_string: str
def dict(self):
return vars(self)
message_header = MessageHeader(str(uuid.uuid4()), "Test", "test 2")
print(message_header.dict())