-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathdataclasses_postinit.py
More file actions
55 lines (39 loc) · 1.03 KB
/
dataclasses_postinit.py
File metadata and controls
55 lines (39 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Tests type checking of the __post_init__ method in a dataclass.
"""
# Specification: https://peps.python.org/pep-0557/#post-init-processing
from dataclasses import InitVar, dataclass, field, replace
from typing import assert_type
@dataclass
class DC1:
a: int
b: int
x: InitVar[int]
c: int
y: InitVar[str]
def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y
pass
dc1 = DC1(1, 2, 3, 4, "")
assert_type(dc1.a, int)
assert_type(dc1.b, int)
assert_type(dc1.c, int)
print(dc1.x) # E: cannot access InitVar
print(dc1.y) # E: cannot access InitVar
@dataclass
class DC2:
x: InitVar[int]
y: InitVar[str]
def __post_init__(self, x: int) -> None: # E: missing y
pass
@dataclass
class DC3:
_name: InitVar[str] = field()
name: str = field(init=False)
def __post_init__(self, _name: str):
...
@dataclass
class DC4(DC3):
_age: InitVar[int] = field()
age: int = field(init=False)
def __post_init__(self, _name: str, _age: int):
...