The match
/case
syntax, otherwise known as Structural Pattern Matching, was only introduced in Python version 3.10. Note well that, following standard conventions, the number after the .
is not a decimal, but a separate "part" of the version number. Python 3.9 (along with 3.8, 3.7 etc.) comes before Python 3.10, and does not support the syntax. Python 3.11 (and onward) do support the syntax.
While it's possible that a syntax error on an earlier line wouldn't be noticed until the match
keyword, this sort of syntax error is much more a sign that the Python version isn't at least 3.10
.
This code will fail with an assertion if the Python version is too low to support match
/case
:
import sys
assert sys.version_info >= (3, 10)
Or check the version at the command line, by passing -V
or --version
to Python. For example, on a system where python
refers to a 3.8 installation (where it won't work):
$ python --version
Python 3.8.10
$ python
Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
For more details, see How do I check which version of Python is running my script? and Which version of Python do I have installed?.
If you're trying to use a virtual environment, make sure that it's activated (Linux/Mac howto, Windows (CMD) howto, Windows (Powershell) howto, using PyCharm).
In 3.10, the code works:
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> http_code = "418"
>>> match http_code:
... case "200":
... print("OK")
... case "404":
... print("Not Found")
... case "418":
... print("I'm a teapot")
... case _:
... print("Code not found")
Out[1]: "I'm a teapot"