TypedDict – Structured Dicts for Python

A TypedDict is a new kind of type recognized by Python typecheckers such as mypy. It describes a structured dictionary/map with an expected set of named string keys mapped to values of particular expected types.

Such structures are ubiquitous when exchanging JSON data, which is common for Python web applications to do.

For example, a web API for fetching TV show ratings may return a JSON response that looks like:

{
    "title": "Queen's Gambit",
    "stars": 5
}

That API probably always returns responses in a particular generic shape:

{
    "title": <some str>,
    "stars": <some int>
}

and that shape can be described by a TypedDict definition:

from typing import TypedDict

class MediaRating(TypedDict):
    title: str
    stars: int

With that TypedDict definition in place, you can take any JSON value received from that API and use it directly in Python, without any additional conversions or additional parsing1:

import requests
from typing import cast

response_json = requests.get(
    'https://media-api.example.com/rating',
    data=dict(search="Queen's Gambit")
).json
media_rating = cast(MediaRating, response_json)  # free; always succeeds; trusts endpoint

print(f'Title: {media_rating['title']}')
print(f'Stars: {media_rating['stars']}')

And if you try to access a part of the API response that isn’t defined in the TypedDict definition, your typechecker will helpfully tell you that you made a mistake:

print(f'Stars: {media_rating['sars']}')  # error: TypedDict "MediaRating" has no key 'sars'

Having your program automatically checked for inconsistencies like this by typecheckers is especially helpful to quickly detect the introduction of bugs in large Python projects maintained by multiple people over a long period of time.

Installation

TypedDict is included in the Python standard library as of Python 3.8, so all you need to do is import it from the typing module:

from typing import TypedDict

If you are using an earlier version of Python, install the typing_extensions module using pip (via: pip install typing_extensions), and then you can import it from there:

from typing_extensions import TypedDict

Usage

See the mypy documentation for TypedDict, or the PEP for TypedDict.

History

I was initially motivated to create TypedDict because I wanted better typechecking support for describing and manipulating some very large structured dictionaries in the code managing the TechSmart Platform’s curriculum import process.

In Sep 2016 I started designing (and naming) what would become TypedDict on the typing issue tracker and implementing on the mypy issue tracker. Big kudos especially to Guido van Rossum, Jukka Lehtosalo, and Ivan Levkivskyi for providing design and implementation feedback.

Later, others in the mypy community continued to extend TypedDict, notably adding class-based syntax and total=False support.

Finally in Mar 2019 Jukka wrote up TypedDict as an official PEP for it to be standardized and added to the standard typing module in Python 3.8.

Learnings

This project is the first where I had detailed collaboration with others in design while working in open source.


  1. If you want to be sure that a JSON-like value is actually in the format you’re expecting you might consider using the trycast(…) library function to actually check the value’s shape at runtime rather than trusting a regular cast(...).