Skip to content

Instantly share code, notes, and snippets.

@martinth
Created July 23, 2015 11:12
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 martinth/92d3d7be54de77e5be86 to your computer and use it in GitHub Desktop.
Save martinth/92d3d7be54de77e5be86 to your computer and use it in GitHub Desktop.
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)
@classmethod
def from_argparse(cls, value):
"""Helper for argparse that accepts strings like
low..high
..high
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 = match.group('low')
if low is None:
low = 0
else:
low = int(low)
high = int(match.group('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