Created
February 20, 2019 19:58
-
-
Save Shuhala/673907bbbfed5ce2979e77b55de97c44 to your computer and use it in GitHub Desktop.
PropertyTypeMixin
This file contains 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
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