dataclasses: how to ignore None values using asdict()?

@dataclass
class Car:
    brand: str
    color: str

How can I get a dict that ignore None values? Something like:

>>> car = Car(brand="Audi", color=None)
>>> asdict(car, some_option_to_ignore_none_values=True)
> {'brand': 'Audi'}

Answer

Here you go:

from dataclasses import dataclass


@dataclass
class Car:
    brand: str
    color: str


def asdict(o, skip_empty=False):
    return {k: v
            for k, v in o.__dict__.items()
            if not (skip_empty and v is None)}


if __name__ == '__main__':
    c = Car(brand='BMW', color=None)
    print(asdict(c, skip_empty=False))
    print(asdict(c, skip_empty=True))

which prints:

{'brand': 'BMW', 'color': None}
{'brand': 'BMW'}
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .