Skip to content

Instantly share code, notes, and snippets.

@samclane
Created August 19, 2020 20:38
Show Gist options
  • Save samclane/87525b7d8b0295abf6573ae5618d1c56 to your computer and use it in GitHub Desktop.
Save samclane/87525b7d8b0295abf6573ae5618d1c56 to your computer and use it in GitHub Desktop.
A class and example sublclass that casts attributes to their annotated types
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