Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}
like image 471
David D. Avatar asked Jul 01 '19 16:07

David D.


2 Answers

All answers are good but to me they are too verbose. Here's a one-liner:

# dc is dataclass
# d is dict out
d = asdict(dc, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})

Show case:

from typing import Optional, Tuple
from dataclasses import asdict, dataclass

@dataclass
class Space:
    size: Optional[int] = None
    dtype: Optional[str] = None
    shape: Optional[Tuple[int]] = None

s1 = Space(size=2)
s1_dict = asdict(s1, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})
print(s1_dict)
# {"size": 2}

s2 = Space(dtype='int', shape=(2, 5))
s2_dict = asdict(s2, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})
print(s2_dict)
# {"dtype": "int", "shape": (2, 5)}
like image 121
Dawid Laszuk Avatar answered Sep 29 '22 11:09

Dawid Laszuk


Another option is to write a dict_factory that will reject adding None values and pass it to asdict method. checkout the code source here https://github.com/python/cpython/blob/master/Lib/dataclasses.py

like image 23
Ramtin M. Seraj Avatar answered Sep 29 '22 12:09

Ramtin M. Seraj