attrs plugin does not support generic type
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
The mypy attrs plugin has custom support for attrs.evolve, which has different code branches for regular and generic types (starting here).
It admits attrs.has as a type guard for attrs.evolve if the original type is Any, but not if it's a generic type parameter T with no type bound.
To Reproduce
On python 3.12 (so lacking copy.replace):
def replace[T](value: T, **kwargs: Any) -> T:
if attrs.has(type(value)):
return attrs.evolve(value, **kwargs)
else:
raise NotImplementedError(f"replace is not implemented for {type(value)}")
Mypy reports, error: Argument 1 to "evolve" has a variable type "T" not bound to an attrs class [misc]
(In the actual code I'd do something else in other branches; this is intended as a replacement for copy.replace on python < 3.13, supporting different types besides attrs classes.)
Using the attr.AttrInstance protocol also doesn't work, which means I can't define my own type guard wrapping attrs.has. This code results in the same mypy error:
def replace[T: attrs.AttrsInstance](value: T, **kwargs: Any) -> T:
return attrs.evolve(value, **kwargs)
However, this code works (and is a viable workaround):
def replace[T](value: T, **kwargs: Any) -> T:
val2: Any = value
if attrs.has(type(val2)):
return attrs.evolve(val2, **kwargs)
else:
raise NotImplementedError(f"replace is not implemented for {type(value)}")
Expected Behavior
Mypy should honor attrs.has as a type guard for attrs.evolve, whether the original type is generic or any other kind.
- Mypy version used: 1.15.0
- Python version used: 3.12.10
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 in mypy/plugins/attrs.py, intorno alla gestione di attrs.evolve alla riga 914, quindi esegui l’esempio generico Python 3.12 fornito con mypy 1.15.0 per osservare la diagnosi. Traccia come attrs.has viene riconosciuto per Any rispetto a un parametro di tipo non associato e conferma il completamento quando l’esempio generico viene accettato senza l’errore di tipo della variabile, preservando il tipo di ritorno previsto.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 48/100