Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. from typing import Any, Dict
  2.  
  3.  
  4. class PropertyTypeMixin:
  5. """
  6. Enforce type checking of attributes at runtime
  7. """
  8. _properties_type: Dict[str, Any] = {}
  9.  
  10. def __setattr__(self, key, value):
  11. type_hint = self._properties_type.get(key)
  12. if type_hint and value and not isinstance(value, type_hint):
  13. err = (f'class {self.__class__.__name__}: Invalid type provided for attribute {key}. '
  14. f'Expected {type_hint.__name__}, got {key} = {value} ({type(value)}).')
  15. raise AttributeError(err)
  16. super().__setattr__(key, value)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement