types — Dynamic type creation and names for built-in types

Source code:Lib/types.py


This module defines utility functions to assist in dynamic creation ofnew types.

It also defines names for some object types that are used by the standardPython interpreter, but not exposed as builtins likeint orstr are.

Finally, it provides some additional type-related utility classes and functionsthat are not fundamental enough to be builtins.

Dynamic Type Creation

types.new_class(name,bases=(),kwds=None,exec_body=None)

Creates a class object dynamically using the appropriate metaclass.

The first three arguments are the components that make up a classdefinition header: the class name, the base classes (in order), thekeyword arguments (such asmetaclass).

Theexec_body argument is a callback that is used to populate thefreshly created class namespace. It should accept the class namespaceas its sole argument and update the namespace directly with the classcontents. If no callback is provided, it has the same effect as passinginlambdans:None.

Added in version 3.3.

types.prepare_class(name,bases=(),kwds=None)

Calculates the appropriate metaclass and creates the class namespace.

The arguments are the components that make up a class definition header:the class name, the base classes (in order) and the keyword arguments(such asmetaclass).

The return value is a 3-tuple:metaclass,namespace,kwds

metaclass is the appropriate metaclass,namespace is theprepared class namespace andkwds is an updated copy of the passedinkwds argument with any'metaclass' entry removed. If nokwdsargument is passed in, this will be an empty dict.

Added in version 3.3.

Changed in version 3.6:The default value for thenamespace element of the returnedtuple has changed. Now an insertion-order-preserving mapping isused when the metaclass does not have a__prepare__ method.

See also

Metaclasses

Full details of the class creation process supported by these functions

PEP 3115 - Metaclasses in Python 3000

Introduced the__prepare__ namespace hook

types.resolve_bases(bases)

Resolve MRO entries dynamically as specified byPEP 560.

This function looks for items inbases that are not instances oftype, and returns a tuple where each such object that hasan__mro_entries__() method is replaced with an unpacked result ofcalling this method. If abases item is an instance oftype,or it doesn’t have an__mro_entries__() method, then it is included inthe return tuple unchanged.

Added in version 3.7.

types.get_original_bases(cls,/)

Return the tuple of objects originally given as the bases ofcls beforethe__mro_entries__() method has been called on any bases(following the mechanisms laid out inPEP 560). This is useful forintrospectingGenerics.

For classes that have an__orig_bases__ attribute, thisfunction returns the value ofcls.__orig_bases__.For classes without the__orig_bases__ attribute,cls.__bases__ is returned.

Examples:

fromtypingimportTypeVar,Generic,NamedTuple,TypedDictT=TypeVar("T")classFoo(Generic[T]):...classBar(Foo[int],float):...classBaz(list[str]):...Eggs=NamedTuple("Eggs",[("a",int),("b",str)])Spam=TypedDict("Spam",{"a":int,"b":str})assertBar.__bases__==(Foo,float)assertget_original_bases(Bar)==(Foo[int],float)assertBaz.__bases__==(list,)assertget_original_bases(Baz)==(list[str],)assertEggs.__bases__==(tuple,)assertget_original_bases(Eggs)==(NamedTuple,)assertSpam.__bases__==(dict,)assertget_original_bases(Spam)==(TypedDict,)assertint.__bases__==(object,)assertget_original_bases(int)==(object,)

Added in version 3.12.

See also

PEP 560 - Core support for typing module and generic types

Standard Interpreter Types

This module provides names for many of the types that are required toimplement a Python interpreter. It deliberately avoids including some ofthe types that arise only incidentally during processing such as thelistiterator type.

Typical use of these names is forisinstance() orissubclass() checks.

If you instantiate any of these types, note that signatures may vary between Python versions.

Standard names are defined for the following types:

types.NoneType

The type ofNone.

Added in version 3.10.

types.FunctionType
types.LambdaType

The type of user-defined functions and functions created bylambda expressions.

Raises anauditing eventfunction.__new__ with argumentcode.

The audit event only occurs for direct instantiation of function objects,and is not raised for normal compilation.

