← Back to index

dataclasses_postinit.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 4
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests type checking of the __post_init__ method in a dataclass.
3"""
4
5# Specification: https://peps.python.org/pep-0557/#post-init-processing
6
7from dataclasses import InitVar, dataclass, field, replace
8from typing import assert_type
9
11@dataclass
12class DC1:
13 a: int
14 b: int
15 x: InitVar[int]
16 c: int
17 y: InitVar[str]
19 def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y
[invalid-dataclass] Invalid `__post_init__` signature for dataclass `DC1`
20 pass
23dc1 = DC1(1, 2, 3, 4, "")
25assert_type(dc1.a, int)
26assert_type(dc1.b, int)
27assert_type(dc1.c, int)
28print(dc1.x) # E: cannot access InitVar
[unresolved-attribute] Object of type `DC1` has no attribute `x`
29print(dc1.y) # E: cannot access InitVar
[unresolved-attribute] Object of type `DC1` has no attribute `y`
31@dataclass
32class DC2:
33 x: InitVar[int]
34 y: InitVar[str]
36 def __post_init__(self, x: int) -> None: # E: missing y
[invalid-dataclass] Invalid `__post_init__` signature for dataclass `DC2`
37 pass
40@dataclass
41class DC3:
42 _name: InitVar[str] = field()
43 name: str = field(init=False)
45 def __post_init__(self, _name: str):
46 ...
49@dataclass
50class DC4(DC3):
51 _age: InitVar[int] = field()
52 age: int = field(init=False)
54 def __post_init__(self, _name: str, _age: int):
55 ...