Protocol invariance not tracked if subclassed
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
-
if
Box.content: str, then a liskov error is reported forBadBox.content: int, but in the above example, becauseintis a subclass ofobjectno error seems to be reported. -
Perhaps
ReadOnlywill help here? https://peps.python.org/pep-0767/ I tried usingFinalbut it's not allowed inProtocols unfortunately.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the Protocol invariance reproducer in the issue and compare the explicit-subclass case with the documented @property example, using the linked mypy-play example to verify behavior. The work is done when mypy reports the incompatible mutable attribute or rejects the call to takes_box, with coverage for the object-to-int case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 42/100