Allow Final attributes declared in class body if initialized in ctor
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
There is currently a safety check around TypeVar-dependent Final attributes declared in the class body that I believe we can loosen when the variable is assigned in the ctor. This should work analogously to non-TypeVar-dependent final attributes declared in the class body, which also require an assignment in the ctor (otherwise they emit "Final name must be initialized with a value").
- Are you reporting a bug, or opening a feature request? feature request
- Please insert below the code you are checking with mypy,
or a mock-up repro if the source is private. We would appreciate
if you try to simplify your case to a minimal repro.from typing import Final, Generic, TypeVar WidgetT = TypeVar('WidgetT', bound='Widget') class Widget: pass class WidgetHolder(Generic[WidgetT]): widget: Final[WidgetT] def __init__(self, widget: WidgetT) -> None: self.widget = widget - What is the actual behavior/output?
final.py: note: In class "WidgetHolder": final.py:13:5: error: Final name declared in class body cannot depend on type variables [misc] widget: Final[WidgetT] ^
In case anyone comes across this issue, the workaround is currently to not declare in the class body, but declare in the ctor with self.widget: Final[WidgetT] = widget instead. But just because a workaround exists doesn't mean we shouldn't try to fix this.
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
Beginne damit, mypy für die bereitgestellte final.py-Reproduktion auszuführen und die bestehenden Prüfungen für Final-Attribute zu untersuchen, die in einem Klassenrumpf deklariert sind, und vergleiche sie mit nicht von TypeVar abhängigen Final-Attributen. Erledigt ist es, wenn die Reproduktion eine Typprüfung besteht, sobald das Attribut in init zugewiesen wird, während der bestehende Fehler bei Deklarationen bestehen bleibt, die dort nicht initialisiert werden.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 3/5
- Geschätzter Aufwand
- 1-2 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 38/100