Skip to content

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

Open
@david-westreicher

Description

@david-westreicher

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]

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions