How to Use a match case Statement

How to Use a match case Statement

August 29, 2023·Luke Hande,Christopher Tyler

From Luke at https://learnpython.com/blog/python-match-case-statement/

Note that this will only work with Python 3.10 and above.

The match case Statement in Python

A basic implementation of match case statements looks like an if statement in Python.

>>> command = 'Hello, World!'
>>> match command:
...     case 'Hello, World!':
...         print('Hello to you too!')
...     case 'Goodbye, World!':
...         print('See you later')
...     case other:
...         print('No match found')

Hello to you too!

It can simplify the flow control statements and make them a little bit more readable.

>>> def file_handler_v2(command):
...     match command.split():
...         case ['show']:
...             print('List all files and directories: ')
...             # code to list files
...         case ['remove' | 'delete', *files] if '--ask' in files:
...             del_files = [f for f in files if len(f.split('.'))>1]
...             print('Please confirm: Removing files: {}'.format(del_files))
...             # code to accept user input, then remove files
...         case ['remove' | 'delete', *files]:
...             print('Removing files: {}'.format(files))
...             # code to remove files
...         case _:
...             print('Command not recognized')

This is easier than a if-elif-else or using something like a dict().