带有特征的强烈类型暗示
typen的Python项目详细描述
带有特征的强烈类型暗示
这个包提供了简单的修饰符,用于在函数参数和返回类型上强制执行Python类型提示。在
fromtypenimportenforce_type_hints@enforce_type_hintsdefhalve_integer(a:int)->float:returna/2halve_integer(5)# 2.5halve_integer(5.0)# ParameterTypeError^{pr2}$
特征类型提示
Trait类型也可用于定义类型提示中的复杂模式
fromtraits.apiimportArray,Either,Enum,Instance,Int,Str,Tuple@enforce_type_hintsdefcomplicated_function(a:Either(Str,Int),# Either a string or an intb:Enum(2,5,"foo"),# One of a specific set of valuesc:Instance(MyClass),# Class instancesd:Array(size=(None,2)),# Numpy array validation)->Tuple(Str,Either(Str,Int)):# Complicated return specification...
严格执行
类型提示也可以与@strict_type_hints
修饰符一起使用。以下两个示例都将在首次调用函数时引发异常。没有严格的强制,没有类型提示的参数和返回值可以有任何值。在
fromtypenimportstrict_type_hints@strict_type_hintsdefadd_numbers(a,b:float)->float:returna+badd_numbers(1,2)# UnspecifiedParameterTypeError
@strict_type_hintsdefadd_numbers(a:float,b:float):returna+badd_numbers(1,2)# UnspecifiedReturnTypeError
压缩args和kwargs
打包参数上的类型提示适用于通过该打包传递的所有值。在
@enforce_type_hintsdeffoos_vs_bars(*foos:int,**bars:str)->bool:returnsum(foos)>=len(bars)foos_vs_bars(1,2,3,a="a",b="b",c="c")# Truefoos_vs_bars(2,3,5,d=4)# ParameterTypeErrorfoos_vs_bars(2,"three",5,e="e")# ParameterTypeError
方法装饰
方法也可以修饰。^{{strict}是从cd2>类型的引用中排除的。@enforce_type_hints
和{@classmethod
或{
classExClass:@strict_type_hintsdef__init__(self,a:int,b:int):...@strict_type_hints@classmethoddefa_class_method(cls,a:int,c:int)->int:...@strict_type_hints@staticmethoddefa_static_method(a:int,c:int)->int:...
胁迫
值是基于Trait type coercion强制给类型的。铸造行为不会添加到函数中:
@enforce_type_hintsdefadd_numbers(a:float,b:float)->float:returna+btype(add_numbers(1,2))# int
正在从ReturnTypeError
恢复
因为必须执行函数来强制执行返回值,所以无效值存储在异常中。这使得可以编程地从ReturnTypeError
恢复。在
fromtypen.exceptionsimportReturnTypeError@enforce_type_hintsdefgive_int(a)->int:returnatry:give_int("a")exceptReturnTypeErroraserr:print(err.return_value)# a
- 项目
标签: