我试图理解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相关问答推荐

如何将CSV或FDF数据解析到Python词典并注入到模板PDF表单中?

如何有效地计算Kernel/Matrix

PythonPandas READ_EXCEL空数据帧

在不使用 split 函数的情况下从字符串中分割逗号(','),句号('.')和空格(' '),将字符串的单词附加到列表中

从一列字符串中提取子字符串并将它们放入列表中

从 LeetCode 的 Python 解决方案类中理解关键字 self

将值从函数传递到标签

拆分列表的元素并将拆分后的元素包含到列表中

在 string.find() 条件下加入两个 Dataframes

平移数组

GEKKO 在没有不等式的模型中抛出不等式定义错误

以不规则频率识别数据框日期时间列上缺失的日期,并用关联值填充它们

XPATH:使用 .find_elements_by_xpath 为未知数量的 xpath 输入值

在不使用字符串方法的情况下查找字符串最后一个单词的长度 - Python

对齐文本文件中的列

具有两个或多个返回参数的函数注释

ValueError:预期的 2D 数组,得到 1D 数组:

如何在 Python 中计算两个包含字符串的列表的 Jaccard 相似度?

Python:在 map 对象上调用列表两次

如何为 anaconda python3 安装 gi 模块?