Skip to content

Instantly share code, notes, and snippets.

@renanivo
Last active August 19, 2019 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renanivo/42b2289208807565c6a5d3e55dc40177 to your computer and use it in GitHub Desktop.
Save renanivo/42b2289208807565c6a5d3e55dc40177 to your computer and use it in GitHub Desktop.
Validated Metaclass
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