Created
August 19, 2020 20:38
-
-
Save samclane/87525b7d8b0295abf6573ae5618d1c56 to your computer and use it in GitHub Desktop.
A class and example sublclass that casts attributes to their annotated types
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 typing import Dict, Any | |
class SelfCastingClass: | |
def __init__(self, **kwargs: Dict[str, Any]): | |
for k, v in kwargs.items(): | |
self.__setattr__(k, self.__annotations__[k](v)) | |
def __repr__(self): | |
return "{" + ", ".join([f"'{k}': {v.__repr__()}" for k, v in self.__dict__.items()]) + "}" | |
class ExampleCastedClass(SelfCastingClass): | |
""" | |
>>> ac=ExampleCastedClass("3", 5) | |
>>> ac | |
{'x': 3, 'y': '5'} | |
""" | |
x: int | |
y: str | |
def __init__(self, x, y): | |
self.x = x | |
self.y = y | |
super().__init__(**self.__dict__) | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() | |
print("Test Success!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment