In JavaScript, using the switch
statement, I can do the following code:
switch(true){
case 1 === 1:
console.log(1)
break
case 1 > 1:
console.log(2)
break
default:
console.log(3)
break
}
And it’s going to return 1
, since JavaScript switch
is comparing true === (1 === 1)
But the same does not happen when I try it with Python Match
statement, like as follows:
match True:
case 1 = 1:
print(1)
case 1 > 1:
print(2)
case _:
print(3)
It returns:
File "<stdin>", line 2
case 1 = 1:
^
SyntaxError: invalid syntax
And another error is returned if I try it this way:
Check1 = 1 == 1
Check2 = 1 > 1
match True:
case Check1:
print(1)
case Check2:
print(2)
case _:
print(3)
It returns:
case Check1:
^^^^^^
SyntaxError: name capture 'Check1' makes remaining patterns unreachable
What would be the cleanest/fastest way to do many different checks without using a lot of if’s and elif’s?
Advertisement
Answer
In JavaScript, using the switch statement, I can do the following code
I definitely wouldn’t be using JavaScript as any form of litmus or comparator for python.
If you used 1==1
in your first test case, the below is what both of your test cases are ultimately doing.
match True:
case True:
print(1)
case False: #will never get hit
print(2)
case _: #will never get hit
print(3)
This is why you get the error for the second version. True
will only ever be True
, so no other case will ever be hit.
Based on your example, it seems like you are trying to use match/case
just to determine the “truthiness” of an expression. Put the expression in the match
.
match a==1:
case True:
pass
case False:
pass
If you have a lot of expressions, you could do something like the below, although I don’t think this is very good.
a = 2
match (a==1, a>1):
case (True, False):
print('equals 1')
case (False, True):
print('greater than 1')
case _:
print(_)
#OR
match ((a>1) << 1) | (a==1):
case 1:
print('equals 1')
case 2:
print('greater than 1')
case _:
print(_)
cases
should be possible results of the match
, NOT expressions that attempt to emulate the match
. You’re doing it backwards. The below link should tell you pretty much everything that you need to know about match/case
, as-well-as provide you with alternatives.