Python >= 3.10
Wow, Python 3.10+ now has a match
/case
syntax which is like switch/case
and more!
PEP 634 -- Structural Pattern Matching
Selected features of match/case
1 - Match values:
Matching values is similar to a simple switch/case
in another language:
match something:
case 1 | 2 | 3:
# Match 1-3.
case _:
# Anything else.
#
# If `case _:` is omitted, an error will be thrown
# if `something` doesn't match any of the patterns.
2 - Match structural patterns:
match something:
case str() | bytes():
# Match a string like object.
case [str(), int()]:
# Match a `str` and an `int` sequence
# (A sequence can be a `list` or a `tuple` but not a `set` or an iterator).
case [_, _]:
# Match a sequence of 2 variables.
# To prevent a common mistake, sequence patterns don’t match strings.
case {"bandwidth": 100, "latency": 300}:
# Match this dict. Extra keys are ignored.
3 - Capture variables
Parse an object; saving it as variables:
match something:
case [name, count]
# Match a sequence of any two objects and parse them into the two variables.
case [x, y, *rest]:
# Match a sequence of two or more objects,
# binding object #3 and on into the rest variable.
case bytes() | str() as text:
# Match any string like object and save it to the text variable.
Capture variables can be useful when parsing data (such as JSON or HTML) that may come in one of a number of different patterns.
Capture variables is a feature. But it also means that you need to use dotted constants (ex: COLOR.RED
) only. Otherwise, the constant will be treated as a capture variable and overwritten.
More sample usage:
match something:
case 0 | 1 | 2:
# Matches 0, 1 or 2 (value).
print("Small number")
case [] | [_]:
# Matches an empty or single value sequence (structure).
# Matches lists and tuples but not sets.
print("A short sequence")
case str() | bytes():
# Something of `str` or `bytes` type (data type).
print("Something string-like")
case _:
# Anything not matched by the above.
print("Something else")
Python <= 3.9
My favorite Python recipe for switch/case was:
choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
Short and simple for simple scenarios.
Compare to 11+ lines of C code:
// C Language version of a simple 'switch/case'.
switch( key )
{
case 'a' :
result = 1;
break;
case 'b' :
result = 2;
break;
default :
result = -1;
}
You can even assign multiple variables by using tuples:
choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}
(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))
switch
is actually more "versatile" than something returning different fixed values based on the value of an input index. It allows for different pieces of code to be executed. It actually does not even need to return a value. I wonder if some of the answers here are good replacements for a generalswitch
statement, or only for the case of returning values with no possibility of executing general pieces of code. – Harmaningswitch
case
statement then all code in the remaining cases will be executed. That is clearly not the same as a collection of if/elseifs – Convulsion