Reputation: 15942
I'd like to use argparse
on Python 2.7 to require that one of my script's parameters be between the range of 0.0 and 1.0. Does argparse.add_argument()
support this?
Upvotes: 53
Views: 30713
Reputation: 1
In case you would also like to in-/exclude the boundaries of the float range(s), I have extended the codings of above as follows:
from typing import Generator
import re
import argparse
class Range(object):
def __init__(self, scope: str):
r = re.compile(
r'^([\[\]]) *([-+]?(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[Ee][+-]?\d+)?) *'
r', *([-+]?(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[Ee][+-]?\d+)?) *([\[\]])$'
)
try:
i = [j for j in re.findall(r, scope)[0]]
self.__start, self.__end = float(i[1]), float(i[2])
if self.__start >= self.__end:
raise ArithmeticError
except (IndexError, ArithmeticError):
raise SyntaxError("An error occurred with the range provided!")
self.__st = '{}{{}},{{}}{}'.format(i[0], i[3])
self.__lamba = "lambda start, end, item: start {0} item {1} end".format(
{'[': '<=', ']': '<'}[i[0]],
{']': '<=', '[': '<'}[i[3]]
)
def __eq__(self, item: float) -> bool: return eval(self.__lamba)(
self.__start,
self.__end,
item
)
def __contains__(self, item: float) -> bool: return self.__eq__(item)
def __iter__(self) -> Generator[object, None, None]: yield self
def __str__(self) -> str: return self.__st.format(self.__start, self.__end)
def __repr__(self) -> str: return self.__str__()
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=float, choices=Range('[0., 1.0['))
parser.add_argument('--bar', type=float, choices=[Range(']0., 1.0['), Range(']2.0E0, 3.0e0]')])
Upvotes: 0
Reputation: 91
Adding str makes that the boundaries are visuable in the help.
import argparse
class Range(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start <= other <= self.end
def __contains__(self, item):
return self.__eq__(item)
def __iter__(self):
yield self
def __str__(self):
return '[{0},{1}]'.format(self.start, self.end)
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=float, choices=Range(0.0, 1.0))
parser.add_argument('--bar', type=float, choices=[Range(0.0, 1.0), Range(2.0,3.0)])
Upvotes: 8
Reputation: 530990
The type
parameter to add_argument
just needs to be a callable object that takes a string and returns a converted value. You can write a wrapper around float
that checks its value and raises an error if it is out of range.
def restricted_float(x):
try:
x = float(x)
except ValueError:
raise argparse.ArgumentTypeError("%r not a floating-point literal" % (x,))
if x < 0.0 or x > 1.0:
raise argparse.ArgumentTypeError("%r not in range [0.0, 1.0]"%(x,))
return x
p = argparse.ArgumentParser()
p.add_argument("--arg", type=restricted_float)
Upvotes: 60
Reputation: 117
The argparse.add_argument call expects an iterable as 'choices' parameter. So what about adding the iterable property to the Range class above. So both scenarios could be used:
import argparse
class Range(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start <= other <= self.end
def __contains__(self, item):
return self.__eq__(item)
def __iter__(self):
yield self
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=float, choices=Range(0.0, 1.0))
parser.add_argument('--bar', type=float, choices=[Range(0.0, 1.0), Range(2.0,3.0)])
Upvotes: 2
Reputation: 208435
Here is a method that uses the choices
parameter to add_argument
, with a custom class that is considered "equal" to any float within the specified range:
import argparse
class Range(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start <= other <= self.end
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=float, choices=[Range(0.0, 1.0)])
Upvotes: 33