Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
LITERAL_TYPE,
REVEAL_LOCALS,
REVEAL_TYPE,
RUNTIME_PROTOCOL_DECOS,
UNBOUND_IMPORTED,
ArgKind,
AssertTypeExpr,
Expand Down Expand Up @@ -772,9 +773,16 @@ def check_runtime_protocol_test(self, e: CallExpr) -> None:
and tp.is_type_obj()
and tp.type_object().is_protocol
and not tp.type_object().runtime_protocol
and not self._is_runtime_checkable_call(expr)
):
self.chk.fail(message_registry.RUNTIME_PROTOCOL_EXPECTED, e)

def _is_runtime_checkable_call(self, expr: Expression) -> bool:
"""Check if expr is a call to runtime_checkable() wrapping a protocol."""
if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr):
return expr.callee.fullname in RUNTIME_PROTOCOL_DECOS
return False

def check_protocol_issubclass(self, e: CallExpr) -> None:
for expr in mypy.checker.flatten(e.args[1]):
tp = get_proper_type(self.chk.lookup_type(expr))
Expand Down
18 changes: 18 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -1718,6 +1718,24 @@ if isinstance(x, R):
[builtins fixtures/isinstance.pyi]
[typing fixtures/typing-full.pyi]

[case testRuntimeCheckableCalledAsFunctionInIsinstance]
from typing import Protocol, runtime_checkable

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

x: object

# runtime_checkable() used as a function call rather than a decorator
if isinstance(x, runtime_checkable(P)):
reveal_type(x) # N: Revealed type is "__main__.P"

if issubclass(type(x), runtime_checkable(P)):
pass
[builtins fixtures/isinstance.pyi]
[typing fixtures/typing-full.pyi]

[case testRuntimeIterableProtocolCheck]
from typing import Iterable, List, Union

Expand Down