Switch case is coming to Python

Switch case is coming to Python

Yes you read it right, Not a click-bait. Python 3.10 will feature improvised version of switch_case, It's going to be termed as a match.

To give a brief, If you're coming from C/C++ background, There is a switch case, conditional operator, by definition

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

switch(expression) {
   case constant-expression 1 :
      statement(s);
      break; //optional
   case constant-expression 2  :
      statement(s);
      break; //optional

   // you can have any number of case statements.
   default : //Optional
      statement(s);
}

Previous versions of python doesn't support implicit switch case statements, here's how typical switch case block was implemented in python.

class PythonSwitchStatement:

    def switch(self, month):
        default = "Incorrect month"
        return getattr(self, 'case_' + str(month), lambda: default)()

    def case_1(self):
        return "January"

    def case_2(self):
        return "February"

    def case_3(self):
        return "March"

    def case_4(self):
        return "April"

    def case_5(self):
        return "May"

    def case_6(self):
        return "June"
    def case_7(self):
        return "July"

s = PythonSwitchStatement()

I know this is not a better way of implementing switch case, there are many ways, but the point here is python(previous versions) doesn't provide out of the box switch case conditional operators.

In Python 3.10 PEP636 match command will feature to effectively implement switch case functionality. A high-level overview of match functionality

command = input("What are you doing next? ")
# analyze the result of command.split()

[action, obj] = command.split()
... # interpret action, obj

match command.split():
    case [action, obj]:
        ... # interpret action, obj

Some of the features that match will be supporting

  • Matching multiple patterns

  • Matching multiple values

  • Matching positional attributes

  • Composing patterns

and many more

This brings to the conclusion of the article, I strongly believe, this will be one of the defining features of python release, fingers-crossed.

References:

Python 3.10 Github