• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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:: 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:: builtin: 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
315.. class:: UnionType
316
317   The type of :ref:`union type expressions<types-union>`.
318
319   .. versionadded:: 3.10
320
321.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
322
323   The type of traceback objects such as found in ``sys.exc_info()[2]``.
324
325   See :ref:`the language reference <traceback-objects>` for details of the
326   available attributes and operations, and guidance on creating tracebacks
327   dynamically.
328
329
330.. data:: FrameType
331
332   The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
333   traceback object.
334
335   See :ref:`the language reference <frame-objects>` for details of the
336   available attributes and operations.
337
338
339.. data:: GetSetDescriptorType
340
341   The type of objects defined in extension modules with ``PyGetSetDef``, such
342   as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
343   descriptor for object attributes; it has the same purpose as the
344   :class:`property` type, but for classes defined in extension modules.
345
346
347.. data:: MemberDescriptorType
348
349   The type of objects defined in extension modules with ``PyMemberDef``, such
350   as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
351   data members which use standard conversion functions; it has the same purpose
352   as the :class:`property` type, but for classes defined in extension modules.
353
354   .. impl-detail::
355
356      In other implementations of Python, this type may be identical to
357      ``GetSetDescriptorType``.
358
359.. class:: MappingProxyType(mapping)
360
361   Read-only proxy of a mapping. It provides a dynamic view on the mapping's
362   entries, which means that when the mapping changes, the view reflects these
363   changes.
364
365   .. versionadded:: 3.3
366
367   .. versionchanged:: 3.9
368
369      Updated to support the new union (``|``) operator from :pep:`584`, which
370      simply delegates to the underlying mapping.
371
372   .. describe:: key in proxy
373
374      Return ``True`` if the underlying mapping has a key *key*, else
375      ``False``.
376
377   .. describe:: proxy[key]
378
379      Return the item of the underlying mapping with key *key*.  Raises a
380      :exc:`KeyError` if *key* is not in the underlying mapping.
381
382   .. describe:: iter(proxy)
383
384      Return an iterator over the keys of the underlying mapping.  This is a
385      shortcut for ``iter(proxy.keys())``.
386
387   .. describe:: len(proxy)
388
389      Return the number of items in the underlying mapping.
390
391   .. method:: copy()
392
393      Return a shallow copy of the underlying mapping.
394
395   .. method:: get(key[, default])
396
397      Return the value for *key* if *key* is in the underlying mapping, else
398      *default*.  If *default* is not given, it defaults to ``None``, so that
399      this method never raises a :exc:`KeyError`.
400
401   .. method:: items()
402
403      Return a new view of the underlying mapping's items (``(key, value)``
404      pairs).
405
406   .. method:: keys()
407
408      Return a new view of the underlying mapping's keys.
409
410   .. method:: values()
411
412      Return a new view of the underlying mapping's values.
413
414   .. describe:: reversed(proxy)
415
416      Return a reverse iterator over the keys of the underlying mapping.
417
418      .. versionadded:: 3.9
419
420
421Additional Utility Classes and Functions
422----------------------------------------
423
424.. class:: SimpleNamespace
425
426   A simple :class:`object` subclass that provides attribute access to its
427   namespace, as well as a meaningful repr.
428
429   Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
430   attributes.  If a ``SimpleNamespace`` object is initialized with keyword
431   arguments, those are directly added to the underlying namespace.
432
433   The type is roughly equivalent to the following code::
434
435       class SimpleNamespace:
436           def __init__(self, /, **kwargs):
437               self.__dict__.update(kwargs)
438
439           def __repr__(self):
440               items = (f"{k}={v!r}" for k, v in self.__dict__.items())
441               return "{}({})".format(type(self).__name__, ", ".join(items))
442
443           def __eq__(self, other):
444               if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
445                  return self.__dict__ == other.__dict__
446               return NotImplemented
447
448   ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
449   However, for a structured record type use :func:`~collections.namedtuple`
450   instead.
451
452   .. versionadded:: 3.3
453
454   .. versionchanged:: 3.9
455      Attribute order in the repr changed from alphabetical to insertion (like
456      ``dict``).
457
458.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
459
460   Route attribute access on a class to __getattr__.
461
462   This is a descriptor, used to define attributes that act differently when
463   accessed through an instance and through a class.  Instance access remains
464   normal, but access to an attribute through a class will be routed to the
465   class's __getattr__ method; this is done by raising AttributeError.
466
467   This allows one to have properties active on an instance, and have virtual
468   attributes on the class with the same name (see :class:`enum.Enum` for an example).
469
470   .. versionadded:: 3.4
471
472
473Coroutine Utility Functions
474---------------------------
475
476.. function:: coroutine(gen_func)
477
478   This function transforms a :term:`generator` function into a
479   :term:`coroutine function` which returns a generator-based coroutine.
480   The generator-based coroutine is still a :term:`generator iterator`,
481   but is also considered to be a :term:`coroutine` object and is
482   :term:`awaitable`.  However, it may not necessarily implement
483   the :meth:`__await__` method.
484
485   If *gen_func* is a generator function, it will be modified in-place.
486
487   If *gen_func* is not a generator function, it will be wrapped. If it
488   returns an instance of :class:`collections.abc.Generator`, the instance
489   will be wrapped in an *awaitable* proxy object.  All other types
490   of objects will be returned as is.
491
492   .. versionadded:: 3.5
493