Skip to content

Instantly share code, notes, and snippets.

@dirn
Last active January 28, 2016 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirn/0061a5e4b832c1e4b1d6 to your computer and use it in GitHub Desktop.
Save dirn/0061a5e4b832c1e4b1d6 to your computer and use it in GitHub Desktop.
Validator for a range of values using Voluptuous
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