Skip to content

Instantly share code, notes, and snippets.

@cellularmitosis
Last active April 11, 2025 21:06
Show Gist options
  • Save cellularmitosis/86cf62202897cf16c485fc250ca4e2da to your computer and use it in GitHub Desktop.
Save cellularmitosis/86cf62202897cf16c485fc250ca4e2da to your computer and use it in GitHub Desktop.
A demo of Python 3.10's match statement

Blog 2025/4/11

<- previous | index

A demo of Python 3.10's match statement

Python's match statement is more powerful than I had at first realized.

Here's a quick demo of what it can do:

#!/usr/bin/env python3

# a demo of Python 3.10's 'match' keyword.

# see https://peps.python.org/pep-0636/

@dataclass
class Branch():
    left
    right

@dataclass
class Leaf():
    value

def matchdemo(x):
    match x:
        # matching None:
        case None:
            print("matched None")

        # matching specific bools:
        case True:
            print("matched a specific bool")
        
        # matching specific strings:
        case "":
            print("matched the empty string")
        case "foo":
            print("matched a specific string")

        # matching specific ints:
        case 42:
            print("matched a specific int")

        # nested arrays
        case [[a,b],c]:
            # note: this case must come before 'case [a,b]'.
            print("matched a nested array")

        # matching sequences:
        case ["foo", b] if isinstance(b,str) and len(b) > 10:
            # note: this case must come before 'case ["foo",b]'.
            print("matched with a conditional:", b)
        case ["foo",b]:
            # note: this case must come before 'case [a,b]'.
            print("matched specific item in array of len 2:", b)
        case ["shift", ("down"|"up") as direction]:
            # note: this case must come before 'case [a,b]'.
            print("matched a captured OR group:", direction)
        case []:
            print("matched array of len 0")
        case [a]:
            print("matched array of len 1:", a)
        case [a,b]:
            print("matched array of len 2:", a, b)
        case [a,b,c,*rest]:
            print("matched array of 3 or more:", a, b, c, rest)

        # fallthrough:
        case _:
            print("default match")


matchdemo(None)
matchdemo(True)
matchdemo("")
matchdemo("foo")
matchdemo(42)
matchdemo([])
matchdemo([10])
matchdemo([10,20])
matchdemo(["foo",30])
matchdemo([10,20,30])
matchdemo([10,20,30,40])
matchdemo([10,20,30,40,50])
matchdemo("fallthrough")
matchdemo([[10,20],30])
matchdemo(["shift", "up"])
matchdemo(["foo", "baaaaaaaar"])
matchdemo(["foo", "baaaaaaaaar"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment