Python 3.10 新增功能


本文解释了 Python 3.10 中与 3.9 相比的新特性。
带括号的上下文管理器:
现在支持使用括号在上下文管理器中跨多行继续。这允许以类似于以前使用 import 语句可能的方式在多行中格式化一长串上下文管理器。例如,所有这些示例现在都有效:

with (CtxManager() as example):
    ...

with (
    CtxManager1(),
    CtxManager2()
):
    ...

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

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

with (
    CtxManager1() as example1,
    CtxManager2() as example2
):
    ...

with (
    CtxManager1() as example1,
    CtxManager2() as example2,
    CtxManager3() as example3,
):

这种新语法使用了新解析器的非 LL(1) 能力。查看PEP 617了解更多详情。
 
结构模式匹配
增加match和case语句实现结构模式匹配,模式匹配使程序能够从复杂的数据类型中提取信息,在数据结构上进行分支,并根据不同形式的数据应用特定的操作。
模式匹配的通用语法是:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

match 语句采用表达式并将其值与作为一个或多个 case 块给出的连续模式进行比较。具体来说,模式匹配通过以下方式运作:

  1. 使用具有类型和形状的数据 (the subject)
  2. 评估subject的match声明
  3. case从上到下将主题与语句中的每个模式进行比较,直到确认匹配为止。
  4. 执行与确认匹配的模式相关联的操作
  5. 如果未确认完全匹配,则最后一种情况,通配符_(如果提供)将用作匹配情况。如果未确认完全匹配且不存在通配符大小写,则整个匹配块为空操作。

简单模式:匹配文字
让我们把这个例子看作是最简单形式的模式匹配:一个值,主题,与几个文字匹配,模式。在下面的示例中,status是 match 语句的主题。模式是每个 case 语句,其中文字表示请求状态代码。匹配后执行与案例相关的操作:
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return
"Not found"
        case 418:
            return
"I'm a teapot"
        case _:
            return
"Something's wrong with the internet"

如果上述函数传递了status418 的a ,则返回“我是茶壶”。如果上面的函数传递了status500 的 a,则 case 语句 with _将作为通配符匹配,并返回“互联网出现问题”。请注意最后一个块:变量名称 "_" 充当通配符并确保始终匹配。
您可以使用|(“or”)在单个模式中组合多个文字:

case 401 | 403 | 404:
    return "Not allowed"

结合类使用:
class Point:
    x: int
    y: int

def location(point):
    match point:
        case Point(x=0, y=0):
            print("Origin is the point's location.")
        case Point(x=0, y=y):
            print(f
"Y={y} and the point is on the y-axis.")
        case Point(x=x, y=0):
            print(f
"X={x} and the point is on the x-axis.")
        case Point():
            print(
"The point is located somewhere else on the plane.")
        case _:
            print(
"Not a point")

可以在模式中添加一个if子句,称为“守卫Guard”。如果守卫为假,match则继续尝试下一个案例块。

match point:
    case Point(x, y) if x == y:
        print(f"The point is located on the diagonal Y=X at {x}.")
    case Point(x, y):
        print(f
"Point is not on the diagonal.")


更多点击标题