@@ -376,7 +376,7 @@ def _type_check(arg, msg):
376
376
if (
377
377
type (arg ).__name__ in ('_Union' , '_Optional' ) and
378
378
not getattr (arg , '__origin__' , None ) or
379
- isinstance (arg , TypingMeta ) and _gorg ( arg ) in (Generic , _Protocol )
379
+ isinstance (arg , TypingMeta ) and arg . _gorg in (Generic , _Protocol )
380
380
):
381
381
raise TypeError ("Plain %s is not valid as type argument" % arg )
382
382
return arg
@@ -849,29 +849,6 @@ def __getitem__(self, arg):
849
849
Optional = _Optional (_root = True )
850
850
851
851
852
- def _gorg (a ):
853
- """Return the farthest origin of a generic class (internal helper)."""
854
- assert isinstance (a , GenericMeta )
855
- while a .__origin__ is not None :
856
- a = a .__origin__
857
- return a
858
-
859
-
860
- def _geqv (a , b ):
861
- """Return whether two generic classes are equivalent (internal helper).
862
-
863
- The intention is to consider generic class X and any of its
864
- parameterized forms (X[T], X[int], etc.) as equivalent.
865
-
866
- However, X is not equivalent to a subclass of X.
867
-
868
- The relation is reflexive, symmetric and transitive.
869
- """
870
- assert isinstance (a , GenericMeta ) and isinstance (b , GenericMeta )
871
- # Reduce each to its origin.
872
- return _gorg (a ) is _gorg (b )
873
-
874
-
875
852
def _next_in_mro (cls ):
876
853
"""Helper for Generic.__new__.
877
854
@@ -881,7 +858,7 @@ def _next_in_mro(cls):
881
858
next_in_mro = object
882
859
# Look for the last occurrence of Generic or Generic[...].
883
860
for i , c in enumerate (cls .__mro__ [:- 1 ]):
884
- if isinstance (c , GenericMeta ) and _gorg ( c ) is Generic :
861
+ if isinstance (c , GenericMeta ) and c . _gorg is Generic :
885
862
next_in_mro = cls .__mro__ [i + 1 ]
886
863
return next_in_mro
887
864
@@ -991,14 +968,15 @@ def __new__(cls, name, bases, namespace,
991
968
initial_bases = bases
992
969
if extra is not None and type (extra ) is abc .ABCMeta and extra not in bases :
993
970
bases = (extra ,) + bases
994
- bases = tuple (_gorg ( b ) if isinstance (b , GenericMeta ) else b for b in bases )
971
+ bases = tuple (b . _gorg if isinstance (b , GenericMeta ) else b for b in bases )
995
972
996
973
# remove bare Generic from bases if there are other generic bases
997
974
if any (isinstance (b , GenericMeta ) and b is not Generic for b in bases ):
998
975
bases = tuple (b for b in bases if b is not Generic )
999
976
namespace .update ({'__origin__' : origin , '__extra__' : extra })
1000
977
self = super ().__new__ (cls , name , bases , namespace , _root = True )
1001
-
978
+ super (GenericMeta , self ).__setattr__ ('_gorg' ,
979
+ self if not origin else origin ._gorg )
1002
980
self .__parameters__ = tvars
1003
981
# Be prepared that GenericMeta will be subclassed by TupleMeta
1004
982
# and CallableMeta, those two allow ..., (), or [] in __args___.
@@ -1041,7 +1019,7 @@ def __new__(cls, name, bases, namespace,
1041
1019
def _abc_negative_cache (self ):
1042
1020
if isinstance (self .__extra__ , abc .ABCMeta ):
1043
1021
return self .__extra__ ._abc_negative_cache
1044
- return _gorg ( self ) ._abc_generic_negative_cache
1022
+ return self . _gorg ._abc_generic_negative_cache
1045
1023
1046
1024
@_abc_negative_cache .setter
1047
1025
def _abc_negative_cache (self , value ):
@@ -1055,7 +1033,7 @@ def _abc_negative_cache(self, value):
1055
1033
def _abc_negative_cache_version (self ):
1056
1034
if isinstance (self .__extra__ , abc .ABCMeta ):
1057
1035
return self .__extra__ ._abc_negative_cache_version
1058
- return _gorg ( self ) ._abc_generic_negative_cache_version
1036
+ return self . _gorg ._abc_generic_negative_cache_version
1059
1037
1060
1038
@_abc_negative_cache_version .setter
1061
1039
def _abc_negative_cache_version (self , value ):
@@ -1105,7 +1083,7 @@ def _subs_tree(self, tvars=None, args=None):
1105
1083
if self .__origin__ is None :
1106
1084
return self
1107
1085
tree_args = _subs_tree (self , tvars , args )
1108
- return (_gorg ( self ) ,) + tuple (tree_args )
1086
+ return (self . _gorg ,) + tuple (tree_args )
1109
1087
1110
1088
def __eq__ (self , other ):
1111
1089
if not isinstance (other , GenericMeta ):
@@ -1121,7 +1099,7 @@ def __hash__(self):
1121
1099
def __getitem__ (self , params ):
1122
1100
if not isinstance (params , tuple ):
1123
1101
params = (params ,)
1124
- if not params and not _gorg ( self ) is Tuple :
1102
+ if not params and self . _gorg is not Tuple :
1125
1103
raise TypeError (
1126
1104
"Parameter list to %s[...] cannot be empty" % _qualname (self ))
1127
1105
msg = "Parameters to generic types must be types."
@@ -1189,14 +1167,14 @@ def __copy__(self):
1189
1167
self .__extra__ , self .__orig_bases__ )
1190
1168
1191
1169
def __setattr__ (self , attr , value ):
1192
- # We consider all the subscripted genrics as proxies for original class
1170
+ # We consider all the subscripted generics as proxies for original class
1193
1171
if (
1194
1172
attr .startswith ('__' ) and attr .endswith ('__' ) or
1195
1173
attr .startswith ('_abc_' )
1196
1174
):
1197
1175
super (GenericMeta , self ).__setattr__ (attr , value )
1198
1176
else :
1199
- super (GenericMeta , _gorg ( self ) ).__setattr__ (attr , value )
1177
+ super (GenericMeta , self . _gorg ).__setattr__ (attr , value )
1200
1178
1201
1179
1202
1180
# Prevent checks for Generic to crash when defining Generic.
@@ -1209,7 +1187,7 @@ def _generic_new(base_cls, cls, *args, **kwds):
1209
1187
if cls .__origin__ is None :
1210
1188
return base_cls .__new__ (cls )
1211
1189
else :
1212
- origin = _gorg ( cls )
1190
+ origin = cls . _gorg
1213
1191
obj = base_cls .__new__ (origin )
1214
1192
try :
1215
1193
obj .__orig_class__ = cls
@@ -1243,7 +1221,7 @@ def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
1243
1221
__slots__ = ()
1244
1222
1245
1223
def __new__ (cls , * args , ** kwds ):
1246
- if _geqv ( cls , Generic ) :
1224
+ if cls . _gorg is Generic :
1247
1225
raise TypeError ("Type Generic cannot be instantiated; "
1248
1226
"it can be used only as a base class" )
1249
1227
return _generic_new (cls .__next_in_mro__ , cls , * args , ** kwds )
@@ -1265,7 +1243,7 @@ class TupleMeta(GenericMeta):
1265
1243
1266
1244
@_tp_cache
1267
1245
def __getitem__ (self , parameters ):
1268
- if self .__origin__ is not None or not _geqv ( self , Tuple ) :
1246
+ if self .__origin__ is not None or self . _gorg is not Tuple :
1269
1247
# Normal generic rules apply if this is not the first subscription
1270
1248
# or a subscription of a subclass.
1271
1249
return super ().__getitem__ (parameters )
@@ -1307,7 +1285,7 @@ class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1307
1285
__slots__ = ()
1308
1286
1309
1287
def __new__ (cls , * args , ** kwds ):
1310
- if _geqv ( cls , Tuple ) :
1288
+ if cls . _gorg is Tuple :
1311
1289
raise TypeError ("Type Tuple cannot be instantiated; "
1312
1290
"use tuple() instead" )
1313
1291
return _generic_new (tuple , cls , * args , ** kwds )
@@ -1322,7 +1300,7 @@ def __repr__(self):
1322
1300
return self ._tree_repr (self ._subs_tree ())
1323
1301
1324
1302
def _tree_repr (self , tree ):
1325
- if _gorg ( self ) is not Callable :
1303
+ if self . _gorg is not Callable :
1326
1304
return super ()._tree_repr (tree )
1327
1305
# For actual Callable (not its subclass) we override
1328
1306
# super()._tree_repr() for nice formatting.
@@ -1342,7 +1320,7 @@ def __getitem__(self, parameters):
1342
1320
with hashable arguments to improve speed.
1343
1321
"""
1344
1322
1345
- if self .__origin__ is not None or not _geqv ( self , Callable ) :
1323
+ if self .__origin__ is not None or self . _gorg is not Callable :
1346
1324
return super ().__getitem__ (parameters )
1347
1325
if not isinstance (parameters , tuple ) or len (parameters ) != 2 :
1348
1326
raise TypeError ("Callable must be used as "
@@ -1384,7 +1362,7 @@ class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
1384
1362
__slots__ = ()
1385
1363
1386
1364
def __new__ (cls , * args , ** kwds ):
1387
- if _geqv ( cls , Callable ) :
1365
+ if cls . _gorg is Callable :
1388
1366
raise TypeError ("Type Callable cannot be instantiated; "
1389
1367
"use a non-abstract subclass instead" )
1390
1368
return _generic_new (cls .__next_in_mro__ , cls , * args , ** kwds )
@@ -1568,7 +1546,7 @@ def no_type_check(arg):
1568
1546
if isinstance (arg , type ):
1569
1547
arg_attrs = arg .__dict__ .copy ()
1570
1548
for attr , val in arg .__dict__ .items ():
1571
- if val in arg .__bases__ :
1549
+ if val in arg .__bases__ + ( arg ,) :
1572
1550
arg_attrs .pop (attr )
1573
1551
for obj in arg_attrs .values ():
1574
1552
if isinstance (obj , types .FunctionType ):
@@ -1687,6 +1665,7 @@ def _get_protocol_attrs(self):
1687
1665
attr != '__annotations__' and
1688
1666
attr != '__weakref__' and
1689
1667
attr != '_is_protocol' and
1668
+ attr != '_gorg' and
1690
1669
attr != '__dict__' and
1691
1670
attr != '__args__' and
1692
1671
attr != '__slots__' and
@@ -1892,7 +1871,7 @@ class List(list, MutableSequence[T], extra=list):
1892
1871
__slots__ = ()
1893
1872
1894
1873
def __new__ (cls , * args , ** kwds ):
1895
- if _geqv ( cls , List ) :
1874
+ if cls . _gorg is List :
1896
1875
raise TypeError ("Type List cannot be instantiated; "
1897
1876
"use list() instead" )
1898
1877
return _generic_new (list , cls , * args , ** kwds )
@@ -1903,7 +1882,7 @@ class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1903
1882
__slots__ = ()
1904
1883
1905
1884
def __new__ (cls , * args , ** kwds ):
1906
- if _geqv ( cls , Deque ) :
1885
+ if cls . _gorg is Deque :
1907
1886
return collections .deque (* args , ** kwds )
1908
1887
return _generic_new (collections .deque , cls , * args , ** kwds )
1909
1888
@@ -1913,7 +1892,7 @@ class Set(set, MutableSet[T], extra=set):
1913
1892
__slots__ = ()
1914
1893
1915
1894
def __new__ (cls , * args , ** kwds ):
1916
- if _geqv ( cls , Set ) :
1895
+ if cls . _gorg is Set :
1917
1896
raise TypeError ("Type Set cannot be instantiated; "
1918
1897
"use set() instead" )
1919
1898
return _generic_new (set , cls , * args , ** kwds )
@@ -1923,7 +1902,7 @@ class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
1923
1902
__slots__ = ()
1924
1903
1925
1904
def __new__ (cls , * args , ** kwds ):
1926
- if _geqv ( cls , FrozenSet ) :
1905
+ if cls . _gorg is FrozenSet :
1927
1906
raise TypeError ("Type FrozenSet cannot be instantiated; "
1928
1907
"use frozenset() instead" )
1929
1908
return _generic_new (frozenset , cls , * args , ** kwds )
@@ -2014,7 +1993,7 @@ class Dict(dict, MutableMapping[KT, VT], extra=dict):
2014
1993
__slots__ = ()
2015
1994
2016
1995
def __new__ (cls , * args , ** kwds ):
2017
- if _geqv ( cls , Dict ) :
1996
+ if cls . _gorg is Dict :
2018
1997
raise TypeError ("Type Dict cannot be instantiated; "
2019
1998
"use dict() instead" )
2020
1999
return _generic_new (dict , cls , * args , ** kwds )
@@ -2026,7 +2005,7 @@ class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
2026
2005
__slots__ = ()
2027
2006
2028
2007
def __new__ (cls , * args , ** kwds ):
2029
- if _geqv ( cls , DefaultDict ) :
2008
+ if cls . _gorg is DefaultDict :
2030
2009
return collections .defaultdict (* args , ** kwds )
2031
2010
return _generic_new (collections .defaultdict , cls , * args , ** kwds )
2032
2011
@@ -2036,7 +2015,7 @@ class Counter(collections.Counter, Dict[T, int], extra=collections.Counter):
2036
2015
__slots__ = ()
2037
2016
2038
2017
def __new__ (cls , * args , ** kwds ):
2039
- if _geqv ( cls , Counter ) :
2018
+ if cls . _gorg is Counter :
2040
2019
return collections .Counter (* args , ** kwds )
2041
2020
return _generic_new (collections .Counter , cls , * args , ** kwds )
2042
2021
@@ -2051,7 +2030,7 @@ class ChainMap(collections.ChainMap, MutableMapping[KT, VT],
2051
2030
__slots__ = ()
2052
2031
2053
2032
def __new__ (cls , * args , ** kwds ):
2054
- if _geqv ( cls , ChainMap ) :
2033
+ if cls . _gorg is ChainMap :
2055
2034
return collections .ChainMap (* args , ** kwds )
2056
2035
return _generic_new (collections .ChainMap , cls , * args , ** kwds )
2057
2036
@@ -2070,7 +2049,7 @@ class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
2070
2049
__slots__ = ()
2071
2050
2072
2051
def __new__ (cls , * args , ** kwds ):
2073
- if _geqv ( cls , Generator ) :
2052
+ if cls . _gorg is Generator :
2074
2053
raise TypeError ("Type Generator cannot be instantiated; "
2075
2054
"create a subclass instead" )
2076
2055
return _generic_new (_G_base , cls , * args , ** kwds )
0 commit comments