blob: ff75de1ef555d8031731c102ec7d86cde8e9497b [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
58.. seealso::
59
Nick Coghlana0cf90e2012-05-30 22:17:30 +100060 :ref:`metaclasses`
61 Full details of the class creation process supported by these functions
62
Nick Coghlan7fc570a2012-05-20 02:34:13 +100063 :pep:`3115` - Metaclasses in Python 3000
64 Introduced the ``__prepare__`` namespace hook
65
66
67Standard Interpreter Types
68--------------------------
69
70This module provides names for many of the types that are required to
71implement a Python interpreter. It deliberately avoids including some of
72the types that arise only incidentally during processing such as the
73``listiterator`` type.
74
Ezio Melottid26c3062012-08-26 07:33:10 +030075Typical use of these names is for :func:`isinstance` or
Nick Coghlan7fc570a2012-05-20 02:34:13 +100076:func:`issubclass` checks.
77
78Standard names are defined for the following types:
Georg Brandl116aa622007-08-15 14:28:22 +000079
Georg Brandl116aa622007-08-15 14:28:22 +000080.. data:: FunctionType
Georg Brandla1e9ef72007-09-04 07:23:09 +000081 LambdaType
Georg Brandl116aa622007-08-15 14:28:22 +000082
Nick Coghlan7fc570a2012-05-20 02:34:13 +100083 The type of user-defined functions and functions created by
84 :keyword:`lambda` expressions.
Georg Brandl116aa622007-08-15 14:28:22 +000085
86
Georg Brandl116aa622007-08-15 14:28:22 +000087.. data:: GeneratorType
88
Georg Brandl9afde1c2007-11-01 20:32:30 +000089 The type of :term:`generator`-iterator objects, produced by calling a
90 generator function.
Georg Brandl116aa622007-08-15 14:28:22 +000091
Georg Brandl116aa622007-08-15 14:28:22 +000092
Yury Selivanov5376ba92015-06-22 12:19:30 -040093.. data:: CoroutineType
94
95 The type of :term:`coroutine` objects, produced by calling a
96 function defined with an :keyword:`async def` statement.
97
98 .. versionadded:: 3.5
99
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101.. data:: CodeType
102
103 .. index:: builtin: compile
104
105 The type for code objects such as returned by :func:`compile`.
106
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108.. data:: MethodType
109
110 The type of methods of user-defined class instances.
111
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113.. data:: BuiltinFunctionType
Georg Brandla1e9ef72007-09-04 07:23:09 +0000114 BuiltinMethodType
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandld66a0292008-08-23 15:14:57 +0000116 The type of built-in functions like :func:`len` or :func:`sys.exit`, and
117 methods of built-in classes. (Here, the term "built-in" means "written in
118 C".)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120
Brett Cannon2d772042013-06-14 19:19:57 -0400121.. class:: ModuleType(name, doc=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Brett Cannon2d772042013-06-14 19:19:57 -0400123 The type of :term:`modules <module>`. Constructor takes the name of the
124 module to be created and optionally its :term:`docstring`.
125
Brett Cannon2a17bde2014-05-30 14:55:29 -0400126 .. note::
127 Use :func:`importlib.util.module_from_spec` to create a new module if you
128 wish to set the various import-controlled attributes.
129
Brett Cannon2d772042013-06-14 19:19:57 -0400130 .. attribute:: __doc__
131
132 The :term:`docstring` of the module. Defaults to ``None``.
133
134 .. attribute:: __loader__
135
136 The :term:`loader` which loaded the module. Defaults to ``None``.
137
138 .. versionchanged:: 3.4
139 Defaults to ``None``. Previously the attribute was optional.
140
141 .. attribute:: __name__
142
143 The name of the module.
144
145 .. attribute:: __package__
146
147 Which :term:`package` a module belongs to. If the module is top-level
148 (i.e. not a part of any specific package) then the attribute should be set
149 to ``''``, else it should be set to the name of the package (which can be
150 :attr:`__name__` if the module is a package itself). Defaults to ``None``.
151
152 .. versionchanged:: 3.4
153 Defaults to ``None``. Previously the attribute was optional.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156.. data:: TracebackType
157
158 The type of traceback objects such as found in ``sys.exc_info()[2]``.
159
160
161.. data:: FrameType
162
163 The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
164 traceback object.
165
166
Georg Brandl116aa622007-08-15 14:28:22 +0000167.. data:: GetSetDescriptorType
168
Christian Heimes5e696852008-04-09 08:37:03 +0000169 The type of objects defined in extension modules with ``PyGetSetDef``, such
170 as ``FrameType.f_locals`` or ``array.array.typecode``. This type is used as
171 descriptor for object attributes; it has the same purpose as the
172 :class:`property` type, but for classes defined in extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175.. data:: MemberDescriptorType
176
Christian Heimes5e696852008-04-09 08:37:03 +0000177 The type of objects defined in extension modules with ``PyMemberDef``, such
178 as ``datetime.timedelta.days``. This type is used as descriptor for simple C
179 data members which use standard conversion functions; it has the same purpose
180 as the :class:`property` type, but for classes defined in extension modules.
Georg Brandl495f7b52009-10-27 15:28:25 +0000181
182 .. impl-detail::
183
184 In other implementations of Python, this type may be identical to
185 ``GetSetDescriptorType``.
Victor Stinner0db176f2012-04-16 00:16:30 +0200186
187.. class:: MappingProxyType(mapping)
188
189 Read-only proxy of a mapping. It provides a dynamic view on the mapping's
190 entries, which means that when the mapping changes, the view reflects these
191 changes.
192
193 .. versionadded:: 3.3
194
195 .. describe:: key in proxy
196
197 Return ``True`` if the underlying mapping has a key *key*, else
198 ``False``.
199
200 .. describe:: proxy[key]
201
202 Return the item of the underlying mapping with key *key*. Raises a
203 :exc:`KeyError` if *key* is not in the underlying mapping.
204
205 .. describe:: iter(proxy)
206
207 Return an iterator over the keys of the underlying mapping. This is a
208 shortcut for ``iter(proxy.keys())``.
209
210 .. describe:: len(proxy)
211
212 Return the number of items in the underlying mapping.
213
214 .. method:: copy()
215
216 Return a shallow copy of the underlying mapping.
217
218 .. method:: get(key[, default])
219
220 Return the value for *key* if *key* is in the underlying mapping, else
221 *default*. If *default* is not given, it defaults to ``None``, so that
222 this method never raises a :exc:`KeyError`.
223
224 .. method:: items()
225
226 Return a new view of the underlying mapping's items (``(key, value)``
227 pairs).
228
229 .. method:: keys()
230
231 Return a new view of the underlying mapping's keys.
232
233 .. method:: values()
234
235 Return a new view of the underlying mapping's values.
236
237
R David Murray13cc8832014-02-25 16:03:14 -0500238Additional Utility Classes and Functions
239----------------------------------------
240
Barry Warsaw409da152012-06-03 16:18:47 -0400241.. class:: SimpleNamespace
242
243 A simple :class:`object` subclass that provides attribute access to its
244 namespace, as well as a meaningful repr.
245
246 Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
247 attributes. If a ``SimpleNamespace`` object is initialized with keyword
248 arguments, those are directly added to the underlying namespace.
249
250 The type is roughly equivalent to the following code::
251
252 class SimpleNamespace:
253 def __init__(self, **kwargs):
254 self.__dict__.update(kwargs)
255 def __repr__(self):
256 keys = sorted(self.__dict__)
257 items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
258 return "{}({})".format(type(self).__name__, ", ".join(items))
Eric Snowb5c8f922013-02-16 16:32:39 -0700259 def __eq__(self, other):
260 return self.__dict__ == other.__dict__
Barry Warsaw409da152012-06-03 16:18:47 -0400261
262 ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
263 However, for a structured record type use :func:`~collections.namedtuple`
264 instead.
265
266 .. versionadded:: 3.3
R David Murray13cc8832014-02-25 16:03:14 -0500267
268
269.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
270
271 Route attribute access on a class to __getattr__.
272
273 This is a descriptor, used to define attributes that act differently when
274 accessed through an instance and through a class. Instance access remains
275 normal, but access to an attribute through a class will be routed to the
276 class's __getattr__ method; this is done by raising AttributeError.
277
278 This allows one to have properties active on an instance, and have virtual
279 attributes on the class with the same name (see Enum for an example).
280
281 .. versionadded:: 3.4
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400282
283
Yury Selivanov66f88282015-06-24 11:04:15 -0400284Coroutine Utility Functions
285---------------------------
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400286
287.. function:: coroutine(gen_func)
288
Yury Selivanov66f88282015-06-24 11:04:15 -0400289 This function transforms a :term:`generator` function into a
290 :term:`coroutine function` which returns a generator-based coroutine.
291 The generator-based coroutine is still a :term:`generator iterator`,
292 but is also considered to be a :term:`coroutine` object and is
293 :term:`awaitable`. However, it may not necessarily implement
294 the :meth:`__await__` method.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400295
Yury Selivanov66f88282015-06-24 11:04:15 -0400296 If *gen_func* is a generator function, it will be modified in-place.
297
298 If *gen_func* is not a generator function, it will be wrapped. If it
299 returns an instance of :class:`collections.abc.Generator`, the instance
300 will be wrapped in an *awaitable* proxy object. All other types
301 of objects will be returned as is.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400302
303 .. versionadded:: 3.5