Python 3.10 match-case (switch)

Intro

Python 3.10 offers many new cool things (check out official website). One of my favourites is match-case, equivalent to our familiar switch-case.

What is cool about it?

Easier to read (code complexity)

If-else needs variable to be used in the condition repeatedly, makes code longer than necessary. Furthermore, you should NOT use if-else with more than 3 cases.

Statement “If A then this, if not A then that” works well if A is binary. However, you may have combination condition (says red color apple fruit), it gets more and more complicated to set all the statements right.

Some examples:

# Multiple pattern value using OR operator
sample = True
match sample:
        case (True|False):
            print('value is boolean')
        case _:
            print('value is not boolean')
# checking for a collection of value
list1 = ['a', 'b', 'c', 'd']
match list1:
  case ['e','f'] : print("e,f present")
  case ['a','b','c','d'] : print("a,b,c,d present")
# Inline if statement
n = 0
match n:
    case n if n < 0:
        print("Number is negative")
    case n if n == 0:
        print("Number is zero")
    case n if n > 0:
        print("Number is positive")

Faster execution

Lets check the example here:

# time measurement
import time
def measure_time(funcion):
    def measured_function(*args, **kwargs):
        init = time.time()
        c = funcion(*args, **kwargs)
        print(f"Input: {args[1]} Time: {time.time() - init}")
        return c
    return measured_function

@measure_time
def repeat(function, input):
    return [function(input) for i in range(10000000)]

Simple test implementation

def match_case(decimal):
    match decimal:
        case '0':
            return "000"
        case '1':
            return "001"
        case '2':
            return "010"
        case '3':
            return "011"
        case '4':
            return "100"
        case '5':
            return "101"
        case '6':
            return "110"
        case '7':
            return "111"
        case _:
            return "NA"

def test_match_case():
    for i in range(8):
        repeat(match_case, str(i))
def match_if(decimal):
    if decimal == '0':
        return "000"
    elif decimal == '1':
        return "001"
    elif decimal == '2':
        return "010"
    elif decimal == '3':
        return "011"
    elif decimal == '4':
        return "100"
    elif decimal == '5':
        return "101"
    elif decimal == '6':
        return "110"
    elif decimal == '7':
        return "111"
    else:
        return "NA"

def test_match_if():
    for i in range(8):
        repeat(match_if, str(i))

And result:

This can’t fully show the difference between if-else and match-case but it will be more prevalent when more conditions are considered.