← Back to index

typeddicts_class_syntax.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 5
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the class syntax for defining a TypedDict.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict
6
7from typing import Generic, TypeVar, TypedDict
8
9
10class Movie(TypedDict):
11 name: str
12 year: int
14 # > String literal forward references are valid in the value types.
15 director: "Person"
18class Person(TypedDict):
19 name: str
20 age: int
23# > Methods are not allowed, since the runtime type of a TypedDict object
24# > will always be just dict (it is never a subclass of dict).
25class BadTypedDict1(TypedDict):
26 name: str
28 # Methods are not allowed, so this should generate an error.
29 def method1(self): # E
[invalid-typed-dict-statement] TypedDict class cannot have methods
30 pass
32 # Methods are not allowed, so this should generate an error.
33 @classmethod # E[method2]
Tag 'method2' [invalid-typed-dict-statement] TypedDict class cannot have methods
34 def method2(cls): # E[method2]
35 pass
37 # Methods are not allowed, so this should generate an error.
38 @staticmethod # E[method3]
Tag 'method3' [invalid-typed-dict-statement] TypedDict class cannot have methods
39 def method3(): # E[method3]
40 pass
43# > Specifying a metaclass is not allowed.
44class BadTypedDict2(TypedDict, metaclass=type): # E
[invalid-typed-dict-header] Custom metaclasses are not supported in `TypedDict` definitions
45 name: str
48# This should generate an error because "other" is not an allowed keyword argument.
49class BadTypedDict3(TypedDict, other=True): # E
[unknown-argument] Unknown keyword argument `other` in `TypedDict` definition
50 name: str
53# > TypedDicts may be made generic by adding Generic[T] among the bases.
54T = TypeVar("T")
57class GenericTypedDict(TypedDict, Generic[T]):
58 name: str
59 value: T
62# > An empty TypedDict can be created by only including pass in the
63# > body (if there is a docstring, pass can be omitted):
64class EmptyDict1(TypedDict):
65 pass
68class EmptyDict2(TypedDict):
69 """Docstring"""
72class MovieTotal(TypedDict, total=True):
73 name: str
76class MovieOptional(TypedDict, total=False):
77 name: str