Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:26
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 smailliwcs/b94c53363bce0a30e7d168a87372d297 to your computer and use it in GitHub Desktop.
Save smailliwcs/b94c53363bce0a30e7d168a87372d297 to your computer and use it in GitHub Desktop.
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