Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Prev Previous commit
Next Next commit
Tests
  • Loading branch information
AlexWaygood committed Mar 24, 2023
commit ef713954946720ba28d194f73985667798712688
68 changes: 68 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2555,6 +2555,74 @@ def meth(x): ...
with self.assertRaises(TypeError):
isinstance(C(), BadPG)

def test_protocols_isinstance_attribute_access_with_side_effects(self):
class C:
@property
def attr(self):
raise AttributeError('no')

class CustomDescriptor:
def __get__(self, obj, objtype=None):
raise RuntimeError("NO")

class D:
attr = CustomDescriptor()

# Check that properties set on superclasses
# are still found by the isinstance() logic
class E(C): ...
class F(D): ...

class WhyWouldYouDoThis:
def __getattr__(self, name):
raise RuntimeError("wut")

T = TypeVar('T')

@runtime_checkable
class P(Protocol):
@property
def attr(self): ...

@runtime_checkable
class P1(Protocol):
attr: int

@runtime_checkable
class PG(Protocol[T]):
@property
def attr(self): ...

@runtime_checkable
class PG1(Protocol[T]):
attr: T

for protocol_class in P, P1, PG, PG1:
for klass in C, D, E, F:
with self.subTest(
klass=klass.__name__,
protocol_class=protocol_class.__name__
):
self.assertIsInstance(klass(), protocol_class)

with self.subTest(
klass="WhyWouldYouDoThis",
protocol_class=protocol_class.__name__
):
self.assertNotIsInstance(WhyWouldYouDoThis(), protocol_class)

def test_protocols_isinstance___slots__(self):
# As per the consensus in https://github.com/python/typing/issues/1367,
# this is desirable behaviour
@runtime_checkable
class HasX(Protocol):
x: int

class HasNothingButSlots:
__slots__ = ("x",)

self.assertIsInstance(HasNothingButSlots(), HasX)

def test_protocols_isinstance_properties_and_descriptors(self):
class C:
@property
Expand Down