• 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代码的可读性和维护性,特别是在大型项目和团队合作中,它们可以帮助开发者更明确地表达意图并提早发现潜在的错误。

  • 相关阅读:
    想要精通算法和SQL的成长之路 - 填充书架
    [附源码]计算机毕业设计springboot小区物业管理系统
    推导式(生成式)
    c++文件操作
    计算机毕业设计Java校园资料分享平台(系统+源码+mysql数据库+lw文档)
    推荐一个拥有386万订阅者,10000多免费学习视频的频道
    【今日文章】:1.关于 $attr $lisenner $slot 用法的思考 2. 关于父子组件传值的思考 3.关于前端日志系统搭建的思考
    go 指针
    初识Java 18-2 泛型
    Android修行手册 - Activity 在 Java 和 Kotlin 中怎么写构造参数
  • 原文地址:https://blog.csdn.net/weixin_49520696/article/details/134277997