简体   繁体   English

Python 3.10中的结构模式匹配“NameError: name 'match' is not defined”

[英]Structural pattern matching in Python 3.10 "NameError: name 'match' is not defined"

I'm excited to try the new structural pattern matching in Python 3.10 but the commands are not recognized.我很高兴尝试 Python 3.10 中的新结构模式匹配,但无法识别命令。 I tried on both 3.10.0 and 3.10.4:我在 3.10.0 和 3.10.4 上都试过了:

Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)]
>>> match
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'match' is not defined

Any ideas?有任何想法吗?

The specification of the match statement ( PEP 634 ) says: match语句 ( PEP 634 ) 的规范说:

The match and case keywords are soft keywords, ie they are not reserved words in other grammatical contexts (including at the start of a line if there is no colon where expected). match 和 case 关键字是软关键字,即它们不是其他语法上下文中的保留字(如果预期没有冒号,则包括在行的开头)。 This implies that they are recognized as keywords when part of a match statement or case block only, and are allowed to be used in all other contexts as variable or argument names.这意味着它们仅在匹配语句或 case 块的一部分时被识别为关键字,并且允许在所有其他上下文中用作变量或参数名称。

This means that if you try to evaluate an expression that is just match , it will not be treated as a match statement, but as a variable called match , which isn't defined in your case (no pun intended).这意味着如果您尝试计算一个表达式,它只是match ,它将不会被视为match语句,而是被视为一个名为match的变量,该变量未在您的案例中定义(没有双关语意)。

Try writing a complete match statement.尝试写一个完整的match语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM