| 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 |
.. class:: 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 |
.. class:: 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 |
.. class:: 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:: GetSetDescriptorType |
| 337 |
|
| 338 |
The type of objects defined in extension modules with ``PyGetSetDef``, such |
| 339 |
as :attr:`FrameType.f_locals <frame.f_locals>` or ``array.array.typecode``. |
| 340 |
This type is used as |
| 341 |
descriptor for object attributes; it has the same purpose as the |
| 342 |
:class:`property` type, but for classes defined in extension modules. |
| 343 |
|
| 344 |
|
| 345 |
.. data:: MemberDescriptorType |
| 346 |
|
| 347 |
The type of objects defined in extension modules with ``PyMemberDef``, such |
| 348 |
as ``datetime.timedelta.days``. This type is used as descriptor for simple C |
| 349 |
data members which use standard conversion functions; it has the same purpose |
| 350 |
as the :class:`property` type, but for classes defined in extension modules. |
| 351 |
|
| 352 |
In addition, when a class is defined with a :attr:`~object.__slots__` attribute, then for |
| 353 |
each slot, an instance of :class:`!MemberDescriptorType` will be added as an attribute |
| 354 |
on the class. This allows the slot to appear in the class's :attr:`~type.__dict__`. |
| 355 |
|
| 356 |
.. impl-detail:: |
| 357 |
|
| 358 |
In other implementations of Python, this type may be identical to |
| 359 |
``GetSetDescriptorType``. |
| 360 |
|
| 361 |
.. class:: MappingProxyType(mapping) |
| 362 |
|
| 363 |
Read-only proxy of a mapping. It provides a dynamic view on the mapping's |
| 364 |
entries, which means that when the mapping changes, the view reflects these |
| 365 |
changes. |
| 366 |
|
| 367 |
:class:`!MappingProxyType`\s are :ref:`generic <generics>` over two types, |
| 368 |
signifying (respectively) the types of the underlying mapping's keys and |
| 369 |
values. |
| 370 |
|
| 371 |
.. versionadded:: 3.3 |
| 372 |
|
| 373 |
.. versionchanged:: 3.9 |
| 374 |
|
| 375 |
Updated to support the new union (``|``) operator from :pep:`584`, which |
| 376 |
simply delegates to the underlying mapping. |
| 377 |
|
| 378 |
.. describe:: key in proxy |
| 379 |
|
| 380 |
Return ``True`` if the underlying mapping has a key *key*, else |
| 381 |
``False``. |
| 382 |
|
| 383 |
.. describe:: proxy[key] |
| 384 |
|
| 385 |
Return the item of the underlying mapping with key *key*. Raises a |
| 386 |
:exc:`KeyError` if *key* is not in the underlying mapping. |
| 387 |
|
| 388 |
.. describe:: iter(proxy) |
| 389 |
|
| 390 |
Return an iterator over the keys of the underlying mapping. This is a |
| 391 |
shortcut for ``iter(proxy.keys())``. |
| 392 |
|
| 393 |
.. describe:: len(proxy) |
| 394 |
|
| 395 |
Return the number of items in the underlying mapping. |
| 396 |
|
| 397 |
.. method:: copy() |
| 398 |
|
| 399 |
Return a shallow copy of the underlying mapping. |
| 400 |
|
| 401 |
.. method:: get(key[, default]) |
| 402 |
|
| 403 |
Return the value for *key* if *key* is in the underlying mapping, else |
| 404 |
*default*. If *default* is not given, it defaults to ``None``, so that |
| 405 |
this method never raises a :exc:`KeyError`. |
| 406 |
|
| 407 |
.. method:: items() |
| 408 |
|
| 409 |
Return a new view of the underlying mapping's items (``(key, value)`` |
| 410 |
pairs). |
| 411 |
|
| 412 |
.. method:: keys() |
| 413 |
|
| 414 |
Return a new view of the underlying mapping's keys. |
| 415 |
|
| 416 |
.. method:: values() |
| 417 |
|
| 418 |
Return a new view of the underlying mapping's values. |
| 419 |
|
| 420 |
.. describe:: reversed(proxy) |
| 421 |
|
| 422 |
Return a reverse iterator over the keys of the underlying mapping. |
| 423 |
|
| 424 |
.. versionadded:: 3.9 |
| 425 |
|
| 426 |
.. describe:: hash(proxy) |
| 427 |
|
| 428 |
Return a hash of the underlying mapping. |
| 429 |
|
| 430 |
.. versionadded:: 3.12 |
| 431 |
|
| 432 |
.. class:: CapsuleType |
| 433 |
|
| 434 |
The type of :ref:`capsule objects <capsules>`. |
| 435 |
|
| 436 |
.. versionadded:: 3.13 |
| 437 |
|
| 438 |
|
| 439 |
Additional Utility Classes and Functions |
| 440 |
---------------------------------------- |
| 441 |
|
| 442 |
.. class:: SimpleNamespace |
| 443 |
|
| 444 |
A simple :class:`object` subclass that provides attribute access to its |
| 445 |
namespace, as well as a meaningful repr. |
| 446 |
|
| 447 |
Unlike :class:`object`, with :class:`!SimpleNamespace` you can add and remove |
| 448 |
attributes. |
| 449 |
|
| 450 |
:py:class:`SimpleNamespace` objects may be initialized |
| 451 |
in the same way as :class:`dict`: either with keyword arguments, |
| 452 |
with a single positional argument, or with both. |
| 453 |
When initialized with keyword arguments, |
| 454 |
those are directly added to the underlying namespace. |
| 455 |
Alternatively, when initialized with a positional argument, |
| 456 |
the underlying namespace will be updated with key-value pairs |
| 457 |
from that argument (either a mapping object or |
| 458 |
an :term:`iterable` object producing key-value pairs). |
| 459 |
All such keys must be strings. |
| 460 |
|
| 461 |
The type is roughly equivalent to the following code:: |
| 462 |
|
| 463 |
class SimpleNamespace: |
| 464 |
def __init__(self, mapping_or_iterable=(), /, **kwargs): |
| 465 |
self.__dict__.update(mapping_or_iterable) |
| 466 |
self.__dict__.update(kwargs) |
| 467 |
|
| 468 |
def __repr__(self): |
| 469 |
items = (f"{k}={v!r}" for k, v in self.__dict__.items()) |
| 470 |
return "{}({})".format(type(self).__name__, ", ".join(items)) |
| 471 |
|
| 472 |
def __eq__(self, other): |
| 473 |
if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace): |
| 474 |
return self.__dict__ == other.__dict__ |
| 475 |
return NotImplemented |
| 476 |
|
| 477 |
``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``. |
| 478 |
However, for a structured record type use :func:`~collections.namedtuple` |
| 479 |
instead. |
| 480 |
|
| 481 |
:class:`!SimpleNamespace` objects are supported by :func:`copy.replace`. |
| 482 |
|
| 483 |
.. versionadded:: 3.3 |
| 484 |
|
| 485 |
.. versionchanged:: 3.9 |
| 486 |
Attribute order in the repr changed from alphabetical to insertion (like |
| 487 |
``dict``). |
| 488 |
|
| 489 |
.. versionchanged:: 3.13 |
| 490 |
Added support for an optional positional argument. |
| 491 |
|
| 492 |
.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None) |
| 493 |
|
| 494 |
Route attribute access on a class to __getattr__. |
| 495 |
|
| 496 |
This is a descriptor, used to define attributes that act differently when |
| 497 |
accessed through an instance and through a class. Instance access remains |
| 498 |
normal, but access to an attribute through a class will be routed to the |
| 499 |
class's __getattr__ method; this is done by raising AttributeError. |
| 500 |
|
| 501 |
This allows one to have properties active on an instance, and have virtual |
| 502 |
attributes on the class with the same name (see :class:`enum.Enum` for an example). |
| 503 |
|
| 504 |
.. versionadded:: 3.4 |
| 505 |
|
| 506 |
|
| 507 |
Coroutine Utility Functions |
| 508 |
--------------------------- |
| 509 |
|
| 510 |
.. function:: coroutine(gen_func) |
| 511 |
|
| 512 |
This function transforms a :term:`generator` function into a |
| 513 |
:term:`coroutine function` which returns a generator-based coroutine. |
| 514 |
The generator-based coroutine is still a :term:`generator iterator`, |
| 515 |
but is also considered to be a :term:`coroutine` object and is |
| 516 |
:term:`awaitable`. However, it may not necessarily implement |
| 517 |
the :meth:`~object.__await__` method. |
| 518 |
|
| 519 |
If *gen_func* is a generator function, it will be modified in-place. |
| 520 |
|
| 521 |
If *gen_func* is not a generator function, it will be wrapped. If it |
| 522 |
returns an instance of :class:`collections.abc.Generator`, the instance |
| 523 |
will be wrapped in an *awaitable* proxy object. All other types |
| 524 |
of objects will be returned as is. |
| 525 |
|
| 526 |
.. versionadded:: 3.5 |