我正在尝试了解Python 3.10 中新的结构模式匹配语法。我知道可以匹配这样的文字值:
def handle(retcode):
match retcode:
case 200:
print('success')
case 404:
print('not found')
case _:
print('unknown')
handle(404)
# not found
Run Code Online (Sandbox Code Playgroud)
但是,如果我重构并将这些值移动到模块级变量,则会导致错误,因为语句现在表示结构或模式而不是值:
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
Run Code Online (Sandbox Code Playgroud)
有没有办法使用 match 语句来匹配存储在变量中的值?
python switch-statement python-3.x python-3.10 structural-pattern-matching