自python3.5開始,PEP484爲python引入了類型註解(type hints)html
官網typing詳細說明
typing類型標註python
int,long,float: 整型,長整形,浮點型函數
bool,str: 布爾型,字符串類型ui
List, Tuple, Dict, Set:列表,元組,字典, 集合this
Iterable,Iterator:可迭代類型,迭代器類型scala
Generator:生成器類型code
def test(a:int, b:str) -> str: print(a, b) return 1000 if __name__ == '__main__': test('test', 'abc')
函數test, a:int 指定了輸入參數a爲int類型, b:str b爲str類型, -> str 返回值爲srt類型。 能夠看到, 在方法中,咱們最終返回了一個int,此時pycharm就會有警告; 當咱們在調用這個方法時,參數a咱們輸入的是字符串,此時也會有警告; 但很是重要的一點是,pycharm只是提出了警告,但實際上運行是不會報錯,畢竟python的本質仍是動態語言
from typing import List Vector = List[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])
from typing import Dict, Tuple, Sequence ConnectionOptions = Dict[str, str] Address = Tuple[str, int] Server = Tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None: ... ): ...
這裏須要注意,元組這個類型是比較特殊的,由於它是不可變的。 因此,當咱們指定Tuple[str, str]時,就只能傳入長度爲2, 而且元組中的全部元素都是str類型
from typing import Sequence, TypeVar, Union T = TypeVar('T') # Declare type variable def first(l: Sequence[T]) -> T: # Generic function return l[0] T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes A = Union[str, None] # Must be str or None
from typing import NamedTuple class Employee(NamedTuple): name: str id: int = 3 employee = Employee('Guido') assert employee.id == 3
from typing import List def test(b: List[int]) -> str: print(b) return 'test' if __name__ == '__main__': test([1, 'a'])
從這個例子能夠看出來,雖然咱們指定了List[int]即由int組成的列表, 可是,實際中,只要這個列表中存在nt(其餘的能夠爲任何類型),就不會出現警告