Get the latest tech news

Approximating sum types in Python with Pydantic


12, 2024 Tags: devblog, programming, python TL;DR: You can use Pydantic’s support for tagged unions to approximate sum types in Python; go right to Sum types in Python (and onwards) to see how it’s done. Python is one of my favorite programming languages, and Pydantic is one of my favorite libraries for Python.

Thanks to Pydantic, I can write full-fledged data models for my inputs and outputs (e.g. REST APIs, RPC endpoints, application state between runs, &c) without needing to haphazardly poke through a dict or manually round-trip through another validation layer. In other words, Pydantic enables correct by construction design patterns: by declaring the expected shape of a piece of data upfront, we can collapse the question of “is this object valid?” into a single check. Our object is now correct by construction, but our object’s types don’t reflect its correctness: the typechecker doesn’t know what we’ve performed the XOR check, and will require us to either scatter type: ignore all over the place or add no-op checks where we know a particular variant is present.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of python

python

Photo of Pydantic

Pydantic

Related news:

News photo

Someone's been messing with Python's floating point subnormals

News photo

GIL Become Optional in Python 3.13

News photo

Writing a tile server in Python