Unions of TypedDicts

October 10, 2021 - Tags: python, mypy

At runtime TypedDicts are only plain dictionaries. I.e. it is not possible to distinguish a Union of TypedDicts with isinstance. If you want to distinguish Unions of TypedDicts, it is recommended to use the tagged union pattern:

from typing import Literal, TypedDict, Union

class A(TypedDict):
    tag: Literal["A"]
    a: int
    
class B(TypedDict):
    tag: Literal["B"]
    b: str
    
TDs = Union[A, B]

def match(t: TDs) -> None:
    if t["tag"] == "A":
        print(t["a"])
    else:
        print(t["b"])

In existing code bases which use a lot of dicts a Union of TypedDicts may appear when types are introduced. The question is then if it is possible to introduce an additional field or if you have to silence the error temporarily until the code is cleaned up.