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:`~type.__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 File objects implement common methods, listed below, to simplify usage in
1352 generic code. They are expected to be :ref:`context-managers`.
1353
1354 The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are
1355 initialized to file objects corresponding to the interpreter's standard
1356 input, output and error streams; they are all open in text mode and
1357 therefore follow the interface defined by the :class:`io.TextIOBase`
1358 abstract class.
1359
1360 .. method:: file.read(size=-1, /)
1361
1362 Retrieve up to *size* data from the file. As a convenience if *size* is
1363 unspecified or -1 retrieve all data available.
1364
1365 .. method:: file.write(data, /)
1366
1367 Store *data* to the file.
1368
1369 .. method:: file.close()
1370
1371 Flush any buffers and close the underlying file.
1372
1373
1374 Internal types
1375 --------------
1376
1377 .. index::
1378 single: internal type
1379 single: types, internal
1380
1381 A few types used internally by the interpreter are exposed to the user. Their
1382 definitions may change with future versions of the interpreter, but they are
1383 mentioned here for completeness.
1384
1385
1386 .. _code-objects:
1387
1388 Code objects
1389 ^^^^^^^^^^^^
1390
1391 .. index:: bytecode, object; code, code object
1392
1393 Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
1394 The difference between a code object and a function object is that the function
1395 object contains an explicit reference to the function's globals (the module in
1396 which it was defined), while a code object contains no context; also the default
1397 argument values are stored in the function object, not in the code object
1398 (because they represent values calculated at run-time). Unlike function
1399 objects, code objects are immutable and contain no references (directly or
1400 indirectly) to mutable objects.
1401
1402 .. index::
1403 single: co_argcount (code object attribute)
1404 single: co_posonlyargcount (code object attribute)
1405 single: co_kwonlyargcount (code object attribute)
1406 single: co_code (code object attribute)
1407 single: co_consts (code object attribute)
1408 single: co_filename (code object attribute)
1409 single: co_firstlineno (code object attribute)
1410 single: co_flags (code object attribute)
1411 single: co_lnotab (code object attribute)
1412 single: co_name (code object attribute)
1413 single: co_names (code object attribute)
1414 single: co_nlocals (code object attribute)
1415 single: co_stacksize (code object attribute)
1416 single: co_varnames (code object attribute)
1417 single: co_cellvars (code object attribute)
1418 single: co_freevars (code object attribute)
1419 single: co_qualname (code object attribute)
1420
1421 Special read-only attributes
1422 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1423
1424 .. list-table::
1425
1426 * - .. attribute:: codeobject.co_name
1427 - The function name
1428
1429 * - .. attribute:: codeobject.co_qualname
1430 - The fully qualified function name
1431
1432 .. versionadded:: 3.11
1433
1434 * - .. attribute:: codeobject.co_argcount
1435 - The total number of positional :term:`parameters <parameter>`
1436 (including positional-only parameters and parameters with default values)
1437 that the function has
1438
1439 * - .. attribute:: codeobject.co_posonlyargcount
1440 - The number of positional-only :term:`parameters <parameter>`
1441 (including arguments with default values) that the function has
1442
1443 * - .. attribute:: codeobject.co_kwonlyargcount
1444 - The number of keyword-only :term:`parameters <parameter>`
1445 (including arguments with default values) that the function has
1446
1447 * - .. attribute:: codeobject.co_nlocals
1448 - The number of :ref:`local variables <naming>` used by the function
1449 (including parameters)
1450
1451 * - .. attribute:: codeobject.co_varnames
1452 - A :class:`tuple` containing the names of the local variables in the
1453 function (starting with the parameter names)
1454
1455 * - .. attribute:: codeobject.co_cellvars
1456 - A :class:`tuple` containing the names of :ref:`local variables <naming>`
1457 that are referenced from at least one :term:`nested scope` inside the function
1458
1459 * - .. attribute:: codeobject.co_freevars
1460 - A :class:`tuple` containing the names of
1461 :term:`free (closure) variables <closure variable>` that a :term:`nested scope`
1462 references in an outer scope. See also :attr:`function.__closure__`.
1463
1464 Note: references to global and builtin names are *not* included.
1465
1466 * - .. attribute:: codeobject.co_code
1467 - A string representing the sequence of :term:`bytecode` instructions in
1468 the function
1469
1470 * - .. attribute:: codeobject.co_consts
1471 - A :class:`tuple` containing the literals used by the :term:`bytecode` in
1472 the function
1473
1474 * - .. attribute:: codeobject.co_names
1475 - A :class:`tuple` containing the names used by the :term:`bytecode` in
1476 the function
1477
1478 * - .. attribute:: codeobject.co_filename
1479 - The name of the file from which the code was compiled
1480
1481 * - .. attribute:: codeobject.co_firstlineno
1482 - The line number of the first line of the function
1483
1484 * - .. attribute:: codeobject.co_lnotab
1485 - A string encoding the mapping from :term:`bytecode` offsets to line
1486 numbers. For details, see the source code of the interpreter.
1487
1488 .. deprecated:: 3.12
1489 This attribute of code objects is deprecated, and may be removed in
1490 Python 3.15.
1491
1492 * - .. attribute:: codeobject.co_stacksize
1493 - The required stack size of the code object
1494
1495 * - .. attribute:: codeobject.co_flags
1496 - An :class:`integer <int>` encoding a number of flags for the
1497 interpreter.
1498
1499 .. index:: pair: object; generator
1500
1501 The following flag bits are defined for :attr:`~codeobject.co_flags`:
1502 bit ``0x04`` is set if
1503 the function uses the ``*arguments`` syntax to accept an arbitrary number of
1504 positional arguments; bit ``0x08`` is set if the function uses the
1505 ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set
1506 if the function is a generator. See :ref:`inspect-module-co-flags` for details
1507 on the semantics of each flags that might be present.
1508
1509 Future feature declarations (for example, ``from __future__ import division``) also use bits
1510 in :attr:`~codeobject.co_flags` to indicate whether a code object was compiled with a
1511 particular feature enabled. See :attr:`~__future__._Feature.compiler_flag`.
1512
1513 Other bits in :attr:`~codeobject.co_flags` are reserved for internal use.
1514
1515 .. index:: single: documentation string
1516
1517 If a code object represents a function, the first item in
1518 :attr:`~codeobject.co_consts` is
1519 the documentation string of the function, or ``None`` if undefined.
1520
1521 Methods on code objects
1522 ~~~~~~~~~~~~~~~~~~~~~~~
1523
1524 .. method:: codeobject.co_positions()
1525
1526 Returns an iterable over the source code positions of each :term:`bytecode`
1527 instruction in the code object.
1528
1529 The iterator returns :class:`tuple`\s containing the ``(start_line, end_line,
1530 start_column, end_column)``. The *i-th* tuple corresponds to the
1531 position of the source code that compiled to the *i-th* code unit.
1532 Column information is 0-indexed utf-8 byte offsets on the given source
1533 line.
1534
1535 This positional information can be missing. A non-exhaustive lists of
1536 cases where this may happen:
1537
1538 - Running the interpreter with :option:`-X` ``no_debug_ranges``.
1539 - Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``.
1540 - Position tuples corresponding to artificial instructions.
1541 - Line and column numbers that can't be represented due to
1542 implementation specific limitations.
1543
1544 When this occurs, some or all of the tuple elements can be
1545 :const:`None`.
1546
1547 .. versionadded:: 3.11
1548
1549 .. note::
1550 This feature requires storing column positions in code objects which may
1551 result in a small increase of disk usage of compiled Python files or
1552 interpreter memory usage. To avoid storing the extra information and/or
1553 deactivate printing the extra traceback information, the
1554 :option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES`
1555 environment variable can be used.
1556
1557 .. method:: codeobject.co_lines()
1558
1559 Returns an iterator that yields information about successive ranges of
1560 :term:`bytecode`\s. Each item yielded is a ``(start, end, lineno)``
1561 :class:`tuple`:
1562
1563 * ``start`` (an :class:`int`) represents the offset (inclusive) of the start
1564 of the :term:`bytecode` range
1565 * ``end`` (an :class:`int`) represents the offset (exclusive) of the end of
1566 the :term:`bytecode` range
1567 * ``lineno`` is an :class:`int` representing the line number of the
1568 :term:`bytecode` range, or ``None`` if the bytecodes in the given range
1569 have no line number
1570
1571 The items yielded will have the following properties:
1572
1573 * The first range yielded will have a ``start`` of 0.
1574 * The ``(start, end)`` ranges will be non-decreasing and consecutive. That
1575 is, for any pair of :class:`tuple`\s, the ``start`` of the second will be
1576 equal to the ``end`` of the first.
1577 * No range will be backwards: ``end >= start`` for all triples.
1578 * The last :class:`tuple` yielded will have ``end`` equal to the size of the
1579 :term:`bytecode`.
1580
1581 Zero-width ranges, where ``start == end``, are allowed. Zero-width ranges
1582 are used for lines that are present in the source code, but have been
1583 eliminated by the :term:`bytecode` compiler.
1584
1585 .. versionadded:: 3.10
1586
1587 .. seealso::
1588
1589 :pep:`626` - Precise line numbers for debugging and other tools.
1590 The PEP that introduced the :meth:`!co_lines` method.
1591
1592 .. method:: codeobject.replace(**kwargs)
1593
1594 Return a copy of the code object with new values for the specified fields.
1595
1596 Code objects are also supported by the generic function :func:`copy.replace`.
1597
1598 .. versionadded:: 3.8
1599
1600
1601 .. _frame-objects:
1602
1603 Frame objects
1604 ^^^^^^^^^^^^^
1605
1606 .. index:: pair: object; frame
1607
1608 Frame objects represent execution frames. They may occur in
1609 :ref:`traceback objects <traceback-objects>`,
1610 and are also passed to registered trace functions.
1611
1612 .. index::
1613 single: f_back (frame attribute)
1614 single: f_code (frame attribute)
1615 single: f_globals (frame attribute)
1616 single: f_locals (frame attribute)
1617 single: f_lasti (frame attribute)
1618 single: f_builtins (frame attribute)
1619
1620 Special read-only attributes
1621 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1622
1623 .. list-table::
1624
1625 * - .. attribute:: frame.f_back
1626 - Points to the previous stack frame (towards the caller),
1627 or ``None`` if this is the bottom stack frame
1628
1629 * - .. attribute:: frame.f_code
1630 - The :ref:`code object <code-objects>` being executed in this frame.
1631 Accessing this attribute raises an :ref:`auditing event <auditing>`
1632 ``object.__getattr__`` with arguments ``obj`` and ``"f_code"``.
1633
1634 * - .. attribute:: frame.f_locals
1635 - The mapping used by the frame to look up
1636 :ref:`local variables <naming>`.
1637 If the frame refers to an :term:`optimized scope`,
1638 this may return a write-through proxy object.
1639
1640 .. versionchanged:: 3.13
1641 Return a proxy for optimized scopes.
1642
1643 * - .. attribute:: frame.f_globals
1644 - The dictionary used by the frame to look up
1645 :ref:`global variables <naming>`
1646
1647 * - .. attribute:: frame.f_builtins
1648 - The dictionary used by the frame to look up
1649 :ref:`built-in (intrinsic) names <naming>`
1650
1651 * - .. attribute:: frame.f_lasti
1652 - The "precise instruction" of the frame object
1653 (this is an index into the :term:`bytecode` string of the
1654 :ref:`code object <code-objects>`)
1655
1656 .. index::
1657 single: f_trace (frame attribute)
1658 single: f_trace_lines (frame attribute)
1659 single: f_trace_opcodes (frame attribute)
1660 single: f_lineno (frame attribute)
1661
1662 Special writable attributes
1663 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1664
1665 .. list-table::
1666
1667 * - .. attribute:: frame.f_trace
1668 - If not ``None``, this is a function called for various events during
1669 code execution (this is used by debuggers). Normally an event is
1670 triggered for each new source line (see :attr:`~frame.f_trace_lines`).
1671
1672 * - .. attribute:: frame.f_trace_lines
1673 - Set this attribute to :const:`False` to disable triggering a tracing
1674 event for each source line.
1675
1676 * - .. attribute:: frame.f_trace_opcodes
1677 - Set this attribute to :const:`True` to allow per-opcode events to be
1678 requested. Note that this may lead to
1679 undefined interpreter behaviour if exceptions raised by the trace
1680 function escape to the function being traced.
1681
1682 * - .. attribute:: frame.f_lineno
1683 - The current line number of the frame -- writing to this
1684 from within a trace function jumps to the given line (only for the bottom-most
1685 frame). A debugger can implement a Jump command (aka Set Next Statement)
1686 by writing to this attribute.
1687
1688 Frame object methods
1689 ~~~~~~~~~~~~~~~~~~~~
1690
1691 Frame objects support one method:
1692
1693 .. method:: frame.clear()
1694
1695 This method clears all references to :ref:`local variables <naming>` held by the
1696 frame. Also, if the frame belonged to a :term:`generator`, the generator
1697 is finalized. This helps break reference cycles involving frame
1698 objects (for example when catching an :ref:`exception <bltin-exceptions>`
1699 and storing its :ref:`traceback <traceback-objects>` for later use).
1700
1701 :exc:`RuntimeError` is raised if the frame is currently executing
1702 or suspended.
1703
1704 .. versionadded:: 3.4
1705
1706 .. versionchanged:: 3.13
1707 Attempting to clear a suspended frame raises :exc:`RuntimeError`
1708 (as has always been the case for executing frames).
1709
1710
1711 .. _traceback-objects:
1712
1713 Traceback objects
1714 ^^^^^^^^^^^^^^^^^
1715
1716 .. index::
1717 pair: object; traceback
1718 pair: stack; trace
1719 pair: exception; handler
1720 pair: execution; stack
1721 single: exc_info (in module sys)
1722 single: last_traceback (in module sys)
1723 single: sys.exc_info
1724 single: sys.exception
1725 single: sys.last_traceback
1726
1727 Traceback objects represent the stack trace of an :ref:`exception <tut-errors>`.
1728 A traceback object
1729 is implicitly created when an exception occurs, and may also be explicitly
1730 created by calling :class:`types.TracebackType`.
1731
1732 .. versionchanged:: 3.7
1733 Traceback objects can now be explicitly instantiated from Python code.
1734
1735 For implicitly created tracebacks, when the search for an exception handler
1736 unwinds the execution stack, at each unwound level a traceback object is
1737 inserted in front of the current traceback. When an exception handler is
1738 entered, the stack trace is made available to the program. (See section
1739 :ref:`try`.) It is accessible as the third item of the
1740 tuple returned by :func:`sys.exc_info`, and as the
1741 :attr:`~BaseException.__traceback__` attribute
1742 of the caught exception.
1743
1744 When the program contains no suitable
1745 handler, the stack trace is written (nicely formatted) to the standard error
1746 stream; if the interpreter is interactive, it is also made available to the user
1747 as :data:`sys.last_traceback`.
1748
1749 For explicitly created tracebacks, it is up to the creator of the traceback
1750 to determine how the :attr:`~traceback.tb_next` attributes should be linked to
1751 form a full stack trace.
1752
1753 .. index::
1754 single: tb_frame (traceback attribute)
1755 single: tb_lineno (traceback attribute)
1756 single: tb_lasti (traceback attribute)
1757 pair: statement; try
1758
1759 Special read-only attributes:
1760
1761 .. list-table::
1762
1763 * - .. attribute:: traceback.tb_frame
1764 - Points to the execution :ref:`frame <frame-objects>` of the current
1765 level.
1766
1767 Accessing this attribute raises an
1768 :ref:`auditing event <auditing>` ``object.__getattr__`` with arguments
1769 ``obj`` and ``"tb_frame"``.
1770
1771 * - .. attribute:: traceback.tb_lineno
1772 - Gives the line number where the exception occurred
1773
1774 * - .. attribute:: traceback.tb_lasti
1775 - Indicates the "precise instruction".
1776
1777 The line number and last instruction in the traceback may differ from the
1778 line number of its :ref:`frame object <frame-objects>` if the exception
1779 occurred in a
1780 :keyword:`try` statement with no matching except clause or with a
1781 :keyword:`finally` clause.
1782
1783 .. index::
1784 single: tb_next (traceback attribute)
1785
1786 .. attribute:: traceback.tb_next
1787
1788 The special writable attribute :attr:`!tb_next` is the next level in the
1789 stack trace (towards the frame where the exception occurred), or ``None`` if
1790 there is no next level.
1791
1792 .. versionchanged:: 3.7
1793 This attribute is now writable
1794
1795
1796 Slice objects
1797 ^^^^^^^^^^^^^
1798
1799 .. index:: pair: built-in function; slice
1800
1801 Slice objects are used to represent slices for
1802 :meth:`~object.__getitem__`
1803 methods. They are also created by the built-in :func:`slice` function.
1804
1805 .. index::
1806 single: start (slice object attribute)
1807 single: stop (slice object attribute)
1808 single: step (slice object attribute)
1809
1810 Special read-only attributes: :attr:`~slice.start` is the lower bound;
1811 :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step
1812 value; each is ``None`` if omitted. These attributes can have any type.
1813
1814 Slice objects support one method:
1815
1816 .. method:: slice.indices(self, length)
1817
1818 This method takes a single integer argument *length* and computes
1819 information about the slice that the slice object would describe if
1820 applied to a sequence of *length* items. It returns a tuple of three
1821 integers; respectively these are the *start* and *stop* indices and the
1822 *step* or stride length of the slice. Missing or out-of-bounds indices
1823 are handled in a manner consistent with regular slices.
1824
1825
1826 Static method objects
1827 ^^^^^^^^^^^^^^^^^^^^^
1828
1829 Static method objects provide a way of defeating the transformation of function
1830 objects to method objects described above. A static method object is a wrapper
1831 around any other object, usually a user-defined method object. When a static
1832 method object is retrieved from a class or a class instance, the object actually
1833 returned is the wrapped object, which is not subject to any further
1834 transformation. Static method objects are also callable. Static method
1835 objects are created by the built-in :func:`staticmethod` constructor.
1836
1837
1838 Class method objects
1839 ^^^^^^^^^^^^^^^^^^^^
1840
1841 A class method object, like a static method object, is a wrapper around another
1842 object that alters the way in which that object is retrieved from classes and
1843 class instances. The behaviour of class method objects upon such retrieval is
1844 described above, under :ref:`"instance methods" <instance-methods>`. Class method objects are created
1845 by the built-in :func:`classmethod` constructor.
1846
1847
1848 .. _specialnames:
1849
1850 Special method names
1851 ====================
1852
1853 .. index::
1854 pair: operator; overloading
1855 single: __getitem__() (mapping object method)
1856
1857 A class can implement certain operations that are invoked by special syntax
1858 (such as arithmetic operations or subscripting and slicing) by defining methods
1859 with special names. This is Python's approach to :dfn:`operator overloading`,
1860 allowing classes to define their own behavior with respect to language
1861 operators. For instance, if a class defines a method named
1862 :meth:`~object.__getitem__`,
1863 and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
1864 to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an
1865 operation raise an exception when no appropriate method is defined (typically
1866 :exc:`AttributeError` or :exc:`TypeError`).
1867
1868 Setting a special method to ``None`` indicates that the corresponding
1869 operation is not available. For example, if a class sets
1870 :meth:`~object.__iter__` to ``None``, the class is not iterable, so calling
1871 :func:`iter` on its instances will raise a :exc:`TypeError` (without
1872 falling back to :meth:`~object.__getitem__`). [#]_
1873
1874 When implementing a class that emulates any built-in type, it is important that
1875 the emulation only be implemented to the degree that it makes sense for the
1876 object being modelled. For example, some sequences may work well with retrieval
1877 of individual elements, but extracting a slice may not make sense.
1878 (One example of this is the :ref:`NodeList <dom-nodelist-objects>` interface
1879 in the W3C's Document Object Model.)
1880
1881
1882 .. _customization:
1883
1884 Basic customization
1885 -------------------
1886
1887 .. method:: object.__new__(cls[, ...])
1888
1889 .. index:: pair: subclassing; immutable types
1890
1891 Called to create a new instance of class *cls*. :meth:`__new__` is a static
1892 method (special-cased so you need not declare it as such) that takes the class
1893 of which an instance was requested as its first argument. The remaining
1894 arguments are those passed to the object constructor expression (the call to the
1895 class). The return value of :meth:`__new__` should be the new object instance
1896 (usually an instance of *cls*).
1897
1898 Typical implementations create a new instance of the class by invoking the
1899 superclass's :meth:`__new__` method using ``super().__new__(cls[, ...])``
1900 with appropriate arguments and then modifying the newly created instance
1901 as necessary before returning it.
1902
1903 If :meth:`__new__` is invoked during object construction and it returns an
1904 instance of *cls*, then the new instance’s :meth:`__init__` method
1905 will be invoked like ``__init__(self[, ...])``, where *self* is the new instance
1906 and the remaining arguments are the same as were passed to the object constructor.
1907
1908 If :meth:`__new__` does not return an instance of *cls*, then the new instance's
1909 :meth:`__init__` method will not be invoked.
1910
1911 :meth:`__new__` is intended mainly to allow subclasses of immutable types (like
1912 int, str, or tuple) to customize instance creation. It is also commonly
1913 overridden in custom metaclasses in order to customize class creation.
1914
1915
1916 .. method:: object.__init__(self[, ...])
1917
1918 .. index:: pair: class; constructor
1919
1920 Called after the instance has been created (by :meth:`__new__`), but before
1921 it is returned to the caller. The arguments are those passed to the
1922 class constructor expression. If a base class has an :meth:`__init__`
1923 method, the derived class's :meth:`__init__` method, if any, must explicitly
1924 call it to ensure proper initialization of the base class part of the
1925 instance; for example: ``super().__init__([args...])``.
1926
1927 Because :meth:`__new__` and :meth:`__init__` work together in constructing
1928 objects (:meth:`__new__` to create it, and :meth:`__init__` to customize it),
1929 no non-``None`` value may be returned by :meth:`__init__`; doing so will
1930 cause a :exc:`TypeError` to be raised at runtime.
1931
1932
1933 .. method:: object.__del__(self)
1934
1935 .. index::
1936 single: destructor
1937 single: finalizer
1938 pair: statement; del
1939
1940 Called when the instance is about to be destroyed. This is also called a
1941 finalizer or (improperly) a destructor. If a base class has a
1942 :meth:`__del__` method, the derived class's :meth:`__del__` method,
1943 if any, must explicitly call it to ensure proper deletion of the base
1944 class part of the instance.
1945
1946 It is possible (though not recommended!) for the :meth:`__del__` method
1947 to postpone destruction of the instance by creating a new reference to
1948 it. This is called object *resurrection*. It is implementation-dependent
1949 whether :meth:`__del__` is called a second time when a resurrected object
1950 is about to be destroyed; the current :term:`CPython` implementation
1951 only calls it once.
1952
1953 It is not guaranteed that :meth:`__del__` methods are called for objects
1954 that still exist when the interpreter exits.
1955 :class:`weakref.finalize` provides a straightforward way to register
1956 a cleanup function to be called when an object is garbage collected.
1957
1958 .. note::
1959
1960 ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements
1961 the reference count for ``x`` by one, and the latter is only called when
1962 ``x``'s reference count reaches zero.
1963
1964 .. impl-detail::
1965 It is possible for a reference cycle to prevent the reference count
1966 of an object from going to zero. In this case, the cycle will be
1967 later detected and deleted by the :term:`cyclic garbage collector
1968 <garbage collection>`. A common cause of reference cycles is when
1969 an exception has been caught in a local variable. The frame's
1970 locals then reference the exception, which references its own
1971 traceback, which references the locals of all frames caught in the
1972 traceback.
1973
1974 .. seealso::
1975 Documentation for the :mod:`gc` module.
1976
1977 .. warning::
1978
1979 Due to the precarious circumstances under which :meth:`__del__` methods are
1980 invoked, exceptions that occur during their execution are ignored, and a warning
1981 is printed to ``sys.stderr`` instead. In particular:
1982
1983 * :meth:`__del__` can be invoked when arbitrary code is being executed,
1984 including from any arbitrary thread. If :meth:`__del__` needs to take
1985 a lock or invoke any other blocking resource, it may deadlock as
1986 the resource may already be taken by the code that gets interrupted
1987 to execute :meth:`__del__`.
1988
1989 * :meth:`__del__` can be executed during interpreter shutdown. As a
1990 consequence, the global variables it needs to access (including other
1991 modules) may already have been deleted or set to ``None``. Python
1992 guarantees that globals whose name begins with a single underscore
1993 are deleted from their module before other globals are deleted; if
1994 no other references to such globals exist, this may help in assuring
1995 that imported modules are still available at the time when the
1996 :meth:`__del__` method is called.
1997
1998
1999 .. index::
2000 single: repr() (built-in function); __repr__() (object method)
2001
2002 .. method:: object.__repr__(self)
2003
2004 Called by the :func:`repr` built-in function to compute the "official" string
2005 representation of an object. If at all possible, this should look like a
2006 valid Python expression that could be used to recreate an object with the
2007 same value (given an appropriate environment). If this is not possible, a
2008 string of the form ``<...some useful description...>`` should be returned.
2009 The return value must be a string object. If a class defines :meth:`__repr__`
2010 but not :meth:`__str__`, then :meth:`__repr__` is also used when an
2011 "informal" string representation of instances of that class is required.
2012
2013 This is typically used for debugging, so it is important that the representation
2014 is information-rich and unambiguous. A default implementation is provided by the
2015 :class:`object` class itself.
2016
2017 .. index::
2018 single: string; __str__() (object method)
2019 single: format() (built-in function); __str__() (object method)
2020 single: print() (built-in function); __str__() (object method)
2021
2022
2023 .. method:: object.__str__(self)
2024
2025 Called by :func:`str(object) <str>`, the default :meth:`__format__` implementation,
2026 and the built-in function :func:`print`, to compute the "informal" or nicely
2027 printable string representation of an object. The return value must be a
2028 :ref:`str <textseq>` object.
2029
2030 This method differs from :meth:`object.__repr__` in that there is no
2031 expectation that :meth:`__str__` return a valid Python expression: a more
2032 convenient or concise representation can be used.
2033
2034 The default implementation defined by the built-in type :class:`object`
2035 calls :meth:`object.__repr__`.
2036
2037 .. XXX what about subclasses of string?
2038
2039
2040 .. method:: object.__bytes__(self)
2041
2042 .. index:: pair: built-in function; bytes
2043
2044 Called by :ref:`bytes <func-bytes>` to compute a byte-string representation
2045 of an object. This should return a :class:`bytes` object. The :class:`object`
2046 class itself does not provide this method.
2047
2048 .. index::
2049 single: string; __format__() (object method)
2050 pair: string; conversion
2051 pair: built-in function; print
2052
2053
2054 .. method:: object.__format__(self, format_spec)
2055
2056 Called by the :func:`format` built-in function,
2057 and by extension, evaluation of :ref:`formatted string literals
2058 <f-strings>` and the :meth:`str.format` method, to produce a "formatted"
2059 string representation of an object. The *format_spec* argument is
2060 a string that contains a description of the formatting options desired.
2061 The interpretation of the *format_spec* argument is up to the type
2062 implementing :meth:`__format__`, however most classes will either
2063 delegate formatting to one of the built-in types, or use a similar
2064 formatting option syntax.
2065
2066 See :ref:`formatspec` for a description of the standard formatting syntax.
2067
2068 The return value must be a string object.
2069
2070 The default implementation by the :class:`object` class should be given
2071 an empty *format_spec* string. It delegates to :meth:`__str__`.
2072
2073 .. versionchanged:: 3.4
2074 The __format__ method of ``object`` itself raises a :exc:`TypeError`
2075 if passed any non-empty string.
2076
2077 .. versionchanged:: 3.7
2078 ``object.__format__(x, '')`` is now equivalent to ``str(x)`` rather
2079 than ``format(str(x), '')``.
2080
2081
2082 .. _richcmpfuncs:
2083 .. method:: object.__lt__(self, other)
2084 object.__le__(self, other)
2085 object.__eq__(self, other)
2086 object.__ne__(self, other)
2087 object.__gt__(self, other)
2088 object.__ge__(self, other)
2089
2090 .. index::
2091 single: comparisons
2092
2093 These are the so-called "rich comparison" methods. The correspondence between
2094 operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``,
2095 ``x<=y`` calls ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls
2096 ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls
2097 ``x.__ge__(y)``.
2098
2099 A rich comparison method may return the singleton :data:`NotImplemented` if it does
2100 not implement the operation for a given pair of arguments. By convention,
2101 ``False`` and ``True`` are returned for a successful comparison. However, these
2102 methods can return any value, so if the comparison operator is used in a Boolean
2103 context (e.g., in the condition of an ``if`` statement), Python will call
2104 :func:`bool` on the value to determine if the result is true or false.
2105
2106 By default, ``object`` implements :meth:`__eq__` by using ``is``, returning
2107 :data:`NotImplemented` in the case of a false comparison:
2108 ``True if x is y else NotImplemented``. For :meth:`__ne__`, by default it
2109 delegates to :meth:`__eq__` and inverts the result unless it is
2110 :data:`!NotImplemented`. There are no other implied relationships among the
2111 comparison operators or default implementations; for example, the truth of
2112 ``(x<y or x==y)`` does not imply ``x<=y``. To automatically generate ordering
2113 operations from a single root operation, see :deco:`functools.total_ordering`.
2114
2115 By default, the :class:`object` class provides implementations consistent
2116 with :ref:`expressions-value-comparisons`: equality compares according to
2117 object identity, and order comparisons raise :exc:`TypeError`. Each default
2118 method may generate these results directly, but may also return
2119 :data:`NotImplemented`.
2120
2121 See the paragraph on :meth:`__hash__` for
2122 some important notes on creating :term:`hashable` objects which support
2123 custom comparison operations and are usable as dictionary keys.
2124
2125 There are no swapped-argument versions of these methods (to be used when the
2126 left argument does not support the operation but the right argument does);
2127 rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection,
2128 :meth:`__le__` and :meth:`__ge__` are each other's reflection, and
2129 :meth:`__eq__` and :meth:`__ne__` are their own reflection.
2130 If the operands are of different types, and the right operand's type is
2131 a direct or indirect subclass of the left operand's type,
2132 the reflected method of the right operand has priority, otherwise
2133 the left operand's method has priority. Virtual subclassing is
2134 not considered.
2135
2136 When no appropriate method returns any value other than :data:`NotImplemented`, the
2137 ``==`` and ``!=`` operators will fall back to ``is`` and ``is not``, respectively.
2138
2139 .. method:: object.__hash__(self)
2140
2141 .. index::
2142 pair: object; dictionary
2143 pair: built-in function; hash
2144
2145 Called by built-in function :func:`hash` and for operations on members of
2146 hashed collections including :class:`set`, :class:`frozenset`, and
2147 :class:`dict`. The ``__hash__()`` method should return an integer. The only required
2148 property is that objects which compare equal have the same hash value; it is
2149 advised to mix together the hash values of the components of the object that
2150 also play a part in comparison of objects by packing them into a tuple and
2151 hashing the tuple. Example::
2152
2153 def __hash__(self):
2154 return hash((self.name, self.nick, self.color))
2155
2156 .. note::
2157
2158 :func:`hash` truncates the value returned from an object's custom
2159 :meth:`__hash__` method to the size of a :c:type:`Py_ssize_t`. This is
2160 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an
2161 object's :meth:`__hash__` must interoperate on builds of different bit
2162 sizes, be sure to check the width on all supported builds. An easy way
2163 to do this is with
2164 ``python -c "import sys; print(sys.hash_info.width)"``.
2165
2166 If a class does not define an :meth:`__eq__` method it should not define a
2167 :meth:`__hash__` operation either; if it defines :meth:`__eq__` but not
2168 :meth:`__hash__`, its instances will not be usable as items in hashable
2169 collections. If a class defines mutable objects and implements an
2170 :meth:`__eq__` method, it should not implement :meth:`__hash__`, since the
2171 implementation of :term:`hashable` collections requires that a key's hash value is
2172 immutable (if the object's hash value changes, it will be in the wrong hash
2173 bucket).
2174
2175 User-defined classes have :meth:`__eq__` and :meth:`__hash__` methods
2176 by default (inherited from the :class:`object` class); with them, all objects compare
2177 unequal (except with themselves) and ``x.__hash__()`` returns an appropriate
2178 value such that ``x == y`` implies both that ``x is y`` and ``hash(x) == hash(y)``.
2179
2180 A class that overrides :meth:`__eq__` and does not define :meth:`__hash__`
2181 will have its :meth:`__hash__` implicitly set to ``None``. When the
2182 :meth:`__hash__` method of a class is ``None``, instances of the class will
2183 raise an appropriate :exc:`TypeError` when a program attempts to retrieve
2184 their hash value, and will also be correctly identified as unhashable when
2185 checking ``isinstance(obj, collections.abc.Hashable)``.
2186
2187 If a class that overrides :meth:`__eq__` needs to retain the implementation
2188 of :meth:`__hash__` from a parent class, the interpreter must be told this
2189 explicitly by setting ``__hash__ = <ParentClass>.__hash__``.
2190
2191 If a class that does not override :meth:`__eq__` wishes to suppress hash
2192 support, it should include ``__hash__ = None`` in the class definition.
2193 A class which defines its own :meth:`__hash__` that explicitly raises
2194 a :exc:`TypeError` would be incorrectly identified as hashable by
2195 an ``isinstance(obj, collections.abc.Hashable)`` call.
2196
2197
2198 .. note::
2199
2200 By default, the :meth:`__hash__` values of str and bytes objects are
2201 "salted" with an unpredictable random value. Although they
2202 remain constant within an individual Python process, they are not
2203 predictable between repeated invocations of Python.
2204
2205 This is intended to provide protection against a denial-of-service caused
2206 by carefully chosen inputs that exploit the worst case performance of a
2207 dict insertion, *O*\ (*n*\ :sup:`2`) complexity. See
2208 https://ocert.org/advisories/ocert-2011-003.html for details.
2209
2210 Changing hash values affects the iteration order of sets.
2211 Python has never made guarantees about this ordering
2212 (and it typically varies between 32-bit and 64-bit builds).
2213
2214 See also :envvar:`PYTHONHASHSEED`.
2215
2216 .. versionchanged:: 3.3
2217 Hash randomization is enabled by default.
2218
2219
2220 .. method:: object.__bool__(self)
2221
2222 .. index:: single: __len__() (mapping object method)
2223
2224 Called to implement truth value testing and the built-in operation
2225 ``bool()``; should return ``False`` or ``True``. When this method is not
2226 defined, :meth:`~object.__len__` is called, if it is defined, and the object is
2227 considered true if its result is nonzero. If a class defines neither
2228 :meth:`!__len__` nor :meth:`!__bool__` (which is true of the :class:`object`
2229 class itself), all its instances are considered true.
2230
2231
2232 .. _attribute-access:
2233
2234 Customizing attribute access
2235 ----------------------------
2236
2237 The following methods can be defined to customize the meaning of attribute
2238 access (use of, assignment to, or deletion of ``x.name``) for class instances.
2239
2240 .. XXX explain how descriptors interfere here!
2241
2242
2243 .. method:: object.__getattr__(self, name)
2244
2245 Called when the default attribute access fails with an :exc:`AttributeError`
2246 (either :meth:`__getattribute__` raises an :exc:`AttributeError` because
2247 *name* is not an instance attribute or an attribute in the class tree
2248 for ``self``; or :meth:`__get__` of a *name* property raises
2249 :exc:`AttributeError`). This method should either return the (computed)
2250 attribute value or raise an :exc:`AttributeError` exception.
2251 The :class:`object` class itself does not provide this method.
2252
2253 Note that if the attribute is found through the normal mechanism,
2254 :meth:`__getattr__` is not called. (This is an intentional asymmetry between
2255 :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
2256 reasons and because otherwise :meth:`__getattr__` would have no way to access
2257 other attributes of the instance. Note that at least for instance variables,
2258 you can take total control by not inserting any values in the instance attribute
2259 dictionary (but instead inserting them in another object). See the
2260 :meth:`__getattribute__` method below for a way to actually get total control
2261 over attribute access.
2262
2263
2264 .. method:: object.__getattribute__(self, name)
2265
2266 Called unconditionally to implement attribute accesses for instances of the
2267 class. If the class also defines :meth:`__getattr__`, the latter will not be
2268 called unless :meth:`__getattribute__` either calls it explicitly or raises an
2269 :exc:`AttributeError`. This method should return the (computed) attribute value
2270 or raise an :exc:`AttributeError` exception. In order to avoid infinite
2271 recursion in this method, its implementation should always call the base class
2272 method with the same name to access any attributes it needs, for example,
2273 ``object.__getattribute__(self, name)``.
2274
2275 .. note::
2276
2277 This method may still be bypassed when looking up special methods as the
2278 result of implicit invocation via language syntax or
2279 :ref:`built-in functions <builtin-functions>`.
2280 See :ref:`special-lookup`.
2281
2282 .. audit-event:: object.__getattr__ obj,name object.__getattribute__
2283
2284 For certain sensitive attribute accesses, raises an
2285 :ref:`auditing event <auditing>` ``object.__getattr__`` with arguments
2286 ``obj`` and ``name``.
2287
2288
2289 .. method:: object.__setattr__(self, name, value)
2290
2291 Called when an attribute assignment is attempted. This is called instead of
2292 the normal mechanism (i.e. store the value in the instance dictionary).
2293 *name* is the attribute name, *value* is the value to be assigned to it.
2294
2295 If :meth:`__setattr__` wants to assign to an instance attribute, it should
2296 call the base class method with the same name, for example,
2297 ``object.__setattr__(self, name, value)``.
2298
2299 .. audit-event:: object.__setattr__ obj,name,value object.__setattr__
2300
2301 For certain sensitive attribute assignments, raises an
2302 :ref:`auditing event <auditing>` ``object.__setattr__`` with arguments
2303 ``obj``, ``name``, ``value``.
2304
2305
2306 .. method:: object.__delattr__(self, name)
2307
2308 Like :meth:`__setattr__` but for attribute deletion instead of assignment. This
2309 should only be implemented if ``del obj.name`` is meaningful for the object.
2310
2311 .. audit-event:: object.__delattr__ obj,name object.__delattr__
2312
2313 For certain sensitive attribute deletions, raises an
2314 :ref:`auditing event <auditing>` ``object.__delattr__`` with arguments
2315 ``obj`` and ``name``.
2316
2317
2318 .. method:: object.__dir__(self)
2319
2320 Called when :func:`dir` is called on the object. An iterable must be
2321 returned. :func:`dir` converts the returned iterable to a list and sorts it.
2322
2323
2324 Customizing module attribute access
2325 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2326
2327 .. index::
2328 single: __getattr__ (module attribute)
2329 single: __dir__ (module attribute)
2330 single: __class__ (module attribute)
2331
2332 .. method:: module.__getattr__
2333 module.__dir__
2334
2335 Special names ``__getattr__`` and ``__dir__`` can be also used to customize
2336 access to module attributes. The ``__getattr__`` function at the module level
2337 should accept one argument which is the name of an attribute and return the
2338 computed value or raise an :exc:`AttributeError`. If an attribute is
2339 not found on a module object through the normal lookup, i.e.
2340 :meth:`object.__getattribute__`, then ``__getattr__`` is searched in
2341 the module ``__dict__`` before raising an :exc:`AttributeError`. If found,
2342 it is called with the attribute name and the result is returned.
2343
2344 The ``__dir__`` function should accept no arguments, and return an iterable of
2345 strings that represents the names accessible on module. If present, this
2346 function overrides the standard :func:`dir` search on a module.
2347
2348 .. attribute:: module.__class__
2349
2350 For a more fine grained customization of the module behavior (setting
2351 attributes, properties, etc.), one can set the ``__class__`` attribute of
2352 a module object to a subclass of :class:`types.ModuleType`. For example::
2353
2354 import sys
2355 from types import ModuleType
2356
2357 class VerboseModule(ModuleType):
2358 def __repr__(self):
2359 return f'Verbose {self.__name__}'
2360
2361 def __setattr__(self, attr, value):
2362 print(f'Setting {attr}...')
2363 super().__setattr__(attr, value)
2364
2365 sys.modules[__name__].__class__ = VerboseModule
2366
2367 .. note::
2368 Defining module ``__getattr__`` and setting module ``__class__`` only
2369 affect lookups made using the attribute access syntax -- directly accessing
2370 the module globals (whether by code within the module, or via a reference
2371 to the module's globals dictionary) is unaffected.
2372
2373 .. versionchanged:: 3.5
2374 ``__class__`` module attribute is now writable.
2375
2376 .. versionadded:: 3.7
2377 ``__getattr__`` and ``__dir__`` module attributes.
2378
2379 .. seealso::
2380
2381 :pep:`562` - Module __getattr__ and __dir__
2382 Describes the ``__getattr__`` and ``__dir__`` functions on modules.
2383
2384
2385 .. _descriptors:
2386
2387 Implementing Descriptors
2388 ^^^^^^^^^^^^^^^^^^^^^^^^
2389
2390 The following methods only apply when an instance of the class containing the
2391 method (a so-called *descriptor* class) appears in an *owner* class (the
2392 descriptor must be in either the owner's class dictionary or in the class
2393 dictionary for one of its parents). In the examples below, "the attribute"
2394 refers to the attribute whose name is the key of the property in the owner
2395 class' :attr:`~object.__dict__`. The :class:`object` class itself does not
2396 implement any of these protocols.
2397
2398 .. method:: object.__get__(self, instance, owner=None)
2399
2400 Called to get the attribute of the owner class (class attribute access) or
2401 of an instance of that class (instance attribute access). The optional
2402 *owner* argument is the owner class, while *instance* is the instance that
2403 the attribute was accessed through, or ``None`` when the attribute is
2404 accessed through the *owner*.
2405
2406 This method should return the computed attribute value or raise an
2407 :exc:`AttributeError` exception.
2408
2409 :PEP:`252` specifies that :meth:`__get__` is callable with one or two
2410 arguments. Python's own built-in descriptors support this specification;
2411 however, it is likely that some third-party tools have descriptors
2412 that require both arguments. Python's own :meth:`__getattribute__`
2413 implementation always passes in both arguments whether they are required
2414 or not.
2415
2416 .. method:: object.__set__(self, instance, value)
2417
2418 Called to set the attribute on an instance *instance* of the owner class to a
2419 new value, *value*.
2420
2421 Note, adding :meth:`__set__` or :meth:`__delete__` changes the kind of
2422 descriptor to a "data descriptor". See :ref:`descriptor-invocation` for
2423 more details.
2424
2425 .. method:: object.__delete__(self, instance)
2426
2427 Called to delete the attribute on an instance *instance* of the owner class.
2428
2429 Instances of descriptors may also have the :attr:`!__objclass__` attribute
2430 present:
2431
2432 .. attribute:: object.__objclass__
2433
2434 The attribute :attr:`!__objclass__` is interpreted by the :mod:`inspect` module
2435 as specifying the class where this object was defined (setting this
2436 appropriately can assist in runtime introspection of dynamic class attributes).
2437 For callables, it may indicate that an instance of the given type (or a
2438 subclass) is expected or required as the first positional argument (for example,
2439 CPython sets this attribute for unbound methods that are implemented in C).
2440
2441
2442 .. _descriptor-invocation:
2443
2444 Invoking Descriptors
2445 ^^^^^^^^^^^^^^^^^^^^
2446
2447 In general, a descriptor is an object attribute with "binding behavior", one
2448 whose attribute access has been overridden by methods in the descriptor
2449 protocol: :meth:`~object.__get__`, :meth:`~object.__set__`, and
2450 :meth:`~object.__delete__`. If any of
2451 those methods are defined for an object, it is said to be a descriptor.
2452
2453 The default behavior for attribute access is to get, set, or delete the
2454 attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain
2455 starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and
2456 continuing through the base classes of ``type(a)`` excluding metaclasses.
2457
2458 However, if the looked-up value is an object defining one of the descriptor
2459 methods, then Python may override the default behavior and invoke the descriptor
2460 method instead. Where this occurs in the precedence chain depends on which
2461 descriptor methods were defined and how they were called.
2462
2463 The starting point for descriptor invocation is a binding, ``a.x``. How the
2464 arguments are assembled depends on ``a``:
2465
2466 Direct Call
2467 The simplest and least common call is when user code directly invokes a
2468 descriptor method: ``x.__get__(a)``.
2469
2470 Instance Binding
2471 If binding to an object instance, ``a.x`` is transformed into the call:
2472 ``type(a).__dict__['x'].__get__(a, type(a))``.
2473
2474 Class Binding
2475 If binding to a class, ``A.x`` is transformed into the call:
2476 ``A.__dict__['x'].__get__(None, A)``.
2477
2478 Super Binding
2479 A dotted lookup such as ``super(A, a).x`` searches
2480 ``a.__class__.__mro__`` for a base class ``B`` following ``A`` and then
2481 returns ``B.__dict__['x'].__get__(a, A)``. If not a descriptor, ``x`` is
2482 returned unchanged.
2483
2484 .. testcode::
2485 :hide:
2486
2487 class Desc:
2488 def __get__(*args):
2489 return args
2490
2491 class B:
2492
2493 x = Desc()
2494
2495 class A(B):
2496
2497 x = 999
2498
2499 def m(self):
2500 'Demonstrate these two descriptor invocations are equivalent'
2501 result1 = super(A, self).x
2502 result2 = B.__dict__['x'].__get__(self, A)
2503 return result1 == result2
2504
2505 .. doctest::
2506 :hide:
2507
2508 >>> a = A()
2509 >>> a.__class__.__mro__.index(B) > a.__class__.__mro__.index(A)
2510 True
2511 >>> super(A, a).x == B.__dict__['x'].__get__(a, A)
2512 True
2513 >>> a.m()
2514 True
2515
2516 For instance bindings, the precedence of descriptor invocation depends on
2517 which descriptor methods are defined. A descriptor can define any combination
2518 of :meth:`~object.__get__`, :meth:`~object.__set__` and
2519 :meth:`~object.__delete__`. If it does not
2520 define :meth:`!__get__`, then accessing the attribute will return the descriptor
2521 object itself unless there is a value in the object's instance dictionary. If
2522 the descriptor defines :meth:`!__set__` and/or :meth:`!__delete__`, it is a data
2523 descriptor; if it defines neither, it is a non-data descriptor. Normally, data
2524 descriptors define both :meth:`!__get__` and :meth:`!__set__`, while non-data
2525 descriptors have just the :meth:`!__get__` method. Data descriptors with
2526 :meth:`!__get__` and :meth:`!__set__` (and/or :meth:`!__delete__`) defined
2527 always override a redefinition in an
2528 instance dictionary. In contrast, non-data descriptors can be overridden by
2529 instances.
2530
2531 Python methods (including those decorated with
2532 :deco:`staticmethod` and :deco:`classmethod`) are
2533 implemented as non-data descriptors. Accordingly, instances can redefine and
2534 override methods. This allows individual instances to acquire behaviors that
2535 differ from other instances of the same class.
2536
2537 The :deco:`property` decorator is implemented as a data descriptor. Accordingly,
2538 instances cannot override the behavior of a property.
2539
2540
2541 .. _slots:
2542
2543 __slots__
2544 ^^^^^^^^^
2545
2546 *__slots__* allow us to explicitly declare data members (like
2547 properties) and deny the creation of :attr:`~object.__dict__` and *__weakref__*
2548 (unless explicitly declared in *__slots__* or available in a parent.)
2549
2550 The space saved over using :attr:`~object.__dict__` can be significant.
2551 Attribute lookup speed can be significantly improved as well.
2552
2553 .. data:: object.__slots__
2554
2555 This class variable can be assigned a string, iterable, or sequence of
2556 strings with variable names used by instances. *__slots__* reserves space
2557 for the declared variables and prevents the automatic creation of
2558 :attr:`~object.__dict__`
2559 and *__weakref__* for each instance.
2560
2561
2562 .. _datamodel-note-slots:
2563
2564 Notes on using *__slots__*:
2565
2566 * When inheriting from a class without *__slots__*, the
2567 :attr:`~object.__dict__` and
2568 *__weakref__* attribute of the instances will always be accessible.
2569
2570 * Without a :attr:`~object.__dict__` variable, instances cannot be assigned new
2571 variables not
2572 listed in the *__slots__* definition. Attempts to assign to an unlisted
2573 variable name raises :exc:`AttributeError`. If dynamic assignment of new
2574 variables is desired, then add ``'__dict__'`` to the sequence of strings in
2575 the *__slots__* declaration.
2576
2577 * Without a *__weakref__* variable for each instance, classes defining
2578 *__slots__* do not support :mod:`weak references <weakref>` to its instances.
2579 If weak reference
2580 support is needed, then add ``'__weakref__'`` to the sequence of strings in the
2581 *__slots__* declaration.
2582
2583 * *__slots__* are implemented at the class level by creating :ref:`descriptors <descriptors>`
2584 for each variable name. As a result, class attributes
2585 cannot be used to set default values for instance variables defined by
2586 *__slots__*; otherwise, the class attribute would overwrite the descriptor
2587 assignment.
2588
2589 * The action of a *__slots__* declaration is not limited to the class
2590 where it is defined. *__slots__* declared in parents are available in
2591 child classes. However, instances of a child subclass will get a
2592 :attr:`~object.__dict__` and *__weakref__* unless the subclass also defines
2593 *__slots__* (which should only contain names of any *additional* slots).
2594
2595 * If a class defines a slot also defined in a base class, the instance variable
2596 defined by the base class slot is inaccessible (except by retrieving its
2597 descriptor directly from the base class). This renders the meaning of the
2598 program undefined. In the future, a check may be added to prevent this.
2599
2600 * :exc:`TypeError` will be raised if nonempty *__slots__* are defined for a
2601 class derived from a
2602 :c:member:`"variable-length" built-in type <PyTypeObject.tp_itemsize>` such as
2603 :class:`int`, :class:`bytes`, and :class:`tuple`.
2604
2605 * Any non-string :term:`iterable` may be assigned to *__slots__*.
2606
2607 * If a :class:`dictionary <dict>` is used to assign *__slots__*, the dictionary
2608 keys will be used as the slot names. The values of the dictionary can be used
2609 to provide per-attribute docstrings that will be recognised by
2610 :func:`inspect.getdoc` and displayed in the output of :func:`help`.
2611
2612 * :attr:`~object.__class__` assignment works only if both classes have the
2613 same *__slots__*.
2614
2615 * :ref:`Multiple inheritance <tut-multiple>` with multiple slotted parent
2616 classes can be used,
2617 but only one parent is allowed to have attributes created by slots
2618 (the other bases must have empty slot layouts) - violations raise
2619 :exc:`TypeError`.
2620
2621 * If an :term:`iterator` is used for *__slots__* then a :term:`descriptor` is
2622 created for each
2623 of the iterator's values. However, the *__slots__* attribute will be an empty
2624 iterator.
2625
2626 .. _class-customization:
2627
2628 Customizing class creation
2629 --------------------------
2630
2631 Whenever a class inherits from another class, :meth:`~object.__init_subclass__` is
2632 called on the parent class. This way, it is possible to write classes which
2633 change the behavior of subclasses. This is closely related to class
2634 decorators, but where class decorators only affect the specific class they're
2635 applied to, ``__init_subclass__`` solely applies to future subclasses of the
2636 class defining the method.
2637
2638 .. classmethod:: object.__init_subclass__(cls)
2639
2640 This method is called whenever the containing class is subclassed.
2641 *cls* is then the new subclass. If defined as a normal instance method,
2642 this method is implicitly converted to a class method.
2643
2644 Keyword arguments which are given to a new class are passed to
2645 the parent class's ``__init_subclass__``. For compatibility with
2646 other classes using ``__init_subclass__``, one should take out the
2647 needed keyword arguments and pass the others over to the base
2648 class, as in::
2649
2650 class Philosopher:
2651 def __init_subclass__(cls, /, default_name, **kwargs):
2652 super().__init_subclass__(**kwargs)
2653 cls.default_name = default_name
2654
2655 class AustralianPhilosopher(Philosopher, default_name="Bruce"):
2656 pass
2657
2658 The default implementation ``object.__init_subclass__`` does
2659 nothing, but raises an error if it is called with any arguments.
2660
2661 .. note::
2662
2663 The metaclass hint ``metaclass`` is consumed by the rest of the type
2664 machinery, and is never passed to ``__init_subclass__`` implementations.
2665 The actual metaclass (rather than the explicit hint) can be accessed as
2666 ``type(cls)``.
2667
2668 .. versionadded:: 3.6
2669
2670
2671 When a class is created, :meth:`!type.__new__` scans the class variables
2672 and makes callbacks to those with a :meth:`~object.__set_name__` hook.
2673
2674 .. method:: object.__set_name__(self, owner, name)
2675
2676 Automatically called at the time the owning class *owner* is
2677 created. The object has been assigned to *name* in that class::
2678
2679 class A:
2680 x = C() # Automatically calls: x.__set_name__(A, 'x')
2681
2682 If the class variable is assigned after the class is created,
2683 :meth:`__set_name__` will not be called automatically.
2684 If needed, :meth:`__set_name__` can be called directly::
2685
2686 class A:
2687 pass
2688
2689 c = C()
2690 A.x = c # The hook is not called
2691 c.__set_name__(A, 'x') # Manually invoke the hook
2692
2693 See :ref:`class-object-creation` for more details.
2694
2695 .. versionadded:: 3.6
2696
2697
2698 .. _metaclasses:
2699
2700 Metaclasses
2701 ^^^^^^^^^^^
2702
2703 .. index::
2704 single: metaclass
2705 pair: built-in function; type
2706 single: = (equals); class definition
2707
2708 By default, classes are constructed using :func:`type`. The class body is
2709 executed in a new namespace and the class name is bound locally to the
2710 result of ``type(name, bases, namespace)``.
2711
2712 The class creation process can be customized by passing the ``metaclass``
2713 keyword argument in the class definition line, or by inheriting from an
2714 existing class that included such an argument. In the following example,
2715 both ``MyClass`` and ``MySubclass`` are instances of ``Meta``::
2716
2717 class Meta(type):
2718 pass
2719
2720 class MyClass(metaclass=Meta):
2721 pass
2722
2723 class MySubclass(MyClass):
2724 pass
2725
2726 Any other keyword arguments that are specified in the class definition are
2727 passed through to all metaclass operations described below.
2728
2729 When a class definition is executed, the following steps occur:
2730
2731 * MRO entries are resolved;
2732 * the appropriate metaclass is determined;
2733 * the class namespace is prepared;
2734 * the class body is executed;
2735 * the class object is created.
2736
2737
2738 Resolving MRO entries
2739 ^^^^^^^^^^^^^^^^^^^^^
2740
2741 .. method:: object.__mro_entries__(self, bases)
2742
2743 If a base that appears in a class definition is not an instance of
2744 :class:`type`, then an :meth:`!__mro_entries__` method is searched on the base.
2745 If an :meth:`!__mro_entries__` method is found, the base is substituted with the
2746 result of a call to :meth:`!__mro_entries__` when creating the class.
2747 The method is called with the original bases tuple
2748 passed to the *bases* parameter, and must return a tuple
2749 of classes that will be used instead of the base. The returned tuple may be
2750 empty: in these cases, the original base is ignored.
2751
2752 .. seealso::
2753
2754 :func:`types.resolve_bases`
2755 Dynamically resolve bases that are not instances of :class:`type`.
2756
2757 :func:`types.get_original_bases`
2758 Retrieve a class's "original bases" prior to modifications by
2759 :meth:`~object.__mro_entries__`.
2760
2761 :pep:`560`
2762 Core support for typing module and generic types.
2763
2764
2765 Determining the appropriate metaclass
2766 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2767 .. index::
2768 single: metaclass hint
2769
2770 The appropriate metaclass for a class definition is determined as follows:
2771
2772 * if no bases and no explicit metaclass are given, then :func:`type` is used;
2773 * if an explicit metaclass is given and it is *not* an instance of
2774 :func:`type`, then it is used directly as the metaclass;
2775 * if an instance of :func:`type` is given as the explicit metaclass, or
2776 bases are defined, then the most derived metaclass is used.
2777
2778 The most derived metaclass is selected from the explicitly specified
2779 metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified
2780 base classes. The most derived metaclass is one which is a subtype of *all*
2781 of these candidate metaclasses. If none of the candidate metaclasses meets
2782 that criterion, then the class definition will fail with ``TypeError``.
2783
2784
2785 .. _prepare:
2786
2787 Preparing the class namespace
2788 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2789
2790 .. index::
2791 single: __prepare__ (metaclass method)
2792
2793 Once the appropriate metaclass has been identified, then the class namespace
2794 is prepared. If the metaclass has a ``__prepare__`` attribute, it is called
2795 as ``namespace = metaclass.__prepare__(name, bases, **kwds)`` (where the
2796 additional keyword arguments, if any, come from the class definition). The
2797 ``__prepare__`` method should be implemented as a
2798 :func:`classmethod <classmethod>`. The
2799 namespace returned by ``__prepare__`` is passed in to ``__new__``, but when
2800 the final class object is created the namespace is copied into a new ``dict``.
2801
2802 If the metaclass has no ``__prepare__`` attribute, then the class namespace
2803 is initialised as an empty ordered mapping.
2804
2805 .. seealso::
2806
2807 :pep:`3115` - Metaclasses in Python 3000
2808 Introduced the ``__prepare__`` namespace hook
2809
2810
2811 Executing the class body
2812 ^^^^^^^^^^^^^^^^^^^^^^^^
2813
2814 .. index::
2815 single: class; body
2816
2817 The class body is executed (approximately) as
2818 ``exec(body, globals(), namespace)``. The key difference from a normal
2819 call to :func:`exec` is that lexical scoping allows the class body (including
2820 any methods) to reference names from the current and outer scopes when the
2821 class definition occurs inside a function.
2822
2823 However, even when the class definition occurs inside the function, methods
2824 defined inside the class still cannot see names defined at the class scope.
2825 Class variables must be accessed through the first parameter of instance or
2826 class methods, or through the implicit lexically scoped ``__class__`` reference
2827 described in the next section.
2828
2829 .. _class-object-creation:
2830
2831 Creating the class object
2832 ^^^^^^^^^^^^^^^^^^^^^^^^^
2833
2834 .. index::
2835 single: __class__ (method cell)
2836 single: __classcell__ (class namespace entry)
2837
2838
2839 Once the class namespace has been populated by executing the class body,
2840 the class object is created by calling
2841 ``metaclass(name, bases, namespace, **kwds)`` (the additional keywords
2842 passed here are the same as those passed to ``__prepare__``).
2843
2844 This class object is the one that will be referenced by the zero-argument
2845 form of :func:`super`. ``__class__`` is an implicit closure reference
2846 created by the compiler if any methods in a class body refer to either
2847 ``__class__`` or ``super``. This allows the zero argument form of
2848 :func:`super` to correctly identify the class being defined based on
2849 lexical scoping, while the class or instance that was used to make the
2850 current call is identified based on the first argument passed to the method.
2851
2852 .. impl-detail::
2853
2854 In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass
2855 as a ``__classcell__`` entry in the class namespace. If present, this must
2856 be propagated up to the ``type.__new__`` call in order for the class to be
2857 initialised correctly.
2858 Failing to do so will result in a :exc:`RuntimeError` in Python 3.8.
2859
2860 When using the default metaclass :class:`type`, or any metaclass that ultimately
2861 calls ``type.__new__``, the following additional customization steps are
2862 invoked after creating the class object:
2863
2864 1) The ``type.__new__`` method collects all of the attributes in the class
2865 namespace that define a :meth:`~object.__set_name__` method;
2866 2) Those ``__set_name__`` methods are called with the class
2867 being defined and the assigned name of that particular attribute;
2868 3) The :meth:`~object.__init_subclass__` hook is called on the
2869 immediate parent of the new class in its method resolution order.
2870
2871 After the class object is created, it is passed to the class decorators
2872 included in the class definition (if any) and the resulting object is bound
2873 in the local namespace as the defined class.
2874
2875 When a new class is created by ``type.__new__``, the object provided as the
2876 namespace parameter is copied to a new ordered mapping and the original
2877 object is discarded. The new copy is wrapped in a read-only proxy, which
2878 becomes the :attr:`~type.__dict__` attribute of the class object.
2879
2880 .. seealso::
2881
2882 :pep:`3135` - New super
2883 Describes the implicit ``__class__`` closure reference
2884
2885
2886 Uses for metaclasses
2887 ^^^^^^^^^^^^^^^^^^^^
2888
2889 The potential uses for metaclasses are boundless. Some ideas that have been
2890 explored include enum, logging, interface checking, automatic delegation,
2891 automatic property creation, proxies, frameworks, and automatic resource
2892 locking/synchronization.
2893
2894
2895 Customizing instance and subclass checks
2896 ----------------------------------------
2897
2898 The following methods are used to override the default behavior of the
2899 :func:`isinstance` and :func:`issubclass` built-in functions.
2900
2901 In particular, the metaclass :class:`abc.ABCMeta` implements these methods in
2902 order to allow the addition of Abstract Base Classes (ABCs) as "virtual base
2903 classes" to any class or type (including built-in types), including other
2904 ABCs.
2905
2906 .. method:: type.__instancecheck__(self, instance)
2907
2908 Return true if *instance* should be considered a (direct or indirect)
2909 instance of *class*. If defined, called to implement ``isinstance(instance,
2910 class)``.
2911
2912
2913 .. method:: type.__subclasscheck__(self, subclass)
2914
2915 Return true if *subclass* should be considered a (direct or indirect)
2916 subclass of *class*. If defined, called to implement ``issubclass(subclass,
2917 class)``.
2918
2919
2920 Note that these methods are looked up on the type (metaclass) of a class. They
2921 cannot be defined as class methods in the actual class. This is consistent with
2922 the lookup of special methods that are called on instances, only in this
2923 case the instance is itself a class.
2924
2925 .. seealso::
2926
2927 :pep:`3119` - Introducing Abstract Base Classes
2928 Includes the specification for customizing :func:`isinstance` and
2929 :func:`issubclass` behavior through :meth:`~type.__instancecheck__` and
2930 :meth:`~type.__subclasscheck__`, with motivation for this functionality
2931 in the context of adding Abstract Base Classes (see the :mod:`abc`
2932 module) to the language.
2933
2934
2935 Emulating generic types
2936 -----------------------
2937
2938 When using :term:`type annotations<annotation>`, it is often useful to
2939 *parameterize* a :term:`generic type` using Python's square-brackets notation.
2940 For example, the annotation ``list[int]`` might be used to signify a
2941 :class:`list` in which all the elements are of type :class:`int`.
2942
2943 .. seealso::
2944
2945 :pep:`484` - Type Hints
2946 Introducing Python's framework for type annotations
2947
2948 :ref:`Generic Alias Types<types-genericalias>`
2949 Documentation for objects representing parameterized generic classes
2950
2951 :ref:`Generics`, :ref:`user-defined generics<user-defined-generics>` and :class:`typing.Generic`
2952 Documentation on how to implement generic classes that can be
2953 parameterized at runtime and understood by static type-checkers.
2954
2955 A class can *generally* only be parameterized if it defines the special
2956 class method ``__class_getitem__()``.
2957
2958 .. classmethod:: object.__class_getitem__(cls, key)
2959
2960 Return an object representing the specialization of a generic class
2961 by type arguments found in *key*.
2962
2963 When defined on a class, ``__class_getitem__()`` is automatically a class
2964 method. As such, there is no need for it to be decorated with
2965 :deco:`classmethod` when it is defined.
2966
2967
2968 The purpose of *__class_getitem__*
2969 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2970
2971 The purpose of :meth:`~object.__class_getitem__` is to allow runtime
2972 parameterization of standard-library generic classes in order to more easily
2973 apply :term:`type hints<type hint>` to these classes.
2974
2975 To implement custom generic classes that can be parameterized at runtime and
2976 understood by static type-checkers, users should either inherit from a standard
2977 library class that already implements :meth:`~object.__class_getitem__`, or
2978 inherit from :class:`typing.Generic`, which has its own implementation of
2979 ``__class_getitem__()``.
2980
2981 Custom implementations of :meth:`~object.__class_getitem__` on classes defined
2982 outside of the standard library may not be understood by third-party
2983 type-checkers such as mypy. Using ``__class_getitem__()`` on any class for
2984 purposes other than type hinting is discouraged.
2985
2986
2987 .. _classgetitem-versus-getitem:
2988
2989
2990 *__class_getitem__* versus *__getitem__*
2991 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2992
2993 Usually, the :ref:`subscription<subscriptions>` of an object using square
2994 brackets will call the :meth:`~object.__getitem__` instance method defined on
2995 the object's class. However, if the object being subscribed is itself a class,
2996 the class method :meth:`~object.__class_getitem__` may be called instead.
2997 ``__class_getitem__()`` should return a :ref:`GenericAlias<types-genericalias>`
2998 object if it is properly defined.
2999
3000 Presented with the :term:`expression` ``obj[x]``, the Python interpreter
3001 follows something like the following process to decide whether
3002 :meth:`~object.__getitem__` or :meth:`~object.__class_getitem__` should be
3003 called::
3004
3005 from inspect import isclass
3006
3007 def subscribe(obj, x):
3008 """Return the result of the expression 'obj[x]'"""
3009
3010 class_of_obj = type(obj)
3011
3012 # If the class of obj defines __getitem__,
3013 # call class_of_obj.__getitem__(obj, x)
3014 if hasattr(class_of_obj, '__getitem__'):
3015 return class_of_obj.__getitem__(obj, x)
3016
3017 # Else, if obj is a class and defines __class_getitem__,
3018 # call obj.__class_getitem__(x)
3019 elif isclass(obj) and hasattr(obj, '__class_getitem__'):
3020 return obj.__class_getitem__(x)
3021
3022 # Else, raise an exception
3023 else:
3024 raise TypeError(
3025 f"'{class_of_obj.__name__}' object is not subscriptable"
3026 )
3027
3028 In Python, all classes are themselves instances of other classes. The class of
3029 a class is known as that class's :term:`metaclass`, and most classes have the
3030 :class:`type` class as their metaclass. :class:`type` does not define
3031 :meth:`~object.__getitem__`, meaning that expressions such as ``list[int]``,
3032 ``dict[str, float]`` and ``tuple[str, bytes]`` all result in
3033 :meth:`~object.__class_getitem__` being called::
3034
3035 >>> # list has class "type" as its metaclass, like most classes:
3036 >>> type(list)
3037 <class 'type'>
3038 >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
3039 True
3040 >>> # "list[int]" calls "list.__class_getitem__(int)"
3041 >>> list[int]
3042 list[int]
3043 >>> # list.__class_getitem__ returns a GenericAlias object:
3044 >>> type(list[int])
3045 <class 'types.GenericAlias'>
3046
3047 However, if a class has a custom metaclass that defines
3048 :meth:`~object.__getitem__`, subscribing the class may result in different
3049 behaviour. An example of this can be found in the :mod:`enum` module::
3050
3051 >>> from enum import Enum
3052 >>> class Menu(Enum):
3053 ... """A breakfast menu"""
3054 ... SPAM = 'spam'
3055 ... BACON = 'bacon'
3056 ...
3057 >>> # Enum classes have a custom metaclass:
3058 >>> type(Menu)
3059 <class 'enum.EnumMeta'>
3060 >>> # EnumMeta defines __getitem__,
3061 >>> # so __class_getitem__ is not called,
3062 >>> # and the result is not a GenericAlias object:
3063 >>> Menu['SPAM']
3064 <Menu.SPAM: 'spam'>
3065 >>> type(Menu['SPAM'])
3066 <enum 'Menu'>
3067
3068
3069 .. seealso::
3070 :pep:`560` - Core Support for typing module and generic types
3071 Introducing :meth:`~object.__class_getitem__`, and outlining when a
3072 :ref:`subscription<subscriptions>` results in ``__class_getitem__()``
3073 being called instead of :meth:`~object.__getitem__`
3074
3075
3076 .. _callable-types:
3077
3078 Emulating callable objects
3079 --------------------------
3080
3081
3082 .. method:: object.__call__(self[, args...])
3083
3084 .. index:: pair: call; instance
3085
3086 Called when the instance is "called" as a function; if this method is defined,
3087 ``x(arg1, arg2, ...)`` roughly translates to ``type(x).__call__(x, arg1, ...)``.
3088 The :class:`object` class itself does not provide this method.
3089
3090
3091 .. _sequence-types:
3092
3093 Emulating container types
3094 -------------------------
3095
3096 The following methods can be defined to implement container objects. None of them
3097 are provided by the :class:`object` class itself. Containers usually are
3098 :term:`sequences <sequence>` (such as :class:`lists <list>` or
3099 :class:`tuples <tuple>`) or :term:`mappings <mapping>` (like
3100 :term:`dictionaries <dictionary>`),
3101 but can represent other containers as well. The first set of methods is used
3102 either to emulate a sequence or to emulate a mapping; the difference is that for
3103 a sequence, the allowable keys should be the integers *k* for which ``0 <= k <
3104 N`` where *N* is the length of the sequence, or :class:`slice` objects, which define a
3105 range of items. It is also recommended that mappings provide the methods
3106 :meth:`!keys`, :meth:`!values`, :meth:`!items`, :meth:`!get`, :meth:`!clear`,
3107 :meth:`!setdefault`, :meth:`!pop`, :meth:`!popitem`, :meth:`!copy`, and
3108 :meth:`!update` behaving similar to those for Python's standard :class:`dictionary <dict>`
3109 objects. The :mod:`collections.abc` module provides a
3110 :class:`~collections.abc.MutableMapping`
3111 :term:`abstract base class` to help create those methods from a base set of
3112 :meth:`~object.__getitem__`, :meth:`~object.__setitem__`,
3113 :meth:`~object.__delitem__`, and :meth:`!keys`.
3114
3115 Mutable sequences should provide methods
3116 :meth:`~sequence.append`, :meth:`~sequence.clear`, :meth:`~sequence.count`,
3117 :meth:`~sequence.extend`, :meth:`~sequence.index`, :meth:`~sequence.insert`,
3118 :meth:`~sequence.pop`, :meth:`~sequence.remove`, and :meth:`~sequence.reverse`,
3119 like Python standard :class:`list` objects.
3120 Finally, sequence types should implement addition (meaning concatenation) and
3121 multiplication (meaning repetition) by defining the methods
3122 :meth:`~object.__add__`, :meth:`~object.__radd__`, :meth:`~object.__iadd__`,
3123 :meth:`~object.__mul__`, :meth:`~object.__rmul__` and :meth:`~object.__imul__`
3124 described below; they should not define other numerical
3125 operators.
3126
3127 It is recommended that both mappings and sequences implement the
3128 :meth:`~object.__contains__` method to allow efficient use of the ``in``
3129 operator; for
3130 mappings, ``in`` should search the mapping's keys; for sequences, it should
3131 search through the values. It is further recommended that both mappings and
3132 sequences implement the :meth:`~object.__iter__` method to allow efficient iteration
3133 through the container; for mappings, :meth:`!__iter__` should iterate
3134 through the object's keys; for sequences, it should iterate through the values.
3135
3136 .. method:: object.__len__(self)
3137
3138 .. index::
3139 pair: built-in function; len
3140 single: __bool__() (object method)
3141
3142 Called to implement the built-in function :func:`len`. Should return the length
3143 of the object, an integer ``>=`` 0. Also, an object that doesn't define a
3144 :meth:`~object.__bool__` method and whose :meth:`!__len__` method returns zero is
3145 considered to be false in a Boolean context.
3146
3147 .. impl-detail::
3148
3149 In CPython, the length is required to be at most :data:`sys.maxsize`.
3150 If the length is larger than :data:`!sys.maxsize` some features (such as
3151 :func:`len`) may raise :exc:`OverflowError`. To prevent raising
3152 :exc:`!OverflowError` by truth value testing, an object must define a
3153 :meth:`~object.__bool__` method.
3154
3155
3156 .. method:: object.__length_hint__(self)
3157
3158 Called to implement :func:`operator.length_hint`. Should return an estimated
3159 length for the object (which may be greater or less than the actual length).
3160 The length must be an integer ``>=`` 0. The return value may also be
3161 :data:`NotImplemented`, which is treated the same as if the
3162 ``__length_hint__`` method didn't exist at all. This method is purely an
3163 optimization and is never required for correctness.
3164
3165 .. versionadded:: 3.4
3166
3167
3168 .. index:: pair: object; slice
3169
3170 .. note::
3171
3172 Slicing is done exclusively with the following three methods. A call like ::
3173
3174 a[1:2] = b
3175
3176 is translated to ::
3177
3178 a[slice(1, 2, None)] = b
3179
3180 and so forth. Missing slice items are always filled in with ``None``.
3181
3182
3183 .. method:: object.__getitem__(self, key)
3184
3185 Called to implement evaluation of ``self[key]``. For :term:`sequence` types,
3186 the accepted keys should be integers. Optionally, they may support
3187 :class:`slice` objects as well. Negative index support is also optional.
3188 If *key* is
3189 of an inappropriate type, :exc:`TypeError` may be raised; if *key* is a value
3190 outside the set of indexes for the sequence (after any special
3191 interpretation of negative values), :exc:`IndexError` should be raised. For
3192 :term:`mapping` types, if *key* is missing (not in the container),
3193 :exc:`KeyError` should be raised.
3194
3195 .. note::
3196
3197 :keyword:`for` loops expect that an :exc:`IndexError` will be raised for
3198 illegal indexes to allow proper detection of the end of the sequence.
3199
3200 .. note::
3201
3202 When :ref:`subscripting<subscriptions>` a *class*, the special
3203 class method :meth:`~object.__class_getitem__` may be called instead of
3204 ``__getitem__()``. See :ref:`classgetitem-versus-getitem` for more
3205 details.
3206
3207
3208 .. method:: object.__setitem__(self, key, value)
3209
3210 Called to implement assignment to ``self[key]``. Same note as for
3211 :meth:`__getitem__`. This should only be implemented for mappings if the
3212 objects support changes to the values for keys, or if new keys can be added, or
3213 for sequences if elements can be replaced. The same exceptions should be raised
3214 for improper *key* values as for the :meth:`__getitem__` method.
3215
3216
3217 .. method:: object.__delitem__(self, key)
3218
3219 Called to implement deletion of ``self[key]``. Same note as for
3220 :meth:`__getitem__`. This should only be implemented for mappings if the
3221 objects support removal of keys, or for sequences if elements can be removed
3222 from the sequence. The same exceptions should be raised for improper *key*
3223 values as for the :meth:`__getitem__` method.
3224
3225
3226 .. method:: object.__missing__(self, key)
3227
3228 Called by :class:`dict`\ .\ :meth:`__getitem__` to implement ``self[key]`` for dict subclasses
3229 when key is not in the dictionary.
3230
3231
3232 .. method:: object.__iter__(self)
3233
3234 This method is called when an :term:`iterator` is required for a container.
3235 This method should return a new iterator object that can iterate over all the
3236 objects in the container. For mappings, it should iterate over the keys of
3237 the container.
3238
3239
3240 .. method:: object.__reversed__(self)
3241
3242 Called (if present) by the :func:`reversed` built-in to implement
3243 reverse iteration. It should return a new iterator object that iterates
3244 over all the objects in the container in reverse order.
3245
3246 If the :meth:`__reversed__` method is not provided, the :func:`reversed`
3247 built-in will fall back to using the sequence protocol (:meth:`__len__` and
3248 :meth:`__getitem__`). Objects that support the sequence protocol should
3249 only provide :meth:`__reversed__` if they can provide an implementation
3250 that is more efficient than the one provided by :func:`reversed`.
3251
3252
3253 The membership test operators (:keyword:`in` and :keyword:`not in`) are normally
3254 implemented as an iteration through a container. However, container objects can
3255 supply the following special method with a more efficient implementation, which
3256 also does not require the object be iterable.
3257
3258 .. method:: object.__contains__(self, item)
3259
3260 Called to implement membership test operators. Should return true if *item*
3261 is in *self*, false otherwise. For mapping objects, this should consider the
3262 keys of the mapping rather than the values or the key-item pairs.
3263
3264 For objects that don't define :meth:`__contains__`, the membership test first
3265 tries iteration via :meth:`__iter__`, then the old sequence iteration
3266 protocol via :meth:`__getitem__`, see :ref:`this section in the language
3267 reference <membership-test-details>`.
3268
3269
3270 .. _numeric-types:
3271
3272 Emulating numeric types
3273 -----------------------
3274
3275 The following methods can be defined to emulate numeric objects. Methods
3276 corresponding to operations that are not supported by the particular kind of
3277 number implemented (e.g., bitwise operations for non-integral numbers) should be
3278 left undefined.
3279
3280
3281 .. method:: object.__add__(self, other)
3282 object.__sub__(self, other)
3283 object.__mul__(self, other)
3284 object.__matmul__(self, other)
3285 object.__truediv__(self, other)
3286 object.__floordiv__(self, other)
3287 object.__mod__(self, other)
3288 object.__divmod__(self, other)
3289 object.__pow__(self, other[, modulo])
3290 object.__lshift__(self, other)
3291 object.__rshift__(self, other)
3292 object.__and__(self, other)
3293 object.__xor__(self, other)
3294 object.__or__(self, other)
3295
3296 .. index::
3297 pair: built-in function; divmod
3298 pair: built-in function; pow
3299 pair: built-in function; pow
3300
3301 These methods are called to implement the binary arithmetic operations
3302 (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`,
3303 :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to
3304 evaluate the expression ``x + y``, where *x* is an instance of a class that
3305 has an :meth:`__add__` method, ``type(x).__add__(x, y)`` is called. The
3306 :meth:`__divmod__` method should be the equivalent to using
3307 :meth:`__floordiv__` and :meth:`__mod__`; it should not be related to
3308 :meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept
3309 an optional third argument if the ternary version of the built-in :func:`pow`
3310 function is to be supported.
3311
3312 If one of those methods does not support the operation with the supplied
3313 arguments, it should return :data:`NotImplemented`.
3314
3315
3316 .. method:: object.__radd__(self, other)
3317 object.__rsub__(self, other)
3318 object.__rmul__(self, other)
3319 object.__rmatmul__(self, other)
3320 object.__rtruediv__(self, other)
3321 object.__rfloordiv__(self, other)
3322 object.__rmod__(self, other)
3323 object.__rdivmod__(self, other)
3324 object.__rpow__(self, other[, modulo])
3325 object.__rlshift__(self, other)
3326 object.__rrshift__(self, other)
3327 object.__rand__(self, other)
3328 object.__rxor__(self, other)
3329 object.__ror__(self, other)
3330
3331 .. index::
3332 pair: built-in function; divmod
3333 pair: built-in function; pow
3334
3335 These methods are called to implement the binary arithmetic operations
3336 (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`,
3337 :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected
3338 (swapped) operands. These functions are only called if the left operand does
3339 not support the corresponding operation [#]_ and the operands are of different
3340 types. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is
3341 an instance of a class that has an :meth:`__rsub__` method,
3342 ``type(y).__rsub__(y, x)`` is called if ``type(x).__sub__(x, y)`` returns
3343 :data:`NotImplemented`.
3344
3345 .. index:: pair: built-in function; pow
3346
3347 Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the
3348 coercion rules would become too complicated).
3349
3350 .. note::
3351
3352 If the right operand's type is a subclass of the left operand's type and
3353 that subclass provides a different implementation of the reflected method
3354 for the operation, this method will be called before the left operand's
3355 non-reflected method. This behavior allows subclasses to override their
3356 ancestors' operations.
3357
3358
3359 .. method:: object.__iadd__(self, other)
3360 object.__isub__(self, other)
3361 object.__imul__(self, other)
3362 object.__imatmul__(self, other)
3363 object.__itruediv__(self, other)
3364 object.__ifloordiv__(self, other)
3365 object.__imod__(self, other)
3366 object.__ipow__(self, other[, modulo])
3367 object.__ilshift__(self, other)
3368 object.__irshift__(self, other)
3369 object.__iand__(self, other)
3370 object.__ixor__(self, other)
3371 object.__ior__(self, other)
3372
3373 These methods are called to implement the augmented arithmetic assignments
3374 (``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``,
3375 ``>>=``, ``&=``, ``^=``, ``|=``). These methods should attempt to do the
3376 operation in-place (modifying *self*) and return the result (which could be,
3377 but does not have to be, *self*). If a specific method is not defined, or if
3378 that method returns :data:`NotImplemented`, the
3379 augmented assignment falls back to the normal methods. For instance, if *x*
3380 is an instance of a class with an :meth:`__iadd__` method, ``x += y`` is
3381 equivalent to ``x = x.__iadd__(y)`` . If :meth:`__iadd__` does not exist, or if ``x.__iadd__(y)``
3382 returns :data:`!NotImplemented`, ``x.__add__(y)`` and
3383 ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``. In
3384 certain situations, augmented assignment can result in unexpected errors (see
3385 :ref:`faq-augmented-assignment-tuple-error`), but this behavior is in fact
3386 part of the data model.
3387
3388
3389 .. method:: object.__neg__(self)
3390 object.__pos__(self)
3391 object.__abs__(self)
3392 object.__invert__(self)
3393
3394 .. index:: pair: built-in function; abs
3395
3396 Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs`
3397 and ``~``).
3398
3399
3400 .. method:: object.__complex__(self)
3401 object.__int__(self)
3402 object.__float__(self)
3403
3404 .. index::
3405 pair: built-in function; complex
3406 pair: built-in function; int
3407 pair: built-in function; float
3408
3409 Called to implement the built-in functions :func:`complex`,
3410 :func:`int` and :func:`float`. Should return a value
3411 of the appropriate type.
3412
3413
3414 .. method:: object.__index__(self)
3415
3416 Called to implement :func:`operator.index`, and whenever Python needs to
3417 losslessly convert the numeric object to an integer object (such as in
3418 slicing, or in the built-in :func:`bin`, :func:`hex` and :func:`oct`
3419 functions). Presence of this method indicates that the numeric object is
3420 an integer type. Must return an integer.
3421
3422 If :meth:`__int__`, :meth:`__float__` and :meth:`__complex__` are not
3423 defined then corresponding built-in functions :func:`int`, :func:`float`
3424 and :func:`complex` fall back to :meth:`__index__`.
3425
3426
3427 .. method:: object.__round__(self, [,ndigits])
3428 object.__trunc__(self)
3429 object.__floor__(self)
3430 object.__ceil__(self)
3431
3432 .. index:: pair: built-in function; round
3433
3434 Called to implement the built-in function :func:`round` and :mod:`math`
3435 functions :func:`~math.trunc`, :func:`~math.floor` and :func:`~math.ceil`.
3436 Unless *ndigits* is passed to :meth:`!__round__` all these methods should
3437 return the value of the object truncated to an :class:`~numbers.Integral`
3438 (typically an :class:`int`).
3439
3440 The built-in function :func:`int` falls back to :meth:`__trunc__` if neither
3441 :meth:`__int__` nor :meth:`__index__` is defined.
3442
3443 .. versionchanged:: 3.11
3444 The delegation of :func:`int` to :meth:`__trunc__` is deprecated.
3445
3446
3447 .. _context-managers:
3448
3449 With Statement Context Managers
3450 -------------------------------
3451
3452 A :dfn:`context manager` is an object that defines the runtime context to be
3453 established when executing a :keyword:`with` statement. The context manager
3454 handles the entry into, and the exit from, the desired runtime context for the
3455 execution of the block of code. Context managers are normally invoked using the
3456 :keyword:`!with` statement (described in section :ref:`with`), but can also be
3457 used by directly invoking their methods.
3458
3459 .. index::
3460 pair: statement; with
3461 single: context manager
3462
3463 Typical uses of context managers include saving and restoring various kinds of
3464 global state, locking and unlocking resources, closing opened files, etc.
3465
3466 For more information on context managers, see :ref:`typecontextmanager`.
3467 The :class:`object` class itself does not provide the context manager methods.
3468
3469
3470 .. method:: object.__enter__(self)
3471
3472 Enter the runtime context related to this object. The :keyword:`with` statement
3473 will bind this method's return value to the target(s) specified in the
3474 :keyword:`!as` clause of the statement, if any.
3475
3476
3477 .. method:: object.__exit__(self, exc_type, exc_value, traceback)
3478
3479 Exit the runtime context related to this object. The parameters describe the
3480 exception that caused the context to be exited. If the context was exited
3481 without an exception, all three arguments will be :const:`None`.
3482
3483 If an exception is supplied, and the method wishes to suppress the exception
3484 (i.e., prevent it from being propagated), it should return a true value.
3485 Otherwise, the exception will be processed normally upon exit from this method.
3486
3487 Note that :meth:`~object.__exit__` methods should not reraise the passed-in exception;
3488 this is the caller's responsibility.
3489
3490
3491 .. seealso::
3492
3493 :pep:`343` - The "with" statement
3494 The specification, background, and examples for the Python :keyword:`with`
3495 statement.
3496
3497
3498 .. _class-pattern-matching:
3499
3500 Customizing positional arguments in class pattern matching
3501 ----------------------------------------------------------
3502
3503 When using a class name in a pattern, positional arguments in the pattern are not
3504 allowed by default, i.e. ``case MyClass(x, y)`` is typically invalid without special
3505 support in ``MyClass``. To be able to use that kind of pattern, the class needs to
3506 define a *__match_args__* attribute.
3507
3508 .. data:: object.__match_args__
3509
3510 This class variable can be assigned a tuple of strings. When this class is
3511 used in a class pattern with positional arguments, each positional argument will
3512 be converted into a keyword argument, using the corresponding value in
3513 *__match_args__* as the keyword. The absence of this attribute is equivalent to
3514 setting it to ``()``.
3515
3516 For example, if ``MyClass.__match_args__`` is ``("left", "center", "right")`` that means
3517 that ``case MyClass(x, y)`` is equivalent to ``case MyClass(left=x, center=y)``. Note
3518 that the number of arguments in the pattern must be smaller than or equal to the number
3519 of elements in *__match_args__*; if it is larger, the pattern match attempt will raise
3520 a :exc:`TypeError`.
3521
3522 .. versionadded:: 3.10
3523
3524 .. seealso::
3525
3526 :pep:`634` - Structural Pattern Matching
3527 The specification for the Python ``match`` statement.
3528
3529
3530 .. _python-buffer-protocol:
3531
3532 Emulating buffer types
3533 ----------------------
3534
3535 The :ref:`buffer protocol <bufferobjects>` provides a way for Python
3536 objects to expose efficient access to a low-level memory array. This protocol
3537 is implemented by builtin types such as :class:`bytes` and :class:`memoryview`,
3538 and third-party libraries may define additional buffer types.
3539
3540 While buffer types are usually implemented in C, it is also possible to
3541 implement the protocol in Python.
3542
3543 .. method:: object.__buffer__(self, flags)
3544
3545 Called when a buffer is requested from *self* (for example, by the
3546 :class:`memoryview` constructor). The *flags* argument is an integer
3547 representing the kind of buffer requested, affecting for example whether
3548 the returned buffer is read-only or writable. :class:`inspect.BufferFlags`
3549 provides a convenient way to interpret the flags. The method must return
3550 a :class:`memoryview` object.
3551
3552 .. method:: object.__release_buffer__(self, buffer)
3553
3554 Called when a buffer is no longer needed. The *buffer* argument is a
3555 :class:`memoryview` object that was previously returned by
3556 :meth:`~object.__buffer__`. The method must release any resources associated
3557 with the buffer. This method should return ``None``.
3558 Buffer objects that do not need to perform any cleanup are not required
3559 to implement this method.
3560
3561 .. versionadded:: 3.12
3562
3563 .. seealso::
3564
3565 :pep:`688` - Making the buffer protocol accessible in Python
3566 Introduces the Python ``__buffer__`` and ``__release_buffer__`` methods.
3567
3568 :class:`collections.abc.Buffer`
3569 ABC for buffer types.
3570
3571 .. _special-lookup:
3572
3573 Special method lookup
3574 ---------------------
3575
3576 For custom classes, implicit invocations of special methods are only guaranteed
3577 to work correctly if defined on an object's type, not in the object's instance
3578 dictionary. That behaviour is the reason why the following code raises an
3579 exception::
3580
3581 >>> class C:
3582 ... pass
3583 ...
3584 >>> c = C()
3585 >>> c.__len__ = lambda: 5
3586 >>> len(c)
3587 Traceback (most recent call last):
3588 File "<stdin>", line 1, in <module>
3589 TypeError: object of type 'C' has no len()
3590
3591 The rationale behind this behaviour lies with a number of special methods such
3592 as :meth:`~object.__hash__` and :meth:`~object.__repr__` that are implemented
3593 by all objects,
3594 including type objects. If the implicit lookup of these methods used the
3595 conventional lookup process, they would fail when invoked on the type object
3596 itself::
3597
3598 >>> 1 .__hash__() == hash(1)
3599 True
3600 >>> int.__hash__() == hash(int)
3601 Traceback (most recent call last):
3602 File "<stdin>", line 1, in <module>
3603 TypeError: descriptor '__hash__' of 'int' object needs an argument
3604
3605 Incorrectly attempting to invoke an unbound method of a class in this way is
3606 sometimes referred to as 'metaclass confusion', and is avoided by bypassing
3607 the instance when looking up special methods::
3608
3609 >>> type(1).__hash__(1) == hash(1)
3610 True
3611 >>> type(int).__hash__(int) == hash(int)
3612 True
3613
3614 In addition to bypassing any instance attributes in the interest of
3615 correctness, implicit special method lookup generally also bypasses the
3616 :meth:`~object.__getattribute__` method even of the object's metaclass::
3617
3618 >>> class Meta(type):
3619 ... def __getattribute__(*args):
3620 ... print("Metaclass getattribute invoked")
3621 ... return type.__getattribute__(*args)
3622 ...
3623 >>> class C(object, metaclass=Meta):
3624 ... def __len__(self):
3625 ... return 10
3626 ... def __getattribute__(*args):
3627 ... print("Class getattribute invoked")
3628 ... return object.__getattribute__(*args)
3629 ...
3630 >>> c = C()
3631 >>> c.__len__() # Explicit lookup via instance
3632 Class getattribute invoked
3633 10
3634 >>> type(c).__len__(c) # Explicit lookup via type
3635 Metaclass getattribute invoked
3636 10
3637 >>> len(c) # Implicit lookup
3638 10
3639
3640 Bypassing the :meth:`~object.__getattribute__` machinery in this fashion
3641 provides significant scope for speed optimisations within the
3642 interpreter, at the cost of some flexibility in the handling of
3643 special methods (the special method *must* be set on the class
3644 object itself in order to be consistently invoked by the interpreter).
3645
3646
3647 .. index::
3648 single: coroutine
3649
3650 Coroutines
3651 ==========
3652
3653
3654 Awaitable Objects
3655 -----------------
3656
3657 An :term:`awaitable` object generally implements an :meth:`~object.__await__` method.
3658 :term:`Coroutine objects <coroutine>` returned from :keyword:`async def` functions
3659 are awaitable.
3660
3661 .. note::
3662
3663 The :term:`generator iterator` objects returned from generators
3664 decorated with :func:`types.coroutine`
3665 are also awaitable, but they do not implement :meth:`~object.__await__`.
3666
3667 .. method:: object.__await__(self)
3668
3669 Must return an :term:`iterator`. Should be used to implement
3670 :term:`awaitable` objects. For instance, :class:`asyncio.Future` implements
3671 this method to be compatible with the :keyword:`await` expression.
3672 The :class:`object` class itself is not awaitable and does not provide
3673 this method.
3674
3675 .. note::
3676
3677 The language doesn't place any restriction on the type or value of the
3678 objects yielded by the iterator returned by ``__await__``, as this is
3679 specific to the implementation of the asynchronous execution framework
3680 (e.g. :mod:`asyncio`) that will be managing the :term:`awaitable` object.
3681
3682
3683 .. versionadded:: 3.5
3684
3685 .. seealso:: :pep:`492` for additional information about awaitable objects.
3686
3687
3688 .. _coroutine-objects:
3689
3690 Coroutine Objects
3691 -----------------
3692
3693 :term:`Coroutine objects <coroutine>` are :term:`awaitable` objects.
3694 A coroutine's execution can be controlled by calling :meth:`~object.__await__` and
3695 iterating over the result. When the coroutine has finished executing and
3696 returns, the iterator raises :exc:`StopIteration`, and the exception's
3697 :attr:`~StopIteration.value` attribute holds the return value. If the
3698 coroutine raises an exception, it is propagated by the iterator. Coroutines
3699 should not directly raise unhandled :exc:`StopIteration` exceptions.
3700
3701 Coroutines also have the methods listed below, which are analogous to
3702 those of generators (see :ref:`generator-methods`). However, unlike
3703 generators, coroutines do not directly support iteration.
3704
3705 Coroutines are :ref:`generic <generics>` over the types of their yield, send,
3706 and return values, respectively.
3707
3708 .. versionchanged:: 3.5.2
3709 It is a :exc:`RuntimeError` to await on a coroutine more than once.
3710
3711
3712 .. method:: coroutine.send(value)
3713
3714 Starts or resumes execution of the coroutine. If *value* is ``None``,
3715 this is equivalent to advancing the iterator returned by
3716 :meth:`~object.__await__`. If *value* is not ``None``, this method delegates
3717 to the :meth:`~generator.send` method of the iterator that caused
3718 the coroutine to suspend. The result (return value,
3719 :exc:`StopIteration`, or other exception) is the same as when
3720 iterating over the :meth:`!__await__` return value, described above.
3721
3722 .. method:: coroutine.throw(value)
3723 coroutine.throw(type[, value[, traceback]])
3724
3725 Raises the specified exception in the coroutine. This method delegates
3726 to the :meth:`~generator.throw` method of the iterator that caused
3727 the coroutine to suspend, if it has such a method. Otherwise,
3728 the exception is raised at the suspension point. The result
3729 (return value, :exc:`StopIteration`, or other exception) is the same as
3730 when iterating over the :meth:`~object.__await__` return value, described
3731 above. If the exception is not caught in the coroutine, it propagates
3732 back to the caller.
3733
3734 .. versionchanged:: 3.12
3735
3736 The second signature \(type\[, value\[, traceback\]\]\) is deprecated and
3737 may be removed in a future version of Python.
3738
3739 .. method:: coroutine.close()
3740
3741 Causes the coroutine to clean itself up and exit. If the coroutine
3742 is suspended, this method first delegates to the :meth:`~generator.close`
3743 method of the iterator that caused the coroutine to suspend, if it
3744 has such a method. Then it raises :exc:`GeneratorExit` at the
3745 suspension point, causing the coroutine to immediately clean itself up.
3746 Finally, the coroutine is marked as having finished executing, even if
3747 it was never started.
3748
3749 Coroutine objects are automatically closed using the above process when
3750 they are about to be destroyed.
3751
3752 .. _async-iterators:
3753
3754 Asynchronous Iterators
3755 ----------------------
3756
3757 An *asynchronous iterator* can call asynchronous code in
3758 its ``__anext__`` method.
3759
3760 Asynchronous iterators can be used in an :keyword:`async for` statement.
3761
3762 The :class:`object` class itself does not provide these methods.
3763
3764
3765 .. method:: object.__aiter__(self)
3766
3767 Must return an *asynchronous iterator* object.
3768
3769 .. method:: object.__anext__(self)
3770
3771 Must return an *awaitable* resulting in a next value of the iterator. Should
3772 raise a :exc:`StopAsyncIteration` error when the iteration is over.
3773
3774 An example of an asynchronous iterable object::
3775
3776 class Reader:
3777 async def readline(self):
3778 ...
3779
3780 def __aiter__(self):
3781 return self
3782
3783 async def __anext__(self):
3784 val = await self.readline()
3785 if val == b'':
3786 raise StopAsyncIteration
3787 return val
3788
3789 .. versionadded:: 3.5
3790
3791 .. versionchanged:: 3.7
3792 Prior to Python 3.7, :meth:`~object.__aiter__` could return an *awaitable*
3793 that would resolve to an
3794 :term:`asynchronous iterator <asynchronous iterator>`.
3795
3796 Starting with Python 3.7, :meth:`~object.__aiter__` must return an
3797 asynchronous iterator object. Returning anything else
3798 will result in a :exc:`TypeError` error.
3799
3800
3801 .. _async-context-managers:
3802
3803 Asynchronous Context Managers
3804 -----------------------------
3805
3806 An *asynchronous context manager* is a *context manager* that is able to
3807 suspend execution in its ``__aenter__`` and ``__aexit__`` methods.
3808
3809 Asynchronous context managers can be used in an :keyword:`async with` statement.
3810
3811 The :class:`object` class itself does not provide these methods.
3812
3813 .. method:: object.__aenter__(self)
3814
3815 Semantically similar to :meth:`~object.__enter__`, the only
3816 difference being that it must return an *awaitable*.
3817
3818 .. method:: object.__aexit__(self, exc_type, exc_value, traceback)
3819
3820 Semantically similar to :meth:`~object.__exit__`, the only
3821 difference being that it must return an *awaitable*.
3822
3823 An example of an asynchronous context manager class::
3824
3825 class AsyncContextManager:
3826 async def __aenter__(self):
3827 await log('entering context')
3828
3829 async def __aexit__(self, exc_type, exc, tb):
3830 await log('exiting context')
3831
3832 .. versionadded:: 3.5
3833
3834
3835 .. rubric:: Footnotes
3836
3837 .. [#] It *is* possible in some cases to change an object's type, under certain
3838 controlled conditions. It generally isn't a good idea though, since it can
3839 lead to some very strange behaviour if it is handled incorrectly.
3840
3841 .. [#] The :meth:`~object.__hash__`, :meth:`~object.__iter__`,
3842 :meth:`~object.__reversed__`, :meth:`~object.__contains__`,
3843 :meth:`~object.__class_getitem__` and :meth:`~os.PathLike.__fspath__`
3844 methods have special handling for this. Others
3845 will still raise a :exc:`TypeError`, but may do so by relying on
3846 the behavior that ``None`` is not callable.
3847
3848 .. [#] "Does not support" here means that the class has no such method, or
3849 the method returns :data:`NotImplemented`. Do not set the method to
3850 ``None`` if you want to force fallback to the right operand's reflected
3851 method—that will instead have the opposite effect of explicitly
3852 *blocking* such fallback.
3853
3854 .. [#] For operands of the same type, it is assumed that if the non-reflected
3855 method -- such as :meth:`~object.__add__` -- fails then the overall
3856 operation is not
3857 supported, which is why the reflected method is not called.