types.rst 10.4 KB
Newer Older
1 2
:mod:`types` --- Dynamic type creation and names for built-in types
===================================================================
3 4 5 6

.. module:: types
   :synopsis: Names for built-in types.

Raymond Hettinger's avatar
Raymond Hettinger committed
7 8 9
**Source code:** :source:`Lib/types.py`

--------------
10

11 12 13 14
This module defines utility function to assist in dynamic creation of
new types.

It also defines names for some object types that are used by the standard
15
Python interpreter, but not exposed as builtins like :class:`int` or
16 17
:class:`str` are.

18 19 20
Finally, it provides some additional type-related utility classes and functions
that are not fundamental enough to be builtins.

21 22 23 24 25 26 27 28

Dynamic Type Creation
---------------------

.. function:: new_class(name, bases=(), kwds=None, exec_body=None)

   Creates a class object dynamically using the appropriate metaclass.

29 30 31
   The first three arguments are the components that make up a class
   definition header: the class name, the base classes (in order), the
   keyword arguments (such as ``metaclass``).
32

33 34 35 36 37
   The *exec_body* argument is a callback that is used to populate the
   freshly created class namespace. It should accept the class namespace
   as its sole argument and update the namespace directly with the class
   contents. If no callback is provided, it has the same effect as passing
   in ``lambda ns: ns``.
38

39 40
   .. versionadded:: 3.3

41 42 43 44
.. function:: prepare_class(name, bases=(), kwds=None)

   Calculates the appropriate metaclass and creates the class namespace.

45 46 47
   The arguments are the components that make up a class definition header:
   the class name, the base classes (in order) and the keyword arguments
   (such as ``metaclass``).
48 49 50

   The return value is a 3-tuple: ``metaclass, namespace, kwds``

51 52 53 54
   *metaclass* is the appropriate metaclass, *namespace* is the
   prepared class namespace and *kwds* is an updated copy of the passed
   in *kwds* argument with any ``'metaclass'`` entry removed. If no *kwds*
   argument is passed in, this will be an empty dict.
55

56
   .. versionadded:: 3.3
57

58 59 60
   .. versionchanged:: 3.6

      The default value for the ``namespace`` element of the returned
61 62
      tuple has changed.  Now an insertion-order-preserving mapping is
      used when the metaclass does not have a ``__prepare__`` method,
63

64 65
.. seealso::

66 67 68
   :ref:`metaclasses`
      Full details of the class creation process supported by these functions

69 70 71 72 73 74 75 76 77 78 79
   :pep:`3115` - Metaclasses in Python 3000
      Introduced the ``__prepare__`` namespace hook


Standard Interpreter Types
--------------------------

This module provides names for many of the types that are required to
implement a Python interpreter. It deliberately avoids including some of
the types that arise only incidentally during processing such as the
``listiterator`` type.
80

Ezio Melotti's avatar
Ezio Melotti committed
81
Typical use of these names is for :func:`isinstance` or
82
:func:`issubclass` checks.
83

84
Standard names are defined for the following types:
85 86

.. data:: FunctionType
87
          LambdaType
88

89 90
   The type of user-defined functions and functions created by
   :keyword:`lambda`  expressions.
91 92 93 94


.. data:: GeneratorType

95 96
   The type of :term:`generator`-iterator objects, created by
   generator functions.
97 98


99 100
.. data:: CoroutineType

101 102
   The type of :term:`coroutine` objects, created by
   :keyword:`async def` functions.
103 104 105 106

   .. versionadded:: 3.5


107 108 109 110 111 112 113 114
.. data:: AsyncGeneratorType

   The type of :term:`asynchronous generator`-iterator objects, created by
   asynchronous generator functions.

   .. versionadded:: 3.6


115 116 117 118 119 120 121 122 123 124 125 126 127
.. data:: CodeType

   .. index:: builtin: compile

   The type for code objects such as returned by :func:`compile`.


.. data:: MethodType

   The type of methods of user-defined class instances.


.. data:: BuiltinFunctionType
128
          BuiltinMethodType
129

