python / python/mypy

Protocol invariance not tracked if subclassed

Offen
#18,724 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

Taking the Protocol with @property example from the docs: https://mypy.readthedocs.io/en/stable/protocols.html#invariance-of-protocol-attributes
The example shows that attributes must be read-only for subclass covariance to be inferred. This makes sense.

However, if a child class explicitly subclasses the Protocol then mypy doesn't report the error. This results in unsound code. This seems like a bug in typechecker behavior (and also docs which are confusing.)

To Reproduce

class Box(Protocol):
    content: object

def takes_box(box: Box) -> None:
    box.content = object()

@dataclasses.dataclass(slots=False)
class BadBox(Box):  # XXX: inheritence wrongly hides the error
    content: int

takes_box(BadBox(42))  # XXX should fail but doesn't!!

Full example here: https://mypy-play.net/?mypy=latest&python=3.11&gist=4d7e99ee4f933393234041a219e3f952

Expected Behavior

mypy to report that BadBox.content doesn't match Box, either in the declaration of content: int or in the function call to takes_box.

Actual Behavior

Mypy reports no errors, but at runtime, BadBox.content is no longer an int.

Notes

  1. if Box.content: str, then a liskov error is reported for BadBox.content: int, but in the above example, because int is a subclass of object no error seems to be reported.

  2. Perhaps ReadOnly will help here? https://peps.python.org/pep-0767/ I tried using Final but it's not allowed in Protocols unfortunately.

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

Beginne mit dem Reproducer für die Protocol-Invarianz im Issue und vergleiche den Fall einer expliziten Subclass mit dem dokumentierten @property-Beispiel. Verwende das verlinkte Beispiel mypy-play, um das Verhalten zu überprüfen. Die Arbeit ist abgeschlossen, wenn mypy das inkompatible veränderliche Attribut meldet oder den Aufruf von takes_box ablehnt, mit Abdeckung für den object-to-int-Fall.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
42/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.