Created
April 11, 2017 13:08
-
-
Save emolch/543e7feb02e33dac717e8da94c165b4f to your computer and use it in GitHub Desktop.
How to implement range checking with guts.
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 pyrocko.guts import Float, Object, ValidationError, List | |
def float_or_none(x): | |
if x is None: | |
return None | |
else: | |
return float(x) | |
class FloatWithRange(Float): | |
class __T(Float.T): | |
def __init__( | |
self, ge=None, le=None, gt=None, lt=None, *args, **kwargs): | |
Float.T.__init__(self, *args, **kwargs) | |
self.ge = float_or_none(ge) | |
self.le = float_or_none(le) | |
self.gt = float_or_none(gt) | |
self.lt = float_or_none(lt) | |
def validate_extra(self, val): | |
if self.ge is not None and val < self.ge: | |
raise ValidationError( | |
'must be greater than or equal to %g (value: %g)' % ( | |
self.ge, val)) | |
if self.le is not None and val > self.le: | |
raise ValidationError( | |
'must be less than or equal to %g (value: %g)' % ( | |
self.le, val)) | |
if self.gt is not None and val <= self.gt: | |
raise ValidationError( | |
'must be greater than %g (value: %g)' % ( | |
self.gt, val)) | |
if self.lt is not None and val >= self.lt: | |
raise ValidationError( | |
'must be less than %g (value: %g)' % ( | |
self.lt, val)) | |
return Float.T.validate_extra(self, val) | |
class Test(Object): | |
a = FloatWithRange.T(ge=0., le=10.) | |
l = List.T(FloatWithRange.T(gt=0.)) | |
t = Test(a=1., l=[2., 0., 2.]) | |
try: | |
t.validate() | |
assert False | |
except ValidationError as e: | |
print e | |
t = Test(a=0.) | |
t.validate() | |
t = Test(a=-12.) | |
try: | |
t.validate() | |
assert False | |
except ValidationError as e: | |
print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment