Replacements for switch statement in Python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping
--
Chapters
00:00 Question
00:31 Accepted answer (Score 2106)
01:16 Answer 2 (Score 1569)
01:33 Answer 3 (Score 481)
01:49 Answer 4 (Score 455)
02:35 Thank you
--
Full question
https://stackoverflow.com/questions/6020...
Accepted answer links:
[match]: https://www.python.org/dev/peps/pep-0634/
Answer 2 links:
[get(key[, default])]: https://docs.python.org/3/library/stdtyp...
Answer 3 links:
[From here]: http://blog.simonwillison.net/post/57956...
--
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.