Debian Codegraph @

docs/source/typed_dict.rst

raw
1 .. _typeddict:
2
3 TypedDict
4 *********
5
6 Python programs often use dictionaries with string keys to represent objects.
7 ``TypedDict`` lets you give precise types for dictionaries that represent
8 objects with a fixed schema, such as ``{'id': 1, 'items': ['x']}``.
9
10 Here is a typical example:
11
12 .. code-block:: python
13
14 movie = {'name': 'Blade Runner', 'year': 1982}
15
16 Only a fixed set of string keys is expected (``'name'`` and
17 ``'year'`` above), and each key has an independent value type (``str``
18 for ``'name'`` and ``int`` for ``'year'`` above). We've previously
19 seen the ``dict[K, V]`` type, which lets you declare uniform
20 dictionary types, where every value has the same type, and arbitrary keys
21 are supported. This is clearly not a good fit for
22 ``movie`` above. Instead, you can use a ``TypedDict`` to give a precise
23 type for objects like ``movie``, where the type of each
24 dictionary value depends on the key:
25
26 .. code-block:: python
27
28 from typing import TypedDict
29
30 Movie = TypedDict('Movie', {'name': str, 'year': int})
31
32 movie: Movie = {'name': 'Blade Runner', 'year': 1982}
33
34 ``Movie`` is a ``TypedDict`` type with two items: ``'name'`` (with type ``str``)
35 and ``'year'`` (with type ``int``). Note that we used an explicit type
36 annotation for the ``movie`` variable. This type annotation is
37 important -- without it, mypy will try to infer a regular, uniform
38 :py:class:`dict` type for ``movie``, which is not what we want here.
39
40 .. note::
41
42 If you pass a ``TypedDict`` object as an argument to a function, no
43 type annotation is usually necessary since mypy can infer the
44 desired type based on the declared argument type. Also, if an
45 assignment target has been previously defined, and it has a
46 ``TypedDict`` type, mypy will treat the assigned value as a ``TypedDict``,
47 not :py:class:`dict`.
48
49 Now mypy will recognize these as valid:
50
51 .. code-block:: python
52
53 name = movie['name'] # Okay; type of name is str
54 year = movie['year'] # Okay; type of year is int
55
56 Mypy will detect an invalid key as an error:
57
58 .. code-block:: python
59
60 director = movie['director'] # Error: 'director' is not a valid key
61
62 Mypy will also reject a runtime-computed expression as a key, as
63 it can't verify that it's a valid key. You can only use string
64 literals as ``TypedDict`` keys.
65
66 The ``TypedDict`` type object can also act as a constructor. It
67 returns a normal :py:class:`dict` object at runtime -- a ``TypedDict`` does
68 not define a new runtime type:
69
70 .. code-block:: python
71
72 toy_story = Movie(name='Toy Story', year=1995)
73
74 This is equivalent to just constructing a dictionary directly using
75 ``{ ... }`` or ``dict(key=value, ...)``. The constructor form is
76 sometimes convenient, since it can be used without a type annotation,
77 and it also makes the type of the object explicit.
78
79 Like all types, ``TypedDict``\s can be used as components to build
80 arbitrarily complex types. For example, you can define nested
81 ``TypedDict``\s and containers with ``TypedDict`` items.
82 Unlike most other types, mypy uses structural compatibility checking
83 (or structural subtyping) with ``TypedDict``\s. A ``TypedDict`` object with
84 extra items can be compatible with (a subtype of) a narrower
85 ``TypedDict``, assuming item types are compatible (*totality* also affects
86 subtyping, as does *closing*, as discussed below).
87
88 A ``TypedDict`` object is not a subtype of the regular ``dict[...]``
89 type (and vice versa), since :py:class:`dict` allows arbitrary keys to be
90 added and removed, unlike ``TypedDict``. However, any ``TypedDict`` object is
91 a subtype of (that is, compatible with) ``Mapping[str, object]``, since
92 :py:class:`~collections.abc.Mapping` only provides read-only access to the dictionary items:
93
94 .. code-block:: python
95
96 def print_typed_dict(obj: Mapping[str, object]) -> None:
97 for key, value in obj.items():
98 print(f'{key}: {value}')
99
100 print_typed_dict(Movie(name='Toy Story', year=1995)) # OK
101
102 .. note::
103
104 Unless you are on Python 3.8 or newer (where ``TypedDict`` is available in
105 standard library :py:mod:`typing` module) you need to install ``typing_extensions``
106 using pip to use ``TypedDict``:
107
108 .. code-block:: text
109
110 python3 -m pip install --upgrade typing-extensions
111
112 Totality
113 --------
114
115 By default mypy ensures that a ``TypedDict`` object has all the specified
116 keys. This will be flagged as an error:
117
118 .. code-block:: python
119
120 # Error: 'year' missing
121 toy_story: Movie = {'name': 'Toy Story'}
122
123 Sometimes you want to allow keys to be left out when creating a
124 ``TypedDict`` object. You can provide the ``total=False`` argument to
125 ``TypedDict(...)`` to achieve this:
126
127 .. code-block:: python
128
129 GuiOptions = TypedDict(
130 'GuiOptions', {'language': str, 'color': str}, total=False)
131 options: GuiOptions = {} # Okay
132 options['language'] = 'en'
133
134 You may need to use :py:meth:`~dict.get` to access items of a partial (non-total)
135 ``TypedDict``, since indexing using ``[]`` could fail at runtime.
136 However, mypy still lets use ``[]`` with a partial ``TypedDict`` -- you
137 just need to be careful with it, as it could result in a :py:exc:`KeyError`.
138 Requiring :py:meth:`~dict.get` everywhere would be too cumbersome. (Note that you
139 are free to use :py:meth:`~dict.get` with total ``TypedDict``\s as well.)
140
141 Keys that aren't required are shown with a ``?`` in error messages:
142
143 .. code-block:: python
144
145 # Revealed type is "TypedDict('GuiOptions', {'language'?: builtins.str,
146 # 'color'?: builtins.str})"
147 reveal_type(options)
148
149 Totality also affects structural compatibility. You can't use a partial
150 ``TypedDict`` when a total one is expected. Also, a total ``TypedDict`` is not
151 valid when a partial one is expected.
152
153 Supported operations
154 --------------------
155
156 ``TypedDict`` objects support a subset of dictionary operations and methods.
157 You must use string literals as keys when calling most of the methods,
158 as otherwise mypy won't be able to check that the key is valid. List
159 of supported operations:
160
161 * Anything included in :py:class:`~collections.abc.Mapping`:
162
163 * ``d[key]``
164 * ``key in d``
165 * ``len(d)``
166 * ``for key in d`` (iteration)
167 * :py:meth:`d.get(key[, default]) <dict.get>`
168 * :py:meth:`d.keys() <dict.keys>`
169 * :py:meth:`d.values() <dict.values>`
170 * :py:meth:`d.items() <dict.items>`
171
172 * :py:meth:`d.copy() <dict.copy>`
173 * :py:meth:`d.setdefault(key, default) <dict.setdefault>`
174 * :py:meth:`d1.update(d2) <dict.update>`
175 * :py:meth:`d.pop(key[, default]) <dict.pop>` (partial ``TypedDict``\s only)
176 * ``del d[key]`` (partial ``TypedDict``\s only)
177
178 .. note::
179
180 :py:meth:`~dict.clear` and :py:meth:`~dict.popitem` are not supported since they are unsafe
181 -- they could delete required ``TypedDict`` items that are not visible to
182 mypy because of structural subtyping.
183
184 Class-based syntax
185 ------------------
186
187 An alternative, class-based syntax to define a ``TypedDict`` is supported
188 in Python 3.6 and later:
189
190 .. code-block:: python
191
192 from typing import TypedDict # "from typing_extensions" in Python 3.7 and earlier
193
194 class Movie(TypedDict):
195 name: str
196 year: int
197
198 The above definition is equivalent to the original ``Movie``
199 definition. It doesn't actually define a real class. This syntax also
200 supports a form of inheritance -- subclasses can define additional
201 items. However, this is primarily a notational shortcut. Since mypy
202 uses structural compatibility with ``TypedDict``\s, inheritance is not
203 required for compatibility. Here is an example of inheritance:
204
205 .. code-block:: python
206
207 class Movie(TypedDict):
208 name: str
209 year: int
210
211 class BookBasedMovie(Movie):
212 based_on: str
213
214 Now ``BookBasedMovie`` has keys ``name``, ``year`` and ``based_on``.
215
216 Mixing required and non-required items
217 --------------------------------------
218
219 In addition to allowing reuse across ``TypedDict`` types, inheritance also allows
220 you to mix required and non-required (using ``total=False``) items
221 in a single ``TypedDict``. Example:
222
223 .. code-block:: python
224
225 class MovieBase(TypedDict):
226 name: str
227 year: int
228
229 class Movie(MovieBase, total=False):
230 based_on: str
231
232 Now ``Movie`` has required keys ``name`` and ``year``, while ``based_on``
233 can be left out when constructing an object. A ``TypedDict`` with a mix of required
234 and non-required keys, such as ``Movie`` above, will only be compatible with
235 another ``TypedDict`` if all required keys in the other ``TypedDict`` are required keys in the
236 first ``TypedDict``, and all non-required keys of the other ``TypedDict`` are also non-required keys
237 in the first ``TypedDict``.
238
239 Read-only items
240 ---------------
241
242 You can use ``typing.ReadOnly``, introduced in Python 3.13, or
243 ``typing_extensions.ReadOnly`` to mark TypedDict items as read-only (:pep:`705`):
244
245 .. code-block:: python
246
247 from typing import TypedDict
248
249 # Or "from typing ..." on Python 3.13+
250 from typing_extensions import ReadOnly
251
252 class Movie(TypedDict):
253 name: ReadOnly[str]
254 num_watched: int
255
256 m: Movie = {"name": "Jaws", "num_watched": 1}
257 m["name"] = "The Godfather" # Error: "name" is read-only
258 m["num_watched"] += 1 # OK
259
260 A TypedDict with a mutable item can be assigned to a TypedDict
261 with a corresponding read-only item, and the type of the item can
262 vary :ref:`covariantly <variance-of-generics>`:
263
264 .. code-block:: python
265
266 class Entry(TypedDict):
267 name: ReadOnly[str | None]
268 year: ReadOnly[int]
269
270 class Movie(TypedDict):
271 name: str
272 year: int
273
274 def process_entry(i: Entry) -> None: ...
275
276 m: Movie = {"name": "Jaws", "year": 1975}
277 process_entry(m) # OK
278
279 You can override a read-only item with a compatible subtype, make a
280 read-only item mutable, and inherit from multiple parents with compatible
281 definitions:
282
283 .. code-block:: python
284
285 from collections.abc import Collection, Sequence
286
287 class Competition(TypedDict):
288 hosts: ReadOnly[Collection[str]]
289 entries: ReadOnly[Sequence[Entry]]
290
291 class MovieShow(TypedDict):
292 entries: list[Movie]
293
294 class Oscars(Competition, MovieShow):
295 hosts: set[str]
296
297 Defining ``hosts`` as a mutable ``set[str]`` item works as this is compatible
298 with the read-only ``Collection[str]`` definition in ``Competition``.
299 ``entries`` will be of type ``list[Movie]``, taken from the ``MovieShow`` type,
300 as it is the only non-readonly definition, and is compatible with the definition
301 in ``Competition``.
302
303 If an item is only defined in supertypes, and is always read-only, mypy takes
304 the definition from the first parent in the inheritance order, and raises an
305 error if any other parent definition is incompatible:
306
307 .. code-block:: python
308
309 class NameIds(TypedDict):
310 ids: ReadOnly[Collection[str]]
311
312 class OrderedIds(TypedDict):
313 ids: ReadOnly[Sequence[int | str]]
314
315 class OrderedNameIds(NameIds, OrderedIds):
316 pass # Error! Parent definitions incompatible
317
318 In this example, the definition of ``ids`` will be taken from ``NameIds``,
319 which would not be compatible with the definition in ``OrderedIds``; reordering
320 the parents would not solve the problem. Instead, you will need to make a
321 compatible definition explicitly:
322
323 .. code-block:: python
324
325 class OrderedNameIds(NameIds, OrderedIds):
326 ids: ReadOnly[Sequence[str]]
327
328 Closing
329 -------
330
331 You can use the ``closed`` keyword, introduced to ``TypedDict`` in Python
332 3.15 (and available via ``typing_extensions.TypedDict`` in older
333 versions) to prevent structural subtypes from adding extra keys to a
334 type (:pep:`728`):
335
336 .. code-block:: python
337
338 HasName = TypedDict("HasName", {"name": str})
339 HasOnlyName = TypedDict("HasOnlyName", {"name": str}, closed=True)
340 Movie = TypedDict("Movie", {"name": str, "year": int})
341
342 movie: Movie = {"name": "Nimona", "year": 2023}
343 has_name: HasName = movie # OK: type is open
344 has_only_name: HasOnlyName = movie # Error: type is closed
345
346 This allows the typechecker to determine that certain operations are safe,
347 when they otherwise wouldn't be due to the potential presence of unknown
348 keys.
349
350 The ``closed`` keyword can also be used in class-based syntax:
351
352 .. code-block:: python
353
354 class HasOnlyName(TypedDict, closed=True):
355 name: str
356
357 Unions of TypedDicts
358 --------------------
359
360 Since TypedDicts are really just regular dicts at runtime, it is not possible to
361 use ``isinstance`` checks to distinguish between different variants of a Union of
362 TypedDict in the same way you can with regular objects.
363
364 Instead, you can use the :ref:`tagged union pattern <tagged_unions>`. The referenced
365 section of the docs has a full description with an example, but in short, you will
366 need to give each TypedDict the same key where each value has a unique
367 :ref:`Literal type <literal_types>`. Then, check that key to distinguish
368 between your TypedDicts.
369
370 Alternatively, you can implement tagged unions with single-key wrapper dictionaries:
371
372 .. code-block:: python
373
374 class Book(TypedDict):
375 name: str
376 length: int
377 ...
378
379 class DVD(TypedDict):
380 name: str
381 length: int
382 ...
383
384 TaggedBook = TypedDict('TaggedBook', {'book': Book}, closed=True)
385 TaggedDVD = TypedDict('TaggedDVD', {'dvd': DVD}, closed=True)
386 type Inventory = TaggedBook | TaggedDVD
387
388 def print_length(inventory: Inventory) -> None:
389 if "book" in inventory:
390 print(inventory["book"]["length"], 'pages')
391 else:
392 print(inventory["dvd"]["length"], 'minutes')
393
394 Here, the ``closed`` keyword is necessary to allow the ``if`` guard to safely
395 narrow the types; without it, there could be a structural subtype of ``TaggedDVD``
396 that contains a ``book`` field of arbitrary type.
397
398 .. note::
399
400 Applying ``@final`` to a TypedDict is a legacy way of marking it as closed
401 for the purposes of type narrowing. It was never fully implemented and is
402 now superseded; it may be removed in future.
403
404 Inline TypedDict types
405 ----------------------
406
407 .. note::
408
409 This is an experimental (non-standard) feature. Use
410 ``--enable-incomplete-feature=InlineTypedDict`` to enable.
411
412 Sometimes you may want to define a complex nested JSON schema, or annotate
413 a one-off function that returns a TypedDict. In such cases it may be convenient
414 to use inline TypedDict syntax. For example:
415
416 .. code-block:: python
417
418 def test_values() -> {"width": int, "description": str}:
419 return {"width": 42, "description": "test"}
420
421 class Response(TypedDict):
422 status: int
423 msg: str
424 # Using inline syntax here avoids defining two additional TypedDicts.
425 content: {"items": list[{"key": str, "value": str}]}
426
427 Inline TypedDicts can also by used as targets of type aliases, but due to
428 ambiguity with a regular variables it is only allowed for (newer) explicit
429 type alias forms:
430
431 .. code-block:: python
432
433 from typing import TypeAlias
434
435 X = {"a": int, "b": int} # creates a variable with type dict[str, type[int]]
436 Y: TypeAlias = {"a": int, "b": int} # creates a type alias
437 type Z = {"a": int, "b": int} # same as above (Python 3.12+ only)
438
439 Also, due to incompatibility with runtime type-checking it is strongly recommended
440 to *not* use inline syntax in union types.