Python3 类型注解

发布时间: 更新时间: 总字数:294 阅读时间:1m 作者: 分享 复制网址

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
  • 自定义类型(Python 3.6 开始支持)
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]]
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数