[Tutor] data validation logic
Alan Gauld
alan.gauld at btinternet.com
Sun Apr 17 02:19:31 CEST 2011
"Rance Hall" <ranceh at gmail.com> wrote
> I'd like to define a datavalidation function that returns true if
> data
> is valid, and false if it isn't.
>
>
> Here is the clincher. the logic of the data validator needs to be
> able to handle different types of data testing on request.
>
This is a good candidate for a factory function which takes
a function as a parameter. The function can be applied to
the data and the resultant function returned as the validator
used by your code. Something like(untested):
def makeValidator(operator, validValues)
def validator(data, vals = validValues):
return operator(data, vals)
return validator
validLowFloat = makeValidator(lambda d,v: type(d) == float and v[0] <
d < v[1],
(0.0,10.0))
validChoice = makeValidator(lambda d,v: type(d) == str and d.lower()
in v, ("yes", "no"))
x = 12.0
print validLowFloat(x) # returns False
y = 7.4
print validLowFloat(y) # returns True
s = "Maybe"
print validChoice(s) # -> False
print validChoice("No") # -> True
If you really want to get clever you could probably wrap
this as a decorator!
Whether its worth the effort over just defining validators as needed
is another matter...
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list