如何编写通用"validate"方法来接收各种输入



我有几个函数有一些常见的输入:

func_1(x1, x2, x3, y1)
func_2(x1, x3, y2)
func_3(x1, x2, x3, y1, y3)

我想为所有输入编写输入错误处理代码(例如,如果x1None,则抛出异常(。我发现配置输入验证功能的方法是一个很好的选择,其中所有功能的所有输入都可以检查/验证

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

问题:我应该如何将validate_inputs配置为具有这样的"灵活"输入?

查看:

首先,编写一些验证器:

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..")

然后,将验证器保存在某个dict:中

validators = {'x1': validate_int,
'y1': validate_int,
'y3': validate_int,
'x2': validate_something}

编写一个decorator来验证args:

def validate_args(func):
def wrapper(*args, **kwargs):
for k,v in kwargs.items():
validators.get(k, lambda x: x)(v)
return wrapper

现在,您希望每个方法都经过封装验证,并使用键值vars:进行调用


@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})

最新更新