Python 3.x “如何编写泛型”;“验证”;方法来接收各种输入
我有几个具有一些公共输入的函数:Python 3.x “如何编写泛型”;“验证”;方法来接收各种输入,python-3.x,Python 3.x,我有几个具有一些公共输入的函数: func_1(x1, x2, x3, y1) func_2(x1, x3, y2) func_3(x1, x2, x3, y1, y3) 我想为所有输入编写输入错误处理代码(例如,如果x1为None,则抛出异常)。我发现将输入验证函数配置为一个很好的选项,可以检查/验证来自所有函数的所有输入 def validate_inputs(x1, x2, x3, y1, y2, y3) # do the all checks for x1, x2, x3, y
func_1(x1, x2, x3, y1)
func_2(x1, x3, y2)
func_3(x1, x2, x3, y1, y3)
我想为所有输入编写输入错误处理代码(例如,如果x1
为None
,则抛出异常)。我发现将输入验证函数配置为一个很好的选项,可以检查/验证来自所有函数的所有输入
def validate_inputs(x1, x2, x3, y1, y2, y3)
# do the all checks for x1, x2, x3, y1, y2, y3 here
并通过必要的输入从相应的函数调用:
def func_1(x1, x2, x3, y1)
validate_inputs(x1, x2, x3, y1)
# do whatever the function is supposed to do
def func_2(x1, x3, y2)
validate_inputs(x1, x3, y2)
# do whatever the function is supposed to do
问题:我应该如何配置验证\u输入
以具有这样的“灵活”输入?查看:
首先,编写一些验证器:
def validate_int(i):
if not type(i) == int:
raise Exception(f"{i} is not a number")
//TODO complete code
def validate_something(i):
if not ....:
raise Exception(f"{i} is not something..")
然后,将验证器保存在某些目录中:
validators = {'x1': validate_int,
'y1': validate_int,
'y3': validate_int,
'x2': validate_something}
编写装饰程序以验证参数:
def validate_args(func):
def wrapper(*args, **kwargs):
for k,v in kwargs.items():
validators.get(k, lambda x: x)(v)
return wrapper
现在,您希望将每个方法验证为包装并使用键值变量调用:
@validate_args
def func1(*, x1,y1,y2):
pass
@validate_args
def func2(*, x2,x5):
pass
就这样。打电话给你的方法
func1(x1=1,y1=2,y2=3,y3=4)
func2(x1=5, y3={'a':3})
使用可选参数的可能解决方案?看看*args和**kwargsuse
validate_inputs
作为一个decorator
,看起来更好。在使用**kwargs进行配置的过程中,有些输入必须是可选的吗?为什么不传递一个参数列表args=[x1,x2]
func_2(args)
并验证列表<代码>验证输入(参数)。如果您要对传递的任何值执行相同的验证,那么这就很好了。如果不是,可能需要更多的处理