Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14155

Type alias for a union of two @runtime_checkable Protocols triggers mypy's "Cannot use parameterized generics in instance checks"

$
0
0

Here's my code, simplified a lot (playground, using _typeshed.SupportsTrunc):

from typing import Protocol, runtime_checkable, SupportsIndex, SupportsInt@runtime_checkableclass SupportsTrunc(Protocol):    def __trunc__(self) -> int:        ..._ConvertibleToInt = SupportsInt | SupportsIndex | SupportsTrunc
def f(o: object) -> None:    if isinstance(o, _ConvertibleToInt):        # error: Parameterized generics cannot be used with class or instance checks        # error: Argument 2 to "isinstance" has incompatible type "<typing special form>"; expected "_ClassInfo"        ...

All of the three Protocols are @runtime_checkable. As far as I'm aware, these are clearly not parameterized as mypy claimed. What am I doing wrong? Or is this a mypy bug?


Thanks to @wjandrea, I have found a more minimal example:

from typing import SupportsIndex, SupportsInt_ConvertibleToInt = SupportsInt | SupportsIndexdef f(o: object) -> None:    if isinstance(o, _ConvertibleToInt):  # error        ...

The same error does not happen if there is no alias (playground):

def f(o: object) -> None:    if isinstance(o, SupportsInt | SupportsIndex):  # fine        ...

...or if the alias is for one Protocol and not a union (playground):

_ConvertibleToInt = SupportsIntdef f(o: object) -> None:    if isinstance(o, _ConvertibleToInt):  # fine        ...

A union of the same Protocol repeated twice still triggers this error (playground):

_ConvertibleToInt = SupportsInt | SupportsIntdef f(o: object) -> None:    if isinstance(o, _ConvertibleToInt):  # error        ...

Viewing all articles
Browse latest Browse all 14155

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>