Skip to content

type[T] cannot be an instance of a runtime checkable protocol #4485

@pulustelu

Description

@pulustelu

Describe the bug
isinstance checks comparing instances of type / type[object] / type[T] / type[Any] to any @runtime_checkable marked Protocol infer the instance as Never.

Expected behavior
The instance should be inferred as the intersection of type and the given protocol, i.e. <subclass of type and ...>.

Screenshots or Code
If applicable, add screenshots or the text of the code (surrounded by triple back ticks) to help explain your problem.

from typing import Any, Protocol, runtime_checkable

@runtime_checkable
class Foo(Protocol):
    foo: int # or ClassVar[int]

def bar(cls: type[Any]): # or any other type expression
    if isinstance(cls, Foo):
        reveal_type(cls) # Never

VS Code extension or command-line

  • Pylance v2023.1.20

Additional context

Mypy infers the reveal_type call to be unreachable. However, if type[Any] is replaced with type, the inferred result is __main__.<subclass of "type" and "Foo">. Evidently, since these behaviors are different there is an additional bug on mypy's end here too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    as designedNot a bug, working as intended

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions