python / python/cpython

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

Offen
#148,941 6 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

pending stdlib topic-dataclasses type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduziere die beiden Beispiele mit dataclasses.dataclass und untersuche anschließend die verknüpfte Arbeit in gh-151184 und gh-153601, bevor du entscheidest, ob das Verhalten oder die Dokumentation inkonsistent ist. Als erledigt gilt, wenn der beabsichtigte Umgang mit einem vorhandenen init festgelegt und durch geeignete Regressionstests abgedeckt ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
backend
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.