python 验证数据类型函数
2012-11-13 17:59
316 查看
在查看谷歌API类时发现这个函数,发现有问题,先上原函数:
代码通过验证,本来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. """ 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)
能正确地抛出异常:
这个函数非常灵活,以后项目中能用上的地方非常多,呵呵~
相关文章推荐
- Python数据类型和相关函数方法
- JavaScript常用工具函数(验证数据格式、清除空格、判断浏览器类型、cookie操作等)
- Python基础:数据类型、变量定义、输入/输出、逻辑、函数/模块(导入)/类、异常处理
- python通过装饰器检查函数参数数据类型的方法
- [python-1]数据类型、控制流语句、模块、函数和类
- 【Python】数据类型转换相关函数大集合
- 【python 】数据类型和返回数据类型的函数
- python下的数据类型转换的函数
- Python全栈开发之3、数据类型set补充、深浅拷贝与函数
- python -- numpy 基本数据类型,算术运算,组合,分割 函数
- Python数据类型之间的转换 函数 描述 int(x [,base]) 将x转换为一个整数 long(x [,base] ) 将x转换为一个长整数 float(x) 将x转换到一个浮点数
- python 学习笔记(3) 各种数据类型常用的函数
- C++与Python的混合编程-调用有参函数以及C++数据类型与Python数据类型间的转换
- 函数名function是一个数据类型,可以赋值 分类: python基础学习 2013-09-12 11:01 366人阅读 评论(0) 收藏
- python数据类型和3个重要函数
- Python成长之路第二篇(1)_数据类型内置函数用法
- Python基础数据类型-函数传参详解
- Python3.X基础语法(数据类型/对象引用/组合数据类型/逻辑操作符/控制流语句/算数操作符/输入输出/函数创建和引用)001
- python 函数定义和内置函数isinstance以及数据类型检查type的使用
- Python成长之路第二篇(1)_数据类型内置函数用法