灵活的函数参数显式类型检查(仅限python3)
typecheck-decorator-stable的Python项目详细描述
函数的装饰符@tc.typecheck,与一起使用 python3函数参数和函数结果注释。 decorator将对函数的每个调用执行动态参数类型检查。
@tc.typecheck def foo1(a:int, b=None, c:str="mydefault") -> bool : print(a, b, c) return b is not None and a != b
部分:int、:str和-> bool是注释。 这是python 3中引入的语法特性,其中:(用于参数) 和->(对于结果)是分隔符,其余的可以是 任意表达。 理解这一点很重要, 注释没有任何语义。 一定有明确的python代码 它看着他们,做一些事情,以便给他们一个意义。
@tc.typecheckdecorator赋予上述注释以下含义: foo1的参数a必须具有类型int, b没有注释,可以有任何类型,它将不会被检查, c必须具有类型字符串, 函数的结果必须是 True(不是17或"yes"或[3,7,44]或诸如此类的)或 False(不是0或None或[]或诸如此类)。
如果任何参数的类型错误,将引发TypeCheckError异常。 类类型、集合类型、固定长度集合和 类型谓词也可以被注释。 下面是一个更复杂的示例:
import typecheck as tc @tc.typecheck def foo2(record:(int,int,bool), rgb:tc.re("^[rgb]$")) -> tc.any(int,float) : a = record[0]; b = record[1] return a/b if (a/b == float(a)/b) else float(a)/b foo2((4,10,True), "r") # OK foo2([4,10,True], "g") # OK: list is acceptable in place of tuple foo2((4,10,1), "rg") # Wrong: 1 is not a bool, string is too long foo2(None, "R") # Wrong: None is no tuple, string has illegal character
这些注释意味着record是由两个int和 实际的bool和rgb是一个单字符字符串,即 通过正则表达式测试“r”或“g”或“b”。 结果将是一个可以是int或float的数字。
其他类型的注释:
- tc.optional(int)将允许int和none,
- tc.enum(1, 2.0, "three")允许定义特殊枚举类型,
- tc.map_of(str, tc.list_of(Person))描述所有 键是字符串,所有值都是相同的人员列表,
- 等等。
文档可在 https://github.com/prechelt/typecheck-decorator