使用其他参数定义自定义操作或类型



我正在开发一个包含几个python脚本的工具箱。对于其中的几个,一些参数可能是数值。根据脚本的不同,有些脚本可能要求值v介于-1和1之间,或0和1之间或1和10之间,或。。。一个例子可以是输出图的页面宽度,它应该始终为正。

我可以一直检查v是否在要求的范围内。我还可以使用argparse为每个范围定义一个Action或一个类型。给出了一个使用新型的例子

def positive_num(a_value):
"""Check a numeric positive."""
if not a_value > 0:
raise argparse.ArgumentTypeError("Should be positive.")
return a_value 

稍后将其添加到解析器中:

parser_grp.add_argument('-pw', '--page-width',
help='Output pdf file width (e.g. 7 inches).',
type=positive_num,
default=None,
required=False)

现在,如果该值是一个相关系数(或范围内的任何值(,是否可以使用动作或类型来编写更通用的东西:

def ranged_num(a_value, lowest=-1, highest=1):
"""Check a numeric is in expected range."""
if not (a_value >= lowest and a_value <= highest):
raise argparse.ArgumentTypeError("Not in range.")
return a_value 

稍后可以添加如下内容:

parser_grp.add_argument('-c', '--correlation',
help='A value for the correlation coefficient',
type=ranged_num(-1,1),
default=None,
required=False)

我尝试过几种方法,但都没有成功。

谢谢

根据文档:

type=可以接受任何接受单个字符串参数的可调用对象,并且返回转换值

因此,要像使用type=ranged_num(-1,1)一样使用它,ranged_num函数必须返回函数本身。返回函数(或接受函数作为自变量,或两者兼而有之(的函数通常被称为"高阶函数"。

这里有一个最小的例子:

def ranged_num(lowest=-1, highest=1):
"""Check a numeric is in expected range."""
def type_func(a_value):
a_value = int(a_value)  # or "float"; you could also have error handling here
if not (a_value >= lowest and a_value <= highest):  # I'd rewrite this to an "or"
raise argparse.ArgumentTypeError("Not in range.")
return a_value
return type_func

现在ranged_num创建并返回一个函数type_func,该函数负责处理来自命令行的字符串。

最新更新