Skip to content

Instantly share code, notes, and snippets.

@clintval
Created May 9, 2019 21:18
Show Gist options
  • Select an option

  • Save clintval/3b2ffdfb01b8d26263cfb515dd510abf to your computer and use it in GitHub Desktop.

Select an option

Save clintval/3b2ffdfb01b8d26263cfb515dd510abf to your computer and use it in GitHub Desktop.
Type Safe Metric (Don't look at this... sandbox)
from types import MethodType
class TypeSafeAttribute(object):
def _type_of(self, attr):
if not self._has_attr(attr):
raise ValueError(f'No attribute defined as annotation: {attr}')
return self.__annotations__[attr]
def _has_attr(self, attr):
return attr in self.__annotations__
def __setattr__(self, attr, value):
if self._has_attr(attr) and not isinstance(value, self._type_of(attr)):
raise ValueError(f'Value not of type {self._type_of(attr)}: {value}')
super().__setattr__(attr, value)
def typesafe(clazz):
clazz._type_of = TypeSafeAttribute._type_of
clazz._has_attr = MethodType(TypeSafeAttribute._has_attr, clazz)
clazz.__setattr__ = MethodType(TypeSafeAttribute.__setattr__, clazz)
return clazz
class Metric():
pass
@typesafe
class DuplexYield(Metric):
duplex_bases: int = 0
d = DuplexYield()
#DuplexYield().duplex_bases = '2'
DuplexYield().hii = 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment