def greeting(name: str) -> str:
return 'Hello ' + name
复杂类型typing:
from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
from typing import Dict, Tuple, Sequence
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
自定义类型:
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
简单的类型注解:
def add(a: int) -> int:
return a + 1
复杂的类型:
这个时候就要借助typing
模块
List[str]
:表示由str类型组成的列表
Tuple[int, int. int]
表示由int类型的元素组成的长度为3的元组
from typing import List, Tuple, Dict
names: List[str] = ['Germey', 'Guido']
version: Tuple[int, int, int] = (3, 7, 4)
operations: Dict[str, bool] = {'show': False, 'sort': True}
list
var: List[int or float] = [2, 3.5]
var: List[List[int]] = [[1, 2], [2, 3]]
tuple
person: Tuple[str, int, float] = ('Mike', 22, 1.75)
Dict
def size(rect: Mapping[str, int]) -> Dict[str, int]:
return {'width': rect['width'] + 100, 'height': rect['width'] + 100}
sequence
当我们不需要严格区分一个变量是list还是tuple的时候
def square(elements: Sequence[float]) -> List[float]:
return [x ** 2 for x in elements]
NoReturn
当一个方法没有返回结果时:
def hello() -> NoReturn:
print('hello')
TypeVar
可以借助它来自定义兼容特定类型的变量,比如int,float,None都是符合要求的。
Height = TypeVar('Height', int, float, None)
def get_height() -> Height:
return height
Callable
可调用类型,用来注解一个方法
def date(year: int, month: int, day: int) -> str:
return f'{year}-{month}-{day}'
def get_date_fn() -> Callable[[int, int, int], str]:
return date