gpt4 book ai didi

python - 如何使用存储在变量中的值作为案例模式?

转载 作者:行者123 更新时间:2023-12-04 04:28:07 25 4
gpt4 key购买 nike

我正在尝试了解新的 structural pattern matching Python 3.10 中的语法。我知道可以匹配这样的文字值:

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

handle(404)
# not found
但是,如果我重构并将这些值移动到模块级变量,则会导致错误,因为这些语句现在表示结构或模式而不是值:
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 是如何尝试实现模式匹配的,我认为对于这种情况,使用 if/elif/else 可能更安全、更清晰的代码。对照常数值检查时的塔。

关于python - 如何使用存储在变量中的值作为案例模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66159432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com