1 """Unit tests for __instancecheck__ and __subclasscheck__."""
4 from test
import test_support
9 def __instancecheck__(cls
, inst
):
10 """Implement isinstance(inst, cls)."""
11 return any(cls
.__subclasscheck
__(c
)
12 for c
in set([type(inst
), inst
.__class
__]))
14 def __subclasscheck__(cls
, sub
):
15 """Implement issubclass(sub, cls)."""
16 candidates
= cls
.__dict
__.get("__subclass__", set()) |
set([cls
])
17 return any(c
in candidates
for c
in sub
.mro())
24 __subclass__
= set([int])
27 class SubInt(Integer
):
32 class TypeChecksTest(unittest
.TestCase
):
34 def testIsSubclassInternal(self
):
35 self
.assertEqual(Integer
.__subclasscheck
__(int), True)
36 self
.assertEqual(Integer
.__subclasscheck
__(float), False)
38 def testIsSubclassBuiltin(self
):
39 self
.assertEqual(issubclass(int, Integer
), True)
40 self
.assertEqual(issubclass(int, (Integer
,)), True)
41 self
.assertEqual(issubclass(float, Integer
), False)
42 self
.assertEqual(issubclass(float, (Integer
,)), False)
44 def testIsInstanceBuiltin(self
):
45 self
.assertEqual(isinstance(42, Integer
), True)
46 self
.assertEqual(isinstance(42, (Integer
,)), True)
47 self
.assertEqual(isinstance(3.14, Integer
), False)
48 self
.assertEqual(isinstance(3.14, (Integer
,)), False)
50 def testIsInstanceActual(self
):
51 self
.assertEqual(isinstance(Integer(), Integer
), True)
52 self
.assertEqual(isinstance(Integer(), (Integer
,)), True)
54 def testIsSubclassActual(self
):
55 self
.assertEqual(issubclass(Integer
, Integer
), True)
56 self
.assertEqual(issubclass(Integer
, (Integer
,)), True)
58 def testSubclassBehavior(self
):
59 self
.assertEqual(issubclass(SubInt
, Integer
), True)
60 self
.assertEqual(issubclass(SubInt
, (Integer
,)), True)
61 self
.assertEqual(issubclass(SubInt
, SubInt
), True)
62 self
.assertEqual(issubclass(SubInt
, (SubInt
,)), True)
63 self
.assertEqual(issubclass(Integer
, SubInt
), False)
64 self
.assertEqual(issubclass(Integer
, (SubInt
,)), False)
65 self
.assertEqual(issubclass(int, SubInt
), False)
66 self
.assertEqual(issubclass(int, (SubInt
,)), False)
67 self
.assertEqual(isinstance(SubInt(), Integer
), True)
68 self
.assertEqual(isinstance(SubInt(), (Integer
,)), True)
69 self
.assertEqual(isinstance(SubInt(), SubInt
), True)
70 self
.assertEqual(isinstance(SubInt(), (SubInt
,)), True)
71 self
.assertEqual(isinstance(42, SubInt
), False)
72 self
.assertEqual(isinstance(42, (SubInt
,)), False)
74 def test_oldstyle(self
):
75 # These should just be ignored.
77 def __instancecheck__(self
, inst
):
79 def __subclasscheck__(self
, cls
):
82 self
.assertNotIsInstance(3, X
)
83 self
.assertIsInstance(X(), X
)
84 self
.assertFalse(issubclass(int, X
))
85 self
.assertTrue(issubclass(Sub
, X
))
89 test_support
.run_unittest(TypeChecksTest
)
92 if __name__
== "__main__":