Sophie

Sophie

distrib > Mageia > 6 > armv5tl > by-pkgid > a600cd26dfe6bfd8c11f12bce5cb0eee > files > 972

python3-docs-3.5.3-1.1.mga6.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>3. Data model &mdash; Python 3.5.3 documentation</title>
    
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.5.3',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.5.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.5.3 documentation" href="../contents.html" />
    <link rel="up" title="The Python Language Reference" href="index.html" />
    <link rel="next" title="4. Execution model" href="executionmodel.html" />
    <link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/version_switch.js"></script>
    
    
 

  </head>
  <body role="document">  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.5.3</span>
          <a href="../index.html">Documentation </a> &raquo;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &raquo;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-model">
<span id="datamodel"></span><h1>3. Data model<a class="headerlink" href="#data-model" title="Permalink to this headline">¶</a></h1>
<div class="section" id="objects-values-and-types">
<span id="objects"></span><h2>3.1. Objects, values and types<a class="headerlink" href="#objects-values-and-types" title="Permalink to this headline">¶</a></h2>
<p id="index-0"><em class="dfn">Objects</em> are Python&#8217;s abstraction for data.  All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
conformance to Von Neumann&#8217;s model of a &#8220;stored program computer,&#8221; code is also
represented by objects.)</p>
<span class="target" id="index-1"></span><p>Every object has an identity, a type and a value.  An object&#8217;s <em>identity</em> never
changes once it has been created; you may think of it as the object&#8217;s address in
memory.  The &#8216;<a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal"><span class="pre">is</span></code></a>&#8216; operator compares the identity of two objects; the
<a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal"><span class="pre">id()</span></code></a> function returns an integer representing its identity.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> For CPython, <code class="docutils literal"><span class="pre">id(x)</span></code> is the memory address where <code class="docutils literal"><span class="pre">x</span></code> is stored.</p>
</div>
<p>An object&#8217;s type determines the operations that the object supports (e.g., &#8220;does
it have a length?&#8221;) and also defines the possible values for objects of that
type.  The <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a> function returns an object&#8217;s type (which is an object
itself).  Like its identity, an object&#8217;s <em class="dfn">type</em> is also unchangeable.
<a class="footnote-reference" href="#id5" id="id1">[1]</a></p>
<p>The <em>value</em> of some objects can change.  Objects whose value can
change are said to be <em>mutable</em>; objects whose value is unchangeable once they
are created are called <em>immutable</em>. (The value of an immutable container object
that contains a reference to a mutable object can change when the latter&#8217;s value
is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed.  So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.) An
object&#8217;s mutability is determined by its type; for instance, numbers, strings
and tuples are immutable, while dictionaries and lists are mutable.</p>
<p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable
they may be garbage-collected.  An implementation is allowed to postpone garbage
collection or omit it altogether &#8212; it is a matter of implementation quality
how garbage collection is implemented, as long as no objects are collected that
are still reachable.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed
detection of cyclically linked garbage, which collects most objects as soon
as they become unreachable, but is not guaranteed to collect garbage
containing circular references.  See the documentation of the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal"><span class="pre">gc</span></code></a>
module for information on controlling the collection of cyclic garbage.
Other implementations act differently and CPython may change.
Do not depend on immediate finalization of objects when they become
unreachable (so you should always close files explicitly).</p>
</div>
<p>Note that the use of the implementation&#8217;s tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a &#8216;<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a>...<a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal"><span class="pre">except</span></code></a>&#8216; statement may keep
objects alive.</p>
<p>Some objects contain references to &#8220;external&#8221; resources such as open files or
windows.  It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a <code class="xref py py-meth docutils literal"><span class="pre">close()</span></code> method. Programs are strongly recommended to explicitly
close such objects.  The &#8216;<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a>...<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal"><span class="pre">finally</span></code></a>&#8216; statement
and the &#8216;<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a>&#8216; statement provide convenient ways to do this.</p>
<p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>.
Examples of containers are tuples, lists and dictionaries.  The references are
part of a container&#8217;s value.  In most cases, when we talk about the value of a
container, we imply the values, not the identities of the contained objects;
however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied.  So, if an immutable container
(like a tuple) contains a reference to a mutable object, its value changes if
that mutable object is changed.</p>
<p>Types affect almost all aspects of object behavior.  Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.  E.g.,
after <code class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></code>, <code class="docutils literal"><span class="pre">a</span></code> and <code class="docutils literal"><span class="pre">b</span></code> may or may not refer to the same object
with the value one, depending on the implementation, but after <code class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span>
<span class="pre">[]</span></code>, <code class="docutils literal"><span class="pre">c</span></code> and <code class="docutils literal"><span class="pre">d</span></code> are guaranteed to refer to two different, unique, newly
created empty lists. (Note that <code class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> assigns the same object to both
<code class="docutils literal"><span class="pre">c</span></code> and <code class="docutils literal"><span class="pre">d</span></code>.)</p>
</div>
<div class="section" id="the-standard-type-hierarchy">
<span id="types"></span><h2>3.2. The standard type hierarchy<a class="headerlink" href="#the-standard-type-hierarchy" title="Permalink to this headline">¶</a></h2>
<p id="index-4">Below is a list of the types that are built into Python.  Extension modules
(written in C, Java, or other languages, depending on the implementation) can
define additional types.  Future versions of Python may add types to the type
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.),
although such additions will often be provided via the standard library instead.</p>
<p id="index-5">Some of the type descriptions below contain a paragraph listing &#8216;special
attributes.&#8217;  These are attributes that provide access to the implementation and
are not intended for general use.  Their definition may change in the future.</p>
<dl class="docutils">
<dt>None</dt>
<dd><p class="first last" id="index-6">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal"><span class="pre">None</span></code>. It is used to signify the
absence of a value in many situations, e.g., it is returned from functions that
don&#8217;t explicitly return anything. Its truth value is false.</p>
</dd>
<dt>NotImplemented</dt>
<dd><p class="first" id="index-7">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal"><span class="pre">NotImplemented</span></code>. Numeric methods
and rich comparison methods should return this value if they do not implement the
operation for the operands provided.  (The interpreter will then try the
reflected operation, or some other fallback, depending on the operator.)  Its
truth value is true.</p>
<p class="last">See
<a class="reference internal" href="../library/numbers.html#implementing-the-arithmetic-operations"><span>Implementing the arithmetic operations</span></a>
for more details.</p>
</dd>
<dt>Ellipsis</dt>
<dd><p class="first last" id="index-8">This type has a single value.  There is a single object with this value. This
object is accessed through the literal <code class="docutils literal"><span class="pre">...</span></code> or the built-in name
<code class="docutils literal"><span class="pre">Ellipsis</span></code>.  Its truth value is true.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><code class="xref py py-class docutils literal"><span class="pre">numbers.Number</span></code></a></dt>
<dd><p class="first" id="index-9">These are created by numeric literals and returned as results by arithmetic
operators and arithmetic built-in functions.  Numeric objects are immutable;
once created their value never changes.  Python numbers are of course strongly
related to mathematical numbers, but subject to the limitations of numerical
representation in computers.</p>
<p>Python distinguishes between integers, floating point numbers, and complex
numbers:</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal"><span class="pre">numbers.Integral</span></code></a></dt>
<dd><p class="first" id="index-10">These represent elements from the mathematical set of integers (positive and
negative).</p>
<p>There are two types of integers:</p>
<p>Integers (<a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal"><span class="pre">int</span></code></a>)</p>
<blockquote>
<div>These represent numbers in an unlimited range, subject to available (virtual)
memory only.  For the purpose of shift and mask operations, a binary
representation is assumed, and negative numbers are represented in a variant of
2&#8217;s complement which gives the illusion of an infinite string of sign bits
extending to the left.</div></blockquote>
<dl class="docutils">
<dt>Booleans (<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal"><span class="pre">bool</span></code></a>)</dt>
<dd><p class="first last" id="index-11">These represent the truth values False and True.  The two objects representing
the values <code class="docutils literal"><span class="pre">False</span></code> and <code class="docutils literal"><span class="pre">True</span></code> are the only Boolean objects. The Boolean type is a
subtype of the integer type, and Boolean values behave like the values 0 and 1,
respectively, in almost all contexts, the exception being that when converted to
a string, the strings <code class="docutils literal"><span class="pre">&quot;False&quot;</span></code> or <code class="docutils literal"><span class="pre">&quot;True&quot;</span></code> are returned, respectively.</p>
</dd>
</dl>
<p class="last" id="index-12">The rules for integer representation are intended to give the most meaningful
interpretation of shift and mask operations involving negative integers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></code></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal"><span class="pre">float</span></code></a>)</dt>
<dd><p class="first last" id="index-13">These represent machine-level double precision floating point numbers. You are
at the mercy of the underlying machine architecture (and C or Java
implementation) for the accepted range and handling of overflow. Python does not
support single-precision floating point numbers; the savings in processor and
memory usage that are usually the reason for using these are dwarfed by the
overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal"><span class="pre">numbers.Complex</span></code></a> (<a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal"><span class="pre">complex</span></code></a>)</dt>
<dd><p class="first last" id="index-14">These represent complex numbers as a pair of machine-level double precision
floating point numbers.  The same caveats apply as for floating point numbers.
The real and imaginary parts of a complex number <code class="docutils literal"><span class="pre">z</span></code> can be retrieved through
the read-only attributes <code class="docutils literal"><span class="pre">z.real</span></code> and <code class="docutils literal"><span class="pre">z.imag</span></code>.</p>
</dd>
</dl>
</dd>
<dt>Sequences</dt>
<dd><p class="first" id="index-15">These represent finite ordered sets indexed by non-negative numbers. The
built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> returns the number of items of a sequence. When
the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1,
..., <em>n</em>-1.  Item <em>i</em> of sequence <em>a</em> is selected by <code class="docutils literal"><span class="pre">a[i]</span></code>.</p>
<p id="index-16">Sequences also support slicing: <code class="docutils literal"><span class="pre">a[i:j]</span></code> selects all items with index <em>k</em> such
that <em>i</em> <code class="docutils literal"><span class="pre">&lt;=</span></code> <em>k</em> <code class="docutils literal"><span class="pre">&lt;</span></code> <em>j</em>.  When used as an expression, a slice is a
sequence of the same type.  This implies that the index set is renumbered so
that it starts at 0.</p>
<p>Some sequences also support &#8220;extended slicing&#8221; with a third &#8220;step&#8221; parameter:
<code class="docutils literal"><span class="pre">a[i:j:k]</span></code> selects all items of <em>a</em> with index <em>x</em> where <code class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code>, <em>n</em>
<code class="docutils literal"><span class="pre">&gt;=</span></code> <code class="docutils literal"><span class="pre">0</span></code> and <em>i</em> <code class="docutils literal"><span class="pre">&lt;=</span></code> <em>x</em> <code class="docutils literal"><span class="pre">&lt;</span></code> <em>j</em>.</p>
<p>Sequences are distinguished according to their mutability:</p>
<dl class="last docutils">
<dt>Immutable sequences</dt>
<dd><p class="first" id="index-17">An object of an immutable sequence type cannot change once it is created.  (If
the object contains references to other objects, these other objects may be
mutable and may be changed; however, the collection of objects directly
referenced by an immutable object cannot change.)</p>
<p>The following types are immutable sequences:</p>
<dl class="last docutils" id="index-18">
<dt>Strings</dt>
<dd><p class="first last" id="index-19">A string is a sequence of values that represent Unicode code points.
All the code points in the range <code class="docutils literal"><span class="pre">U+0000</span> <span class="pre">-</span> <span class="pre">U+10FFFF</span></code> can be
represented in a string.  Python doesn&#8217;t have a <code class="xref c c-type docutils literal"><span class="pre">char</span></code> type;
instead, every code point in the string is represented as a string
object with length <code class="docutils literal"><span class="pre">1</span></code>.  The built-in function <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal"><span class="pre">ord()</span></code></a>
converts a code point from its string form to an integer in the
range <code class="docutils literal"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code>; <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal"><span class="pre">chr()</span></code></a> converts an integer in the range
<code class="docutils literal"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code> to the corresponding length <code class="docutils literal"><span class="pre">1</span></code> string object.
<a class="reference internal" href="../library/stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal"><span class="pre">str.encode()</span></code></a> can be used to convert a <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal"><span class="pre">str</span></code></a> to
<a class="reference internal" href="../library/functions.html#bytes" title="bytes"><code class="xref py py-class docutils literal"><span class="pre">bytes</span></code></a> using the given text encoding, and
<a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal"><span class="pre">bytes.decode()</span></code></a> can be used to achieve the opposite.</p>
</dd>
<dt>Tuples</dt>
<dd><p class="first last" id="index-20">The items of a tuple are arbitrary Python objects. Tuples of two or
more items are formed by comma-separated lists of expressions.  A tuple
of one item (a &#8216;singleton&#8217;) can be formed by affixing a comma to an
expression (an expression by itself does not create a tuple, since
parentheses must be usable for grouping of expressions).  An empty
tuple can be formed by an empty pair of parentheses.</p>
</dd>
<dt>Bytes</dt>
<dd><p class="first last" id="index-21">A bytes object is an immutable array.  The items are 8-bit bytes,
represented by integers in the range 0 &lt;= x &lt; 256.  Bytes literals
(like <code class="docutils literal"><span class="pre">b'abc'</span></code>) and the built-in function <a class="reference internal" href="../library/functions.html#bytes" title="bytes"><code class="xref py py-func docutils literal"><span class="pre">bytes()</span></code></a> can be used to
construct bytes objects.  Also, bytes objects can be decoded to strings
via the <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal"><span class="pre">decode()</span></code></a> method.</p>
</dd>
</dl>
</dd>
<dt>Mutable sequences</dt>
<dd><p class="first" id="index-22">Mutable sequences can be changed after they are created.  The subscription and
slicing notations can be used as the target of assignment and <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal"><span class="pre">del</span></code></a>
(delete) statements.</p>
<p>There are currently two intrinsic mutable sequence types:</p>
<dl class="docutils">
<dt>Lists</dt>
<dd><p class="first last" id="index-23">The items of a list are arbitrary Python objects.  Lists are formed by
placing a comma-separated list of expressions in square brackets. (Note
that there are no special cases needed to form lists of length 0 or 1.)</p>
</dd>
<dt>Byte Arrays</dt>
<dd><p class="first last" id="index-24">A bytearray object is a mutable array. They are created by the built-in
<a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal"><span class="pre">bytearray()</span></code></a> constructor.  Aside from being mutable (and hence
unhashable), byte arrays otherwise provide the same interface and
functionality as immutable bytes objects.</p>
</dd>
</dl>
<p class="last" id="index-25">The extension module <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal"><span class="pre">array</span></code></a> provides an additional example of a
mutable sequence type, as does the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal"><span class="pre">collections</span></code></a> module.</p>
</dd>
</dl>
</dd>
<dt>Set types</dt>
<dd><p class="first" id="index-26">These represent unordered, finite sets of unique, immutable objects. As such,
they cannot be indexed by any subscript. However, they can be iterated over, and
the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> returns the number of items in a set. Common
uses for sets are fast membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.</p>
<p>For set elements, the same immutability rules apply as for dictionary keys. Note
that numeric types obey the normal rules for numeric comparison: if two numbers
compare equal (e.g., <code class="docutils literal"><span class="pre">1</span></code> and <code class="docutils literal"><span class="pre">1.0</span></code>), only one of them can be contained in a
set.</p>
<p>There are currently two intrinsic set types:</p>
<dl class="last docutils">
<dt>Sets</dt>
<dd><p class="first last" id="index-27">These represent a mutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal"><span class="pre">set()</span></code></a>
constructor and can be modified afterwards by several methods, such as
<a class="reference internal" href="../library/stdtypes.html#set.add" title="set.add"><code class="xref py py-meth docutils literal"><span class="pre">add()</span></code></a>.</p>
</dd>
<dt>Frozen sets</dt>
<dd><p class="first last" id="index-28">These represent an immutable set.  They are created by the built-in
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal"><span class="pre">frozenset()</span></code></a> constructor.  As a frozenset is immutable and
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, it can be used again as an element of another set, or as
a dictionary key.</p>
</dd>
</dl>
</dd>
<dt>Mappings</dt>
<dd><p class="first" id="index-29">These represent finite sets of objects indexed by arbitrary index sets. The
subscript notation <code class="docutils literal"><span class="pre">a[k]</span></code> selects the item indexed by <code class="docutils literal"><span class="pre">k</span></code> from the mapping
<code class="docutils literal"><span class="pre">a</span></code>; this can be used in expressions and as the target of assignments or
<a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal"><span class="pre">del</span></code></a> statements. The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> returns the number
of items in a mapping.</p>
<p>There is currently a single intrinsic mapping type:</p>
<dl class="last docutils">
<dt>Dictionaries</dt>
<dd><p class="first" id="index-30">These represent finite sets of objects indexed by nearly arbitrary values.  The
only types of values not acceptable as keys are values containing lists or
dictionaries or other mutable types that are compared by value rather than by
object identity, the reason being that the efficient implementation of
dictionaries requires a key&#8217;s hash value to remain constant. Numeric types used
for keys obey the normal rules for numeric comparison: if two numbers compare
equal (e.g., <code class="docutils literal"><span class="pre">1</span></code> and <code class="docutils literal"><span class="pre">1.0</span></code>) then they can be used interchangeably to index
the same dictionary entry.</p>
<p>Dictionaries are mutable; they can be created by the <code class="docutils literal"><span class="pre">{...}</span></code> notation (see
section <a class="reference internal" href="expressions.html#dict"><span>Dictionary displays</span></a>).</p>
<p class="last" id="index-31">The extension modules <a class="reference internal" href="../library/dbm.html#module-dbm.ndbm" title="dbm.ndbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal"><span class="pre">dbm.ndbm</span></code></a> and <a class="reference internal" href="../library/dbm.html#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal"><span class="pre">dbm.gnu</span></code></a> provide
additional examples of mapping types, as does the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal"><span class="pre">collections</span></code></a>
module.</p>
</dd>
</dl>
</dd>
<dt>Callable types</dt>
<dd><p class="first" id="index-32">These are the types to which the function call operation (see section
<a class="reference internal" href="expressions.html#calls"><span>Calls</span></a>) can be applied:</p>
<dl class="last docutils">
<dt>User-defined functions</dt>
<dd><p class="first" id="index-33">A user-defined function object is created by a function definition (see
section <a class="reference internal" href="compound_stmts.html#function"><span>Function definitions</span></a>).  It should be called with an argument list
containing the same number of items as the function&#8217;s formal parameter
list.</p>
<p>Special attributes:</p>
<table border="1" class="docutils" id="index-34">
<colgroup>
<col width="37%" />
<col width="46%" />
<col width="16%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Meaning</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code></td>
<td>The function&#8217;s documentation
string, or <code class="docutils literal"><span class="pre">None</span></code> if
unavailable; not inherited by
subclasses</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a></td>
<td>The function&#8217;s name</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="../library/stdtypes.html#definition.__qualname__" title="definition.__qualname__"><code class="xref py py-attr docutils literal"><span class="pre">__qualname__</span></code></a></td>
<td><p class="first">The function&#8217;s
<a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a></p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 3.3.</span></p>
</div>
</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code></td>
<td>The name of the module the
function was defined in, or
<code class="docutils literal"><span class="pre">None</span></code> if unavailable.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__defaults__</span></code></td>
<td>A tuple containing default
argument values for those
arguments that have defaults,
or <code class="docutils literal"><span class="pre">None</span></code> if no arguments
have a default value</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal"><span class="pre">__code__</span></code></td>
<td>The code object representing
the compiled function body.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__globals__</span></code></td>
<td>A reference to the dictionary
that holds the function&#8217;s
global variables &#8212; the
global namespace of the
module in which the function
was defined.</td>
<td>Read-only</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a></td>
<td>The namespace supporting
arbitrary function
attributes.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__closure__</span></code></td>
<td><code class="docutils literal"><span class="pre">None</span></code> or a tuple of cells
that contain bindings for the
function&#8217;s free variables.</td>
<td>Read-only</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal"><span class="pre">__annotations__</span></code></td>
<td>A dict containing annotations
of parameters.  The keys of
the dict are the parameter
names, and <code class="docutils literal"><span class="pre">'return'</span></code> for
the return annotation, if
provided.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__kwdefaults__</span></code></td>
<td>A dict containing defaults
for keyword-only parameters.</td>
<td>Writable</td>
</tr>
</tbody>
</table>
<p>Most of the attributes labelled &#8220;Writable&#8221; check the type of the assigned value.</p>
<p>Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions.  Regular attribute
dot-notation is used to get and set such attributes. <em>Note that the current
implementation only supports function attributes on user-defined functions.
Function attributes on built-in functions may be supported in the future.</em></p>
<p class="last">Additional information about a function&#8217;s definition can be retrieved from its
code object; see the description of internal types below.</p>
</dd>
<dt>Instance methods</dt>
<dd><p class="first" id="index-35">An instance method object combines a class, a class instance and any
callable object (normally a user-defined function).</p>
<p id="index-36">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> is the class instance object,
<code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code> is the function object; <code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the method&#8217;s
documentation (same as <code class="docutils literal"><span class="pre">__func__.__doc__</span></code>); <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the
method name (same as <code class="docutils literal"><span class="pre">__func__.__name__</span></code>); <code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code> is the
name of the module the method was defined in, or <code class="docutils literal"><span class="pre">None</span></code> if unavailable.</p>
<p>Methods also support accessing (but not setting) the arbitrary function
attributes on the underlying function object.</p>
<p>User-defined method objects may be created when getting an attribute of a
class (perhaps via an instance of that class), if that attribute is a
user-defined function object or a class method object.</p>
<p>When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its
<code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> attribute is the instance, and the method object is said
to be bound.  The new method&#8217;s <code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code> attribute is the original
function object.</p>
<p>When a user-defined method object is created by retrieving another method
object from a class or instance, the behaviour is the same as for a
function object, except that the <code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code> attribute of the new
instance is not the original method object but its <code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code>
attribute.</p>
<p>When an instance method object is created by retrieving a class method
object from a class or instance, its <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> attribute is the
class itself, and its <code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code> attribute is the function object
underlying the class method.</p>
<p>When an instance method object is called, the underlying function
(<code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code>) is called, inserting the class instance
(<code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code>) in front of the argument list.  For instance, when
<code class="xref py py-class docutils literal"><span class="pre">C</span></code> is a class which contains a definition for a function
<code class="xref py py-meth docutils literal"><span class="pre">f()</span></code>, and <code class="docutils literal"><span class="pre">x</span></code> is an instance of <code class="xref py py-class docutils literal"><span class="pre">C</span></code>, calling <code class="docutils literal"><span class="pre">x.f(1)</span></code> is
equivalent to calling <code class="docutils literal"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>.</p>
<p>When an instance method object is derived from a class method object, the
&#8220;class instance&#8221; stored in <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> will actually be the class
itself, so that calling either <code class="docutils literal"><span class="pre">x.f(1)</span></code> or <code class="docutils literal"><span class="pre">C.f(1)</span></code> is equivalent to
calling <code class="docutils literal"><span class="pre">f(C,1)</span></code> where <code class="docutils literal"><span class="pre">f</span></code> is the underlying function.</p>
<p class="last">Note that the transformation from function object to instance method
object happens each time the attribute is retrieved from the instance.  In
some cases, a fruitful optimization is to assign the attribute to a local
variable and call that local variable. Also notice that this
transformation only happens for user-defined functions; other callable
objects (and all non-callable objects) are retrieved without
transformation.  It is also important to note that user-defined functions
which are attributes of a class instance are not converted to bound
methods; this <em>only</em> happens when the function is an attribute of the
class.</p>
</dd>
<dt>Generator functions</dt>
<dd><p class="first last" id="index-37">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal"><span class="pre">yield</span></code></a> statement (see section
<a class="reference internal" href="simple_stmts.html#yield"><span>The yield statement</span></a>) is called a <em class="dfn">generator function</em>.  Such a function, when
called, always returns an iterator object which can be used to execute the
body of the function:  calling the iterator&#8217;s <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal"><span class="pre">iterator.__next__()</span></code></a>
method will cause the function to execute until it provides a value
using the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal"><span class="pre">yield</span></code></a> statement.  When the function executes a
<a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal"><span class="pre">return</span></code></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></code></a>
exception is raised and the iterator will have reached the end of the set of
values to be returned.</p>
</dd>
<dt>Coroutine functions</dt>
<dd><p class="first last" id="index-38">A function or method which is defined using <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal"><span class="pre">async</span> <span class="pre">def</span></code></a> is called
a <em class="dfn">coroutine function</em>.  Such a function, when called, returns a
<a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> object.  It may contain <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal"><span class="pre">await</span></code></a> expressions,
as well as <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal"><span class="pre">async</span> <span class="pre">with</span></code></a> and <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal"><span class="pre">async</span> <span class="pre">for</span></code></a> statements. See
also the <a class="reference internal" href="#coroutine-objects"><span>Coroutine Objects</span></a> section.</p>
</dd>
<dt>Built-in functions</dt>
<dd><p class="first last" id="index-39">A built-in function object is a wrapper around a C function.  Examples of
built-in functions are <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal"><span class="pre">math.sin()</span></code></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal"><span class="pre">math</span></code></a> is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:
<code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the function&#8217;s documentation string, or <code class="docutils literal"><span class="pre">None</span></code> if
unavailable; <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the function&#8217;s name; <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> is
set to <code class="docutils literal"><span class="pre">None</span></code> (but see the next item); <code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code> is the name of
the module the function was defined in or <code class="docutils literal"><span class="pre">None</span></code> if unavailable.</p>
</dd>
<dt>Built-in methods</dt>
<dd><p class="first last" id="index-40">This is really a different disguise of a built-in function, this time containing
an object passed to the C function as an implicit extra argument.  An example of
a built-in method is <code class="docutils literal"><span class="pre">alist.append()</span></code>, assuming <em>alist</em> is a list object. In
this case, the special read-only attribute <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> is set to the object
denoted by <em>alist</em>.</p>
</dd>
<dt>Classes</dt>
<dd>Classes are callable.  These objects normally act as factories for new
instances of themselves, but variations are possible for class types that
override <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a>.  The arguments of the call are passed to
<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> to
initialize the new instance.</dd>
<dt>Class Instances</dt>
<dd>Instances of arbitrary classes can be made callable by defining a
<a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal"><span class="pre">__call__()</span></code></a> method in their class.</dd>
</dl>
</dd>
<dt>Modules</dt>
<dd><p class="first" id="index-41">Modules are a basic organizational unit of Python code, and are created by
the <a class="reference internal" href="import.html#importsystem"><span>import system</span></a> as invoked either by the
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal"><span class="pre">import</span></code></a> statement (see <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal"><span class="pre">import</span></code></a>), or by calling
functions such as <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal"><span class="pre">importlib.import_module()</span></code></a> and built-in
<a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal"><span class="pre">__import__()</span></code></a>.  A module object has a namespace implemented by a
dictionary object (this is the dictionary referenced by the <code class="docutils literal"><span class="pre">__globals__</span></code>
attribute of functions defined in the module).  Attribute references are
translated to lookups in this dictionary, e.g., <code class="docutils literal"><span class="pre">m.x</span></code> is equivalent to
<code class="docutils literal"><span class="pre">m.__dict__[&quot;x&quot;]</span></code>. A module object does not contain the code object used
to initialize the module (since it isn&#8217;t needed once the initialization is
done).</p>
<p>Attribute assignment updates the module&#8217;s namespace dictionary, e.g.,
<code class="docutils literal"><span class="pre">m.x</span> <span class="pre">=</span> <span class="pre">1</span></code> is equivalent to <code class="docutils literal"><span class="pre">m.__dict__[&quot;x&quot;]</span> <span class="pre">=</span> <span class="pre">1</span></code>.</p>
<p id="index-42">Special read-only attribute: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> is the module&#8217;s namespace as a
dictionary object.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module
dictionary will be cleared when the module falls out of scope even if the
dictionary still has live references.  To avoid this, copy the dictionary
or keep the module around while using its dictionary directly.</p>
</div>
<p class="last" id="index-43">Predefined (writable) attributes: <a class="reference internal" href="import.html#__name__" title="__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the module&#8217;s name;
<code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the module&#8217;s documentation string, or <code class="docutils literal"><span class="pre">None</span></code> if
unavailable; <a class="reference internal" href="import.html#__file__" title="__file__"><code class="xref py py-attr docutils literal"><span class="pre">__file__</span></code></a> is the pathname of the file from which the
module was loaded, if it was loaded from a file. The <a class="reference internal" href="import.html#__file__" title="__file__"><code class="xref py py-attr docutils literal"><span class="pre">__file__</span></code></a>
attribute may be missing for certain types of modules, such as C modules
that are statically linked into the interpreter; for extension modules
loaded dynamically from a shared library, it is the pathname of the shared
library file.</p>
</dd>
<dt>Custom classes</dt>
<dd><p class="first">Custom class types are typically created by class definitions (see section
<a class="reference internal" href="compound_stmts.html#class"><span>Class definitions</span></a>).  A class has a namespace implemented by a dictionary object.
Class attribute references are translated to lookups in this dictionary, e.g.,
<code class="docutils literal"><span class="pre">C.x</span></code> is translated to <code class="docutils literal"><span class="pre">C.__dict__[&quot;x&quot;]</span></code> (although there are a number of
hooks which allow for other means of locating attributes). When the attribute
name is not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order which
behaves correctly even in the presence of &#8216;diamond&#8217; inheritance structures
where there are multiple inheritance paths leading back to a common ancestor.
Additional details on the C3 MRO used by Python can be found in the
documentation accompanying the 2.3 release at
<a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
<p id="index-44">When a class attribute reference (for class <code class="xref py py-class docutils literal"><span class="pre">C</span></code>, say) would yield a
class method object, it is transformed into an instance method object whose
<code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> attributes is <code class="xref py py-class docutils literal"><span class="pre">C</span></code>.  When it would yield a static
method object, it is transformed into the object wrapped by the static method
object. See section <a class="reference internal" href="#descriptors"><span>Implementing Descriptors</span></a> for another way in which attributes
retrieved from a class may differ from those actually contained in its
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a>.</p>
<p id="index-45">Class attribute assignments update the class&#8217;s dictionary, never the dictionary
of a base class.</p>
<p id="index-46">A class object can be called (see above) to yield a class instance (see below).</p>
<p class="last" id="index-47">Special attributes: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the class name; <code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code> is
the module name in which the class was defined; <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> is the
dictionary containing the class&#8217;s namespace; <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal"><span class="pre">__bases__</span></code></a> is a
tuple containing the base classes, in the order of their occurrence in the
base class list; <code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the class&#8217;s documentation string, or
<code class="docutils literal"><span class="pre">None</span></code> if undefined.</p>
</dd>
<dt>Class instances</dt>
<dd><p class="first" id="index-48">A class instance is created by calling a class object (see above).  A class
instance has a namespace implemented as a dictionary which is the first place
in which attribute references are searched.  When an attribute is not found
there, and the instance&#8217;s class has an attribute by that name, the search
continues with the class attributes.  If a class attribute is found that is a
user-defined function object, it is transformed into an instance method
object whose <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> attribute is the instance.  Static method and
class method objects are also transformed; see above under &#8220;Classes&#8221;.  See
section <a class="reference internal" href="#descriptors"><span>Implementing Descriptors</span></a> for another way in which attributes of a class
retrieved via its instances may differ from the objects actually stored in
the class&#8217;s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a>.  If no class attribute is found, and the
object&#8217;s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> method, that is called to satisfy
the lookup.</p>
<p id="index-49">Attribute assignments and deletions update the instance&#8217;s dictionary, never a
class&#8217;s dictionary.  If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a> or
<a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal"><span class="pre">__delattr__()</span></code></a> method, this is called instead of updating the instance
dictionary directly.</p>
<p id="index-50">Class instances can pretend to be numbers, sequences, or mappings if they have
methods with certain special names.  See section <a class="reference internal" href="#specialnames"><span>Special method names</span></a>.</p>
<p class="last" id="index-51">Special attributes: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> is the attribute dictionary;
<a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal"><span class="pre">__class__</span></code></a> is the instance&#8217;s class.</p>
</dd>
<dt>I/O objects (also known as file objects)</dt>
<dd><p class="first" id="index-52">A <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> represents an open file.  Various shortcuts are
available to create file objects: the <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal"><span class="pre">open()</span></code></a> built-in function, and
also <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal"><span class="pre">os.popen()</span></code></a>, <a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal"><span class="pre">os.fdopen()</span></code></a>, and the
<a class="reference internal" href="../library/socket.html#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal"><span class="pre">makefile()</span></code></a> method of socket objects (and perhaps by
other functions or methods provided by extension modules).</p>
<p class="last">The objects <code class="docutils literal"><span class="pre">sys.stdin</span></code>, <code class="docutils literal"><span class="pre">sys.stdout</span></code> and <code class="docutils literal"><span class="pre">sys.stderr</span></code> are
initialized to file objects corresponding to the interpreter&#8217;s standard
input, output and error streams; they are all open in text mode and
therefore follow the interface defined by the <a class="reference internal" href="../library/io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal"><span class="pre">io.TextIOBase</span></code></a>
abstract class.</p>
</dd>
<dt>Internal types</dt>
<dd><p class="first" id="index-53">A few types used internally by the interpreter are exposed to the user. Their
definitions may change with future versions of the interpreter, but they are
mentioned here for completeness.</p>
<dl class="docutils" id="index-54">
<dt>Code objects</dt>
<dd><p class="first">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>.
The difference between a code object and a function object is that the function
object contains an explicit reference to the function&#8217;s globals (the module in
which it was defined), while a code object contains no context; also the default
argument values are stored in the function object, not in the code object
(because they represent values calculated at run-time).  Unlike function
objects, code objects are immutable and contain no references (directly or
indirectly) to mutable objects.</p>
<p id="index-55">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">co_name</span></code> gives the function name;
<code class="xref py py-attr docutils literal"><span class="pre">co_argcount</span></code> is the number of positional arguments (including arguments
with default values); <code class="xref py py-attr docutils literal"><span class="pre">co_nlocals</span></code> is the number of local variables used
by the function (including arguments); <code class="xref py py-attr docutils literal"><span class="pre">co_varnames</span></code> is a tuple containing
the names of the local variables (starting with the argument names);
<code class="xref py py-attr docutils literal"><span class="pre">co_cellvars</span></code> is a tuple containing the names of local variables that are
referenced by nested functions; <code class="xref py py-attr docutils literal"><span class="pre">co_freevars</span></code> is a tuple containing the
names of free variables; <code class="xref py py-attr docutils literal"><span class="pre">co_code</span></code> is a string representing the sequence
of bytecode instructions; <code class="xref py py-attr docutils literal"><span class="pre">co_consts</span></code> is a tuple containing the literals
used by the bytecode; <code class="xref py py-attr docutils literal"><span class="pre">co_names</span></code> is a tuple containing the names used by
the bytecode; <code class="xref py py-attr docutils literal"><span class="pre">co_filename</span></code> is the filename from which the code was
compiled; <code class="xref py py-attr docutils literal"><span class="pre">co_firstlineno</span></code> is the first line number of the function;
<code class="xref py py-attr docutils literal"><span class="pre">co_lnotab</span></code> is a string encoding the mapping from bytecode offsets to
line numbers (for details see the source code of the interpreter);
<code class="xref py py-attr docutils literal"><span class="pre">co_stacksize</span></code> is the required stack size (including local variables);
<code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code> is an integer encoding a number of flags for the interpreter.</p>
<p id="index-56">The following flag bits are defined for <code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code>: bit <code class="docutils literal"><span class="pre">0x04</span></code> is set if
the function uses the <code class="docutils literal"><span class="pre">*arguments</span></code> syntax to accept an arbitrary number of
positional arguments; bit <code class="docutils literal"><span class="pre">0x08</span></code> is set if the function uses the
<code class="docutils literal"><span class="pre">**keywords</span></code> syntax to accept arbitrary keyword arguments; bit <code class="docutils literal"><span class="pre">0x20</span></code> is set
if the function is a generator.</p>
<p>Future feature declarations (<code class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code>) also use bits
in <code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code> to indicate whether a code object was compiled with a
particular feature enabled: bit <code class="docutils literal"><span class="pre">0x2000</span></code> is set if the function was compiled
with future division enabled; bits <code class="docutils literal"><span class="pre">0x10</span></code> and <code class="docutils literal"><span class="pre">0x1000</span></code> were used in earlier
versions of Python.</p>
<p>Other bits in <code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code> are reserved for internal use.</p>
<p class="last" id="index-57">If a code object represents a function, the first item in <code class="xref py py-attr docutils literal"><span class="pre">co_consts</span></code> is
the documentation string of the function, or <code class="docutils literal"><span class="pre">None</span></code> if undefined.</p>
</dd>
</dl>
<dl class="last docutils" id="frame-objects">
<dt>Frame objects</dt>
<dd><p class="first" id="index-58">Frame objects represent execution frames.  They may occur in traceback objects
(see below).</p>
<p id="index-59">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">f_back</span></code> is to the previous stack frame
(towards the caller), or <code class="docutils literal"><span class="pre">None</span></code> if this is the bottom stack frame;
<code class="xref py py-attr docutils literal"><span class="pre">f_code</span></code> is the code object being executed in this frame; <code class="xref py py-attr docutils literal"><span class="pre">f_locals</span></code>
is the dictionary used to look up local variables; <code class="xref py py-attr docutils literal"><span class="pre">f_globals</span></code> is used for
global variables; <code class="xref py py-attr docutils literal"><span class="pre">f_builtins</span></code> is used for built-in (intrinsic) names;
<code class="xref py py-attr docutils literal"><span class="pre">f_lasti</span></code> gives the precise instruction (this is an index into the
bytecode string of the code object).</p>
<p id="index-60">Special writable attributes: <code class="xref py py-attr docutils literal"><span class="pre">f_trace</span></code>, if not <code class="docutils literal"><span class="pre">None</span></code>, is a function
called at the start of each source code line (this is used by the debugger);
<code class="xref py py-attr docutils literal"><span class="pre">f_lineno</span></code> is the current line number of the frame &#8212; writing to this
from within a trace function jumps to the given line (only for the bottom-most
frame).  A debugger can implement a Jump command (aka Set Next Statement)
by writing to f_lineno.</p>
<p>Frame objects support one method:</p>
<dl class="last method">
<dt id="frame.clear">
<code class="descclassname">frame.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frame.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>This method clears all references to local variables held by the
frame.  Also, if the frame belonged to a generator, the generator
is finalized.  This helps break reference cycles involving frame
objects (for example when catching an exception and storing its
traceback for later use).</p>
<p><a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></code></a> is raised if the frame is currently executing.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.4.</span></p>
</div>
</dd></dl>

</dd>
<dt>Traceback objects</dt>
<dd><p class="first" id="index-61">Traceback objects represent a stack trace of an exception.  A traceback object
is created when an exception occurs.  When the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is
inserted in front of the current traceback.  When an exception handler is
entered, the stack trace is made available to the program. (See section
<a class="reference internal" href="compound_stmts.html#try"><span>The try statement</span></a>.) It is accessible as the third item of the
tuple returned by <code class="docutils literal"><span class="pre">sys.exc_info()</span></code>. When the program contains no suitable
handler, the stack trace is written (nicely formatted) to the standard error
stream; if the interpreter is interactive, it is also made available to the user
as <code class="docutils literal"><span class="pre">sys.last_traceback</span></code>.</p>
<p class="last" id="index-62">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">tb_next</span></code> is the next level in the stack
trace (towards the frame where the exception occurred), or <code class="docutils literal"><span class="pre">None</span></code> if there is
no next level; <code class="xref py py-attr docutils literal"><span class="pre">tb_frame</span></code> points to the execution frame of the current
level; <code class="xref py py-attr docutils literal"><span class="pre">tb_lineno</span></code> gives the line number where the exception occurred;
<code class="xref py py-attr docutils literal"><span class="pre">tb_lasti</span></code> indicates the precise instruction.  The line number and last
instruction in the traceback may differ from the line number of its frame object
if the exception occurred in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a> statement with no matching except
clause or with a finally clause.</p>
</dd>
<dt>Slice objects</dt>
<dd><p class="first" id="index-63">Slice objects are used to represent slices for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>
methods.  They are also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-func docutils literal"><span class="pre">slice()</span></code></a> function.</p>
<p id="index-64">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">start</span></code> is the lower bound;
<code class="xref py py-attr docutils literal"><span class="pre">stop</span></code> is the upper bound; <code class="xref py py-attr docutils literal"><span class="pre">step</span></code> is the step
value; each is <code class="docutils literal"><span class="pre">None</span></code> if omitted.  These attributes can have any type.</p>
<p>Slice objects support one method:</p>
<dl class="last method">
<dt id="slice.indices">
<code class="descclassname">slice.</code><code class="descname">indices</code><span class="sig-paren">(</span><em>self</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#slice.indices" title="Permalink to this definition">¶</a></dt>
<dd><p>This method takes a single integer argument <em>length</em> and computes
information about the slice that the slice object would describe if
applied to a sequence of <em>length</em> items.  It returns a tuple of three
integers; respectively these are the <em>start</em> and <em>stop</em> indices and the
<em>step</em> or stride length of the slice. Missing or out-of-bounds indices
are handled in a manner consistent with regular slices.</p>
</dd></dl>

</dd>
<dt>Static method objects</dt>
<dd>Static method objects provide a way of defeating the transformation of function
objects to method objects described above. A static method object is a wrapper
around any other object, usually a user-defined method object. When a static
method object is retrieved from a class or a class instance, the object actually
returned is the wrapped object, which is not subject to any further
transformation. Static method objects are not themselves callable, although the
objects they wrap usually are. Static method objects are created by the built-in
<a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></code></a> constructor.</dd>
<dt>Class method objects</dt>
<dd>A class method object, like a static method object, is a wrapper around another
object that alters the way in which that object is retrieved from classes and
class instances. The behaviour of class method objects upon such retrieval is
described above, under &#8220;User-defined methods&#8221;. Class method objects are created
by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal"><span class="pre">classmethod()</span></code></a> constructor.</dd>
</dl>
</dd>
</dl>
</div>
<div class="section" id="special-method-names">
<span id="specialnames"></span><h2>3.3. Special method names<a class="headerlink" href="#special-method-names" title="Permalink to this headline">¶</a></h2>
<p id="index-65">A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Python&#8217;s approach to <em class="dfn">operator overloading</em>,
allowing classes to define their own behavior with respect to language
operators.  For instance, if a class defines a method named <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>,
and <code class="docutils literal"><span class="pre">x</span></code> is an instance of this class, then <code class="docutils literal"><span class="pre">x[i]</span></code> is roughly equivalent
to <code class="docutils literal"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></code>.  Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
<a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a>).</p>
<p>When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled.  For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense.  (One example
of this is the <code class="xref py py-class docutils literal"><span class="pre">NodeList</span></code> interface in the W3C&#8217;s Document
Object Model.)</p>
<div class="section" id="basic-customization">
<span id="customization"></span><h3>3.3.1. Basic customization<a class="headerlink" href="#basic-customization" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__new__">
<code class="descclassname">object.</code><code class="descname">__new__</code><span class="sig-paren">(</span><em>cls</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__new__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-66">Called to create a new instance of class <em>cls</em>.  <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> is a static
method (special-cased so you need not declare it as such) that takes the class
of which an instance was requested as its first argument.  The remaining
arguments are those passed to the object constructor expression (the call to the
class).  The return value of <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> should be the new object instance
(usually an instance of <em>cls</em>).</p>
<p>Typical implementations create a new instance of the class by invoking the
superclass&#8217;s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> method using <code class="docutils literal"><span class="pre">super(currentclass,</span>
<span class="pre">cls).__new__(cls[,</span> <span class="pre">...])</span></code> with appropriate arguments and then modifying the
newly-created instance as necessary before returning it.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> returns an instance of <em>cls</em>, then the new instance&#8217;s
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method will be invoked like <code class="docutils literal"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></code>, where
<em>self</em> is the new instance and the remaining arguments are the same as were
passed to <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a>.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> does not return an instance of <em>cls</em>, then the new instance&#8217;s
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method will not be invoked.</p>
<p><a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> is intended mainly to allow subclasses of immutable types (like
int, str, or tuple) to customize instance creation.  It is also commonly
overridden in custom metaclasses in order to customize class creation.</p>
</dd></dl>

<dl class="method">
<dt id="object.__init__">
<code class="descclassname">object.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-67">Called after the instance has been created (by <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a>), but before
it is returned to the caller.  The arguments are those passed to the
class constructor expression.  If a base class has an <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a>
method, the derived class&#8217;s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method, if any, must explicitly
call it to ensure proper initialization of the base class part of the
instance; for example: <code class="docutils literal"><span class="pre">BaseClass.__init__(self,</span> <span class="pre">[args...])</span></code>.</p>
<p>Because <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> work together in constructing
objects (<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> to create it, and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> to customize it),
no non-<code class="docutils literal"><span class="pre">None</span></code> value may be returned by <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a>; doing so will
cause a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> to be raised at runtime.</p>
</dd></dl>

<dl class="method">
<dt id="object.__del__">
<code class="descclassname">object.</code><code class="descname">__del__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__del__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-68">Called when the instance is about to be destroyed.  This is also called a
destructor.  If a base class has a <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method, the derived class&#8217;s
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method, if any, must explicitly call it to ensure proper
deletion of the base class part of the instance.  Note that it is possible
(though not recommended!) for the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method to postpone destruction
of the instance by creating a new reference to it.  It may then be called at a
later time when this new reference is deleted.  It is not guaranteed that
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods are called for objects that still exist when the
interpreter exits.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal"><span class="pre">del</span> <span class="pre">x</span></code> doesn&#8217;t directly call <code class="docutils literal"><span class="pre">x.__del__()</span></code> &#8212; the former decrements
the reference count for <code class="docutils literal"><span class="pre">x</span></code> by one, and the latter is only called when
<code class="docutils literal"><span class="pre">x</span></code>&#8216;s reference count reaches zero.  Some common situations that may
prevent the reference count of an object from going to zero include:
circular references between objects (e.g., a doubly-linked list or a tree
data structure with parent and child pointers); a reference to the object
on the stack frame of a function that caught an exception (the traceback
stored in <code class="docutils literal"><span class="pre">sys.exc_info()[2]</span></code> keeps the stack frame alive); or a
reference to the object on the stack frame that raised an unhandled
exception in interactive mode (the traceback stored in
<code class="docutils literal"><span class="pre">sys.last_traceback</span></code> keeps the stack frame alive).  The first situation
can only be remedied by explicitly breaking the cycles; the second can be
resolved by freeing the reference to the traceback object when it is no
longer useful, and the third can be resolved by storing <code class="docutils literal"><span class="pre">None</span></code> in
<code class="docutils literal"><span class="pre">sys.last_traceback</span></code>.
Circular references which are garbage are detected and cleaned up when
the cyclic garbage collector is enabled (it&#8217;s on by default). Refer to the
documentation for the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal"><span class="pre">gc</span></code></a> module for more information about this
topic.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Due to the precarious circumstances under which <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods are
invoked, exceptions that occur during their execution are ignored, and a warning
is printed to <code class="docutils literal"><span class="pre">sys.stderr</span></code> instead.  Also, when <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> is invoked in
response to a module being deleted (e.g., when execution of the program is
done), other globals referenced by the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method may already have
been deleted or in the process of being torn down (e.g. the import
machinery shutting down).  For this reason, <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods
should do the absolute
minimum needed to maintain external invariants.  Starting with version 1.5,
Python guarantees that globals whose name begins with a single underscore are
deleted from their module before other globals are deleted; if no other
references to such globals exist, this may help in assuring that imported
modules are still available at the time when the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method is
called.</p>
<span class="target" id="index-69"></span></div>
</dd></dl>

<dl class="method">
<dt id="object.__repr__">
<code class="descclassname">object.</code><code class="descname">__repr__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__repr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal"><span class="pre">repr()</span></code></a> built-in function to compute the &#8220;official&#8221; string
representation of an object.  If at all possible, this should look like a
valid Python expression that could be used to recreate an object with the
same value (given an appropriate environment).  If this is not possible, a
string of the form <code class="docutils literal"><span class="pre">&lt;...some</span> <span class="pre">useful</span> <span class="pre">description...&gt;</span></code> should be returned.
The return value must be a string object. If a class defines <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a>
but not <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal"><span class="pre">__str__()</span></code></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a> is also used when an
&#8220;informal&#8221; string representation of instances of that class is required.</p>
<p>This is typically used for debugging, so it is important that the representation
is information-rich and unambiguous.</p>
<span class="target" id="index-70"></span></dd></dl>

<dl class="method">
<dt id="object.__str__">
<code class="descclassname">object.</code><code class="descname">__str__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal"><span class="pre">str(object)</span></code></a> and the built-in functions
<a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal"><span class="pre">format()</span></code></a> and <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal"><span class="pre">print()</span></code></a> to compute the &#8220;informal&#8221; or nicely
printable string representation of an object.  The return value must be a
<a class="reference internal" href="../library/stdtypes.html#textseq"><span>string</span></a> object.</p>
<p>This method differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">object.__repr__()</span></code></a> in that there is no
expectation that <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal"><span class="pre">__str__()</span></code></a> return a valid Python expression: a more
convenient or concise representation can be used.</p>
<p>The default implementation defined by the built-in type <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a>
calls <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">object.__repr__()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__bytes__">
<code class="descclassname">object.</code><code class="descname">__bytes__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bytes__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-71">Called by <a class="reference internal" href="../library/functions.html#bytes" title="bytes"><code class="xref py py-func docutils literal"><span class="pre">bytes()</span></code></a> to compute a byte-string representation of an
object. This should return a <code class="docutils literal"><span class="pre">bytes</span></code> object.</p>
<span class="target" id="index-72"></span></dd></dl>

<dl class="method">
<dt id="object.__format__">
<code class="descclassname">object.</code><code class="descname">__format__</code><span class="sig-paren">(</span><em>self</em>, <em>format_spec</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__format__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal"><span class="pre">format()</span></code></a> built-in function (and by extension, the
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal"><span class="pre">str.format()</span></code></a> method of class <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal"><span class="pre">str</span></code></a>) to produce a &#8220;formatted&#8221;
string representation of an object. The <code class="docutils literal"><span class="pre">format_spec</span></code> argument is
a string that contains a description of the formatting options desired.
The interpretation of the <code class="docutils literal"><span class="pre">format_spec</span></code> argument is up to the type
implementing <a class="reference internal" href="#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal"><span class="pre">__format__()</span></code></a>, however most classes will either
delegate formatting to one of the built-in types, or use a similar
formatting option syntax.</p>
<p>See <a class="reference internal" href="../library/string.html#formatspec"><span>Format Specification Mini-Language</span></a> for a description of the standard formatting syntax.</p>
<p>The return value must be a string object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.4: </span>The __format__ method of <code class="docutils literal"><span class="pre">object</span></code> itself raises a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a>
if passed any non-empty string.</p>
</div>
</dd></dl>

<span class="target" id="richcmpfuncs"></span><dl class="method">
<dt id="object.__lt__">
<code class="descclassname">object.</code><code class="descname">__lt__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lt__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__le__">
<code class="descclassname">object.</code><code class="descname">__le__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__le__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__eq__">
<code class="descclassname">object.</code><code class="descname">__eq__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__eq__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ne__">
<code class="descclassname">object.</code><code class="descname">__ne__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ne__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__gt__">
<code class="descclassname">object.</code><code class="descname">__gt__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__gt__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ge__">
<code class="descclassname">object.</code><code class="descname">__ge__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ge__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-73">These are the so-called &#8220;rich comparison&#8221; methods. The correspondence between
operator symbols and method names is as follows: <code class="docutils literal"><span class="pre">x&lt;y</span></code> calls <code class="docutils literal"><span class="pre">x.__lt__(y)</span></code>,
<code class="docutils literal"><span class="pre">x&lt;=y</span></code> calls <code class="docutils literal"><span class="pre">x.__le__(y)</span></code>, <code class="docutils literal"><span class="pre">x==y</span></code> calls <code class="docutils literal"><span class="pre">x.__eq__(y)</span></code>, <code class="docutils literal"><span class="pre">x!=y</span></code> calls
<code class="docutils literal"><span class="pre">x.__ne__(y)</span></code>, <code class="docutils literal"><span class="pre">x&gt;y</span></code> calls <code class="docutils literal"><span class="pre">x.__gt__(y)</span></code>, and <code class="docutils literal"><span class="pre">x&gt;=y</span></code> calls
<code class="docutils literal"><span class="pre">x.__ge__(y)</span></code>.</p>
<p>A rich comparison method may return the singleton <code class="docutils literal"><span class="pre">NotImplemented</span></code> if it does
not implement the operation for a given pair of arguments. By convention,
<code class="docutils literal"><span class="pre">False</span></code> and <code class="docutils literal"><span class="pre">True</span></code> are returned for a successful comparison. However, these
methods can return any value, so if the comparison operator is used in a Boolean
context (e.g., in the condition of an <code class="docutils literal"><span class="pre">if</span></code> statement), Python will call
<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-func docutils literal"><span class="pre">bool()</span></code></a> on the value to determine if the result is true or false.</p>
<p>By default, <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></code></a> delegates to <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> and
inverts the result unless it is <code class="docutils literal"><span class="pre">NotImplemented</span></code>.  There are no other
implied relationships among the comparison operators, for example,
the truth of <code class="docutils literal"><span class="pre">(x&lt;y</span> <span class="pre">or</span> <span class="pre">x==y)</span></code> does not imply <code class="docutils literal"><span class="pre">x&lt;=y</span></code>.
To automatically generate ordering operations from a single root operation,
see <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal"><span class="pre">functools.total_ordering()</span></code></a>.</p>
<p>See the paragraph on <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> for
some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects which support
custom comparison operations and are usable as dictionary keys.</p>
<p>There are no swapped-argument versions of these methods (to be used when the
left argument does not support the operation but the right argument does);
rather, <a class="reference internal" href="#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal"><span class="pre">__lt__()</span></code></a> and <a class="reference internal" href="#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal"><span class="pre">__gt__()</span></code></a> are each other&#8217;s reflection,
<a class="reference internal" href="#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal"><span class="pre">__le__()</span></code></a> and <a class="reference internal" href="#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal"><span class="pre">__ge__()</span></code></a> are each other&#8217;s reflection, and
<a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></code></a> are their own reflection.
If the operands are of different types, and right operand&#8217;s type is
a direct or indirect subclass of the left operand&#8217;s type,
the reflected method of the right operand has priority, otherwise
the left operand&#8217;s method has priority.  Virtual subclassing is
not considered.</p>
</dd></dl>

<dl class="method">
<dt id="object.__hash__">
<code class="descclassname">object.</code><code class="descname">__hash__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hash__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-74">Called by built-in function <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal"><span class="pre">hash()</span></code></a> and for operations on members of
hashed collections including <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal"><span class="pre">set</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal"><span class="pre">frozenset</span></code></a>, and
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal"><span class="pre">dict</span></code></a>.  <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> should return an integer. The only required
property is that objects which compare equal have the same hash value; it is
advised to mix together the hash values of the components of the object that
also play a part in comparison of objects by packing them into a tuple and
hashing the tuple. Example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">hash</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">nick</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">color</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal"><span class="pre">hash()</span></code></a> truncates the value returned from an object&#8217;s custom
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> method to the size of a <code class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></code>.  This is
typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.  If an
object&#8217;s   <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> must interoperate on builds of different bit
sizes, be sure to check the width on all supported builds.  An easy way
to do this is with
<code class="docutils literal"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">&quot;import</span> <span class="pre">sys;</span> <span class="pre">print(sys.hash_info.width)&quot;</span></code>.</p>
</div>
<p>If a class does not define an <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> method it should not define a
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> operation either; if it defines <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> but not
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a>, its instances will not be usable as items in hashable
collections.  If a class defines mutable objects and implements an
<a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> method, it should not implement <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a>, since the
implementation of hashable collections requires that a key&#8217;s hash value is
immutable (if the object&#8217;s hash value changes, it will be in the wrong hash
bucket).</p>
<p>User-defined classes have <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> methods
by default; with them, all objects compare unequal (except with themselves)
and <code class="docutils literal"><span class="pre">x.__hash__()</span></code> returns an appropriate value such that <code class="docutils literal"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code>
implies both that <code class="docutils literal"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code> and <code class="docutils literal"><span class="pre">hash(x)</span> <span class="pre">==</span> <span class="pre">hash(y)</span></code>.</p>
<p>A class that overrides <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> and does not define <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a>
will have its <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> implicitly set to <code class="docutils literal"><span class="pre">None</span></code>.  When the
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> method of a class is <code class="docutils literal"><span class="pre">None</span></code>, instances of the class will
raise an appropriate <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> when a program attempts to retrieve
their hash value, and will also be correctly identified as unhashable when
checking <code class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable)</span></code>.</p>
<p>If a class that overrides <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> needs to retain the implementation
of <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> from a parent class, the interpreter must be told this
explicitly by setting <code class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">&lt;ParentClass&gt;.__hash__</span></code>.</p>
<p>If a class that does not override <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> wishes to suppress hash
support, it should include <code class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> in the class definition.
A class which defines its own <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> that explicitly raises
a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> would be incorrectly identified as hashable by
an <code class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable)</span></code> call.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>By default, the <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> values of str, bytes and datetime
objects are &#8220;salted&#8221; with an unpredictable random value.  Although they
remain constant within an individual Python process, they are not
predictable between repeated invocations of Python.</p>
<p>This is intended to provide protection against a denial-of-service caused
by carefully-chosen inputs that exploit the worst case performance of a
dict insertion, O(n^2) complexity.  See
<a class="reference external" href="http://www.ocert.org/advisories/ocert-2011-003.html">http://www.ocert.org/advisories/ocert-2011-003.html</a> for details.</p>
<p>Changing hash values affects the iteration order of dicts, sets and
other mappings.  Python has never made guarantees about this ordering
(and it typically varies between 32-bit and 64-bit builds).</p>
<p class="last">See also <span class="target" id="index-75"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHASHSEED"><code class="xref std std-envvar docutils literal"><span class="pre">PYTHONHASHSEED</span></code></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>Hash randomization is enabled by default.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__bool__">
<code class="descclassname">object.</code><code class="descname">__bool__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bool__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-76">Called to implement truth value testing and the built-in operation
<code class="docutils literal"><span class="pre">bool()</span></code>; should return <code class="docutils literal"><span class="pre">False</span></code> or <code class="docutils literal"><span class="pre">True</span></code>.  When this method is not
defined, <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> is called, if it is defined, and the object is
considered true if its result is nonzero.  If a class defines neither
<a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> nor <a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal"><span class="pre">__bool__()</span></code></a>, all its instances are considered
true.</p>
</dd></dl>

</div>
<div class="section" id="customizing-attribute-access">
<span id="attribute-access"></span><h3>3.3.2. Customizing attribute access<a class="headerlink" href="#customizing-attribute-access" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to customize the meaning of attribute
access (use of, assignment to, or deletion of <code class="docutils literal"><span class="pre">x.name</span></code>) for class instances.</p>
<dl class="method">
<dt id="object.__getattr__">
<code class="descclassname">object.</code><code class="descname">__getattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an attribute lookup has not found the attribute in the usual places
(i.e. it is not an instance attribute nor is it found in the class tree for
<code class="docutils literal"><span class="pre">self</span></code>).  <code class="docutils literal"><span class="pre">name</span></code> is the attribute name. This method should return the
(computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> exception.</p>
<p>Note that if the attribute is found through the normal mechanism,
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> is not called.  (This is an intentional asymmetry between
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> and <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a>.) This is done both for efficiency
reasons and because otherwise <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> would have no way to access
other attributes of the instance.  Note that at least for instance variables,
you can fake total control by not inserting any values in the instance attribute
dictionary (but instead inserting them in another object).  See the
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> method below for a way to actually get total control
over attribute access.</p>
</dd></dl>

<dl class="method">
<dt id="object.__getattribute__">
<code class="descclassname">object.</code><code class="descname">__getattribute__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattribute__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called unconditionally to implement attribute accesses for instances of the
class. If the class also defines <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a>, the latter will not be
called unless <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> either calls it explicitly or raises an
<a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a>. This method should return the (computed) attribute value
or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> exception. In order to avoid infinite
recursion in this method, its implementation should always call the base class
method with the same name to access any attributes it needs, for example,
<code class="docutils literal"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method may still be bypassed when looking up special methods as the
result of implicit invocation via language syntax or built-in functions.
See <a class="reference internal" href="#special-lookup"><span>Special method lookup</span></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__setattr__">
<code class="descclassname">object.</code><code class="descname">__setattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an attribute assignment is attempted.  This is called instead of
the normal mechanism (i.e. store the value in the instance dictionary).
<em>name</em> is the attribute name, <em>value</em> is the value to be assigned to it.</p>
<p>If <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a> wants to assign to an instance attribute, it should
call the base class method with the same name, for example,
<code class="docutils literal"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span> <span class="pre">value)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delattr__">
<code class="descclassname">object.</code><code class="descname">__delattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a> but for attribute deletion instead of assignment.  This
should only be implemented if <code class="docutils literal"><span class="pre">del</span> <span class="pre">obj.name</span></code> is meaningful for the object.</p>
</dd></dl>

<dl class="method">
<dt id="object.__dir__">
<code class="descclassname">object.</code><code class="descname">__dir__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__dir__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal"><span class="pre">dir()</span></code></a> is called on the object. A sequence must be
returned. <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal"><span class="pre">dir()</span></code></a> converts the returned sequence to a list and sorts it.</p>
</dd></dl>

<div class="section" id="implementing-descriptors">
<span id="descriptors"></span><h4>3.3.2.1. Implementing Descriptors<a class="headerlink" href="#implementing-descriptors" title="Permalink to this headline">¶</a></h4>
<p>The following methods only apply when an instance of the class containing the
method (a so-called <em>descriptor</em> class) appears in an <em>owner</em> class (the
descriptor must be in either the owner&#8217;s class dictionary or in the class
dictionary for one of its parents).  In the examples below, &#8220;the attribute&#8221;
refers to the attribute whose name is the key of the property in the owner
class&#8217; <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a>.</p>
<dl class="method">
<dt id="object.__get__">
<code class="descclassname">object.</code><code class="descname">__get__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em>, <em>owner</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__get__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to get the attribute of the owner class (class attribute access) or of an
instance of that class (instance attribute access). <em>owner</em> is always the owner
class, while <em>instance</em> is the instance that the attribute was accessed through,
or <code class="docutils literal"><span class="pre">None</span></code> when the attribute is accessed through the <em>owner</em>.  This method
should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a>
exception.</p>
</dd></dl>

<dl class="method">
<dt id="object.__set__">
<code class="descclassname">object.</code><code class="descname">__set__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to set the attribute on an instance <em>instance</em> of the owner class to a
new value, <em>value</em>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delete__">
<code class="descclassname">object.</code><code class="descname">__delete__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delete__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to delete the attribute on an instance <em>instance</em> of the owner class.</p>
</dd></dl>

<p>The attribute <code class="xref py py-attr docutils literal"><span class="pre">__objclass__</span></code> is interpreted by the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal"><span class="pre">inspect</span></code></a> module
as specifying the class where this object was defined (setting this
appropriately can assist in runtime introspection of dynamic class attributes).
For callables, it may indicate that an instance of the given type (or a
subclass) is expected or required as the first positional argument (for example,
CPython sets this attribute for unbound methods that are implemented in C).</p>
</div>
<div class="section" id="invoking-descriptors">
<span id="descriptor-invocation"></span><h4>3.3.2.2. Invoking Descriptors<a class="headerlink" href="#invoking-descriptors" title="Permalink to this headline">¶</a></h4>
<p>In general, a descriptor is an object attribute with &#8220;binding behavior&#8221;, one
whose attribute access has been overridden by methods in the descriptor
protocol:  <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a>, and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></code></a>. If any of
those methods are defined for an object, it is said to be a descriptor.</p>
<p>The default behavior for attribute access is to get, set, or delete the
attribute from an object&#8217;s dictionary. For instance, <code class="docutils literal"><span class="pre">a.x</span></code> has a lookup chain
starting with <code class="docutils literal"><span class="pre">a.__dict__['x']</span></code>, then <code class="docutils literal"><span class="pre">type(a).__dict__['x']</span></code>, and
continuing through the base classes of <code class="docutils literal"><span class="pre">type(a)</span></code> excluding metaclasses.</p>
<p>However, if the looked-up value is an object defining one of the descriptor
methods, then Python may override the default behavior and invoke the descriptor
method instead.  Where this occurs in the precedence chain depends on which
descriptor methods were defined and how they were called.</p>
<p>The starting point for descriptor invocation is a binding, <code class="docutils literal"><span class="pre">a.x</span></code>. How the
arguments are assembled depends on <code class="docutils literal"><span class="pre">a</span></code>:</p>
<dl class="docutils">
<dt>Direct Call</dt>
<dd>The simplest and least common call is when user code directly invokes a
descriptor method:    <code class="docutils literal"><span class="pre">x.__get__(a)</span></code>.</dd>
<dt>Instance Binding</dt>
<dd>If binding to an object instance, <code class="docutils literal"><span class="pre">a.x</span></code> is transformed into the call:
<code class="docutils literal"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></code>.</dd>
<dt>Class Binding</dt>
<dd>If binding to a class, <code class="docutils literal"><span class="pre">A.x</span></code> is transformed into the call:
<code class="docutils literal"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></code>.</dd>
<dt>Super Binding</dt>
<dd>If <code class="docutils literal"><span class="pre">a</span></code> is an instance of <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-class docutils literal"><span class="pre">super</span></code></a>, then the binding <code class="docutils literal"><span class="pre">super(B,</span>
<span class="pre">obj).m()</span></code> searches <code class="docutils literal"><span class="pre">obj.__class__.__mro__</span></code> for the base class <code class="docutils literal"><span class="pre">A</span></code>
immediately preceding <code class="docutils literal"><span class="pre">B</span></code> and then invokes the descriptor with the call:
<code class="docutils literal"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">obj.__class__)</span></code>.</dd>
</dl>
<p>For instance bindings, the precedence of descriptor invocation depends on the
which descriptor methods are defined.  A descriptor can define any combination
of <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></code></a>.  If it does not
define <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a>, then accessing the attribute will return the descriptor
object itself unless there is a value in the object&#8217;s instance dictionary.  If
the descriptor defines <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a> and/or <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></code></a>, it is a data
descriptor; if it defines neither, it is a non-data descriptor.  Normally, data
descriptors define both <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a> and <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a>, while non-data
descriptors have just the <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a> method.  Data descriptors with
<a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a> defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be overridden by
instances.</p>
<p>Python methods (including <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></code></a> and <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal"><span class="pre">classmethod()</span></code></a>) are
implemented as non-data descriptors.  Accordingly, instances can redefine and
override methods.  This allows individual instances to acquire behaviors that
differ from other instances of the same class.</p>
<p>The <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal"><span class="pre">property()</span></code></a> function is implemented as a data descriptor. Accordingly,
instances cannot override the behavior of a property.</p>
</div>
<div class="section" id="slots">
<span id="id2"></span><h4>3.3.2.3. __slots__<a class="headerlink" href="#slots" title="Permalink to this headline">¶</a></h4>
<p>By default, instances of classes have a dictionary for attribute storage.  This
wastes space for objects having very few instance variables.  The space
consumption can become acute when creating large numbers of instances.</p>
<p>The default can be overridden by defining <em>__slots__</em> in a class definition.
The <em>__slots__</em> declaration takes a sequence of instance variables and reserves
just enough space in each instance to hold a value for each variable.  Space is
saved because <em>__dict__</em> is not created for each instance.</p>
<dl class="data">
<dt id="object.__slots__">
<code class="descclassname">object.</code><code class="descname">__slots__</code><a class="headerlink" href="#object.__slots__" title="Permalink to this definition">¶</a></dt>
<dd><p>This class variable can be assigned a string, iterable, or sequence of
strings with variable names used by instances.  <em>__slots__</em> reserves space
for the declared variables and prevents the automatic creation of <em>__dict__</em>
and <em>__weakref__</em> for each instance.</p>
</dd></dl>

<div class="section" id="notes-on-using-slots">
<h5>3.3.2.3.1. Notes on using <em>__slots__</em><a class="headerlink" href="#notes-on-using-slots" title="Permalink to this headline">¶</a></h5>
<ul class="simple">
<li>When inheriting from a class without <em>__slots__</em>, the <em>__dict__</em> attribute of
that class will always be accessible, so a <em>__slots__</em> definition in the
subclass is meaningless.</li>
<li>Without a <em>__dict__</em> variable, instances cannot be assigned new variables not
listed in the <em>__slots__</em> definition.  Attempts to assign to an unlisted
variable name raises <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a>. If dynamic assignment of new
variables is desired, then add <code class="docutils literal"><span class="pre">'__dict__'</span></code> to the sequence of strings in
the <em>__slots__</em> declaration.</li>
<li>Without a <em>__weakref__</em> variable for each instance, classes defining
<em>__slots__</em> do not support weak references to its instances. If weak reference
support is needed, then add <code class="docutils literal"><span class="pre">'__weakref__'</span></code> to the sequence of strings in the
<em>__slots__</em> declaration.</li>
<li><em>__slots__</em> are implemented at the class level by creating descriptors
(<a class="reference internal" href="#descriptors"><span>Implementing Descriptors</span></a>) for each variable name.  As a result, class attributes
cannot be used to set default values for instance variables defined by
<em>__slots__</em>; otherwise, the class attribute would overwrite the descriptor
assignment.</li>
<li>The action of a <em>__slots__</em> declaration is limited to the class where it is
defined.  As a result, subclasses will have a <em>__dict__</em> unless they also define
<em>__slots__</em> (which must only contain names of any <em>additional</em> slots).</li>
<li>If a class defines a slot also defined in a base class, the instance variable
defined by the base class slot is inaccessible (except by retrieving its
descriptor directly from the base class). This renders the meaning of the
program undefined.  In the future, a check may be added to prevent this.</li>
<li>Nonempty <em>__slots__</em> does not work for classes derived from &#8220;variable-length&#8221;
built-in types such as <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal"><span class="pre">int</span></code></a>, <a class="reference internal" href="../library/functions.html#bytes" title="bytes"><code class="xref py py-class docutils literal"><span class="pre">bytes</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal"><span class="pre">tuple</span></code></a>.</li>
<li>Any non-string iterable may be assigned to <em>__slots__</em>. Mappings may also be
used; however, in the future, special meaning may be assigned to the values
corresponding to each key.</li>
<li><em>__class__</em> assignment works only if both classes have the same <em>__slots__</em>.</li>
</ul>
</div>
</div>
</div>
<div class="section" id="customizing-class-creation">
<span id="metaclasses"></span><h3>3.3.3. Customizing class creation<a class="headerlink" href="#customizing-class-creation" title="Permalink to this headline">¶</a></h3>
<p>By default, classes are constructed using <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a>. The class body is
executed in a new namespace and the class name is bound locally to the
result of <code class="docutils literal"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">namespace)</span></code>.</p>
<p>The class creation process can be customized by passing the <code class="docutils literal"><span class="pre">metaclass</span></code>
keyword argument in the class definition line, or by inheriting from an
existing class that included such an argument. In the following example,
both <code class="docutils literal"><span class="pre">MyClass</span></code> and <code class="docutils literal"><span class="pre">MySubclass</span></code> are instances of <code class="docutils literal"><span class="pre">Meta</span></code>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">MySubclass</span><span class="p">(</span><span class="n">MyClass</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>Any other keyword arguments that are specified in the class definition are
passed through to all metaclass operations described below.</p>
<p>When a class definition is executed, the following steps occur:</p>
<ul class="simple">
<li>the appropriate metaclass is determined</li>
<li>the class namespace is prepared</li>
<li>the class body is executed</li>
<li>the class object is created</li>
</ul>
<div class="section" id="determining-the-appropriate-metaclass">
<h4>3.3.3.1. Determining the appropriate metaclass<a class="headerlink" href="#determining-the-appropriate-metaclass" title="Permalink to this headline">¶</a></h4>
<p>The appropriate metaclass for a class definition is determined as follows:</p>
<ul class="simple">
<li>if no bases and no explicit metaclass are given, then <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a> is used</li>
<li>if an explicit metaclass is given and it is <em>not</em> an instance of
<a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a>, then it is used directly as the metaclass</li>
<li>if an instance of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a> is given as the explicit metaclass, or
bases are defined, then the most derived metaclass is used</li>
</ul>
<p>The most derived metaclass is selected from the explicitly specified
metaclass (if any) and the metaclasses (i.e. <code class="docutils literal"><span class="pre">type(cls)</span></code>) of all specified
base classes. The most derived metaclass is one which is a subtype of <em>all</em>
of these candidate metaclasses. If none of the candidate metaclasses meets
that criterion, then the class definition will fail with <code class="docutils literal"><span class="pre">TypeError</span></code>.</p>
</div>
<div class="section" id="preparing-the-class-namespace">
<span id="prepare"></span><h4>3.3.3.2. Preparing the class namespace<a class="headerlink" href="#preparing-the-class-namespace" title="Permalink to this headline">¶</a></h4>
<p>Once the appropriate metaclass has been identified, then the class namespace
is prepared. If the metaclass has a <code class="docutils literal"><span class="pre">__prepare__</span></code> attribute, it is called
as <code class="docutils literal"><span class="pre">namespace</span> <span class="pre">=</span> <span class="pre">metaclass.__prepare__(name,</span> <span class="pre">bases,</span> <span class="pre">**kwds)</span></code> (where the
additional keyword arguments, if any, come from the class definition).</p>
<p>If the metaclass has no <code class="docutils literal"><span class="pre">__prepare__</span></code> attribute, then the class namespace
is initialised as an empty <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal"><span class="pre">dict()</span></code></a> instance.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-77"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3115"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt>
<dd>Introduced the <code class="docutils literal"><span class="pre">__prepare__</span></code> namespace hook</dd>
</dl>
</div>
</div>
<div class="section" id="executing-the-class-body">
<h4>3.3.3.3. Executing the class body<a class="headerlink" href="#executing-the-class-body" title="Permalink to this headline">¶</a></h4>
<p>The class body is executed (approximately) as
<code class="docutils literal"><span class="pre">exec(body,</span> <span class="pre">globals(),</span> <span class="pre">namespace)</span></code>. The key difference from a normal
call to <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal"><span class="pre">exec()</span></code></a> is that lexical scoping allows the class body (including
any methods) to reference names from the current and outer scopes when the
class definition occurs inside a function.</p>
<p>However, even when the class definition occurs inside the function, methods
defined inside the class still cannot see names defined at the class scope.
Class variables must be accessed through the first parameter of instance or
class methods, and cannot be accessed at all from static methods.</p>
</div>
<div class="section" id="creating-the-class-object">
<h4>3.3.3.4. Creating the class object<a class="headerlink" href="#creating-the-class-object" title="Permalink to this headline">¶</a></h4>
<p>Once the class namespace has been populated by executing the class body,
the class object is created by calling
<code class="docutils literal"><span class="pre">metaclass(name,</span> <span class="pre">bases,</span> <span class="pre">namespace,</span> <span class="pre">**kwds)</span></code> (the additional keywords
passed here are the same as those passed to <code class="docutils literal"><span class="pre">__prepare__</span></code>).</p>
<p>This class object is the one that will be referenced by the zero-argument
form of <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal"><span class="pre">super()</span></code></a>. <code class="docutils literal"><span class="pre">__class__</span></code> is an implicit closure reference
created by the compiler if any methods in a class body refer to either
<code class="docutils literal"><span class="pre">__class__</span></code> or <code class="docutils literal"><span class="pre">super</span></code>. This allows the zero argument form of
<a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal"><span class="pre">super()</span></code></a> to correctly identify the class being defined based on
lexical scoping, while the class or instance that was used to make the
current call is identified based on the first argument passed to the method.</p>
<p>After the class object is created, it is passed to the class decorators
included in the class definition (if any) and the resulting object is bound
in the local namespace as the defined class.</p>
<p>When a new class is created by <code class="docutils literal"><span class="pre">type.__new__</span></code>, the object provided as the
namespace parameter is copied to a standard Python dictionary and the original
object is discarded. The new copy becomes the <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> attribute
of the class object.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-78"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3135"><strong>PEP 3135</strong></a> - New super</dt>
<dd>Describes the implicit <code class="docutils literal"><span class="pre">__class__</span></code> closure reference</dd>
</dl>
</div>
</div>
<div class="section" id="metaclass-example">
<h4>3.3.3.5. Metaclass example<a class="headerlink" href="#metaclass-example" title="Permalink to this headline">¶</a></h4>
<p>The potential uses for metaclasses are boundless. Some ideas that have been
explored include logging, interface checking, automatic delegation, automatic
property creation, proxies, frameworks, and automatic resource
locking/synchronization.</p>
<p>Here is an example of a metaclass that uses an <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></code></a>
to remember the order that class variables are defined:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">OrderedClass</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">__prepare__</span><span class="p">(</span><span class="n">metacls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">collections</span><span class="o">.</span><span class="n">OrderedDict</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">namespace</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="n">result</span> <span class="o">=</span> <span class="nb">type</span><span class="o">.</span><span class="n">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="nb">dict</span><span class="p">(</span><span class="n">namespace</span><span class="p">))</span>
        <span class="n">result</span><span class="o">.</span><span class="n">members</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">namespace</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result</span>

<span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">OrderedClass</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">one</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">two</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">three</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">four</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">A</span><span class="o">.</span><span class="n">members</span>
<span class="p">(</span><span class="s1">&#39;__module__&#39;</span><span class="p">,</span> <span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">,</span> <span class="s1">&#39;four&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>When the class definition for <em>A</em> gets executed, the process begins with
calling the metaclass&#8217;s <code class="xref py py-meth docutils literal"><span class="pre">__prepare__()</span></code> method which returns an empty
<a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></code></a>.  That mapping records the methods and
attributes of <em>A</em> as they are defined within the body of the class statement.
Once those definitions are executed, the ordered dictionary is fully populated
and the metaclass&#8217;s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> method gets invoked.  That method builds
the new type and it saves the ordered dictionary keys in an attribute
called <code class="docutils literal"><span class="pre">members</span></code>.</p>
</div>
</div>
<div class="section" id="customizing-instance-and-subclass-checks">
<h3>3.3.4. Customizing instance and subclass checks<a class="headerlink" href="#customizing-instance-and-subclass-checks" title="Permalink to this headline">¶</a></h3>
<p>The following methods are used to override the default behavior of the
<a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal"><span class="pre">issubclass()</span></code></a> built-in functions.</p>
<p>In particular, the metaclass <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">abc.ABCMeta</span></code></a> implements these methods in
order to allow the addition of Abstract Base Classes (ABCs) as &#8220;virtual base
classes&#8221; to any class or type (including built-in types), including other
ABCs.</p>
<dl class="method">
<dt id="class.__instancecheck__">
<code class="descclassname">class.</code><code class="descname">__instancecheck__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__instancecheck__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>instance</em> should be considered a (direct or indirect)
instance of <em>class</em>. If defined, called to implement <code class="docutils literal"><span class="pre">isinstance(instance,</span>
<span class="pre">class)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="class.__subclasscheck__">
<code class="descclassname">class.</code><code class="descname">__subclasscheck__</code><span class="sig-paren">(</span><em>self</em>, <em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__subclasscheck__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>subclass</em> should be considered a (direct or indirect)
subclass of <em>class</em>.  If defined, called to implement <code class="docutils literal"><span class="pre">issubclass(subclass,</span>
<span class="pre">class)</span></code>.</p>
</dd></dl>

<p>Note that these methods are looked up on the type (metaclass) of a class.  They
cannot be defined as class methods in the actual class.  This is consistent with
the lookup of special methods that are called on instances, only in this
case the instance is itself a class.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-79"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt>
<dd>Includes the specification for customizing <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal"><span class="pre">isinstance()</span></code></a> and
<a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal"><span class="pre">issubclass()</span></code></a> behavior through <a class="reference internal" href="#class.__instancecheck__" title="class.__instancecheck__"><code class="xref py py-meth docutils literal"><span class="pre">__instancecheck__()</span></code></a> and
<a class="reference internal" href="#class.__subclasscheck__" title="class.__subclasscheck__"><code class="xref py py-meth docutils literal"><span class="pre">__subclasscheck__()</span></code></a>, with motivation for this functionality
in the context of adding Abstract Base Classes (see the <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal"><span class="pre">abc</span></code></a>
module) to the language.</dd>
</dl>
</div>
</div>
<div class="section" id="emulating-callable-objects">
<span id="callable-types"></span><h3>3.3.5. Emulating callable objects<a class="headerlink" href="#emulating-callable-objects" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__call__">
<code class="descclassname">object.</code><code class="descname">__call__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>args...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__call__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-80">Called when the instance is &#8220;called&#8221; as a function; if this method is defined,
<code class="docutils literal"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> is a shorthand for <code class="docutils literal"><span class="pre">x.__call__(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="emulating-container-types">
<span id="sequence-types"></span><h3>3.3.6. Emulating container types<a class="headerlink" href="#emulating-container-types" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to implement container objects.  Containers
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
but can represent other containers as well.  The first set of methods is used
either to emulate a sequence or to emulate a mapping; the difference is that for
a sequence, the allowable keys should be the integers <em>k</em> for which <code class="docutils literal"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span>
<span class="pre">N</span></code> where <em>N</em> is the length of the sequence, or slice objects, which define a
range of items.  It is also recommended that mappings provide the methods
<code class="xref py py-meth docutils literal"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">values()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">items()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">get()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">clear()</span></code>,
<code class="xref py py-meth docutils literal"><span class="pre">setdefault()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">popitem()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">copy()</span></code>, and
<code class="xref py py-meth docutils literal"><span class="pre">update()</span></code> behaving similar to those for Python&#8217;s standard dictionary
objects.  The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal"><span class="pre">collections</span></code></a> module provides a
<a class="reference internal" href="../library/collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code class="xref py py-class docutils literal"><span class="pre">MutableMapping</span></code></a>
abstract base class to help create those methods from a base set of
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></code></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></code></a>, and <code class="xref py py-meth docutils literal"><span class="pre">keys()</span></code>.
Mutable sequences should provide methods <code class="xref py py-meth docutils literal"><span class="pre">append()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">count()</span></code>,
<code class="xref py py-meth docutils literal"><span class="pre">index()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">extend()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">insert()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">remove()</span></code>,
<code class="xref py py-meth docutils literal"><span class="pre">reverse()</span></code> and <code class="xref py py-meth docutils literal"><span class="pre">sort()</span></code>, like Python standard list objects.  Finally,
sequence types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a>,
<a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal"><span class="pre">__radd__()</span></code></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></code></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal"><span class="pre">__mul__()</span></code></a>, <a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal"><span class="pre">__rmul__()</span></code></a> and
<a class="reference internal" href="#object.__imul__" title="object.__imul__"><code class="xref py py-meth docutils literal"><span class="pre">__imul__()</span></code></a> described below; they should not define other numerical
operators.  It is recommended that both mappings and sequences implement the
<a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></code></a> method to allow efficient use of the <code class="docutils literal"><span class="pre">in</span></code> operator; for
mappings, <code class="docutils literal"><span class="pre">in</span></code> should search the mapping&#8217;s keys; for sequences, it should
search through the values.  It is further recommended that both mappings and
sequences implement the <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a> method to allow efficient iteration
through the container; for mappings, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a> should be the same as
<code class="xref py py-meth docutils literal"><span class="pre">keys()</span></code>; for sequences, it should iterate through the values.</p>
<dl class="method">
<dt id="object.__len__">
<code class="descclassname">object.</code><code class="descname">__len__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__len__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-81">Called to implement the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a>.  Should return the length
of the object, an integer <code class="docutils literal"><span class="pre">&gt;=</span></code> 0.  Also, an object that doesn&#8217;t define a
<a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal"><span class="pre">__bool__()</span></code></a> method and whose <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> method returns zero is
considered to be false in a Boolean context.</p>
</dd></dl>

<dl class="method">
<dt id="object.__length_hint__">
<code class="descclassname">object.</code><code class="descname">__length_hint__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__length_hint__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.length_hint" title="operator.length_hint"><code class="xref py py-func docutils literal"><span class="pre">operator.length_hint()</span></code></a>. Should return an estimated
length for the object (which may be greater or less than the actual length).
The length must be an integer <code class="docutils literal"><span class="pre">&gt;=</span></code> 0. This method is purely an
optimization and is never required for correctness.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.4.</span></p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Slicing is done exclusively with the following three methods.  A call like</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span>
</pre></div>
</div>
<p>is translated to</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">a</span><span class="p">[</span><span class="nb">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="kc">None</span><span class="p">)]</span> <span class="o">=</span> <span class="n">b</span>
</pre></div>
</div>
<p class="last">and so forth.  Missing slice items are always filled in with <code class="docutils literal"><span class="pre">None</span></code>.</p>
</div>
<dl class="method">
<dt id="object.__getitem__">
<code class="descclassname">object.</code><code class="descname">__getitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-82">Called to implement evaluation of <code class="docutils literal"><span class="pre">self[key]</span></code>. For sequence types, the
accepted keys should be integers and slice objects.  Note that the special
interpretation of negative indexes (if the class wishes to emulate a sequence
type) is up to the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method. If <em>key</em> is of an inappropriate
type, <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> may be raised; if of a value outside the set of indexes
for the sequence (after any special interpretation of negative values),
<a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal"><span class="pre">IndexError</span></code></a> should be raised. For mapping types, if <em>key</em> is missing (not
in the container), <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal"><span class="pre">KeyError</span></code></a> should be raised.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal"><span class="pre">for</span></code></a> loops expect that an <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal"><span class="pre">IndexError</span></code></a> will be raised for illegal
indexes to allow proper detection of the end of the sequence.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__missing__">
<code class="descclassname">object.</code><code class="descname">__missing__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal"><span class="pre">dict</span></code></a>.<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> to implement <code class="docutils literal"><span class="pre">self[key]</span></code> for dict subclasses
when key is not in the dictionary.</p>
</dd></dl>

<dl class="method">
<dt id="object.__setitem__">
<code class="descclassname">object.</code><code class="descname">__setitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement assignment to <code class="docutils literal"><span class="pre">self[key]</span></code>.  Same note as for
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>.  This should only be implemented for mappings if the
objects support changes to the values for keys, or if new keys can be added, or
for sequences if elements can be replaced.  The same exceptions should be raised
for improper <em>key</em> values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delitem__">
<code class="descclassname">object.</code><code class="descname">__delitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement deletion of <code class="docutils literal"><span class="pre">self[key]</span></code>.  Same note as for
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>.  This should only be implemented for mappings if the
objects support removal of keys, or for sequences if elements can be removed
from the sequence.  The same exceptions should be raised for improper <em>key</em>
values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="object.__iter__">
<code class="descclassname">object.</code><code class="descname">__iter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when an iterator is required for a container. This method
should return a new iterator object that can iterate over all the objects in the
container.  For mappings, it should iterate over the keys of the container.</p>
<p>Iterator objects also need to implement this method; they are required to return
themselves.  For more information on iterator objects, see <a class="reference internal" href="../library/stdtypes.html#typeiter"><span>Iterator Types</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__reversed__">
<code class="descclassname">object.</code><code class="descname">__reversed__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reversed__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called (if present) by the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal"><span class="pre">reversed()</span></code></a> built-in to implement
reverse iteration.  It should return a new iterator object that iterates
over all the objects in the container in reverse order.</p>
<p>If the <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></code></a> method is not provided, the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal"><span class="pre">reversed()</span></code></a>
built-in will fall back to using the sequence protocol (<a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> and
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>).  Objects that support the sequence protocol should
only provide <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></code></a> if they can provide an implementation
that is more efficient than the one provided by <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal"><span class="pre">reversed()</span></code></a>.</p>
</dd></dl>

<p>The membership test operators (<a class="reference internal" href="expressions.html#in"><code class="xref std std-keyword docutils literal"><span class="pre">in</span></code></a> and <a class="reference internal" href="expressions.html#not-in"><code class="xref std std-keyword docutils literal"><span class="pre">not</span> <span class="pre">in</span></code></a>) are normally
implemented as an iteration through a sequence.  However, container objects can
supply the following special method with a more efficient implementation, which
also does not require the object be a sequence.</p>
<dl class="method">
<dt id="object.__contains__">
<code class="descclassname">object.</code><code class="descname">__contains__</code><span class="sig-paren">(</span><em>self</em>, <em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement membership test operators.  Should return true if <em>item</em>
is in <em>self</em>, false otherwise.  For mapping objects, this should consider the
keys of the mapping rather than the values or the key-item pairs.</p>
<p>For objects that don&#8217;t define <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></code></a>, the membership test first
tries iteration via <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a>, then the old sequence iteration
protocol via <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>, see <a class="reference internal" href="expressions.html#membership-test-details"><span>this section in the language
reference</span></a>.</p>
</dd></dl>

</div>
<div class="section" id="emulating-numeric-types">
<span id="numeric-types"></span><h3>3.3.7. Emulating numeric types<a class="headerlink" href="#emulating-numeric-types" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to emulate numeric objects. Methods
corresponding to operations that are not supported by the particular kind of
number implemented (e.g., bitwise operations for non-integral numbers) should be
left undefined.</p>
<dl class="method">
<dt id="object.__add__">
<code class="descclassname">object.</code><code class="descname">__add__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__add__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__sub__">
<code class="descclassname">object.</code><code class="descname">__sub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__sub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__mul__">
<code class="descclassname">object.</code><code class="descname">__mul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__matmul__">
<code class="descclassname">object.</code><code class="descname">__matmul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__matmul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__truediv__">
<code class="descclassname">object.</code><code class="descname">__truediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__truediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__floordiv__">
<code class="descclassname">object.</code><code class="descname">__floordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__mod__">
<code class="descclassname">object.</code><code class="descname">__mod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__divmod__">
<code class="descclassname">object.</code><code class="descname">__divmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__divmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__pow__">
<code class="descclassname">object.</code><code class="descname">__pow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__pow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__lshift__">
<code class="descclassname">object.</code><code class="descname">__lshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rshift__">
<code class="descclassname">object.</code><code class="descname">__rshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__and__">
<code class="descclassname">object.</code><code class="descname">__and__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__and__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__xor__">
<code class="descclassname">object.</code><code class="descname">__xor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__xor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__or__">
<code class="descclassname">object.</code><code class="descname">__or__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__or__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-83">These methods are called to implement the binary arithmetic operations
(<code class="docutils literal"><span class="pre">+</span></code>, <code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">*</span></code>, <code class="docutils literal"><span class="pre">&#64;</span></code>, <code class="docutils literal"><span class="pre">/</span></code>, <code class="docutils literal"><span class="pre">//</span></code>, <code class="docutils literal"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal"><span class="pre">divmod()</span></code></a>,
<a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a>, <code class="docutils literal"><span class="pre">**</span></code>, <code class="docutils literal"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal"><span class="pre">&gt;&gt;</span></code>, <code class="docutils literal"><span class="pre">&amp;</span></code>, <code class="docutils literal"><span class="pre">^</span></code>, <code class="docutils literal"><span class="pre">|</span></code>).  For instance, to
evaluate the expression <code class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>, where <em>x</em> is an instance of a class that
has an <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a> method, <code class="docutils literal"><span class="pre">x.__add__(y)</span></code> is called.  The
<a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><code class="xref py py-meth docutils literal"><span class="pre">__divmod__()</span></code></a> method should be the equivalent to using
<a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal"><span class="pre">__floordiv__()</span></code></a> and <a class="reference internal" href="#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal"><span class="pre">__mod__()</span></code></a>; it should not be related to
<a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal"><span class="pre">__truediv__()</span></code></a>.  Note that <a class="reference internal" href="#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal"><span class="pre">__pow__()</span></code></a> should be defined to accept
an optional third argument if the ternary version of the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a>
function is to be supported.</p>
<p>If one of those methods does not support the operation with the supplied
arguments, it should return <code class="docutils literal"><span class="pre">NotImplemented</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__radd__">
<code class="descclassname">object.</code><code class="descname">__radd__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__radd__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rsub__">
<code class="descclassname">object.</code><code class="descname">__rsub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rsub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmul__">
<code class="descclassname">object.</code><code class="descname">__rmul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmatmul__">
<code class="descclassname">object.</code><code class="descname">__rmatmul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmatmul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rtruediv__">
<code class="descclassname">object.</code><code class="descname">__rtruediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rtruediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rfloordiv__">
<code class="descclassname">object.</code><code class="descname">__rfloordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rfloordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmod__">
<code class="descclassname">object.</code><code class="descname">__rmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rdivmod__">
<code class="descclassname">object.</code><code class="descname">__rdivmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdivmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rpow__">
<code class="descclassname">object.</code><code class="descname">__rpow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rpow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rlshift__">
<code class="descclassname">object.</code><code class="descname">__rlshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rlshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rrshift__">
<code class="descclassname">object.</code><code class="descname">__rrshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rrshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rand__">
<code class="descclassname">object.</code><code class="descname">__rand__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rand__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rxor__">
<code class="descclassname">object.</code><code class="descname">__rxor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rxor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ror__">
<code class="descclassname">object.</code><code class="descname">__ror__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ror__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-84">These methods are called to implement the binary arithmetic operations
(<code class="docutils literal"><span class="pre">+</span></code>, <code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">*</span></code>, <code class="docutils literal"><span class="pre">&#64;</span></code>, <code class="docutils literal"><span class="pre">/</span></code>, <code class="docutils literal"><span class="pre">//</span></code>, <code class="docutils literal"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal"><span class="pre">divmod()</span></code></a>,
<a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a>, <code class="docutils literal"><span class="pre">**</span></code>, <code class="docutils literal"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal"><span class="pre">&gt;&gt;</span></code>, <code class="docutils literal"><span class="pre">&amp;</span></code>, <code class="docutils literal"><span class="pre">^</span></code>, <code class="docutils literal"><span class="pre">|</span></code>) with reflected
(swapped) operands.  These functions are only called if the left operand does
not support the corresponding operation and the operands are of different
types. <a class="footnote-reference" href="#id6" id="id3">[2]</a> For instance, to evaluate the expression <code class="docutils literal"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code>, where <em>y</em> is
an instance of a class that has an <a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><code class="xref py py-meth docutils literal"><span class="pre">__rsub__()</span></code></a> method, <code class="docutils literal"><span class="pre">y.__rsub__(x)</span></code>
is called if <code class="docutils literal"><span class="pre">x.__sub__(y)</span></code> returns <em>NotImplemented</em>.</p>
<p id="index-85">Note that ternary <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a> will not try calling <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><code class="xref py py-meth docutils literal"><span class="pre">__rpow__()</span></code></a> (the
coercion rules would become too complicated).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the right operand&#8217;s type is a subclass of the left operand&#8217;s type and that
subclass provides the reflected method for the operation, this method will be
called before the left operand&#8217;s non-reflected method.  This behavior allows
subclasses to override their ancestors&#8217; operations.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__iadd__">
<code class="descclassname">object.</code><code class="descname">__iadd__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iadd__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__isub__">
<code class="descclassname">object.</code><code class="descname">__isub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__isub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imul__">
<code class="descclassname">object.</code><code class="descname">__imul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imatmul__">
<code class="descclassname">object.</code><code class="descname">__imatmul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imatmul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__itruediv__">
<code class="descclassname">object.</code><code class="descname">__itruediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__itruediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ifloordiv__">
<code class="descclassname">object.</code><code class="descname">__ifloordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ifloordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imod__">
<code class="descclassname">object.</code><code class="descname">__imod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ipow__">
<code class="descclassname">object.</code><code class="descname">__ipow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__ipow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ilshift__">
<code class="descclassname">object.</code><code class="descname">__ilshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ilshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__irshift__">
<code class="descclassname">object.</code><code class="descname">__irshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__irshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__iand__">
<code class="descclassname">object.</code><code class="descname">__iand__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iand__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ixor__">
<code class="descclassname">object.</code><code class="descname">__ixor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ixor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ior__">
<code class="descclassname">object.</code><code class="descname">__ior__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ior__" title="Permalink to this definition">¶</a></dt>
<dd><p>These methods are called to implement the augmented arithmetic assignments
(<code class="docutils literal"><span class="pre">+=</span></code>, <code class="docutils literal"><span class="pre">-=</span></code>, <code class="docutils literal"><span class="pre">*=</span></code>, <code class="docutils literal"><span class="pre">&#64;=</span></code>, <code class="docutils literal"><span class="pre">/=</span></code>, <code class="docutils literal"><span class="pre">//=</span></code>, <code class="docutils literal"><span class="pre">%=</span></code>, <code class="docutils literal"><span class="pre">**=</span></code>, <code class="docutils literal"><span class="pre">&lt;&lt;=</span></code>,
<code class="docutils literal"><span class="pre">&gt;&gt;=</span></code>, <code class="docutils literal"><span class="pre">&amp;=</span></code>, <code class="docutils literal"><span class="pre">^=</span></code>, <code class="docutils literal"><span class="pre">|=</span></code>).  These methods should attempt to do the
operation in-place (modifying <em>self</em>) and return the result (which could be,
but does not have to be, <em>self</em>).  If a specific method is not defined, the
augmented assignment falls back to the normal methods.  For instance, if <em>x</em>
is an instance of a class with an <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></code></a> method, <code class="docutils literal"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></code> is
equivalent to <code class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x.__iadd__(y)</span></code> . Otherwise, <code class="docutils literal"><span class="pre">x.__add__(y)</span></code> and
<code class="docutils literal"><span class="pre">y.__radd__(x)</span></code> are considered, as with the evaluation of <code class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>. In
certain situations, augmented assignment can result in unexpected errors (see
<a class="reference internal" href="../faq/programming.html#faq-augmented-assignment-tuple-error"><span>Why does a_tuple[i] += [&#8216;item&#8217;] raise an exception when the addition works?</span></a>), but this behavior is in fact
part of the data model.</p>
</dd></dl>

<dl class="method">
<dt id="object.__neg__">
<code class="descclassname">object.</code><code class="descname">__neg__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__neg__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__pos__">
<code class="descclassname">object.</code><code class="descname">__pos__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__pos__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__abs__">
<code class="descclassname">object.</code><code class="descname">__abs__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__abs__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__invert__">
<code class="descclassname">object.</code><code class="descname">__invert__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__invert__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-86">Called to implement the unary arithmetic operations (<code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">+</span></code>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal"><span class="pre">abs()</span></code></a>
and <code class="docutils literal"><span class="pre">~</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="object.__complex__">
<code class="descclassname">object.</code><code class="descname">__complex__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__complex__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__int__">
<code class="descclassname">object.</code><code class="descname">__int__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__int__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__float__">
<code class="descclassname">object.</code><code class="descname">__float__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__float__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__round__">
<code class="descclassname">object.</code><code class="descname">__round__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__round__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-87">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal"><span class="pre">complex()</span></code></a>,
<a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal"><span class="pre">int()</span></code></a>, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal"><span class="pre">float()</span></code></a> and <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal"><span class="pre">round()</span></code></a>.  Should return a value
of the appropriate type.</p>
</dd></dl>

<dl class="method">
<dt id="object.__index__">
<code class="descclassname">object.</code><code class="descname">__index__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__index__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.index" title="operator.index"><code class="xref py py-func docutils literal"><span class="pre">operator.index()</span></code></a>, and whenever Python needs to
losslessly convert the numeric object to an integer object (such as in
slicing, or in the built-in <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal"><span class="pre">bin()</span></code></a>, <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal"><span class="pre">hex()</span></code></a> and <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal"><span class="pre">oct()</span></code></a>
functions). Presence of this method indicates that the numeric object is
an integer type.  Must return an integer.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In order to have a coherent integer type class, when <a class="reference internal" href="#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal"><span class="pre">__index__()</span></code></a> is
defined <a class="reference internal" href="#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal"><span class="pre">__int__()</span></code></a> should also be defined, and both should return
the same value.</p>
</div>
</dd></dl>

</div>
<div class="section" id="with-statement-context-managers">
<span id="context-managers"></span><h3>3.3.8. With Statement Context Managers<a class="headerlink" href="#with-statement-context-managers" title="Permalink to this headline">¶</a></h3>
<p>A <em class="dfn">context manager</em> is an object that defines the runtime context to be
established when executing a <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a> statement. The context manager
handles the entry into, and the exit from, the desired runtime context for the
execution of the block of code.  Context managers are normally invoked using the
<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a> statement (described in section <a class="reference internal" href="compound_stmts.html#with"><span>The with statement</span></a>), but can also be
used by directly invoking their methods.</p>
<p id="index-88">Typical uses of context managers include saving and restoring various kinds of
global state, locking and unlocking resources, closing opened files, etc.</p>
<p>For more information on context managers, see <a class="reference internal" href="../library/stdtypes.html#typecontextmanager"><span>Context Manager Types</span></a>.</p>
<dl class="method">
<dt id="object.__enter__">
<code class="descclassname">object.</code><code class="descname">__enter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__enter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter the runtime context related to this object. The <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a> statement
will bind this method&#8217;s return value to the target(s) specified in the
<a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal"><span class="pre">as</span></code></a> clause of the statement, if any.</p>
</dd></dl>

<dl class="method">
<dt id="object.__exit__">
<code class="descclassname">object.</code><code class="descname">__exit__</code><span class="sig-paren">(</span><em>self</em>, <em>exc_type</em>, <em>exc_value</em>, <em>traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__exit__" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit the runtime context related to this object. The parameters describe the
exception that caused the context to be exited. If the context was exited
without an exception, all three arguments will be <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>.</p>
<p>If an exception is supplied, and the method wishes to suppress the exception
(i.e., prevent it from being propagated), it should return a true value.
Otherwise, the exception will be processed normally upon exit from this method.</p>
<p>Note that <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></code></a> methods should not reraise the passed-in exception;
this is the caller&#8217;s responsibility.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-89"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The &#8220;with&#8221; statement</dt>
<dd>The specification, background, and examples for the Python <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a>
statement.</dd>
</dl>
</div>
</div>
<div class="section" id="special-method-lookup">
<span id="special-lookup"></span><h3>3.3.9. Special method lookup<a class="headerlink" href="#special-method-lookup" title="Permalink to this headline">¶</a></h3>
<p>For custom classes, implicit invocations of special methods are only guaranteed
to work correctly if defined on an object&#8217;s type, not in the object&#8217;s instance
dictionary.  That behaviour is the reason why the following code raises an
exception:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">object of type &#39;C&#39; has no len()</span>
</pre></div>
</div>
<p>The rationale behind this behaviour lies with a number of special methods such
as <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> and <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a> that are implemented by all objects,
including type objects. If the implicit lookup of these methods used the
conventional lookup process, they would fail when invoked on the type object
itself:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">.</span><span class="n">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">descriptor &#39;__hash__&#39; of &#39;int&#39; object needs an argument</span>
</pre></div>
</div>
<p>Incorrectly attempting to invoke an unbound method of a class in this way is
sometimes referred to as &#8216;metaclass confusion&#8217;, and is avoided by bypassing
the instance when looking up special methods:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">__hash__</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span><span class="o">.</span><span class="n">__hash__</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses the
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> method even of the object&#8217;s metaclass:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Metaclass getattribute invoked&quot;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="n">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">10</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Class getattribute invoked&quot;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">object</span><span class="o">.</span><span class="n">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">__len__</span><span class="p">()</span>                 <span class="c1"># Explicit lookup via instance</span>
<span class="go">Class getattribute invoked</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="n">__len__</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>          <span class="c1"># Explicit lookup via type</span>
<span class="go">Metaclass getattribute invoked</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                      <span class="c1"># Implicit lookup</span>
<span class="go">10</span>
</pre></div>
</div>
<p>Bypassing the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> machinery in this fashion
provides significant scope for speed optimisations within the
interpreter, at the cost of some flexibility in the handling of
special methods (the special method <em>must</em> be set on the class
object itself in order to be consistently invoked by the interpreter).</p>
</div>
</div>
<div class="section" id="coroutines">
<span id="index-90"></span><h2>3.4. Coroutines<a class="headerlink" href="#coroutines" title="Permalink to this headline">¶</a></h2>
<div class="section" id="awaitable-objects">
<h3>3.4.1. Awaitable Objects<a class="headerlink" href="#awaitable-objects" title="Permalink to this headline">¶</a></h3>
<p>An <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object generally implements an <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal"><span class="pre">__await__()</span></code></a> method.
<a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">Coroutine</span></a> objects returned from <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal"><span class="pre">async</span> <span class="pre">def</span></code></a> functions
are awaitable.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="../glossary.html#term-generator-iterator"><span class="xref std std-term">generator iterator</span></a> objects returned from generators
decorated with <a class="reference internal" href="../library/types.html#types.coroutine" title="types.coroutine"><code class="xref py py-func docutils literal"><span class="pre">types.coroutine()</span></code></a> or <a class="reference internal" href="../library/asyncio-task.html#asyncio.coroutine" title="asyncio.coroutine"><code class="xref py py-func docutils literal"><span class="pre">asyncio.coroutine()</span></code></a>
are also awaitable, but they do not implement <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal"><span class="pre">__await__()</span></code></a>.</p>
</div>
<dl class="method">
<dt id="object.__await__">
<code class="descclassname">object.</code><code class="descname">__await__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__await__" title="Permalink to this definition">¶</a></dt>
<dd><p>Must return an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.  Should be used to implement
<a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> objects.  For instance, <a class="reference internal" href="../library/asyncio-task.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal"><span class="pre">asyncio.Future</span></code></a> implements
this method to be compatible with the <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal"><span class="pre">await</span></code></a> expression.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 3.5.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><span class="target" id="index-91"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0492"><strong>PEP 492</strong></a> for additional information about awaitable objects.</p>
</div>
</div>
<div class="section" id="coroutine-objects">
<span id="id4"></span><h3>3.4.2. Coroutine Objects<a class="headerlink" href="#coroutine-objects" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">Coroutine</span></a> objects are <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> objects.
A coroutine&#8217;s execution can be controlled by calling <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal"><span class="pre">__await__()</span></code></a> and
iterating over the result.  When the coroutine has finished executing and
returns, the iterator raises <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></code></a>, and the exception&#8217;s
<code class="xref py py-attr docutils literal"><span class="pre">value</span></code> attribute holds the return value.  If the
coroutine raises an exception, it is propagated by the iterator.  Coroutines
should not directly raise unhandled <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></code></a> exceptions.</p>
<p>Coroutines also have the methods listed below, which are analogous to
those of generators (see <a class="reference internal" href="expressions.html#generator-methods"><span>Generator-iterator methods</span></a>).  However, unlike
generators, coroutines do not directly support iteration.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.5.2: </span>It is a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></code></a> to await on a coroutine more than once.</p>
</div>
<dl class="method">
<dt id="coroutine.send">
<code class="descclassname">coroutine.</code><code class="descname">send</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Starts or resumes execution of the coroutine.  If <em>value</em> is <code class="docutils literal"><span class="pre">None</span></code>,
this is equivalent to advancing the iterator returned by
<a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal"><span class="pre">__await__()</span></code></a>.  If <em>value</em> is not <code class="docutils literal"><span class="pre">None</span></code>, this method delegates
to the <a class="reference internal" href="expressions.html#generator.send" title="generator.send"><code class="xref py py-meth docutils literal"><span class="pre">send()</span></code></a> method of the iterator that caused
the coroutine to suspend.  The result (return value,
<a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></code></a>, or other exception) is the same as when
iterating over the <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal"><span class="pre">__await__()</span></code></a> return value, described above.</p>
</dd></dl>

<dl class="method">
<dt id="coroutine.throw">
<code class="descclassname">coroutine.</code><code class="descname">throw</code><span class="sig-paren">(</span><em>type</em><span class="optional">[</span>, <em>value</em><span class="optional">[</span>, <em>traceback</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.throw" title="Permalink to this definition">¶</a></dt>
<dd><p>Raises the specified exception in the coroutine.  This method delegates
to the <a class="reference internal" href="expressions.html#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal"><span class="pre">throw()</span></code></a> method of the iterator that caused
the coroutine to suspend, if it has such a method.  Otherwise,
the exception is raised at the suspension point.  The result
(return value, <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></code></a>, or other exception) is the same as
when iterating over the <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal"><span class="pre">__await__()</span></code></a> return value, described
above.  If the exception is not caught in the coroutine, it propagates
back to the caller.</p>
</dd></dl>

<dl class="method">
<dt id="coroutine.close">
<code class="descclassname">coroutine.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Causes the coroutine to clean itself up and exit.  If the coroutine
is suspended, this method first delegates to the <a class="reference internal" href="expressions.html#generator.close" title="generator.close"><code class="xref py py-meth docutils literal"><span class="pre">close()</span></code></a>
method of the iterator that caused the coroutine to suspend, if it
has such a method.  Then it raises <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></code></a> at the
suspension point, causing the coroutine to immediately clean itself up.
Finally, the coroutine is marked as having finished executing, even if
it was never started.</p>
<p>Coroutine objects are automatically closed using the above process when
they are about to be destroyed.</p>
</dd></dl>

</div>
<div class="section" id="asynchronous-iterators">
<span id="async-iterators"></span><h3>3.4.3. Asynchronous Iterators<a class="headerlink" href="#asynchronous-iterators" title="Permalink to this headline">¶</a></h3>
<p>An <em>asynchronous iterable</em> is able to call asynchronous code in its
<code class="docutils literal"><span class="pre">__aiter__</span></code> implementation, and an <em>asynchronous iterator</em> can call
asynchronous code in its <code class="docutils literal"><span class="pre">__anext__</span></code> method.</p>
<p>Asynchronous iterators can be used in an <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal"><span class="pre">async</span> <span class="pre">for</span></code></a> statement.</p>
<dl class="method">
<dt id="object.__aiter__">
<code class="descclassname">object.</code><code class="descname">__aiter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aiter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Must return an <em>asynchronous iterator</em> object.</p>
</dd></dl>

<dl class="method">
<dt id="object.__anext__">
<code class="descclassname">object.</code><code class="descname">__anext__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__anext__" title="Permalink to this definition">¶</a></dt>
<dd><p>Must return an <em>awaitable</em> resulting in a next value of the iterator.  Should
raise a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopAsyncIteration</span></code></a> error when the iteration is over.</p>
</dd></dl>

<p>An example of an asynchronous iterable object:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Reader</span><span class="p">:</span>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">readline</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

    <span class="k">def</span> <span class="nf">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">async</span> <span class="k">def</span> <span class="nf">__anext__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">val</span> <span class="o">=</span> <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">val</span> <span class="o">==</span> <span class="n">b</span><span class="s1">&#39;&#39;</span><span class="p">:</span>
            <span class="k">raise</span> <span class="n">StopAsyncIteration</span>
        <span class="k">return</span> <span class="n">val</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.5.</span></p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<div class="last versionchanged">
<p><span class="versionmodified">Changed in version 3.5.2: </span>Starting with CPython 3.5.2, <code class="docutils literal"><span class="pre">__aiter__</span></code> can directly return
<a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterators</span></a>.  Returning
an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object will result in a
<a class="reference internal" href="../library/exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal"><span class="pre">PendingDeprecationWarning</span></code></a>.</p>
<p>The recommended way of writing backwards compatible code in
CPython 3.5.x is to continue returning awaitables from
<code class="docutils literal"><span class="pre">__aiter__</span></code>.  If you want to avoid the PendingDeprecationWarning
and keep the code backwards compatible, the following decorator
can be used:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span> <span class="o">&lt;</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">aiter_compat</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
        <span class="nd">@functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">func</span><span class="p">)</span>
        <span class="k">async</span> <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">func</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">wrapper</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">aiter_compat</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">func</span>
</pre></div>
</div>
<p>Example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">AsyncIterator</span><span class="p">:</span>

    <span class="nd">@aiter_compat</span>
    <span class="k">def</span> <span class="nf">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">async</span> <span class="k">def</span> <span class="nf">__anext__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>Starting with CPython 3.6, the <a class="reference internal" href="../library/exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal"><span class="pre">PendingDeprecationWarning</span></code></a>
will be replaced with the <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal"><span class="pre">DeprecationWarning</span></code></a>.
In CPython 3.7, returning an awaitable from <code class="docutils literal"><span class="pre">__aiter__</span></code> will
result in a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></code></a>.</p>
</div>
</div>
</div>
<div class="section" id="asynchronous-context-managers">
<h3>3.4.4. Asynchronous Context Managers<a class="headerlink" href="#asynchronous-context-managers" title="Permalink to this headline">¶</a></h3>
<p>An <em>asynchronous context manager</em> is a <em>context manager</em> that is able to
suspend execution in its <code class="docutils literal"><span class="pre">__aenter__</span></code> and <code class="docutils literal"><span class="pre">__aexit__</span></code> methods.</p>
<p>Asynchronous context managers can be used in an <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal"><span class="pre">async</span> <span class="pre">with</span></code></a> statement.</p>
<dl class="method">
<dt id="object.__aenter__">
<code class="descclassname">object.</code><code class="descname">__aenter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aenter__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is semantically similar to the <a class="reference internal" href="#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></code></a>, with only
difference that it must return an <em>awaitable</em>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__aexit__">
<code class="descclassname">object.</code><code class="descname">__aexit__</code><span class="sig-paren">(</span><em>self</em>, <em>exc_type</em>, <em>exc_value</em>, <em>traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aexit__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is semantically similar to the <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></code></a>, with only
difference that it must return an <em>awaitable</em>.</p>
</dd></dl>

<p>An example of an asynchronous context manager class:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">AsyncContextManager</span><span class="p">:</span>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">__aenter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">await</span> <span class="n">log</span><span class="p">(</span><span class="s1">&#39;entering context&#39;</span><span class="p">)</span>

    <span class="k">async</span> <span class="k">def</span> <span class="nf">__aexit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
        <span class="k">await</span> <span class="n">log</span><span class="p">(</span><span class="s1">&#39;exiting context&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.5.</span></p>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>It <em>is</em> possible in some cases to change an object&#8217;s type, under certain
controlled conditions. It generally isn&#8217;t a good idea though, since it can
lead to some very strange behaviour if it is handled incorrectly.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[2]</a></td><td>For operands of the same type, it is assumed that if the non-reflected method
(such as <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a>) fails the operation is not supported, which is why the
reflected method is not called.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">3. Data model</a><ul>
<li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li>
<li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
<li><a class="reference internal" href="#special-method-names">3.3. Special method names</a><ul>
<li><a class="reference internal" href="#basic-customization">3.3.1. Basic customization</a></li>
<li><a class="reference internal" href="#customizing-attribute-access">3.3.2. Customizing attribute access</a><ul>
<li><a class="reference internal" href="#implementing-descriptors">3.3.2.1. Implementing Descriptors</a></li>
<li><a class="reference internal" href="#invoking-descriptors">3.3.2.2. Invoking Descriptors</a></li>
<li><a class="reference internal" href="#slots">3.3.2.3. __slots__</a><ul>
<li><a class="reference internal" href="#notes-on-using-slots">3.3.2.3.1. Notes on using <em>__slots__</em></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#customizing-class-creation">3.3.3. Customizing class creation</a><ul>
<li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.1. Determining the appropriate metaclass</a></li>
<li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.2. Preparing the class namespace</a></li>
<li><a class="reference internal" href="#executing-the-class-body">3.3.3.3. Executing the class body</a></li>
<li><a class="reference internal" href="#creating-the-class-object">3.3.3.4. Creating the class object</a></li>
<li><a class="reference internal" href="#metaclass-example">3.3.3.5. Metaclass example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. Customizing instance and subclass checks</a></li>
<li><a class="reference internal" href="#emulating-callable-objects">3.3.5. Emulating callable objects</a></li>
<li><a class="reference internal" href="#emulating-container-types">3.3.6. Emulating container types</a></li>
<li><a class="reference internal" href="#emulating-numeric-types">3.3.7. Emulating numeric types</a></li>
<li><a class="reference internal" href="#with-statement-context-managers">3.3.8. With Statement Context Managers</a></li>
<li><a class="reference internal" href="#special-method-lookup">3.3.9. Special method lookup</a></li>
</ul>
</li>
<li><a class="reference internal" href="#coroutines">3.4. Coroutines</a><ul>
<li><a class="reference internal" href="#awaitable-objects">3.4.1. Awaitable Objects</a></li>
<li><a class="reference internal" href="#coroutine-objects">3.4.2. Coroutine Objects</a></li>
<li><a class="reference internal" href="#asynchronous-iterators">3.4.3. Asynchronous Iterators</a></li>
<li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. Asynchronous Context Managers</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="lexical_analysis.html"
                        title="previous chapter">2. Lexical analysis</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="executionmodel.html"
                        title="next chapter">4. Execution model</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li><a href="../_sources/reference/datamodel.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             >next</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.5.3</span>
          <a href="../index.html">Documentation </a> &raquo;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &raquo;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 2001-2017, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jan 20, 2017.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
    </div>

  </body>
</html>