• 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: ns``.
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>`. 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      .. versionchanged:: 3.4
228         Defaults to ``None``. Previously the attribute was optional.
229
230   .. attribute:: __name__
231
232      The name of the module.
233
234   .. attribute:: __package__
235
236      Which :term:`package` a module belongs to. If the module is top-level
237      (i.e. not a part of any specific package) then the attribute should be set
238      to ``''``, else it should be set to the name of the package (which can be
239      :attr:`__name__` if the module is a package itself). Defaults to ``None``.
240
241      .. versionchanged:: 3.4
242         Defaults to ``None``. Previously the attribute was optional.
243
244
245.. class:: GenericAlias(t_origin, t_args)
246
247   The type of :ref:`parameterized generics <types-genericalias>` such as
248   ``list[int]``.
249
250   ``t_origin`` should be a non-parameterized generic class, such as ``list``,
251   ``tuple`` or ``dict``.  ``t_args`` should be a :class:`tuple` (possibly of
252   length 1) of types which parameterize ``t_origin``::
253
254      >>> from types import GenericAlias
255
256      >>> list[int] == GenericAlias(list, (int,))
257      True
258      >>> dict[str, int] == GenericAlias(dict, (str, int))
259      True
260
261   .. versionadded:: 3.9
262
263   .. versionchanged:: 3.9.2
264      This type can now be subclassed.
265
266
267.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
268
269   The type of traceback objects such as found in ``sys.exc_info()[2]``.
270
271   See :ref:`the language reference <traceback-objects>` for details of the
272   available attributes and operations, and guidance on creating tracebacks
273   dynamically.
274
275
276.. data:: FrameType
277
278   The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
279   traceback object.
280
281   See :ref:`the language reference <frame-objects>` for details of the
282   available attributes and operations.
283
284
285.. data:: GetSetDescriptorType
286
287   The type of objects defined in extension modules with ``PyGetSetDef``, such
288   as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
289   descriptor for object attributes; it has the same purpose as the
290   :class:`property` type, but for classes defined in extension modules.
291
292
293.. data:: MemberDescriptorType
294
295   The type of objects defined in extension modules with ``PyMemberDef``, such
296   as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
297   data members which use standard conversion functions; it has the same purpose
298   as the :class:`property` type, but for classes defined in extension modules.
299
300   .. impl-detail::
301
302      In other implementations of Python, this type may be identical to
303      ``GetSetDescriptorType``.
304
305.. class:: MappingProxyType(mapping)
306
307   Read-only proxy of a mapping. It provides a dynamic view on the mapping's
308   entries, which means that when the mapping changes, the view reflects these
309   changes.
310
311   .. versionadded:: 3.3
312
313   .. versionchanged:: 3.9
314
315      Updated to support the new union (``|``) operator from :pep:`584`, which
316      simply delegates to the underlying mapping.
317
318   .. describe:: key in proxy
319
320      Return ``True`` if the underlying mapping has a key *key*, else
321      ``False``.
322
323   .. describe:: proxy[key]
324
325      Return the item of the underlying mapping with key *key*.  Raises a
326      :exc:`KeyError` if *key* is not in the underlying mapping.
327
328   .. describe:: iter(proxy)
329
330      Return an iterator over the keys of the underlying mapping.  This is a
331      shortcut for ``iter(proxy.keys())``.
332
333   .. describe:: len(proxy)
334
335      Return the number of items in the underlying mapping.
336
337   .. method:: copy()
338
339      Return a shallow copy of the underlying mapping.
340
341   .. method:: get(key[, default])
342
343      Return the value for *key* if *key* is in the underlying mapping, else
344      *default*.  If *default* is not given, it defaults to ``None``, so that
345      this method never raises a :exc:`KeyError`.
346
347   .. method:: items()
348
349      Return a new view of the underlying mapping's items (``(key, value)``
350      pairs).
351
352   .. method:: keys()
353
354      Return a new view of the underlying mapping's keys.
355
356   .. method:: values()
357
358      Return a new view of the underlying mapping's values.
359
360   .. describe:: reversed(proxy)
361
362      Return a reverse iterator over the keys of the underlying mapping.
363
364      .. versionadded:: 3.9
365
366
367Additional Utility Classes and Functions
368----------------------------------------
369
370.. class:: SimpleNamespace
371
372   A simple :class:`object` subclass that provides attribute access to its
373   namespace, as well as a meaningful repr.
374
375   Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
376   attributes.  If a ``SimpleNamespace`` object is initialized with keyword
377   arguments, those are directly added to the underlying namespace.
378
379   The type is roughly equivalent to the following code::
380
381       class SimpleNamespace:
382           def __init__(self, /, **kwargs):
383               self.__dict__.update(kwargs)
384
385           def __repr__(self):
386               items = (f"{k}={v!r}" for k, v in self.__dict__.items())
387               return "{}({})".format(type(self).__name__, ", ".join(items))
388
389           def __eq__(self, other):
390               if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
391                  return self.__dict__ == other.__dict__
392               return NotImplemented
393
394   ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
395   However, for a structured record type use :func:`~collections.namedtuple`
396   instead.
397
398   .. versionadded:: 3.3
399
400   .. versionchanged:: 3.9
401      Attribute order in the repr changed from alphabetical to insertion (like
402      ``dict``).
403
404.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
405
406   Route attribute access on a class to __getattr__.
407
408   This is a descriptor, used to define attributes that act differently when
409   accessed through an instance and through a class.  Instance access remains
410   normal, but access to an attribute through a class will be routed to the
411   class's __getattr__ method; this is done by raising AttributeError.
412
413   This allows one to have properties active on an instance, and have virtual
414   attributes on the class with the same name (see :class:`enum.Enum` for an example).
415
416   .. versionadded:: 3.4
417
418
419Coroutine Utility Functions
420---------------------------
421
422.. function:: coroutine(gen_func)
423
424   This function transforms a :term:`generator` function into a
425   :term:`coroutine function` which returns a generator-based coroutine.
426   The generator-based coroutine is still a :term:`generator iterator`,
427   but is also considered to be a :term:`coroutine` object and is
428   :term:`awaitable`.  However, it may not necessarily implement
429   the :meth:`__await__` method.
430
431   If *gen_func* is a generator function, it will be modified in-place.
432
433   If *gen_func* is not a generator function, it will be wrapped. If it
434   returns an instance of :class:`collections.abc.Generator`, the instance
435   will be wrapped in an *awaitable* proxy object.  All other types
436   of objects will be returned as is.
437
438   .. versionadded:: 3.5
439