@@ -143,7 +143,6 @@ class _TypingBase(metaclass=TypingMeta, _root=True):
143
143
144
144
__slots__ = ()
145
145
146
-
147
146
def __init__ (self , * args , ** kwds ):
148
147
pass
149
148
@@ -158,7 +157,7 @@ def __new__(cls, *args, **kwds):
158
157
isinstance (args [1 ], tuple )):
159
158
# Close enough.
160
159
raise TypeError ("Cannot subclass %r" % cls )
161
- return object .__new__ (cls )
160
+ return super () .__new__ (cls )
162
161
163
162
# Things that are not classes also need these.
164
163
def _eval_type (self , globalns , localns ):
@@ -177,7 +176,11 @@ def __call__(self, *args, **kwds):
177
176
178
177
179
178
class _FinalTypingBase (_TypingBase , _root = True ):
180
- """Mix-in class to prevent instantiation."""
179
+ """Mix-in class to prevent instantiation.
180
+
181
+ Prevents instantiation unless _root=True is given in class call.
182
+ It is used to create pseudo-singleton instances Any, Union, Tuple, etc.
183
+ """
181
184
182
185
__slots__ = ()
183
186
@@ -273,7 +276,7 @@ def __init__(self, name, type_var, impl_type, type_checker):
273
276
assert isinstance (name , str ), repr (name )
274
277
assert isinstance (impl_type , type ), repr (impl_type )
275
278
assert not isinstance (impl_type , TypingMeta ), repr (impl_type )
276
- assert isinstance (type_var , (type , _TypingBase ))
279
+ assert isinstance (type_var , (type , _TypingBase )), repr ( type_var )
277
280
self .name = name
278
281
self .type_var = type_var
279
282
self .impl_type = impl_type
@@ -375,9 +378,13 @@ def _type_repr(obj):
375
378
class _Any (_FinalTypingBase , _root = True ):
376
379
"""Special type indicating an unconstrained type.
377
380
378
- - Any object is an instance of Any.
379
- - Any class is a subclass of Any.
380
- - As a special case, Any and object are subclasses of each other.
381
+ - Any is compatible with every type.
382
+ - Any assumed to have all methods.
383
+ - All values assumed to be instances of Any.
384
+
385
+ Note that all the above statements are true from the point of view of
386
+ static type checkers. At runtime, Any should not be used with instance
387
+ or class checks.
381
388
"""
382
389
383
390
__slots__ = ()
@@ -502,7 +509,7 @@ def inner(*args, **kwds):
502
509
try :
503
510
return cached (* args , ** kwds )
504
511
except TypeError :
505
- pass # Do not duplicate real errors .
512
+ pass # All real errors ( not unhashable args) are raised below .
506
513
return func (* args , ** kwds )
507
514
return inner
508
515
@@ -542,16 +549,10 @@ class Manager(Employee): pass
542
549
Union[Manager, int, Employee] == Union[int, Employee]
543
550
Union[Employee, Manager] == Employee
544
551
545
- - Corollary: if Any is present it is the sole survivor, e.g.::
546
-
547
- Union[int, Any] == Any
548
-
549
552
- Similar for object::
550
553
551
554
Union[int, object] == object
552
555
553
- - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
554
-
555
556
- You cannot subclass or instantiate a union.
556
557
557
558
- You cannot write Union[X][Y] (what would it mean?).
@@ -589,14 +590,11 @@ def __new__(cls, parameters=None, *args, _root=False):
589
590
assert not all_params , all_params
590
591
# Weed out subclasses.
591
592
# E.g. Union[int, Employee, Manager] == Union[int, Employee].
592
- # If Any or object is present it will be the sole survivor.
593
- # If both Any and object are present, Any wins.
594
- # Never discard type variables, except against Any.
593
+ # If object is present it will be sole survivor among proper classes.
594
+ # Never discard type variables.
595
595
# (In particular, Union[str, AnyStr] != AnyStr.)
596
596
all_params = set (params )
597
597
for t1 in params :
598
- if t1 is Any :
599
- return Any
600
598
if not isinstance (t1 , type ):
601
599
continue
602
600
if any (isinstance (t2 , type ) and issubclass (t1 , t2 )
@@ -662,7 +660,7 @@ def __subclasscheck__(self, cls):
662
660
class _Optional (_FinalTypingBase , _root = True ):
663
661
"""Optional type.
664
662
665
- Optional[X] is equivalent to Union[X, type( None) ].
663
+ Optional[X] is equivalent to Union[X, None].
666
664
"""
667
665
668
666
__slots__ = ()
@@ -894,11 +892,55 @@ def _next_in_mro(cls):
894
892
return next_in_mro
895
893
896
894
895
+ def _valid_for_check (cls ):
896
+ if cls is Generic :
897
+ raise TypeError ("Class %r cannot be used with class "
898
+ "or instance checks" % cls )
899
+ if (cls .__origin__ is not None and
900
+ sys ._getframe (3 ).f_globals ['__name__' ] not in ['abc' , 'functools' ]):
901
+ raise TypeError ("Parameterized generics cannot be used with class "
902
+ "or instance checks" )
903
+
904
+
905
+ def _make_subclasshook (cls ):
906
+ """Construct a __subclasshook__ callable that incorporates
907
+ the associated __extra__ class in subclass checks performed
908
+ against cls.
909
+ """
910
+ if isinstance (cls .__extra__ , abc .ABCMeta ):
911
+ # The logic mirrors that of ABCMeta.__subclasscheck__.
912
+ # Registered classes need not be checked here because
913
+ # cls and its extra share the same _abc_registry.
914
+ def __extrahook__ (subclass ):
915
+ _valid_for_check (cls )
916
+ res = cls .__extra__ .__subclasshook__ (subclass )
917
+ if res is not NotImplemented :
918
+ return res
919
+ if cls .__extra__ in subclass .__mro__ :
920
+ return True
921
+ for scls in cls .__extra__ .__subclasses__ ():
922
+ if isinstance (scls , GenericMeta ):
923
+ continue
924
+ if issubclass (subclass , scls ):
925
+ return True
926
+ return NotImplemented
927
+ else :
928
+ # For non-ABC extras we'll just call issubclass().
929
+ def __extrahook__ (subclass ):
930
+ _valid_for_check (cls )
931
+ if cls .__extra__ and issubclass (subclass , cls .__extra__ ):
932
+ return True
933
+ return NotImplemented
934
+ return __extrahook__
935
+
936
+
897
937
class GenericMeta (TypingMeta , abc .ABCMeta ):
898
938
"""Metaclass for generic types."""
899
939
900
940
def __new__ (cls , name , bases , namespace ,
901
941
tvars = None , args = None , origin = None , extra = None ):
942
+ if extra is not None and type (extra ) is abc .ABCMeta and extra not in bases :
943
+ bases = (extra ,) + bases
902
944
self = super ().__new__ (cls , name , bases , namespace , _root = True )
903
945
904
946
if tvars is not None :
@@ -947,6 +989,13 @@ def __new__(cls, name, bases, namespace,
947
989
self .__extra__ = extra
948
990
# Speed hack (https://github.com/python/typing/issues/196).
949
991
self .__next_in_mro__ = _next_in_mro (self )
992
+
993
+ # This allows unparameterized generic collections to be used
994
+ # with issubclass() and isinstance() in the same way as their
995
+ # collections.abc counterparts (e.g., isinstance([], Iterable)).
996
+ self .__subclasshook__ = _make_subclasshook (self )
997
+ if isinstance (extra , abc .ABCMeta ):
998
+ self ._abc_registry = extra ._abc_registry
950
999
return self
951
1000
952
1001
def _get_type_vars (self , tvars ):
@@ -1032,21 +1081,7 @@ def __instancecheck__(self, instance):
1032
1081
# latter, we must extend __instancecheck__ too. For simplicity
1033
1082
# we just skip the cache check -- instance checks for generic
1034
1083
# classes are supposed to be rare anyways.
1035
- return self .__subclasscheck__ (instance .__class__ )
1036
-
1037
- def __subclasscheck__ (self , cls ):
1038
- if self is Generic :
1039
- raise TypeError ("Class %r cannot be used with class "
1040
- "or instance checks" % self )
1041
- if (self .__origin__ is not None and
1042
- sys ._getframe (1 ).f_globals ['__name__' ] != 'abc' ):
1043
- raise TypeError ("Parameterized generics cannot be used with class "
1044
- "or instance checks" )
1045
- if super ().__subclasscheck__ (cls ):
1046
- return True
1047
- if self .__extra__ is not None :
1048
- return issubclass (cls , self .__extra__ )
1049
- return False
1084
+ return issubclass (instance .__class__ , self )
1050
1085
1051
1086
1052
1087
# Prevent checks for Generic to crash when defining Generic.
0 commit comments