1.4.4. Python 3.10(2021/10/04)

新特性

  1. 结构模式匹配(Pattern Matching)

    • 模式匹配使得程序能够从复杂的数据类型中提取信息、根据数据结构实现分支,并基于不同的数据形式应用特定的动作

    • 引入了结构模式匹配语法,通过 matchcase 关键字进行模式匹配。例如:

    def match_example(value):
       match value:
           case 1 | 2 | 3: # 使用 | (“ or ”)在一个模式中组合几个字面值
               print("Value is 1")
           case str(s) if len(s) > 10:
               print(f"String is longer than 10 characters: {s}")
           case str(s):
               print(f"String is {len(s)} characters long: {s}")
           case _:
               print("Value is something else")
    
    # 测试 match_example 函数
    match_example(1)        # 输出: Value is 1
    match_example("hello")  # 输出: String is 5 characters long: hello
    match_example("this is a very long string")  # 输出: String is longer than 10 characters: this is a very long string
    match_example(3.14)     # 输出: Value is something else
    
  2. 带圆括号的上下文管理器

    • 使用外层圆括号来使多个上下文管理器可以连续多行地书写(类似import这种多行的形式)

    with (CtxManager() as example):
        ...
    with (
        CtxManager1(),
        CtxManager2()
    ):
        ...
    

新的类型标注特性

  1. 更好的错误消息

    • 改进了解析器和运行时错误的错误消息,使其更加清晰和易于理解。

  2. 类型提示的改进

    • 提升了对类型提示的支持和功能,包括对 TypedDict 的增强和新的类型操作符。

  3. 更灵活的字符串格式化

    • 改进了 f-string 的功能,支持新的转义序列和表达式。

  4. 新的 zoneinfo 模块

    • 引入了 zoneinfo 模块,用于处理时区信息,替代了 datetime.timezonedateutil.tz

  5. 改进的错误处理

    • 引入了 except 关键字的新用法,支持在 except 子句中直接访问异常实例。

  6. 性能优化

    • 提升了解释器的性能和效率,特别是在解析和运行某些类型的代码时。

  7. 其它改进和优化

    • 包括语法改进、标准库的增强和对特定功能的修复。

Python 3.10 带来了许多新特性和改进,进一步提升了语言的功能和性能,增强了开发者的编程体验。