python 验证数据类型函数

在查看谷歌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)

能正确地抛出异常:

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值