← Back to index

typeddicts_usage.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 5
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests for basic usage of TypedDict.
3"""
4
5from typing import TypeVar, TypedDict
6
7
8class Movie(TypedDict):
9 name: str
10 year: int
13movie: Movie = {"name": "Blade Runner", "year": 1982}
16def record_movie(movie: Movie) -> None:
17 ...
20record_movie({"name": "Blade Runner", "year": 1982})
23movie["director"] = "Ridley Scott" # E: invalid key 'director'
[invalid-key] Unknown key "director" for TypedDict `Movie`: Unknown key "director"
24movie["year"] = "1982" # E: invalid value type ("int" expected)
[invalid-assignment] Invalid assignment to key "year" with declared type `int` on TypedDict `Movie`: value of type `Literal["1982"]`
26# The code below should be rejected, since 'title' is not a valid key,
27# and the 'name' key is missing:
28movie2: Movie = {"title": "Blade Runner", "year": 1982} # E
[missing-typed-dict-key] Missing required key 'name' in TypedDict `Movie` constructor [invalid-key] Unknown key "title" for TypedDict `Movie`: Unknown key "title"
30m = Movie(name='Blade Runner', year=1982)
33# > TypedDict type objects cannot be used in isinstance() tests such as
34# > isinstance(d, Movie).
35if isinstance(movie, Movie): # E
[isinstance-against-typed-dict] `TypedDict` class `Movie` cannot be used as the second argument to `isinstance`: This call will raise `TypeError` at runtime
36 pass
39# TypedDict should not be allowed as a bound for a TypeVar.
40T = TypeVar("T", bound=TypedDict) # E
[invalid-type-form] The special form `typing.TypedDict` is not allowed in type expressions