← Back to index

typeddicts_final.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the use of Final values when used with TypedDicts.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types
6
7from typing import Final, Literal, TypedDict
8
9
10class Movie(TypedDict):
11 name: str
12 year: int
15# > Type checkers should allow final names (PEP 591) with string values to be
16# > used instead of string literals in operations on TypedDict objects.
17YEAR: Final = "year"
19m: Movie = {"name": "Alien", "year": 1979}
20years_since_epoch = m[YEAR] - 1970
23# > An expression with a suitable literal type (PEP 586) can be used instead of
24# > a literal value.
25def get_value(movie: Movie, key: Literal["year", "name"]) -> int | str:
26 return movie[key]