Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class Descriptor:
  2.  
  3. def __get__(self, instance, cls):
  4. if instance is None:
  5. return self
  6. return instance.__dict__.get(self.name)
  7.  
  8. def bind(self, name):
  9. self.name = name
  10.  
  11.  
  12. class Typed(Descriptor):
  13. def __init__(self, expected):
  14. self.expected = expected
  15.  
  16. def __set__(self, instance, value):
  17. if value is not None and not isinstance(value, self.expected):
  18. raise TypeError('expected: %s' % self.expected.__name__)
  19. instance.__dict__[self.name] = value
  20.  
  21.  
  22. def declarative(cls):
  23. for name, field in cls.__dict__.items():
  24. if isinstance(field, Descriptor):
  25. field.bind(name)
  26. return cls
  27.  
  28. # example
  29. class PositiveNumber(Declarative):
  30. def __set__(self, instance, value):
  31. if value is not None:
  32. if not isinstance(value, [int, float]):
  33. raise TypeError('expected: %s' % self.expected.__name__)
  34. if value <= 0:
  35. raise ValueError('expected: positive number')
  36. instance.__dict__[self.name] = value
  37.  
  38.  
  39. @declarative
  40. class Role:
  41. id = Typed(int)
  42. name = Typed(str)
  43.  
  44.  
  45. @declarative
  46. class DemoClass:
  47. id = Typed(int)
  48. created_at = Typed(datetime)
  49. guid = Typed(uuid.UUID)
  50. username = Typed(str)
  51. password = Typed(str)
  52. role = Typed(Role)
  53. groups = Typed(list)
  54. height = PositiveNumber()
  55.  
  56. # With this descriptor you can create simple type validated data models
  57. # It could help to make readable classes and avoid basic pitfalls
  58. # However it isn't really for value validation
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement