blob: c4f57e43af313e5fb71f76b2cb3dc3ac80261c08 [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
Christian Heimesc9543e42007-11-28 08:28:28 +000018
Nick Coghlan7fc570a2012-05-20 02:34:13 +100019Dynamic Type Creation
20---------------------
21
22.. function:: new_class(name, bases=(), kwds=None, exec_body=None)
23
24 Creates a class object dynamically using the appropriate metaclass.
25
Nick Coghlana0cf90e2012-05-30 22:17:30 +100026 The first three arguments are the components that make up a class
27 definition header: the class name, the base classes (in order), the
28 keyword arguments (such as ``metaclass``).
Nick Coghlan7fc570a2012-05-20 02:34:13 +100029
Nick Coghlana0cf90e2012-05-30 22:17:30 +100030 The *exec_body* argument is a callback that is used to populate the
31 freshly created class namespace. It should accept the class namespace
32 as its sole argument and update the namespace directly with the class
33 contents. If no callback is provided, it has the same effect as passing
34 in ``lambda ns: ns``.
Nick Coghlan7fc570a2012-05-20 02:34:13 +100035
Nick Coghlana497b442012-05-22 23:02:00 +100036 .. versionadded:: 3.3
37
Nick Coghlan7fc570a2012-05-20 02:34:13 +100038.. function:: prepare_class(name, bases=(), kwds=None)
39
40 Calculates the appropriate metaclass and creates the class namespace.
41
Nick Coghlana0cf90e2012-05-30 22:17:30 +100042 The arguments are the components that make up a class definition header:
43 the class name, the base classes (in order) and the keyword arguments
44 (such as ``metaclass``).
Nick Coghlan7fc570a2012-05-20 02:34:13 +100045
46 The return value is a 3-tuple: ``metaclass, namespace, kwds``
47
Nick Coghlana0cf90e2012-05-30 22:17:30 +100048 *metaclass* is the appropriate metaclass, *namespace* is the
49 prepared class namespace and *kwds* is an updated copy of the passed
50 in *kwds* argument with any ``'metaclass'`` entry removed. If no *kwds*
51 argument is passed in, this will be an empty dict.
Nick Coghlan7fc570a2012-05-20 02:34:13 +100052
Nick Coghlana497b442012-05-22 23:02:00 +100053 .. versionadded:: 3.3
Nick Coghlan7fc570a2012-05-20 02:34:13 +100054
55.. seealso::
56
Nick Coghlana0cf90e2012-05-30 22:17:30 +100057 :ref:`metaclasses`
58 Full details of the class creation process supported by these functions
59
Nick Coghlan7fc570a2012-05-20 02:34:13 +100060 :pep:`3115` - Metaclasses in Python 3000
61 Introduced the ``__prepare__`` namespace hook
62
63
64Standard Interpreter Types
65--------------------------
66
67This module provides names for many of the types that are required to
68implement a Python interpreter. It deliberately avoids including some of
69the types that arise only incidentally during processing such as the
70``listiterator`` type.
71
Ezio Melottid26c3062012-08-26 07:33:10 +030072Typical use of these names is for :func:`isinstance` or
Nick Coghlan7fc570a2012-05-20 02:34:13 +100073:func:`issubclass` checks.
74
75Standard names are defined for the following types:
Georg Brandl116aa622007-08-15 14:28:22 +000076
Georg Brandl116aa622007-08-15 14:28:22 +000077.. data:: FunctionType
Georg Brandla1e9ef72007-09-04 07:23:09 +000078 LambdaType
Georg Brandl116aa622007-08-15 14:28:22 +000079
Nick Coghlan7fc570a2012-05-20 02:34:13 +100080 The type of user-defined functions and functions created by
81 :keyword:`lambda` expressions.
Georg Brandl116aa622007-08-15 14:28:22 +000082
83
Georg Brandl116aa622007-08-15 14:28:22 +000084.. data:: GeneratorType
85
Georg Brandl9afde1c2007-11-01 20:32:30 +000086 The type of :term:`generator`-iterator objects, produced by calling a
87 generator function.
Georg Brandl116aa622007-08-15 14:28:22 +000088
Georg Brandl116aa622007-08-15 14:28:22 +000089
90.. data:: CodeType
91
92 .. index:: builtin: compile
93
94 The type for code objects such as returned by :func:`compile`.
95
96
Georg Brandl116aa622007-08-15 14:28:22 +000097.. data:: MethodType
98
99 The type of methods of user-defined class instances.
100
101
Georg Brandl116aa622007-08-15 14:28:22 +0000102.. data:: BuiltinFunctionType
Georg Brandla1e9ef72007-09-04 07:23:09 +0000103 BuiltinMethodType
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Georg Brandld66a0292008-08-23 15:14:57 +0000105 The type of built-in functions like :func:`len` or :func:`sys.exit`, and
106 methods of built-in classes. (Here, the term "built-in" means "written in
107 C".)
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109
Brett Cannon2d772042013-06-14 19:19:57 -0400110.. class:: ModuleType(name, doc=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Brett Cannon2d772042013-06-14 19:19:57 -0400112 The type of :term:`modules <module>`. Constructor takes the name of the
113 module to be created and optionally its :term:`docstring`.
114
115 .. attribute:: __doc__
116
117 The :term:`docstring` of the module. Defaults to ``None``.
118
119 .. attribute:: __loader__
120
121 The :term:`loader` which loaded the module. Defaults to ``None``.
122
123 .. versionchanged:: 3.4
124 Defaults to ``None``. Previously the attribute was optional.
125
126 .. attribute:: __name__
127
128 The name of the module.
129
130 .. attribute:: __package__
131
132 Which :term:`package` a module belongs to. If the module is top-level
133 (i.e. not a part of any specific package) then the attribute should be set
134 to ``''``, else it should be set to the name of the package (which can be
135 :attr:`__name__` if the module is a package itself). Defaults to ``None``.
136
137 .. versionchanged:: 3.4
138 Defaults to ``None``. Previously the attribute was optional.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140
Georg Brandl116aa622007-08-15 14:28:22 +0000141.. data:: TracebackType
142
143 The type of traceback objects such as found in ``sys.exc_info()[2]``.
144
145
146.. data:: FrameType
147
148 The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
149 traceback object.
150
151
Georg Brandl116aa622007-08-15 14:28:22 +0000152.. data:: GetSetDescriptorType
153
Christian Heimes5e696852008-04-09 08:37:03 +0000154 The type of objects defined in extension modules with ``PyGetSetDef``, such
155 as ``FrameType.f_locals`` or ``array.array.typecode``. This type is used as
156 descriptor for object attributes; it has the same purpose as the
157 :class:`property` type, but for classes defined in extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160.. data:: MemberDescriptorType
161
Christian Heimes5e696852008-04-09 08:37:03 +0000162 The type of objects defined in extension modules with ``PyMemberDef``, such
163 as ``datetime.timedelta.days``. This type is used as descriptor for simple C
164 data members which use standard conversion functions; it has the same purpose
165 as the :class:`property` type, but for classes defined in extension modules.
Georg Brandl495f7b52009-10-27 15:28:25 +0000166
167 .. impl-detail::
168
169 In other implementations of Python, this type may be identical to
170 ``GetSetDescriptorType``.
Victor Stinner0db176f2012-04-16 00:16:30 +0200171
172.. class:: MappingProxyType(mapping)
173
174 Read-only proxy of a mapping. It provides a dynamic view on the mapping's
175 entries, which means that when the mapping changes, the view reflects these
176 changes.
177
178 .. versionadded:: 3.3
179
180 .. describe:: key in proxy
181
182 Return ``True`` if the underlying mapping has a key *key*, else
183 ``False``.
184
185 .. describe:: proxy[key]
186
187 Return the item of the underlying mapping with key *key*. Raises a
188 :exc:`KeyError` if *key* is not in the underlying mapping.
189
190 .. describe:: iter(proxy)
191
192 Return an iterator over the keys of the underlying mapping. This is a
193 shortcut for ``iter(proxy.keys())``.
194
195 .. describe:: len(proxy)
196
197 Return the number of items in the underlying mapping.
198
199 .. method:: copy()
200
201 Return a shallow copy of the underlying mapping.
202
203 .. method:: get(key[, default])
204
205 Return the value for *key* if *key* is in the underlying mapping, else
206 *default*. If *default* is not given, it defaults to ``None``, so that
207 this method never raises a :exc:`KeyError`.
208
209 .. method:: items()
210
211 Return a new view of the underlying mapping's items (``(key, value)``
212 pairs).
213
214 .. method:: keys()
215
216 Return a new view of the underlying mapping's keys.
217
218 .. method:: values()
219
220 Return a new view of the underlying mapping's values.
221
222
Barry Warsaw409da152012-06-03 16:18:47 -0400223.. class:: SimpleNamespace
224
225 A simple :class:`object` subclass that provides attribute access to its
226 namespace, as well as a meaningful repr.
227
228 Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
229 attributes. If a ``SimpleNamespace`` object is initialized with keyword
230 arguments, those are directly added to the underlying namespace.
231
232 The type is roughly equivalent to the following code::
233
234 class SimpleNamespace:
235 def __init__(self, **kwargs):
236 self.__dict__.update(kwargs)
237 def __repr__(self):
238 keys = sorted(self.__dict__)
239 items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
240 return "{}({})".format(type(self).__name__, ", ".join(items))
Eric Snowb5c8f922013-02-16 16:32:39 -0700241 def __eq__(self, other):
242 return self.__dict__ == other.__dict__
Barry Warsaw409da152012-06-03 16:18:47 -0400243
244 ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
245 However, for a structured record type use :func:`~collections.namedtuple`
246 instead.
247
248 .. versionadded:: 3.3