您的位置:首页 > 编程语言 > Python开发

python 验证数据类型函数

2012-11-13 17:59 316 查看
在查看谷歌API类时发现这个函数,发现有问题,先上原函数:

def ValidateTypes(vars_tpl):
"""Checks that each variable in a set of variables is the correct type.

Args:
vars_tpl: A tuple containing a set of variables to check.

Raises:
ValidationError: The given object was not one of the given accepted types.
"""
for var, var_types in vars_tpl:
if not isinstance(var_types, tuple):
var_types = (var_types,)
for var_type in var_types:
if isinstance(var, var_type):
return
msg = ('The \'%s\' is of type %s, expecting one of %s.'
% (var, type(var), var_types))
raise ValidationError(msg)

d = {'d':1}
e = (1,2,3)
ValidateTypes(((d, dict), (e, list)))


代码通过验证,本来e是tuple,用来验证的类是list,应该抛错才对,因为15行那里用了return返回,所以后面的验证不再进行。

修改后的函数如下:

def ValidateTypes(vars_tpl):
"""Checks that each variable in a set of variables is the correct type.

Args:
vars_tpl: A tuple containing a set of variables to check.

Raises:
ValidationError: The given object was not one of the given accepted types.
"""
if not isinstance(vars_tpl, tuple):
raise ValidationError("vars_tpl argument must be tuple")
for var, var_types in vars_tpl:
if not isinstance(var_types, tuple):
var_types = (var_types,)
msg = ('The \'%s\' is of type %s, expecting one of %s.'
% (var, type(var), var_types))

for var_type in var_types:
if not isinstance(var, var_type):
raise ValidationError(msg)


能正确地抛出异常:



这个函数非常灵活,以后项目中能用上的地方非常多,呵呵~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