Advertisement
cirossmonteiro

validator class

Nov 9th, 2023 (edited)
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. class Validator:
  2.     def __call__(self, value):
  3.         return self.validate(value)
  4.  
  5. class MinValidator(Validator):
  6.     def __init__(self, minimum):
  7.         self.minimum = minimum
  8.        
  9.     def validate(self, value):
  10.         return value >= self.minimum
  11.  
  12. class MaxValidator(Validator):
  13.     def __init__(self, maximum):
  14.         self.maximum = maximum
  15.        
  16.     def validate(self, value):
  17.         return value <= self.maximum
  18.  
  19. # big version
  20. ##class BetweenValidator(MinValidator, MaxValidator):
  21. ##    def __init__(self, minimum, maximum):
  22. ##        MinValidator.__init__(self, minimum)
  23. ##        MaxValidator.__init__(self, maximum)
  24. ##        
  25. ##    def validate(self, value):
  26. ##        return MinValidator.validate(self, value) and MaxValidator.validate(self, value)
  27.  
  28. class MergeValidators(Validator):
  29.     validator_classes = []
  30.    
  31.     def __init__(self, *args):
  32.         for index, vclass in enumerate(self.validator_classes):
  33.             if type(args[index]) == list:
  34.                 vclass.__init__(self, *args[index])
  35.             else:
  36.                 vclass.__init__(self, args[index])
  37.  
  38.     def validate(self, value):
  39.         for vclass in self.validator_classes:
  40.             if not vclass.validate(self, value):
  41.                 return False
  42.  
  43.         return True
  44.        
  45. # small version
  46. class BetweenValidator(MergeValidators):
  47.     validator_classes = [
  48.         MinValidator,
  49.         MaxValidator
  50.     ]
  51.  
  52. assert BetweenValidator(18, 25)(18)
  53. # same as "MinValidator(18)(18) and MaxValidator(25)(18)"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement