← Back to index

typeddicts_inheritance.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 1
FP: 0
FN: 3
Optional: 0 / 0
1"""
2Tests inheritance rules for TypedDict classes.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict
6
7from typing import TypedDict
8
9
10class Movie(TypedDict):
11 name: str
12 year: int
14class BookBasedMovie(Movie):
15 based_on: str
17class BookBasedMovieAlso(TypedDict):
18 name: str
19 year: int
20 based_on: str
22b1: BookBasedMovie = {"name": "Little Women", "year": 2019, "based_on": "Little Women"}
24b2: BookBasedMovieAlso = b1
27class X(TypedDict):
28 x: int
30class Y(TypedDict):
31 y: str
33class XYZ(X, Y):
34 z: bool
36x1 = XYZ(x=1, y="", z=True)
38# > A TypedDict cannot inherit from both a TypedDict type and a
39# > non-TypedDict base class other than Generic.
41class NonTypedDict:
42 pass
44class BadTypedDict(TypedDict, NonTypedDict): # E
[invalid-typed-dict-header] TypedDict class `BadTypedDict` can only inherit from TypedDict classes: `NonTypedDict` is not a `TypedDict` class
45 pass
48# > Changing a field type of a parent TypedDict class in a subclass is
49# > not allowed.
51class X1(TypedDict):
52 x: str
54class Y1(X1): # E[Y1]
Expected a ty diagnostic for this line (tag 'Y1')
55 x: int # E[Y1]: cannot overwrite TypedDict field "x"
Expected a ty diagnostic for this line (tag 'Y1')
58# > Multiple inheritance does not allow conflict types for the same name field:
59class X2(TypedDict):
60 x: int
62class Y2(TypedDict):
63 x: str
65class XYZ2(X2, Y2): # E: cannot overwrite TypedDict field "x" while merging
Expected a ty diagnostic for this line
66 xyz: bool