types.GeneratorType

The type ofgenerator-iterator objects, created bygenerator functions.

types.CoroutineType

The type ofcoroutine objects, created byasyncdef functions.

Added in version 3.5.

types.AsyncGeneratorType

The type ofasynchronous generator-iterator objects, created byasynchronous generator functions.

Added in version 3.6.

classtypes.CodeType(**kwargs)

The type ofcode objects such as returned bycompile().

Raises anauditing eventcode.__new__ with argumentscode,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags.

Note that the audited arguments may not match the names or positionsrequired by the initializer. The audit event only occurs for directinstantiation of code objects, and is not raised for normal compilation.

types.CellType

The type for cell objects: such objects are used as containers fora function’sclosure variables.

Added in version 3.8.

types.MethodType

The type of methods of user-defined class instances.

types.BuiltinFunctionType
types.BuiltinMethodType

The type of built-in functions likelen() orsys.exit(), andmethods of built-in classes. (Here, the term “built-in” means “written inC”.)

types.WrapperDescriptorType

The type of methods of some built-in data types and base classes such asobject.__init__() orobject.__lt__().

Added in version 3.7.

types.MethodWrapperType

The type ofbound methods of some built-in data types and base classes.For example it is the type ofobject().__str__.

Added in version 3.7.

types.NotImplementedType

The type ofNotImplemented.

Added in version 3.10.

types.MethodDescriptorType

The type of methods of some built-in data types such asstr.join().

Added in version 3.7.

types.ClassMethodDescriptorType

The type ofunbound class methods of some built-in data types such asdict.__dict__['fromkeys'].

Added in version 3.7.

classtypes.ModuleType(name,doc=None)

The type ofmodules. The constructor takes the name of themodule to be created and optionally itsdocstring.

See also

Documentation on module objects

Provides details on the special attributes that can be found oninstances ofModuleType.

importlib.util.module_from_spec()

Modules created using theModuleType constructor arecreated with many of their special attributes unset or set to defaultvalues.module_from_spec() provides a more robust way ofcreatingModuleType instances which ensures the variousattributes are set appropriately.

types.EllipsisType

The type ofEllipsis.

Added in version 3.10.

classtypes.GenericAlias(t_origin,t_args)

The type ofparameterized generics such aslist[int].

t_origin should be a non-parameterized generic class, such aslist,tuple ordict.t_args should be atuple (possibly oflength 1) of types which parameterizet_origin:

>>>fromtypesimportGenericAlias>>>list[int]==GenericAlias(list,(int,))True>>>dict[str,int]==GenericAlias(dict,(str,int))True

Added in version 3.9.

Changed in version 3.9.2:This type can now be subclassed.

See also

Generic Alias Types

In-depth documentation on instances oftypes.GenericAlias

PEP 585 - Type Hinting Generics In Standard Collections

Introducing thetypes.GenericAlias class

classtypes.UnionType

The type ofunion type expressions.

Added in version 3.10.

classtypes.TracebackType(tb_next,tb_frame,tb_lasti,tb_lineno)

The type of traceback objects such as found insys.exception().__traceback__.

Seethe language reference for details of theavailable attributes and operations, and guidance on creating tracebacksdynamically.

types.FrameType

The type offrame objects such as found intb.tb_frame iftb is a traceback object.

types.GetSetDescriptorType

The type of objects defined in extension modules withPyGetSetDef, suchasFrameType.f_locals orarray.array.typecode.This type is used asdescriptor for object attributes; it has the same purpose as theproperty type, but for classes defined in extension modules.

types.MemberDescriptorType

The type of objects defined in extension modules withPyMemberDef, suchasdatetime.timedelta.days. This type is used as descriptor for simple Cdata members which use standard conversion functions; it has the same purposeas theproperty type, but for classes defined in extension modules.

In addition, when a class is defined with a__slots__ attribute, then foreach slot, an instance ofMemberDescriptorType will be added as an attributeon the class. This allows the slot to appear in the class’s__dict__.

