Reputation: 373
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?
Upvotes: 4
Views: 6749
Reputation: 2054
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.
Upvotes: 4
Reputation: 799
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
Upvotes: 4