我试图理解Python 3.10中新的structural pattern matching语法.我知道可以匹配如下文字值:

def handle(retcode):
    match retcode:
        case 200:
            print('success')
        case 404:
            print('not found')
        case _:
            print('unknown')

handle(404)
# not found

但是,如果我重构这些值并将其移动到模块级变量,就会导致错误,因为这些语句现在表示的是 struct 或模式,而不是值:

SUCCESS = 200
NOT_FOUND = 404

def handle(retcode):
    match retcode:
        case SUCCESS:
            print('success')
        case NOT_FOUND:
            print('not found')
        case _:
            print('unknown')

handle(404)
#  File "<ipython-input-2-fa4ae710e263>", line 6
#    case SUCCESS:
#         ^
# SyntaxError: name capture 'SUCCESS' makes remaining patterns unreachable

有没有办法使用match语句来匹配存储在变量中的值?

推荐答案

如果要测试的常量是虚线名称,则应将其视为常量,而不是用于捕获的变量的名称(参见PEP 636 # Matching against constants and enums):

class Codes:
    SUCCESS = 200
    NOT_FOUND = 404

def handle(retcode):
    match retcode:
        case Codes.SUCCESS:
            print('success')
        case Codes.NOT_FOUND:
            print('not found')
        case _:
            print('unknown')

尽管如此,考虑到python试图实现pattern-matching的方式,我认为在这种情况下,在判断常量值时使用if/elif/else塔可能更安全、更清晰.

Python-3.x相关问答推荐

以编程方式关闭jupyterlab内核

我不能使用拆分来分隔数据

如何使用魔杖扭曲图像

在 sum() 中将字符串转换为 int (或 float)

与 pandas 0.22 相比,pandas 2.0.3 中的 df.replace() 会抛出 ValueError 错误

Pandas教程:如何更新行内数值的位置

「Python Pandas」多级索引列和行匹配,如果列和行名称相似,则排除这些单元格中的值添加

三重奏:为什么频道被记录为使用async with,而不是with?

来自嵌套字典的完整地址

包含值超出范围的 ID 的新 DataFrame 列?

如何通过 GitLab V4 api 列出 gitlab 项目中的所有项目变量

Pygame 错误地渲染等距图像

是否将dict转换为一个数据帧,每个值都有重复的键?

将变量传递给 Google Cloud 函数

简单的 get/post 请求在 python 3 中被阻止,但在 python 2 中没有

如何判断一个字符串是否包含有效的 Python 代码

pandas 中 df.reindex() 和 df.set_index() 方法的区别

AttributeError:系列对象没有属性iterrows

用 numpy nan 查找列表的最大值

try 在 Windows 10 高 DPI 显示器上解决模糊的 tkinter 文本 + zoom ,但担心我的方法不是 Pythonic 或不安全