MCPcopy Index your code
hub / github.com/python/cpython / test_protocols_isinstance

Method test_protocols_isinstance

Lib/test/test_typing.py:3466–3526  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

3464 issubclass(Eggs, Spam)
3465
3466 def test_protocols_isinstance(self):
3467 T = TypeVar('T')
3468
3469 @runtime_checkable
3470 class P(Protocol):
3471 def meth(x): ...
3472
3473 @runtime_checkable
3474 class PG(Protocol[T]):
3475 def meth(x): ...
3476
3477 @runtime_checkable
3478 class WeirdProto(Protocol):
3479 meth = str.maketrans
3480
3481 @runtime_checkable
3482 class WeirdProto2(Protocol):
3483 meth = lambda *args, **kwargs: None
3484
3485 class CustomCallable:
3486 def __call__(self, *args, **kwargs):
3487 pass
3488
3489 @runtime_checkable
3490 class WeirderProto(Protocol):
3491 meth = CustomCallable()
3492
3493 class BadP(Protocol):
3494 def meth(x): ...
3495
3496 class BadPG(Protocol[T]):
3497 def meth(x): ...
3498
3499 class C:
3500 def meth(x): ...
3501
3502 class C2:
3503 def __init__(self):
3504 self.meth = lambda: None
3505
3506 for klass in C, C2:
3507 for proto in P, PG, WeirdProto, WeirdProto2, WeirderProto:
3508 with self.subTest(klass=klass.__name__, proto=proto.__name__):
3509 self.assertIsInstance(klass(), proto)
3510
3511 no_subscripted_generics = "Subscripted generics cannot be used with class and instance checks"
3512
3513 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
3514 isinstance(C(), PG[T])
3515 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
3516 isinstance(C(), PG[C])
3517
3518 only_runtime_checkable_msg = (
3519 "Instance and class checks can only be used "
3520 "with @runtime_checkable protocols"
3521 )
3522
3523 with self.assertRaisesRegex(TypeError, only_runtime_checkable_msg):

Callers

nothing calls this directly

Calls 4

assertIsInstanceMethod · 0.80
assertRaisesRegexMethod · 0.80
CClass · 0.70
subTestMethod · 0.45

Tested by

no test coverage detected