import dataclasses @dataclasses.dataclass() class Parent: def __post_init__(self): for (name, field_type) in self.__annotations__.items(): if not isinstance(self.__dict__[name], field_type): current_type = type(self.__dict__[name]) raise TypeError(f"The field `{name}` was assigned by `{current_type}` instead of `{field_type}`") print("Check is passed successfully") @dataclasses.dataclass() class MyClass(Parent): value: str obj1 = MyClass(value="1") obj2 = MyClass(value=1)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter