Python3.5 开始支持类型注解(type hints,PEP 484),用来限定方法参数类型、返回值类型、变量类型等
介绍
- 作用:类型提示,不影响程序的运行,编辑器会提示错误
- 常见类型
int整型long长整形float浮点型bool布尔型str字符串类型
- typing 定义了支持的类型
Any任意类型,item: AnyList列表Tuple元组Dict字典Set集合Iterable可迭代类型Iterator迭代器类型Generator生成器类型- 等
- 指定类型时,也可以使用
list、set、dict、tuple
- 可以使用 python
mypy来检查
示例
- 变量定义注解
a: int = 521
b: str = 'xyz'- 函数参数和返回值注解
def add(x:int, y:int, z: bool or str) -> int:
return x + yfrom typing import Tuple
def function() -> Tuple[str, int]:
return "abc", 1- 自定义类型(Python 3.6 开始支持)
from typing import List
alist: List[int] = [5, 2, 1]vector = List[int]
alist: vector = [5, 2, 1]
# 等价于
alist: List[int] = [5, 2, 1]- 泛型
from typing import TypeVar
T = TypeVar('T') # Declare type variable- 同一个参数多个返回值类型
def int_or_str(arg: int | str) -> None:- 复合类型
# 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):- 定义函数参数类型和默认值
Union联合类型Union[int, str]表示既可以是int,也可以是str;等价于vars: [int or str]
def set(name: str, ok: bool = False, abc: Union[ExpiryT, None] = None):
...
# (true, ['s11', 's12', ...], ['s21', 's22', ...])
Tuple[bool, List[str], List[str]]- 任意类型
T = TypeVar('T')
def test(name: T) -> T:
print(name)
return name
test(11)Callable可调用类型
# True or False
isinstance(<obj>, Callable)
# 函数定义
def print_name(name: str):
print(name)
# Callable 作为函数参数使用时有类型检查的作用,检查传入的参数值 get_func 是否为可调用对象
# 第一个类型(str)代表参数类型
# 第二个类型(None)代表返回值类型
def get_name(get_func: Callable[[str], None]):
return get_func
vars = get_name(print_name)
vars("test")- 类
class Person:
def __init__(self, name: str):
self.name = name
def hello(p: Person) -> str:
return f'Hello, {p.name}'