Home > front end >  Python match case shows error with list element as case. Expected ":"
Python match case shows error with list element as case. Expected ":"

Time:02-04

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?

CodePudding user response:

You can’t use arbitrary expressions as patterns (since that would sometimes be ambiguous), only a certain subset.

If you want to match against the elements of a list, you should probably, depending on the situation, either make them separate variables, or use list.index.

CodePudding user response:

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.

  •  Tags:  
  • Related