• Python的高级用法:类型注解


    类型注解是在Python中用于指明变量、函数参数和返回值等应有的数据类型的语法。类型注解的引入,尤其是通过PEP 484,为Python带来了一种可选的、正式的类型指定方法。这有助于静态类型检查工具、IDE、文档生成工具和其他工具更好地理解代码。

    typing模块

    typing模块是类型注解的核心,提供了许多构建类型提示的工具。它为标准Python数据类型提供了泛型版本,并引入了新的类型,如Union, Optional, Tuple, Callable等。

    示例类型注解

    变量注解

    from typing import List, Set, Dict, Tuple
    
    # 注解表示:变量numbers是整数列表
    numbers: List[int] = [1, 2, 3]
    
    # 注解表示:变量unique_names是包含字符串的集合
    unique_names: Set[str] = {"John", "Jane", "Jack"}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    函数参数和返回值注解

    from typing import Dict, List, Optional
    
    # 注解表示:函数接受字符串和整数列表,返回整数
    def process_data(name: str, data: List[int]) -> int:
        # 处理数据
        return sum(data)
    
    # 注解表示:函数返回值可能是字符串,也可能是None
    def fetch_data(key: str) -> Optional[str]:
        # 获取数据逻辑
        return "some data" if key == "valid_key" else None
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    复杂类型注解

    from typing import Union, Callable, Tuple
    
    # 注解表示:变量可以是整数或浮点数
    number: Union[int, float] = 3.14
    
    # 注解表示:函数接受一个函数作为参数,该函数接受整数并返回字符串
    def run_function(func: Callable[[int], str], value: int) -> None:
        result = func(value)
        print(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    新的类型提示特性(Python 3.8+)

    从Python 3.8开始,typing模块引入了更多高级特性,如Literal, TypedDict, Protocol等。这些特性为类型提示提供了更细致的控制。

    字面量类型(Literal)

    from typing import Literal
    
    def operate_machine(mode: Literal['on', 'off']) -> None:
        # 函数体
        pass
    
    operate_machine('on')  # 正确
    operate_machine('nope')  # 错误,静态类型检查器将报错
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    类型别名

    from typing import Dict, Tuple, List
    
    # 定义类型别名
    Vector = List[float]
    
    # 使用类型别名注解变量
    position: Vector = [1.2, 3.4, 5.6]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    typing模块和Python 3.9+

    从Python 3.9开始,很多来自typing模块的类型提示可以直接使用Python标准集合类的内置泛型。例如,List[T]可以简写为list[T]

    from typing import Union
    
    # Python 3.9之前的写法
    def square(number: Union[int, float]) -> Union[int, float]:
        return number * number
    
    # Python 3.9+ 的写法
    def square(number: int | float) -> int | float:
        return number * number
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    类型注解和typing模块大大提升了Python代码的可读性和维护性,特别是在大型项目和团队合作中,它们可以帮助开发者更明确地表达意图并提早发现潜在的错误。

  • 相关阅读:
    React.js学习(一):设计并实现一个“任务清单列表”
    《向量数据库指南》——Milvus Cloud当初为什么选择向量数据库这个赛道呢?
    按字寻址和按字节寻址
    冒泡排序 和 选择排序
    [ Skill ] load 函数优化,识别相对路径
    华为od项目
    分析谐波失真
    后端开发怎么做得更优秀?记住这15个好习惯
    【LeetCode】54. 螺旋矩阵
    高校教务系统登录页面JS分析——华东交通大学
  • 原文地址:https://blog.csdn.net/weixin_49520696/article/details/134277997