moriga是什么意思iga在线翻译读音例句-达里娅 克里什娜
2023年4月3日发(作七夕节为什么是情人节 者:不是的拼音)
Python标准库之typing的⽤法(类型标注)
PEP3107引⼊了功能注释的语法,PEP484加⼊了类型检查
标准库typing为类型提⽰指定的运⾏时提供⽀持。
⽰例:
deff(a:str,b:int)->str:
returna*b
如果实参不是预期的类型:
但是,Python运⾏时不强制执⾏函数和变量类型注释。使⽤类型检查器,IDE,lint等才能帮助代码进⾏强制类型检查。
使⽤NewType创建类型
NewType()是⼀个辅助函数,⽤于向类型检查器指⽰不同的类型,在运⾏时,它返回⼀个函数,该函数返回其参数。
importtyping
Id=e(\"Id\",int)
a=Id(2020)
使⽤NewType()创建的类型会被类型检查器视为它的原始类型的⼦类。
回调(Callable)
将回调函数类型标注为Callable[[Arg1离骚原文一一对应翻译 Type,Arg2Type],ReturnType]。
fromtypingimportCallable
deff(a:int)->str:
returnstr(a)
defcallback(a:int,func:Callable[[int],str])-绝字开头的成语 >str:
returnfunc(a)
print(callback(1,f))
泛型
为容器元素添加预期的类型
fromtypingimportMapping
a:Mapping[str,str]
通过TypeVar进⾏参数化来约束⼀个类型集合:
fromtypingimportTypeVar
T=TypeVar(\'T\')#可以是任何东西。
A=TypeVar(\'A\',str,bytes)#必须是str或bytes
使⽤TypeVar约束⼀个类型集合,但不允许单个约束
例如:
T=TypeVar(\'T\',str)
这样会抛出⼀个异常TypeError:Asingleconstraintisnotallowed
typing包含的类型
AbstractSet=ctSet
Any=
AnyStr=~AnyStr
AsyncContextManager=ctAsyncContextManager
AsyncGenerator=enerator
AsyncIterable=terable
AsyncIterator=terator
Awaitable=ble
ByteString=ring
Callable=le
ClassVar=ar
Collection=tion
Container=ner
ContextManager=ctContextManager
Coroutine=ine
Counter=r
DefaultDict=tDict
Deque=
Dict=
FrozenSet=Set
Generator=tor
Hashable=le
ItemsView=iew
Iterable=le
Iterator=or
KeysView=ew
List=
Mapping=g
MappingView=gView
MutableMapping=eMapping
MutableSequence=eSequence
MutableSet=eSet
NoReturn=rn
Optional=al
Reversible=ible
Sequence=ce
Set=
Sized=
TYPE_CHECKING=False
Tuple=
Type=
Union=
ValuesView=View
typing-python⽤于类型注解的库
简介
动态语⾔的灵活性使其在做⼀些⼯具,脚本时⾮常⽅便,但是同时也给⼤型项⽬的开发带来了⼀些⿇烦。
⾃python3.5开始,PEP484为python引⼊了类型注解(typehints),虽然在定义了函数注释(functionannotation)的语法,但仍然故
意留下了⼀些未定义的⾏为.现在已经拥有许多对于静态类型的分析的第三⽅⼯具,⽽pep484引⼊了⼀个模块来提供这些⼯具,
同时还规定⼀些不能使⽤注释(annoation)的情况
#⼀画龙点睛造句 个典型的函数注释例⼦,为参数加上了类型
defgreeting(name:str)->str:
return\'Hello\'+name
伴随着python3.6的pep526则更进⼀步引⼊了对变量类型的声明,和在以前我们只能在注释中对变量的郭永怀 类型进⾏说明
#使⽤注释来标明变量类型
primes=[]#type:list[int]
captain=...#type:str
classStarship:
stats={}#type:Dict[str,int]
primes:List[int]=[]
captain:str#Note:noinitialvalue
classStarship:
stats:ClassVar[Dict[str,int]]={}
typing--对于typehints⽀持的标准库
typing模块已经被加⼊标准库的provisionalbasis中,新的特性可能会增加,如果开发者认为有必要,api也可能会发⽣改变,
即不保证向后兼容性
我们已经在简介中介绍过类型注解,那么除了默认类型的int、str⽤于类型注解的类型有哪些呢?
typing库便是⼀个帮助我们实现类型注解的库
类型别名(typealias)
在下⾯这个例⼦中,Vector和List[float]可以视为同义词
fromtypingimportList
Vector=List[float]
defscale(scalar:float,vector:Vector)->Vector:
return[scalar*numfornuminvector]
new_vector=scale(2.0,[1.0,-4.2,5.4])
类型别名有助于简化⼀些复杂的类型声明
fromtypingimportDict,Tuple,List
ConnectionOptions=Dict[str,str]
Address=Tuple[str,int]
Server=Tuple[Address,ConnectionOptions]
defbroadcast_message(message:str,servers:List[Server])->None:
...
#Thestatictypecheckerwilltreattheprevioustypesignatureas
#beingexactlyequivalenttothisone.
defbroadcast_message(
message:str,
servers:List[Tuple[Tuple[str,int],Dict[str,str]]])->None:
pass
新类型(NewType)
使⽤NewType来辅助函数创造不同的类型
formtypingimportNewType
UserId=NewType(\"UserId\",int)
some_id=UserId(524313)
静态类型检查器将将新类型视为原始类型的⼦类。这对于帮助捕获逻辑错误⾮常有⽤
defget_user_name(user_id:UserId)->str:
pass
#typechecks
user_a=get_user_name(UserId(42351))
#doesnottypecheck;anintisnotaUserId
user_b=get_user_name(-1)
你仍然可以使⽤int类型变量的所有操作来使⽤UserId类型的变量,但结果返回的都是都是int类型。例如
#output仍然是int类型⽽不是UserId类型
output=UserId(23413)+UserId(54341)
虽然这⽆法阻⽌你使⽤int类型代替UserId类型,但可以避免你滥⽤UserId类型
注意,这些检查仅仅被静态检查器强制检查,在运⾏时Derived=NewType(\'Derived\',base)将派⽣出⼀个函数直接返回你传的
任何参数,这意味着Derived(some_value)并不会创建任何新类或者创建任何消耗⼤于普通函数调⽤消耗的函数
确切地说,这个表达式some_valueisDerived(some_value)在运⾏时总是对的。
这也意味着不可能创建派⽣的⼦类型,因为它在运⾏时是⼀个标识函数,⽽不是⼀个实际类型:
fromtypingimportNewType
UserId=NewType(\'UserId\',int)
#Failsatruntimeanddoesnottypecheck
classAdminUserId(UserId):pass
然⽽,它可以创建⼀个新的类型基于衍⽣的NewType
fromtypingimportNewType
UserId=NewType(\'UserId\',int)
ProUserId=NewType(\'ProUserId\',UserId)
然后对于ProUserId的类型检查会如预料般⼯作
Note:回想⼀下,使⽤类型别名声明的两个类型是完全⼀样的,令Doing=Original将会使静态类型检查时把Alias等同于
Original,这个结论能够帮助你简化复杂的类型声明
与Alias不同,NewType声明了另⼀个的⼦类,令Derived=NewType(\'Derived\',Original)将会使静态类型检查把Derived看做
Original的⼦类,这意味秋风词李白原文 着类型Original不能⽤于类型Derived,这有助于使⽤最⼩的消耗来防⽌逻辑错误。
回调(callable)
回调函数可以使⽤类似Callable[[Arg1Type,Arg2Type],ReturnType]的类型注释
例如
fromtypingimportCallable
deffeeder(get_next_item:Callable[[],str])->None:
#Body
defasync_query(on_success:Callable[[int],None],
on_error:Callable[[int,Exception],None])->None:
#Body
可以通过对类型提⽰中的参数列表替换⼀个⽂本省略号来声明⼀个可调⽤的返回类型,⽽不指定调⽤参数,例如Callable[...,
ReturnType]
泛型(Generics)
因为容器中的元素的类型信息由于泛型不同通过⼀般⽅式静态推断,因此抽象类被⽤来拓展表⽰容器中的元素
fromtypingimportMapping,S人至察则无徒 equence
defnotify_by_email(employees:Sequence[Employee],
overrides:Mapping[str,str])->None:...
可以通过typing中的TypeVar将泛型参数化
fromtypingimportSequence,TypeVar
T=TypeVar(\'T\')#申明类型变量
deffirst(l:Sequence[T])->T:#Genericfunction
returnl[0]
⽤户定义泛型类型
fromtypingimportTypeVar,Generic
fromloggingimportLogger
T=TypeVar(\'T\')
classLoggedVar(Generic[T]):
def__init__(self,value:T,name:str,logger:Logger)->None:
=name
=logger
=value
defset(self,new:T)->None:
(\'Set\'+repr())
=new
defget(self)->T:
(\'Get\'+repr())
deflog(sel关于描写春天的优美句子 f,message:str)->None:
(\'%s:%s\',,message)
定义了Generic[T]作为LoggedVar的基类,同时T也作为了⽅法中的参数。
通过Generic基类使⽤元类(metaclass)定义__getitem__()使得LoggedVar[t]是有效类型
fromtypingimportIterable
defzero_all_vars(vars:Iterable[LoggedVar[int]])->None:
forvarinvars:
(0)
泛型可以是任意类型的变量,但也可以被约束
fromtypingimportTypeVar,Generic
...
T=TypeVar(\'T\')
S=TypeVar(\'S\',int,str)
classStrangePair(Generic[T,S]):
...
每个类型变量的参数必须是不同的
下⾯是⾮法的
fromtypingimportTypeVar,Generic
...
T=TypeVar(\'T\')
classPair(Generic[T,T]):#INVALID
...
你可以使⽤Generic实现多继承
fromtypingimportTypeVar,Generic,Sized
T=TypeVar(\'T\')
classLinkedList(Sized,Generic[T]):
...
当继承泛型类时,⼀些类型变量可以被固定
fromtypingimportTypeVar,Mapping
T=TypeVar(\'T\')
classMyDict(Mapping[str,T]):
...
使⽤泛型类⽽不指定类型参数则假定每个位置都是Any,。在下⾯的例⼦中,myiterable不是泛型但隐式继承Iterable[Any]
fromtypingimportIterable
classMyIterable(Iterable):#SameasIterable[Any]
还⽀持⽤户定义的泛型类型别名。实例:
fromtypingimportTypeVar,Iterable,Tuple,Union
S=TypeVar(\'S\')
Response=Union[Iterable[S],int]
#ReturntypehereissameasUnion[Iterable[str],int]
defresponse(query:str)->Response[str]:
...
T=TypeVar(\'T\',int,float,complex)
Vec=Iterable[Tuple[T,T]]
definproduct(v:Vec[T])->T:#SameasIterable[Tuple[T,T]]
returnsum(x*yforx,yinv)
Generic的元类是a的⼦类,泛型类可以是包含抽象⽅法或属性的ABC类(AgenericclasscanbeanABCby
includingabstractmethodsorproperties)
同时泛型类也可以含有ABC类的⽅法⽽没有元类冲突。
Any
⼀种特殊的类型是。静态类型检查器将将每个类型视为与任何类型和任何类型兼容,与每个类型兼容。
fromtypingimportAny
a=None#type:Any
a=[]#OK
a=2#OK
s=\'\'#type:str
s=a#OK
deffoo(item:Any)->int:
#Typechecks;\'item\'couldbeanytype,
#andthattypemighthavea\'bar\'method
()
...
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
更多推荐
newtype是什么意思type在线翻译读音例句
发布评论