Deny free type variables in instance attributes coming from constructor args
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Feature
Detect free type variables as instance attribute annotations, when they appear from constructor with TypeVar in signature without Generic.
Pitch
It would be especially useful for beginners. People often do not understand Generic necessity under some circumstances, though more experienced user may also accidentally forget about this.
This does not deny type variables in constructor arguments, if they do not become part of attributes annotations (say, __init__(self, x: _T, y: _T): do_something(x, y); super().__init__()).
Simple example (playground link):
from typing import TypeVar
_T = TypeVar('_T')
class Foo:
def __init__(self, foo: _T, bar: _T):
self.foo = foo
self.bar = bar
f = Foo(1, 1)
reveal_type(f.foo) # N: Revealed type is "_T`-1"
mypy already denies another scenario, which is essentially the same:
...
class Bar:
x: _T # E: Type variable "__main__._T" is unbound [valid-type]
results in
main.py:15: error: Type variable "__main__._T" is unbound [valid-type]
main.py:15: note: (Hint: Use "Generic[_T]" or "Protocol[_T]" base class to bind "_T" inside a class)
main.py:15: note: (Hint: Use "_T" in function signature to bind "_T" inside a function)
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginnen Sie mit dem verknüpften mypy-play-Reproducer und vergleichen Sie ihn mit der bestehenden Diagnose für ungebundene TypeVar bei Klassenattributen. Verfolgen Sie, wie Zuweisungen im Konstruktor zu Annotationen von Instanzattributen werden; abgeschlossen ist die Arbeit, wenn dort ungebundene TypeVars gemeldet werden, während TypeVars, die nur in Konstruktorargumenten verwendet werden, weiterhin zulässig sind.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100