less than 1 minute read

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

Updated:

Leave a comment