Skip to content

dataclasses docs do not mention that kw_only fields are ignored from __match_args__ #132221

@sobolevn

Description

@sobolevn

Bug report

Documentation

Docs right now: https://docs.python.org/3.14/library/dataclasses.html#dataclasses.dataclass

match_args: If true (the default is True), the [__match_args__](https://docs.python.org/3.14/reference/datamodel.html#object.__match_args__)
tuple will be created from the list of parameters to the generated
[__init__()](https://docs.python.org/3.14/reference/datamodel.html#object.__init__)
method (even if __init__() is not generated, see above).
If false, or if __match_args__ is already defined in the class,
then __match_args__ will not be generated.

But, in runtime this does not work this way:

>>> import dataclasses
>>> @dataclasses.dataclass(kw_only=True)
... class A:
...     a: int
... 
>>> print(A.__match_args__)
()

It only add non-kw-only params here:

  • cpython/Lib/dataclasses.py

    Lines 1174 to 1177 in 895d983

    if match_args:
    # I could probably compute this once.
    _set_new_attribute(cls, '__match_args__',
    tuple(f.name for f in std_init_fields))
  • cpython/Lib/dataclasses.py

    Lines 411 to 417 in 895d983

    def _fields_in_init_order(fields):
    # Returns the fields as __init__ will output them. It returns 2 tuples:
    # the first for normal args, and the second for keyword args.
    return (tuple(f for f in fields if f.init and not f.kw_only),
    tuple(f for f in fields if f.init and f.kw_only)
    )

Found while working on python/mypy#18892
I have a PR ready.

Thanks to @sterliakov!

Linked PRs

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dirtopic-dataclassestype-bugAn unexpected behavior, bug, or error

Projects

Status

Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions