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