python 验证数据类型函数

 2023-09-11 阅读 24 评论 0

摘要:在查看谷歌API类时发现这个函数,发现有问题,先上原函数: 1 def ValidateTypes(vars_tpl): 2 """Checks that each variable in a set of variables is the correct type. 3 4 Args: 5 vars_tpl: A tuple containing a set of variables to check. 6 7 Rais

在查看谷歌API类时发现这个函数,发现有问题,先上原函数:

 1 def ValidateTypes(vars_tpl):
 2   """Checks that each variable in a set of variables is the correct type.
 3 
 4   Args:
 5     vars_tpl: A tuple containing a set of variables to check.
 6 
 7   Raises:
 8     ValidationError: The given object was not one of the given accepted types.
 9   """
10   for var, var_types in vars_tpl:
11     if not isinstance(var_types, tuple):
12       var_types = (var_types,)
13     for var_type in var_types:
14       if isinstance(var, var_type):
15         return
16     msg = ('The \'%s\' is of type %s, expecting one of %s.'
17            % (var, type(var), var_types))
18     raise ValidationError(msg)
19 
20 
21  d = {'d':1}
22  e = (1,2,3)
23  ValidateTypes(((d, dict), (e, list)))

任何数据类型都可以通过转化函数?代码通过验证,本来e是tuple,用来验证的类是list,应该抛错才对,因为15行那里用了return返回,所以后面的验证不再进行。

修改后的函数如下:

 1 def ValidateTypes(vars_tpl):
 2   """Checks that each variable in a set of variables is the correct type.
 3 
 4   Args:
 5     vars_tpl: A tuple containing a set of variables to check.
 6 
 7   Raises:
 8     ValidationError: The given object was not one of the given accepted types.
 9   """
10   if not isinstance(vars_tpl, tuple):
11     raise ValidationError("vars_tpl argument must be tuple")
12   for var, var_types in vars_tpl:
13     if not isinstance(var_types, tuple):
14       var_types = (var_types,)
15     msg = ('The \'%s\' is of type %s, expecting one of %s.'
16            % (var, type(var), var_types))
17 
18     for var_type in var_types:
19       if not isinstance(var, var_type):
20         raise ValidationError(msg)

能正确地抛出异常:

 

这个函数非常灵活,以后项目中能用上的地方非常多,呵呵~

转载于:https://www.cnblogs.com/bjdxy/archive/2012/11/13/2768464.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/46463.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息