Python 类型注解

类型注解描述

Python 3.5 版本后引入 Typing 模块为 Python 静态类型注解提供了支持。其只要作用于增强代码可读性和维护性,并不影响代码运行

静态类型检查

Python 的类型注解本身不进行类型检查,但是可以借助第三方工具对代码中的静态类型进行检查,常用的静态类型检查有 mypy 和 pyright(适用于 Vscode 编辑器)

类型注解语法

arg_type 代表参数类型,return_type 代表返回值类型

def example(arg1: arg_type) -> return_type:
    return xxx

类型注解

内置类型

str 为字符串类型,int 为整数类型,float 为浮点数类型,bool 为布尔类型

def test(arg1: str, arg2: int, arg3: float, arg4: bool):
    pass

List 类型

入参 arg1 为 List 列表类型,列表中的每个元素都为 int 整数类型,同时返回为为 None

from typing import List

def test(arg1:List[int]) -> None:
    pass

Dict 类型

入参 arg1 为 Dict 字典类型,字典中的元素的键为 str 类型,值为 int 类型,同时返回为为 None

from typing import Dict

def test(arg1: Dict[str, int]) -> None:
    pass

Tuple 类型

入参 arg1 为 Tuple 元组类型,元组中的每个元素都为 str 类型,同时返回为为 None

from typing import Tuple

def test(arg1: Tuple[str]) -> None:
    pass

Set 类型

入参 arg1 为 Set 集合类型,集合中的每个元素都为 int 类型,同时返回为为 None

from typing import Set

def test(arg1: Set[int]) -> None:
    pass

Any 类型

入参 arg1 为 Any 类型,该参数可以是任何类型的数据,同时返回为为 None

from typing import Any

def test(arg1: Any) -> None:
    pass

Union 类型

入参 arg1 为 Union 类型,标识该参数可以接收多种类型,同时返回为为 None

from typing import Union

def test(arg1: Union[int, str, float]) -> None:
    pass

Optional 类型

入参 arg1 为 Optional 类型,标识该参数可以是指定类型或者 None,同时返回为为 int

from typing import Optional

def test(arg1: Optional[str]) -> int:
    pass



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • SNAT和DNAT
  • Clickhouse Drop表过大异常
  • Jmeter使用指南
  • Excel导入图片URL并显示图片
  • Shell命令汇总