diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 90c983b0bacd..b46b42f78866 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -381,7 +381,9 @@ def transform(self) -> bool: ): str_type = self._api.named_type("builtins.str") literals: list[Type] = [ - LiteralType(attr.name, str_type) for attr in attributes if attr.is_in_init + LiteralType(attr.name, str_type) + for attr in attributes + if attr.is_in_init and not attr.kw_only ] match_args_type = TupleType(literals, self._api.named_type("builtins.tuple")) add_attribute_to_class(self._api, self._cls, "__match_args__", match_args_type) diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index 887a9052d0b9..048ac831dd25 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -1847,6 +1847,22 @@ e: Empty reveal_type(e.__match_args__) # N: Revealed type is "Tuple[()]" [builtins fixtures/dataclasses.pyi] +[case testDataclassWithMatchArgsAndKwOnly] +# flags: --python-version 3.10 +from dataclasses import dataclass, field +@dataclass(kw_only=True) +class One: + a: int + b: str +reveal_type(One.__match_args__) # N: Revealed type is "Tuple[()]" + +@dataclass(kw_only=True) +class Two: + a: int = field(kw_only=False) + b: str +reveal_type(Two.__match_args__) # N: Revealed type is "Tuple[Literal['a']]" +[builtins fixtures/dataclasses.pyi] + [case testDataclassWithoutMatchArgs] # flags: --python-version 3.10 from dataclasses import dataclass