The Python argparse
module lacks a built-in mechanism for validating
argument ranges. For instance, while you can specify an argument type as int
, there is no straightforward way to
restrict it to only positive values. Similarly, when dealing with float
arguments, there is no native method to
ensure that the provided values fall within the range of [0.0, 1.0).
CheckRange
is a possible solution to this problem. It is a subclass of argparse.Action
.
It allows you to validate open, closed, and half-open intervals. Each endpoint can be either a number or positive or negative infinity:
- [a, b] →
min=a, max=b
- [a, b) →
min=a, sup=b
- (a, b] →
inf=a, max=b
- (a, b) →
inf=a, sup=b
- [a, +∞) →
min=a
- (a, +∞) →
inf=a
- (-∞, b] →
max=b
- (-∞, b) →
sup=b
parser = argparse.ArgumentParser()
parser.add_argument('--int-value', type=int, min=1,
action=CheckRange, metavar='N',
help='Positive integer')
print(parser.parse_args())
$ python3 test.py --help
usage: test.py [-h] [--int-value N]
options:
-h, --help show this help message and exit
--int-value N Positive integer
$ python3 test.py --int-value 0
usage: test.py [-h] [--int-value N]
test.py: error: argument --int-value: valid range: [1, +infinity)
$ python3 test.py --int-value 100
Namespace(int_value=100)
parser = argparse.ArgumentParser()
parser.add_argument('--float-value', type=float, min=0.0, sup=1.0,
action=CheckRange, metavar='F',
help='Float value in [%(min)s, %(sup)s)')
print(parser.parse_args())
$ python3 test.py --help
usage: test.py [-h] [--float-value F]
options:
-h, --help show this help message and exit
--float-value F Float value in [0.0, 1.0)
$ python3 test.py --float-value -1.0
usage: test.py [-h] [--float-value F]
test.py: error: argument --float-value: valid range: [0.0, 1.0)
$ python3 test.py --float-value 1.0
usage: test.py [-h] [--float-value F]
test.py: error: argument --float-value: valid range: [0.0, 1.0)
$ python3 test.py --float-value 0.5
Namespace(float_value=0.5)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import operator
class CheckRange(argparse.Action):
ops = {'inf': operator.gt,
'min': operator.ge,
'sup': operator.lt,
'max': operator.le}
def __init__(self, *args, **kwargs):
if 'min' in kwargs and 'inf' in kwargs:
raise ValueError('either min or inf, but not both')
if 'max' in kwargs and 'sup' in kwargs:
raise ValueError('either max or sup, but not both')
for name in self.ops:
if name in kwargs:
setattr(self, name, kwargs.pop(name))
super().__init__(*args, **kwargs)
def interval(self):
if hasattr(self, 'min'):
l = f'[{self.min}'
elif hasattr(self, 'inf'):
l = f'({self.inf}'
else:
l = '(-infinity'
if hasattr(self, 'max'):
u = f'{self.max}]'
elif hasattr(self, 'sup'):
u = f'{self.sup})'
else:
u = '+infinity)'
return f'valid range: {l}, {u}'
def __call__(self, parser, namespace, values, option_string=None):
for name, op in self.ops.items():
if hasattr(self, name) and not op(values, getattr(self, name)):
raise argparse.ArgumentError(self, self.interval())
setattr(namespace, self.dest, values)
parser = argparse.ArgumentParser()
parser.add_argument('--int-value', type=int, min=1,
action=CheckRange, metavar='N',
help='Positive integer')
parser.add_argument('--float-value', type=float, min=0.0, sup=1.0,
action=CheckRange, metavar='F',
help='Float value in [%(min)s, %(sup)s)')
print(parser.parse_args())
This is super useful! Would you mind declaring the Gist to be Apache License, Version 2.0? That would be awesome!