TypedDict

Python programs often use dictionaries with string keys to represent objects.Here is a typical example:

  1. movie = {'name': 'Blade Runner', 'year': 1982}

Only a fixed set of string keys is expected ('name' and'year' above), and each key has an independent value type (strfor 'name' and int for 'year' above). We’ve previouslyseen the Dict[K, V] type, which lets you declare uniformdictionary types, where every value has the same type, and arbitrary keysare supported. This is clearly not a good fit formovie above. Instead, you can use a TypedDict to give a precisetype for objects like movie, where the type of eachdictionary value depends on the key:

  1. from typing_extensions import TypedDict
  2.  
  3. Movie = TypedDict('Movie', {'name': str, 'year': int})
  4.  
  5. movie = {'name': 'Blade Runner', 'year': 1982} # type: Movie

Movie is a TypedDict type with two items: 'name' (with type str)and 'year' (with type int). Note that we used an explicit typeannotation for the movie variable. This type annotation isimportant – without it, mypy will try to infer a regular, uniformDict type for movie, which is not what we want here.

Note

If you pass a TypedDict object as an argument to a function, notype annotation is usually necessary since mypy can infer thedesired type based on the declared argument type. Also, if anassignment target has been previously defined, and it has aTypedDict type, mypy will treat the assigned value as a TypedDict,not Dict.

Now mypy will recognize these as valid:

  1. name = movie['name'] # Okay; type of name is str
  2. year = movie['year'] # Okay; type of year is int

Mypy will detect an invalid key as an error:

  1. director = movie['director'] # Error: 'director' is not a valid key

Mypy will also reject a runtime-computed expression as a key, asit can’t verify that it’s a valid key. You can only use stringliterals as TypedDict keys.

The TypedDict type object can also act as a constructor. Itreturns a normal dict object at runtime – a TypedDict doesnot define a new runtime type:

  1. toy_story = Movie(name='Toy Story', year=1995)

This is equivalent to just constructing a dictionary directly using{ … } or dict(key=value, …). The constructor form issometimes convenient, since it can be used without a type annotation,and it also makes the type of the object explicit.

Like all types, TypedDicts can be used as components to buildarbitrarily complex types. For example, you can define nestedTypedDicts and containers with TypedDict items.Unlike most other types, mypy uses structural compatibility checking(or structural subtyping) with TypedDicts. A TypedDict object withextra items is a compatible with (a subtype of) a narrowerTypedDict, assuming item types are compatible (totality also affectssubtyping, as discussed below).

A TypedDict object is not a subtype of the regular Dict[…]type (and vice versa), since Dict allows arbitrary keys to beadded and removed, unlike TypedDict. However, any TypedDict object isa subtype of (that is, compatible with) Mapping[str, object], sinceMapping only provides read-only access to the dictionary items:

  1. def print_typed_dict(obj: Mapping[str, object]) -> None:
  2. for key, value in obj.items():
  3. print('{}: {}'.format(key, value))
  4.  
  5. print_typed_dict(Movie(name='Toy Story', year=1995)) # OK

Note

Unless you are on Python 3.8 or newer (where TypedDict is available instandard library typing module) you need to install typing_extensionsusing pip to use TypedDict:

  1. python3 -m pip install --upgrade typing-extensions

Or, if you are using Python 2:

  1. pip install --upgrade typing-extensions

Totality

By default mypy ensures that a TypedDict object has all the specifiedkeys. This will be flagged as an error:

  1. # Error: 'year' missing
  2. toy_story = {'name': 'Toy Story'} # type: Movie

Sometimes you want to allow keys to be left out when creating aTypedDict object. You can provide the total=False argument toTypedDict(…) to achieve this:

  1. GuiOptions = TypedDict(
  2. 'GuiOptions', {'language': str, 'color': str}, total=False)
  3. options = {} # type: GuiOptions # Okay
  4. options['language'] = 'en'

You may need to use get() to access items of a partial (non-total)TypedDict, since indexing using [] could fail at runtime.However, mypy still lets use [] with a partial TypedDict – youjust need to be careful with it, as it could result in a KeyError.Requiring get() everywhere would be too cumbersome. (Note that youare free to use get() with total TypedDicts as well.)

Keys that aren’t required are shown with a ? in error messages:

  1. # Revealed type is 'TypedDict('GuiOptions', {'language'?: builtins.str,
  2. # 'color'?: builtins.str})'
  3. reveal_type(options)

Totality also affects structural compatibility. You can’t use a partialTypedDict when a total one is expected. Also, a total TypedDict is notvalid when a partial one is expected.

Supported operations

TypedDict objects support a subset of dictionary operations and methods.You must use string literals as keys when calling most of the methods,as otherwise mypy won’t be able to check that the key is valid. Listof supported operations:

In Python 2 code, these methods are also supported:

  • has_key(key)
  • viewitems()
  • viewkeys()
  • viewvalues()

Note

clear() and popitem() are not supported since they are unsafe– they could delete required TypedDict items that are not visible tomypy because of structural subtyping.

Class-based syntax

An alternative, class-based syntax to define a TypedDict is supportedin Python 3.6 and later:

  1. from typing_extensions import TypedDict
  2.  
  3. class Movie(TypedDict):
  4. name: str
  5. year: int

The above definition is equivalent to the original Moviedefinition. It doesn’t actually define a real class. This syntax alsosupports a form of inheritance – subclasses can define additionalitems. However, this is primarily a notational shortcut. Since mypyuses structural compatibility with TypedDicts, inheritance is notrequired for compatibility. Here is an example of inheritance:

  1. class Movie(TypedDict):
  2. name: str
  3. year: int
  4.  
  5. class BookBasedMovie(Movie):
  6. based_on: str

Now BookBasedMovie has keys name, year and based_on.

Mixing required and non-required items

In addition to allowing reuse across TypedDict types, inheritance also allowsyou to mix required and non-required (using total=False) itemsin a single TypedDict. Example:

  1. class MovieBase(TypedDict):
  2. name: str
  3. year: int
  4.  
  5. class Movie(MovieBase, total=False):
  6. based_on: str

Now Movie has required keys name and year, while based_oncan be left out when constructing an object. A TypedDict with a mix of requiredand non-required keys, such as Movie above, will only be compatible withanother TypedDict if all required keys in the other TypedDict are required keys in thefirst TypedDict, and all non-required keys of the other TypedDict are also non-required keysin the first TypedDict.

Unions of TypedDicts

Since TypedDicts are really just regular dicts at runtime, it is not possible touse isinstance checks to distinguish between different variants of a Union ofTypedDict in the same way you can with regular objects.

Instead, you can use the tagged union pattern. The referencedsection of the docs has a full description with an example, but in short, you willneed to give each TypedDict the same key where each value has a uniqueunique Literal type. Then, check that key to distinguishbetween your TypedDicts.