1 2.. _datamodel: 3 4********** 5Data model 6********** 7 8 9.. _objects: 10 11Objects, values and types 12========================= 13 14.. index:: 15 single: object 16 single: data 17 18:dfn:`Objects` are Python's abstraction for data. All data in a Python program 19is represented by objects or by relations between objects. (In a sense, and in 20conformance to Von Neumann's model of a "stored program computer", code is also 21represented by objects.) 22 23.. index:: 24 pair: built-in function; id 25 pair: built-in function; type 26 single: identity of an object 27 single: value of an object 28 single: type of an object 29 single: mutable object 30 single: immutable object 31 32.. XXX it *is* now possible in some cases to change an object's 33 type, under certain controlled conditions 34 35Every object has an identity, a type and a value. An object's *identity* never 36changes once it has been created; you may think of it as the object's address in 37memory. The :keyword:`is` operator compares the identity of two objects; the 38:func:`id` function returns an integer representing its identity. 39 40.. impl-detail:: 41 42 For CPython, ``id(x)`` is the memory address where ``x`` is stored. 43 44An object's type determines the operations that the object supports (e.g., "does 45it have a length?") and also defines the possible values for objects of that 46type. The :func:`type` function returns an object's type (which is an object 47itself). Like its identity, an object's :dfn:`type` is also unchangeable. 48[#]_ 49 50The *value* of some objects can change. Objects whose value can 51change are said to be *mutable*; objects whose value is unchangeable once they 52are created are called *immutable*. (The value of an immutable container object 53that contains a reference to a mutable object can change when the latter's value 54is changed; however the container is still considered immutable, because the 55collection of objects it contains cannot be changed. So, immutability is not 56strictly the same as having an unchangeable value, it is more subtle.) An 57object's mutability is determined by its type; for instance, numbers, strings 58and tuples are immutable, while dictionaries and lists are mutable. 59 60.. index:: 61 single: garbage collection 62 single: reference counting 63 single: unreachable object 64 65Objects are never explicitly destroyed; however, when they become unreachable 66they may be garbage-collected. An implementation is allowed to postpone garbage 67collection or omit it altogether --- it is a matter of implementation quality 68how garbage collection is implemented, as long as no objects are collected that 69are still reachable. 70 71.. impl-detail:: 72 73 CPython currently uses a reference-counting scheme with (optional) delayed 74 detection of cyclically linked garbage, which collects most objects as soon 75 as they become unreachable, but is not guaranteed to collect garbage 76 containing circular references. See the documentation of the :mod:`gc` 77 module for information on controlling the collection of cyclic garbage. 78 Other implementations act differently and CPython may change. 79 Do not depend on immediate finalization of objects when they become 80 unreachable (so you should always close files explicitly). 81 82Note that the use of the implementation's tracing or debugging facilities may 83keep objects alive that would normally be collectable. Also note that catching 84an exception with a :keyword:`try`...\ :keyword:`except` statement may keep 85objects alive. 86 87Some objects contain references to "external" resources such as open files or 88windows. It is understood that these resources are freed when the object is 89garbage-collected, but since garbage collection is not guaranteed to happen, 90such objects also provide an explicit way to release the external resource, 91usually a :meth:`!close` method. Programs are strongly recommended to explicitly 92close such objects. The :keyword:`try`...\ :keyword:`finally` statement 93and the :keyword:`with` statement provide convenient ways to do this. 94 95.. index:: single: container 96 97Some objects contain references to other objects; these are called *containers*. 98Examples of containers are tuples, lists and dictionaries. The references are 99part of a container's value. In most cases, when we talk about the value of a 100container, we imply the values, not the identities of the contained objects; 101however, when we talk about the mutability of a container, only the identities 102of the immediately contained objects are implied. So, if an immutable container 103(like a tuple) contains a reference to a mutable object, its value changes if 104that mutable object is changed. 105 106Types affect almost all aspects of object behavior. Even the importance of 107object identity is affected in some sense: for immutable types, operations that 108compute new values may actually return a reference to any existing object with 109the same type and value, while for mutable objects this is not allowed. 110For example, after ``a = 1; b = 1``, *a* and *b* may or may not refer to 111the same object with the value one, depending on the implementation. 112This is because :class:`int` is an immutable type, so the reference to ``1`` 113can be reused. This behaviour depends on the implementation used, so should 114not be relied upon, but is something to be aware of when making use of object 115identity tests. 116However, after ``c = []; d = []``, *c* and *d* are guaranteed to refer to two 117different, unique, newly created empty lists. (Note that ``e = f = []`` assigns 118the *same* object to both *e* and *f*.) 119 120 121.. _types: 122 123The standard type hierarchy 124=========================== 125 126.. index:: 127 single: type 128 pair: data; type 129 pair: type; hierarchy 130 pair: extension; module 131 pair: C; language 132 133Below is a list of the types that are built into Python. Extension modules 134(written in C, Java, or other languages, depending on the implementation) can 135define additional types. Future versions of Python may add types to the type 136hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), 137although such additions will often be provided via the standard library instead. 138 139.. index:: 140 single: attribute 141 pair: special; attribute 142 triple: generic; special; attribute 143 144Some of the type descriptions below contain a paragraph listing 'special 145attributes.' These are attributes that provide access to the implementation and 146are not intended for general use. Their definition may change in the future. 147 148 149None 150---- 151 152.. index:: pair: object; None 153 154This type has a single value. There is a single object with this value. This 155object is accessed through the built-in name ``None``. It is used to signify the 156absence of a value in many situations, e.g., it is returned from functions that 157don't explicitly return anything. Its truth value is false. 158 159 160NotImplemented 161-------------- 162 163.. index:: pair: object; NotImplemented 164 165This type has a single value. There is a single object with this value. This 166object is accessed through the built-in name :data:`NotImplemented`. Numeric methods 167and rich comparison methods should return this value if they do not implement the 168operation for the operands provided. (The interpreter will then try the 169reflected operation, or some other fallback, depending on the operator.) It 170should not be evaluated in a boolean context. 171 172See 173:ref:`implementing-the-arithmetic-operations` 174for more details. 175 176.. versionchanged:: 3.9 177 Evaluating :data:`NotImplemented` in a boolean context is deprecated. While 178 it currently evaluates as true, it will emit a :exc:`DeprecationWarning`. 179 It will raise a :exc:`TypeError` in a future version of Python. 180 181 182Ellipsis 183-------- 184.. index:: 185 pair: object; Ellipsis 186 single: ...; ellipsis literal 187 188This type has a single value. There is a single object with this value. This 189object is accessed through the literal ``...`` or the built-in name 190``Ellipsis``. Its truth value is true. 191 192 193:class:`numbers.Number` 194----------------------- 195 196.. index:: pair: object; numeric 197 198These are created by numeric literals and returned as results by arithmetic 199operators and arithmetic built-in functions. Numeric objects are immutable; 200once created their value never changes. Python numbers are of course strongly 201related to mathematical numbers, but subject to the limitations of numerical 202representation in computers. 203 204The string representations of the numeric classes, computed by 205:meth:`~object.__repr__` and :meth:`~object.__str__`, have the following 206properties: 207 208* They are valid numeric literals which, when passed to their 209 class constructor, produce an object having the value of the 210 original numeric. 211 212* The representation is in base 10, when possible. 213 214* Leading zeros, possibly excepting a single zero before a 215 decimal point, are not shown. 216 217* Trailing zeros, possibly excepting a single zero after a 218 decimal point, are not shown. 219 220* A sign is shown only when the number is negative. 221 222Python distinguishes between integers, floating-point numbers, and complex 223numbers: 224 225 226:class:`numbers.Integral` 227^^^^^^^^^^^^^^^^^^^^^^^^^ 228 229.. index:: pair: object; integer 230 231These represent elements from the mathematical set of integers (positive and 232negative). 233 234.. note:: 235 .. index:: pair: integer; representation 236 237 The rules for integer representation are intended to give the most meaningful 238 interpretation of shift and mask operations involving negative integers. 239 240There are two types of integers: 241 242Integers (:class:`int`) 243 These represent numbers in an unlimited range, subject to available (virtual) 244 memory only. For the purpose of shift and mask operations, a binary 245 representation is assumed, and negative numbers are represented in a variant of 246 2's complement which gives the illusion of an infinite string of sign bits 247 extending to the left. 248 249Booleans (:class:`bool`) 250 .. index:: 251 pair: object; Boolean 252 single: False 253 single: True 254 255 These represent the truth values False and True. The two objects representing 256 the values ``False`` and ``True`` are the only Boolean objects. The Boolean type is a 257 subtype of the integer type, and Boolean values behave like the values 0 and 1, 258 respectively, in almost all contexts, the exception being that when converted to 259 a string, the strings ``"False"`` or ``"True"`` are returned, respectively. 260 261 262:class:`numbers.Real` (:class:`float`) 263^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 264 265.. index:: 266 pair: object; floating-point 267 pair: floating-point; number 268 pair: C; language 269 pair: Java; language 270 271These represent machine-level double precision floating-point numbers. You are 272at the mercy of the underlying machine architecture (and C or Java 273implementation) for the accepted range and handling of overflow. Python does not 274support single-precision floating-point numbers; the savings in processor and 275memory usage that are usually the reason for using these are dwarfed by the 276overhead of using objects in Python, so there is no reason to complicate the 277language with two kinds of floating-point numbers. 278 279 280:class:`numbers.Complex` (:class:`complex`) 281^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 282 283.. index:: 284 pair: object; complex 285 pair: complex; number 286 287These represent complex numbers as a pair of machine-level double precision 288floating-point numbers. The same caveats apply as for floating-point numbers. 289The real and imaginary parts of a complex number ``z`` can be retrieved through 290the read-only attributes ``z.real`` and ``z.imag``. 291 292 293Sequences 294--------- 295 296.. index:: 297 pair: built-in function; len 298 pair: object; sequence 299 single: index operation 300 single: item selection 301 single: subscription 302 303These represent finite ordered sets indexed by non-negative numbers. The 304built-in function :func:`len` returns the number of items of a sequence. When 305the length of a sequence is *n*, the index set contains the numbers 0, 1, 306..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``. Some sequences, 307including built-in sequences, interpret negative subscripts by adding the 308sequence length. For example, ``a[-2]`` equals ``a[n-2]``, the second to last 309item of sequence a with length ``n``. 310 311.. index:: single: slicing 312 313Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such 314that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a 315sequence of the same type. The comment above about negative indexes also applies 316to negative slice positions. 317 318Some sequences also support "extended slicing" with a third "step" parameter: 319``a[i:j:k]`` selects all items of *a* with index *x* where ``x = i + n*k``, *n* 320``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*. 321 322Sequences are distinguished according to their mutability: 323 324 325Immutable sequences 326^^^^^^^^^^^^^^^^^^^ 327 328.. index:: 329 pair: object; immutable sequence 330 pair: object; immutable 331 332An object of an immutable sequence type cannot change once it is created. (If 333the object contains references to other objects, these other objects may be 334mutable and may be changed; however, the collection of objects directly 335referenced by an immutable object cannot change.) 336 337The following types are immutable sequences: 338 339.. index:: 340 single: string; immutable sequences 341 342Strings 343 .. index:: 344 pair: built-in function; chr 345 pair: built-in function; ord 346 single: character 347 single: integer 348 single: Unicode 349 350 A string is a sequence of values that represent Unicode code points. 351 All the code points in the range ``U+0000 - U+10FFFF`` can be 352 represented in a string. Python doesn't have a :c:expr:`char` type; 353 instead, every code point in the string is represented as a string 354 object with length ``1``. The built-in function :func:`ord` 355 converts a code point from its string form to an integer in the 356 range ``0 - 10FFFF``; :func:`chr` converts an integer in the range 357 ``0 - 10FFFF`` to the corresponding length ``1`` string object. 358 :meth:`str.encode` can be used to convert a :class:`str` to 359 :class:`bytes` using the given text encoding, and 360 :meth:`bytes.decode` can be used to achieve the opposite. 361 362Tuples 363 .. index:: 364 pair: object; tuple 365 pair: singleton; tuple 366 pair: empty; tuple 367 368 The items of a tuple are arbitrary Python objects. Tuples of two or 369 more items are formed by comma-separated lists of expressions. A tuple 370 of one item (a 'singleton') can be formed by affixing a comma to an 371 expression (an expression by itself does not create a tuple, since 372 parentheses must be usable for grouping of expressions). An empty 373 tuple can be formed by an empty pair of parentheses. 374 375Bytes 376 .. index:: bytes, byte 377 378 A bytes object is an immutable array. The items are 8-bit bytes, 379 represented by integers in the range 0 <= x < 256. Bytes literals 380 (like ``b'abc'``) and the built-in :func:`bytes` constructor 381 can be used to create bytes objects. Also, bytes objects can be 382 decoded to strings via the :meth:`~bytes.decode` method. 383 384 385Mutable sequences 386^^^^^^^^^^^^^^^^^ 387 388.. index:: 389 pair: object; mutable sequence 390 pair: object; mutable 391 pair: assignment; statement 392 single: subscription 393 single: slicing 394 395Mutable sequences can be changed after they are created. The subscription and 396slicing notations can be used as the target of assignment and :keyword:`del` 397(delete) statements. 398 399.. note:: 400 .. index:: pair: module; array 401 .. index:: pair: module; collections 402 403 The :mod:`collections` and :mod:`array` module provide 404 additional examples of mutable sequence types. 405 406There are currently two intrinsic mutable sequence types: 407 408Lists 409 .. index:: pair: object; list 410 411 The items of a list are arbitrary Python objects. Lists are formed by 412 placing a comma-separated list of expressions in square brackets. (Note 413 that there are no special cases needed to form lists of length 0 or 1.) 414 415Byte Arrays 416 .. index:: bytearray 417 418 A bytearray object is a mutable array. They are created by the built-in 419 :func:`bytearray` constructor. Aside from being mutable 420 (and hence unhashable), byte arrays otherwise provide the same interface 421 and functionality as immutable :class:`bytes` objects. 422 423 424Set types 425--------- 426 427.. index:: 428 pair: built-in function; len 429 pair: object; set type 430 431These represent unordered, finite sets of unique, immutable objects. As such, 432they cannot be indexed by any subscript. However, they can be iterated over, and 433the built-in function :func:`len` returns the number of items in a set. Common 434uses for sets are fast membership testing, removing duplicates from a sequence, 435and computing mathematical operations such as intersection, union, difference, 436and symmetric difference. 437 438For set elements, the same immutability rules apply as for dictionary keys. Note 439that numeric types obey the normal rules for numeric comparison: if two numbers 440compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a 441set. 442 443There are currently two intrinsic set types: 444 445 446Sets 447 .. index:: pair: object; set 448 449 These represent a mutable set. They are created by the built-in :func:`set` 450 constructor and can be modified afterwards by several methods, such as 451 :meth:`~set.add`. 452 453 454Frozen sets 455 .. index:: pair: object; frozenset 456 457 These represent an immutable set. They are created by the built-in 458 :func:`frozenset` constructor. As a frozenset is immutable and 459 :term:`hashable`, it can be used again as an element of another set, or as 460 a dictionary key. 461 462 463Mappings 464-------- 465 466.. index:: 467 pair: built-in function; len 468 single: subscription 469 pair: object; mapping 470 471These represent finite sets of objects indexed by arbitrary index sets. The 472subscript notation ``a[k]`` selects the item indexed by ``k`` from the mapping 473``a``; this can be used in expressions and as the target of assignments or 474:keyword:`del` statements. The built-in function :func:`len` returns the number 475of items in a mapping. 476 477There is currently a single intrinsic mapping type: 478 479 480Dictionaries 481^^^^^^^^^^^^ 482 483.. index:: pair: object; dictionary 484 485These represent finite sets of objects indexed by nearly arbitrary values. The 486only types of values not acceptable as keys are values containing lists or 487dictionaries or other mutable types that are compared by value rather than by 488object identity, the reason being that the efficient implementation of 489dictionaries requires a key's hash value to remain constant. Numeric types used 490for keys obey the normal rules for numeric comparison: if two numbers compare 491equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index 492the same dictionary entry. 493 494Dictionaries preserve insertion order, meaning that keys will be produced 495in the same order they were added sequentially over the dictionary. 496Replacing an existing key does not change the order, however removing a key 497and re-inserting it will add it to the end instead of keeping its old place. 498 499Dictionaries are mutable; they can be created by the ``{}`` notation (see 500section :ref:`dict`). 501 502.. index:: 503 pair: module; dbm.ndbm 504 pair: module; dbm.gnu 505 506The extension modules :mod:`dbm.ndbm` and :mod:`dbm.gnu` provide 507additional examples of mapping types, as does the :mod:`collections` 508module. 509 510.. versionchanged:: 3.7 511 Dictionaries did not preserve insertion order in versions of Python before 3.6. 512 In CPython 3.6, insertion order was preserved, but it was considered 513 an implementation detail at that time rather than a language guarantee. 514 515 516Callable types 517-------------- 518 519.. index:: 520 pair: object; callable 521 pair: function; call 522 single: invocation 523 pair: function; argument 524 525These are the types to which the function call operation (see section 526:ref:`calls`) can be applied: 527 528 529.. _user-defined-funcs: 530 531User-defined functions 532^^^^^^^^^^^^^^^^^^^^^^ 533 534.. index:: 535 pair: user-defined; function 536 pair: object; function 537 pair: object; user-defined function 538 539A user-defined function object is created by a function definition (see 540section :ref:`function`). It should be called with an argument list 541containing the same number of items as the function's formal parameter 542list. 543 544Special read-only attributes 545~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 546 547.. index:: 548 single: __closure__ (function attribute) 549 single: __globals__ (function attribute) 550 pair: global; namespace 551 552.. list-table:: 553 :header-rows: 1 554 555 * - Attribute 556 - Meaning 557 558 * - .. attribute:: function.__globals__ 559 - A reference to the :class:`dictionary <dict>` that holds the function's 560 :ref:`global variables <naming>` -- the global namespace of the module 561 in which the function was defined. 562 563 * - .. attribute:: function.__closure__ 564 - ``None`` or a :class:`tuple` of cells that contain bindings for the names specified 565 in the :attr:`~codeobject.co_freevars` attribute of the function's 566 :attr:`code object <function.__code__>`. 567 568 A cell object has the attribute ``cell_contents``. 569 This can be used to get the value of the cell, as well as set the value. 570 571Special writable attributes 572~~~~~~~~~~~~~~~~~~~~~~~~~~~ 573 574.. index:: 575 single: __doc__ (function attribute) 576 single: __name__ (function attribute) 577 single: __module__ (function attribute) 578 single: __dict__ (function attribute) 579 single: __defaults__ (function attribute) 580 single: __code__ (function attribute) 581 single: __annotations__ (function attribute) 582 single: __kwdefaults__ (function attribute) 583 single: __type_params__ (function attribute) 584 585Most of these attributes check the type of the assigned value: 586 587.. list-table:: 588 :header-rows: 1 589 590 * - Attribute 591 - Meaning 592 593 * - .. attribute:: function.__doc__ 594 - The function's documentation string, or ``None`` if unavailable. 595 596 * - .. attribute:: function.__name__ 597 - The function's name. 598 See also: :attr:`__name__ attributes <definition.__name__>`. 599 600 * - .. attribute:: function.__qualname__ 601 - The function's :term:`qualified name`. 602 See also: :attr:`__qualname__ attributes <definition.__qualname__>`. 603 604 .. versionadded:: 3.3 605 606 * - .. attribute:: function.__module__ 607 - The name of the module the function was defined in, 608 or ``None`` if unavailable. 609 610 * - .. attribute:: function.__defaults__ 611 - A :class:`tuple` containing default :term:`parameter` values 612 for those parameters that have defaults, 613 or ``None`` if no parameters have a default value. 614 615 * - .. attribute:: function.__code__ 616 - The :ref:`code object <code-objects>` representing 617 the compiled function body. 618 619 * - .. attribute:: function.__dict__ 620 - The namespace supporting arbitrary function attributes. 621 See also: :attr:`__dict__ attributes <object.__dict__>`. 622 623 * - .. attribute:: function.__annotations__ 624 - A :class:`dictionary <dict>` containing annotations of 625 :term:`parameters <parameter>`. 626 The keys of the dictionary are the parameter names, 627 and ``'return'`` for the return annotation, if provided. 628 See also: :ref:`annotations-howto`. 629 630 * - .. attribute:: function.__kwdefaults__ 631 - A :class:`dictionary <dict>` containing defaults for keyword-only 632 :term:`parameters <parameter>`. 633 634 * - .. attribute:: function.__type_params__ 635 - A :class:`tuple` containing the :ref:`type parameters <type-params>` of 636 a :ref:`generic function <generic-functions>`. 637 638 .. versionadded:: 3.12 639 640Function objects also support getting and setting arbitrary attributes, which 641can be used, for example, to attach metadata to functions. Regular attribute 642dot-notation is used to get and set such attributes. 643 644.. impl-detail:: 645 646 CPython's current implementation only supports function attributes 647 on user-defined functions. Function attributes on 648 :ref:`built-in functions <builtin-functions>` may be supported in the 649 future. 650 651Additional information about a function's definition can be retrieved from its 652:ref:`code object <code-objects>` 653(accessible via the :attr:`~function.__code__` attribute). 654 655 656.. _instance-methods: 657 658Instance methods 659^^^^^^^^^^^^^^^^ 660 661.. index:: 662 pair: object; method 663 pair: object; user-defined method 664 pair: user-defined; method 665 666An instance method object combines a class, a class instance and any 667callable object (normally a user-defined function). 668 669.. index:: 670 single: __func__ (method attribute) 671 single: __self__ (method attribute) 672 single: __doc__ (method attribute) 673 single: __name__ (method attribute) 674 single: __module__ (method attribute) 675 676Special read-only attributes: 677 678.. list-table:: 679 680 * - .. attribute:: method.__self__ 681 - Refers to the class instance object to which the method is 682 :ref:`bound <method-binding>` 683 684 * - .. attribute:: method.__func__ 685 - Refers to the original :ref:`function object <user-defined-funcs>` 686 687 * - .. attribute:: method.__doc__ 688 - The method's documentation 689 (same as :attr:`method.__func__.__doc__ <function.__doc__>`). 690 A :class:`string <str>` if the original function had a docstring, else 691 ``None``. 692 693 * - .. attribute:: method.__name__ 694 - The name of the method 695 (same as :attr:`method.__func__.__name__ <function.__name__>`) 696 697 * - .. attribute:: method.__module__ 698 - The name of the module the method was defined in, or ``None`` if 699 unavailable. 700 701Methods also support accessing (but not setting) the arbitrary function 702attributes on the underlying :ref:`function object <user-defined-funcs>`. 703 704User-defined method objects may be created when getting an attribute of a 705class (perhaps via an instance of that class), if that attribute is a 706user-defined :ref:`function object <user-defined-funcs>` or a 707:class:`classmethod` object. 708 709.. _method-binding: 710 711When an instance method object is created by retrieving a user-defined 712:ref:`function object <user-defined-funcs>` from a class via one of its 713instances, its :attr:`~method.__self__` attribute is the instance, and the 714method object is said to be *bound*. The new method's :attr:`~method.__func__` 715attribute is the original function object. 716 717When an instance method object is created by retrieving a :class:`classmethod` 718object from a class or instance, its :attr:`~method.__self__` attribute is the 719class itself, and its :attr:`~method.__func__` attribute is the function object 720underlying the class method. 721 722When an instance method object is called, the underlying function 723(:attr:`~method.__func__`) is called, inserting the class instance 724(:attr:`~method.__self__`) in front of the argument list. For instance, when 725:class:`!C` is a class which contains a definition for a function 726:meth:`!f`, and ``x`` is an instance of :class:`!C`, calling ``x.f(1)`` is 727equivalent to calling ``C.f(x, 1)``. 728 729When an instance method object is derived from a :class:`classmethod` object, the 730"class instance" stored in :attr:`~method.__self__` will actually be the class 731itself, so that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to 732calling ``f(C,1)`` where ``f`` is the underlying function. 733 734It is important to note that user-defined functions 735which are attributes of a class instance are not converted to bound 736methods; this *only* happens when the function is an attribute of the 737class. 738 739 740Generator functions 741^^^^^^^^^^^^^^^^^^^ 742 743.. index:: 744 single: generator; function 745 single: generator; iterator 746 747A function or method which uses the :keyword:`yield` statement (see section 748:ref:`yield`) is called a :dfn:`generator function`. Such a function, when 749called, always returns an :term:`iterator` object which can be used to 750execute the body of the function: calling the iterator's 751:meth:`iterator.__next__` method will cause the function to execute until 752it provides a value using the :keyword:`!yield` statement. When the 753function executes a :keyword:`return` statement or falls off the end, a 754:exc:`StopIteration` exception is raised and the iterator will have 755reached the end of the set of values to be returned. 756 757 758Coroutine functions 759^^^^^^^^^^^^^^^^^^^ 760 761.. index:: 762 single: coroutine; function 763 764A function or method which is defined using :keyword:`async def` is called 765a :dfn:`coroutine function`. Such a function, when called, returns a 766:term:`coroutine` object. It may contain :keyword:`await` expressions, 767as well as :keyword:`async with` and :keyword:`async for` statements. See 768also the :ref:`coroutine-objects` section. 769 770 771Asynchronous generator functions 772^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 773 774.. index:: 775 single: asynchronous generator; function 776 single: asynchronous generator; asynchronous iterator 777 778A function or method which is defined using :keyword:`async def` and 779which uses the :keyword:`yield` statement is called a 780:dfn:`asynchronous generator function`. Such a function, when called, 781returns an :term:`asynchronous iterator` object which can be used in an 782:keyword:`async for` statement to execute the body of the function. 783 784Calling the asynchronous iterator's 785:meth:`aiterator.__anext__ <object.__anext__>` method 786will return an :term:`awaitable` which when awaited 787will execute until it provides a value using the :keyword:`yield` 788expression. When the function executes an empty :keyword:`return` 789statement or falls off the end, a :exc:`StopAsyncIteration` exception 790is raised and the asynchronous iterator will have reached the end of 791the set of values to be yielded. 792 793 794.. _builtin-functions: 795 796Built-in functions 797^^^^^^^^^^^^^^^^^^ 798 799.. index:: 800 pair: object; built-in function 801 pair: object; function 802 pair: C; language 803 804A built-in function object is a wrapper around a C function. Examples of 805built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a 806standard built-in module). The number and type of the arguments are 807determined by the C function. Special read-only attributes: 808 809* :attr:`!__doc__` is the function's documentation string, or ``None`` if 810 unavailable. See :attr:`function.__doc__`. 811* :attr:`!__name__` is the function's name. See :attr:`function.__name__`. 812* :attr:`!__self__` is set to ``None`` (but see the next item). 813* :attr:`!__module__` is the name of 814 the module the function was defined in or ``None`` if unavailable. 815 See :attr:`function.__module__`. 816 817 818.. _builtin-methods: 819 820Built-in methods 821^^^^^^^^^^^^^^^^ 822 823.. index:: 824 pair: object; built-in method 825 pair: object; method 826 pair: built-in; method 827 828This is really a different disguise of a built-in function, this time containing 829an object passed to the C function as an implicit extra argument. An example of 830a built-in method is ``alist.append()``, assuming *alist* is a list object. In 831this case, the special read-only attribute :attr:`!__self__` is set to the object 832denoted by *alist*. (The attribute has the same semantics as it does with 833:attr:`other instance methods <method.__self__>`.) 834 835.. _classes: 836 837Classes 838^^^^^^^ 839 840Classes are callable. These objects normally act as factories for new 841instances of themselves, but variations are possible for class types that 842override :meth:`~object.__new__`. The arguments of the call are passed to 843:meth:`!__new__` and, in the typical case, to :meth:`~object.__init__` to 844initialize the new instance. 845 846 847Class Instances 848^^^^^^^^^^^^^^^ 849 850Instances of arbitrary classes can be made callable by defining a 851:meth:`~object.__call__` method in their class. 852 853 854.. _module-objects: 855 856Modules 857------- 858 859.. index:: 860 pair: statement; import 861 pair: object; module 862 863Modules are a basic organizational unit of Python code, and are created by 864the :ref:`import system <importsystem>` as invoked either by the 865:keyword:`import` statement, or by calling 866functions such as :func:`importlib.import_module` and built-in 867:func:`__import__`. A module object has a namespace implemented by a 868:class:`dictionary <dict>` object (this is the dictionary referenced by the 869:attr:`~function.__globals__` 870attribute of functions defined in the module). Attribute references are 871translated to lookups in this dictionary, e.g., ``m.x`` is equivalent to 872``m.__dict__["x"]``. A module object does not contain the code object used 873to initialize the module (since it isn't needed once the initialization is 874done). 875 876Attribute assignment updates the module's namespace dictionary, e.g., 877``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``. 878 879.. index:: 880 single: __name__ (module attribute) 881 single: __spec__ (module attribute) 882 single: __package__ (module attribute) 883 single: __loader__ (module attribute) 884 single: __path__ (module attribute) 885 single: __file__ (module attribute) 886 single: __cached__ (module attribute) 887 single: __doc__ (module attribute) 888 single: __annotations__ (module attribute) 889 pair: module; namespace 890 891.. _import-mod-attrs: 892 893Import-related attributes on module objects 894^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 895 896Module objects have the following attributes that relate to the 897:ref:`import system <importsystem>`. When a module is created using the machinery associated 898with the import system, these attributes are filled in based on the module's 899:term:`spec <module spec>`, before the :term:`loader` executes and loads the 900module. 901 902To create a module dynamically rather than using the import system, 903it's recommended to use :func:`importlib.util.module_from_spec`, 904which will set the various import-controlled attributes to appropriate values. 905It's also possible to use the :class:`types.ModuleType` constructor to create 906modules directly, but this technique is more error-prone, as most attributes 907must be manually set on the module object after it has been created when using 908this approach. 909 910.. caution:: 911 912 With the exception of :attr:`~module.__name__`, it is **strongly** 913 recommended that you rely on :attr:`~module.__spec__` and its attributes 914 instead of any of the other individual attributes listed in this subsection. 915 Note that updating an attribute on :attr:`!__spec__` will not update the 916 corresponding attribute on the module itself: 917 918 .. doctest:: 919 920 >>> import typing 921 >>> typing.__name__, typing.__spec__.name 922 ('typing', 'typing') 923 >>> typing.__spec__.name = 'spelling' 924 >>> typing.__name__, typing.__spec__.name 925 ('typing', 'spelling') 926 >>> typing.__name__ = 'keyboard_smashing' 927 >>> typing.__name__, typing.__spec__.name 928 ('keyboard_smashing', 'spelling') 929 930.. attribute:: module.__name__ 931 932 The name used to uniquely identify the module in the import system. 933 For a directly executed module, this will be set to ``"__main__"``. 934 935 This attribute must be set to the fully qualified name of the module. 936 It is expected to match the value of 937 :attr:`module.__spec__.name <importlib.machinery.ModuleSpec.name>`. 938 939.. attribute:: module.__spec__ 940 941 A record of the module's import-system-related state. 942 943 Set to the :class:`module spec <importlib.machinery.ModuleSpec>` that was 944 used when importing the module. See :ref:`module-specs` for more details. 945 946 .. versionadded:: 3.4 947 948.. attribute:: module.__package__ 949 950 The :term:`package` a module belongs to. 951 952 If the module is top-level (that is, not a part of any specific package) 953 then the attribute should be set to ``''`` (the empty string). Otherwise, 954 it should be set to the name of the module's package (which can be equal to 955 :attr:`module.__name__` if the module itself is a package). See :pep:`366` 956 for further details. 957 958 This attribute is used instead of :attr:`~module.__name__` to calculate 959 explicit relative imports for main modules. It defaults to ``None`` for 960 modules created dynamically using the :class:`types.ModuleType` constructor; 961 use :func:`importlib.util.module_from_spec` instead to ensure the attribute 962 is set to a :class:`str`. 963 964 It is **strongly** recommended that you use 965 :attr:`module.__spec__.parent <importlib.machinery.ModuleSpec.parent>` 966 instead of :attr:`!module.__package__`. :attr:`__package__` is now only used 967 as a fallback if :attr:`!__spec__.parent` is not set, and this fallback 968 path is deprecated. 969 970 .. versionchanged:: 3.4 971 This attribute now defaults to ``None`` for modules created dynamically 972 using the :class:`types.ModuleType` constructor. 973 Previously the attribute was optional. 974 975 .. versionchanged:: 3.6 976 The value of :attr:`!__package__` is expected to be the same as 977 :attr:`__spec__.parent <importlib.machinery.ModuleSpec.parent>`. 978 :attr:`__package__` is now only used as a fallback during import 979 resolution if :attr:`!__spec__.parent` is not defined. 980 981 .. versionchanged:: 3.10 982 :exc:`ImportWarning` is raised if an import resolution falls back to 983 :attr:`!__package__` instead of 984 :attr:`__spec__.parent <importlib.machinery.ModuleSpec.parent>`. 985 986 .. versionchanged:: 3.12 987 Raise :exc:`DeprecationWarning` instead of :exc:`ImportWarning` when 988 falling back to :attr:`!__package__` during import resolution. 989 990 .. deprecated-removed:: 3.13 3.15 991 :attr:`!__package__` will cease to be set or taken into consideration 992 by the import system or standard library. 993 994.. attribute:: module.__loader__ 995 996 The :term:`loader` object that the import machinery used to load the module. 997 998 This attribute is mostly useful for introspection, but can be used for 999 additional loader-specific functionality, for example getting data 1000 associated with a loader. 1001 1002 :attr:`!__loader__` defaults to ``None`` for modules created dynamically 1003 using the :class:`types.ModuleType` constructor; 1004 use :func:`importlib.util.module_from_spec` instead to ensure the attribute 1005 is set to a :term:`loader` object. 1006 1007 It is **strongly** recommended that you use 1008 :attr:`module.__spec__.loader <importlib.machinery.ModuleSpec.loader>` 1009 instead of :attr:`!module.__loader__`. 1010 1011 .. versionchanged:: 3.4 1012 This attribute now defaults to ``None`` for modules created dynamically 1013 using the :class:`types.ModuleType` constructor. 1014 Previously the attribute was optional. 1015 1016 .. deprecated-removed:: 3.12 3.16 1017 Setting :attr:`!__loader__` on a module while failing to set 1018 :attr:`!__spec__.loader` is deprecated. In Python 3.16, 1019 :attr:`!__loader__` will cease to be set or taken into consideration by 1020 the import system or the standard library. 1021 1022.. attribute:: module.__path__ 1023 1024 A (possibly empty) :term:`sequence` of strings enumerating the locations 1025 where the package's submodules will be found. Non-package modules should 1026 not have a :attr:`!__path__` attribute. See :ref:`package-path-rules` for 1027 more details. 1028 1029 It is **strongly** recommended that you use 1030 :attr:`module.__spec__.submodule_search_locations <importlib.machinery.ModuleSpec.submodule_search_locations>` 1031 instead of :attr:`!module.__path__`. 1032 1033.. attribute:: module.__file__ 1034.. attribute:: module.__cached__ 1035 1036 :attr:`!__file__` and :attr:`!__cached__` are both optional attributes that 1037 may or may not be set. Both attributes should be a :class:`str` when they 1038 are available. 1039 1040 :attr:`!__file__` indicates the pathname of the file from which the module 1041 was loaded (if loaded from a file), or the pathname of the shared library 1042 file for extension modules loaded dynamically from a shared library. 1043 It might be missing for certain types of modules, such as C modules that are 1044 statically linked into the interpreter, and the 1045 :ref:`import system <importsystem>` may opt to leave it unset if it 1046 has no semantic meaning (for example, a module loaded from a database). 1047 1048 If :attr:`!__file__` is set then the :attr:`!__cached__` attribute might 1049 also be set, which is the path to any compiled version of 1050 the code (for example, a byte-compiled file). The file does not need to exist 1051 to set this attribute; the path can simply point to where the 1052 compiled file *would* exist (see :pep:`3147`). 1053 1054 Note that :attr:`!__cached__` may be set even if :attr:`!__file__` is not 1055 set. However, that scenario is quite atypical. Ultimately, the 1056 :term:`loader` is what makes use of the module spec provided by the 1057 :term:`finder` (from which :attr:`!__file__` and :attr:`!__cached__` are 1058 derived). So if a loader can load from a cached module but otherwise does 1059 not load from a file, that atypical scenario may be appropriate. 1060 1061 It is **strongly** recommended that you use 1062 :attr:`module.__spec__.cached <importlib.machinery.ModuleSpec.cached>` 1063 instead of :attr:`!module.__cached__`. 1064 1065 .. deprecated-removed:: 3.13 3.15 1066 Setting :attr:`!__cached__` on a module while failing to set 1067 :attr:`!__spec__.cached` is deprecated. In Python 3.15, 1068 :attr:`!__cached__` will cease to be set or taken into consideration by 1069 the import system or standard library. 1070 1071Other writable attributes on module objects 1072^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1073 1074As well as the import-related attributes listed above, module objects also have 1075the following writable attributes: 1076 1077.. attribute:: module.__doc__ 1078 1079 The module's documentation string, or ``None`` if unavailable. 1080 See also: :attr:`__doc__ attributes <definition.__doc__>`. 1081 1082.. attribute:: module.__annotations__ 1083 1084 A dictionary containing 1085 :term:`variable annotations <variable annotation>` collected during module 1086 body execution. For best practices on working with :attr:`__annotations__`, 1087 please see :ref:`annotations-howto`. 1088 1089Module dictionaries 1090^^^^^^^^^^^^^^^^^^^ 1091 1092Module objects also have the following special read-only attribute: 1093 1094.. index:: single: __dict__ (module attribute) 1095.. attribute:: module.__dict__ 1096 1097 The module's namespace as a dictionary object. Uniquely among the attributes 1098 listed here, :attr:`!__dict__` cannot be accessed as a global variable from 1099 within a module; it can only be accessed as an attribute on module objects. 1100 1101 .. impl-detail:: 1102 1103 Because of the way CPython clears module dictionaries, the module 1104 dictionary will be cleared when the module falls out of scope even if the 1105 dictionary still has live references. To avoid this, copy the dictionary 1106 or keep the module around while using its dictionary directly. 1107 1108 1109.. _class-attrs-and-methods: 1110 1111Custom classes 1112-------------- 1113 1114Custom class types are typically created by class definitions (see section 1115:ref:`class`). A class has a namespace implemented by a dictionary object. 1116Class attribute references are translated to lookups in this dictionary, e.g., 1117``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of 1118hooks which allow for other means of locating attributes). When the attribute 1119name is not found there, the attribute search continues in the base classes. 1120This search of the base classes uses the C3 method resolution order which 1121behaves correctly even in the presence of 'diamond' inheritance structures 1122where there are multiple inheritance paths leading back to a common ancestor. 1123Additional details on the C3 MRO used by Python can be found at 1124:ref:`python_2.3_mro`. 1125 1126.. index:: 1127 pair: object; class 1128 pair: object; class instance 1129 pair: object; instance 1130 pair: class object; call 1131 single: container 1132 pair: object; dictionary 1133 pair: class; attribute 1134 1135When a class attribute reference (for class :class:`!C`, say) would yield a 1136class method object, it is transformed into an instance method object whose 1137:attr:`~method.__self__` attribute is :class:`!C`. 1138When it would yield a :class:`staticmethod` object, 1139it is transformed into the object wrapped by the static method 1140object. See section :ref:`descriptors` for another way in which attributes 1141retrieved from a class may differ from those actually contained in its 1142:attr:`~object.__dict__`. 1143 1144.. index:: triple: class; attribute; assignment 1145 1146Class attribute assignments update the class's dictionary, never the dictionary 1147of a base class. 1148 1149.. index:: pair: class object; call 1150 1151A class object can be called (see above) to yield a class instance (see below). 1152 1153Special attributes 1154^^^^^^^^^^^^^^^^^^ 1155 1156.. index:: 1157 single: __name__ (class attribute) 1158 single: __module__ (class attribute) 1159 single: __dict__ (class attribute) 1160 single: __bases__ (class attribute) 1161 single: __doc__ (class attribute) 1162 single: __annotations__ (class attribute) 1163 single: __type_params__ (class attribute) 1164 single: __static_attributes__ (class attribute) 1165 single: __firstlineno__ (class attribute) 1166 1167.. list-table:: 1168 :header-rows: 1 1169 1170 * - Attribute 1171 - Meaning 1172 1173 * - .. attribute:: type.__name__ 1174 - The class's name. 1175 See also: :attr:`__name__ attributes <definition.__name__>`. 1176 1177 * - .. attribute:: type.__qualname__ 1178 - The class's :term:`qualified name`. 1179 See also: :attr:`__qualname__ attributes <definition.__qualname__>`. 1180 1181 * - .. attribute:: type.__module__ 1182 - The name of the module in which the class was defined. 1183 1184 * - .. attribute:: type.__dict__ 1185 - A :class:`mapping proxy <types.MappingProxyType>` 1186 providing a read-only view of the class's namespace. 1187 See also: :attr:`__dict__ attributes <object.__dict__>`. 1188 1189 * - .. attribute:: type.__bases__ 1190 - A :class:`tuple` containing the class's bases. 1191 In most cases, for a class defined as ``class X(A, B, C)``, 1192 ``X.__bases__`` will be exactly equal to ``(A, B, C)``. 1193 1194 * - .. attribute:: type.__doc__ 1195 - The class's documentation string, or ``None`` if undefined. 1196 Not inherited by subclasses. 1197 1198 * - .. attribute:: type.__annotations__ 1199 - A dictionary containing 1200 :term:`variable annotations <variable annotation>` 1201 collected during class body execution. For best practices on working 1202 with :attr:`!__annotations__`, please see :ref:`annotations-howto`. 1203 1204 .. caution:: 1205 1206 Accessing the :attr:`!__annotations__` attribute of a class 1207 object directly may yield incorrect results in the presence of 1208 metaclasses. In addition, the attribute may not exist for 1209 some classes. Use :func:`inspect.get_annotations` to 1210 retrieve class annotations safely. 1211 1212 * - .. attribute:: type.__type_params__ 1213 - A :class:`tuple` containing the :ref:`type parameters <type-params>` of 1214 a :ref:`generic class <generic-classes>`. 1215 1216 .. versionadded:: 3.12 1217 1218 * - .. attribute:: type.__static_attributes__ 1219 - A :class:`tuple` containing names of attributes of this class which are 1220 assigned through ``self.X`` from any function in its body. 1221 1222 .. versionadded:: 3.13 1223 1224 * - .. attribute:: type.__firstlineno__ 1225 - The line number of the first line of the class definition, 1226 including decorators. 1227 Setting the :attr:`__module__` attribute removes the 1228 :attr:`!__firstlineno__` item from the type's dictionary. 1229 1230 .. versionadded:: 3.13 1231 1232 * - .. attribute:: type.__mro__ 1233 - The :class:`tuple` of classes that are considered when looking for 1234 base classes during method resolution. 1235 1236 1237Special methods 1238^^^^^^^^^^^^^^^ 1239 1240In addition to the special attributes described above, all Python classes also 1241have the following two methods available: 1242 1243.. method:: type.mro 1244 1245 This method can be overridden by a metaclass to customize the method 1246 resolution order for its instances. It is called at class instantiation, 1247 and its result is stored in :attr:`~type.__mro__`. 1248 1249.. method:: type.__subclasses__ 1250 1251 Each class keeps a list of weak references to its immediate subclasses. This 1252 method returns a list of all those references still alive. The list is in 1253 definition order. Example: 1254 1255 .. doctest:: 1256 1257 >>> class A: pass 1258 >>> class B(A): pass 1259 >>> A.__subclasses__() 1260 [<class 'B'>] 1261 1262Class instances 1263--------------- 1264 1265.. index:: 1266 pair: object; class instance 1267 pair: object; instance 1268 pair: class; instance 1269 pair: class instance; attribute 1270 1271A class instance is created by calling a class object (see above). A class 1272instance has a namespace implemented as a dictionary which is the first place 1273in which attribute references are searched. When an attribute is not found 1274there, and the instance's class has an attribute by that name, the search 1275continues with the class attributes. If a class attribute is found that is a 1276user-defined function object, it is transformed into an instance method 1277object whose :attr:`~method.__self__` attribute is the instance. Static method and 1278class method objects are also transformed; see above under "Classes". See 1279section :ref:`descriptors` for another way in which attributes of a class 1280retrieved via its instances may differ from the objects actually stored in 1281the class's :attr:`~object.__dict__`. If no class attribute is found, and the 1282object's class has a :meth:`~object.__getattr__` method, that is called to satisfy 1283the lookup. 1284 1285.. index:: triple: class instance; attribute; assignment 1286 1287Attribute assignments and deletions update the instance's dictionary, never a 1288class's dictionary. If the class has a :meth:`~object.__setattr__` or 1289:meth:`~object.__delattr__` method, this is called instead of updating the instance 1290dictionary directly. 1291 1292.. index:: 1293 pair: object; numeric 1294 pair: object; sequence 1295 pair: object; mapping 1296 1297Class instances can pretend to be numbers, sequences, or mappings if they have 1298methods with certain special names. See section :ref:`specialnames`. 1299 1300Special attributes 1301^^^^^^^^^^^^^^^^^^ 1302 1303.. index:: 1304 single: __dict__ (instance attribute) 1305 single: __class__ (instance attribute) 1306 1307.. attribute:: object.__class__ 1308 1309 The class to which a class instance belongs. 1310 1311.. attribute:: object.__dict__ 1312 1313 A dictionary or other mapping object used to store an object's (writable) 1314 attributes. Not all instances have a :attr:`!__dict__` attribute; see the 1315 section on :ref:`slots` for more details. 1316 1317 1318I/O objects (also known as file objects) 1319---------------------------------------- 1320 1321.. index:: 1322 pair: built-in function; open 1323 pair: module; io 1324 single: popen() (in module os) 1325 single: makefile() (socket method) 1326 single: sys.stdin 1327 single: sys.stdout 1328 single: sys.stderr 1329 single: stdio 1330 single: stdin (in module sys) 1331 single: stdout (in module sys) 1332 single: stderr (in module sys) 1333 1334A :term:`file object` represents an open file. Various shortcuts are 1335available to create file objects: the :func:`open` built-in function, and 1336also :func:`os.popen`, :func:`os.fdopen`, and the 1337:meth:`~socket.socket.makefile` method of socket objects (and perhaps by 1338other functions or methods provided by extension modules). 1339 1340The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are 1341initialized to file objects corresponding to the interpreter's standard 1342input, output and error streams; they are all open in text mode and 1343therefore follow the interface defined by the :class:`io.TextIOBase` 1344abstract class. 1345 1346 1347Internal types 1348-------------- 1349 1350.. index:: 1351 single: internal type 1352 single: types, internal 1353 1354A few types used internally by the interpreter are exposed to the user. Their 1355definitions may change with future versions of the interpreter, but they are 1356mentioned here for completeness. 1357 1358 1359.. _code-objects: 1360 1361Code objects 1362^^^^^^^^^^^^ 1363 1364.. index:: bytecode, object; code, code object 1365 1366Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`. 1367The difference between a code object and a function object is that the function 1368object contains an explicit reference to the function's globals (the module in 1369which it was defined), while a code object contains no context; also the default 1370argument values are stored in the function object, not in the code object 1371(because they represent values calculated at run-time). Unlike function 1372objects, code objects are immutable and contain no references (directly or 1373indirectly) to mutable objects. 1374 1375.. index:: 1376 single: co_argcount (code object attribute) 1377 single: co_posonlyargcount (code object attribute) 1378 single: co_kwonlyargcount (code object attribute) 1379 single: co_code (code object attribute) 1380 single: co_consts (code object attribute) 1381 single: co_filename (code object attribute) 1382 single: co_firstlineno (code object attribute) 1383 single: co_flags (code object attribute) 1384 single: co_lnotab (code object attribute) 1385 single: co_name (code object attribute) 1386 single: co_names (code object attribute) 1387 single: co_nlocals (code object attribute) 1388 single: co_stacksize (code object attribute) 1389 single: co_varnames (code object attribute) 1390 single: co_cellvars (code object attribute) 1391 single: co_freevars (code object attribute) 1392 single: co_qualname (code object attribute) 1393 1394Special read-only attributes 1395~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1396 1397.. list-table:: 1398 1399 * - .. attribute:: codeobject.co_name 1400 - The function name 1401 1402 * - .. attribute:: codeobject.co_qualname 1403 - The fully qualified function name 1404 1405 .. versionadded:: 3.11 1406 1407 * - .. attribute:: codeobject.co_argcount 1408 - The total number of positional :term:`parameters <parameter>` 1409 (including positional-only parameters and parameters with default values) 1410 that the function has 1411 1412 * - .. attribute:: codeobject.co_posonlyargcount 1413 - The number of positional-only :term:`parameters <parameter>` 1414 (including arguments with default values) that the function has 1415 1416 * - .. attribute:: codeobject.co_kwonlyargcount 1417 - The number of keyword-only :term:`parameters <parameter>` 1418 (including arguments with default values) that the function has 1419 1420 * - .. attribute:: codeobject.co_nlocals 1421 - The number of :ref:`local variables <naming>` used by the function 1422 (including parameters) 1423 1424 * - .. attribute:: codeobject.co_varnames 1425 - A :class:`tuple` containing the names of the local variables in the 1426 function (starting with the parameter names) 1427 1428 * - .. attribute:: codeobject.co_cellvars 1429 - A :class:`tuple` containing the names of :ref:`local variables <naming>` 1430 that are referenced from at least one :term:`nested scope` inside the function 1431 1432 * - .. attribute:: codeobject.co_freevars 1433 - A :class:`tuple` containing the names of 1434 :term:`free (closure) variables <closure variable>` that a :term:`nested scope` 1435 references in an outer scope. See also :attr:`function.__closure__`. 1436 1437 Note: references to global and builtin names are *not* included. 1438 1439 * - .. attribute:: codeobject.co_code 1440 - A string representing the sequence of :term:`bytecode` instructions in 1441 the function 1442 1443 * - .. attribute:: codeobject.co_consts 1444 - A :class:`tuple` containing the literals used by the :term:`bytecode` in 1445 the function 1446 1447 * - .. attribute:: codeobject.co_names 1448 - A :class:`tuple` containing the names used by the :term:`bytecode` in 1449 the function 1450 1451 * - .. attribute:: codeobject.co_filename 1452 - The name of the file from which the code was compiled 1453 1454 * - .. attribute:: codeobject.co_firstlineno 1455 - The line number of the first line of the function 1456 1457 * - .. attribute:: codeobject.co_lnotab 1458 - A string encoding the mapping from :term:`bytecode` offsets to line 1459 numbers. For details, see the source code of the interpreter. 1460 1461 .. deprecated:: 3.12 1462 This attribute of code objects is deprecated, and may be removed in 1463 Python 3.15. 1464 1465 * - .. attribute:: codeobject.co_stacksize 1466 - The required stack size of the code object 1467 1468 * - .. attribute:: codeobject.co_flags 1469 - An :class:`integer <int>` encoding a number of flags for the 1470 interpreter. 1471 1472.. index:: pair: object; generator 1473 1474The following flag bits are defined for :attr:`~codeobject.co_flags`: 1475bit ``0x04`` is set if 1476the function uses the ``*arguments`` syntax to accept an arbitrary number of 1477positional arguments; bit ``0x08`` is set if the function uses the 1478``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set 1479if the function is a generator. See :ref:`inspect-module-co-flags` for details 1480on the semantics of each flags that might be present. 1481 1482Future feature declarations (``from __future__ import division``) also use bits 1483in :attr:`~codeobject.co_flags` to indicate whether a code object was compiled with a 1484particular feature enabled: bit ``0x2000`` is set if the function was compiled 1485with future division enabled; bits ``0x10`` and ``0x1000`` were used in earlier 1486versions of Python. 1487 1488Other bits in :attr:`~codeobject.co_flags` are reserved for internal use. 1489 1490.. index:: single: documentation string 1491 1492If a code object represents a function, the first item in 1493:attr:`~codeobject.co_consts` is 1494the documentation string of the function, or ``None`` if undefined. 1495 1496Methods on code objects 1497~~~~~~~~~~~~~~~~~~~~~~~ 1498 1499.. method:: codeobject.co_positions() 1500 1501 Returns an iterable over the source code positions of each :term:`bytecode` 1502 instruction in the code object. 1503 1504 The iterator returns :class:`tuple`\s containing the ``(start_line, end_line, 1505 start_column, end_column)``. The *i-th* tuple corresponds to the 1506 position of the source code that compiled to the *i-th* code unit. 1507 Column information is 0-indexed utf-8 byte offsets on the given source 1508 line. 1509 1510 This positional information can be missing. A non-exhaustive lists of 1511 cases where this may happen: 1512 1513 - Running the interpreter with :option:`-X` ``no_debug_ranges``. 1514 - Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``. 1515 - Position tuples corresponding to artificial instructions. 1516 - Line and column numbers that can't be represented due to 1517 implementation specific limitations. 1518 1519 When this occurs, some or all of the tuple elements can be 1520 :const:`None`. 1521 1522 .. versionadded:: 3.11 1523 1524 .. note:: 1525 This feature requires storing column positions in code objects which may 1526 result in a small increase of disk usage of compiled Python files or 1527 interpreter memory usage. To avoid storing the extra information and/or 1528 deactivate printing the extra traceback information, the 1529 :option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES` 1530 environment variable can be used. 1531 1532.. method:: codeobject.co_lines() 1533 1534 Returns an iterator that yields information about successive ranges of 1535 :term:`bytecode`\s. Each item yielded is a ``(start, end, lineno)`` 1536 :class:`tuple`: 1537 1538 * ``start`` (an :class:`int`) represents the offset (inclusive) of the start 1539 of the :term:`bytecode` range 1540 * ``end`` (an :class:`int`) represents the offset (exclusive) of the end of 1541 the :term:`bytecode` range 1542 * ``lineno`` is an :class:`int` representing the line number of the 1543 :term:`bytecode` range, or ``None`` if the bytecodes in the given range 1544 have no line number 1545 1546 The items yielded will have the following properties: 1547 1548 * The first range yielded will have a ``start`` of 0. 1549 * The ``(start, end)`` ranges will be non-decreasing and consecutive. That 1550 is, for any pair of :class:`tuple`\s, the ``start`` of the second will be 1551 equal to the ``end`` of the first. 1552 * No range will be backwards: ``end >= start`` for all triples. 1553 * The last :class:`tuple` yielded will have ``end`` equal to the size of the 1554 :term:`bytecode`. 1555 1556 Zero-width ranges, where ``start == end``, are allowed. Zero-width ranges 1557 are used for lines that are present in the source code, but have been 1558 eliminated by the :term:`bytecode` compiler. 1559 1560 .. versionadded:: 3.10 1561 1562 .. seealso:: 1563 1564 :pep:`626` - Precise line numbers for debugging and other tools. 1565 The PEP that introduced the :meth:`!co_lines` method. 1566 1567.. method:: codeobject.replace(**kwargs) 1568 1569 Return a copy of the code object with new values for the specified fields. 1570 1571 Code objects are also supported by the generic function :func:`copy.replace`. 1572 1573 .. versionadded:: 3.8 1574 1575 1576.. _frame-objects: 1577 1578Frame objects 1579^^^^^^^^^^^^^ 1580 1581.. index:: pair: object; frame 1582 1583Frame objects represent execution frames. They may occur in 1584:ref:`traceback objects <traceback-objects>`, 1585and are also passed to registered trace functions. 1586 1587.. index:: 1588 single: f_back (frame attribute) 1589 single: f_code (frame attribute) 1590 single: f_globals (frame attribute) 1591 single: f_locals (frame attribute) 1592 single: f_lasti (frame attribute) 1593 single: f_builtins (frame attribute) 1594 1595Special read-only attributes 1596~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1597 1598.. list-table:: 1599 1600 * - .. attribute:: frame.f_back 1601 - Points to the previous stack frame (towards the caller), 1602 or ``None`` if this is the bottom stack frame 1603 1604 * - .. attribute:: frame.f_code 1605 - The :ref:`code object <code-objects>` being executed in this frame. 1606 Accessing this attribute raises an :ref:`auditing event <auditing>` 1607 ``object.__getattr__`` with arguments ``obj`` and ``"f_code"``. 1608 1609 * - .. attribute:: frame.f_locals 1610 - The mapping used by the frame to look up 1611 :ref:`local variables <naming>`. 1612 If the frame refers to an :term:`optimized scope`, 1613 this may return a write-through proxy object. 1614 1615 .. versionchanged:: 3.13 1616 Return a proxy for optimized scopes. 1617 1618 * - .. attribute:: frame.f_globals 1619 - The dictionary used by the frame to look up 1620 :ref:`global variables <naming>` 1621 1622 * - .. attribute:: frame.f_builtins 1623 - The dictionary used by the frame to look up 1624 :ref:`built-in (intrinsic) names <naming>` 1625 1626 * - .. attribute:: frame.f_lasti 1627 - The "precise instruction" of the frame object 1628 (this is an index into the :term:`bytecode` string of the 1629 :ref:`code object <code-objects>`) 1630 1631.. index:: 1632 single: f_trace (frame attribute) 1633 single: f_trace_lines (frame attribute) 1634 single: f_trace_opcodes (frame attribute) 1635 single: f_lineno (frame attribute) 1636 1637Special writable attributes 1638~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1639 1640.. list-table:: 1641 1642 * - .. attribute:: frame.f_trace 1643 - If not ``None``, this is a function called for various events during 1644 code execution (this is used by debuggers). Normally an event is 1645 triggered for each new source line (see :attr:`~frame.f_trace_lines`). 1646 1647 * - .. attribute:: frame.f_trace_lines 1648 - Set this attribute to :const:`False` to disable triggering a tracing 1649 event for each source line. 1650 1651 * - .. attribute:: frame.f_trace_opcodes 1652 - Set this attribute to :const:`True` to allow per-opcode events to be 1653 requested. Note that this may lead to 1654 undefined interpreter behaviour if exceptions raised by the trace 1655 function escape to the function being traced. 1656 1657 * - .. attribute:: frame.f_lineno 1658 - The current line number of the frame -- writing to this 1659 from within a trace function jumps to the given line (only for the bottom-most 1660 frame). A debugger can implement a Jump command (aka Set Next Statement) 1661 by writing to this attribute. 1662 1663Frame object methods 1664~~~~~~~~~~~~~~~~~~~~ 1665 1666Frame objects support one method: 1667 1668.. method:: frame.clear() 1669 1670 This method clears all references to :ref:`local variables <naming>` held by the 1671 frame. Also, if the frame belonged to a :term:`generator`, the generator 1672 is finalized. This helps break reference cycles involving frame 1673 objects (for example when catching an :ref:`exception <bltin-exceptions>` 1674 and storing its :ref:`traceback <traceback-objects>` for later use). 1675 1676 :exc:`RuntimeError` is raised if the frame is currently executing 1677 or suspended. 1678 1679 .. versionadded:: 3.4 1680 1681 .. versionchanged:: 3.13 1682 Attempting to clear a suspended frame raises :exc:`RuntimeError` 1683 (as has always been the case for executing frames). 1684 1685 1686.. _traceback-objects: 1687 1688Traceback objects 1689^^^^^^^^^^^^^^^^^ 1690 1691.. index:: 1692 pair: object; traceback 1693 pair: stack; trace 1694 pair: exception; handler 1695 pair: execution; stack 1696 single: exc_info (in module sys) 1697 single: last_traceback (in module sys) 1698 single: sys.exc_info 1699 single: sys.exception 1700 single: sys.last_traceback 1701 1702Traceback objects represent the stack trace of an :ref:`exception <tut-errors>`. 1703A traceback object 1704is implicitly created when an exception occurs, and may also be explicitly 1705created by calling :class:`types.TracebackType`. 1706 1707.. versionchanged:: 3.7 1708 Traceback objects can now be explicitly instantiated from Python code. 1709 1710For implicitly created tracebacks, when the search for an exception handler 1711unwinds the execution stack, at each unwound level a traceback object is 1712inserted in front of the current traceback. When an exception handler is 1713entered, the stack trace is made available to the program. (See section 1714:ref:`try`.) It is accessible as the third item of the 1715tuple returned by :func:`sys.exc_info`, and as the 1716:attr:`~BaseException.__traceback__` attribute 1717of the caught exception. 1718 1719When the program contains no suitable 1720handler, the stack trace is written (nicely formatted) to the standard error 1721stream; if the interpreter is interactive, it is also made available to the user 1722as :data:`sys.last_traceback`. 1723 1724For explicitly created tracebacks, it is up to the creator of the traceback 1725to determine how the :attr:`~traceback.tb_next` attributes should be linked to 1726form a full stack trace. 1727 1728.. index:: 1729 single: tb_frame (traceback attribute) 1730 single: tb_lineno (traceback attribute) 1731 single: tb_lasti (traceback attribute) 1732 pair: statement; try 1733 1734Special read-only attributes: 1735 1736.. list-table:: 1737 1738 * - .. attribute:: traceback.tb_frame 1739 - Points to the execution :ref:`frame <frame-objects>` of the current 1740 level. 1741 1742 Accessing this attribute raises an 1743 :ref:`auditing event <auditing>` ``object.__getattr__`` with arguments 1744 ``obj`` and ``"tb_frame"``. 1745 1746 * - .. attribute:: traceback.tb_lineno 1747 - Gives the line number where the exception occurred 1748 1749 * - .. attribute:: traceback.tb_lasti 1750 - Indicates the "precise instruction". 1751 1752The line number and last instruction in the traceback may differ from the 1753line number of its :ref:`frame object <frame-objects>` if the exception 1754occurred in a 1755:keyword:`try` statement with no matching except clause or with a 1756:keyword:`finally` clause. 1757 1758.. index:: 1759 single: tb_next (traceback attribute) 1760 1761.. attribute:: traceback.tb_next 1762 1763 The special writable attribute :attr:`!tb_next` is the next level in the 1764 stack trace (towards the frame where the exception occurred), or ``None`` if 1765 there is no next level. 1766 1767 .. versionchanged:: 3.7 1768 This attribute is now writable 1769 1770 1771Slice objects 1772^^^^^^^^^^^^^ 1773 1774.. index:: pair: built-in function; slice 1775 1776Slice objects are used to represent slices for 1777:meth:`~object.__getitem__` 1778methods. They are also created by the built-in :func:`slice` function. 1779 1780.. index:: 1781 single: start (slice object attribute) 1782 single: stop (slice object attribute) 1783 single: step (slice object attribute) 1784 1785Special read-only attributes: :attr:`~slice.start` is the lower bound; 1786:attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step 1787value; each is ``None`` if omitted. These attributes can have any type. 1788 1789Slice objects support one method: 1790 1791.. method:: slice.indices(self, length) 1792 1793 This method takes a single integer argument *length* and computes 1794 information about the slice that the slice object would describe if 1795 applied to a sequence of *length* items. It returns a tuple of three 1796 integers; respectively these are the *start* and *stop* indices and the 1797 *step* or stride length of the slice. Missing or out-of-bounds indices 1798 are handled in a manner consistent with regular slices. 1799 1800 1801Static method objects 1802^^^^^^^^^^^^^^^^^^^^^ 1803 1804Static method objects provide a way of defeating the transformation of function 1805objects to method objects described above. A static method object is a wrapper 1806around any other object, usually a user-defined method object. When a static 1807method object is retrieved from a class or a class instance, the object actually 1808returned is the wrapped object, which is not subject to any further 1809transformation. Static method objects are also callable. Static method 1810objects are created by the built-in :func:`staticmethod` constructor. 1811 1812 1813Class method objects 1814^^^^^^^^^^^^^^^^^^^^ 1815 1816A class method object, like a static method object, is a wrapper around another 1817object that alters the way in which that object is retrieved from classes and 1818class instances. The behaviour of class method objects upon such retrieval is 1819described above, under :ref:`"instance methods" <instance-methods>`. Class method objects are created 1820by the built-in :func:`classmethod` constructor. 1821 1822 1823.. _specialnames: 1824 1825Special method names 1826==================== 1827 1828.. index:: 1829 pair: operator; overloading 1830 single: __getitem__() (mapping object method) 1831 1832A class can implement certain operations that are invoked by special syntax 1833(such as arithmetic operations or subscripting and slicing) by defining methods 1834with special names. This is Python's approach to :dfn:`operator overloading`, 1835allowing classes to define their own behavior with respect to language 1836operators. For instance, if a class defines a method named 1837:meth:`~object.__getitem__`, 1838and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent 1839to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an 1840operation raise an exception when no appropriate method is defined (typically 1841:exc:`AttributeError` or :exc:`TypeError`). 1842 1843Setting a special method to ``None`` indicates that the corresponding 1844operation is not available. For example, if a class sets 1845:meth:`~object.__iter__` to ``None``, the class is not iterable, so calling 1846:func:`iter` on its instances will raise a :exc:`TypeError` (without 1847falling back to :meth:`~object.__getitem__`). [#]_ 1848 1849When implementing a class that emulates any built-in type, it is important that 1850the emulation only be implemented to the degree that it makes sense for the 1851object being modelled. For example, some sequences may work well with retrieval 1852of individual elements, but extracting a slice may not make sense. (One example 1853of this is the :class:`~xml.dom.NodeList` interface in the W3C's Document 1854Object Model.) 1855 1856 1857.. _customization: 1858 1859Basic customization 1860------------------- 1861 1862.. method:: object.__new__(cls[, ...]) 1863 1864 .. index:: pair: subclassing; immutable types 1865 1866 Called to create a new instance of class *cls*. :meth:`__new__` is a static 1867 method (special-cased so you need not declare it as such) that takes the class 1868 of which an instance was requested as its first argument. The remaining 1869 arguments are those passed to the object constructor expression (the call to the 1870 class). The return value of :meth:`__new__` should be the new object instance 1871 (usually an instance of *cls*). 1872 1873 Typical implementations create a new instance of the class by invoking the 1874 superclass's :meth:`__new__` method using ``super().__new__(cls[, ...])`` 1875 with appropriate arguments and then modifying the newly created instance 1876 as necessary before returning it. 1877 1878 If :meth:`__new__` is invoked during object construction and it returns an 1879 instance of *cls*, then the new instance’s :meth:`__init__` method 1880 will be invoked like ``__init__(self[, ...])``, where *self* is the new instance 1881 and the remaining arguments are the same as were passed to the object constructor. 1882 1883 If :meth:`__new__` does not return an instance of *cls*, then the new instance's 1884 :meth:`__init__` method will not be invoked. 1885 1886 :meth:`__new__` is intended mainly to allow subclasses of immutable types (like 1887 int, str, or tuple) to customize instance creation. It is also commonly 1888 overridden in custom metaclasses in order to customize class creation. 1889 1890 1891.. method:: object.__init__(self[, ...]) 1892 1893 .. index:: pair: class; constructor 1894 1895 Called after the instance has been created (by :meth:`__new__`), but before 1896 it is returned to the caller. The arguments are those passed to the 1897 class constructor expression. If a base class has an :meth:`__init__` 1898 method, the derived class's :meth:`__init__` method, if any, must explicitly 1899 call it to ensure proper initialization of the base class part of the 1900 instance; for example: ``super().__init__([args...])``. 1901 1902 Because :meth:`__new__` and :meth:`__init__` work together in constructing 1903 objects (:meth:`__new__` to create it, and :meth:`__init__` to customize it), 1904 no non-``None`` value may be returned by :meth:`__init__`; doing so will 1905 cause a :exc:`TypeError` to be raised at runtime. 1906 1907 1908.. method:: object.__del__(self) 1909 1910 .. index:: 1911 single: destructor 1912 single: finalizer 1913 pair: statement; del 1914 1915 Called when the instance is about to be destroyed. This is also called a 1916 finalizer or (improperly) a destructor. If a base class has a 1917 :meth:`__del__` method, the derived class's :meth:`__del__` method, 1918 if any, must explicitly call it to ensure proper deletion of the base 1919 class part of the instance. 1920 1921 It is possible (though not recommended!) for the :meth:`__del__` method 1922 to postpone destruction of the instance by creating a new reference to 1923 it. This is called object *resurrection*. It is implementation-dependent 1924 whether :meth:`__del__` is called a second time when a resurrected object 1925 is about to be destroyed; the current :term:`CPython` implementation 1926 only calls it once. 1927 1928 It is not guaranteed that :meth:`__del__` methods are called for objects 1929 that still exist when the interpreter exits. 1930 :class:`weakref.finalize` provides a straightforward way to register 1931 a cleanup function to be called when an object is garbage collected. 1932 1933 .. note:: 1934 1935 ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements 1936 the reference count for ``x`` by one, and the latter is only called when 1937 ``x``'s reference count reaches zero. 1938 1939 .. impl-detail:: 1940 It is possible for a reference cycle to prevent the reference count 1941 of an object from going to zero. In this case, the cycle will be 1942 later detected and deleted by the :term:`cyclic garbage collector 1943 <garbage collection>`. A common cause of reference cycles is when 1944 an exception has been caught in a local variable. The frame's 1945 locals then reference the exception, which references its own 1946 traceback, which references the locals of all frames caught in the 1947 traceback. 1948 1949 .. seealso:: 1950 Documentation for the :mod:`gc` module. 1951 1952 .. warning:: 1953 1954 Due to the precarious circumstances under which :meth:`__del__` methods are 1955 invoked, exceptions that occur during their execution are ignored, and a warning 1956 is printed to ``sys.stderr`` instead. In particular: 1957 1958 * :meth:`__del__` can be invoked when arbitrary code is being executed, 1959 including from any arbitrary thread. If :meth:`__del__` needs to take 1960 a lock or invoke any other blocking resource, it may deadlock as 1961 the resource may already be taken by the code that gets interrupted 1962 to execute :meth:`__del__`. 1963 1964 * :meth:`__del__` can be executed during interpreter shutdown. As a 1965 consequence, the global variables it needs to access (including other 1966 modules) may already have been deleted or set to ``None``. Python 1967 guarantees that globals whose name begins with a single underscore 1968 are deleted from their module before other globals are deleted; if 1969 no other references to such globals exist, this may help in assuring 1970 that imported modules are still available at the time when the 1971 :meth:`__del__` method is called. 1972 1973 1974 .. index:: 1975 single: repr() (built-in function); __repr__() (object method) 1976 1977.. method:: object.__repr__(self) 1978 1979 Called by the :func:`repr` built-in function to compute the "official" string 1980 representation of an object. If at all possible, this should look like a 1981 valid Python expression that could be used to recreate an object with the 1982 same value (given an appropriate environment). If this is not possible, a 1983 string of the form ``<...some useful description...>`` should be returned. 1984 The return value must be a string object. If a class defines :meth:`__repr__` 1985 but not :meth:`__str__`, then :meth:`__repr__` is also used when an 1986 "informal" string representation of instances of that class is required. 1987 1988 This is typically used for debugging, so it is important that the representation 1989 is information-rich and unambiguous. A default implementation is provided by the 1990 :class:`object` class itself. 1991 1992 .. index:: 1993 single: string; __str__() (object method) 1994 single: format() (built-in function); __str__() (object method) 1995 single: print() (built-in function); __str__() (object method) 1996 1997 1998.. method:: object.__str__(self) 1999 2000 Called by :func:`str(object) <str>`, the default :meth:`__format__` implementation, 2001 and the built-in function :func:`print`, to compute the "informal" or nicely 2002 printable string representation of an object. The return value must be a 2003 :ref:`str <textseq>` object. 2004 2005 This method differs from :meth:`object.__repr__` in that there is no 2006 expectation that :meth:`__str__` return a valid Python expression: a more 2007 convenient or concise representation can be used. 2008 2009 The default implementation defined by the built-in type :class:`object` 2010 calls :meth:`object.__repr__`. 2011 2012 .. XXX what about subclasses of string? 2013 2014 2015.. method:: object.__bytes__(self) 2016 2017 .. index:: pair: built-in function; bytes 2018 2019 Called by :ref:`bytes <func-bytes>` to compute a byte-string representation 2020 of an object. This should return a :class:`bytes` object. The :class:`object` 2021 class itself does not provide this method. 2022 2023 .. index:: 2024 single: string; __format__() (object method) 2025 pair: string; conversion 2026 pair: built-in function; print 2027 2028 2029.. method:: object.__format__(self, format_spec) 2030 2031 Called by the :func:`format` built-in function, 2032 and by extension, evaluation of :ref:`formatted string literals 2033 <f-strings>` and the :meth:`str.format` method, to produce a "formatted" 2034 string representation of an object. The *format_spec* argument is 2035 a string that contains a description of the formatting options desired. 2036 The interpretation of the *format_spec* argument is up to the type 2037 implementing :meth:`__format__`, however most classes will either 2038 delegate formatting to one of the built-in types, or use a similar 2039 formatting option syntax. 2040 2041 See :ref:`formatspec` for a description of the standard formatting syntax. 2042 2043 The return value must be a string object. 2044 2045 The default implementation by the :class:`object` class should be given 2046 an empty *format_spec* string. It delegates to :meth:`__str__`. 2047 2048 .. versionchanged:: 3.4 2049 The __format__ method of ``object`` itself raises a :exc:`TypeError` 2050 if passed any non-empty string. 2051 2052 .. versionchanged:: 3.7 2053 ``object.__format__(x, '')`` is now equivalent to ``str(x)`` rather 2054 than ``format(str(x), '')``. 2055 2056 2057.. _richcmpfuncs: 2058.. method:: object.__lt__(self, other) 2059 object.__le__(self, other) 2060 object.__eq__(self, other) 2061 object.__ne__(self, other) 2062 object.__gt__(self, other) 2063 object.__ge__(self, other) 2064 2065 .. index:: 2066 single: comparisons 2067 2068 These are the so-called "rich comparison" methods. The correspondence between 2069 operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``, 2070 ``x<=y`` calls ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls 2071 ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls 2072 ``x.__ge__(y)``. 2073 2074 A rich comparison method may return the singleton :data:`NotImplemented` if it does 2075 not implement the operation for a given pair of arguments. By convention, 2076 ``False`` and ``True`` are returned for a successful comparison. However, these 2077 methods can return any value, so if the comparison operator is used in a Boolean 2078 context (e.g., in the condition of an ``if`` statement), Python will call 2079 :func:`bool` on the value to determine if the result is true or false. 2080 2081 By default, ``object`` implements :meth:`__eq__` by using ``is``, returning 2082 :data:`NotImplemented` in the case of a false comparison: 2083 ``True if x is y else NotImplemented``. For :meth:`__ne__`, by default it 2084 delegates to :meth:`__eq__` and inverts the result unless it is 2085 :data:`!NotImplemented`. There are no other implied relationships among the 2086 comparison operators or default implementations; for example, the truth of 2087 ``(x<y or x==y)`` does not imply ``x<=y``. To automatically generate ordering 2088 operations from a single root operation, see :func:`functools.total_ordering`. 2089 2090 By default, the :class:`object` class provides implementations consistent 2091 with :ref:`expressions-value-comparisons`: equality compares according to 2092 object identity, and order comparisons raise :exc:`TypeError`. Each default 2093 method may generate these results directly, but may also return 2094 :data:`NotImplemented`. 2095 2096 See the paragraph on :meth:`__hash__` for 2097 some important notes on creating :term:`hashable` objects which support 2098 custom comparison operations and are usable as dictionary keys. 2099 2100 There are no swapped-argument versions of these methods (to be used when the 2101 left argument does not support the operation but the right argument does); 2102 rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection, 2103 :meth:`__le__` and :meth:`__ge__` are each other's reflection, and 2104 :meth:`__eq__` and :meth:`__ne__` are their own reflection. 2105 If the operands are of different types, and the right operand's type is 2106 a direct or indirect subclass of the left operand's type, 2107 the reflected method of the right operand has priority, otherwise 2108 the left operand's method has priority. Virtual subclassing is 2109 not considered. 2110 2111 When no appropriate method returns any value other than :data:`NotImplemented`, the 2112 ``==`` and ``!=`` operators will fall back to ``is`` and ``is not``, respectively. 2113 2114.. method:: object.__hash__(self) 2115 2116 .. index:: 2117 pair: object; dictionary 2118 pair: built-in function; hash 2119 2120 Called by built-in function :func:`hash` and for operations on members of 2121 hashed collections including :class:`set`, :class:`frozenset`, and 2122 :class:`dict`. The ``__hash__()`` method should return an integer. The only required 2123 property is that objects which compare equal have the same hash value; it is 2124 advised to mix together the hash values of the components of the object that 2125 also play a part in comparison of objects by packing them into a tuple and 2126 hashing the tuple. Example:: 2127 2128 def __hash__(self): 2129 return hash((self.name, self.nick, self.color)) 2130 2131 .. note:: 2132 2133 :func:`hash` truncates the value returned from an object's custom 2134 :meth:`__hash__` method to the size of a :c:type:`Py_ssize_t`. This is 2135 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an 2136 object's :meth:`__hash__` must interoperate on builds of different bit 2137 sizes, be sure to check the width on all supported builds. An easy way 2138 to do this is with 2139 ``python -c "import sys; print(sys.hash_info.width)"``. 2140 2141 If a class does not define an :meth:`__eq__` method it should not define a 2142 :meth:`__hash__` operation either; if it defines :meth:`__eq__` but not 2143 :meth:`__hash__`, its instances will not be usable as items in hashable 2144 collections. If a class defines mutable objects and implements an 2145 :meth:`__eq__` method, it should not implement :meth:`__hash__`, since the 2146 implementation of :term:`hashable` collections requires that a key's hash value is 2147 immutable (if the object's hash value changes, it will be in the wrong hash 2148 bucket). 2149 2150 User-defined classes have :meth:`__eq__` and :meth:`__hash__` methods 2151 by default (inherited from the :class:`object` class); with them, all objects compare 2152 unequal (except with themselves) and ``x.__hash__()`` returns an appropriate 2153 value such that ``x == y`` implies both that ``x is y`` and ``hash(x) == hash(y)``. 2154 2155 A class that overrides :meth:`__eq__` and does not define :meth:`__hash__` 2156 will have its :meth:`__hash__` implicitly set to ``None``. When the 2157 :meth:`__hash__` method of a class is ``None``, instances of the class will 2158 raise an appropriate :exc:`TypeError` when a program attempts to retrieve 2159 their hash value, and will also be correctly identified as unhashable when 2160 checking ``isinstance(obj, collections.abc.Hashable)``. 2161 2162 If a class that overrides :meth:`__eq__` needs to retain the implementation 2163 of :meth:`__hash__` from a parent class, the interpreter must be told this 2164 explicitly by setting ``__hash__ = <ParentClass>.__hash__``. 2165 2166 If a class that does not override :meth:`__eq__` wishes to suppress hash 2167 support, it should include ``__hash__ = None`` in the class definition. 2168 A class which defines its own :meth:`__hash__` that explicitly raises 2169 a :exc:`TypeError` would be incorrectly identified as hashable by 2170 an ``isinstance(obj, collections.abc.Hashable)`` call. 2171 2172 2173 .. note:: 2174 2175 By default, the :meth:`__hash__` values of str and bytes objects are 2176 "salted" with an unpredictable random value. Although they 2177 remain constant within an individual Python process, they are not 2178 predictable between repeated invocations of Python. 2179 2180 This is intended to provide protection against a denial-of-service caused 2181 by carefully chosen inputs that exploit the worst case performance of a 2182 dict insertion, *O*\ (*n*\ :sup:`2`) complexity. See 2183 http://ocert.org/advisories/ocert-2011-003.html for details. 2184 2185 Changing hash values affects the iteration order of sets. 2186 Python has never made guarantees about this ordering 2187 (and it typically varies between 32-bit and 64-bit builds). 2188 2189 See also :envvar:`PYTHONHASHSEED`. 2190 2191 .. versionchanged:: 3.3 2192 Hash randomization is enabled by default. 2193 2194 2195.. method:: object.__bool__(self) 2196 2197 .. index:: single: __len__() (mapping object method) 2198 2199 Called to implement truth value testing and the built-in operation 2200 ``bool()``; should return ``False`` or ``True``. When this method is not 2201 defined, :meth:`~object.__len__` is called, if it is defined, and the object is 2202 considered true if its result is nonzero. If a class defines neither 2203 :meth:`!__len__` nor :meth:`!__bool__` (which is true of the :class:`object` 2204 class itself), all its instances are considered true. 2205 2206 2207.. _attribute-access: 2208 2209Customizing attribute access 2210---------------------------- 2211 2212The following methods can be defined to customize the meaning of attribute 2213access (use of, assignment to, or deletion of ``x.name``) for class instances. 2214 2215.. XXX explain how descriptors interfere here! 2216 2217 2218.. method:: object.__getattr__(self, name) 2219 2220 Called when the default attribute access fails with an :exc:`AttributeError` 2221 (either :meth:`__getattribute__` raises an :exc:`AttributeError` because 2222 *name* is not an instance attribute or an attribute in the class tree 2223 for ``self``; or :meth:`__get__` of a *name* property raises 2224 :exc:`AttributeError`). This method should either return the (computed) 2225 attribute value or raise an :exc:`AttributeError` exception. 2226 The :class:`object` class itself does not provide this method. 2227 2228 Note that if the attribute is found through the normal mechanism, 2229 :meth:`__getattr__` is not called. (This is an intentional asymmetry between 2230 :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency 2231 reasons and because otherwise :meth:`__getattr__` would have no way to access 2232 other attributes of the instance. Note that at least for instance variables, 2233 you can take total control by not inserting any values in the instance attribute 2234 dictionary (but instead inserting them in another object). See the 2235 :meth:`__getattribute__` method below for a way to actually get total control 2236 over attribute access. 2237 2238 2239.. method:: object.__getattribute__(self, name) 2240 2241 Called unconditionally to implement attribute accesses for instances of the 2242 class. If the class also defines :meth:`__getattr__`, the latter will not be 2243 called unless :meth:`__getattribute__` either calls it explicitly or raises an 2244 :exc:`AttributeError`. This method should return the (computed) attribute value 2245 or raise an :exc:`AttributeError` exception. In order to avoid infinite 2246 recursion in this method, its implementation should always call the base class 2247 method with the same name to access any attributes it needs, for example, 2248 ``object.__getattribute__(self, name)``. 2249 2250 .. note:: 2251 2252 This method may still be bypassed when looking up special methods as the 2253 result of implicit invocation via language syntax or 2254 :ref:`built-in functions <builtin-functions>`. 2255 See :ref:`special-lookup`. 2256 2257 .. audit-event:: object.__getattr__ obj,name object.__getattribute__ 2258 2259 For certain sensitive attribute accesses, raises an 2260 :ref:`auditing event <auditing>` ``object.__getattr__`` with arguments 2261 ``obj`` and ``name``. 2262 2263 2264.. method:: object.__setattr__(self, name, value) 2265 2266 Called when an attribute assignment is attempted. This is called instead of 2267 the normal mechanism (i.e. store the value in the instance dictionary). 2268 *name* is the attribute name, *value* is the value to be assigned to it. 2269 2270 If :meth:`__setattr__` wants to assign to an instance attribute, it should 2271 call the base class method with the same name, for example, 2272 ``object.__setattr__(self, name, value)``. 2273 2274 .. audit-event:: object.__setattr__ obj,name,value object.__setattr__ 2275 2276 For certain sensitive attribute assignments, raises an 2277 :ref:`auditing event <auditing>` ``object.__setattr__`` with arguments 2278 ``obj``, ``name``, ``value``. 2279 2280 2281.. method:: object.__delattr__(self, name) 2282 2283 Like :meth:`__setattr__` but for attribute deletion instead of assignment. This 2284 should only be implemented if ``del obj.name`` is meaningful for the object. 2285 2286 .. audit-event:: object.__delattr__ obj,name object.__delattr__ 2287 2288 For certain sensitive attribute deletions, raises an 2289 :ref:`auditing event <auditing>` ``object.__delattr__`` with arguments 2290 ``obj`` and ``name``. 2291 2292 2293.. method:: object.__dir__(self) 2294 2295 Called when :func:`dir` is called on the object. An iterable must be 2296 returned. :func:`dir` converts the returned iterable to a list and sorts it. 2297 2298 2299Customizing module attribute access 2300^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2301 2302.. index:: 2303 single: __getattr__ (module attribute) 2304 single: __dir__ (module attribute) 2305 single: __class__ (module attribute) 2306 2307Special names ``__getattr__`` and ``__dir__`` can be also used to customize 2308access to module attributes. The ``__getattr__`` function at the module level 2309should accept one argument which is the name of an attribute and return the 2310computed value or raise an :exc:`AttributeError`. If an attribute is 2311not found on a module object through the normal lookup, i.e. 2312:meth:`object.__getattribute__`, then ``__getattr__`` is searched in 2313the module ``__dict__`` before raising an :exc:`AttributeError`. If found, 2314it is called with the attribute name and the result is returned. 2315 2316The ``__dir__`` function should accept no arguments, and return an iterable of 2317strings that represents the names accessible on module. If present, this 2318function overrides the standard :func:`dir` search on a module. 2319 2320For a more fine grained customization of the module behavior (setting 2321attributes, properties, etc.), one can set the ``__class__`` attribute of 2322a module object to a subclass of :class:`types.ModuleType`. For example:: 2323 2324 import sys 2325 from types import ModuleType 2326 2327 class VerboseModule(ModuleType): 2328 def __repr__(self): 2329 return f'Verbose {self.__name__}' 2330 2331 def __setattr__(self, attr, value): 2332 print(f'Setting {attr}...') 2333 super().__setattr__(attr, value) 2334 2335 sys.modules[__name__].__class__ = VerboseModule 2336 2337.. note:: 2338 Defining module ``__getattr__`` and setting module ``__class__`` only 2339 affect lookups made using the attribute access syntax -- directly accessing 2340 the module globals (whether by code within the module, or via a reference 2341 to the module's globals dictionary) is unaffected. 2342 2343.. versionchanged:: 3.5 2344 ``__class__`` module attribute is now writable. 2345 2346.. versionadded:: 3.7 2347 ``__getattr__`` and ``__dir__`` module attributes. 2348 2349.. seealso:: 2350 2351 :pep:`562` - Module __getattr__ and __dir__ 2352 Describes the ``__getattr__`` and ``__dir__`` functions on modules. 2353 2354 2355.. _descriptors: 2356 2357Implementing Descriptors 2358^^^^^^^^^^^^^^^^^^^^^^^^ 2359 2360The following methods only apply when an instance of the class containing the 2361method (a so-called *descriptor* class) appears in an *owner* class (the 2362descriptor must be in either the owner's class dictionary or in the class 2363dictionary for one of its parents). In the examples below, "the attribute" 2364refers to the attribute whose name is the key of the property in the owner 2365class' :attr:`~object.__dict__`. The :class:`object` class itself does not 2366implement any of these protocols. 2367 2368.. method:: object.__get__(self, instance, owner=None) 2369 2370 Called to get the attribute of the owner class (class attribute access) or 2371 of an instance of that class (instance attribute access). The optional 2372 *owner* argument is the owner class, while *instance* is the instance that 2373 the attribute was accessed through, or ``None`` when the attribute is 2374 accessed through the *owner*. 2375 2376 This method should return the computed attribute value or raise an 2377 :exc:`AttributeError` exception. 2378 2379 :PEP:`252` specifies that :meth:`__get__` is callable with one or two 2380 arguments. Python's own built-in descriptors support this specification; 2381 however, it is likely that some third-party tools have descriptors 2382 that require both arguments. Python's own :meth:`__getattribute__` 2383 implementation always passes in both arguments whether they are required 2384 or not. 2385 2386.. method:: object.__set__(self, instance, value) 2387 2388 Called to set the attribute on an instance *instance* of the owner class to a 2389 new value, *value*. 2390 2391 Note, adding :meth:`__set__` or :meth:`__delete__` changes the kind of 2392 descriptor to a "data descriptor". See :ref:`descriptor-invocation` for 2393 more details. 2394 2395.. method:: object.__delete__(self, instance) 2396 2397 Called to delete the attribute on an instance *instance* of the owner class. 2398 2399Instances of descriptors may also have the :attr:`!__objclass__` attribute 2400present: 2401 2402.. attribute:: object.__objclass__ 2403 2404 The attribute :attr:`!__objclass__` is interpreted by the :mod:`inspect` module 2405 as specifying the class where this object was defined (setting this 2406 appropriately can assist in runtime introspection of dynamic class attributes). 2407 For callables, it may indicate that an instance of the given type (or a 2408 subclass) is expected or required as the first positional argument (for example, 2409 CPython sets this attribute for unbound methods that are implemented in C). 2410 2411 2412.. _descriptor-invocation: 2413 2414Invoking Descriptors 2415^^^^^^^^^^^^^^^^^^^^ 2416 2417In general, a descriptor is an object attribute with "binding behavior", one 2418whose attribute access has been overridden by methods in the descriptor 2419protocol: :meth:`~object.__get__`, :meth:`~object.__set__`, and 2420:meth:`~object.__delete__`. If any of 2421those methods are defined for an object, it is said to be a descriptor. 2422 2423The default behavior for attribute access is to get, set, or delete the 2424attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain 2425starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and 2426continuing through the base classes of ``type(a)`` excluding metaclasses. 2427 2428However, if the looked-up value is an object defining one of the descriptor 2429methods, then Python may override the default behavior and invoke the descriptor 2430method instead. Where this occurs in the precedence chain depends on which 2431descriptor methods were defined and how they were called. 2432 2433The starting point for descriptor invocation is a binding, ``a.x``. How the 2434arguments are assembled depends on ``a``: 2435 2436Direct Call 2437 The simplest and least common call is when user code directly invokes a 2438 descriptor method: ``x.__get__(a)``. 2439 2440Instance Binding 2441 If binding to an object instance, ``a.x`` is transformed into the call: 2442 ``type(a).__dict__['x'].__get__(a, type(a))``. 2443 2444Class Binding 2445 If binding to a class, ``A.x`` is transformed into the call: 2446 ``A.__dict__['x'].__get__(None, A)``. 2447 2448Super Binding 2449 A dotted lookup such as ``super(A, a).x`` searches 2450 ``a.__class__.__mro__`` for a base class ``B`` following ``A`` and then 2451 returns ``B.__dict__['x'].__get__(a, A)``. If not a descriptor, ``x`` is 2452 returned unchanged. 2453 2454.. testcode:: 2455 :hide: 2456 2457 class Desc: 2458 def __get__(*args): 2459 return args 2460 2461 class B: 2462 2463 x = Desc() 2464 2465 class A(B): 2466 2467 x = 999 2468 2469 def m(self): 2470 'Demonstrate these two descriptor invocations are equivalent' 2471 result1 = super(A, self).x 2472 result2 = B.__dict__['x'].__get__(self, A) 2473 return result1 == result2 2474 2475.. doctest:: 2476 :hide: 2477 2478 >>> a = A() 2479 >>> a.__class__.__mro__.index(B) > a.__class__.__mro__.index(A) 2480 True 2481 >>> super(A, a).x == B.__dict__['x'].__get__(a, A) 2482 True 2483 >>> a.m() 2484 True 2485 2486For instance bindings, the precedence of descriptor invocation depends on 2487which descriptor methods are defined. A descriptor can define any combination 2488of :meth:`~object.__get__`, :meth:`~object.__set__` and 2489:meth:`~object.__delete__`. If it does not 2490define :meth:`!__get__`, then accessing the attribute will return the descriptor 2491object itself unless there is a value in the object's instance dictionary. If 2492the descriptor defines :meth:`!__set__` and/or :meth:`!__delete__`, it is a data 2493descriptor; if it defines neither, it is a non-data descriptor. Normally, data 2494descriptors define both :meth:`!__get__` and :meth:`!__set__`, while non-data 2495descriptors have just the :meth:`!__get__` method. Data descriptors with 2496:meth:`!__get__` and :meth:`!__set__` (and/or :meth:`!__delete__`) defined 2497always override a redefinition in an 2498instance dictionary. In contrast, non-data descriptors can be overridden by 2499instances. 2500 2501Python methods (including those decorated with 2502:func:`@staticmethod <staticmethod>` and :func:`@classmethod <classmethod>`) are 2503implemented as non-data descriptors. Accordingly, instances can redefine and 2504override methods. This allows individual instances to acquire behaviors that 2505differ from other instances of the same class. 2506 2507The :func:`property` function is implemented as a data descriptor. Accordingly, 2508instances cannot override the behavior of a property. 2509 2510 2511.. _slots: 2512 2513__slots__ 2514^^^^^^^^^ 2515 2516*__slots__* allow us to explicitly declare data members (like 2517properties) and deny the creation of :attr:`~object.__dict__` and *__weakref__* 2518(unless explicitly declared in *__slots__* or available in a parent.) 2519 2520The space saved over using :attr:`~object.__dict__` can be significant. 2521Attribute lookup speed can be significantly improved as well. 2522 2523.. data:: object.__slots__ 2524 2525 This class variable can be assigned a string, iterable, or sequence of 2526 strings with variable names used by instances. *__slots__* reserves space 2527 for the declared variables and prevents the automatic creation of 2528 :attr:`~object.__dict__` 2529 and *__weakref__* for each instance. 2530 2531 2532.. _datamodel-note-slots: 2533 2534Notes on using *__slots__*: 2535 2536* When inheriting from a class without *__slots__*, the 2537 :attr:`~object.__dict__` and 2538 *__weakref__* attribute of the instances will always be accessible. 2539 2540* Without a :attr:`~object.__dict__` variable, instances cannot be assigned new 2541 variables not 2542 listed in the *__slots__* definition. Attempts to assign to an unlisted 2543 variable name raises :exc:`AttributeError`. If dynamic assignment of new 2544 variables is desired, then add ``'__dict__'`` to the sequence of strings in 2545 the *__slots__* declaration. 2546 2547* Without a *__weakref__* variable for each instance, classes defining 2548 *__slots__* do not support :mod:`weak references <weakref>` to its instances. 2549 If weak reference 2550 support is needed, then add ``'__weakref__'`` to the sequence of strings in the 2551 *__slots__* declaration. 2552 2553* *__slots__* are implemented at the class level by creating :ref:`descriptors <descriptors>` 2554 for each variable name. As a result, class attributes 2555 cannot be used to set default values for instance variables defined by 2556 *__slots__*; otherwise, the class attribute would overwrite the descriptor 2557 assignment. 2558 2559* The action of a *__slots__* declaration is not limited to the class 2560 where it is defined. *__slots__* declared in parents are available in 2561 child classes. However, instances of a child subclass will get a 2562 :attr:`~object.__dict__` and *__weakref__* unless the subclass also defines 2563 *__slots__* (which should only contain names of any *additional* slots). 2564 2565* If a class defines a slot also defined in a base class, the instance variable 2566 defined by the base class slot is inaccessible (except by retrieving its 2567 descriptor directly from the base class). This renders the meaning of the 2568 program undefined. In the future, a check may be added to prevent this. 2569 2570* :exc:`TypeError` will be raised if nonempty *__slots__* are defined for a 2571 class derived from a 2572 :c:member:`"variable-length" built-in type <PyTypeObject.tp_itemsize>` such as 2573 :class:`int`, :class:`bytes`, and :class:`tuple`. 2574 2575* Any non-string :term:`iterable` may be assigned to *__slots__*. 2576 2577* If a :class:`dictionary <dict>` is used to assign *__slots__*, the dictionary 2578 keys will be used as the slot names. The values of the dictionary can be used 2579 to provide per-attribute docstrings that will be recognised by 2580 :func:`inspect.getdoc` and displayed in the output of :func:`help`. 2581 2582* :attr:`~object.__class__` assignment works only if both classes have the 2583 same *__slots__*. 2584 2585* :ref:`Multiple inheritance <tut-multiple>` with multiple slotted parent 2586 classes can be used, 2587 but only one parent is allowed to have attributes created by slots 2588 (the other bases must have empty slot layouts) - violations raise 2589 :exc:`TypeError`. 2590 2591* If an :term:`iterator` is used for *__slots__* then a :term:`descriptor` is 2592 created for each 2593 of the iterator's values. However, the *__slots__* attribute will be an empty 2594 iterator. 2595 2596.. _class-customization: 2597 2598Customizing class creation 2599-------------------------- 2600 2601Whenever a class inherits from another class, :meth:`~object.__init_subclass__` is 2602called on the parent class. This way, it is possible to write classes which 2603change the behavior of subclasses. This is closely related to class 2604decorators, but where class decorators only affect the specific class they're 2605applied to, ``__init_subclass__`` solely applies to future subclasses of the 2606class defining the method. 2607 2608.. classmethod:: object.__init_subclass__(cls) 2609 2610 This method is called whenever the containing class is subclassed. 2611 *cls* is then the new subclass. If defined as a normal instance method, 2612 this method is implicitly converted to a class method. 2613 2614 Keyword arguments which are given to a new class are passed to 2615 the parent class's ``__init_subclass__``. For compatibility with 2616 other classes using ``__init_subclass__``, one should take out the 2617 needed keyword arguments and pass the others over to the base 2618 class, as in:: 2619 2620 class Philosopher: 2621 def __init_subclass__(cls, /, default_name, **kwargs): 2622 super().__init_subclass__(**kwargs) 2623 cls.default_name = default_name 2624 2625 class AustralianPhilosopher(Philosopher, default_name="Bruce"): 2626 pass 2627 2628 The default implementation ``object.__init_subclass__`` does 2629 nothing, but raises an error if it is called with any arguments. 2630 2631 .. note:: 2632 2633 The metaclass hint ``metaclass`` is consumed by the rest of the type 2634 machinery, and is never passed to ``__init_subclass__`` implementations. 2635 The actual metaclass (rather than the explicit hint) can be accessed as 2636 ``type(cls)``. 2637 2638 .. versionadded:: 3.6 2639 2640 2641When a class is created, :meth:`type.__new__` scans the class variables 2642and makes callbacks to those with a :meth:`~object.__set_name__` hook. 2643 2644.. method:: object.__set_name__(self, owner, name) 2645 2646 Automatically called at the time the owning class *owner* is 2647 created. The object has been assigned to *name* in that class:: 2648 2649 class A: 2650 x = C() # Automatically calls: x.__set_name__(A, 'x') 2651 2652 If the class variable is assigned after the class is created, 2653 :meth:`__set_name__` will not be called automatically. 2654 If needed, :meth:`__set_name__` can be called directly:: 2655 2656 class A: 2657 pass 2658 2659 c = C() 2660 A.x = c # The hook is not called 2661 c.__set_name__(A, 'x') # Manually invoke the hook 2662 2663 See :ref:`class-object-creation` for more details. 2664 2665 .. versionadded:: 3.6 2666 2667 2668.. _metaclasses: 2669 2670Metaclasses 2671^^^^^^^^^^^ 2672 2673.. index:: 2674 single: metaclass 2675 pair: built-in function; type 2676 single: = (equals); class definition 2677 2678By default, classes are constructed using :func:`type`. The class body is 2679executed in a new namespace and the class name is bound locally to the 2680result of ``type(name, bases, namespace)``. 2681 2682The class creation process can be customized by passing the ``metaclass`` 2683keyword argument in the class definition line, or by inheriting from an 2684existing class that included such an argument. In the following example, 2685both ``MyClass`` and ``MySubclass`` are instances of ``Meta``:: 2686 2687 class Meta(type): 2688 pass 2689 2690 class MyClass(metaclass=Meta): 2691 pass 2692 2693 class MySubclass(MyClass): 2694 pass 2695 2696Any other keyword arguments that are specified in the class definition are 2697passed through to all metaclass operations described below. 2698 2699When a class definition is executed, the following steps occur: 2700 2701* MRO entries are resolved; 2702* the appropriate metaclass is determined; 2703* the class namespace is prepared; 2704* the class body is executed; 2705* the class object is created. 2706 2707 2708Resolving MRO entries 2709^^^^^^^^^^^^^^^^^^^^^ 2710 2711.. method:: object.__mro_entries__(self, bases) 2712 2713 If a base that appears in a class definition is not an instance of 2714 :class:`type`, then an :meth:`!__mro_entries__` method is searched on the base. 2715 If an :meth:`!__mro_entries__` method is found, the base is substituted with the 2716 result of a call to :meth:`!__mro_entries__` when creating the class. 2717 The method is called with the original bases tuple 2718 passed to the *bases* parameter, and must return a tuple 2719 of classes that will be used instead of the base. The returned tuple may be 2720 empty: in these cases, the original base is ignored. 2721 2722.. seealso:: 2723 2724 :func:`types.resolve_bases` 2725 Dynamically resolve bases that are not instances of :class:`type`. 2726 2727 :func:`types.get_original_bases` 2728 Retrieve a class's "original bases" prior to modifications by 2729 :meth:`~object.__mro_entries__`. 2730 2731 :pep:`560` 2732 Core support for typing module and generic types. 2733 2734 2735Determining the appropriate metaclass 2736^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2737.. index:: 2738 single: metaclass hint 2739 2740The appropriate metaclass for a class definition is determined as follows: 2741 2742* if no bases and no explicit metaclass are given, then :func:`type` is used; 2743* if an explicit metaclass is given and it is *not* an instance of 2744 :func:`type`, then it is used directly as the metaclass; 2745* if an instance of :func:`type` is given as the explicit metaclass, or 2746 bases are defined, then the most derived metaclass is used. 2747 2748The most derived metaclass is selected from the explicitly specified 2749metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified 2750base classes. The most derived metaclass is one which is a subtype of *all* 2751of these candidate metaclasses. If none of the candidate metaclasses meets 2752that criterion, then the class definition will fail with ``TypeError``. 2753 2754 2755.. _prepare: 2756 2757Preparing the class namespace 2758^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2759 2760.. index:: 2761 single: __prepare__ (metaclass method) 2762 2763Once the appropriate metaclass has been identified, then the class namespace 2764is prepared. If the metaclass has a ``__prepare__`` attribute, it is called 2765as ``namespace = metaclass.__prepare__(name, bases, **kwds)`` (where the 2766additional keyword arguments, if any, come from the class definition). The 2767``__prepare__`` method should be implemented as a 2768:func:`classmethod <classmethod>`. The 2769namespace returned by ``__prepare__`` is passed in to ``__new__``, but when 2770the final class object is created the namespace is copied into a new ``dict``. 2771 2772If the metaclass has no ``__prepare__`` attribute, then the class namespace 2773is initialised as an empty ordered mapping. 2774 2775.. seealso:: 2776 2777 :pep:`3115` - Metaclasses in Python 3000 2778 Introduced the ``__prepare__`` namespace hook 2779 2780 2781Executing the class body 2782^^^^^^^^^^^^^^^^^^^^^^^^ 2783 2784.. index:: 2785 single: class; body 2786 2787The class body is executed (approximately) as 2788``exec(body, globals(), namespace)``. The key difference from a normal 2789call to :func:`exec` is that lexical scoping allows the class body (including 2790any methods) to reference names from the current and outer scopes when the 2791class definition occurs inside a function. 2792 2793However, even when the class definition occurs inside the function, methods 2794defined inside the class still cannot see names defined at the class scope. 2795Class variables must be accessed through the first parameter of instance or 2796class methods, or through the implicit lexically scoped ``__class__`` reference 2797described in the next section. 2798 2799.. _class-object-creation: 2800 2801Creating the class object 2802^^^^^^^^^^^^^^^^^^^^^^^^^ 2803 2804.. index:: 2805 single: __class__ (method cell) 2806 single: __classcell__ (class namespace entry) 2807 2808 2809Once the class namespace has been populated by executing the class body, 2810the class object is created by calling 2811``metaclass(name, bases, namespace, **kwds)`` (the additional keywords 2812passed here are the same as those passed to ``__prepare__``). 2813 2814This class object is the one that will be referenced by the zero-argument 2815form of :func:`super`. ``__class__`` is an implicit closure reference 2816created by the compiler if any methods in a class body refer to either 2817``__class__`` or ``super``. This allows the zero argument form of 2818:func:`super` to correctly identify the class being defined based on 2819lexical scoping, while the class or instance that was used to make the 2820current call is identified based on the first argument passed to the method. 2821 2822.. impl-detail:: 2823 2824 In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass 2825 as a ``__classcell__`` entry in the class namespace. If present, this must 2826 be propagated up to the ``type.__new__`` call in order for the class to be 2827 initialised correctly. 2828 Failing to do so will result in a :exc:`RuntimeError` in Python 3.8. 2829 2830When using the default metaclass :class:`type`, or any metaclass that ultimately 2831calls ``type.__new__``, the following additional customization steps are 2832invoked after creating the class object: 2833 28341) The ``type.__new__`` method collects all of the attributes in the class 2835 namespace that define a :meth:`~object.__set_name__` method; 28362) Those ``__set_name__`` methods are called with the class 2837 being defined and the assigned name of that particular attribute; 28383) The :meth:`~object.__init_subclass__` hook is called on the 2839 immediate parent of the new class in its method resolution order. 2840 2841After the class object is created, it is passed to the class decorators 2842included in the class definition (if any) and the resulting object is bound 2843in the local namespace as the defined class. 2844 2845When a new class is created by ``type.__new__``, the object provided as the 2846namespace parameter is copied to a new ordered mapping and the original 2847object is discarded. The new copy is wrapped in a read-only proxy, which 2848becomes the :attr:`~type.__dict__` attribute of the class object. 2849 2850.. seealso:: 2851 2852 :pep:`3135` - New super 2853 Describes the implicit ``__class__`` closure reference 2854 2855 2856Uses for metaclasses 2857^^^^^^^^^^^^^^^^^^^^ 2858 2859The potential uses for metaclasses are boundless. Some ideas that have been 2860explored include enum, logging, interface checking, automatic delegation, 2861automatic property creation, proxies, frameworks, and automatic resource 2862locking/synchronization. 2863 2864 2865Customizing instance and subclass checks 2866---------------------------------------- 2867 2868The following methods are used to override the default behavior of the 2869:func:`isinstance` and :func:`issubclass` built-in functions. 2870 2871In particular, the metaclass :class:`abc.ABCMeta` implements these methods in 2872order to allow the addition of Abstract Base Classes (ABCs) as "virtual base 2873classes" to any class or type (including built-in types), including other 2874ABCs. 2875 2876.. method:: type.__instancecheck__(self, instance) 2877 2878 Return true if *instance* should be considered a (direct or indirect) 2879 instance of *class*. If defined, called to implement ``isinstance(instance, 2880 class)``. 2881 2882 2883.. method:: type.__subclasscheck__(self, subclass) 2884 2885 Return true if *subclass* should be considered a (direct or indirect) 2886 subclass of *class*. If defined, called to implement ``issubclass(subclass, 2887 class)``. 2888 2889 2890Note that these methods are looked up on the type (metaclass) of a class. They 2891cannot be defined as class methods in the actual class. This is consistent with 2892the lookup of special methods that are called on instances, only in this 2893case the instance is itself a class. 2894 2895.. seealso:: 2896 2897 :pep:`3119` - Introducing Abstract Base Classes 2898 Includes the specification for customizing :func:`isinstance` and 2899 :func:`issubclass` behavior through :meth:`~type.__instancecheck__` and 2900 :meth:`~type.__subclasscheck__`, with motivation for this functionality 2901 in the context of adding Abstract Base Classes (see the :mod:`abc` 2902 module) to the language. 2903 2904 2905Emulating generic types 2906----------------------- 2907 2908When using :term:`type annotations<annotation>`, it is often useful to 2909*parameterize* a :term:`generic type` using Python's square-brackets notation. 2910For example, the annotation ``list[int]`` might be used to signify a 2911:class:`list` in which all the elements are of type :class:`int`. 2912 2913.. seealso:: 2914 2915 :pep:`484` - Type Hints 2916 Introducing Python's framework for type annotations 2917 2918 :ref:`Generic Alias Types<types-genericalias>` 2919 Documentation for objects representing parameterized generic classes 2920 2921 :ref:`Generics`, :ref:`user-defined generics<user-defined-generics>` and :class:`typing.Generic` 2922 Documentation on how to implement generic classes that can be 2923 parameterized at runtime and understood by static type-checkers. 2924 2925A class can *generally* only be parameterized if it defines the special 2926class method ``__class_getitem__()``. 2927 2928.. classmethod:: object.__class_getitem__(cls, key) 2929 2930 Return an object representing the specialization of a generic class 2931 by type arguments found in *key*. 2932 2933 When defined on a class, ``__class_getitem__()`` is automatically a class 2934 method. As such, there is no need for it to be decorated with 2935 :func:`@classmethod<classmethod>` when it is defined. 2936 2937 2938The purpose of *__class_getitem__* 2939^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2940 2941The purpose of :meth:`~object.__class_getitem__` is to allow runtime 2942parameterization of standard-library generic classes in order to more easily 2943apply :term:`type hints<type hint>` to these classes. 2944 2945To implement custom generic classes that can be parameterized at runtime and 2946understood by static type-checkers, users should either inherit from a standard 2947library class that already implements :meth:`~object.__class_getitem__`, or 2948inherit from :class:`typing.Generic`, which has its own implementation of 2949``__class_getitem__()``. 2950 2951Custom implementations of :meth:`~object.__class_getitem__` on classes defined 2952outside of the standard library may not be understood by third-party 2953type-checkers such as mypy. Using ``__class_getitem__()`` on any class for 2954purposes other than type hinting is discouraged. 2955 2956 2957.. _classgetitem-versus-getitem: 2958 2959 2960*__class_getitem__* versus *__getitem__* 2961^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2962 2963Usually, the :ref:`subscription<subscriptions>` of an object using square 2964brackets will call the :meth:`~object.__getitem__` instance method defined on 2965the object's class. However, if the object being subscribed is itself a class, 2966the class method :meth:`~object.__class_getitem__` may be called instead. 2967``__class_getitem__()`` should return a :ref:`GenericAlias<types-genericalias>` 2968object if it is properly defined. 2969 2970Presented with the :term:`expression` ``obj[x]``, the Python interpreter 2971follows something like the following process to decide whether 2972:meth:`~object.__getitem__` or :meth:`~object.__class_getitem__` should be 2973called:: 2974 2975 from inspect import isclass 2976 2977 def subscribe(obj, x): 2978 """Return the result of the expression 'obj[x]'""" 2979 2980 class_of_obj = type(obj) 2981 2982 # If the class of obj defines __getitem__, 2983 # call class_of_obj.__getitem__(obj, x) 2984 if hasattr(class_of_obj, '__getitem__'): 2985 return class_of_obj.__getitem__(obj, x) 2986 2987 # Else, if obj is a class and defines __class_getitem__, 2988 # call obj.__class_getitem__(x) 2989 elif isclass(obj) and hasattr(obj, '__class_getitem__'): 2990 return obj.__class_getitem__(x) 2991 2992 # Else, raise an exception 2993 else: 2994 raise TypeError( 2995 f"'{class_of_obj.__name__}' object is not subscriptable" 2996 ) 2997 2998In Python, all classes are themselves instances of other classes. The class of 2999a class is known as that class's :term:`metaclass`, and most classes have the 3000:class:`type` class as their metaclass. :class:`type` does not define 3001:meth:`~object.__getitem__`, meaning that expressions such as ``list[int]``, 3002``dict[str, float]`` and ``tuple[str, bytes]`` all result in 3003:meth:`~object.__class_getitem__` being called:: 3004 3005 >>> # list has class "type" as its metaclass, like most classes: 3006 >>> type(list) 3007 <class 'type'> 3008 >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes) 3009 True 3010 >>> # "list[int]" calls "list.__class_getitem__(int)" 3011 >>> list[int] 3012 list[int] 3013 >>> # list.__class_getitem__ returns a GenericAlias object: 3014 >>> type(list[int]) 3015 <class 'types.GenericAlias'> 3016 3017However, if a class has a custom metaclass that defines 3018:meth:`~object.__getitem__`, subscribing the class may result in different 3019behaviour. An example of this can be found in the :mod:`enum` module:: 3020 3021 >>> from enum import Enum 3022 >>> class Menu(Enum): 3023 ... """A breakfast menu""" 3024 ... SPAM = 'spam' 3025 ... BACON = 'bacon' 3026 ... 3027 >>> # Enum classes have a custom metaclass: 3028 >>> type(Menu) 3029 <class 'enum.EnumMeta'> 3030 >>> # EnumMeta defines __getitem__, 3031 >>> # so __class_getitem__ is not called, 3032 >>> # and the result is not a GenericAlias object: 3033 >>> Menu['SPAM'] 3034 <Menu.SPAM: 'spam'> 3035 >>> type(Menu['SPAM']) 3036 <enum 'Menu'> 3037 3038 3039.. seealso:: 3040 :pep:`560` - Core Support for typing module and generic types 3041 Introducing :meth:`~object.__class_getitem__`, and outlining when a 3042 :ref:`subscription<subscriptions>` results in ``__class_getitem__()`` 3043 being called instead of :meth:`~object.__getitem__` 3044 3045 3046.. _callable-types: 3047 3048Emulating callable objects 3049-------------------------- 3050 3051 3052.. method:: object.__call__(self[, args...]) 3053 3054 .. index:: pair: call; instance 3055 3056 Called when the instance is "called" as a function; if this method is defined, 3057 ``x(arg1, arg2, ...)`` roughly translates to ``type(x).__call__(x, arg1, ...)``. 3058 The :class:`object` class itself does not provide this method. 3059 3060 3061.. _sequence-types: 3062 3063Emulating container types 3064------------------------- 3065 3066The following methods can be defined to implement container objects. None of them 3067are provided by the :class:`object` class itself. Containers usually are 3068:term:`sequences <sequence>` (such as :class:`lists <list>` or 3069:class:`tuples <tuple>`) or :term:`mappings <mapping>` (like 3070:term:`dictionaries <dictionary>`), 3071but can represent other containers as well. The first set of methods is used 3072either to emulate a sequence or to emulate a mapping; the difference is that for 3073a sequence, the allowable keys should be the integers *k* for which ``0 <= k < 3074N`` where *N* is the length of the sequence, or :class:`slice` objects, which define a 3075range of items. It is also recommended that mappings provide the methods 3076:meth:`!keys`, :meth:`!values`, :meth:`!items`, :meth:`!get`, :meth:`!clear`, 3077:meth:`!setdefault`, :meth:`!pop`, :meth:`!popitem`, :meth:`!copy`, and 3078:meth:`!update` behaving similar to those for Python's standard :class:`dictionary <dict>` 3079objects. The :mod:`collections.abc` module provides a 3080:class:`~collections.abc.MutableMapping` 3081:term:`abstract base class` to help create those methods from a base set of 3082:meth:`~object.__getitem__`, :meth:`~object.__setitem__`, 3083:meth:`~object.__delitem__`, and :meth:`!keys`. 3084Mutable sequences should provide methods :meth:`!append`, :meth:`!count`, 3085:meth:`!index`, :meth:`!extend`, :meth:`!insert`, :meth:`!pop`, :meth:`!remove`, 3086:meth:`!reverse` and :meth:`!sort`, like Python standard :class:`list` 3087objects. Finally, 3088sequence types should implement addition (meaning concatenation) and 3089multiplication (meaning repetition) by defining the methods 3090:meth:`~object.__add__`, :meth:`~object.__radd__`, :meth:`~object.__iadd__`, 3091:meth:`~object.__mul__`, :meth:`~object.__rmul__` and :meth:`~object.__imul__` 3092described below; they should not define other numerical 3093operators. It is recommended that both mappings and sequences implement the 3094:meth:`~object.__contains__` method to allow efficient use of the ``in`` 3095operator; for 3096mappings, ``in`` should search the mapping's keys; for sequences, it should 3097search through the values. It is further recommended that both mappings and 3098sequences implement the :meth:`~object.__iter__` method to allow efficient iteration 3099through the container; for mappings, :meth:`!__iter__` should iterate 3100through the object's keys; for sequences, it should iterate through the values. 3101 3102.. method:: object.__len__(self) 3103 3104 .. index:: 3105 pair: built-in function; len 3106 single: __bool__() (object method) 3107 3108 Called to implement the built-in function :func:`len`. Should return the length 3109 of the object, an integer ``>=`` 0. Also, an object that doesn't define a 3110 :meth:`~object.__bool__` method and whose :meth:`!__len__` method returns zero is 3111 considered to be false in a Boolean context. 3112 3113 .. impl-detail:: 3114 3115 In CPython, the length is required to be at most :data:`sys.maxsize`. 3116 If the length is larger than :data:`!sys.maxsize` some features (such as 3117 :func:`len`) may raise :exc:`OverflowError`. To prevent raising 3118 :exc:`!OverflowError` by truth value testing, an object must define a 3119 :meth:`~object.__bool__` method. 3120 3121 3122.. method:: object.__length_hint__(self) 3123 3124 Called to implement :func:`operator.length_hint`. Should return an estimated 3125 length for the object (which may be greater or less than the actual length). 3126 The length must be an integer ``>=`` 0. The return value may also be 3127 :data:`NotImplemented`, which is treated the same as if the 3128 ``__length_hint__`` method didn't exist at all. This method is purely an 3129 optimization and is never required for correctness. 3130 3131 .. versionadded:: 3.4 3132 3133 3134.. index:: pair: object; slice 3135 3136.. note:: 3137 3138 Slicing is done exclusively with the following three methods. A call like :: 3139 3140 a[1:2] = b 3141 3142 is translated to :: 3143 3144 a[slice(1, 2, None)] = b 3145 3146 and so forth. Missing slice items are always filled in with ``None``. 3147 3148 3149.. method:: object.__getitem__(self, key) 3150 3151 Called to implement evaluation of ``self[key]``. For :term:`sequence` types, 3152 the accepted keys should be integers. Optionally, they may support 3153 :class:`slice` objects as well. Negative index support is also optional. 3154 If *key* is 3155 of an inappropriate type, :exc:`TypeError` may be raised; if *key* is a value 3156 outside the set of indexes for the sequence (after any special 3157 interpretation of negative values), :exc:`IndexError` should be raised. For 3158 :term:`mapping` types, if *key* is missing (not in the container), 3159 :exc:`KeyError` should be raised. 3160 3161 .. note:: 3162 3163 :keyword:`for` loops expect that an :exc:`IndexError` will be raised for 3164 illegal indexes to allow proper detection of the end of the sequence. 3165 3166 .. note:: 3167 3168 When :ref:`subscripting<subscriptions>` a *class*, the special 3169 class method :meth:`~object.__class_getitem__` may be called instead of 3170 ``__getitem__()``. See :ref:`classgetitem-versus-getitem` for more 3171 details. 3172 3173 3174.. method:: object.__setitem__(self, key, value) 3175 3176 Called to implement assignment to ``self[key]``. Same note as for 3177 :meth:`__getitem__`. This should only be implemented for mappings if the 3178 objects support changes to the values for keys, or if new keys can be added, or 3179 for sequences if elements can be replaced. The same exceptions should be raised 3180 for improper *key* values as for the :meth:`__getitem__` method. 3181 3182 3183.. method:: object.__delitem__(self, key) 3184 3185 Called to implement deletion of ``self[key]``. Same note as for 3186 :meth:`__getitem__`. This should only be implemented for mappings if the 3187 objects support removal of keys, or for sequences if elements can be removed 3188 from the sequence. The same exceptions should be raised for improper *key* 3189 values as for the :meth:`__getitem__` method. 3190 3191 3192.. method:: object.__missing__(self, key) 3193 3194 Called by :class:`dict`\ .\ :meth:`__getitem__` to implement ``self[key]`` for dict subclasses 3195 when key is not in the dictionary. 3196 3197 3198.. method:: object.__iter__(self) 3199 3200 This method is called when an :term:`iterator` is required for a container. 3201 This method should return a new iterator object that can iterate over all the 3202 objects in the container. For mappings, it should iterate over the keys of 3203 the container. 3204 3205 3206.. method:: object.__reversed__(self) 3207 3208 Called (if present) by the :func:`reversed` built-in to implement 3209 reverse iteration. It should return a new iterator object that iterates 3210 over all the objects in the container in reverse order. 3211 3212 If the :meth:`__reversed__` method is not provided, the :func:`reversed` 3213 built-in will fall back to using the sequence protocol (:meth:`__len__` and 3214 :meth:`__getitem__`). Objects that support the sequence protocol should 3215 only provide :meth:`__reversed__` if they can provide an implementation 3216 that is more efficient than the one provided by :func:`reversed`. 3217 3218 3219The membership test operators (:keyword:`in` and :keyword:`not in`) are normally 3220implemented as an iteration through a container. However, container objects can 3221supply the following special method with a more efficient implementation, which 3222also does not require the object be iterable. 3223 3224.. method:: object.__contains__(self, item) 3225 3226 Called to implement membership test operators. Should return true if *item* 3227 is in *self*, false otherwise. For mapping objects, this should consider the 3228 keys of the mapping rather than the values or the key-item pairs. 3229 3230 For objects that don't define :meth:`__contains__`, the membership test first 3231 tries iteration via :meth:`__iter__`, then the old sequence iteration 3232 protocol via :meth:`__getitem__`, see :ref:`this section in the language 3233 reference <membership-test-details>`. 3234 3235 3236.. _numeric-types: 3237 3238Emulating numeric types 3239----------------------- 3240 3241The following methods can be defined to emulate numeric objects. Methods 3242corresponding to operations that are not supported by the particular kind of 3243number implemented (e.g., bitwise operations for non-integral numbers) should be 3244left undefined. 3245 3246 3247.. method:: object.__add__(self, other) 3248 object.__sub__(self, other) 3249 object.__mul__(self, other) 3250 object.__matmul__(self, other) 3251 object.__truediv__(self, other) 3252 object.__floordiv__(self, other) 3253 object.__mod__(self, other) 3254 object.__divmod__(self, other) 3255 object.__pow__(self, other[, modulo]) 3256 object.__lshift__(self, other) 3257 object.__rshift__(self, other) 3258 object.__and__(self, other) 3259 object.__xor__(self, other) 3260 object.__or__(self, other) 3261 3262 .. index:: 3263 pair: built-in function; divmod 3264 pair: built-in function; pow 3265 pair: built-in function; pow 3266 3267 These methods are called to implement the binary arithmetic operations 3268 (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, 3269 :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to 3270 evaluate the expression ``x + y``, where *x* is an instance of a class that 3271 has an :meth:`__add__` method, ``type(x).__add__(x, y)`` is called. The 3272 :meth:`__divmod__` method should be the equivalent to using 3273 :meth:`__floordiv__` and :meth:`__mod__`; it should not be related to 3274 :meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept 3275 an optional third argument if the ternary version of the built-in :func:`pow` 3276 function is to be supported. 3277 3278 If one of those methods does not support the operation with the supplied 3279 arguments, it should return :data:`NotImplemented`. 3280 3281 3282.. method:: object.__radd__(self, other) 3283 object.__rsub__(self, other) 3284 object.__rmul__(self, other) 3285 object.__rmatmul__(self, other) 3286 object.__rtruediv__(self, other) 3287 object.__rfloordiv__(self, other) 3288 object.__rmod__(self, other) 3289 object.__rdivmod__(self, other) 3290 object.__rpow__(self, other[, modulo]) 3291 object.__rlshift__(self, other) 3292 object.__rrshift__(self, other) 3293 object.__rand__(self, other) 3294 object.__rxor__(self, other) 3295 object.__ror__(self, other) 3296 3297 .. index:: 3298 pair: built-in function; divmod 3299 pair: built-in function; pow 3300 3301 These methods are called to implement the binary arithmetic operations 3302 (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, 3303 :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected 3304 (swapped) operands. These functions are only called if the left operand does 3305 not support the corresponding operation [#]_ and the operands are of different 3306 types. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is 3307 an instance of a class that has an :meth:`__rsub__` method, 3308 ``type(y).__rsub__(y, x)`` is called if ``type(x).__sub__(x, y)`` returns 3309 :data:`NotImplemented`. 3310 3311 .. index:: pair: built-in function; pow 3312 3313 Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the 3314 coercion rules would become too complicated). 3315 3316 .. note:: 3317 3318 If the right operand's type is a subclass of the left operand's type and 3319 that subclass provides a different implementation of the reflected method 3320 for the operation, this method will be called before the left operand's 3321 non-reflected method. This behavior allows subclasses to override their 3322 ancestors' operations. 3323 3324 3325.. method:: object.__iadd__(self, other) 3326 object.__isub__(self, other) 3327 object.__imul__(self, other) 3328 object.__imatmul__(self, other) 3329 object.__itruediv__(self, other) 3330 object.__ifloordiv__(self, other) 3331 object.__imod__(self, other) 3332 object.__ipow__(self, other[, modulo]) 3333 object.__ilshift__(self, other) 3334 object.__irshift__(self, other) 3335 object.__iand__(self, other) 3336 object.__ixor__(self, other) 3337 object.__ior__(self, other) 3338 3339 These methods are called to implement the augmented arithmetic assignments 3340 (``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, 3341 ``>>=``, ``&=``, ``^=``, ``|=``). These methods should attempt to do the 3342 operation in-place (modifying *self*) and return the result (which could be, 3343 but does not have to be, *self*). If a specific method is not defined, or if 3344 that method returns :data:`NotImplemented`, the 3345 augmented assignment falls back to the normal methods. For instance, if *x* 3346 is an instance of a class with an :meth:`__iadd__` method, ``x += y`` is 3347 equivalent to ``x = x.__iadd__(y)`` . If :meth:`__iadd__` does not exist, or if ``x.__iadd__(y)`` 3348 returns :data:`!NotImplemented`, ``x.__add__(y)`` and 3349 ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``. In 3350 certain situations, augmented assignment can result in unexpected errors (see 3351 :ref:`faq-augmented-assignment-tuple-error`), but this behavior is in fact 3352 part of the data model. 3353 3354 3355.. method:: object.__neg__(self) 3356 object.__pos__(self) 3357 object.__abs__(self) 3358 object.__invert__(self) 3359 3360 .. index:: pair: built-in function; abs 3361 3362 Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs` 3363 and ``~``). 3364 3365 3366.. method:: object.__complex__(self) 3367 object.__int__(self) 3368 object.__float__(self) 3369 3370 .. index:: 3371 pair: built-in function; complex 3372 pair: built-in function; int 3373 pair: built-in function; float 3374 3375 Called to implement the built-in functions :func:`complex`, 3376 :func:`int` and :func:`float`. Should return a value 3377 of the appropriate type. 3378 3379 3380.. method:: object.__index__(self) 3381 3382 Called to implement :func:`operator.index`, and whenever Python needs to 3383 losslessly convert the numeric object to an integer object (such as in 3384 slicing, or in the built-in :func:`bin`, :func:`hex` and :func:`oct` 3385 functions). Presence of this method indicates that the numeric object is 3386 an integer type. Must return an integer. 3387 3388 If :meth:`__int__`, :meth:`__float__` and :meth:`__complex__` are not 3389 defined then corresponding built-in functions :func:`int`, :func:`float` 3390 and :func:`complex` fall back to :meth:`__index__`. 3391 3392 3393.. method:: object.__round__(self, [,ndigits]) 3394 object.__trunc__(self) 3395 object.__floor__(self) 3396 object.__ceil__(self) 3397 3398 .. index:: pair: built-in function; round 3399 3400 Called to implement the built-in function :func:`round` and :mod:`math` 3401 functions :func:`~math.trunc`, :func:`~math.floor` and :func:`~math.ceil`. 3402 Unless *ndigits* is passed to :meth:`!__round__` all these methods should 3403 return the value of the object truncated to an :class:`~numbers.Integral` 3404 (typically an :class:`int`). 3405 3406 The built-in function :func:`int` falls back to :meth:`__trunc__` if neither 3407 :meth:`__int__` nor :meth:`__index__` is defined. 3408 3409 .. versionchanged:: 3.11 3410 The delegation of :func:`int` to :meth:`__trunc__` is deprecated. 3411 3412 3413.. _context-managers: 3414 3415With Statement Context Managers 3416------------------------------- 3417 3418A :dfn:`context manager` is an object that defines the runtime context to be 3419established when executing a :keyword:`with` statement. The context manager 3420handles the entry into, and the exit from, the desired runtime context for the 3421execution of the block of code. Context managers are normally invoked using the 3422:keyword:`!with` statement (described in section :ref:`with`), but can also be 3423used by directly invoking their methods. 3424 3425.. index:: 3426 pair: statement; with 3427 single: context manager 3428 3429Typical uses of context managers include saving and restoring various kinds of 3430global state, locking and unlocking resources, closing opened files, etc. 3431 3432For more information on context managers, see :ref:`typecontextmanager`. 3433The :class:`object` class itself does not provide the context manager methods. 3434 3435 3436.. method:: object.__enter__(self) 3437 3438 Enter the runtime context related to this object. The :keyword:`with` statement 3439 will bind this method's return value to the target(s) specified in the 3440 :keyword:`!as` clause of the statement, if any. 3441 3442 3443.. method:: object.__exit__(self, exc_type, exc_value, traceback) 3444 3445 Exit the runtime context related to this object. The parameters describe the 3446 exception that caused the context to be exited. If the context was exited 3447 without an exception, all three arguments will be :const:`None`. 3448 3449 If an exception is supplied, and the method wishes to suppress the exception 3450 (i.e., prevent it from being propagated), it should return a true value. 3451 Otherwise, the exception will be processed normally upon exit from this method. 3452 3453 Note that :meth:`~object.__exit__` methods should not reraise the passed-in exception; 3454 this is the caller's responsibility. 3455 3456 3457.. seealso:: 3458 3459 :pep:`343` - The "with" statement 3460 The specification, background, and examples for the Python :keyword:`with` 3461 statement. 3462 3463 3464.. _class-pattern-matching: 3465 3466Customizing positional arguments in class pattern matching 3467---------------------------------------------------------- 3468 3469When using a class name in a pattern, positional arguments in the pattern are not 3470allowed by default, i.e. ``case MyClass(x, y)`` is typically invalid without special 3471support in ``MyClass``. To be able to use that kind of pattern, the class needs to 3472define a *__match_args__* attribute. 3473 3474.. data:: object.__match_args__ 3475 3476 This class variable can be assigned a tuple of strings. When this class is 3477 used in a class pattern with positional arguments, each positional argument will 3478 be converted into a keyword argument, using the corresponding value in 3479 *__match_args__* as the keyword. The absence of this attribute is equivalent to 3480 setting it to ``()``. 3481 3482For example, if ``MyClass.__match_args__`` is ``("left", "center", "right")`` that means 3483that ``case MyClass(x, y)`` is equivalent to ``case MyClass(left=x, center=y)``. Note 3484that the number of arguments in the pattern must be smaller than or equal to the number 3485of elements in *__match_args__*; if it is larger, the pattern match attempt will raise 3486a :exc:`TypeError`. 3487 3488.. versionadded:: 3.10 3489 3490.. seealso:: 3491 3492 :pep:`634` - Structural Pattern Matching 3493 The specification for the Python ``match`` statement. 3494 3495 3496.. _python-buffer-protocol: 3497 3498Emulating buffer types 3499---------------------- 3500 3501The :ref:`buffer protocol <bufferobjects>` provides a way for Python 3502objects to expose efficient access to a low-level memory array. This protocol 3503is implemented by builtin types such as :class:`bytes` and :class:`memoryview`, 3504and third-party libraries may define additional buffer types. 3505 3506While buffer types are usually implemented in C, it is also possible to 3507implement the protocol in Python. 3508 3509.. method:: object.__buffer__(self, flags) 3510 3511 Called when a buffer is requested from *self* (for example, by the 3512 :class:`memoryview` constructor). The *flags* argument is an integer 3513 representing the kind of buffer requested, affecting for example whether 3514 the returned buffer is read-only or writable. :class:`inspect.BufferFlags` 3515 provides a convenient way to interpret the flags. The method must return 3516 a :class:`memoryview` object. 3517 3518.. method:: object.__release_buffer__(self, buffer) 3519 3520 Called when a buffer is no longer needed. The *buffer* argument is a 3521 :class:`memoryview` object that was previously returned by 3522 :meth:`~object.__buffer__`. The method must release any resources associated 3523 with the buffer. This method should return ``None``. 3524 Buffer objects that do not need to perform any cleanup are not required 3525 to implement this method. 3526 3527.. versionadded:: 3.12 3528 3529.. seealso:: 3530 3531 :pep:`688` - Making the buffer protocol accessible in Python 3532 Introduces the Python ``__buffer__`` and ``__release_buffer__`` methods. 3533 3534 :class:`collections.abc.Buffer` 3535 ABC for buffer types. 3536 3537.. _special-lookup: 3538 3539Special method lookup 3540--------------------- 3541 3542For custom classes, implicit invocations of special methods are only guaranteed 3543to work correctly if defined on an object's type, not in the object's instance 3544dictionary. That behaviour is the reason why the following code raises an 3545exception:: 3546 3547 >>> class C: 3548 ... pass 3549 ... 3550 >>> c = C() 3551 >>> c.__len__ = lambda: 5 3552 >>> len(c) 3553 Traceback (most recent call last): 3554 File "<stdin>", line 1, in <module> 3555 TypeError: object of type 'C' has no len() 3556 3557The rationale behind this behaviour lies with a number of special methods such 3558as :meth:`~object.__hash__` and :meth:`~object.__repr__` that are implemented 3559by all objects, 3560including type objects. If the implicit lookup of these methods used the 3561conventional lookup process, they would fail when invoked on the type object 3562itself:: 3563 3564 >>> 1 .__hash__() == hash(1) 3565 True 3566 >>> int.__hash__() == hash(int) 3567 Traceback (most recent call last): 3568 File "<stdin>", line 1, in <module> 3569 TypeError: descriptor '__hash__' of 'int' object needs an argument 3570 3571Incorrectly attempting to invoke an unbound method of a class in this way is 3572sometimes referred to as 'metaclass confusion', and is avoided by bypassing 3573the instance when looking up special methods:: 3574 3575 >>> type(1).__hash__(1) == hash(1) 3576 True 3577 >>> type(int).__hash__(int) == hash(int) 3578 True 3579 3580In addition to bypassing any instance attributes in the interest of 3581correctness, implicit special method lookup generally also bypasses the 3582:meth:`~object.__getattribute__` method even of the object's metaclass:: 3583 3584 >>> class Meta(type): 3585 ... def __getattribute__(*args): 3586 ... print("Metaclass getattribute invoked") 3587 ... return type.__getattribute__(*args) 3588 ... 3589 >>> class C(object, metaclass=Meta): 3590 ... def __len__(self): 3591 ... return 10 3592 ... def __getattribute__(*args): 3593 ... print("Class getattribute invoked") 3594 ... return object.__getattribute__(*args) 3595 ... 3596 >>> c = C() 3597 >>> c.__len__() # Explicit lookup via instance 3598 Class getattribute invoked 3599 10 3600 >>> type(c).__len__(c) # Explicit lookup via type 3601 Metaclass getattribute invoked 3602 10 3603 >>> len(c) # Implicit lookup 3604 10 3605 3606Bypassing the :meth:`~object.__getattribute__` machinery in this fashion 3607provides significant scope for speed optimisations within the 3608interpreter, at the cost of some flexibility in the handling of 3609special methods (the special method *must* be set on the class 3610object itself in order to be consistently invoked by the interpreter). 3611 3612 3613.. index:: 3614 single: coroutine 3615 3616Coroutines 3617========== 3618 3619 3620Awaitable Objects 3621----------------- 3622 3623An :term:`awaitable` object generally implements an :meth:`~object.__await__` method. 3624:term:`Coroutine objects <coroutine>` returned from :keyword:`async def` functions 3625are awaitable. 3626 3627.. note:: 3628 3629 The :term:`generator iterator` objects returned from generators 3630 decorated with :func:`types.coroutine` 3631 are also awaitable, but they do not implement :meth:`~object.__await__`. 3632 3633.. method:: object.__await__(self) 3634 3635 Must return an :term:`iterator`. Should be used to implement 3636 :term:`awaitable` objects. For instance, :class:`asyncio.Future` implements 3637 this method to be compatible with the :keyword:`await` expression. 3638 The :class:`object` class itself is not awaitable and does not provide 3639 this method. 3640 3641 .. note:: 3642 3643 The language doesn't place any restriction on the type or value of the 3644 objects yielded by the iterator returned by ``__await__``, as this is 3645 specific to the implementation of the asynchronous execution framework 3646 (e.g. :mod:`asyncio`) that will be managing the :term:`awaitable` object. 3647 3648 3649.. versionadded:: 3.5 3650 3651.. seealso:: :pep:`492` for additional information about awaitable objects. 3652 3653 3654.. _coroutine-objects: 3655 3656Coroutine Objects 3657----------------- 3658 3659:term:`Coroutine objects <coroutine>` are :term:`awaitable` objects. 3660A coroutine's execution can be controlled by calling :meth:`~object.__await__` and 3661iterating over the result. When the coroutine has finished executing and 3662returns, the iterator raises :exc:`StopIteration`, and the exception's 3663:attr:`~StopIteration.value` attribute holds the return value. If the 3664coroutine raises an exception, it is propagated by the iterator. Coroutines 3665should not directly raise unhandled :exc:`StopIteration` exceptions. 3666 3667Coroutines also have the methods listed below, which are analogous to 3668those of generators (see :ref:`generator-methods`). However, unlike 3669generators, coroutines do not directly support iteration. 3670 3671.. versionchanged:: 3.5.2 3672 It is a :exc:`RuntimeError` to await on a coroutine more than once. 3673 3674 3675.. method:: coroutine.send(value) 3676 3677 Starts or resumes execution of the coroutine. If *value* is ``None``, 3678 this is equivalent to advancing the iterator returned by 3679 :meth:`~object.__await__`. If *value* is not ``None``, this method delegates 3680 to the :meth:`~generator.send` method of the iterator that caused 3681 the coroutine to suspend. The result (return value, 3682 :exc:`StopIteration`, or other exception) is the same as when 3683 iterating over the :meth:`!__await__` return value, described above. 3684 3685.. method:: coroutine.throw(value) 3686 coroutine.throw(type[, value[, traceback]]) 3687 3688 Raises the specified exception in the coroutine. This method delegates 3689 to the :meth:`~generator.throw` method of the iterator that caused 3690 the coroutine to suspend, if it has such a method. Otherwise, 3691 the exception is raised at the suspension point. The result 3692 (return value, :exc:`StopIteration`, or other exception) is the same as 3693 when iterating over the :meth:`~object.__await__` return value, described 3694 above. If the exception is not caught in the coroutine, it propagates 3695 back to the caller. 3696 3697 .. versionchanged:: 3.12 3698 3699 The second signature \(type\[, value\[, traceback\]\]\) is deprecated and 3700 may be removed in a future version of Python. 3701 3702.. method:: coroutine.close() 3703 3704 Causes the coroutine to clean itself up and exit. If the coroutine 3705 is suspended, this method first delegates to the :meth:`~generator.close` 3706 method of the iterator that caused the coroutine to suspend, if it 3707 has such a method. Then it raises :exc:`GeneratorExit` at the 3708 suspension point, causing the coroutine to immediately clean itself up. 3709 Finally, the coroutine is marked as having finished executing, even if 3710 it was never started. 3711 3712 Coroutine objects are automatically closed using the above process when 3713 they are about to be destroyed. 3714 3715.. _async-iterators: 3716 3717Asynchronous Iterators 3718---------------------- 3719 3720An *asynchronous iterator* can call asynchronous code in 3721its ``__anext__`` method. 3722 3723Asynchronous iterators can be used in an :keyword:`async for` statement. 3724 3725The :class:`object` class itself does not provide these methods. 3726 3727 3728.. method:: object.__aiter__(self) 3729 3730 Must return an *asynchronous iterator* object. 3731 3732.. method:: object.__anext__(self) 3733 3734 Must return an *awaitable* resulting in a next value of the iterator. Should 3735 raise a :exc:`StopAsyncIteration` error when the iteration is over. 3736 3737An example of an asynchronous iterable object:: 3738 3739 class Reader: 3740 async def readline(self): 3741 ... 3742 3743 def __aiter__(self): 3744 return self 3745 3746 async def __anext__(self): 3747 val = await self.readline() 3748 if val == b'': 3749 raise StopAsyncIteration 3750 return val 3751 3752.. versionadded:: 3.5 3753 3754.. versionchanged:: 3.7 3755 Prior to Python 3.7, :meth:`~object.__aiter__` could return an *awaitable* 3756 that would resolve to an 3757 :term:`asynchronous iterator <asynchronous iterator>`. 3758 3759 Starting with Python 3.7, :meth:`~object.__aiter__` must return an 3760 asynchronous iterator object. Returning anything else 3761 will result in a :exc:`TypeError` error. 3762 3763 3764.. _async-context-managers: 3765 3766Asynchronous Context Managers 3767----------------------------- 3768 3769An *asynchronous context manager* is a *context manager* that is able to 3770suspend execution in its ``__aenter__`` and ``__aexit__`` methods. 3771 3772Asynchronous context managers can be used in an :keyword:`async with` statement. 3773 3774The :class:`object` class itself does not provide these methods. 3775 3776.. method:: object.__aenter__(self) 3777 3778 Semantically similar to :meth:`~object.__enter__`, the only 3779 difference being that it must return an *awaitable*. 3780 3781.. method:: object.__aexit__(self, exc_type, exc_value, traceback) 3782 3783 Semantically similar to :meth:`~object.__exit__`, the only 3784 difference being that it must return an *awaitable*. 3785 3786An example of an asynchronous context manager class:: 3787 3788 class AsyncContextManager: 3789 async def __aenter__(self): 3790 await log('entering context') 3791 3792 async def __aexit__(self, exc_type, exc, tb): 3793 await log('exiting context') 3794 3795.. versionadded:: 3.5 3796 3797 3798.. rubric:: Footnotes 3799 3800.. [#] It *is* possible in some cases to change an object's type, under certain 3801 controlled conditions. It generally isn't a good idea though, since it can 3802 lead to some very strange behaviour if it is handled incorrectly. 3803 3804.. [#] The :meth:`~object.__hash__`, :meth:`~object.__iter__`, 3805 :meth:`~object.__reversed__`, :meth:`~object.__contains__`, 3806 :meth:`~object.__class_getitem__` and :meth:`~os.PathLike.__fspath__` 3807 methods have special handling for this. Others 3808 will still raise a :exc:`TypeError`, but may do so by relying on 3809 the behavior that ``None`` is not callable. 3810 3811.. [#] "Does not support" here means that the class has no such method, or 3812 the method returns :data:`NotImplemented`. Do not set the method to 3813 ``None`` if you want to force fallback to the right operand's reflected 3814 method—that will instead have the opposite effect of explicitly 3815 *blocking* such fallback. 3816 3817.. [#] For operands of the same type, it is assumed that if the non-reflected 3818 method -- such as :meth:`~object.__add__` -- fails then the overall 3819 operation is not 3820 supported, which is why the reflected method is not called. 3821