python decorator模块_Python typecheck-decorator包_程序模块 - PyPI - 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异常

在运行时。

类类型、集合类型、固定长度集合和

类型谓词也可以被注释。

从python 3.5开始,pep 484指定注释应该是类型和

它们的正常使用将是类型检查。

许多高级类型(如Sequence[int])现在可以通过

typingmodule,它也可以在pypi上用于

Python3。

当前模块支持这些typing注释,但它早于

python 3.5,因此有其他形式的类型规范(通过类型

谓词)以及。

其中许多是等价的,但有些更强大。

下面是一个更复杂的示例:import typecheck as tc

@tc.typecheck

def foo2(record:(int,int,bool), rgb:tc.re("^[rgb]$")) -> tc.any(int,float) :

# don't expect the following to make much sense:

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的数字。

其中的第一个和第三个可以用typing注释表示为

好吧,第二个不是。最接近的近似是这样的:import typing as tg

import typecheck as tc

@tc.typecheck

def foo2(record:tg.Tuple[int,int,bool], rgb:str) -> tg.Union[int,float] :

"""rgb must be one of "r","g","b"."""

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 (but meant-to-be-too-long string is not detected)

foo2(None, "R") # Wrong: None is no tuple (but meant-to-be-illegal character is not detected)

其他类型的注释:tc.optional(int)或tg.Optional[int]将允许int和none,

tc.enum(1, 2.0, "three")允许定义特殊枚举类型,

tc.map_of(str, tc.list_of(Person))或

tg.Mapping[str, tg.MutableSequence[Person]]

描述字典或其他映射

键是字符串,所有值都是相同的人员列表,

等等。

对Cpython 3.3,3.4,3.5进行毒性测试。

欢迎加入QQ群-->: 979659372

推荐PyPI第三方库

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值