Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 365
swtto Avatar asked Dec 10 '25 21:12

swtto


2 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

like image 139
Freddy Mcloughlan Avatar answered Dec 13 '25 10:12

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"))
like image 20
Alexis Rodet Avatar answered Dec 13 '25 11:12

Alexis Rodet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!