Last active
March 25, 2025 10:26
-
-
Save ay0ks/b7017c2f5ce2c05d600994c532736d64 to your computer and use it in GitHub Desktop.
PoC Python dataclasses.dataclass reimplementation
This file contains hidden or 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
| import contextlib | |
| import copy | |
| import types | |
| class structure: | |
| def __init__(self, _class): | |
| self.__class = _class | |
| self.annotations: list = list(_class.__annotations__.items()) | |
| _class.__class = self.__class | |
| _class.__repr__ = lambda self: \ | |
| "<structure %s, %s>" % ( | |
| self.__class.__name__, | |
| self.fields | |
| ) | |
| def __call__(self, **args): | |
| _class = copy.deepcopy(self.__class)() | |
| _class.fields = args | |
| for field_name, field_value in list(args.items()): | |
| for ( | |
| annotation_name, | |
| annotation_type | |
| ) in self.annotations: | |
| if not annotation_name in list(args.keys()): | |
| if isinstance(annotation_type, types.UnionType) \ | |
| and type(None) in annotation_type.__args__: | |
| setattr(_class, annotation_name, None) | |
| else: | |
| raise Exception("field %s is not nullable, so it must be specified" % annotation_name) | |
| else: | |
| if field_name == annotation_name: | |
| if isinstance(field_value, annotation_type): | |
| setattr(_class, field_name, field_value) | |
| else: | |
| raise TypeError("type mismatch, required %s, got %s" % ( | |
| annotation_type, | |
| type(field_value) | |
| )) | |
| return _class | |
| def __repr__(self): | |
| return "<structure %s {\n%s\n}>" % ( | |
| self.__class.__name__, | |
| "".join([ | |
| " %s: %s%s" % ( | |
| annotated[0], | |
| annotated[1].__name__, | |
| "\n" if not annotated == self.annotations[-1] \ | |
| else "" | |
| ) | |
| for annotated in self.annotations | |
| ]) | |
| ) |
This file contains hidden or 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
| @structure | |
| class Human: | |
| name: str | |
| age: int | |
| born: datetime.datetime | |
| nullable_field_test: int | None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment