@@ -695,22 +695,62 @@ def test_hash(self):
695
695
self .assertEqual (hash (int | str ), hash (str | int ))
696
696
self .assertEqual (hash (int | str ), hash (typing .Union [int , str ]))
697
697
698
- def test_instancecheck (self ):
699
- x = int | str
700
- self .assertIsInstance (1 , x )
701
- self .assertIsInstance (True , x )
702
- self .assertIsInstance ('a' , x )
703
- self .assertNotIsInstance (None , x )
704
- self .assertTrue (issubclass (int , x ))
705
- self .assertTrue (issubclass (bool , x ))
706
- self .assertTrue (issubclass (str , x ))
707
- self .assertFalse (issubclass (type (None ), x ))
708
- x = int | None
709
- self .assertIsInstance (None , x )
710
- self .assertTrue (issubclass (type (None ), x ))
711
- x = int | collections .abc .Mapping
712
- self .assertIsInstance ({}, x )
713
- self .assertTrue (issubclass (dict , x ))
698
+ def test_instancecheck_and_subclasscheck (self ):
699
+ for x in (int | str , typing .Union [int , str ]):
700
+ with self .subTest (x = x ):
701
+ self .assertIsInstance (1 , x )
702
+ self .assertIsInstance (True , x )
703
+ self .assertIsInstance ('a' , x )
704
+ self .assertNotIsInstance (None , x )
705
+ self .assertTrue (issubclass (int , x ))
706
+ self .assertTrue (issubclass (bool , x ))
707
+ self .assertTrue (issubclass (str , x ))
708
+ self .assertFalse (issubclass (type (None ), x ))
709
+
710
+ for x in (int | None , typing .Union [int , None ]):
711
+ with self .subTest (x = x ):
712
+ self .assertIsInstance (None , x )
713
+ self .assertTrue (issubclass (type (None ), x ))
714
+
715
+ for x in (
716
+ int | collections .abc .Mapping ,
717
+ typing .Union [int , collections .abc .Mapping ],
718
+ ):
719
+ with self .subTest (x = x ):
720
+ self .assertIsInstance ({}, x )
721
+ self .assertNotIsInstance ((), x )
722
+ self .assertTrue (issubclass (dict , x ))
723
+ self .assertFalse (issubclass (list , x ))
724
+
725
+ def test_instancecheck_and_subclasscheck_order (self ):
726
+ T = typing .TypeVar ('T' )
727
+
728
+ will_resolve = (
729
+ int | T ,
730
+ typing .Union [int , T ],
731
+ )
732
+ for x in will_resolve :
733
+ with self .subTest (x = x ):
734
+ self .assertIsInstance (1 , x )
735
+ self .assertTrue (issubclass (int , x ))
736
+
737
+ wont_resolve = (
738
+ T | int ,
739
+ typing .Union [T , int ],
740
+ )
741
+ for x in wont_resolve :
742
+ with self .subTest (x = x ):
743
+ with self .assertRaises (TypeError ):
744
+ issubclass (int , x )
745
+ with self .assertRaises (TypeError ):
746
+ isinstance (1 , x )
747
+
748
+ for x in (* will_resolve , * wont_resolve ):
749
+ with self .subTest (x = x ):
750
+ with self .assertRaises (TypeError ):
751
+ issubclass (object , x )
752
+ with self .assertRaises (TypeError ):
753
+ isinstance (object (), x )
714
754
715
755
def test_bad_instancecheck (self ):
716
756
class BadMeta (type ):
0 commit comments