Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python match/case using global variables in the cases (solvable by use of classes) [duplicate]

I wanted to implement match/case by matching inputs stored in variables. The intended logic should be like:

match x:
    case y:
        print(...)    
    case z:
        print(...) 

Turns out this approach doesn't work.
It causes this error: "Irrefutable pattern is allowed only for the last case statement",
which I believe occurs because somehow the variable next to the first case is assigned to the value of the variable next to match: if I go and debug, by the "case y" line, y has its value changed to whatever is stored in x.

That, however, does not happen if everything belongs to a class, as in:

class Vars:
    x = int(input())
    y = int(input())
    z = int(input())
match Vars.x:
    case Vars.y:
        print("something")
    case Vars.z:
        print("anything")

This approach causes no errors whatsoever.

Why is that? I mean, what makes a class variable a refutable pattern?

like image 624
101is5 Avatar asked Dec 30 '25 23:12

101is5


1 Answers

I find the new match command (officially: structural pattern matching) quite a complex thing. It took 3 PEPs to document and explain this new Python feature (PEP-634 Specification, 635 Rationale and 636 Tutorial).

I consider myself a novice in this topic but would like to answer this question. So, why does case y: not work and case Vars.y: works just fine?

case y: does not mean "compare with y" as one might have expected. It is a "capture pattern", meaning it always matches anything and stores it into the variable y.

Python calls a pattern that always matches "irrefutable" and has some special rules for it. In short: any irrefutable pattern must be the last one (which is the source of the error mentioned in the question.) But as I explained, it wouldn't work even with this error corrected.

On the other hand, case Vars.y is a "value pattern"; the dot makes the difference. As the names suggests, it means "compare with this value".

There are many other pattern types. To summarize, it is hardly possible to understand the matching rules by mere intuition. And I don't mean some obscure details. A good tutorial (e.g. PEP-636) is recommended.

like image 74
VPfB Avatar answered Jan 02 '26 11:01

VPfB