Skip to content

Fix false positive when runtime_checkable() is used as a function#20831

Open
Fridayai700 wants to merge 2 commits intopython:masterfrom
Fridayai700:fix-runtime-checkable-function-call
Open

Fix false positive when runtime_checkable() is used as a function#20831
Fridayai700 wants to merge 2 commits intopython:masterfrom
Fridayai700:fix-runtime-checkable-function-call

Conversation

@Fridayai700
Copy link

Summary

When runtime_checkable(SomeProtocol) is called as a function (rather than used as a @runtime_checkable decorator), mypy incorrectly reports:

Only @runtime_checkable protocols can be used with instance and class checks

for isinstance(x, runtime_checkable(SomeProtocol)).

This is a valid pattern — for example, when you want to use isinstance() checks in tests without permanently marking the protocol as runtime-checkable in its definition.

Before:

from typing import Protocol, runtime_checkable

class P(Protocol):
    def meth(self) -> None: ...

x: object
isinstance(x, runtime_checkable(P))  # error: Only @runtime_checkable protocols...

After: No error.

Fix

check_runtime_protocol_test() now checks whether the expression passed to isinstance()/issubclass() is a direct call to runtime_checkable() (or typing_extensions.runtime_checkable/typing_extensions.runtime). If so, the protocol is treated as runtime-checkable at the point of use.

Test plan

  • Added testRuntimeCheckableCalledAsFunctionInIsinstance covering both isinstance() and issubclass() with runtime_checkable() as a function call
  • All 23 existing runtime protocol tests pass
  • python -m pytest mypy/test/testcheck.py -k Runtime -o "addopts=" — all pass

Fixes #20787

Fridayai700 and others added 2 commits February 17, 2026 13:08
When `runtime_checkable(SomeProtocol)` is called as a function (rather
than used as a `@runtime_checkable` decorator), mypy incorrectly
reports "Only @runtime_checkable protocols can be used with instance
and class checks" for `isinstance(x, runtime_checkable(SomeProtocol))`.

This is a valid pattern — for example, when you want to use
`isinstance()` checks in tests without marking the protocol as
runtime-checkable in its definition.

The fix adds a check in `check_runtime_protocol_test()` to recognize
when the second argument to `isinstance()`/`issubclass()` is a direct
call to `runtime_checkable()`.

Fixes python#20787
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect check of runtime_checkable protocol which is not used @ class decorator

1 participant

Comments