Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match/Case not condition

How do I use a not in the new match/case structure?

a = 5
match a:
    case not 10:
        print(a)

This produces an error. How would I correctly syntax this?

like image 368
TheAngriestCrusader Avatar asked Sep 05 '25 03:09

TheAngriestCrusader


2 Answers

The PEP recommends that negation could be implemented using guards. e.g.:

a = 5
match a:
    case x if x != 10:
        print(a)

Obviously in this simple case you could just use an if statement, but as you say, this is a toy example, but this may be useful for a more complex use case.

like image 78
ipetrik Avatar answered Sep 08 '25 00:09

ipetrik


I don't think you can use not in structural pattern matching, an alternative is to capture the values you need and then use the default _ case to be the 'not' expression.

a = 5
match a:
    case 10:
        print(a)
    case _:
        print("not 10")

EDIT: I was curious and did some research, turns out a negative match was rejected. https://www.python.org/dev/peps/pep-0622/#negative-match-patterns

like image 30
DNy Avatar answered Sep 07 '25 23:09

DNy