Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Integer range command-line arguments in Python
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
You can’t perform that action at this time.