asdict that ignore sentinel

33

from dataclasses import dataclass
from typing import Optional, Dict, cast

SENTINEL = cast(None, object())  # have a sentinel that pretends to be 'None'


@dataclass
class Bla:
    arg1: Optional[int] = SENTINEL
    arg2: Optional[str] = SENTINEL
    arg3: Optional[Dict[str, str]] = SENTINEL

    def asdict(self):
        return {k: v for k, v in self.__dict__.items() if v is not SENTINEL}

Comments

Submit
0 Comments