Python3.5 开始支持类型注解(type hints,PEP 484),用来限定方法参数类型、返回值类型、变量类型等
介绍
- 作用:类型提示,不影响程序的运行,编辑器会提示错误
- 常见类型
int
整型
long
长整形
float
浮点型
bool
布尔型
str
字符串类型
- typing 定义了支持的类型
Any
任意类型
List
列表
Tuple
元组
Dict
字典
Set
集合
Iterable
可迭代类型
Iterator
迭代器类型
Generator
生成器类型
- 等
- 可以使用 python
mypy
来检查
示例
a: int = 521
b: str = 'xyz'
def add(x:int, y:int) -> int:
return x + y
from typing import Tuple
def function() -> Tuple[str, int]:
return "abc", 1
from typing import List
alist: List[int] = [5, 2, 1]
from typing import TypeVar
T = TypeVar('T') # Declare type variable
# https://github.com/x-actions/python3-cisctl/blob/main/cisctl/api/__init__.py#L27
def sort_tags(self, name) -> (bool, List[Tuple[str, int]], Dict):
def set(name: str, ok: bool = False, abc: Union[ExpiryT, None] = None):
...
# (true, ['s11', 's12', ...], ['s21', 's22', ...])
Tuple[bool, List[str], List[str]]