Debian Codegraph @

Doc/reference/datamodel.rst

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