8000 `@runtime_checkable` `Protocol` doesn't check if `__class_getitem__` exists. · Issue #112319 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content
@runtime_checkable Protocol doesn't check if __class_getitem__ exists. #112319
@randolf-scholz

Description

@randolf-scholz

Bug report

Bug description:

Basically, the isinstance-check is ignoring that I manually specified that the class must have __class_getitem__.

from types import GenericAlias
from typing import runtime_checkable, Protocol, Iterator, TypeVar

T_co = TypeVar("T_co", covariant=True)


@runtime_checkable
class GenericIterable(Protocol[T_co]):
    def __class_getitem__(cls, item: type) -> GenericAlias: ...
    def __iter__(self) -> Iterator[T_co]: ...


x = ["a", "b", "c"]
assert hasattr(x, "__class_getitem__")  # ✅
assert isinstance(x, GenericIterable)   # ✅

y = "abc"
assert not hasattr(y, "__class_getitem__")  # ✅
assert not isinstance(y, GenericIterable)   # ❌

I was considering this Protocol as a partial workaround for the Iterable[str] vs str issue python/typing#256.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtopic-typingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0