强制函数为给定参数获取一组特定值的 pythonic 方法是什么?例如有一个函数如下:
def results(status, data):
我想将参数 status
限制为一组值,例如 0、1 或 99。
最佳答案
您需要检查函数内部的值:
def results(status, data):
valid = {0, 1, 99}
if status not in valid:
raise ValueError("results: status must be one of %r." % valid)
这里,valid
是一个集合,因为我们唯一关心的是status
是否是集合的成员(我们对顺序不感兴趣,因为例子)。为避免每次使用该函数时都重新创建集合,您可能会将其定义为“常量”1 全局变量:
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)
示例用法:
>>> 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}.
始终尝试提高 the most appropriate exception你可以 - ValueError
告诉函数的调用者发生了什么比 Exception
更好例如。
1 它不是真正常量,但按照惯例,Python 中的ALL_UPPERCASE
变量名被认为是常量。
关于python - 对特定的值列表强制执行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25854380/