2Tests operations provided by a TypedDict object.
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations
8from typing import TypedDict, assert_type
11class Movie(TypedDict):
18movie = {"name": "Blade Runner", "year": 1982}
19movie["name"] = "Other"
22movie["name"] = 1982 # E: wrong type
[invalid-assignment] Invalid assignment to key "name" with declared type `str` on TypedDict `Movie`: value of type `Literal[1982]`
23movie["year"] = "" # E: wrong type
[invalid-assignment] Invalid assignment to key "year" with declared type `int` on TypedDict `Movie`: value of type `Literal[""]`
24movie["other"] = "" # E: unknown key added
[invalid-key] Unknown key "other" for TypedDict `Movie`: Unknown key "other"
26print(movie["other"]) # E: unknown key referenced
[invalid-key] Unknown key "other" for TypedDict `Movie`: Unknown key "other"
28movie = {"name": "Blade Runner"} # E: year is missing
[missing-typed-dict-key] Missing required key 'year' in TypedDict `Movie` constructor
29movie = {"name": "Blade Runner", "year": 1982.1} # E: year is wrong type
[invalid-argument-type] Invalid argument to key "year" with declared type `int` on TypedDict `Movie`: value of type `float`
31# > The use of a key that is not known to exist should be reported as an error.
32movie = {"name": "", "year": 1900, "other": 2} # E: extra key
[invalid-key] Unknown key "other" for TypedDict `Movie`: Unknown key "other"
35def func1(variable_key: str):
36 # > A key that is not a literal should generally be rejected.
37 movie: Movie = {variable_key: "", "year": 1900} # E: variable key
[missing-typed-dict-key] Missing required key 'name' in TypedDict `Movie` constructor
40# It's not clear from the spec what type this should be.
43# It's not clear from the spec what type this should be.
44movie.get("other") # E?
47movie.clear() # E: clear not allowed
[unresolved-attribute] Object of type `Movie` has no attribute `clear`
49del movie["name"] # E: del not allowed for required key
[invalid-argument-type] Cannot delete required key "name" from TypedDict `Movie`
53class MovieOptional(TypedDict, total=False):
58movie_optional: MovieOptional = {}
60assert_type(movie_optional.get("name"), str | None)
62movie_optional.clear() # E: clear not allowed
[unresolved-attribute] Object of type `MovieOptional` has no attribute `clear`
64del movie_optional["name"]