Last active
August 19, 2019 13:16
-
-
Save renanivo/42b2289208807565c6a5d3e55dc40177 to your computer and use it in GitHub Desktop.
Validated Metaclass
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 typing | |
import functools | |
from dataclasses import dataclass | |
def validated_set(self, value, field_name, field_type): | |
if not isinstance(value, field_type): | |
raise TypeError( | |
f'"{field_name}" should be "{field_type.__name__}". ' | |
f'Value: {value!r}' | |
) | |
self.__dict__[field_name] = value | |
class Validated(type): | |
def __init__(cls, name, bases, attrs, **kwargs): | |
for field_name, field_type in cls.__annotations__.items(): | |
fset = functools.partial( | |
validated_set, | |
field_name=field_name, | |
field_type=field_type | |
) | |
validated_property = property( | |
fset=fset | |
) | |
setattr(cls, field_name, validated_property) | |
@dataclass | |
class Employee(metaclass=Validated): | |
name: str | |
id: int |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment