简体   繁体   中英

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. I tried on both 3.10.0 and 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:

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). 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.

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).

Try writing a complete match statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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