Exhaustive Union Matching in Python

January 12, 2022 – tagged Python, Programming

This blog post has been published on the Preferred Networks Tech Blog.

Pattern matching on algebraic data types is a powerful technique to process a given input and many programming languages have adopted it in one way or another. A check on whether a given match is “exhaustive”, i.e., covers all possible inputs, is helpful to avoid bugs when the set of possible inputs is extended; for example, when new enumeration values are added.

In this blog post I will first briefly explain the concept of sum types, a kind of algebraic data types, and give examples of pattern matching on these types in Rust and Scala. Then I will show how to define sum types in recent Python versions, and I will explain how the mypy type checker can (to a limited degree) be used to add exhaustiveness checks to Python code working with these types.

See the Preferred Networks Tech Blog for the full text of this blog post.