Created
September 22, 2020 15:26
-
-
Save smailliwcs/b94c53363bce0a30e7d168a87372d297 to your computer and use it in GitHub Desktop.
Integer range command-line arguments in Python
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
import argparse | |
class IntRangeArg: | |
def __init__(self, start=None, stop=None): | |
assert start is None or stop is None or start < stop | |
self.start = start | |
self.stop = stop | |
def __contains__(self, value): | |
return (self.start is None or value >= self.start) and (self.stop is None or value < self.stop) | |
def __call__(self, arg): | |
value = None | |
try: | |
value = int(arg) | |
except ValueError: | |
pass | |
if value is None or value not in self: | |
raise argparse.ArgumentTypeError(f"invalid int value: '{arg}' (choose from [{self.start}, {self.stop}))") | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment