blob: e17070022cd2ede364653288c7b9561f4204100d [file] [log] [blame]
Nick Coghlan7fc570a2012-05-20 02:34:13 +10001:mod:`types` --- Dynamic type creation and names for built-in types
2===================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: types
5 :synopsis: Names for built-in types.
6
Raymond Hettingera1993682011-01-27 01:20:32 +00007**Source code:** :source:`Lib/types.py`
8
9--------------
Georg Brandl116aa622007-08-15 14:28:22 +000010
Nick Coghlan7fc570a2012-05-20 02:34:13 +100011This module defines utility function to assist in dynamic creation of
12new types.
13
14It also defines names for some object types that are used by the standard
Georg Brandld66a0292008-08-23 15:14:57 +000015Python interpreter, but not exposed as builtins like :class:`int` or
Nick Coghlan7fc570a2012-05-20 02:34:13 +100016:class:`str` are.
Georg Brandl116aa622007-08-15 14:28:22 +000017
R David Murray13cc8832014-02-25 16:03:14 -050018Finally, it provides some additional type-related utility classes and functions
19that are not fundamental enough to be builtins.
20
Christian Heimesc9543e42007-11-28 08:28:28 +000021
Nick Coghlan7fc570a2012-05-20 02:34:13 +100022Dynamic 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
Nick Coghlana0cf90e2012-05-30 22:17:30 +100029 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``).
Nick Coghlan7fc570a2012-05-20 02:34:13 +100032
Nick Coghlana0cf90e2012-05-30 22:17:30 +100033 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``.
Nick Coghlan7fc570a2012-05-20 02:34:13 +100038
Nick Coghlana497b442012-05-22 23:02:00 +100039 .. versionadded:: 3.3
40
Nick Coghlan7fc570a2012-05-20 02:34:13 +100041.. function:: prepare_class(name, bases=(), kwds=None)
42
43 Calculates the appropriate metaclass and creates the class namespace.
44
Nick Coghlana0cf90e2012-05-30 22:17:30 +100045 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``).
Nick Coghlan7fc570a2012-05-20 02:34:13 +100048
49 The return value is a 3-tuple: ``metaclass, namespace, kwds``
50
Nick Coghlana0cf90e2012-05-30 22:17:30 +100051 *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.
Nick Coghlan7fc570a2012-05-20 02:34:13 +100055
Nick Coghlana497b442012-05-22 23:02:00 +100056 .. versionadded:: 3.3
Nick Coghlan7fc570a2012-05-20 02:34:13 +100057
Eric Snow92a6c172016-09-05 14:50:11 -070058 .. versionchanged:: 3.6
59
60 The default value for the ``namespace`` element of the returned
Eric Snow4f29e752016-09-08 15:11:11 -070061 tuple has changed. Now an insertion-order-preserving mapping is
Ivan Levkivskyibd5f9652018-05-08 19:38:41 +010062 used when the metaclass does not have a ``__prepare__`` method.
Eric Snow92a6c172016-09-05 14:50:11 -070063
Nick Coghlan7fc570a2012-05-20 02:34:13 +100064.. seealso::
65
Nick Coghlana0cf90e2012-05-30 22:17:30 +100066 :ref:`metaclasses`
67 Full details of the class creation process supported by these functions
68
Nick Coghlan7fc570a2012-05-20 02:34:13 +100069 :pep:`3115` - Metaclasses in Python 3000
70 Introduced the ``__prepare__`` namespace hook
71
Ivan Levkivskyibd5f9652018-05-08 19:38:41 +010072.. 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
Nick Coghlan7fc570a2012-05-20 02:34:13 +100089
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
Ezio Melottid26c3062012-08-26 07:33:10 +030098Typical use of these names is for :func:`isinstance` or
Nick Coghlan7fc570a2012-05-20 02:34:13 +100099:func:`issubclass` checks.
100
101Standard names are defined for the following types:
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Georg Brandl116aa622007-08-15 14:28:22 +0000103.. data:: FunctionType
Georg Brandla1e9ef72007-09-04 07:23:09 +0000104 LambdaType
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Nick Coghlan7fc570a2012-05-20 02:34:13 +1000106 The type of user-defined functions and functions created by
107 :keyword:`lambda` expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109
Georg Brandl116aa622007-08-15 14:28:22 +0000110.. data:: GeneratorType
111
Yury Selivanova88cd642015-09-10 21:26:54 -0400112 The type of :term:`generator`-iterator objects, created by
113 generator functions.
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Yury Selivanov5376ba92015-06-22 12:19:30 -0400116.. data:: CoroutineType
117
Yury Selivanova88cd642015-09-10 21:26:54 -0400118 The type of :term:`coroutine` objects, created by
119 :keyword:`async def` functions.
Yury Selivanov5376ba92015-06-22 12:19:30 -0400120
121 .. versionadded:: 3.5
122
123
Yury Selivanov03660042016-12-15 17:36:05 -0500124.. data:: AsyncGeneratorType
125
126 The type of :term:`asynchronous generator`-iterator objects, created by
127 asynchronous generator functions.
128
129 .. versionadded:: 3.6
130
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132.. data:: CodeType
133
134 .. index:: builtin: compile
135
136 The type for code objects such as returned by :func:`compile`.
137
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139.. data:: MethodType
140
141 The type of methods of user-defined class instances.
142
143
Georg Brandl116aa622007-08-15 14:28:22 +0000144.. data:: BuiltinFunctionType
Georg Brandla1e9ef72007-09-04 07:23:09 +0000145 BuiltinMethodType
Georg Brandl116aa622007-08-15 14:28:22 +0000146
Georg Brandld66a0292008-08-23 15:14:57 +0000147 The type of built-in functions like :func:`len` or :func:`sys.exit`, and
148 methods of built-in classes. (Here, the term "built-in" means "written in
149 C".)
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151
Jim Fasarakis-Hilliard08c16012017-04-25 21:26:36 +0300152.. data:: WrapperDescriptorType
Guido van Rossum934aba62017-02-01 10:55:58 -0800153
154 The type of methods of some built-in data types and base classes such as
155 :meth:`object.__init__` or :meth:`object.__lt__`.
156
157 .. versionadded:: 3.7
158
159
160.. data:: MethodWrapperType
161
162 The type of *bound* methods of some built-in data types and base classes.
163 For example it is the type of :code:`object().__str__`.
164
165 .. versionadded:: 3.7
166
167
168.. data:: MethodDescriptorType
169
170 The type of methods of some built-in data types such as :meth:`str.join`.
171
172 .. versionadded:: 3.7
173
174
Serhiy Storchaka3327a2d2017-12-15 14:13:41 +0200175.. data:: ClassMethodDescriptorType
176
177 The type of *unbound* class methods of some built-in data types such as
178 ``dict.__dict__['fromkeys']``.
179
180 .. versionadded:: 3.7
181
182
Brett Cannon2d772042013-06-14 19:19:57 -0400183.. class:: ModuleType(name, doc=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Brett Cannon2d772042013-06-14 19:19:57 -0400185 The type of :term:`modules <module>`. Constructor takes the name of the
186 module to be created and optionally its :term:`docstring`.
187
Brett Cannon2a17bde2014-05-30 14:55:29 -0400188 .. note::
189 Use :func:`importlib.util.module_from_spec` to create a new module if you
190 wish to set the various import-controlled attributes.
191
Brett Cannon2d772042013-06-14 19:19:57 -0400192 .. attribute:: __doc__
193
194 The :term:`docstring` of the module. Defaults to ``None``.
195
196 .. attribute:: __loader__
197
198 The :term:`loader` which loaded the module. Defaults to ``None``.
199
200 .. versionchanged:: 3.4
201 Defaults to ``None``. Previously the attribute was optional.
202
203 .. attribute:: __name__
204
205 The name of the module.
206
207 .. attribute:: __package__
208
209 Which :term:`package` a module belongs to. If the module is top-level
210 (i.e. not a part of any specific package) then the attribute should be set
211 to ``''``, else it should be set to the name of the package (which can be
212 :attr:`__name__` if the module is a package itself). Defaults to ``None``.
213
214 .. versionchanged:: 3.4
215 Defaults to ``None``. Previously the attribute was optional.
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217
Nick Coghlanaec75322018-02-13 18:10:58 +1000218.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220 The type of traceback objects such as found in ``sys.exc_info()[2]``.
221
Nick Coghlanaec75322018-02-13 18:10:58 +1000222 See :ref:`the language reference <traceback-objects>` for details of the
223 available attributes and operations, and guidance on creating tracebacks
224 dynamically.
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227.. data:: FrameType
228
229 The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
230 traceback object.
231
Nick Coghlanaec75322018-02-13 18:10:58 +1000232 See :ref:`the language reference <frame-objects>` for details of the
233 available attributes and operations.
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236.. data:: GetSetDescriptorType
237
Christian Heimes5e696852008-04-09 08:37:03 +0000238 The type of objects defined in extension modules with ``PyGetSetDef``, such
239 as ``FrameType.f_locals`` or ``array.array.typecode``. This type is used as
240 descriptor for object attributes; it has the same purpose as the
241 :class:`property` type, but for classes defined in extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244.. data:: MemberDescriptorType
245
Christian Heimes5e696852008-04-09 08:37:03 +0000246 The type of objects defined in extension modules with ``PyMemberDef``, such
247 as ``datetime.timedelta.days``. This type is used as descriptor for simple C
248 data members which use standard conversion functions; it has the same purpose
249 as the :class:`property` type, but for classes defined in extension modules.
Georg Brandl495f7b52009-10-27 15:28:25 +0000250
251 .. impl-detail::
252
253 In other implementations of Python, this type may be identical to
254 ``GetSetDescriptorType``.
Victor Stinner0db176f2012-04-16 00:16:30 +0200255
256.. class:: MappingProxyType(mapping)
257
258 Read-only proxy of a mapping. It provides a dynamic view on the mapping's
259 entries, which means that when the mapping changes, the view reflects these
260 changes.
261
262 .. versionadded:: 3.3
263
264 .. describe:: key in proxy
265
266 Return ``True`` if the underlying mapping has a key *key*, else
267 ``False``.
268
269 .. describe:: proxy[key]
270
271 Return the item of the underlying mapping with key *key*. Raises a
272 :exc:`KeyError` if *key* is not in the underlying mapping.
273
274 .. describe:: iter(proxy)
275
276 Return an iterator over the keys of the underlying mapping. This is a
277 shortcut for ``iter(proxy.keys())``.
278
279 .. describe:: len(proxy)
280
281 Return the number of items in the underlying mapping.
282
283 .. method:: copy()
284
285 Return a shallow copy of the underlying mapping.
286
287 .. method:: get(key[, default])
288
289 Return the value for *key* if *key* is in the underlying mapping, else
290 *default*. If *default* is not given, it defaults to ``None``, so that
291 this method never raises a :exc:`KeyError`.
292
293 .. method:: items()
294
295 Return a new view of the underlying mapping's items (``(key, value)``
296 pairs).
297
298 .. method:: keys()
299
300 Return a new view of the underlying mapping's keys.
301
302 .. method:: values()
303
304 Return a new view of the underlying mapping's values.
305
306
R David Murray13cc8832014-02-25 16:03:14 -0500307Additional Utility Classes and Functions
308----------------------------------------
309
Barry Warsaw409da152012-06-03 16:18:47 -0400310.. class:: SimpleNamespace
311
312 A simple :class:`object` subclass that provides attribute access to its
313 namespace, as well as a meaningful repr.
314
315 Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
316 attributes. If a ``SimpleNamespace`` object is initialized with keyword
317 arguments, those are directly added to the underlying namespace.
318
319 The type is roughly equivalent to the following code::
320
321 class SimpleNamespace:
322 def __init__(self, **kwargs):
323 self.__dict__.update(kwargs)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300324
Barry Warsaw409da152012-06-03 16:18:47 -0400325 def __repr__(self):
326 keys = sorted(self.__dict__)
327 items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
328 return "{}({})".format(type(self).__name__, ", ".join(items))
Serhiy Storchakadba90392016-05-10 12:01:23 +0300329
Eric Snowb5c8f922013-02-16 16:32:39 -0700330 def __eq__(self, other):
331 return self.__dict__ == other.__dict__
Barry Warsaw409da152012-06-03 16:18:47 -0400332
333 ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
334 However, for a structured record type use :func:`~collections.namedtuple`
335 instead.
336
337 .. versionadded:: 3.3
R David Murray13cc8832014-02-25 16:03:14 -0500338
339
340.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
341
342 Route attribute access on a class to __getattr__.
343
344 This is a descriptor, used to define attributes that act differently when
345 accessed through an instance and through a class. Instance access remains
346 normal, but access to an attribute through a class will be routed to the
347 class's __getattr__ method; this is done by raising AttributeError.
348
349 This allows one to have properties active on an instance, and have virtual
350 attributes on the class with the same name (see Enum for an example).
351
352 .. versionadded:: 3.4
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400353
354
Yury Selivanov66f88282015-06-24 11:04:15 -0400355Coroutine Utility Functions
356---------------------------
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400357
358.. function:: coroutine(gen_func)
359
Yury Selivanov66f88282015-06-24 11:04:15 -0400360 This function transforms a :term:`generator` function into a
361 :term:`coroutine function` which returns a generator-based coroutine.
362 The generator-based coroutine is still a :term:`generator iterator`,
363 but is also considered to be a :term:`coroutine` object and is
364 :term:`awaitable`. However, it may not necessarily implement
365 the :meth:`__await__` method.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400366
Yury Selivanov66f88282015-06-24 11:04:15 -0400367 If *gen_func* is a generator function, it will be modified in-place.
368
369 If *gen_func* is not a generator function, it will be wrapped. If it
370 returns an instance of :class:`collections.abc.Generator`, the instance
371 will be wrapped in an *awaitable* proxy object. All other types
372 of objects will be returned as is.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400373
374 .. versionadded:: 3.5