Switch-Case is Match-Case python


When migrating to python language from any other programming language programmers often ask “Is there a switch statement in python ?” but soon they get disappointment because python does not have a switch statement but until now.
In PEP (python enhancement proposal) 634, 635, 636 Brandt Bucher and Guido van Rossum talks about the specification of adding a match statement which is exactly similar to switch statements in other languages.
A brief of switch case statement.
A switch case control block is similar to a ladder of if-else statements which executes a block of code based on the condition or case.
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Switch case prove simple and effective when we have pattern matching or when the expression is a contant.
Switch Case or Match in python
“What a match making”
After all these years python gods have decided to delight the developers with “match” statement works like switch-case but is more powerful in pattern matching.
PEP634, PEP635, PEP636 lays the foundation for “Structural Pattern Matching” and talks about the specification, motivation and a tutorial for the new “match” statement which will be introduced in python alpha version 3.10a later this year.
Syntax of match in python
match command.split(): case ["quit"]: print("Goodbye!") quit_game() case ["look"]: current_room.describe() case ["get", obj]: character.get(obj, current_room) case ["go", direction]: current_room = current_room.neighbor(direction) # The rest of your commands go here
The above command splits the command string into a list, this list is used as the input expression for the match statement. Upon entry, each case will have a constant or a literal which will be matched against the input expression, if the match comes true that case block will be executed.
Example of match statement in web development.
def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: return "Something's wrong with the Internet"
The above function returns the error statement based on the error code. However this can be done with using multiple if and else statements but match statement is more intuitive, readable and explainable.