Replacements for switch statement in Python?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands
--
Chapters
00:00 Replacements For Switch Statement In Python?
00:22 Accepted Answer Score 2198
00:58 Answer 2 Score 489
01:11 Answer 3 Score 463
01:46 Answer 4 Score 1592
01:57 Thank you
--
Full question
https://stackoverflow.com/questions/6020...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #switchstatement
#avk47
ACCEPTED ANSWER
Score 2198
Python 3.10 (2021) introduced the match-case statement, which provides a first-class implementation of a "switch" for Python. For example:
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found
The match-case statement is considerably more powerful than this simple example.
If you need to support Python ≤ 3.9, use a dictionary instead:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
ANSWER 2
Score 1592
If you'd like defaults, you could use the dictionary get(key[, default]) function:
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 will be returned default if x is not found
ANSWER 3
Score 489
I've always liked doing it this way
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
ANSWER 4
Score 463
In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:
if x == 'a':
# Do the thing
elif x == 'b':
# Do the other thing
if x in 'bc':
# Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
# Do yet another thing
else:
# Do the default
This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the break statement, but you can have a more complicated test. Its formatting is nicer than a series of nested ifs, even though functionally that's what it is closer to.