python / python/mypy

Infer type of `attrs.fields(type(attrs_instance))`

Offen
#17,426 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature topic-attrs
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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.

ref https://github.com/python-attrs/attrs/issues/1297

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 Fälle von attrs.fields aus dem Issue, einschließlich der reveal_type-Prüfungen für fields.bar und fields.not_bar, im strict mode. Verfolge, wie mypy attrs.fields(type(foo)) behandelt; abgeschlossen ist die Aufgabe, wenn die aus der Instanz abgeleitete Form denselben nützlichen Feldtyp wie attrs.fields(Foo) erhält und das nicht vorhandene Feld ablehnt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
tooling
Issue-Typ
Feature
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 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.