Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class Range(object):
"""Represents an integer range"""
regex = re.compile(r'(?P<low>\d+|-\d+)?\.\.(?P<high>\d+|-\d+)')
def __init__(self, low, high):
self.low = low
self.high = high
def __repr__(self):
return '<Range {0}..{1}>'.format(self.low, self.high)
def from_argparse(cls, value):
"""Helper for argparse that accepts strings like
where `low` and `high` are (possibly negative) integers. If `low` is omitted it defaults to 0.
`low` must always be smaller than `high`.
match = cls.regex.match(value)
if match is None:
raise argparse.ArgumentTypeError('{0} is no a valid range'.format(value))
low ='low')
if low is None:
low = 0
low = int(low)
high = int('high'))
if low > high:
raise argparse.ArgumentTypeError('low value cannot be greater than high value')
return cls(low=int(low), high=int(high))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment