Why do I get "SyntaxError: invalid syntax" when using `match` in Python?

Question:

I tried to run a Python script using

python3 ds_main.py

but it returns the error:

Traceback (most recent call last):
  File "ds_main.py", line 14 in <module>
    import cmd_main
  File "/home/me/discord/cmd_main.py", line 190
    match action:
          ^
SyntaxError: invalid syntax

In this section, I did add a match case clause, which the error seems to be pointing to.

I checked the version using python3 --version which returns Python 3.8.10.

Asked By: swtto

||

Answers:

Python 3.8.10 does not support structural pattern matching (match keyword).

You need Python ≥ 3.10:

https://docs.python.org/3/whatsnew/3.10.html

PEP 634, Structural Pattern Matching: Specification

Answered By: Freddy Mcloughlan

If you need to stay compatible with older Python versions (because of not up to date production operating system), then you shall use the old Python switch case fashion with a dictionary, as example:

http_code = "418"

http_code_str = {
    "200": "OK",
    "404": "Not Found",
    "418": "I'm a teapot",
}
print(http_code_str.get(http_code, "Code not found"))
Answered By: Alexis Rodet
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.