gh-74690: Avoid a costly type check where possible in _ProtocolMeta.__subclasscheck__ (#112717)

This commit is contained in:
Alex Waygood 2023-12-04 19:35:46 +00:00 committed by GitHub
parent 1e4680ce52
commit 2ed20d3bd8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 37 additions and 6 deletions

View file

@ -3533,13 +3533,26 @@ class ProtocolTests(BaseTestCase):
def test_issubclass_fails_correctly(self):
@runtime_checkable
class P(Protocol):
class NonCallableMembers(Protocol):
x = 1
class NotRuntimeCheckable(Protocol):
def callable_member(self) -> int: ...
@runtime_checkable
class RuntimeCheckable(Protocol):
def callable_member(self) -> int: ...
class C: pass
with self.assertRaisesRegex(TypeError, r"issubclass\(\) arg 1 must be a class"):
issubclass(C(), P)
# These three all exercise different code paths,
# but should result in the same error message:
for protocol in NonCallableMembers, NotRuntimeCheckable, RuntimeCheckable:
with self.subTest(proto_name=protocol.__name__):
with self.assertRaisesRegex(
TypeError, r"issubclass\(\) arg 1 must be a class"
):
issubclass(C(), protocol)
def test_defining_generic_protocols(self):
T = TypeVar('T')