Python

Literal + match for Exhaustive Switching

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Literal` pins a value to specific strings/ints. Combine with the match statement (Python 3.10+) and a `_ : assert_never` clause for exhaustiveness — every variant must be handled or mypy yells at you.
Python
Raw
from typing import Literal, assert_never

Status = Literal["draft", "published", "archived"]

def describe(status: Status) -> str:
    match status:
        case "draft":     return "Not yet visible"
        case "published": return "Live to readers"
        case "archived":  return "Hidden but preserved"
        case _:           assert_never(status)   # mypy enforces this

print(describe("draft"))       # Not yet visible
# describe("deleted")          # mypy error: not a Status literal
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.