(false positive) Using `@final` decorator on a `Protocol` class results in an error in most cases
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Applying the @final decorator on a class that inherits from Protocol results in an error when the class implements abstract attributes (attributes, methods, properties). Protocols often implement abstract attributes or methods.
The original reasoning behind the error is that, for normal classes, the abstract attributes could never be implemented if the class is final.
But this reasoning doesn't really extend to Protocol since they support virtual subclasses.
There are at least a few potentially valid use cases for declaring a Protocol as final.
In my use case, a few of my concrete implementations are unable to subclass the Protocol because of issues with property overriding. Since this Protocol is very tiny and has no default implementations anyway, it makes sense to enforce that none of the concrete implementations subclass from it, for consistency and a bit more freedom, as in certain cases it isn't possible to and in my opinion there aren't many benefits.
To Reproduce
from typing import Protocol, final
@final
class Inter(Protocol):
x: int
def y(self) -> int:
...
@property
def z(self) -> int:
...
https://gist.github.com/mypy-play/95be80b2ef05cc43ed77677df133d9d5
Error
main.py:4: error: Final class __main__.Inter has abstract attributes "x", "y", "z" [misc]
mypy thinks that abstract implementations in a final class is useless, as per #8316.
For Protocols however, the virtual subclasses may implement the abstract attributes without needing to subclass the Protocol.
Your Environment
- Mypy version used: 1.10.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): default - Python version used: 3.12
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 mit dem bereitgestellten Python-Reproduzierer und vergleiche die Diagnose für ein finales Protocol mit abstrakten Attributen mit dem Verhalten gewöhnlicher finaler Klassen. Erledigt ist die Aufgabe, wenn ein finales Protocol mit abstrakten Attributen nicht den gemeldeten False-Positive-Fehler erzeugt und die bestehende Prüfung für finale Klassen weiterhin korrekt ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100