python - How to enforce dataclass fields' types? - Stack Overflow

PHOTO EMBED

Tue Oct 01 2024 11:11:31 GMT+0000 (Coordinated Universal Time)

Saved by @kapkap #python

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)
content_copyCOPY

https://stackoverflow.com/questions/58992252/how-to-enforce-dataclass-fields-types