Skip to content

Commit

Permalink
pythongh-102433: Add tests for how properties interact with `typing.r…
Browse files Browse the repository at this point in the history
…untime_checkable` protocols
  • Loading branch information
AlexWaygood committed Mar 5, 2023
1 parent 3222054 commit 7595693
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2535,6 +2535,98 @@ def meth(x): ...
with self.assertRaises(TypeError):
isinstance(C(), BadPG)

def test_protocols_isinstance_simple_properties(self):
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: int

class BadP(Protocol):
@property
def attr(self): ...

class BadP1(Protocol):
attr: int

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

class BadPG1(Protocol[T]):
attr: T

class C:
@property
def attr(self):
return 42

self.assertEqual(C().attr, 42)
self.assertIsInstance(C(), P)
self.assertIsInstance(C(), P1)
self.assertIsInstance(C(), PG)
self.assertIsInstance(C(), PG1)
with self.assertRaises(TypeError):
isinstance(C(), PG[T])
with self.assertRaises(TypeError):
isinstance(C(), PG[C])
with self.assertRaises(TypeError):
isinstance(C(), PG1[T])
with self.assertRaises(TypeError):
isinstance(C(), PG1[C])
with self.assertRaises(TypeError):
isinstance(C(), BadP)
with self.assertRaises(TypeError):
isinstance(C(), BadP1)
with self.assertRaises(TypeError):
isinstance(C(), BadPG)
with self.assertRaises(TypeError):
isinstance(C(), BadPG1)

def test_protocols_isinstance_dynamic_properties(self):
T = TypeVar('T')

@runtime_checkable
class P(Protocol):
attr: int

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

class C:
X = False
@property
def attr(self):
if self.X:
return 42
raise AttributeError

inst = C()
with self.assertRaises(AttributeError):
inst.attr
self.assertNotIsInstance(inst, P)
self.assertNotIsInstance(inst, PG)

C.X = True
self.assertEqual(inst.attr, 42)
self.assertIsInstance(inst, P)
self.assertIsInstance(inst, PG)

def test_protocols_isinstance_py36(self):
class APoint:
def __init__(self, x, y, label):
Expand Down

0 comments on commit 7595693

Please sign in to comment.