33

I've been trying to use a match case instead of a million IF statements, but anything I try returns the error:

    match http_code:
          ^
SyntaxError: invalid syntax

I've also tried testing examples I've found, which also return this error, including this one:

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

I'm aware that match cases are quite new to python, but I'm using 3.10 so I'm not sure why they always return this error.

1 Answers1

26

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"
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Joshua Voskamp
  • 1,855
  • 1
  • 10
  • 13
  • In my case this happened: I was using python 3.8 in my virtual environment but in my dockerized project I was using `python:3.8-slim` so docker was not able to compile it successfully as it was not using python3.10. Once I changed image it got resolved. Hope this helps – Yalchin Mammadli May 24 '23 at 01:25