如何使用存储在变量中的值作为案例模式? [英] How to use values stored in variables as case patterns?

查看:35
本文介绍了如何使用存储在变量中的值作为案例模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解新的结构模式匹配语法在 Python 3.10 中.我知道可以匹配这样的文字值:

I'm trying to understand the new structural pattern matching syntax in Python 3.10. I understand that it is possible to match on literal values like this:

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

handle(404)
# not found

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

However, if I refactor and move these values to module-level variables, it results in an error because the statements now represent structures or patterns rather than values:

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 语句来匹配存储在变量中的值?

Is there any way to use the match statement to match values that are stored within variables?

推荐答案

如果你测试的常量是一个带点的名字,那么它应该被当作一个常量而不是变量的名字来放置捕获在(参见 PEP 636 # 匹配常量和枚举):

If the constant you're testing against is a dotted name, then it should be treated as a constant instead of as the name of the variable to put the capture in (see 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 是如何尝试实现模式匹配的,我认为对于这种情况,使用 if/elif/else 可能是更安全和更清晰的代码代码> 塔在检查常量值时.

Although, given how python is trying to implement pattern-matching, I think that for situations like this it's probably safer and clearer code to just use an if/elif/else tower when checking against constant values.

这篇关于如何使用存储在变量中的值作为案例模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