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.

New 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.

New 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.

New in version 3.7.

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.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.

New in version 3.5.

types.AsyncGeneratorType

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

New in version 3.6.

classtypes.CodeType(**kwargs)

The type for code 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.

replace(**kwargs)

Return a copy of the code object with new values for the specified fields.

New in version 3.8.

types.CellType

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

New 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__().

New 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__.

New in version 3.7.

types.MethodDescriptorType

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

New in version 3.7.

types.ClassMethodDescriptorType

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

New 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.

Note

Useimportlib.util.module_from_spec() to create a new module if youwish to set the various import-controlled attributes.

__doc__

Thedocstring of the module. Defaults toNone.

__loader__

Theloader which loaded the module. Defaults toNone.

This attribute is to matchimportlib.machinery.ModuleSpec.loaderas stored in the attr:__spec__ object.

Note

A future version of Python may stop setting this attribute by default.To guard against this potential change, preferably read from the__spec__ attribute instead or usegetattr(module,"__loader__",None) if you explicitly need to usethis attribute.

Changed in version 3.4:Defaults toNone. Previously the attribute was optional.

__name__

The name of the module. Expected to matchimportlib.machinery.ModuleSpec.name.

__package__

Whichpackage a module belongs to. If the module is top-level(i.e. not a part of any specific package) then the attribute should be setto'', else it should be set to the name of the package (which can be__name__ if the module is a package itself). Defaults toNone.

This attribute is to matchimportlib.machinery.ModuleSpec.parentas stored in the attr:__spec__ object.

Note

A future version of Python may stop setting this attribute by default.To guard against this potential change, preferably read from the__spec__ attribute instead or usegetattr(module,"__package__",None) if you explicitly need to usethis attribute.

Changed in version 3.4:Defaults toNone. Previously the attribute was optional.

__spec__

A record of the module’s import-system-related state. Expected to be aninstance ofimportlib.machinery.ModuleSpec.

New in version 3.4.

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

New in version 3.9.

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

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

The type of traceback objects such as found insys.exc_info()[2].

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

types.FrameType

The type of frame objects such as found intb.tb_frame iftb is atraceback object.

Seethe language reference for details of theavailable attributes and operations.

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.

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.

New in version 3.3.

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

key in proxy

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.

New in version 3.9.

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. If aSimpleNamespace object is initialized with keywordarguments, those are directly added to the underlying namespace.

The type is roughly equivalent to the following code:

classSimpleNamespace:def__init__(self,/,**kwargs):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.

New in version 3.3.

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

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).

New 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.

New in version 3.5.