Skip to content

Instantly share code, notes, and snippets.

@Shuhala
Created February 20, 2019 19:58
Show Gist options
  • Save Shuhala/673907bbbfed5ce2979e77b55de97c44 to your computer and use it in GitHub Desktop.
Save Shuhala/673907bbbfed5ce2979e77b55de97c44 to your computer and use it in GitHub Desktop.
PropertyTypeMixin
from typing import Any, Dict
class PropertyTypeMixin:
"""
Enforce type checking of attributes at runtime
"""
_properties_type: Dict[str, Any] = {}
def __setattr__(self, key, value):
type_hint = self._properties_type.get(key)
if type_hint and value and not isinstance(value, type_hint):
err = (f'class {self.__class__.__name__}: Invalid type provided for attribute {key}. '
f'Expected {type_hint.__name__}, got {key} = {value} ({type(value)}).')
raise AttributeError(err)
super().__setattr__(key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment