Last active
January 28, 2016 21:00
-
-
Save dirn/0061a5e4b832c1e4b1d6 to your computer and use it in GitHub Desktop.
Validator for a range of values using Voluptuous
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
class Range: | |
"""A validator to check if a value is within a range.""" | |
def __init__(self, start, stop=None, step=1): | |
# Do our best to match range's signature. | |
if stop is None: | |
# If there is no value for stop, use start as stop instead. | |
self.range = range(start) | |
else: | |
self.range = range(start, stop, step) | |
def __call__(self, other): | |
return other in self.range | |
if __name__ == '__main__': | |
from voluptuous import Schema | |
schema = Schema(Range(10)) | |
for x in range(10): | |
assert schema(x) | |
assert not schema(10) | |
schema = Schema(Range(10, 100, 5)) | |
for x in range(10, 100, 5): | |
assert schema(x) | |
assert not schema(9) | |
assert not schema(11) | |
assert not schema(101) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment