Tuesday, 17 November 2026

Python Generics, Union vs Type Constraints

I've recently come up with some use of Python generic types that confused me a bit, so I've been looking into it a bit. It's not our typical list[Book] kind of generics, but a composed form, with 2 apparently similar shapes:

list[Human | Book] vs list[(Human, Book)]

The first case, a generic type: Human | Book, is just like the normal uses we're used to, only that with a Union type. So T is a Union Type here, rather than a single Type. We call this bound type / bound union type. It tells us that the objects used there have to be of that type or a derived type. list[Book] means that in that list we can have instances of Book, of CheapBook, or ExpensiveBook, and they can be mixed, the same list can have both CheapBooks and ExpensiveBooks. For Union types, it's the same idea. list[Human, Book] means that the same list can contain instances of CheapBook, ExpensiveBook, Employer and Employee, all in the same list.

The second case, (Human, Book), is a bit different. This is called a Type Constraint. With list[(Human, Book)] a list instance will go one way or another, but not both. In a list we can have Humans, Employers and Employees, or Books, CheapBooks and ExpensiveBooks, but we won't mix Humans and Books.

C# and Kotlin do not have Union types (and much less Intersection types, not present in Python either), but for Generic Types they have sort of "Intersection Constraints" where we can express multiple requirements that T must satisfy. For example in Kotlin:


fun <T> process(x: T)
where T : Human,
	T : Serializable

T has to be both Human and Serializable. We don't have this kind of type constraint in Python. To achieve something similar (an intersection bound) we would have to leverage Protocols, like this: (remember that a protocol can’t extend a regular class, otherwise you get a TypeError: Protocols can only inherit from other protocols).


class HumanLike(Protocol):
    def speak(self) -> str: ...

class BookLike(Protocol):
    def isbn(self) -> str: ...

class HumanAndBookLike(HumanLike, BookLike, Protocol):
    pass


def process(x: HumanAndBookLike) -> None:
    ...

But notice that given that Protocols are involved and Protocols use structural typing rather than nominal typing, the above is not strictly equivalent to the Kotlin code. The Python solution means:
"anything having the required Human-like AND Book-like interface"
rather than:
"anything nominally belonging to Human AND BookLike."

No comments:

Post a Comment