dataclasses.dataclass, custom __init__ and dataclasses.replace false positive.
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo il riproduttore Playground collegato o l’esempio Python fornito con mypy 1.15.0 o master e conferma il falso positivo di dataclasses.replace. Traccia il modo in cui dataclasses.replace deduce il tipo di campo accettato, quindi verifica che la modifica completata accetti l’argomento string mantenendo il comportamento esistente per integer.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 42/100