What is Pattern Matching

Pattern matching is a newer feature that came with Python 3.10. Using pattern matching simplifies the code and improves readability. The other option is to write multiple if-else statements, but this can quickly become very unreadable.

Example

Consider these 2 examples. The first one using multiple if-else statements, the second one pattern matching - match/case.

Which one is more readable?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# if-else statements

if x == 'red':
    print("The color is red")
elif x == 'blue':
    print("The color is blue")
elif x == 'green':
    print("The color is green")
else:
    print("Unknown color")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Pattern matching

match x:
    case 'red':
        print("The color is red")
    case 'blue':
        print("The color is blue")
    case 'green':
        print("The color is green")
    case _:
        print("Unknown color")

This is a very simple example, and pattern matching can be also used in more complex situations where more conditions need to be met.

My use-case

I have recently built for myself a simple workout generator with Django. I used pattern matching to query the database based on selected difficulty. This is also a very simple use case, but I believe it makes the code readable, and it’s pretty clear what is going on.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Different query based on difficulty

match difficulty:

	case 'beginner':
		exercises = Exercise.objects.filter(equipment='kettlebell').exclude(difficulty='hard').exclude(difficulty='medium')
	case 'intermediate':
		exercises = Exercise.objects.filter(equipment='kettlebell').exclude(difficulty='hard')
	case 'advanced':
		exercises = Exercise.objects.filter(equipment='kettlebell')