'Python match case shows error with list element as case. Expected ":"

Hi I was using the newly added match case function but I encountered this problem.

Here's my code:

from typing import List

class Wee():
    def __init__(self) -> None:
        self.lololol: List[str] = ["car", "goes", "brrrr"]

    def func1(self):
        self.weee = input()
        try:
            match self.weee:
                case self.lololol[0]:
                    print(self.lololol[0])
                case self.lololol[1]:
                    print(self.lololol[1])
                case _:
                    print(self.lololol[2])
        except SyntaxError as e:
            print(e)

waa = Wee()
waa.func1()

At line 11 and 13, errors show up saying SyntaxError: expected ':'. However, when I change case self.lololol[0]: to case "car":, the errors disappear. What is happening?



Solution 1:[1]

This is because the match case statement is intended for structural matching. Specifically PEP 635 says:

Although patterns might superficially look like expressions, it is important to keep in mind that there is a clear distinction. In fact, no pattern is or contains an expression. It is more productive to think of patterns as declarative elements similar to the formal parameters in a function definition.

Specifically, plain variables are used as capture patterns and not as match patterns - definitely not what a C/C++ programmer could expect... - and functions or subscripts or just not allowed.

On a practical point of view, only litteral or dotted expressions can be used as matching patterns.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge Ballesta