2021 › home
Match Expressions in Python
PEP 636 introduced a new match expression which effectively is a switch statement on steriods. It not only fills the void due to the lack of switch cases in Python but caters to advanced use cases that will supercharge your Python codebase. Its basically Guido's way of saying, "In you're face" to the other programming languages commmunity.
A simplest example would be to evaluate an expression and match it with the corresponding case from top-to-bottom. Once the match is found, it will execute the body of that case, and ignore the rest of the cases. It doesnt need a "break" or a default case like we have in switch cases of other languages.
match operation: case "add": result = a + b case "sub": res = a - b
The behavior is exactly like
if/elif statements, albeit, a much more idiomatic syntax to please Python enthusiasts.
The match expression can be any Python statement, and the case statements can look for complex values. The interpreter can bind values with the case variables, if the sgnature matches. It can match subpatterns, allows using conditional expression, bind values in a dict, or use a wildchar
_ to match anything.
match operation.split(): case ["add", a, b]: res = a+b case ["sub", *operands]: a, b = operands res = a-b case ["div", obj]: res = obj.a / obj.b case ["mul", a, b] | ["*", a, b]: res = a*b case [("^" | "xor"), a, b]: res = a^b case _: printf("Always matches, but doesn't bind any variables")
PEP 636 will be released in the alpha channel of v3.10, and I'm excited to try it asap. Overall it looks really promising and intuitive, and with a few minor tweaks it should be good enough to be released in Python 3.10. For more detailed examples, please visit the official PEP Index.