1:mod:`types` --- Dynamic type creation and names for built-in types
2===================================================================
3
4.. module:: types
5   :synopsis: Names for built-in types.
6
7**Source code:** :source:`Lib/types.py`
8
9--------------
10
11This module defines utility functions to assist in dynamic creation of
12new types.
13
14It also defines names for some object types that are used by the standard
15Python interpreter, but not exposed as builtins like :class:`int` or
16:class:`str` are.
17
18Finally, it provides some additional type-related utility classes and functions
19that are not fundamental enough to be builtins.
20
21
22Dynamic Type Creation
23---------------------
24
25.. function:: new_class(name, bases=(), kwds=None, exec_body=None)
26
27   Creates a class object dynamically using the appropriate metaclass.
28
29   The first three arguments are the components that make up a class
30   definition header: the class name, the base classes (in order), the
31   keyword arguments (such as ``metaclass``).
32
33   The *exec_body* argument is a callback that is used to populate the
34   freshly created class namespace. It should accept the class namespace
35   as its sole argument and update the namespace directly with the class
36   contents. If no callback is provided, it has the same effect as passing
37   in ``lambda ns: None``.
38
39   .. versionadded:: 3.3
40
41.. function:: prepare_class(name, bases=(), kwds=None)
42
43   Calculates the appropriate metaclass and creates the class namespace.
44
45   The arguments are the components that make up a class definition header:
46   the class name, the base classes (in order) and the keyword arguments
47   (such as ``metaclass``).
48
49   The return value is a 3-tuple: ``metaclass, namespace, kwds``
50
51   *metaclass* is the appropriate metaclass, *namespace* is the
52   prepared class namespace and *kwds* is an updated copy of the passed
53   in *kwds* argument with any ``'metaclass'`` entry removed. If no *kwds*
54   argument is passed in, this will be an empty dict.
55
56   .. versionadded:: 3.3
57
58   .. versionchanged:: 3.6
59
60      The default value for the ``namespace`` element of the returned
61      tuple has changed.  Now an insertion-order-preserving mapping is
62      used when the metaclass does not have a ``__prepare__`` method.
63
64.. seealso::
65
66   :ref:`metaclasses`
67      Full details of the class creation process supported by these functions
68
69   :pep:`3115` - Metaclasses in Python 3000
70      Introduced the ``__prepare__`` namespace hook
71
72.. function:: resolve_bases(bases)
73
74   Resolve MRO entries dynamically as specified by :pep:`560`.
75
76   This function looks for items in *bases* that are not instances of
77   :class:`type`, and returns a tuple where each such object that has
78   an :meth:`~object.__mro_entries__` method is replaced with an unpacked result of
79   calling this method.  If a *bases* item is an instance of :class:`type`,
80   or it doesn't have an :meth:`!__mro_entries__` method, then it is included in
81   the return tuple unchanged.
82
83   .. versionadded:: 3.7
84
85.. seealso::
86
87   :pep:`560` - Core support for typing module and generic types
88
89
90Standard Interpreter Types
91--------------------------
92
93This module provides names for many of the types that are required to
94implement a Python interpreter. It deliberately avoids including some of
95the types that arise only incidentally during processing such as the
96``listiterator`` type.
97
98Typical use of these names is for :func:`isinstance` or
99:func:`issubclass` checks.
100
101
102If you instantiate any of these types, note that signatures may vary between Python versions.
103
104Standard names are defined for the following types:
105
106.. data:: NoneType
107
108   The type of :data:`None`.
109
110   .. versionadded:: 3.10
111
112
113.. data:: FunctionType
114          LambdaType
115
116   The type of user-defined functions and functions created by
117   :keyword:`lambda`  expressions.
118
119   .. audit-event:: function.__new__ code types.FunctionType
120
121   The audit event only occurs for direct instantiation of function objects,
122   and is not raised for normal compilation.
123
124
125.. data:: GeneratorType
126
127   The type of :term:`generator`-iterator objects, created by
128   generator functions.
129
130
131.. data:: CoroutineType
132
133   The type of :term:`coroutine` objects, created by
134   :keyword:`async def` functions.
135
136   .. versionadded:: 3.5
137
138
139.. data:: AsyncGeneratorType
140
141   The type of :term:`asynchronous generator`-iterator objects, created by
142   asynchronous generator functions.
143
144   .. versionadded:: 3.6
145
146
147.. class:: CodeType(**kwargs)
148
149   .. index:: pair: built-in function; compile
150
151   The type for code objects such as returned by :func:`compile`.
152
153   .. audit-event:: code.__new__ code,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags types.CodeType
154
155   Note that the audited arguments may not match the names or positions
156   required by the initializer.  The audit event only occurs for direct
157   instantiation of code objects, and is not raised for normal compilation.
158
159   .. method:: CodeType.replace(**kwargs)
160
161     Return a copy of the code object with new values for the specified fields.
162
163     .. versionadded:: 3.8
164
165.. data:: CellType
166
167   The type for cell objects: such objects are used as containers for
168   a function's free variables.
169
170   .. versionadded:: 3.8
171
172
173.. data:: MethodType
174
175   The type of methods of user-defined class instances.
176
177
178.. data:: BuiltinFunctionType
179          BuiltinMethodType
180
181   The type of built-in functions like :func:`len` or :func:`sys.exit`, and
182   methods of built-in classes.  (Here, the term "built-in" means "written in
183   C".)
184
185
186.. data:: WrapperDescriptorType
187
188   The type of methods of some built-in data types and base classes such as
189   :meth:`object.__init__` or :meth:`object.__lt__`.
190
191   .. versionadded:: 3.7
192
193
194.. data:: MethodWrapperType
195
196   The type of *bound* methods of some built-in data types and base classes.
197   For example it is the type of :code:`object().__str__`.
198
199   .. versionadded:: 3.7
200
201
202.. data:: NotImplementedType
203
204   The type of :data:`NotImplemented`.
205
206   .. versionadded:: 3.10
207
208
209.. data:: MethodDescriptorType
210
211   The type of methods of some built-in data types such as :meth:`str.join`.
212
213   .. versionadded:: 3.7
214
215
216.. data:: ClassMethodDescriptorType
217
218   The type of *unbound* class methods of some built-in data types such as
219   ``dict.__dict__['fromkeys']``.
220
221   .. versionadded:: 3.7
222
223
224.. class:: ModuleType(name, doc=None)
225
226   The type of :term:`modules <module>`. The constructor takes the name of the
227   module to be created and optionally its :term:`docstring`.
228
229   .. note::
230      Use :func:`importlib.util.module_from_spec` to create a new module if you
231      wish to set the various import-controlled attributes.
232
233   .. attribute:: __doc__
234
235      The :term:`docstring` of the module. Defaults to ``None``.
236
237   .. attribute:: __loader__
238
239      The :term:`loader` which loaded the module. Defaults to ``None``.
240
241      This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader`
242      as stored in the :attr:`__spec__` object.
243
244      .. note::
245         A future version of Python may stop setting this attribute by default.
246         To guard against this potential change, preferably read from the
247         :attr:`__spec__` attribute instead or use
248         ``getattr(module, "__loader__", None)`` if you explicitly need to use
249         this attribute.
250
251      .. versionchanged:: 3.4
252         Defaults to ``None``. Previously the attribute was optional.
253
254   .. attribute:: __name__
255
256      The name of the module. Expected to match
257      :attr:`importlib.machinery.ModuleSpec.name`.
258
259   .. attribute:: __package__
260
261      Which :term:`package` a module belongs to. If the module is top-level
262      (i.e. not a part of any specific package) then the attribute should be set
263      to ``''``, else it should be set to the name of the package (which can be
264      :attr:`__name__` if the module is a package itself). Defaults to ``None``.
265
266      This attribute is to match :attr:`importlib.machinery.ModuleSpec.parent`
267      as stored in the :attr:`__spec__` object.
268
269      .. note::
270         A future version of Python may stop setting this attribute by default.
271         To guard against this potential change, preferably read from the
272         :attr:`__spec__` attribute instead or use
273         ``getattr(module, "__package__", None)`` if you explicitly need to use
274         this attribute.
275
276      .. versionchanged:: 3.4
277         Defaults to ``None``. Previously the attribute was optional.
278
279   .. attribute:: __spec__
280
281      A record of the module's import-system-related state. Expected to be an
282      instance of :class:`importlib.machinery.ModuleSpec`.
283
284      .. versionadded:: 3.4
285
286
287.. data:: EllipsisType
288
289   The type of :data:`Ellipsis`.
290
291   .. versionadded:: 3.10
292
293.. class:: GenericAlias(t_origin, t_args)
294
295   The type of :ref:`parameterized generics <types-genericalias>` such as
296   ``list[int]``.
297
298   ``t_origin`` should be a non-parameterized generic class, such as ``list``,
299   ``tuple`` or ``dict``.  ``t_args`` should be a :class:`tuple` (possibly of
300   length 1) of types which parameterize ``t_origin``::
301
302      >>> from types import GenericAlias
303
304      >>> list[int] == GenericAlias(list, (int,))
305      True
306      >>> dict[str, int] == GenericAlias(dict, (str, int))
307      True
308
309   .. versionadded:: 3.9
310
311   .. versionchanged:: 3.9.2
312      This type can now be subclassed.
313
314   .. seealso::
315
316      :ref:`Generic Alias Types<types-genericalias>`
317         In-depth documentation on instances of :class:`!types.GenericAlias`
318
319      :pep:`585` - Type Hinting Generics In Standard Collections
320         Introducing the :class:`!types.GenericAlias` class
321
322.. class:: UnionType
323
324   The type of :ref:`union type expressions<types-union>`.
325
326   .. versionadded:: 3.10
327
328.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
329
330   The type of traceback objects such as found in ``sys.exception().__traceback__``.
331
332   See :ref:`the language reference <traceback-objects>` for details of the
333   available attributes and operations, and guidance on creating tracebacks
334   dynamically.
335
336
337.. data:: FrameType
338
339   The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
340   traceback object.
341
342   See :ref:`the language reference <frame-objects>` for details of the
343   available attributes and operations.
344
345
346.. data:: GetSetDescriptorType
347
348   The type of objects defined in extension modules with ``PyGetSetDef``, such
349   as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
350   descriptor for object attributes; it has the same purpose as the
351   :class:`property` type, but for classes defined in extension modules.
352
353
354.. data:: MemberDescriptorType
355
356   The type of objects defined in extension modules with ``PyMemberDef``, such
357   as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
358   data members which use standard conversion functions; it has the same purpose
359   as the :class:`property` type, but for classes defined in extension modules.
360
361   .. impl-detail::
362
363      In other implementations of Python, this type may be identical to
364      ``GetSetDescriptorType``.
365
366.. class:: MappingProxyType(mapping)
367
368   Read-only proxy of a mapping. It provides a dynamic view on the mapping's
369   entries, which means that when the mapping changes, the view reflects these
370   changes.
371
372   .. versionadded:: 3.3
373
374   .. versionchanged:: 3.9
375
376      Updated to support the new union (``|``) operator from :pep:`584`, which
377      simply delegates to the underlying mapping.
378
379   .. describe:: key in proxy
380
381      Return ``True`` if the underlying mapping has a key *key*, else
382      ``False``.
383
384   .. describe:: proxy[key]
385
386      Return the item of the underlying mapping with key *key*.  Raises a
387      :exc:`KeyError` if *key* is not in the underlying mapping.
388
389   .. describe:: iter(proxy)
390
391      Return an iterator over the keys of the underlying mapping.  This is a
392      shortcut for ``iter(proxy.keys())``.
393
394   .. describe:: len(proxy)
395
396      Return the number of items in the underlying mapping.
397
398   .. method:: copy()
399
400      Return a shallow copy of the underlying mapping.
401
402   .. method:: get(key[, default])
403
404      Return the value for *key* if *key* is in the underlying mapping, else
405      *default*.  If *default* is not given, it defaults to ``None``, so that
406      this method never raises a :exc:`KeyError`.
407
408   .. method:: items()
409
410      Return a new view of the underlying mapping's items (``(key, value)``
411      pairs).
412
413   .. method:: keys()
414
415      Return a new view of the underlying mapping's keys.
416
417   .. method:: values()
418
419      Return a new view of the underlying mapping's values.
420
421   .. describe:: reversed(proxy)
422
423      Return a reverse iterator over the keys of the underlying mapping.
424
425      .. versionadded:: 3.9
426
427
428Additional Utility Classes and Functions
429----------------------------------------
430
431.. class:: SimpleNamespace
432
433   A simple :class:`object` subclass that provides attribute access to its
434   namespace, as well as a meaningful repr.
435
436   Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
437   attributes.  If a ``SimpleNamespace`` object is initialized with keyword
438   arguments, those are directly added to the underlying namespace.
439
440   The type is roughly equivalent to the following code::
441
442       class SimpleNamespace:
443           def __init__(self, /, **kwargs):
444               self.__dict__.update(kwargs)
445
446           def __repr__(self):
447               items = (f"{k}={v!r}" for k, v in self.__dict__.items())
448               return "{}({})".format(type(self).__name__, ", ".join(items))
449
450           def __eq__(self, other):
451               if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
452                  return self.__dict__ == other.__dict__
453               return NotImplemented
454
455   ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
456   However, for a structured record type use :func:`~collections.namedtuple`
457   instead.
458
459   .. versionadded:: 3.3
460
461   .. versionchanged:: 3.9
462      Attribute order in the repr changed from alphabetical to insertion (like
463      ``dict``).
464
465.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
466
467   Route attribute access on a class to __getattr__.
468
469   This is a descriptor, used to define attributes that act differently when
470   accessed through an instance and through a class.  Instance access remains
471   normal, but access to an attribute through a class will be routed to the
472   class's __getattr__ method; this is done by raising AttributeError.
473
474   This allows one to have properties active on an instance, and have virtual
475   attributes on the class with the same name (see :class:`enum.Enum` for an example).
476
477   .. versionadded:: 3.4
478
479
480Coroutine Utility Functions
481---------------------------
482
483.. function:: coroutine(gen_func)
484
485   This function transforms a :term:`generator` function into a
486   :term:`coroutine function` which returns a generator-based coroutine.
487   The generator-based coroutine is still a :term:`generator iterator`,
488   but is also considered to be a :term:`coroutine` object and is
489   :term:`awaitable`.  However, it may not necessarily implement
490   the :meth:`~object.__await__` method.
491
492   If *gen_func* is a generator function, it will be modified in-place.
493
494   If *gen_func* is not a generator function, it will be wrapped. If it
495   returns an instance of :class:`collections.abc.Generator`, the instance
496   will be wrapped in an *awaitable* proxy object.  All other types
497   of objects will be returned as is.
498
499   .. versionadded:: 3.5
500