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