Last active
November 26, 2021 12:37
-
-
Save overengineer/e3bd09be670a179795e126eb051c8d8b to your computer and use it in GitHub Desktop.
Flexible Python Dataclass Base using Munch
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
from munch import Munch | |
# Validates annotations | |
# Adding extra fields is allowed | |
# | |
# class Foo(Base): | |
# a: str | |
# b: int | |
# | |
# foo = Foo(a="hello", b=42, c=True) # This is OK! | |
# foo = Foo(a="hi") # raises error | |
class Base(Munch): | |
def __init__(self, **kwargs): | |
for key, typ in self.__annotations__.items(): | |
assert key in kwargs, f'missing field {key}' | |
val = kwargs[key] | |
assert isinstance(val, typ), f'field {key} of value {val} is not an instance of type {typ}' | |
super().__init__(**kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment