Infer type of `attrs.fields(type(attrs_instance))`
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
Feature
mypy currently infers the type of attrs.fields(foo) as Any, where foo is an instance of an attrs class. Is it possible to have mypy infer the correct type?
With this setup:
import attrs
from attrs import define
@define
class Foo:
bar: int
foo = Foo(1)
mypy infers the correct type for attrs.fields(Foo):
fields = attrs.fields(Foo)
reveal_type(fields)
reveal_type(fields.bar)
reveal_type(fields.not_bar)
"""
demo.py:13: note: Revealed type is "tuple[attr.Attribute[builtins.int], fallback=demo.Foo.__demo_Foo_AttrsAttributes__]"
demo.py:14: note: Revealed type is "attr.Attribute[builtins.int]"
demo.py:15: error: "__demo_Foo_AttrsAttributes__" has no attribute "not_bar" [attr-defined]
demo.py:15: note: Revealed type is "Any"
Found 1 error in 1 file (checked 1 source file)
"""
but mypy infers attrs.fields(type(foo)) as Any:
fields = attrs.fields(type(foo))
reveal_type(fields)
reveal_type(fields.bar)
reveal_type(fields.not_bar)
"""
demo.py:13: note: Revealed type is "Any"
demo.py:14: note: Revealed type is "Any"
demo.py:15: note: Revealed type is "Any"
Success: no issues found in 1 source file
"""
Pitch
Passing the class to attrs.fields() is the documented usage.
If you pass type(attrs_instance) instead, mypy quietly treats the type as Any (even under strict mode), so it cannot catch attr-defined errors when you access a non-existent field.
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
Riproduci i due casi di attrs.fields dell’issue, inclusi i controlli reveal_type per fields.bar e fields.not_bar, in strict mode. Traccia la gestione di attrs.fields(type(foo)) da parte di mypy; il lavoro è completo quando la forma derivata dall’istanza riceve lo stesso tipo di campo utile di attrs.fields(Foo) e rifiuta il campo inesistente.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Funzionalità
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 42/100