python / python/cpython

dataclass tries to generate `__init__()` even though the class already defines one

Open
#148,941 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

pending stdlib topic-dataclasses type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

When running this code:

from dataclasses import dataclass

@dataclass
class A:
    a: int = 1

@dataclass
class B(A):
    b: int
    def __init__(self, *args, **kwargs): ...

I got TypeError: non-default argument 'b' follows default argument

However, if I set init=False for the second dataclass, like this:

from dataclasses import dataclass

@dataclass
class A:
    a: int = 1

@dataclass(init=False)
class B(A):
    b: int
    def __init__(self, *args, **kwargs): ...

There error disappeared.

I think the error comes from the process where dataclass tries to generate the default __init__() and checks the fields. But, if I understand correctly, this should not happen when the class already defines its own __init__().

Although I'm not sure whether the behavior should be defined as a bug, I do find the results inconsistant with the docs, which says

If the class already defines __init__(), this parameter (init) is ignored.

so, intuitively, adding init=False shouldn't have changed the result.

CPython versions tested on:

3.12, 3.13, 3.14

Operating systems tested on:

Windows

Linked PRs
  • gh-151184
  • gh-153601

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

Reproduce the two examples using dataclasses.dataclass, then inspect the linked work in gh-151184 and gh-153601 before deciding whether the behavior or documentation is inconsistent. Done means the intended handling of an existing init is established and covered by appropriate regression evidence.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.