match statements

https://docs.python.org/3/tutorial/controlflow.html#match-statements

https://docs.python.org/3/reference/compound_stmts.html#match

PEP 634 - Structural Pattern Matching: Specification

PEP 636 - Structural Pattern Matching: Tutorial

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

INTRODUCTION

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This statement was introduced in Python 3.10. Note that match and case words are described as soft keywords, meaning they only work as keywords in a match statement.


# The simplest form of a 'match' statement.

def http_error(status, flag=False):
    match status:   # header line
        case 400:
            return "Bad request"
        case 401 | 403 | 404:   # several literals can be combined using |
            return "Not allowed"
        case 404:
            return "Not found"
        case 418 if flag:   # using a guard
            return "I'm a teapot"
        case _:   # optional, never fails to match
            return "Something's wrong with the internet"

# if-else version.

def http_error(status, flag=False):
    if status == 400:
        return "Bad request"
    elif status == 401 or status == 403 or status == 404:
        return "Not allowed"
    elif status == 404:
        return "Not found"
    elif status == 418 and flag:   # using a guard
        return "I'm a teapot"
    else:
        return "Something's wrong with the internet"