Home | History | Annotate | Download | only in library
      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 
     11 This module defines utility function to assist in dynamic creation of
     12 new types.
     13 
     14 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 :class:`str` are.
     17 
     18 Finally, it provides some additional type-related utility classes and functions
     19 that are not fundamental enough to be builtins.
     20 
     21 
     22 Dynamic 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 
     73 Standard Interpreter Types
     74 --------------------------
     75 
     76 This module provides names for many of the types that are required to
     77 implement a Python interpreter. It deliberately avoids including some of
     78 the types that arise only incidentally during processing such as the
     79 ``listiterator`` type.
     80 
     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    The type of user-defined functions and functions created by
     90    :keyword:`lambda`  expressions.
     91 
     92 
     93 .. data:: GeneratorType
     94 
     95    The type of :term:`generator`-iterator objects, created by
     96    generator functions.
     97 
     98 
     99 .. data:: CoroutineType
    100 
    101    The type of :term:`coroutine` objects, created by
    102    :keyword:`async def` functions.
    103 
    104    .. versionadded:: 3.5
    105 
    106 
    107 .. data:: AsyncGeneratorType
    108 
    109    The type of :term:`asynchronous generator`-iterator objects, created by
    110    asynchronous generator functions.
    111 
    112    .. versionadded:: 3.6
    113 
    114 
    115 .. data:: CodeType
    116 
    117    .. index:: builtin: compile
    118 
    119    The type for code objects such as returned by :func:`compile`.
    120 
    121 
    122 .. data:: MethodType
    123 
    124    The type of methods of user-defined class instances.
    125 
    126 
    127 .. data:: BuiltinFunctionType
    128           BuiltinMethodType
    129 
    130    The type of built-in functions like :func:`len` or :func:`sys.exit`, and
    131    methods of built-in classes.  (Here, the term "built-in" means "written in
    132    C".)
    133 
    134 
    135 .. class:: ModuleType(name, doc=None)
    136 
    137    The type of :term:`modules <module>`. Constructor takes the name of the
    138    module to be created and optionally its :term:`docstring`.
    139 
    140    .. note::
    141       Use :func:`importlib.util.module_from_spec` to create a new module if you
    142       wish to set the various import-controlled attributes.
    143 
    144    .. attribute:: __doc__
    145 
    146       The :term:`docstring` of the module. Defaults to ``None``.
    147 
    148    .. attribute:: __loader__
    149 
    150       The :term:`loader` which loaded the module. Defaults to ``None``.
    151 
    152       .. versionchanged:: 3.4
    153          Defaults to ``None``. Previously the attribute was optional.
    154 
    155    .. attribute:: __name__
    156 
    157       The name of the module.
    158 
    159    .. attribute:: __package__
    160 
    161       Which :term:`package` a module belongs to. If the module is top-level
    162       (i.e. not a part of any specific package) then the attribute should be set
    163       to ``''``, else it should be set to the name of the package (which can be
    164       :attr:`__name__` if the module is a package itself). Defaults to ``None``.
    165 
    166       .. versionchanged:: 3.4
    167          Defaults to ``None``. Previously the attribute was optional.
    168 
    169 
    170 .. data:: TracebackType
    171 
    172    The type of traceback objects such as found in ``sys.exc_info()[2]``.
    173 
    174 
    175 .. data:: FrameType
    176 
    177    The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
    178    traceback object.
    179 
    180 
    181 .. data:: GetSetDescriptorType
    182 
    183    The type of objects defined in extension modules with ``PyGetSetDef``, such
    184    as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
    185    descriptor for object attributes; it has the same purpose as the
    186    :class:`property` type, but for classes defined in extension modules.
    187 
    188 
    189 .. data:: MemberDescriptorType
    190 
    191    The type of objects defined in extension modules with ``PyMemberDef``, such
    192    as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
    193    data members which use standard conversion functions; it has the same purpose
    194    as the :class:`property` type, but for classes defined in extension modules.
    195 
    196    .. impl-detail::
    197 
    198       In other implementations of Python, this type may be identical to
    199       ``GetSetDescriptorType``.
    200 
    201 .. class:: MappingProxyType(mapping)
    202 
    203    Read-only proxy of a mapping. It provides a dynamic view on the mapping's
    204    entries, which means that when the mapping changes, the view reflects these
    205    changes.
    206 
    207    .. versionadded:: 3.3
    208 
    209    .. describe:: key in proxy
    210 
    211       Return ``True`` if the underlying mapping has a key *key*, else
    212       ``False``.
    213 
    214    .. describe:: proxy[key]
    215 
    216       Return the item of the underlying mapping with key *key*.  Raises a
    217       :exc:`KeyError` if *key* is not in the underlying mapping.
    218 
    219    .. describe:: iter(proxy)
    220 
    221       Return an iterator over the keys of the underlying mapping.  This is a
    222       shortcut for ``iter(proxy.keys())``.
    223 
    224    .. describe:: len(proxy)
    225 
    226       Return the number of items in the underlying mapping.
    227 
    228    .. method:: copy()
    229 
    230       Return a shallow copy of the underlying mapping.
    231 
    232    .. method:: get(key[, default])
    233 
    234       Return the value for *key* if *key* is in the underlying mapping, else
    235       *default*.  If *default* is not given, it defaults to ``None``, so that
    236       this method never raises a :exc:`KeyError`.
    237 
    238    .. method:: items()
    239 
    240       Return a new view of the underlying mapping's items (``(key, value)``
    241       pairs).
    242 
    243    .. method:: keys()
    244 
    245       Return a new view of the underlying mapping's keys.
    246 
    247    .. method:: values()
    248 
    249       Return a new view of the underlying mapping's values.
    250 
    251 
    252 Additional Utility Classes and Functions
    253 ----------------------------------------
    254 
    255 .. class:: SimpleNamespace
    256 
    257    A simple :class:`object` subclass that provides attribute access to its
    258    namespace, as well as a meaningful repr.
    259 
    260    Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
    261    attributes.  If a ``SimpleNamespace`` object is initialized with keyword
    262    arguments, those are directly added to the underlying namespace.
    263 
    264    The type is roughly equivalent to the following code::
    265 
    266        class SimpleNamespace:
    267            def __init__(self, **kwargs):
    268                self.__dict__.update(kwargs)
    269 
    270            def __repr__(self):
    271                keys = sorted(self.__dict__)
    272                items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
    273                return "{}({})".format(type(self).__name__, ", ".join(items))
    274 
    275            def __eq__(self, other):
    276                return self.__dict__ == other.__dict__
    277 
    278    ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
    279    However, for a structured record type use :func:`~collections.namedtuple`
    280    instead.
    281 
    282    .. versionadded:: 3.3
    283 
    284 
    285 .. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
    286 
    287    Route attribute access on a class to __getattr__.
    288 
    289    This is a descriptor, used to define attributes that act differently when
    290    accessed through an instance and through a class.  Instance access remains
    291    normal, but access to an attribute through a class will be routed to the
    292    class's __getattr__ method; this is done by raising AttributeError.
    293 
    294    This allows one to have properties active on an instance, and have virtual
    295    attributes on the class with the same name (see Enum for an example).
    296 
    297    .. versionadded:: 3.4
    298 
    299 
    300 Coroutine Utility Functions
    301 ---------------------------
    302 
    303 .. function:: coroutine(gen_func)
    304 
    305    This function transforms a :term:`generator` function into a
    306    :term:`coroutine function` which returns a generator-based coroutine.
    307    The generator-based coroutine is still a :term:`generator iterator`,
    308    but is also considered to be a :term:`coroutine` object and is
    309    :term:`awaitable`.  However, it may not necessarily implement
    310    the :meth:`__await__` method.
    311 
    312    If *gen_func* is a generator function, it will be modified in-place.
    313 
    314    If *gen_func* is not a generator function, it will be wrapped. If it
    315    returns an instance of :class:`collections.abc.Generator`, the instance
    316    will be wrapped in an *awaitable* proxy object.  All other types
    317    of objects will be returned as is.
    318 
    319    .. versionadded:: 3.5
    320