You can define a default case in Python. For this you use a wild card (_). The following code demonstrates it:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
case _:
print("not matched")
Answer from Prince Hamza on Stack OverflowUse "case else" instead of "case _" in match statement - Ideas - Discussions on Python.org
Opinions on match-case?
Is it "right" to use the match/case statement rather than if/else when you just want to check certain conditions?
Naming of the match default case
Videos
You can define a default case in Python. For this you use a wild card (_). The following code demonstrates it:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
case _:
print("not matched")
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
cf: https://docs.python.org/3.10/whatsnew/3.10.html#syntax-and-operations
I am curious on the Python community’s opinions on the match-case structure. I know that it has been around for a couple of years now, but some people still consider it relatively new.
I personally really like it. It is much cleaner and concise compared if-elif-else chains, and I appreciate the pattern-matching.
match-case example:
# note that this is just an example, it would be more fit in a case where there is more complex logic with side-effects
from random import randint
value = randint(0, 2)
match value:
case 0:
print("Foo")
case 1:
print("Bar")
case 2:
print("Baz")I can't say I fully understand the match/case statement yet, but I know a part of it involves more than just simple pattern matching. I know that the expression in the match statement, for example, actually runs and creates a result, such as an object if it's a call to a class.
So I'm wondering, if I don't want to do all that and just want to use it as a cleaner version of if/else, is this considered Pythonic, or is it overkill?
For example:
if some_value == True and some_other == 1:
do something
elif some_value == False and some_other == 1:
do something else
etc etc etcor:
match (some_value, some_other):
case (True, 1):
do something
case (False, 1):
do something else
etc etc etcFirst off, I *think* I'm getting the syntax correct! Second, I'm not actually creating any values with the expressions, so it feels like a glorified if/else construct, just cleaner looking.
Is this a valid use of match/case?
Thanks!