I have the following dataclass:
@dataclass
class Image:
    content_type: str
    data: bytes = b''
    id: str = ""
    upload_date: datetime = None
    size: int = 0
    def to_dict(self) -> Dict[str, Any]:
        result = {}
        if self.id:
            result['id'] = self.id
        if self.content_type:
            result['content_type'] = self.content_type
        if self.size:
            result['size'] = self.size
        if self.upload_date:
            result['upload_date'] = self.upload_date.isoformat()
        return result
Is there any way to simplify to_dict method? I don't want to list all of the fields using if.
As suggested by meowgoesthedog, you can use asdict and filter the result to skip falsy values:
from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Dict, Any
@dataclass
class Image:
    content_type: str
    data: bytes = b''
    id: str = ""
    upload_date: datetime = None
    size: int = 0
    def to_dict(self) -> Dict[str, Any]:
        return {k: v for k, v in asdict(self).items() if v}
print(Image('a', b'b', 'c', None, 0).to_dict())
# {'content_type': 'a', 'data': b'b', 'id': 'c'}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With