Created
October 6, 2024 02:34
-
-
Save powderflask/69ca9e4d671ce1049ee72213b5a9c684 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Arjan asked: which do you prefer, TypedDict or dataclass? My response: why choose when you can have both? """ | |
from collections.abc import Mapping | |
from dataclasses import dataclass | |
from functools import cached_property | |
@dataclass | |
class Options(Mapping): | |
option1: str = "hello" | |
option2: int = 42 | |
@cached_property | |
def fields(self) -> dict: | |
return {f.name: getattr(self, f.name) for f in dataclasses.fields(self)} | |
def __getitem__(self, key): | |
return self.fields[key] | |
def __iter__(self): | |
return iter(self.fields) | |
def __len__(self): | |
return len(self.fields) | |
o = Options(option1="Arjan") | |
assert list(o.keys())==['option1', 'option2'] | |
assert o['option2'] == 42 | |
opt1, opt2 = o.values() | |
assert opt1 == "Arjan" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment