Skip to content

Commit 749f258

Browse files
authored
Do not add kw_only dataclass fields to __match_args__ (#18892)
In runtime python does not add fields that have `kw_only` marker: - https://github.com/python/cpython/blob/895d983b5c9716aaaab34d14d278084b9b6730d8/Lib/dataclasses.py#L1174-L1177 - https://github.com/python/cpython/blob/895d983b5c9716aaaab34d14d278084b9b6730d8/Lib/dataclasses.py#L411-L417 See: ```python >>> import dataclasses >>> @dataclasses.dataclass(kw_only=True) ... class A: ... a: int ... >>> print(A.__match_args__) () ``` Closes #18863
1 parent e9fa89b commit 749f258

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

mypy/plugins/dataclasses.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,9 @@ def transform(self) -> bool:
381381
):
382382
str_type = self._api.named_type("builtins.str")
383383
literals: list[Type] = [
384-
LiteralType(attr.name, str_type) for attr in attributes if attr.is_in_init
384+
LiteralType(attr.name, str_type)
385+
for attr in attributes
386+
if attr.is_in_init and not attr.kw_only
385387
]
386388
match_args_type = TupleType(literals, self._api.named_type("builtins.tuple"))
387389
add_attribute_to_class(self._api, self._cls, "__match_args__", match_args_type)

test-data/unit/check-dataclasses.test

+16
Original file line numberDiff line numberDiff line change
@@ -1847,6 +1847,22 @@ e: Empty
18471847
reveal_type(e.__match_args__) # N: Revealed type is "Tuple[()]"
18481848
[builtins fixtures/dataclasses.pyi]
18491849

1850+
[case testDataclassWithMatchArgsAndKwOnly]
1851+
# flags: --python-version 3.10
1852+
from dataclasses import dataclass, field
1853+
@dataclass(kw_only=True)
1854+
class One:
1855+
a: int
1856+
b: str
1857+
reveal_type(One.__match_args__) # N: Revealed type is "Tuple[()]"
1858+
1859+
@dataclass(kw_only=True)
1860+
class Two:
1861+
a: int = field(kw_only=False)
1862+
b: str
1863+
reveal_type(Two.__match_args__) # N: Revealed type is "Tuple[Literal['a']]"
1864+
[builtins fixtures/dataclasses.pyi]
1865+
18501866
[case testDataclassWithoutMatchArgs]
18511867
# flags: --python-version 3.10
18521868
from dataclasses import dataclass

0 commit comments

Comments
 (0)