def __new__(cls, *args, **kwds): if _gorg(cls) is Protocol: raise TypeError("Type Protocol cannot be instantiated; " "it can be used only as a base class") if OLD_GENERICS: return _generic_new(_next_in_mro(cls), cls, *args, **kwds) return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
def __new__(cls, name, bases, namespace, tvars=None, args=None, origin=None, extra=None, orig_bases=None): # This is just a version copied from GenericMeta.__new__ that # includes "Protocol" special treatment. (Comments removed for brevity.) assert extra is None # Protocols should not have extra if tvars is not None: assert origin is not None assert all(isinstance(t, TypeVar) for t in tvars), tvars else: tvars = _type_vars(bases) gvars = None for base in bases: if base is Generic: raise TypeError("Cannot inherit from plain Generic") if (isinstance(base, GenericMeta) and base.__origin__ in (Generic, Protocol)): if gvars is not None: raise TypeError( "Cannot inherit from Generic[...] or" " Protocol[...] multiple times.") gvars = base.__parameters__ if gvars is None: gvars = tvars else: tvarset = set(tvars) gvarset = set(gvars) if not tvarset <= gvarset: raise TypeError( "Some type variables (%s) " "are not listed in %s[%s]" % (", ".join(str(t) for t in tvars if t not in gvarset), "Generic" if any(b.__origin__ is Generic for b in bases) else "Protocol", ", ".join(str(g) for g in gvars))) tvars = gvars initial_bases = bases if extra is None: extra = namespace.get('__extra__') if extra is not None and type(extra) is abc.ABCMeta and extra not in bases: bases = (extra,) + bases bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases) if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): bases = tuple(b for b in bases if b is not Generic) namespace.update({'__origin__': origin, '__extra__': extra}) self = abc.ABCMeta.__new__(cls, name, bases, namespace) abc.ABCMeta.__setattr__(self, '_gorg', self if not origin else _gorg(origin)) self.__parameters__ = tvars self.__args__ = tuple(Ellipsis if a is _TypingEllipsis else () if a is _TypingEmpty else a for a in args) if args else None self.__next_in_mro__ = _next_in_mro(self) if orig_bases is None: self.__orig_bases__ = initial_bases self.__tree_hash__ = (hash(self._subs_tree()) if origin else abc.ABCMeta.__hash__(self)) return self