Sum types — also called tagged unions or algebraic data types — are the feature I miss most when I switch from Rust or Haskell back to Python. The match statement landed in 3.10, but the standard library still does not give you a clean way to declare a closed set of variants where each variant carries its own fields.
Here is a 30-line metaclass that fixes that.
The result first
class Computation ( metaclass = EnumMeta ): Nothing = Case () To = Case ( target = int ) List = Case ( targets = list [ int ])
follower = Computation . List ([ 1 ])
match follower : case Computation . To ( target = p ): print ( p ) case Computation . List ( targets = p ): print ( p ) case Computation . Nothing : print ( " nothing " )
Enter fullscreen mode
Exit fullscreen mode
Three variants. Each variant is its own type. Pattern matching destructures fields by name.…