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