-
-
Notifications
You must be signed in to change notification settings - Fork 34.3k
Expand file tree
/
Copy pathtypes.rst
More file actions
544 lines (333 loc) · 16.7 KB
/
types.rst
File metadata and controls
544 lines (333 loc) · 16.7 KB
Edit and raw actions
OlderNewer
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 functions 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: None``.
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
.. function:: resolve_bases(bases)
73
74
Resolve MRO entries dynamically as specified by :pep:`560`.
75
76
This function looks for items in *bases* that are not instances of
77
:class:`type`, and returns a tuple where each such object that has
78
an :meth:`~object.__mro_entries__` method is replaced with an unpacked result of
79
calling this method. If a *bases* item is an instance of :class:`type`,
80
or it doesn't have an :meth:`!__mro_entries__` method, then it is included in
81
the return tuple unchanged.
82
83
.. versionadded:: 3.7
84
85
.. function:: get_original_bases(cls, /)
86
87
Return the tuple of objects originally given as the bases of *cls* before
88
the :meth:`~object.__mro_entries__` method has been called on any bases
89
(following the mechanisms laid out in :pep:`560`). This is useful for
90
introspecting :ref:`Generics <user-defined-generics>`.
91
92
For classes that have an ``__orig_bases__`` attribute, this
93
function returns the value of ``cls.__orig_bases__``.
94
For classes without the ``__orig_bases__`` attribute,
95
:attr:`cls.__bases__ <type.__bases__>` is returned.
96
97
Examples::
98
99
from typing import TypeVar, Generic, NamedTuple, TypedDict
100
101
T = TypeVar("T")
102
class Foo(Generic[T]): ...
103
class Bar(Foo[int], float): ...
104
class Baz(list[str]): ...
105
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
106
Spam = TypedDict("Spam", {"a": int, "b": str})
107
108
assert Bar.__bases__ == (Foo, float)
109
assert get_original_bases(Bar) == (Foo[int], float)
110
111
assert Baz.__bases__ == (list,)
112
assert get_original_bases(Baz) == (list[str],)
113
114
assert Eggs.__bases__ == (tuple,)
115
assert get_original_bases(Eggs) == (NamedTuple,)
116
117
assert Spam.__bases__ == (dict,)
118
assert get_original_bases(Spam) == (TypedDict,)
119
120
assert int.__bases__ == (object,)
121
assert get_original_bases(int) == (object,)
122
123
.. versionadded:: 3.12
124
125
.. seealso::
126
127
:pep:`560` - Core support for typing module and generic types
128
129
130
Standard Interpreter Types
131
--------------------------
132
133
This module provides names for many of the types that are required to
134
implement a Python interpreter. It deliberately avoids including some of
135
the types that arise only incidentally during processing such as the
136
``listiterator`` type.
137
138
Typical use of these names is for :func:`isinstance` or
139
:func:`issubclass` checks.
140
141
142
If you instantiate any of these types, note that signatures may vary between Python versions.
143
144
Standard names are defined for the following types:
145
146
.. data:: NoneType
147
148
The type of :data:`None`.
149
150
.. versionadded:: 3.10
151
152
153
.. data:: FunctionType
154
LambdaType
155
156
The type of user-defined functions and functions created by
157
:keyword:`lambda` expressions.
158
159
.. audit-event:: function.__new__ code types.FunctionType
160
161
The audit event only occurs for direct instantiation of function objects,
162
and is not raised for normal compilation.
163
164
165
.. data:: GeneratorType
166
167
The type of :term:`generator`-iterator objects, created by
168
generator functions.
169
170
171
.. data:: CoroutineType
172
173
The type of :term:`coroutine` objects, created by
174
:keyword:`async def` functions.
175
176
.. versionadded:: 3.5
177
178
179
.. data:: AsyncGeneratorType
180
181
The type of :term:`asynchronous generator`-iterator objects, created by
182
asynchronous generator functions.
183
184
.. versionadded:: 3.6
185
186
187
.. class:: CodeType(**kwargs)
188
189
.. index:: pair: built-in function; compile
190
191
The type of :ref:`code objects <code-objects>` such as returned by :func:`compile`.
192
193
.. audit-event:: code.__new__ code,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags types.CodeType
194
195
Note that the audited arguments may not match the names or positions
196
required by the initializer. The audit event only occurs for direct
197
instantiation of code objects, and is not raised for normal compilation.
198
199
.. data:: CellType
200
201
The type for cell objects: such objects are used as containers for
202
a function's :term:`closure variables <closure variable>`.
203
204
.. versionadded:: 3.8
205
206
207
.. data:: MethodType
208
209
The type of methods of user-defined class instances.
210
211
212
.. data:: BuiltinFunctionType
213
BuiltinMethodType
214
215
The type of built-in functions like :func:`len` or :func:`sys.exit`, and
216
methods of built-in classes. (Here, the term "built-in" means "written in
217
C".)
218
219
220
.. data:: WrapperDescriptorType
221
222
The type of methods of some built-in data types and base classes such as
223
:meth:`object.__init__` or :meth:`object.__lt__`.
224
225
.. versionadded:: 3.7
226
227
228
.. data:: MethodWrapperType
229
230
The type of *bound* methods of some built-in data types and base classes.
231
For example it is the type of :code:`object().__str__`.
232
233
.. versionadded:: 3.7
234
235
236
.. data:: NotImplementedType
237
238
The type of :data:`NotImplemented`.
239
240
.. versionadded:: 3.10
241
242
243
.. data:: MethodDescriptorType
244
245
The type of methods of some built-in data types such as :meth:`str.join`.
246
247
.. versionadded:: 3.7
248
249
250
.. data:: ClassMethodDescriptorType
251
252
The type of *unbound* class methods of some built-in data types such as
253
``dict.__dict__['fromkeys']``.
254
255
.. versionadded:: 3.7
256
257
258
.. class:: ModuleType(name, doc=None)
259
260
The type of :term:`modules <module>`. The constructor takes the name of the
261
module to be created and optionally its :term:`docstring`.
262
263
.. seealso::
264
265
:ref:`Documentation on module objects <module-objects>`
266
Provides details on the special attributes that can be found on
267
instances of :class:`!ModuleType`.
268
269
:func:`importlib.util.module_from_spec`
270
Modules created using the :class:`!ModuleType` constructor are
271
created with many of their special attributes unset or set to default
272
values. :func:`!module_from_spec` provides a more robust way of
273
creating :class:`!ModuleType` instances which ensures the various
274
attributes are set appropriately.
275
276
.. data:: EllipsisType
277
278
The type of :data:`Ellipsis`.
279
280
.. versionadded:: 3.10
281
282
.. class:: GenericAlias(t_origin, t_args)
283
284
The type of :ref:`parameterized generics <types-genericalias>` such as
285
``list[int]``.
286
287
``t_origin`` should be a non-parameterized generic class, such as ``list``,
288
``tuple`` or ``dict``. ``t_args`` should be a :class:`tuple` (possibly of
289
length 1) of types which parameterize ``t_origin``::
290
291
>>> from types import GenericAlias
292
293
>>> list[int] == GenericAlias(list, (int,))
294
True
295
>>> dict[str, int] == GenericAlias(dict, (str, int))
296
True
297
298
.. versionadded:: 3.9
299
300
.. versionchanged:: 3.9.2
301
This type can now be subclassed.
302
303
.. seealso::
304
305
:ref:`Generic Alias Types<types-genericalias>`
306
In-depth documentation on instances of :class:`!types.GenericAlias`
307
308
:pep:`585` - Type Hinting Generics In Standard Collections
309
Introducing the :class:`!types.GenericAlias` class
310
311
.. class:: UnionType
312
313
The type of :ref:`union type expressions<types-union>`.
314
315
.. versionadded:: 3.10
316
317
.. versionchanged:: 3.14
318
319
This is now an alias for :class:`typing.Union`.
320
321
.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)
322
323
The type of traceback objects such as found in ``sys.exception().__traceback__``.
324
325
See :ref:`the language reference <traceback-objects>` for details of the
326
available attributes and operations, and guidance on creating tracebacks
327
dynamically.
328
329
330
.. data:: FrameType
331
332
The type of :ref:`frame objects <frame-objects>` such as found in
333
:attr:`tb.tb_frame <traceback.tb_frame>` if ``tb`` is a traceback object.
334
335
336
.. data:: FrameLocalsProxyType
337
338
The type of frame locals proxy objects, as found on the
339
:attr:`frame.f_locals` attribute.
340
341
.. versionadded:: 3.15
342
343
.. seealso:: :pep:`667`
344
345
346
.. data:: LazyImportType
347
348
The type of lazy import proxy objects. These objects are created when a
349
module is lazily imported and serve as placeholders until the module is
350
actually accessed. This type can be used to detect lazy imports
351
programmatically.
352
353
.. versionadded:: 3.15
354
355
.. seealso:: :pep:`810`
356
357
358
.. data:: GetSetDescriptorType
359
360
The type of objects defined in extension modules with ``PyGetSetDef``, such
361
as :attr:`FrameType.f_locals <frame.f_locals>` or ``array.array.typecode``.
362
This type is used as
363
descriptor for object attributes; it has the same purpose as the
364
:class:`property` type, but for classes defined in extension modules.
365
366
367
.. data:: MemberDescriptorType
368
369
The type of objects defined in extension modules with ``PyMemberDef``, such
370
as ``datetime.timedelta.days``. This type is used as descriptor for simple C
371
data members which use standard conversion functions; it has the same purpose
372
as the :class:`property` type, but for classes defined in extension modules.
373
374
In addition, when a class is defined with a :attr:`~object.__slots__` attribute, then for
375
each slot, an instance of :class:`!MemberDescriptorType` will be added as an attribute
376
on the class. This allows the slot to appear in the class's :attr:`~type.__dict__`.
377
378
.. impl-detail::
379
380
In other implementations of Python, this type may be identical to
381
``GetSetDescriptorType``.
382
383
.. class:: MappingProxyType(mapping)
384
385
Read-only proxy of a mapping. It provides a dynamic view on the mapping's
386
entries, which means that when the mapping changes, the view reflects these
387
changes.
388
389
.. versionadded:: 3.3
390
391
.. versionchanged:: 3.9
392
393
Updated to support the new union (``|``) operator from :pep:`584`, which
394
simply delegates to the underlying mapping.
395
396
.. describe:: key in proxy
397
398
Return ``True`` if the underlying mapping has a key *key*, else
399
``False``.
400
401
.. describe:: proxy[key]
402
403
Return the item of the underlying mapping with key *key*. Raises a
404
:exc:`KeyError` if *key* is not in the underlying mapping.
405
406
.. describe:: iter(proxy)
407
408
Return an iterator over the keys of the underlying mapping. This is a
409
shortcut for ``iter(proxy.keys())``.
410
411
.. describe:: len(proxy)
412
413
Return the number of items in the underlying mapping.
414
415
.. method:: copy()
416
417
Return a shallow copy of the underlying mapping.
418
419
.. method:: get(key[, default])
420
421
Return the value for *key* if *key* is in the underlying mapping, else
422
*default*. If *default* is not given, it defaults to ``None``, so that
423
this method never raises a :exc:`KeyError`.
424
425
.. method:: items()
426
427
Return a new view of the underlying mapping's items (``(key, value)``
428
pairs).
429
430
.. method:: keys()
431
432
Return a new view of the underlying mapping's keys.
433
434
.. method:: values()
435
436
Return a new view of the underlying mapping's values.
437
438
.. describe:: reversed(proxy)
439
440
Return a reverse iterator over the keys of the underlying mapping.
441
442
.. versionadded:: 3.9
443
444
.. describe:: hash(proxy)
445
446
Return a hash of the underlying mapping.
447
448
.. versionadded:: 3.12
449
450
.. class:: CapsuleType
451
452
The type of :ref:`capsule objects <capsules>`.
453
454
.. versionadded:: 3.13
455
456
457
Additional Utility Classes and Functions
458
----------------------------------------
459
460
.. class:: SimpleNamespace
461
462
A simple :class:`object` subclass that provides attribute access to its
463
namespace, as well as a meaningful repr.
464
465
Unlike :class:`object`, with :class:`!SimpleNamespace` you can add and remove
466
attributes.
467
468
:py:class:`SimpleNamespace` objects may be initialized
469
in the same way as :class:`dict`: either with keyword arguments,
470
with a single positional argument, or with both.
471
When initialized with keyword arguments,
472
those are directly added to the underlying namespace.
473
Alternatively, when initialized with a positional argument,
474
the underlying namespace will be updated with key-value pairs
475
from that argument (either a mapping object or
476
an :term:`iterable` object producing key-value pairs).
477
All such keys must be strings.
478
479
The type is roughly equivalent to the following code::
480
481
class SimpleNamespace:
482
def __init__(self, mapping_or_iterable=(), /, **kwargs):
483
self.__dict__.update(mapping_or_iterable)
484
self.__dict__.update(kwargs)
485
486
def __repr__(self):
487
items = (f"{k}={v!r}" for k, v in self.__dict__.items())
488
return "{}({})".format(type(self).__name__, ", ".join(items))
489
490
def __eq__(self, other):
491
if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
492
return self.__dict__ == other.__dict__
493
return NotImplemented
494
495
``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``.
496
However, for a structured record type use :func:`~collections.namedtuple`
497
instead.
498
499
:class:`!SimpleNamespace` objects are supported by :func:`copy.replace`.
500
501
.. versionadded:: 3.3
502
503
.. versionchanged:: 3.9
504
Attribute order in the repr changed from alphabetical to insertion (like
505
``dict``).
506
507
.. versionchanged:: 3.13
508
Added support for an optional positional argument.
509
510
.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)
511
512
Route attribute access on a class to __getattr__.
513
514
This is a descriptor, used to define attributes that act differently when
515
accessed through an instance and through a class. Instance access remains
516
normal, but access to an attribute through a class will be routed to the
517
class's __getattr__ method; this is done by raising AttributeError.
518
519
This allows one to have properties active on an instance, and have virtual
520
attributes on the class with the same name (see :class:`enum.Enum` for an example).
521
522
.. versionadded:: 3.4
523
524
525
Coroutine Utility Functions
526
---------------------------
527
528
.. function:: coroutine(gen_func)
529
530
This function transforms a :term:`generator` function into a
531
:term:`coroutine function` which returns a generator-based coroutine.
532
The generator-based coroutine is still a :term:`generator iterator`,
533
but is also considered to be a :term:`coroutine` object and is
534
:term:`awaitable`. However, it may not necessarily implement
535
the :meth:`~object.__await__` method.
536
537
If *gen_func* is a generator function, it will be modified in-place.
538
539
If *gen_func* is not a generator function, it will be wrapped. If it
540
returns an instance of :class:`collections.abc.Generator`, the instance
541
will be wrapped in an *awaitable* proxy object. All other types
542
of objects will be returned as is.
543
544
.. versionadded:: 3.5