Created
July 23, 2015 11:12
-
-
Save martinth/92d3d7be54de77e5be86 to your computer and use it in GitHub Desktop.
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(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