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

Source code:Lib/types.py


This module defines utility function 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.

8.9.1.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:ns.

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

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

Standard names are defined for the following types:

types.FunctionType
types.LambdaType

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

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.

types.CodeType

The type for code objects such as returned bycompile().

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

classtypes.ModuleType(name,doc=None)

The type ofmodules. 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.

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

__name__

The name of the module.

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

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

types.TracebackType

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

types.FrameType

The type of frame objects such as found intb.tb_frame iftb is atraceback 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.

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.

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.

8.9.3.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):keys=sorted(self.__dict__)items=("{}={!r}".format(k,self.__dict__[k])forkinkeys)return"{}({})".format(type(self).__name__,", ".join(items))def__eq__(self,other):returnself.__dict__==other.__dict__

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

New in version 3.3.

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 (see Enum for an example).

New in version 3.4.

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