python / python/mypy

Incorrect __post_init__ order when KW_ONLY used

Open
#17,564 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

from dataclasses import dataclass, InitVar, KW_ONLY


@dataclass
class A:
    _: KW_ONLY
    x: InitVar[int]

    def __post_init__(self, x: int) -> None:
        pass


@dataclass
class C(A):
    y: InitVar[str]

    def __post_init__(self, x: int, y: str) -> None:  # Correct order.
        super().__post_init__(x)

gives

a.py:19: error: Argument 2 of "__post_init__" is incompatible with supertype "dataclass"; supertype defines the argument type as "str"  [override]
        def __post_init__(self, x: int, y: str) -> None:
                                ^~~~~~
a.py:19: error: Argument 3 of "__post_init__" is incompatible with supertype "dataclass"; supertype defines the argument type as "int"  [override]
        def __post_init__(self, x: int, y: str) -> None:

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 reproducing the reported Python example and confirm the two override errors involving post_init. Then trace mypy's dataclass handling for KW_ONLY and InitVar to determine where the argument order is derived. Done means the example type-checks without those errors while preserving the demonstrated post_init order.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.