Skip to content

Do not add kw_only dataclass fields to __match_args__ #18892

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down