Menu

1 / 2

I Built Rust-Style ADTs in 30 Lines of Python (Pattern Matching Works)

DEV Community·Alexander Mia·6 months ago
#PeDYbtJP
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.