python / python/mypy

dataclasses.dataclass, custom __init__ and dataclasses.replace false positive.

Offen
#19,193 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-dataclasses
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

I am not sure if this is a mypy bug or by design or maybe a missing feature, but at least looking at the runtime behavior it seems like a bug to me. I asked on gitter and one user responed that it seems to be a bug/oversight in the implementation.

I want to do converters with dataclasses, and the way to do this with dataclasses is to provide custom __init__ i.e. consider the following example.

To Reproduce

Playground link

import dataclasses

@dataclasses.dataclass
class WrapsInt:
   value: int
   
   def __init__(self, value: int | str):
       self.value = int(value)

wraps_int = WrapsInt("3")
print(repr(wraps_int.value))

wraps_int2 = dataclasses.replace(wraps_int, value="4")
print(repr(wraps_int2.value))

At runtime it will print and boths will be integers:

3
4

This is because dataclasses.replace always calls init. But mypy seems to take the type information from the class body only instead when analyzing dataclasses.replace call.

Expected Behavior

No error, mypy recognizes __init__ implementation when analyzing dataclass.replace calls.

Actual Behavior

main.py:16: error: Argument "value" to "replace" of "WrapsInt" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.15.0, master branch
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): default
  • Python version used: 3.12

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

Führe zunächst den verknüpften Playground-Reproducer oder das bereitgestellte Python-Beispiel mit mypy 1.15.0 oder master aus und bestätige den False Positive von dataclasses.replace. Verfolge, wie dataclasses.replace den akzeptierten Feldtyp ableitet, und überprüfe anschließend, dass die abgeschlossene Änderung das String-Argument akzeptiert und dabei das bestehende Integer-Verhalten beibehält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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