python / python/mypy

Dataclass field ordering should not be enforced when init=False

Open
#10,309 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-dataclasses
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Dataclasses support fields that have default values. All fields with defaults must appear after all fields without default values. Mypy enforces this ordering requirement and emits an error ("Attributes without a default cannot follow attributes with one") if it is violated. Pyright does the same.

By default, dataclasses include a synthesized __init__ method, but this behavior can be overridden by including an init=False argument to the dataclass decorator.

A pyright user recently submitted a bug report indicating that the field order requirement should not be enforced when init=False. I've re-read PEP 557, and it doesn't provide clarity on this point.

Either mypy and pyright are both doing the right thing here or both of them have a bug.

Perhaps someone who was involved in the development of PEP 557, the dataclass implementation, or the mypy dataclass internal plugin could help clarify which behavior is correct?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing PEP 557, the dataclass implementation, and mypy's internal dataclass plugin, then compare the behavior reported in pyright issue 1753. Determine whether the field-order error should apply when the dataclass decorator uses init=False, and document or implement the agreed behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.