← Back to index

dataclasses_match_args.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 1
FP: 1
FN: 0
Optional: 0 / 0
1"""
2Tests the match_args feature of dataclass added in Python 3.10.
3"""
4
5# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents
6
7from dataclasses import dataclass, KW_ONLY
8from typing import assert_type, Literal
9
10# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method
12@dataclass(match_args=True)
13class DC1:
14 x: int
15 _: KW_ONLY
16 y: str
18assert_type(DC1.__match_args__, tuple[Literal['x']])
20# The match_args default is True
22@dataclass
23class DC2:
24 x: int
26assert_type(DC2.__match_args__, tuple[Literal['x']])
28# __match_args__ is created even if __init__() is not generated
30@dataclass(match_args=True, init=False)
31class DC3:
32 x: int = 0
34assert_type(DC3.__match_args__, tuple[Literal['x']])
36# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.
38@dataclass(match_args=False)
39class DC4:
40 x: int
42DC4.__match_args__ # E
[unresolved-attribute] Class `DC4` has no attribute `__match_args__`
44@dataclass(match_args=True)
45class DC5:
46 __match_args__ = ()
47 x: int
49assert_type(DC5.__match_args__, tuple[()])
Unexpected error [type-assertion-failure] Type `tuple[()]` does not match asserted type `Unknown | tuple[()]`