summaryrefslogtreecommitdiff
path: root/Doc/library/types.rst
blob: 8cbe17df16f1078a1abab636913cf188bf7fccf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
:mod:`types` --- Dynamic type creation and names for built-in types
===================================================================

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

**Source code:** :source:`Lib/types.py`

--------------

This module defines utility functions to assist in dynamic creation of
new types.

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

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


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

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

   Creates a class object dynamically using the appropriate metaclass.

   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``).

   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: None``.

   .. versionadded:: 3.3

.. function:: prepare_class(name, bases=(), kwds=None)

   Calculates the appropriate metaclass and creates the class namespace.

   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``).

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

   *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.

   .. versionadded:: 3.3

   .. versionchanged:: 3.6

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

.. seealso::

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

   :pep:`3115` - Metaclasses in Python 3000
      Introduced the ``__prepare__`` namespace hook

.. function:: resolve_bases(bases)

   Resolve MRO entries dynamically as specified by :pep:`560`.

   This function looks for items in *bases* that are not instances of
   :class:`type`, and returns a tuple where each such object that has
   an :meth:`~object.__mro_entries__` method is replaced with an unpacked result of
   calling this method.  If a *bases* item is an instance of :class:`type`,
   or it doesn't have an :meth:`!__mro_entries__` method, then it is included in
   the return tuple unchanged.

   .. versionadded:: 3.7

.. function:: get_original_bases(cls, /)

    Return the tuple of objects originally given as the bases of *cls* before
    the :meth:`~object.__mro_entries__` method has been called on any bases
    (following the mechanisms laid out in :pep:`560`). This is useful for
    introspecting :ref:`Generics <user-defined-generics>`.

    For classes that have an ``__orig_bases__`` attribute, this
    function returns the value of ``cls.__orig_bases__``.
    For classes without the ``__orig_bases__`` attribute, ``cls.__bases__`` is
    returned.

    Examples::

        from typing import TypeVar, Generic, NamedTuple, TypedDict

        T = TypeVar("T")
        class Foo(Generic[T]): ...
        class Bar(Foo[int], float): ...
        class Baz(list[str]): ...
        Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
        Spam = TypedDict("Spam", {"a": int, "b": str})

        assert Bar.__bases__ == (Foo, float)
        assert get_original_bases(Bar) == (Foo[int], float)

        assert Baz.__bases__ == (list,)
        assert get_original_bases(Baz) == (list[str],)

        assert Eggs.__bases__ == (tuple,)
        assert get_original_bases(Eggs) == (NamedTuple,)

        assert Spam.__bases__ == (dict,)
        assert get_original_bases(Spam) == (TypedDict,)

        assert int.__bases__ == (object,)
        assert get_original_bases(int) == (object,)

    .. versionadded:: 3.12

.. seealso::

   :pep:`560` - Core support for typing module and generic types


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.

Typical use of these names is for :func:`isinstance` or
:func:`issubclass` checks.


If you instantiate any of these types, note that signatures may vary between Python versions.

Standard names are defined for the following types:

.. data:: NoneType

   The type of :data:`None`.

   .. versionadded:: 3.10


.. data:: FunctionType
          LambdaType

   The type of user-defined functions and functions created by
   :keyword:`lambda`  expressions.

   .. audit-event:: function.__new__ code types.FunctionType

   The audit event only occurs for direct instantiation of function objects,
   and is not raised for normal compilation.


.. data:: GeneratorType

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


.. data:: CoroutineType

   The type of :term:`coroutine` objects, created by
   :keyword:`async def` functions.

   .. versionadded:: 3.5


.. data:: AsyncGeneratorType

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

   .. versionadded:: 3.6


.. class:: CodeType(**kwargs)

   .. index:: pair: built-in function; compile

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

   .. audit-event:: code.__new__ code,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags types.CodeType

   Note that the audited arguments may not match the names or positions
   required by the initializer.  The audit event only occurs for direct
   instantiation of code objects, and is not raised for normal compilation.

   .. method:: CodeType.replace(**kwargs)

     Return a copy of the code object with new values for the specified fields.

     .. versionadded:: 3.8

.. data:: CellType

   The type for cell objects: such objects are used as containers for
   a function's free variables.

   .. versionadded:: 3.8


.. data:: MethodType

   The type of methods of user-defined class instances.


.. data:: BuiltinFunctionType
          BuiltinMethodType

   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".)


.. data:: WrapperDescriptorType

   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:: NotImplementedType

   The type of :data:`NotImplemented`.

   .. versionadded:: 3.10


.. data:: MethodDescriptorType

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

   .. versionadded:: 3.7


.. data:: ClassMethodDescriptorType

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

   .. versionadded:: 3.7


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

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

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

   .. attribute:: __doc__

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

   .. attribute:: __loader__

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

      This attribute is to match :attr:`importlib.machinery.ModuleSpec.loader`
      as stored in the :attr:`__spec__` object.

      .. note::
         A future version of Python may stop setting this attribute by default.
         To guard against this potential change, preferably read from the
         :attr:`__spec__` attribute instead or use
         ``getattr(module, "__loader__", None)`` if you explicitly need to use
         this attribute.

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

   .. attribute:: __name__

      The name of the module. Expected to match
      :attr:`importlib.machinery.ModuleSpec.name`.

   .. 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``.

      This attribute is to match :attr:`importlib.machinery.ModuleSpec.parent`
      as stored in the :attr:`__spec__` object.

      .. note::
         A future version of Python may stop setting this attribute by default.
         To guard against this potential change, preferably read from the
         :attr:`__spec__` attribute instead or use
         ``getattr(module, "__package__", None)`` if you explicitly need to use
         this attribute.

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

   .. attribute:: __spec__

      A record of the module's import-system-related state. Expected to be an
      instance of :class:`importlib.machinery.ModuleSpec`.

      .. versionadded:: 3.4


.. data:: EllipsisType

   The type of :data:`Ellipsis`.

   .. versionadded:: 3.10

.. class:: GenericAlias(t_origin, t_args)

   The type of :ref:`parameterized generics <types-genericalias>` such as
   ``list[int]``.

   ``t_origin`` should be a non-parameterized generic class, such as ``list``,
   ``tuple`` or ``dict``.  ``t_args`` should be a :class:`tuple` (possibly of
   length 1) of types which parameterize ``t_origin``::

      >>> from types import GenericAlias

      >>> list[int] == GenericAlias(list, (int,))
      True
      >>> dict[str, int] == GenericAlias(dict, (str, int))
      True

   .. versionadded:: 3.9

   .. versionchanged:: 3.9.2
      This type can now be subclassed.

   .. seealso::

      :ref:`Generic Alias Types<types-genericalias>`
         In-depth documentation on instances of :class:`!types.GenericAlias`

      :pep:`585` - Type Hinting Generics In Standard Collections
         Introducing the :class:`!types.GenericAlias` class

.. class:: UnionType

   The type of :ref:`union type expressions<types-union>`.

   .. versionadded:: 3.10

.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

   The type of traceback objects such as found in ``sys.exception().__traceback__``.

   See :ref:`the language reference <traceback-objects>` for details of the
   available attributes and operations, and guidance on creating tracebacks
   dynamically.


.. data:: FrameType

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

   See :ref:`the language reference <frame-objects>` for details of the
   available attributes and operations.


.. data:: GetSetDescriptorType

   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.


.. data:: MemberDescriptorType

   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.

   .. impl-detail::

      In other implementations of Python, this type may be identical to
      ``GetSetDescriptorType``.

.. 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

   .. versionchanged:: 3.9

      Updated to support the new union (``|``) operator from :pep:`584`, which
      simply delegates to the underlying mapping.

   .. 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.

   .. describe:: reversed(proxy)

      Return a reverse iterator over the keys of the underlying mapping.

      .. versionadded:: 3.9

   .. describe:: hash(proxy)

      Return a hash of the underlying mapping.

      .. versionadded:: 3.12


Additional Utility Classes and Functions
----------------------------------------

.. 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)

           def __repr__(self):
               items = (f"{k}={v!r}" for k, v in self.__dict__.items())
               return "{}({})".format(type(self).__name__, ", ".join(items))

           def __eq__(self, other):
               if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
                  return self.__dict__ == other.__dict__
               return NotImplemented

   ``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

   .. versionchanged:: 3.9
      Attribute order in the repr changed from alphabetical to insertion (like
      ``dict``).

.. 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 :class:`enum.Enum` for an example).

   .. versionadded:: 3.4


Coroutine Utility Functions
---------------------------

.. function:: coroutine(gen_func)

   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:`~object.__await__` method.

   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.

   .. versionadded:: 3.5