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 ``__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 ``__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:: FunctionType
107          LambdaType
108
109   The type of user-defined functions and functions created by
110   :keyword:`lambda`  expressions.
111
112   .. audit-event:: function.__new__ code types.FunctionType
113
114   The audit event only occurs for direct instantiation of function objects,
115   and is not raised for normal compilation.
116
117
118.. data:: GeneratorType
119
120   The type of :term:`generator`-iterator objects, created by
121   generator functions.
122
123
124.. data:: CoroutineType
125
126   The type of :term:`coroutine` objects, created by
127   :keyword:`async def` functions.
128
129   .. versionadded:: 3.5
130
131
132.. data:: AsyncGeneratorType
133
134   The type of :term:`asynchronous generator`-iterator objects, created by
135   asynchronous generator functions.
136
137   .. versionadded:: 3.6
138
139
140.. class:: CodeType(**kwargs)
141
142   .. index:: builtin: compile
143
144   The type for code objects such as returned by :func:`compile`.
145
146   .. audit-event:: code.__new__ code,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags types.CodeType
147
148   Note that the audited arguments may not match the names or positions
149   required by the initializer.  The audit event only occurs for direct
150   instantiation of code objects, and is not raised for normal compilation.
151
152   .. method:: CodeType.replace(**kwargs)
153
154     Return a copy of the code object with new values for the specified fields.
155
156     .. versionadded:: 3.8
157
158.. data:: CellType
159
160   The type for cell objects: such objects are used as containers for
161   a function's free variables.
162
163   .. versionadded:: 3.8
164
165
166.. data:: MethodType
167
168   The type of methods of user-defined class instances.
169
170
171.. data:: BuiltinFunctionType
172          BuiltinMethodType
173
174   The type of built-in functions like :func:`len` or :func:`sys.exit`, and
175   methods of built-in classes.  (Here, the term "built-in" means "written in
176   C".)
177
178
179.. data:: WrapperDescriptorType
180
181   The type of methods of some built-in data types and base classes such as
182   :meth:`object.__init__` or :meth:`object.__lt__`.
183
184   .. versionadded:: 3.7
185
186
187.. data:: MethodWrapperType
188
189   The type of *bound* methods of some built-in data types and base classes.
190   For example it is the type of :code:`object().__str__`.
191
192   .. versionadded:: 3.7
193
194
195.. data:: MethodDescriptorType
196
197   The type of methods of some built-in data types such as :meth:`str.join`.
198
199   .. versionadded:: 3.7
200
201
202.. data:: ClassMethodDescriptorType
203
204   The type of *unbound* class methods of some built-in data types such as
205   ``dict.__dict__['fromkeys']``.
206
207   .. versionadded:: 3.7
208
209
210.. class:: ModuleType(name, doc=None)
211
212   The type of :term:`modules <module>`. The constructor takes the name of the
213   module to be created and optionally its :term:`docstring`.
214
215   .. note::
216      Use :func:`importlib.util.module_from_spec` to create a new module if you
217      wish to set the various import-controlled attributes.
218
219   .. attribute:: __doc__
220
221      The :term:`docstring` of the module. Defaults to ``None``.
222
223   .. attribute:: __loader__
224
225      The :term:`loader` which loaded the module. Defaults to ``None``.
226
227      This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader`
228      as stored in the attr:`__spec__` object.
229
230      .. note::
231         A future version of Python may stop setting this attribute by default.
232         To guard against this potential change, preferrably read from the
233         :attr:`__spec__` attribute instead or use
234         ``getattr(module, "__loader__", None)`` if you explicitly need to use
235         this attribute.
236
237      .. versionchanged:: 3.4
238         Defaults to ``None``. Previously the attribute was optional.
239
240   .. attribute:: __name__
241
242      The name of the module. Expected to match
243      :attr:`importlib.machinery.ModuleSpec.name`.
244
245   .. attribute:: __package__
246
247      Which :term:`package` a module belongs to. If the module is top-level
248      (i.e. not a part of any specific package) then the attribute should be set
249      to ``''``, else it should be set to the name of the package (which can be
250      :attr:`__name__` if the module is a package itself). Defaults to ``None``.
251
252      This attribute is to match :attr:`importlib.machinery.ModuleSpec.parent`
253      as stored in the attr:`__spec__` object.
254
255      .. note::
256         A future version of Python may stop setting this attribute by default.
257         To guard against this potential change, preferrably read from the
258         :attr:`__spec__` attribute instead or use
259         ``getattr(module, "__package__", None)`` if you explicitly need to use
260         this attribute.
261
262      .. versionchanged:: 3.4
263         Defaults to ``None``. Previously the attribute was optional.
264
265   .. attribute:: __spec__
266
267      A record of the the module's import-system-related state. Expected to be
268      an instance of :class:`importlib.machinery.ModuleSpec`.
269
270      .. versionadded:: 3.4
271
272
273.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
274
275   The type of traceback objects such as found in ``sys.exc_info()[2]``.
276
277   See :ref:`the language reference <traceback-objects>` for details of the
278   available attributes and operations, and guidance on creating tracebacks
279   dynamically.
280
281
282.. data:: FrameType
283
284   The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
285   traceback object.
286
287   See :ref:`the language reference <frame-objects>` for details of the
288   available attributes and operations.
289
290
291.. data:: GetSetDescriptorType
292
293   The type of objects defined in extension modules with ``PyGetSetDef``, such
294   as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
295   descriptor for object attributes; it has the same purpose as the
296   :class:`property` type, but for classes defined in extension modules.
297
298
299.. data:: MemberDescriptorType
300
301   The type of objects defined in extension modules with ``PyMemberDef``, such
302   as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
303   data members which use standard conversion functions; it has the same purpose
304   as the :class:`property` type, but for classes defined in extension modules.
305
306   .. impl-detail::
307
308      In other implementations of Python, this type may be identical to
309      ``GetSetDescriptorType``.
310
311.. class:: MappingProxyType(mapping)
312
313   Read-only proxy of a mapping. It provides a dynamic view on the mapping's
314   entries, which means that when the mapping changes, the view reflects these
315   changes.
316
317   .. versionadded:: 3.3
318
319   .. describe:: key in proxy
320
321      Return ``True`` if the underlying mapping has a key *key*, else
322      ``False``.
323
324   .. describe:: proxy[key]
325
326      Return the item of the underlying mapping with key *key*.  Raises a
327      :exc:`KeyError` if *key* is not in the underlying mapping.
328
329   .. describe:: iter(proxy)
330
331      Return an iterator over the keys of the underlying mapping.  This is a
332      shortcut for ``iter(proxy.keys())``.
333
334   .. describe:: len(proxy)
335
336      Return the number of items in the underlying mapping.
337
338   .. method:: copy()
339
340      Return a shallow copy of the underlying mapping.
341
342   .. method:: get(key[, default])
343
344      Return the value for *key* if *key* is in the underlying mapping, else
345      *default*.  If *default* is not given, it defaults to ``None``, so that
346      this method never raises a :exc:`KeyError`.
347
348   .. method:: items()
349
350      Return a new view of the underlying mapping's items (``(key, value)``
351      pairs).
352
353   .. method:: keys()
354
355      Return a new view of the underlying mapping's keys.
356
357   .. method:: values()
358
359      Return a new view of the underlying mapping's values.
360
361
362Additional Utility Classes and Functions
363----------------------------------------
364
365.. class:: SimpleNamespace
366
367   A simple :class:`object` subclass that provides attribute access to its
368   namespace, as well as a meaningful repr.
369
370   Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
371   attributes.  If a ``SimpleNamespace`` object is initialized with keyword
372   arguments, those are directly added to the underlying namespace.
373
374   The type is roughly equivalent to the following code::
375
376       class SimpleNamespace:
377           def __init__(self, /, **kwargs):
378               self.__dict__.update(kwargs)
379
380           def __repr__(self):
381               keys = sorted(self.__dict__)
382               items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
383               return "{}({})".format(type(self).__name__, ", ".join(items))
384
385           def __eq__(self, other):
386               if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
387                  return self.__dict__ == other.__dict__
388               return NotImplemented
389
390   ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
391   However, for a structured record type use :func:`~collections.namedtuple`
392   instead.
393
394   .. versionadded:: 3.3
395
396
397.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
398
399   Route attribute access on a class to __getattr__.
400
401   This is a descriptor, used to define attributes that act differently when
402   accessed through an instance and through a class.  Instance access remains
403   normal, but access to an attribute through a class will be routed to the
404   class's __getattr__ method; this is done by raising AttributeError.
405
406   This allows one to have properties active on an instance, and have virtual
407   attributes on the class with the same name (see Enum for an example).
408
409   .. versionadded:: 3.4
410
411
412Coroutine Utility Functions
413---------------------------
414
415.. function:: coroutine(gen_func)
416
417   This function transforms a :term:`generator` function into a
418   :term:`coroutine function` which returns a generator-based coroutine.
419   The generator-based coroutine is still a :term:`generator iterator`,
420   but is also considered to be a :term:`coroutine` object and is
421   :term:`awaitable`.  However, it may not necessarily implement
422   the :meth:`__await__` method.
423
424   If *gen_func* is a generator function, it will be modified in-place.
425
426   If *gen_func* is not a generator function, it will be wrapped. If it
427   returns an instance of :class:`collections.abc.Generator`, the instance
428   will be wrapped in an *awaitable* proxy object.  All other types
429   of objects will be returned as is.
430
431   .. versionadded:: 3.5
432