强制对特定值列表进行参数 [英] enforce arguments to a specific list of values
问题描述
强制函数对给定参数采用一组特定值的pythonic方法是什么?例如,有一个类似的功能:
def结果(状态,数据):
我想将参数状态"限制为一组值,例如0、1或99.
您需要检查函数内部的值:
def结果(状态,数据):有效= {0,1,99}如果状态无效:引发ValueError(结果:状态必须为%r之一."%有效)
在这里, valid
是一个集合,因为我们唯一关心的是 status
是否是该集合的成员(我们对顺序不感兴趣,因为例子).为了避免每次使用该函数时都重新创建该集合,您可以将其定义为常量" 1 全局变量:
VALID_STATUS = {0,1,99}def结果(状态,数据):如果状态不在VALID_STATUS中:引发ValueError(结果:状态必须为%r之一."%VALID_STATUS)
示例用法:
>>>结果(7,[...])追溯(最近一次通话):在< module>中的文件< stdin>",第1行,结果中的文件< stdin>",第3行ValueError:结果:状态必须为{0,1,99}之一.
始终尝试提出最合适的例外情况-- ValueError
告诉函数调用者发生了什么事例如,比 Exception
相比./p>
1 不是真正的常量,但按照惯例,Python中的 ALL_UPPERCASE
变量名称被认为是常量.
What is the pythonic way to enforce a function to take a specific set of values for a given parameter? For instance there is a function like:
def results(status,data):
I want to restrict parameter 'status' to a set of values like 0, 1 or 99.
You need to check the value inside the function:
def results(status, data):
valid = {0, 1, 99}
if status not in valid:
raise ValueError("results: status must be one of %r." % valid)
Here, valid
is a set, because the only thing we care about is whether status
is a member of the collection (we aren't interested in order, for example). To avoid recreating the set each time you use the function, you'd probably define it as a "constant"1 global:
VALID_STATUS = {0, 1, 99}
def results(status, data):
if status not in VALID_STATUS:
raise ValueError("results: status must be one of %r." % VALID_STATUS)
Example usage:
>>> results(7, [...])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in results
ValueError: results: status must be one of {0, 1, 99}.
Always try to raise the most appropriate exception you can - ValueError
tells the caller of the function what's going on better than Exception
does, for example.
1 It's not really constant, but by convention, ALL_UPPERCASE
variable names in Python are considered to be intended as constants.
这篇关于强制对特定值列表进行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!