CPython implementation detail: In other implementations of Python, this type may be identical toGetSetDescriptorType.

classtypes.MappingProxyType(mapping)

Read-only proxy of a mapping. It provides a dynamic view on the mapping’sentries, which means that when the mapping changes, the view reflects thesechanges.

Added in version 3.3.

Changed in version 3.9:Updated to support the new union (|) operator fromPEP 584, whichsimply delegates to the underlying mapping.

keyinproxy

ReturnTrue if the underlying mapping has a keykey, elseFalse.

proxy[key]

Return the item of the underlying mapping with keykey. Raises aKeyError ifkey is not in the underlying mapping.

iter(proxy)

Return an iterator over the keys of the underlying mapping. This is ashortcut foriter(proxy.keys()).

len(proxy)

Return the number of items in the underlying mapping.

copy()

Return a shallow copy of the underlying mapping.

get(key[,default])

Return the value forkey ifkey is in the underlying mapping, elsedefault. Ifdefault is not given, it defaults toNone, so thatthis method never raises aKeyError.

items()

Return a new view of the underlying mapping’s items ((key,value)pairs).

keys()

Return a new view of the underlying mapping’s keys.

values()

Return a new view of the underlying mapping’s values.

reversed(proxy)

Return a reverse iterator over the keys of the underlying mapping.

Added in version 3.9.

hash(proxy)

Return a hash of the underlying mapping.

Added in version 3.12.

classtypes.CapsuleType

The type ofcapsule objects.

Added in version 3.13.

Additional Utility Classes and Functions

classtypes.SimpleNamespace

A simpleobject subclass that provides attribute access to itsnamespace, as well as a meaningful repr.

Unlikeobject, withSimpleNamespace you can add and removeattributes.

SimpleNamespace objects may be initializedin the same way asdict: either with keyword arguments,with a single positional argument, or with both.When initialized with keyword arguments,those are directly added to the underlying namespace.Alternatively, when initialized with a positional argument,the underlying namespace will be updated with key-value pairsfrom that argument (either a mapping object oraniterable object producing key-value pairs).All such keys must be strings.

The type is roughly equivalent to the following code:

classSimpleNamespace:def__init__(self,mapping_or_iterable=(),/,**kwargs):self.__dict__.update(mapping_or_iterable)self.__dict__.update(kwargs)def__repr__(self):items=(f"{k}={v!r}"fork,vinself.__dict__.items())return"{}({})".format(type(self).__name__,", ".join(items))def__eq__(self,other):ifisinstance(self,SimpleNamespace)andisinstance(other,SimpleNamespace):returnself.__dict__==other.__dict__returnNotImplemented

SimpleNamespace may be useful as a replacement forclassNS:pass.However, for a structured record type usenamedtuple()instead.

SimpleNamespace objects are supported bycopy.replace().

Added in version 3.3.

Changed in version 3.9:Attribute order in the repr changed from alphabetical to insertion (likedict).

Changed in version 3.13:Added support for an optional positional argument.

types.DynamicClassAttribute(fget=None,fset=None,fdel=None,doc=None)

Route attribute access on a class to __getattr__.

This is a descriptor, used to define attributes that act differently whenaccessed through an instance and through a class. Instance access remainsnormal, but access to an attribute through a class will be routed to theclass’s __getattr__ method; this is done by raising AttributeError.

This allows one to have properties active on an instance, and have virtualattributes on the class with the same name (seeenum.Enum for an example).

Added in version 3.4.

Coroutine Utility Functions

types.coroutine(gen_func)

This function transforms agenerator function into acoroutine function which returns a generator-based coroutine.The generator-based coroutine is still agenerator iterator,but is also considered to be acoroutine object and isawaitable. However, it may not necessarily implementthe__await__() method.

Ifgen_func is a generator function, it will be modified in-place.

Ifgen_func is not a generator function, it will be wrapped. If itreturns an instance ofcollections.abc.Generator, the instancewill be wrapped in anawaitable proxy object. All other typesof objects will be returned as is.

Added in version 3.5.