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