130 131 132
   The type of built-in functions like :func:`len` or :func:`sys.exit`, and
   methods of built-in classes.  (Here, the term "built-in" means "written in
   C".)
133 134


135
.. data:: WrapperDescriptorType
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

   The type of methods of some built-in data types and base classes such as
   :meth:`object.__init__` or :meth:`object.__lt__`.

   .. versionadded:: 3.7


.. data:: MethodWrapperType

   The type of *bound* methods of some built-in data types and base classes.
   For example it is the type of :code:`object().__str__`.

   .. versionadded:: 3.7


.. data:: MethodDescriptorType

   The type of methods of some built-in data types such as :meth:`str.join`.

   .. versionadded:: 3.7
156 157 158 159 160 161 162 163


.. data:: ClassMethodDescriptorType

   The type of *unbound* class methods of some built-in data types such as
   ``dict.__dict__['fromkeys']``.

   .. versionadded:: 3.7
164 165


166
.. class:: ModuleType(name, doc=None)
167

168 169 170
   The type of :term:`modules <module>`. Constructor takes the name of the
   module to be created and optionally its :term:`docstring`.

171 172 173 174
   .. note::
      Use :func:`importlib.util.module_from_spec` to create a new module if you
      wish to set the various import-controlled attributes.

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
   .. attribute:: __doc__

      The :term:`docstring` of the module. Defaults to ``None``.

   .. attribute:: __loader__

      The :term:`loader` which loaded the module. Defaults to ``None``.

      .. versionchanged:: 3.4
         Defaults to ``None``. Previously the attribute was optional.

   .. attribute:: __name__

      The name of the module.

   .. attribute:: __package__

      Which :term:`package` a module belongs to. If the module is top-level
      (i.e. not a part of any specific package) then the attribute should be set
      to ``''``, else it should be set to the name of the package (which can be
      :attr:`__name__` if the module is a package itself). Defaults to ``None``.

      .. versionchanged:: 3.4
         Defaults to ``None``. Previously the attribute was optional.
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213


.. data:: TracebackType

   The type of traceback objects such as found in ``sys.exc_info()[2]``.


.. data:: FrameType

   The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
   traceback object.


.. data:: GetSetDescriptorType

Christian Heimes's avatar
Christian Heimes committed
214 215 216 217
   The type of objects defined in extension modules with ``PyGetSetDef``, such
   as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
   descriptor for object attributes; it has the same purpose as the
   :class:`property` type, but for classes defined in extension modules.
218 219 220 221


.. data:: MemberDescriptorType

Christian Heimes's avatar
Christian Heimes committed
222 223 224 225
   The type of objects defined in extension modules with ``PyMemberDef``, such
   as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
   data members which use standard conversion functions; it has the same purpose
   as the :class:`property` type, but for classes defined in extension modules.
Georg Brandl's avatar
Georg Brandl committed
226 227 228 229 230

   .. impl-detail::

      In other implementations of Python, this type may be identical to
      ``GetSetDescriptorType``.
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

.. class:: MappingProxyType(mapping)

   Read-only proxy of a mapping. It provides a dynamic view on the mapping's
   entries, which means that when the mapping changes, the view reflects these
   changes.

   .. versionadded:: 3.3

   .. describe:: key in proxy

      Return ``True`` if the underlying mapping has a key *key*, else
      ``False``.

   .. describe:: proxy[key]

      Return the item of the underlying mapping with key *key*.  Raises a
      :exc:`KeyError` if *key* is not in the underlying mapping.

   .. describe:: iter(proxy)

      Return an iterator over the keys of the underlying mapping.  This is a
      shortcut for ``iter(proxy.keys())``.

   .. describe:: len(proxy)

      Return the number of items in the underlying mapping.

   .. method:: copy()

      Return a shallow copy of the underlying mapping.

   .. method:: get(key[, default])

      Return the value for *key* if *key* is in the underlying mapping, else
      *default*.  If *default* is not given, it defaults to ``None``, so that
      this method never raises a :exc:`KeyError`.

   .. method:: items()

      Return a new view of the underlying mapping's items (``(key, value)``
      pairs).

   .. method:: keys()

      Return a new view of the underlying mapping's keys.

   .. method:: values()

      Return a new view of the underlying mapping's values.


283 284 285
Additional Utility Classes and Functions
----------------------------------------

286 287 288 289 290 291 292 293 294 295 296 297 298 299
.. class:: SimpleNamespace

   A simple :class:`object` subclass that provides attribute access to its
   namespace, as well as a meaningful repr.

   Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
   attributes.  If a ``SimpleNamespace`` object is initialized with keyword
   arguments, those are directly added to the underlying namespace.

   The type is roughly equivalent to the following code::

       class SimpleNamespace:
           def __init__(self, **kwargs):
               self.__dict__.update(kwargs)
300

301 302 303 304
           def __repr__(self):
               keys = sorted(self.__dict__)
               items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
               return "{}({})".format(type(self).__name__, ", ".join(items))
305

306 307
           def __eq__(self, other):
               return self.__dict__ == other.__dict__
308 309 310 311 312 313

   ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
   However, for a structured record type use :func:`~collections.namedtuple`
   instead.

   .. versionadded:: 3.3
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328


.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)

   Route attribute access on a class to __getattr__.

   This is a descriptor, used to define attributes that act differently when
   accessed through an instance and through a class.  Instance access remains
   normal, but access to an attribute through a class will be routed to the
   class's __getattr__ method; this is done by raising AttributeError.

   This allows one to have properties active on an instance, and have virtual
   attributes on the class with the same name (see Enum for an example).

   .. versionadded:: 3.4
329 330


331 332
Coroutine Utility Functions
---------------------------
333 334 335

.. function:: coroutine(gen_func)

336 337 338 339 340 341
   This function transforms a :term:`generator` function into a
   :term:`coroutine function` which returns a generator-based coroutine.
   The generator-based coroutine is still a :term:`generator iterator`,
   but is also considered to be a :term:`coroutine` object and is
   :term:`awaitable`.  However, it may not necessarily implement
   the :meth:`__await__` method.
342

343 344 345 346 347 348
   If *gen_func* is a generator function, it will be modified in-place.

   If *gen_func* is not a generator function, it will be wrapped. If it
   returns an instance of :class:`collections.abc.Generator`, the instance
   will be wrapped in an *awaitable* proxy object.  All other types
   of objects will be returned as is.
349 350

   .. versionadded:: 3.5