Skip to content

Instantly share code, notes, and snippets.

@overengineer
Last active November 26, 2021 12:37
Show Gist options
  • Save overengineer/e3bd09be670a179795e126eb051c8d8b to your computer and use it in GitHub Desktop.
Save overengineer/e3bd09be670a179795e126eb051c8d8b to your computer and use it in GitHub Desktop.
Flexible Python Dataclass Base using Munch
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