You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
classBox(Protocol):
content: objectdeftakes_box(box: Box) ->None:
box.content=object()
@dataclasses.dataclass(slots=False)classBadBox(Box): # XXX: inheritence wrongly hides the errorcontent: inttakes_box(BadBox(42)) # XXX should fail but doesn't!!
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
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.
Perhaps ReadOnly will help here? https://peps.python.org/pep-0767/ I tried using Final but it's not allowed in Protocols unfortunately.
The text was updated successfully, but these errors were encountered:
This sort of check is implemented by the error code mutable-override (disabled by default, not implied by --strict). If you enable mutable-override, you'll get the following error on the declaration of content: int:
main.py:15: error: Covariant override of a mutable attribute (base class "Box" defined the type as "object", expression has type "int") [mutable-override]
Bug Report
Taking the
Protocol
with@property
example from the docs: https://mypy.readthedocs.io/en/stable/protocols.html#invariance-of-protocol-attributesThe 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
Full example here: https://mypy-play.net/?mypy=latest&python=3.11&gist=4d7e99ee4f933393234041a219e3f952
Expected Behavior
mypy to report that
BadBox.content
doesn't matchBox
, either in the declaration ofcontent: int
or in the function call totakes_box
.Actual Behavior
Mypy reports no errors, but at runtime,
BadBox.content
is no longer anint
.Notes
if
Box.content: str
, then a liskov error is reported forBadBox.content: int
, but in the above example, becauseint
is a subclass ofobject
no error seems to be reported.Perhaps
ReadOnly
will help here? https://peps.python.org/pep-0767/ I tried usingFinal
but it's not allowed inProtocol
s unfortunately.The text was updated successfully, but these errors were encountered: