define names for builtin types that aren t directly accessible as a builtin iterators in python aren t a matter of type but of protocol a large and changing number of builtin types implement some flavor of iterator don t check the type use hasattr to check for both iter and next attributes instead provide a pep 3115 compliant mechanism for class creation create a class object dynamically using the appropriate metaclass resolvedbases resolvebasesbases meta ns kwds prepareclassname resolvedbases kwds if execbody is not none execbodyns if resolvedbases is not bases ns origbases bases return metaname resolvedbases ns kwds def resolvebasesbases call the prepare method of the appropriate metaclass returns metaclass namespace kwds as a 3tuple metaclass is the appropriate metaclass namespace is the prepared class namespace kwds is an updated copy of the passed in kwds argument with any metaclass entry removed if no kwds argument is passed in this will be an empty dict when meta is a type we first determine the mostderived metaclass instead of invoking the initial candidate directly calculate the most derived metaclass winner meta for base in bases basemeta typebase if issubclasswinner basemeta continue if issubclassbasemeta winner winner basemeta continue else raise typeerrormetaclass conflict the metaclass of a derived class must be a nonstrict subclass of the metaclasses of all its bases return winner def getoriginalbasescls try return cls dict getorigbases cls bases except attributeerror raise typeerror fexpected an instance of type not typecls name r from none class dynamicclassattribute def initself fgetnone fsetnone fdelnone docnone self fget fget self fset fset self fdel fdel next two lines make dynamicclassattribute act the same as property self doc doc or fget doc self overwritedoc doc is none support for abstract methods self isabstractmethod boolgetattrfget isabstractmethod false def getself instance ownerclassnone if instance is none if self isabstractmethod return self raise attributeerror elif self fget is none raise attributeerrorunreadable attribute return self fgetinstance def setself instance value if self fset is none raise attributeerrorcan t set attribute self fsetinstance value def deleteself instance if self fdel is none raise attributeerrorcan t delete attribute self fdelinstance def getterself fget fdoc fget doc if self overwritedoc else none result typeselffget self fset self fdel fdoc or self doc result overwritedoc self overwritedoc return result def setterself fset result typeselfself fget fset self fdel self doc result overwritedoc self overwritedoc return result def deleterself fdel result typeselfself fget self fset fdel self doc result overwritedoc self overwritedoc return result class generatorwrapper todo implement this in c def initself gen self wrapped gen self isgen gen class is generatortype self name getattrgen name none self qualname getattrgen qualname none def sendself val return self wrapped sendval def throwself tp rest return self wrapped throwtp rest def closeself return self wrapped close property def gicodeself return self wrapped gicode property def giframeself return self wrapped giframe property def girunningself return self wrapped girunning property def giyieldfromself return self wrapped giyieldfrom crcode gicode crframe giframe crrunning girunning crawait giyieldfrom def nextself return nextself wrapped def iterself if self isgen return self wrapped return self await iter def coroutinefunc check if func is a coroutine function 0x180 cocoroutine coiterablecoroutine check if func is a generator function 0x20 cogenerator todo implement this in c 0x100 coiterablecoroutine the following code is primarily to support functions that return generatorlike objects for instance generators compiled with cython delay functools and collectionsabc import for speeding up types import coro is a native coroutine object or an iterable coroutine coro is either a pure python generator iterator or it implements collections abc generator and does not implement collections abc coroutine coro is either an instance of collections abc coroutine or some other object pass it through iterators in python aren t a matter of type but of protocol a large and changing number of builtin types implement some flavor of iterator don t check the type use hasattr to check for both __iter__ and __next__ attributes instead same as functiontype prevent resourcewarning same as builtinfunctiontype not for export provide a pep 3115 compliant mechanism for class creation create a class object dynamically using the appropriate metaclass resolve mro entries dynamically as specified by pep 560 call the __prepare__ method of the appropriate metaclass returns metaclass namespace kwds as a 3 tuple metaclass is the appropriate metaclass namespace is the prepared class namespace kwds is an updated copy of the passed in kwds argument with any metaclass entry removed if no kwds argument is passed in this will be an empty dict don t alter the provided mapping when meta is a type we first determine the most derived metaclass instead of invoking the initial candidate directly calculate the most derived metaclass else return the class s original bases prior to modification by __mro_entries__ examples from typing import typevar generic namedtuple typeddict t typevar t class foo generic t class bar foo int float class baz list str eggs namedtuple eggs a int b str spam typeddict spam a int b str assert get_original_bases bar foo int float assert get_original_bases baz list str assert get_original_bases eggs namedtuple assert get_original_bases spam typeddict assert get_original_bases int object route attribute access on a class to __getattr__ this is a descriptor used to define attributes that act differently when accessed through an instance and through a class instance access remains normal but access to an attribute through a class will be routed to the class s __getattr__ method this is done by raising attributeerror this allows one to have properties active on an instance and have virtual attributes on the class with the same name enum used this between python versions 3 4 3 9 subclass from this to use a different method of accessing virtual attributes and still be treated properly by the inspect module enum uses this since python 3 10 next two lines make dynamicclassattribute act the same as property support for abstract methods todo implement this in c convert regular generator function to a coroutine check if func is a coroutine function 0x180 co_coroutine co_iterable_coroutine check if func is a generator function 0x20 co_generator todo implement this in c 0x100 co_iterable_coroutine the following code is primarily to support functions that return generator like objects for instance generators compiled with cython delay functools and _collections_abc import for speeding up types import coro is a native coroutine object or an iterable coroutine coro is either a pure python generator iterator or it implements collections abc generator and does not implement collections abc coroutine coro is either an instance of collections abc coroutine or some other object pass it through
import sys






def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None)         
CodeType = type(_f.__code__)
MappingProxyType = type(type.__dict__)
SimpleNamespace = type(sys.implementation)

def _cell_factory():
    a = 1
    def f():
        nonlocal a
    return f.__closure__[0]
CellType = type(_cell_factory())

def _g():
    yield 1
GeneratorType = type(_g())

async def _c(): pass
_c = _c()
CoroutineType = type(_c)
_c.close()  

async def _ag():
    yield
_ag = _ag()
AsyncGeneratorType = type(_ag)

class _C:
    def _m(self): pass
MethodType = type(_C()._m)

BuiltinFunctionType = type(len)
BuiltinMethodType = type([].append)     

WrapperDescriptorType = type(object.__init__)
MethodWrapperType = type(object().__str__)
MethodDescriptorType = type(str.join)
ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])

ModuleType = type(sys)

try:
    raise TypeError
except TypeError as exc:
    TracebackType = type(exc.__traceback__)
    FrameType = type(exc.__traceback__.tb_frame)

GetSetDescriptorType = type(FunctionType.__code__)
MemberDescriptorType = type(FunctionType.__globals__)

del sys, _f, _g, _C, _c, _ag, _cell_factory  



def new_class(name, bases=(), kwds=None, exec_body=None):
    
    resolved_bases = resolve_bases(bases)
    meta, ns, kwds = prepare_class(name, resolved_bases, kwds)
    if exec_body is not None:
        exec_body(ns)
    if resolved_bases is not bases:
        ns['__orig_bases__'] = bases
    return meta(name, resolved_bases, ns, **kwds)

def resolve_bases(bases):
    
    new_bases = list(bases)
    updated = False
    shift = 0
    for i, base in enumerate(bases):
        if isinstance(base, type):
            continue
        if not hasattr(base, "__mro_entries__"):
            continue
        new_base = base.__mro_entries__(bases)
        updated = True
        if not isinstance(new_base, tuple):
            raise TypeError("__mro_entries__ must return a tuple")
        else:
            new_bases[i+shift:i+shift+1] = new_base
            shift += len(new_base) - 1
    if not updated:
        return bases
    return tuple(new_bases)

def prepare_class(name, bases=(), kwds=None):
    
    if kwds is None:
        kwds = {}
    else:
        kwds = dict(kwds) 
    if 'metaclass' in kwds:
        meta = kwds.pop('metaclass')
    else:
        if bases:
            meta = type(bases[0])
        else:
            meta = type
    if isinstance(meta, type):
        
        
        meta = _calculate_meta(meta, bases)
    if hasattr(meta, '__prepare__'):
        ns = meta.__prepare__(name, bases, **kwds)
    else:
        ns = {}
    return meta, ns, kwds

def _calculate_meta(meta, bases):
    
    winner = meta
    for base in bases:
        base_meta = type(base)
        if issubclass(winner, base_meta):
            continue
        if issubclass(base_meta, winner):
            winner = base_meta
            continue
        
        raise TypeError("metaclass conflict: "
                        "the metaclass of a derived class "
                        "must be a (non-strict) subclass "
                        "of the metaclasses of all its bases")
    return winner


def get_original_bases(cls, /):
    
    try:
        return cls.__dict__.get("__orig_bases__", cls.__bases__)
    except AttributeError:
        raise TypeError(
            f"Expected an instance of type, not {type(cls).__name__!r}"
        ) from None


class DynamicClassAttribute:
    
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        
        self.__doc__ = doc or fget.__doc__
        self.overwrite_doc = doc is None
        
        self.__isabstractmethod__ = bool(getattr(fget, '__isabstractmethod__', False))

    def __get__(self, instance, ownerclass=None):
        if instance is None:
            if self.__isabstractmethod__:
                return self
            raise AttributeError()
        elif self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(instance)

    def __set__(self, instance, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(instance, value)

    def __delete__(self, instance):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(instance)

    def getter(self, fget):
        fdoc = fget.__doc__ if self.overwrite_doc else None
        result = type(self)(fget, self.fset, self.fdel, fdoc or self.__doc__)
        result.overwrite_doc = self.overwrite_doc
        return result

    def setter(self, fset):
        result = type(self)(self.fget, fset, self.fdel, self.__doc__)
        result.overwrite_doc = self.overwrite_doc
        return result

    def deleter(self, fdel):
        result = type(self)(self.fget, self.fset, fdel, self.__doc__)
        result.overwrite_doc = self.overwrite_doc
        return result


class _GeneratorWrapper:
    
    def __init__(self, gen):
        self.__wrapped = gen
        self.__isgen = gen.__class__ is GeneratorType
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None)
    def send(self, val):
        return self.__wrapped.send(val)
    def throw(self, tp, *rest):
        return self.__wrapped.throw(tp, *rest)
    def close(self):
        return self.__wrapped.close()
    @property
    def gi_code(self):
        return self.__wrapped.gi_code
    @property
    def gi_frame(self):
        return self.__wrapped.gi_frame
    @property
    def gi_running(self):
        return self.__wrapped.gi_running
    @property
    def gi_yieldfrom(self):
        return self.__wrapped.gi_yieldfrom
    cr_code = gi_code
    cr_frame = gi_frame
    cr_running = gi_running
    cr_await = gi_yieldfrom
    def __next__(self):
        return next(self.__wrapped)
    def __iter__(self):
        if self.__isgen:
            return self.__wrapped
        return self
    __await__ = __iter__

def coroutine(func):
    

    if not callable(func):
        raise TypeError('types.coroutine() expects a callable')

    if (func.__class__ is FunctionType and
        getattr(func, '__code__', None).__class__ is CodeType):

        co_flags = func.__code__.co_flags

        
        
        if co_flags & 0x180:
            return func

        
        
        if co_flags & 0x20:
            
            co = func.__code__
            
            func.__code__ = co.replace(co_flags=co.co_flags | 0x100)
            return func

    
    
    

    
    import functools
    import _collections_abc
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        coro = func(*args, **kwargs)
        if (coro.__class__ is CoroutineType or
            coro.__class__ is GeneratorType and coro.gi_code.co_flags & 0x100):
            
            return coro
        if (isinstance(coro, _collections_abc.Generator) and
            not isinstance(coro, _collections_abc.Coroutine)):
            
            
            
            return _GeneratorWrapper(coro)
        
        
        return coro

    return wrapped

GenericAlias = type(list[int])
UnionType = type(int | str)

EllipsisType = type(Ellipsis)
NoneType = type(None)
NotImplementedType = type(NotImplemented)

def __getattr__(name):
    if name == 'CapsuleType':
        import _socket
        return type(_socket.CAPI)
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

__all__ = [n for n in globals() if n[:1] != '_']
__all__ += ['CapsuleType']