python / python/mypy

Protocol Subclass checking method mentioned in documentation does not work / gives desired output

Open
#17,799 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Documentation

The current documentation https://mypy.readthedocs.io/en/latest/protocols.html#defining-subprotocols-and-subclassing-protocols mentions the following:

explicitly assigning to a protocol instance can be a way to ask the type checker to verify that your class implements a protocol:
_proto: SomeProto = cast(ExplicitSubclass, None)

Minimal Test

# test.py
from typing import Protocol, cast

class SomeProto(Protocol):
    def method(self) -> str: ...

class ExplicitSubclass(SomeProto):
    pass

_: SomeProto = cast(ExplicitSubclass, None)

Expected Behaviour
➤ mypy --strict --extra-checks test.py
test.py:12: ERROR  ...
Actual Behaviour
➤ mypy --version
mypy 1.12.0+dev.5dfc7d941253553ab77836e9845cb8fdfb9d23a9 (compiled: no)
➤ mypy --strict --extra-checks test.py
Success: no issues found in 1 source file

Suggestion

Change the documentation example code line to:

_: type[SomeProto] = ExplicitSubclass

This actually triggers a type check of the subclass:

➤ mypy --strict --extra-checks testmypy.py
testmypy.py:12: error: Can only assign concrete classes to a variable of type "type[SomeProto]"  [type-abstract]

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Protocol subclassing section at the linked documentation URL and reproduce the minimal test using mypy --strict --extra-checks. Update the example so it reflects the behavior shown in the issue, then verify that the documentation's example produces the intended type-checker diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.