Server : Apache System : Linux server1.cgrithy.com 3.10.0-1160.95.1.el7.x86_64 #1 SMP Mon Jul 24 13:59:37 UTC 2023 x86_64 User : nobody ( 99) PHP Version : 8.1.23 Disable Function : NONE Directory : /usr/share/doc/python-docs-2.7.5/html/reference/ |
<!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 — Python 2.7.5 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.7.5', 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 2.7.5 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 2.7.5 documentation" href="../index.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> </head> <body> <div class="related"> <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="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" accesskey="U">The Python Language Reference</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <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’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’s model of a “stored program computer,” code is also represented by objects.)</p> <p id="index-1">Every object has an identity, a type and a value. An object’s <em>identity</em> never changes once it has been created; you may think of it as the object’s address in memory. The ‘<a class="reference internal" href="expressions.html#is"><tt class="xref std std-keyword docutils literal"><span class="pre">is</span></tt></a>‘ operator compares the identity of two objects; the <a class="reference internal" href="../library/functions.html#id" title="id"><tt class="xref py py-func docutils literal"><span class="pre">id()</span></tt></a> function returns an integer representing its identity (currently implemented as its address). An object’s <em class="dfn">type</em> is also unchangeable. <a class="footnote-reference" href="#id5" id="id1">[1]</a> An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a> function returns an object’s type (which is an object itself). 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’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’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 — 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."><tt class="xref py py-mod docutils literal"><span class="pre">gc</span></tt></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 (ex: always close files).</p> </div> <p>Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a ‘<a class="reference internal" href="compound_stmts.html#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a>...<a class="reference internal" href="compound_stmts.html#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a>‘ statement may keep objects alive.</p> <p>Some objects contain references to “external” 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 <tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> method. Programs are strongly recommended to explicitly close such objects. The ‘<a class="reference internal" href="compound_stmts.html#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a>...<a class="reference internal" href="compound_stmts.html#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a>‘ statement provides a convenient way 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’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 <tt 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></tt>, <tt class="docutils literal"><span class="pre">a</span></tt> and <tt class="docutils literal"><span class="pre">b</span></tt> may or may not refer to the same object with the value one, depending on the implementation, but after <tt 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></tt>, <tt class="docutils literal"><span class="pre">c</span></tt> and <tt class="docutils literal"><span class="pre">d</span></tt> are guaranteed to refer to two different, unique, newly created empty lists. (Note that <tt 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></tt> assigns the same object to both <tt class="docutils literal"><span class="pre">c</span></tt> and <tt class="docutils literal"><span class="pre">d</span></tt>.)</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.).</p> <p id="index-5">Some of the type descriptions below contain a paragraph listing ‘special attributes.’ 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 <tt class="docutils literal"><span class="pre">None</span></tt>. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false.</p> </dd> <dt>NotImplemented</dt> <dd><p class="first last" 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 <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>. Numeric methods and rich comparison methods may 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> </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 built-in name <tt class="docutils literal"><span class="pre">Ellipsis</span></tt>. It is used to indicate the presence of the <tt class="docutils literal"><span class="pre">...</span></tt> syntax in a slice. Its truth value is true.</p> </dd> <dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Number</span></tt></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"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Integral</span></tt></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 three types of integers:</p> <dl class="docutils"> <dt>Plain integers</dt> <dd><p class="first last" id="index-11">These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation would fall outside this range, the result is normally returned as a long integer (in some cases, the exception <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a> is raised instead). For the purpose of shift and mask operations, integers are assumed to have a binary, 2’s complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).</p> </dd> <dt>Long integers</dt> <dd><p class="first last" id="index-12">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’s complement which gives the illusion of an infinite string of sign bits extending to the left.</p> </dd> <dt>Booleans</dt> <dd><p class="first last" id="index-13">These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, 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 <tt class="docutils literal"><span class="pre">"False"</span></tt> or <tt class="docutils literal"><span class="pre">"True"</span></tt> are returned, respectively.</p> </dd> </dl> <p class="last" id="index-14">The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers and the least surprises when switching between the plain and long integer domains. Any operation, if it yields a result in the plain integer domain, will yield the same result in the long integer domain or when using mixed operands. The switch between domains is transparent to the programmer.</p> </dd> <dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></tt></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>)</dt> <dd><p class="first last" id="index-15">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 is 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"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Complex</span></tt></a></dt> <dd><p class="first last" id="index-16">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 <tt class="docutils literal"><span class="pre">z</span></tt> can be retrieved through the read-only attributes <tt class="docutils literal"><span class="pre">z.real</span></tt> and <tt class="docutils literal"><span class="pre">z.imag</span></tt>.</p> </dd> </dl> </dd> <dt>Sequences</dt> <dd><p class="first" id="index-17">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"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></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 <tt class="docutils literal"><span class="pre">a[i]</span></tt>.</p> <p id="index-18">Sequences also support slicing: <tt class="docutils literal"><span class="pre">a[i:j]</span></tt> selects all items with index <em>k</em> such that <em>i</em> <tt class="docutils literal"><span class="pre"><=</span></tt> <em>k</em> <tt class="docutils literal"><span class="pre"><</span></tt> <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 id="index-19">Some sequences also support “extended slicing” with a third “step” parameter: <tt class="docutils literal"><span class="pre">a[i:j:k]</span></tt> selects all items of <em>a</em> with index <em>x</em> where <tt 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></tt>, <em>n</em> <tt class="docutils literal"><span class="pre">>=</span></tt> <tt class="docutils literal"><span class="pre">0</span></tt> and <em>i</em> <tt class="docutils literal"><span class="pre"><=</span></tt> <em>x</em> <tt class="docutils literal"><span class="pre"><</span></tt> <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-20">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"> <dt>Strings</dt> <dd><p class="first" id="index-21">The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions <a class="reference internal" href="../library/functions.html#chr" title="chr"><tt class="xref py py-func docutils literal"><span class="pre">chr()</span></tt></a> and <a class="reference internal" href="../library/functions.html#ord" title="ord"><tt class="xref py py-func docutils literal"><span class="pre">ord()</span></tt></a> convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file.</p> <p class="last" id="index-22">(On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions <a class="reference internal" href="../library/functions.html#chr" title="chr"><tt class="xref py py-func docutils literal"><span class="pre">chr()</span></tt></a> and <a class="reference internal" href="../library/functions.html#ord" title="ord"><tt class="xref py py-func docutils literal"><span class="pre">ord()</span></tt></a> implement a mapping between ASCII and EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?)</p> </dd> <dt>Unicode</dt> <dd><p class="first last" id="index-23">The items of a Unicode object are Unicode code units. A Unicode code unit is represented by a Unicode object of one item and can hold either a 16-bit or 32-bit value representing a Unicode ordinal (the maximum value for the ordinal is given in <tt class="docutils literal"><span class="pre">sys.maxunicode</span></tt>, and depends on how Python is configured at compile time). Surrogate pairs may be present in the Unicode object, and will be reported as two separate items. The built-in functions <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><tt class="xref py py-func docutils literal"><span class="pre">unichr()</span></tt></a> and <a class="reference internal" href="../library/functions.html#ord" title="ord"><tt class="xref py py-func docutils literal"><span class="pre">ord()</span></tt></a> convert between code units and nonnegative integers representing the Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to other encodings are possible through the Unicode method <tt class="xref py py-meth docutils literal"><span class="pre">encode()</span></tt> and the built-in function <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><tt class="xref py py-func docutils literal"><span class="pre">unicode()</span></tt></a>.</p> </dd> <dt>Tuples</dt> <dd><p class="first last" id="index-24">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 ‘singleton’) 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> </dl> </dd> <dt>Mutable sequences</dt> <dd><p class="first" id="index-25">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"><tt class="xref std std-keyword docutils literal"><span class="pre">del</span></tt></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-26">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-27">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"><tt class="xref py py-func docutils literal"><span class="pre">bytearray()</span></tt></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-28">The extension module <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><tt class="xref py py-mod docutils literal"><span class="pre">array</span></tt></a> provides an additional example of a mutable sequence type.</p> </dd> </dl> </dd> <dt>Set types</dt> <dd><p class="first" id="index-29">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"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></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., <tt class="docutils literal"><span class="pre">1</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>), 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-30">These represent a mutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-func docutils literal"><span class="pre">set()</span></tt></a> constructor and can be modified afterwards by several methods, such as <tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt>.</p> </dd> <dt>Frozen sets</dt> <dd><p class="first last" id="index-31">These represent an immutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-func docutils literal"><span class="pre">frozenset()</span></tt></a> constructor. As a frozenset is immutable and <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></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-32">These represent finite sets of objects indexed by arbitrary index sets. The subscript notation <tt class="docutils literal"><span class="pre">a[k]</span></tt> selects the item indexed by <tt class="docutils literal"><span class="pre">k</span></tt> from the mapping <tt class="docutils literal"><span class="pre">a</span></tt>; this can be used in expressions and as the target of assignments or <a class="reference internal" href="simple_stmts.html#del"><tt class="xref std std-keyword docutils literal"><span class="pre">del</span></tt></a> statements. The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></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-33">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’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., <tt class="docutils literal"><span class="pre">1</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>) then they can be used interchangeably to index the same dictionary entry.</p> <p>Dictionaries are mutable; they can be created by the <tt class="docutils literal"><span class="pre">{...}</span></tt> notation (see section <a class="reference internal" href="expressions.html#dict"><em>Dictionary displays</em></a>).</p> <p class="last" id="index-34">The extension modules <a class="reference internal" href="../library/dbm.html#module-dbm" title="dbm: The standard "database" interface, based on ndbm. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">dbm</span></tt></a>, <a class="reference internal" href="../library/gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">gdbm</span></tt></a>, and <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><tt class="xref py py-mod docutils literal"><span class="pre">bsddb</span></tt></a> provide additional examples of mapping types.</p> </dd> </dl> </dd> <dt>Callable types</dt> <dd><p class="first" id="index-35">These are the types to which the function call operation (see section <a class="reference internal" href="expressions.html#calls"><em>Calls</em></a>) can be applied:</p> <dl class="last docutils"> <dt>User-defined functions</dt> <dd><p class="first" id="index-36">A user-defined function object is created by a function definition (see section <a class="reference internal" href="compound_stmts.html#function"><em>Function definitions</em></a>). It should be called with an argument list containing the same number of items as the function’s formal parameter list.</p> <p>Special attributes:</p> <table border="1" class="docutils"> <colgroup> <col width="35%" /> <col width="48%" /> <col width="17%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Attribute</th> <th class="head">Meaning</th> <th class="head"> </th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_doc</span></tt></td> <td>The function’s documentation string, or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable</td> <td>Writable</td> </tr> <tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt></td> <td>Another way of spelling <tt class="xref py py-attr docutils literal"><span class="pre">func_doc</span></tt></td> <td>Writable</td> </tr> <tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_name</span></tt></td> <td>The function’s name</td> <td>Writable</td> </tr> <tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt></td> <td>Another way of spelling <tt class="xref py py-attr docutils literal"><span class="pre">func_name</span></tt></td> <td>Writable</td> </tr> <tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt></td> <td>The name of the module the function was defined in, or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable.</td> <td>Writable</td> </tr> <tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_defaults</span></tt></td> <td>A tuple containing default argument values for those arguments that have defaults, or <tt class="docutils literal"><span class="pre">None</span></tt> if no arguments have a default value</td> <td>Writable</td> </tr> <tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_code</span></tt></td> <td>The code object representing the compiled function body.</td> <td>Writable</td> </tr> <tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_globals</span></tt></td> <td>A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined.</td> <td>Read-only</td> </tr> <tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_dict</span></tt></td> <td>The namespace supporting arbitrary function attributes.</td> <td>Writable</td> </tr> <tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">func_closure</span></tt></td> <td><tt class="docutils literal"><span class="pre">None</span></tt> or a tuple of cells that contain bindings for the function’s free variables.</td> <td>Read-only</td> </tr> </tbody> </table> <p>Most of the attributes labelled “Writable” check the type of the assigned value.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.4: </span><tt class="docutils literal"><span class="pre">func_name</span></tt> is now writable.</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’s definition can be retrieved from its code object; see the description of internal types below.</p> </dd> <dt>User-defined methods</dt> <dd><p class="first" id="index-38">A user-defined method object combines a class, a class instance (or <tt class="docutils literal"><span class="pre">None</span></tt>) and any callable object (normally a user-defined function).</p> <p>Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> is the class instance object, <tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt> is the function object; <tt class="xref py py-attr docutils literal"><span class="pre">im_class</span></tt> is the class of <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> for bound methods or the class that asked for the method for unbound methods; <tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the method’s documentation (same as <tt class="docutils literal"><span class="pre">im_func.__doc__</span></tt>); <tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt> is the method name (same as <tt class="docutils literal"><span class="pre">im_func.__name__</span></tt>); <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> is the name of the module the method was defined in, or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.2: </span><tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> used to refer to the class that defined the method.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>For Python 3 forward-compatibility, <tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt> is also available as <tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt>, and <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> as <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt>.</p> <p id="index-39">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, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.</p> <p id="index-40">When a user-defined method object is created by retrieving a user-defined function object from a class, its <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> attribute is <tt class="docutils literal"><span class="pre">None</span></tt> and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> attribute is the instance, and the method object is said to be bound. In either case, the new method’s <tt class="xref py py-attr docutils literal"><span class="pre">im_class</span></tt> attribute is the class from which the retrieval takes place, and its <tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt> attribute is the original function object.</p> <p id="index-41">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 <tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt> attribute of the new instance is not the original method object but its <tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt> attribute.</p> <p id="index-42">When a user-defined method object is created by retrieving a class method object from a class or instance, its <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> attribute is the class itself, and its <tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt> attribute is the function object underlying the class method.</p> <p>When an unbound user-defined method object is called, the underlying function (<tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt>) is called, with the restriction that the first argument must be an instance of the proper class (<tt class="xref py py-attr docutils literal"><span class="pre">im_class</span></tt>) or of a derived class thereof.</p> <p>When a bound user-defined method object is called, the underlying function (<tt class="xref py py-attr docutils literal"><span class="pre">im_func</span></tt>) is called, inserting the class instance (<tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt>) in front of the argument list. For instance, when <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt> is a class which contains a definition for a function <tt class="xref py py-meth docutils literal"><span class="pre">f()</span></tt>, and <tt class="docutils literal"><span class="pre">x</span></tt> is an instance of <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>, calling <tt class="docutils literal"><span class="pre">x.f(1)</span></tt> is equivalent to calling <tt class="docutils literal"><span class="pre">C.f(x,</span> <span class="pre">1)</span></tt>.</p> <p>When a user-defined method object is derived from a class method object, the “class instance” stored in <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> will actually be the class itself, so that calling either <tt class="docutils literal"><span class="pre">x.f(1)</span></tt> or <tt class="docutils literal"><span class="pre">C.f(1)</span></tt> is equivalent to calling <tt class="docutils literal"><span class="pre">f(C,1)</span></tt> where <tt class="docutils literal"><span class="pre">f</span></tt> is the underlying function.</p> <p class="last">Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or 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-43">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement (see section <a class="reference internal" href="simple_stmts.html#yield"><em>The yield statement</em></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’s <a class="reference internal" href="../library/functions.html#next" title="next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> method will cause the function to execute until it provides a value using the <a class="reference internal" href="simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement. When the function executes a <a class="reference internal" href="simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a> exception is raised and the iterator will have reached the end of the set of values to be returned.</p> </dd> <dt>Built-in functions</dt> <dd><p class="first last" id="index-44">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"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><tt class="xref py py-func docutils literal"><span class="pre">math.sin()</span></tt></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><tt class="xref py py-mod docutils literal"><span class="pre">math</span></tt></a> is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the function’s documentation string, or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable; <tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt> is the function’s name; <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> is set to <tt class="docutils literal"><span class="pre">None</span></tt> (but see the next item); <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> is the name of the module the function was defined in or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable.</p> </dd> <dt>Built-in methods</dt> <dd><p class="first last" id="index-45">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 <tt class="docutils literal"><span class="pre">alist.append()</span></tt>, assuming <em>alist</em> is a list object. In this case, the special read-only attribute <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> is set to the object denoted by <em>alist</em>.</p> </dd> <dt>Class Types</dt> <dd>Class types, or “new-style 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a>. The arguments of the call are passed to <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> to initialize the new instance.</dd> <dt>Classic Classes</dt> <dd><p class="first last" id="index-46">Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method if it has one. Any arguments are passed on to the <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method. If there is no <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method, the class must be called without arguments.</p> </dd> <dt>Class instances</dt> <dd>Class instances are described below. Class instances are callable only when the class has a <a class="reference internal" href="#object.__call__" title="object.__call__"><tt class="xref py py-meth docutils literal"><span class="pre">__call__()</span></tt></a> method; <tt class="docutils literal"><span class="pre">x(arguments)</span></tt> is a shorthand for <tt class="docutils literal"><span class="pre">x.__call__(arguments)</span></tt>.</dd> </dl> </dd> <dt>Modules</dt> <dd><p class="first" id="index-47">Modules are imported by the <a class="reference internal" href="simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a> statement (see section <a class="reference internal" href="simple_stmts.html#import"><em>The import statement</em></a>). A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the func_globals attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., <tt class="docutils literal"><span class="pre">m.x</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">m.__dict__["x"]</span></tt>. A module object does not contain the code object used to initialize the module (since it isn’t needed once the initialization is done).</p> <p>Attribute assignment updates the module’s namespace dictionary, e.g., <tt class="docutils literal"><span class="pre">m.x</span> <span class="pre">=</span> <span class="pre">1</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">m.__dict__["x"]</span> <span class="pre">=</span> <span class="pre">1</span></tt>.</p> <p id="index-48">Special read-only attribute: <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> is the module’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-49">Predefined (writable) attributes: <tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt> is the module’s name; <tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the module’s documentation string, or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable; <tt class="xref py py-attr docutils literal"><span class="pre">__file__</span></tt> is the pathname of the file from which the module was loaded, if it was loaded from a file. The <tt class="xref py py-attr docutils literal"><span class="pre">__file__</span></tt> attribute is not present for 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>Classes</dt> <dd><p class="first">Both class types (new-style classes) and class objects (old-style/classic classes) are typically created by class definitions (see section <a class="reference internal" href="compound_stmts.html#class"><em>Class definitions</em></a>). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., <tt class="docutils literal"><span class="pre">C.x</span></tt> is translated to <tt class="docutils literal"><span class="pre">C.__dict__["x"]</span></tt> (although for new-style classes in particular 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. For old-style classes, the search is depth-first, left-to-right in the order of occurrence in the base class list. New-style classes use the more complex C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by new-style classes can be found in the documentation accompanying the 2.3 release at <a class="reference external" href="http://www.python.org/download/releases/2.3/mro/">http://www.python.org/download/releases/2.3/mro/</a>.</p> <p id="index-50">When a class attribute reference (for class <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>, say) would yield a user-defined function object or an unbound user-defined method object whose associated class is either <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt> or one of its base classes, it is transformed into an unbound user-defined method object whose <tt class="xref py py-attr docutils literal"><span class="pre">im_class</span></tt> attribute is <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>. When it would yield a class method object, it is transformed into a bound user-defined method object whose <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> attribute is <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>. 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"><em>Implementing Descriptors</em></a> for another way in which attributes retrieved from a class may differ from those actually contained in its <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> (note that only new-style classes support descriptors).</p> <p id="index-51">Class attribute assignments update the class’s dictionary, never the dictionary of a base class.</p> <p id="index-52">A class object can be called (see above) to yield a class instance (see below).</p> <p class="last" id="index-53">Special attributes: <tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt> is the class name; <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> is the module name in which the class was defined; <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> is the dictionary containing the class’s namespace; <tt class="xref py py-attr docutils literal"><span class="pre">__bases__</span></tt> is a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list; <tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the class’s documentation string, or None if undefined.</p> </dd> <dt>Class instances</dt> <dd><p class="first" id="index-54">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’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 or an unbound user-defined method object whose associated class is the class (call it <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>) of the instance for which the attribute reference was initiated or one of its bases, it is transformed into a bound user-defined method object whose <tt class="xref py py-attr docutils literal"><span class="pre">im_class</span></tt> attribute is <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt> and whose <tt class="xref py py-attr docutils literal"><span class="pre">im_self</span></tt> attribute is the instance. Static method and class method objects are also transformed, as if they had been retrieved from class <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>; see above under “Classes”. See section <a class="reference internal" href="#descriptors"><em>Implementing Descriptors</em></a> for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>. If no class attribute is found, and the object’s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> method, that is called to satisfy the lookup.</p> <p id="index-55">Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a> or <a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__delattr__()</span></tt></a> method, this is called instead of updating the instance dictionary directly.</p> <p id="index-56">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"><em>Special method names</em></a>.</p> <p class="last" id="index-57">Special attributes: <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> is the attribute dictionary; <tt class="xref py py-attr docutils literal"><span class="pre">__class__</span></tt> is the instance’s class.</p> </dd> <dt>Files</dt> <dd><p class="first last" id="index-58">A file object represents an open file. File objects are created by the <a class="reference internal" href="../library/functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> built-in function, and also by <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><tt class="xref py py-func docutils literal"><span class="pre">os.popen()</span></tt></a>, <a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><tt class="xref py py-func docutils literal"><span class="pre">os.fdopen()</span></tt></a>, and the <tt class="xref py py-meth docutils literal"><span class="pre">makefile()</span></tt> method of socket objects (and perhaps by other functions or methods provided by extension modules). The objects <tt class="docutils literal"><span class="pre">sys.stdin</span></tt>, <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> and <tt class="docutils literal"><span class="pre">sys.stderr</span></tt> are initialized to file objects corresponding to the interpreter’s standard input, output and error streams. See <a class="reference internal" href="../library/stdtypes.html#bltin-file-objects"><em>File Objects</em></a> for complete documentation of file objects.</p> </dd> <dt>Internal types</dt> <dd><p class="first" id="index-59">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"> <dt>Code objects</dt> <dd><p class="first" id="index-60">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><em class="xref std std-term">bytecode</em></a>. The difference between a code object and a function object is that the function object contains an explicit reference to the function’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-61">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">co_name</span></tt> gives the function name; <tt class="xref py py-attr docutils literal"><span class="pre">co_argcount</span></tt> is the number of positional arguments (including arguments with default values); <tt class="xref py py-attr docutils literal"><span class="pre">co_nlocals</span></tt> is the number of local variables used by the function (including arguments); <tt class="xref py py-attr docutils literal"><span class="pre">co_varnames</span></tt> is a tuple containing the names of the local variables (starting with the argument names); <tt class="xref py py-attr docutils literal"><span class="pre">co_cellvars</span></tt> is a tuple containing the names of local variables that are referenced by nested functions; <tt class="xref py py-attr docutils literal"><span class="pre">co_freevars</span></tt> is a tuple containing the names of free variables; <tt class="xref py py-attr docutils literal"><span class="pre">co_code</span></tt> is a string representing the sequence of bytecode instructions; <tt class="xref py py-attr docutils literal"><span class="pre">co_consts</span></tt> is a tuple containing the literals used by the bytecode; <tt class="xref py py-attr docutils literal"><span class="pre">co_names</span></tt> is a tuple containing the names used by the bytecode; <tt class="xref py py-attr docutils literal"><span class="pre">co_filename</span></tt> is the filename from which the code was compiled; <tt class="xref py py-attr docutils literal"><span class="pre">co_firstlineno</span></tt> is the first line number of the function; <tt class="xref py py-attr docutils literal"><span class="pre">co_lnotab</span></tt> is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); <tt class="xref py py-attr docutils literal"><span class="pre">co_stacksize</span></tt> is the required stack size (including local variables); <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt> is an integer encoding a number of flags for the interpreter.</p> <p id="index-62">The following flag bits are defined for <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt>: bit <tt class="docutils literal"><span class="pre">0x04</span></tt> is set if the function uses the <tt class="docutils literal"><span class="pre">*arguments</span></tt> syntax to accept an arbitrary number of positional arguments; bit <tt class="docutils literal"><span class="pre">0x08</span></tt> is set if the function uses the <tt class="docutils literal"><span class="pre">**keywords</span></tt> syntax to accept arbitrary keyword arguments; bit <tt class="docutils literal"><span class="pre">0x20</span></tt> is set if the function is a generator.</p> <p>Future feature declarations (<tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></tt>) also use bits in <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt> to indicate whether a code object was compiled with a particular feature enabled: bit <tt class="docutils literal"><span class="pre">0x2000</span></tt> is set if the function was compiled with future division enabled; bits <tt class="docutils literal"><span class="pre">0x10</span></tt> and <tt class="docutils literal"><span class="pre">0x1000</span></tt> were used in earlier versions of Python.</p> <p>Other bits in <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt> are reserved for internal use.</p> <p class="last" id="index-63">If a code object represents a function, the first item in <tt class="xref py py-attr docutils literal"><span class="pre">co_consts</span></tt> is the documentation string of the function, or <tt class="docutils literal"><span class="pre">None</span></tt> if undefined.</p> </dd> </dl> <dl class="last docutils" id="frame-objects"> <dt>Frame objects</dt> <dd><p class="first" id="index-64">Frame objects represent execution frames. They may occur in traceback objects (see below).</p> <p id="index-65">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">f_back</span></tt> is to the previous stack frame (towards the caller), or <tt class="docutils literal"><span class="pre">None</span></tt> if this is the bottom stack frame; <tt class="xref py py-attr docutils literal"><span class="pre">f_code</span></tt> is the code object being executed in this frame; <tt class="xref py py-attr docutils literal"><span class="pre">f_locals</span></tt> is the dictionary used to look up local variables; <tt class="xref py py-attr docutils literal"><span class="pre">f_globals</span></tt> is used for global variables; <tt class="xref py py-attr docutils literal"><span class="pre">f_builtins</span></tt> is used for built-in (intrinsic) names; <tt class="xref py py-attr docutils literal"><span class="pre">f_restricted</span></tt> is a flag indicating whether the function is executing in restricted execution mode; <tt class="xref py py-attr docutils literal"><span class="pre">f_lasti</span></tt> gives the precise instruction (this is an index into the bytecode string of the code object).</p> <p class="last" id="index-66">Special writable attributes: <tt class="xref py py-attr docutils literal"><span class="pre">f_trace</span></tt>, if not <tt class="docutils literal"><span class="pre">None</span></tt>, is a function called at the start of each source code line (this is used by the debugger); <tt class="xref py py-attr docutils literal"><span class="pre">f_exc_type</span></tt>, <tt class="xref py py-attr docutils literal"><span class="pre">f_exc_value</span></tt>, <tt class="xref py py-attr docutils literal"><span class="pre">f_exc_traceback</span></tt> represent the last exception raised in the parent frame provided another exception was ever raised in the current frame (in all other cases they are None); <tt class="xref py py-attr docutils literal"><span class="pre">f_lineno</span></tt> is the current line number of the frame — 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> </dd> <dt>Traceback objects</dt> <dd><p class="first" id="index-67">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"><em>The try statement</em></a>.) It is accessible as <tt class="docutils literal"><span class="pre">sys.exc_traceback</span></tt>, and also as the third item of the tuple returned by <tt class="docutils literal"><span class="pre">sys.exc_info()</span></tt>. The latter is the preferred interface, since it works correctly when the program is using multiple threads. 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 <tt class="docutils literal"><span class="pre">sys.last_traceback</span></tt>.</p> <p class="last" id="index-68">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">tb_next</span></tt> is the next level in the stack trace (towards the frame where the exception occurred), or <tt class="docutils literal"><span class="pre">None</span></tt> if there is no next level; <tt class="xref py py-attr docutils literal"><span class="pre">tb_frame</span></tt> points to the execution frame of the current level; <tt class="xref py py-attr docutils literal"><span class="pre">tb_lineno</span></tt> gives the line number where the exception occurred; <tt class="xref py py-attr docutils literal"><span class="pre">tb_lasti</span></tt> 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"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> statement with no matching except clause or with a finally clause.</p> </dd> <dt>Slice objects</dt> <dd><p class="first" id="index-69">Slice objects are used to represent slices when <em>extended slice syntax</em> is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., <tt class="docutils literal"><span class="pre">a[i:j:step]</span></tt>, <tt class="docutils literal"><span class="pre">a[i:j,</span> <span class="pre">k:l]</span></tt>, or <tt class="docutils literal"><span class="pre">a[...,</span> <span class="pre">i:j]</span></tt>. They are also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><tt class="xref py py-func docutils literal"><span class="pre">slice()</span></tt></a> function.</p> <p id="index-70">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">start</span></tt> is the lower bound; <tt class="xref py py-attr docutils literal"><span class="pre">stop</span></tt> is the upper bound; <tt class="xref py py-attr docutils literal"><span class="pre">step</span></tt> is the step value; each is <tt class="docutils literal"><span class="pre">None</span></tt> if omitted. These attributes can have any type.</p> <p>Slice objects support one method:</p> <dl class="last method"> <dt id="slice.indices"> <tt class="descclassname">slice.</tt><tt class="descname">indices</tt><big>(</big><em>self</em>, <em>length</em><big>)</big><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 extended 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> <p class="versionadded"> <span class="versionmodified">New in version 2.3.</span></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"><tt class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></tt></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 “User-defined methods”. Class method objects are created by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></a> constructor.</dd> </dl> </dd> </dl> </div> <div class="section" id="new-style-and-classic-classes"> <span id="newstyle"></span><h2>3.3. New-style and classic classes<a class="headerlink" href="#new-style-and-classic-classes" title="Permalink to this headline">¶</a></h2> <p>Classes and instances come in two flavors: old-style (or classic) and new-style.</p> <p>Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if <em>x</em> is an instance of an old-style class, then <tt class="docutils literal"><span class="pre">x.__class__</span></tt> designates the class of <em>x</em>, but <tt class="docutils literal"><span class="pre">type(x)</span></tt> is always <tt class="docutils literal"><span class="pre"><type</span> <span class="pre">'instance'></span></tt>. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called <tt class="docutils literal"><span class="pre">instance</span></tt>.</p> <p>New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class is neither more nor less than a user-defined type. If <em>x</em> is an instance of a new-style class, then <tt class="docutils literal"><span class="pre">type(x)</span></tt> is typically the same as <tt class="docutils literal"><span class="pre">x.__class__</span></tt> (although this is not guaranteed - a new-style class instance is permitted to override the value returned for <tt class="docutils literal"><span class="pre">x.__class__</span></tt>).</p> <p>The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model. It also has a number of practical benefits, like the ability to subclass most built-in types, or the introduction of “descriptors”, which enable computed properties.</p> <p>For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” <a class="reference internal" href="../library/functions.html#object" title="object"><tt class="xref py py-class docutils literal"><span class="pre">object</span></tt></a> if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a> returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.</p> <p>While this manual aims to provide comprehensive coverage of Python’s class mechanics, it may still be lacking in some areas when it comes to its coverage of new-style classes. Please see <a class="reference external" href="http://www.python.org/doc/newstyle/">http://www.python.org/doc/newstyle/</a> for sources of additional information.</p> <p id="index-71">Old-style classes are removed in Python 3, leaving only the semantics of new-style classes.</p> </div> <div class="section" id="special-method-names"> <span id="specialnames"></span><h2>3.4. Special method names<a class="headerlink" href="#special-method-names" title="Permalink to this headline">¶</a></h2> <p id="index-72">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’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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, and <tt class="docutils literal"><span class="pre">x</span></tt> is an instance of this class, then <tt class="docutils literal"><span class="pre">x[i]</span></tt> is roughly equivalent to <tt class="docutils literal"><span class="pre">x.__getitem__(i)</span></tt> for old-style classes and <tt class="docutils literal"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></tt> for new-style classes. 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#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></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 <tt class="xref py py-class docutils literal"><span class="pre">NodeList</span></tt> interface in the W3C’s Document Object Model.)</p> <div class="section" id="basic-customization"> <span id="customization"></span><h3>3.4.1. Basic customization<a class="headerlink" href="#basic-customization" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="object.__new__"> <tt class="descclassname">object.</tt><tt class="descname">__new__</tt><big>(</big><em>cls</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__new__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-73">Called to create a new instance of class <em>cls</em>. <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></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’s <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> method using <tt class="docutils literal"><span class="pre">super(currentclass,</span> <span class="pre">cls).__new__(cls[,</span> <span class="pre">...])</span></tt> 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> returns an instance of <em>cls</em>, then the new instance’s <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method will be invoked like <tt class="docutils literal"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></tt>, 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a>.</p> <p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> does not return an instance of <em>cls</em>, then the new instance’s <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method will not be invoked.</p> <p><a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></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__"> <tt class="descclassname">object.</tt><tt class="descname">__init__</tt><big>(</big><em>self</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__init__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-74">Called when the instance is created. 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method, the derived class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: <tt class="docutils literal"><span class="pre">BaseClass.__init__(self,</span> <span class="pre">[args...])</span></tt>. As a special constraint on constructors, no value may be returned; doing so will cause a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> to be raised at runtime.</p> </dd></dl> <dl class="method"> <dt id="object.__del__"> <tt class="descclassname">object.</tt><tt class="descname">__del__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__del__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-75">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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method, the derived class’s <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></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"><tt class="docutils literal"><span class="pre">del</span> <span class="pre">x</span></tt> doesn’t directly call <tt class="docutils literal"><span class="pre">x.__del__()</span></tt> — the former decrements the reference count for <tt class="docutils literal"><span class="pre">x</span></tt> by one, and the latter is only called when <tt class="docutils literal"><span class="pre">x</span></tt>‘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 <tt class="docutils literal"><span class="pre">sys.exc_traceback</span></tt> 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 <tt class="docutils literal"><span class="pre">sys.last_traceback</span></tt> keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the latter two situations can be resolved by storing <tt class="docutils literal"><span class="pre">None</span></tt> in <tt class="docutils literal"><span class="pre">sys.exc_traceback</span></tt> or <tt class="docutils literal"><span class="pre">sys.last_traceback</span></tt>. Circular references which are garbage are detected when the option cycle detector is enabled (it’s on by default), but can only be cleaned up if there are no Python-level <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> methods involved. 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."><tt class="xref py py-mod docutils literal"><span class="pre">gc</span></tt></a> module for more information about how <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> methods are handled by the cycle detector, particularly the description of the <tt class="docutils literal"><span class="pre">garbage</span></tt> value.</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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to <tt class="docutils literal"><span class="pre">sys.stderr</span></tt> instead. Also, when <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method is called.</p> </div> <p>See also the <a class="reference internal" href="../using/cmdline.html#cmdoption-R"><em class="xref std std-option">-R</em></a> command-line option.</p> </dd></dl> <dl class="method"> <dt id="object.__repr__"> <tt class="descclassname">object.</tt><tt class="descname">__repr__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__repr__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-76">Called by the <a class="reference internal" href="../library/repr.html#module-repr" title="repr: Alternate repr() implementation with size limits."><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a> built-in function and by string conversions (reverse quotes) to compute the “official” 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 <tt class="docutils literal"><span class="pre"><...some</span> <span class="pre">useful</span> <span class="pre">description...></span></tt> 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a> but not <a class="reference internal" href="#object.__str__" title="object.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a> is also used when an “informal” string representation of instances of that class is required.</p> <p id="index-77">This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.</p> </dd></dl> <dl class="method"> <dt id="object.__str__"> <tt class="descclassname">object.</tt><tt class="descname">__str__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__str__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-78">Called by the <a class="reference internal" href="../library/functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a> built-in function and by the <a class="reference internal" href="simple_stmts.html#print"><tt class="xref std std-keyword docutils literal"><span class="pre">print</span></tt></a> statement to compute the “informal” string representation of an object. This differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a> in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.</p> </dd></dl> <dl class="method"> <dt id="object.__lt__"> <tt class="descclassname">object.</tt><tt class="descname">__lt__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__lt__" title="Permalink to this definition">¶</a></dt> <dt id="object.__le__"> <tt class="descclassname">object.</tt><tt class="descname">__le__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__le__" title="Permalink to this definition">¶</a></dt> <dt id="object.__eq__"> <tt class="descclassname">object.</tt><tt class="descname">__eq__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__eq__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ne__"> <tt class="descclassname">object.</tt><tt class="descname">__ne__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ne__" title="Permalink to this definition">¶</a></dt> <dt id="object.__gt__"> <tt class="descclassname">object.</tt><tt class="descname">__gt__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__gt__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ge__"> <tt class="descclassname">object.</tt><tt class="descname">__ge__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ge__" title="Permalink to this definition">¶</a></dt> <dd><p class="versionadded"> <span class="versionmodified">New in version 2.1.</span></p> <p id="index-79">These are the so-called “rich comparison” methods, and are called for comparison operators in preference to <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> below. The correspondence between operator symbols and method names is as follows: <tt class="docutils literal"><span class="pre">x<y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__lt__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x<=y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__le__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x==y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__eq__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x!=y</span></tt> and <tt class="docutils literal"><span class="pre">x<>y</span></tt> call <tt class="docutils literal"><span class="pre">x.__ne__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x>y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__gt__(y)</span></tt>, and <tt class="docutils literal"><span class="pre">x>=y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__ge__(y)</span></tt>.</p> <p>A rich comparison method may return the singleton <tt class="docutils literal"><span class="pre">NotImplemented</span></tt> if it does not implement the operation for a given pair of arguments. By convention, <tt class="docutils literal"><span class="pre">False</span></tt> and <tt class="docutils literal"><span class="pre">True</span></tt> 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 <tt class="docutils literal"><span class="pre">if</span></tt> statement), Python will call <a class="reference internal" href="../library/functions.html#bool" title="bool"><tt class="xref py py-func docutils literal"><span class="pre">bool()</span></tt></a> on the value to determine if the result is true or false.</p> <p>There are no implied relationships among the comparison operators. The truth of <tt class="docutils literal"><span class="pre">x==y</span></tt> does not imply that <tt class="docutils literal"><span class="pre">x!=y</span></tt> is false. Accordingly, when defining <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a>, one should also define <a class="reference internal" href="#object.__ne__" title="object.__ne__"><tt class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></tt></a> so that the operators will behave as expected. See the paragraph on <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> for some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__lt__()</span></tt></a> and <a class="reference internal" href="#object.__gt__" title="object.__gt__"><tt class="xref py py-meth docutils literal"><span class="pre">__gt__()</span></tt></a> are each other’s reflection, <a class="reference internal" href="#object.__le__" title="object.__le__"><tt class="xref py py-meth docutils literal"><span class="pre">__le__()</span></tt></a> and <a class="reference internal" href="#object.__ge__" title="object.__ge__"><tt class="xref py py-meth docutils literal"><span class="pre">__ge__()</span></tt></a> are each other’s reflection, and <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> and <a class="reference internal" href="#object.__ne__" title="object.__ne__"><tt class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></tt></a> are their own reflection.</p> <p>Arguments to rich comparison methods are never coerced.</p> <p>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"><tt class="xref py py-func docutils literal"><span class="pre">functools.total_ordering()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="object.__cmp__"> <tt class="descclassname">object.</tt><tt class="descname">__cmp__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__cmp__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-80">Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if <tt class="docutils literal"><span class="pre">self</span> <span class="pre"><</span> <span class="pre">other</span></tt>, zero if <tt class="docutils literal"><span class="pre">self</span> <span class="pre">==</span> <span class="pre">other</span></tt>, a positive integer if <tt class="docutils literal"><span class="pre">self</span> <span class="pre">></span> <span class="pre">other</span></tt>. If no <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a>, <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> or <a class="reference internal" href="#object.__ne__" title="object.__ne__"><tt class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></tt></a> operation is defined, class instances are compared by object identity (“address”). See also the description of <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> for some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> has been removed since Python 1.5.)</p> </dd></dl> <dl class="method"> <dt id="object.__rcmp__"> <tt class="descclassname">object.</tt><tt class="descname">__rcmp__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rcmp__" title="Permalink to this definition">¶</a></dt> <dd><p class="versionchanged"> <span class="versionmodified">Changed in version 2.1: </span>No longer supported.</p> </dd></dl> <dl class="method"> <dt id="object.__hash__"> <tt class="descclassname">object.</tt><tt class="descname">__hash__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__hash__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-81">Called by built-in function <a class="reference internal" href="../library/functions.html#hash" title="hash"><tt class="xref py py-func docutils literal"><span class="pre">hash()</span></tt></a> and for operations on members of hashed collections including <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>, and <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>. <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g. using exclusive or) the hash values for the components of the object that also play a part in comparison of objects.</p> <p>If a class does not define a <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> method it should not define a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> operation either; if it defines <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> but not <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>, its instances will not be usable in hashed collections. If a class defines mutable objects and implements a <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> method, it should not implement <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>, since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).</p> <p>User-defined classes have <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> and <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> methods by default; with them, all objects compare unequal (except with themselves) and <tt class="docutils literal"><span class="pre">x.__hash__()</span></tt> returns <tt class="docutils literal"><span class="pre">id(x)</span></tt>.</p> <p>Classes which inherit a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> method from a parent class but change the meaning of <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting <tt class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></tt> in the class definition. Doing so means that not only will instances of the class raise an appropriate <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable)</span></tt> (unlike classes which define their own <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> to explicitly raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>).</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.5: </span><a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> may now also return a long integer object; the 32-bit integer is then derived from the hash of that object.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span><a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-attr docutils literal"><span class="pre">__hash__</span></tt></a> may now be set to <a class="reference internal" href="../library/constants.html#None" title="None"><tt class="xref py py-const docutils literal"><span class="pre">None</span></tt></a> to explicitly flag instances of a class as unhashable.</p> </dd></dl> <dl class="method"> <dt id="object.__nonzero__"> <tt class="descclassname">object.</tt><tt class="descname">__nonzero__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__nonzero__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-82">Called to implement truth value testing and the built-in operation <tt class="docutils literal"><span class="pre">bool()</span></tt>; should return <tt class="docutils literal"><span class="pre">False</span></tt> or <tt class="docutils literal"><span class="pre">True</span></tt>, or their integer equivalents <tt class="docutils literal"><span class="pre">0</span></tt> or <tt class="docutils literal"><span class="pre">1</span></tt>. When this method is not defined, <a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> nor <a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><tt class="xref py py-meth docutils literal"><span class="pre">__nonzero__()</span></tt></a>, all its instances are considered true.</p> </dd></dl> <dl class="method"> <dt id="object.__unicode__"> <tt class="descclassname">object.</tt><tt class="descname">__unicode__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__unicode__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-83">Called to implement <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><tt class="xref py py-func docutils literal"><span class="pre">unicode()</span></tt></a> built-in; should return a Unicode object. When this method is not defined, string conversion is attempted, and the result of string conversion is converted to Unicode using the system default encoding.</p> </dd></dl> </div> <div class="section" id="customizing-attribute-access"> <span id="attribute-access"></span><h3>3.4.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 <tt class="docutils literal"><span class="pre">x.name</span></tt>) for class instances.</p> <dl class="method"> <dt id="object.__getattr__"> <tt class="descclassname">object.</tt><tt class="descname">__getattr__</tt><big>(</big><em>self</em>, <em>name</em><big>)</big><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 <tt class="docutils literal"><span class="pre">self</span></tt>). <tt class="docutils literal"><span class="pre">name</span></tt> is the attribute name. This method should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> exception.</p> <p id="index-84">Note that if the attribute is found through the normal mechanism, <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> is not called. (This is an intentional asymmetry between <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> and <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a>.) This is done both for efficiency reasons and because otherwise <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> method below for a way to actually get total control in new-style classes.</p> </dd></dl> <dl class="method"> <dt id="object.__setattr__"> <tt class="descclassname">object.</tt><tt class="descname">__setattr__</tt><big>(</big><em>self</em>, <em>name</em>, <em>value</em><big>)</big><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 id="index-85">If <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a> wants to assign to an instance attribute, it should not simply execute <tt class="docutils literal"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></tt> — this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., <tt class="docutils literal"><span class="pre">self.__dict__[name]</span> <span class="pre">=</span> <span class="pre">value</span></tt>. For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, <tt class="docutils literal"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span> <span class="pre">value)</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="object.__delattr__"> <tt class="descclassname">object.</tt><tt class="descname">__delattr__</tt><big>(</big><em>self</em>, <em>name</em><big>)</big><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__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a> but for attribute deletion instead of assignment. This should only be implemented if <tt class="docutils literal"><span class="pre">del</span> <span class="pre">obj.name</span></tt> is meaningful for the object.</p> </dd></dl> <div class="section" id="more-attribute-access-for-new-style-classes"> <span id="new-style-attribute-access"></span><h4>3.4.2.1. More attribute access for new-style classes<a class="headerlink" href="#more-attribute-access-for-new-style-classes" title="Permalink to this headline">¶</a></h4> <p>The following methods only apply to new-style classes.</p> <dl class="method"> <dt id="object.__getattribute__"> <tt class="descclassname">object.</tt><tt class="descname">__getattribute__</tt><big>(</big><em>self</em>, <em>name</em><big>)</big><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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a>, the latter will not be called unless <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> either calls it explicitly or raises an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a>. This method should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></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, <tt class="docutils literal"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></tt>.</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="#new-style-special-lookup"><em>Special method lookup for new-style classes</em></a>.</p> </div> </dd></dl> </div> <div class="section" id="implementing-descriptors"> <span id="descriptors"></span><h4>3.4.2.2. 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’s class dictionary or in the class dictionary for one of its parents). In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>.</p> <dl class="method"> <dt id="object.__get__"> <tt class="descclassname">object.</tt><tt class="descname">__get__</tt><big>(</big><em>self</em>, <em>instance</em>, <em>owner</em><big>)</big><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 <tt class="docutils literal"><span class="pre">None</span></tt> 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#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> exception.</p> </dd></dl> <dl class="method"> <dt id="object.__set__"> <tt class="descclassname">object.</tt><tt class="descname">__set__</tt><big>(</big><em>self</em>, <em>instance</em>, <em>value</em><big>)</big><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__"> <tt class="descclassname">object.</tt><tt class="descname">__delete__</tt><big>(</big><em>self</em>, <em>instance</em><big>)</big><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> </div> <div class="section" id="invoking-descriptors"> <span id="descriptor-invocation"></span><h4>3.4.2.3. 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 “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a>, and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><tt class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></tt></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’s dictionary. For instance, <tt class="docutils literal"><span class="pre">a.x</span></tt> has a lookup chain starting with <tt class="docutils literal"><span class="pre">a.__dict__['x']</span></tt>, then <tt class="docutils literal"><span class="pre">type(a).__dict__['x']</span></tt>, and continuing through the base classes of <tt class="docutils literal"><span class="pre">type(a)</span></tt> 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. Note that descriptors are only invoked for new style objects or classes (ones that subclass <a class="reference internal" href="../library/functions.html#object" title="object"><tt class="xref py py-class docutils literal"><span class="pre">object()</span></tt></a> or <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-class docutils literal"><span class="pre">type()</span></tt></a>).</p> <p>The starting point for descriptor invocation is a binding, <tt class="docutils literal"><span class="pre">a.x</span></tt>. How the arguments are assembled depends on <tt class="docutils literal"><span class="pre">a</span></tt>:</p> <dl class="docutils"> <dt>Direct Call</dt> <dd>The simplest and least common call is when user code directly invokes a descriptor method: <tt class="docutils literal"><span class="pre">x.__get__(a)</span></tt>.</dd> <dt>Instance Binding</dt> <dd>If binding to a new-style object instance, <tt class="docutils literal"><span class="pre">a.x</span></tt> is transformed into the call: <tt class="docutils literal"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></tt>.</dd> <dt>Class Binding</dt> <dd>If binding to a new-style class, <tt class="docutils literal"><span class="pre">A.x</span></tt> is transformed into the call: <tt class="docutils literal"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></tt>.</dd> <dt>Super Binding</dt> <dd>If <tt class="docutils literal"><span class="pre">a</span></tt> is an instance of <a class="reference internal" href="../library/functions.html#super" title="super"><tt class="xref py py-class docutils literal"><span class="pre">super</span></tt></a>, then the binding <tt class="docutils literal"><span class="pre">super(B,</span> <span class="pre">obj).m()</span></tt> searches <tt class="docutils literal"><span class="pre">obj.__class__.__mro__</span></tt> for the base class <tt class="docutils literal"><span class="pre">A</span></tt> immediately preceding <tt class="docutils literal"><span class="pre">B</span></tt> and then invokes the descriptor with the call: <tt class="docutils literal"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">obj.__class__)</span></tt>.</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__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a> and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><tt class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></tt></a>. If it does not define <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a>, then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary. If the descriptor defines <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a> and/or <a class="reference internal" href="#object.__delete__" title="object.__delete__"><tt class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a> and <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a>, while non-data descriptors have just the <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a> method. Data descriptors with <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a> and <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></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"><tt class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></tt></a> and <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></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"><tt class="xref py py-func docutils literal"><span class="pre">property()</span></tt></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.4.2.4. __slots__<a class="headerlink" href="#slots" title="Permalink to this headline">¶</a></h4> <p>By default, instances of both old and new-style 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 new-style 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="__slots__"> <tt class="descname">__slots__</tt><a class="headerlink" href="#__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. If defined in a new-style class, <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> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <p>Notes on using <em>__slots__</em></p> <ul> <li><p class="first">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.</p> </li> <li><p class="first">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#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a>. If dynamic assignment of new variables is desired, then add <tt class="docutils literal"><span class="pre">'__dict__'</span></tt> to the sequence of strings in the <em>__slots__</em> declaration.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Previously, adding <tt class="docutils literal"><span class="pre">'__dict__'</span></tt> to the <em>__slots__</em> declaration would not enable the assignment of new attributes not specifically listed in the sequence of instance variable names.</p> </li> <li><p class="first">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 <tt class="docutils literal"><span class="pre">'__weakref__'</span></tt> to the sequence of strings in the <em>__slots__</em> declaration.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.3: </span>Previously, adding <tt class="docutils literal"><span class="pre">'__weakref__'</span></tt> to the <em>__slots__</em> declaration would not enable support for weak references.</p> </li> <li><p class="first"><em>__slots__</em> are implemented at the class level by creating descriptors (<a class="reference internal" href="#descriptors"><em>Implementing Descriptors</em></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.</p> </li> <li><p class="first">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).</p> </li> <li><p class="first">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.</p> </li> <li><p class="first">Nonempty <em>__slots__</em> does not work for classes derived from “variable-length” built-in types such as <a class="reference internal" href="../library/functions.html#long" title="long"><tt class="xref py py-class docutils literal"><span class="pre">long</span></tt></a>, <a class="reference internal" href="../library/functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> and <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a>.</p> </li> <li><p class="first">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.</p> </li> <li><p class="first"><em>__class__</em> assignment works only if both classes have the same <em>__slots__</em>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.6: </span>Previously, <em>__class__</em> assignment raised an error if either new or old class had <em>__slots__</em>.</p> </li> </ul> </div> </div> <div class="section" id="customizing-class-creation"> <span id="metaclasses"></span><h3>3.4.3. Customizing class creation<a class="headerlink" href="#customizing-class-creation" title="Permalink to this headline">¶</a></h3> <p>By default, new-style classes are constructed using <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>. A class definition is read into a separate namespace and the value of class name is bound to the result of <tt class="docutils literal"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">dict)</span></tt>.</p> <p>When the class definition is read, if <em>__metaclass__</em> is defined then the callable assigned to it will be called instead of <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>. This allows classes or functions to be written which monitor or alter the class creation process:</p> <ul class="simple"> <li>Modifying the class dictionary prior to the class being created.</li> <li>Returning an instance of another class – essentially performing the role of a factory function.</li> </ul> <p>These steps will have to be performed in the metaclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> method – <tt class="xref py py-meth docutils literal"><span class="pre">type.__new__()</span></tt> can then be called from this method to create a class with different properties. This example adds a new element to the class dictionary before creating the class:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">metacls</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">mcs</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="nb">dict</span><span class="p">[</span><span class="s">'foo'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'metacls was here'</span> <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="n">__new__</span><span class="p">(</span><span class="n">mcs</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> </pre></div> </div> <p>You can of course also override other class methods (or add new methods); for example defining a custom <a class="reference internal" href="#object.__call__" title="object.__call__"><tt class="xref py py-meth docutils literal"><span class="pre">__call__()</span></tt></a> method in the metaclass allows custom behavior when the class is called, e.g. not always creating a new instance.</p> <dl class="data"> <dt id="__metaclass__"> <tt class="descname">__metaclass__</tt><a class="headerlink" href="#__metaclass__" title="Permalink to this definition">¶</a></dt> <dd><p>This variable can be any callable accepting arguments for <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">bases</span></tt>, and <tt class="docutils literal"><span class="pre">dict</span></tt>. Upon class creation, the callable is used instead of the built-in <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.2.</span></p> </dd></dl> <p>The appropriate metaclass is determined by the following precedence rules:</p> <ul class="simple"> <li>If <tt class="docutils literal"><span class="pre">dict['__metaclass__']</span></tt> exists, it is used.</li> <li>Otherwise, if there is at least one base class, its metaclass is used (this looks for a <em>__class__</em> attribute first and if not found, uses its type).</li> <li>Otherwise, if a global variable named __metaclass__ exists, it is used.</li> <li>Otherwise, the old-style, classic metaclass (types.ClassType) is used.</li> </ul> <p>The potential uses for metaclasses are boundless. Some ideas that have been explored including logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.</p> </div> <div class="section" id="customizing-instance-and-subclass-checks"> <h3>3.4.4. Customizing instance and subclass checks<a class="headerlink" href="#customizing-instance-and-subclass-checks" title="Permalink to this headline">¶</a></h3> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> <p>The following methods are used to override the default behavior of the <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><tt class="xref py py-func docutils literal"><span class="pre">isinstance()</span></tt></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><tt class="xref py py-func docutils literal"><span class="pre">issubclass()</span></tt></a> built-in functions.</p> <p>In particular, the metaclass <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><tt class="xref py py-class docutils literal"><span class="pre">abc.ABCMeta</span></tt></a> implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as “virtual base classes” to any class or type (including built-in types), including other ABCs.</p> <dl class="method"> <dt id="class.__instancecheck__"> <tt class="descclassname">class.</tt><tt class="descname">__instancecheck__</tt><big>(</big><em>self</em>, <em>instance</em><big>)</big><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 <tt class="docutils literal"><span class="pre">isinstance(instance,</span> <span class="pre">class)</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="class.__subclasscheck__"> <tt class="descclassname">class.</tt><tt class="descname">__subclasscheck__</tt><big>(</big><em>self</em>, <em>subclass</em><big>)</big><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 <tt class="docutils literal"><span class="pre">issubclass(subclass,</span> <span class="pre">class)</span></tt>.</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-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><span class="target" id="index-86"></span><a class="pep reference external" href="http://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"><tt class="xref py py-func docutils literal"><span class="pre">isinstance()</span></tt></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><tt class="xref py py-func docutils literal"><span class="pre">issubclass()</span></tt></a> behavior through <tt class="xref py py-meth docutils literal"><span class="pre">__instancecheck__()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">__subclasscheck__()</span></tt>, 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."><tt class="xref py py-mod docutils literal"><span class="pre">abc</span></tt></a> module) to the language.</dd> </dl> </div> </div> <div class="section" id="emulating-callable-objects"> <span id="callable-types"></span><h3>3.4.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__"> <tt class="descclassname">object.</tt><tt class="descname">__call__</tt><big>(</big><em>self</em><span class="optional">[</span>, <em>args...</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__call__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-87">Called when the instance is “called” as a function; if this method is defined, <tt class="docutils literal"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></tt> is a shorthand for <tt class="docutils literal"><span class="pre">x.__call__(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></tt>.</p> </dd></dl> </div> <div class="section" id="emulating-container-types"> <span id="sequence-types"></span><h3>3.4.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 <tt class="docutils literal"><span class="pre">0</span> <span class="pre"><=</span> <span class="pre">k</span> <span class="pre"><</span> <span class="pre">N</span></tt> where <em>N</em> is the length of the sequence, or slice objects, which define a range of items. (For backwards compatibility, the method <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></tt></a> (see below) can also be defined to handle simple, but not extended slices.) It is also recommended that mappings provide the methods <tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">items()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">has_key()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">setdefault()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">itervalues()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">iteritems()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">pop()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">popitem()</span></tt>, <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><tt class="xref py py-meth docutils literal"><span class="pre">copy()</span></tt></a>, and <tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt> behaving similar to those for Python’s standard dictionary objects. The <a class="reference internal" href="../library/userdict.html#module-UserDict" title="UserDict: Class wrapper for dictionary objects."><tt class="xref py py-mod docutils literal"><span class="pre">UserDict</span></tt></a> module provides a <tt class="xref py py-class docutils literal"><span class="pre">DictMixin</span></tt> class to help create those methods from a base set of <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></tt></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></tt></a>, and <tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>. Mutable sequences should provide methods <tt class="xref py py-meth docutils literal"><span class="pre">append()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">count()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">index()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">extend()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">insert()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">pop()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">reverse()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt>, 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></a>, <a class="reference internal" href="#object.__radd__" title="object.__radd__"><tt class="xref py py-meth docutils literal"><span class="pre">__radd__()</span></tt></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><tt class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></tt></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><tt class="xref py py-meth docutils literal"><span class="pre">__mul__()</span></tt></a>, <a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><tt class="xref py py-meth docutils literal"><span class="pre">__rmul__()</span></tt></a> and <a class="reference internal" href="#object.__imul__" title="object.__imul__"><tt class="xref py py-meth docutils literal"><span class="pre">__imul__()</span></tt></a> described below; they should not define <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><tt class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></tt></a> or other numerical operators. It is recommended that both mappings and sequences implement the <a class="reference internal" href="#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a> method to allow efficient use of the <tt class="docutils literal"><span class="pre">in</span></tt> operator; for mappings, <tt class="docutils literal"><span class="pre">in</span></tt> should be equivalent of <tt class="xref py py-meth docutils literal"><span class="pre">has_key()</span></tt>; 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> method to allow efficient iteration through the container; for mappings, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> should be the same as <tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt>; for sequences, it should iterate through the values.</p> <dl class="method"> <dt id="object.__len__"> <tt class="descclassname">object.</tt><tt class="descname">__len__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__len__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-88">Called to implement the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a>. Should return the length of the object, an integer <tt class="docutils literal"><span class="pre">>=</span></tt> 0. Also, an object that doesn’t define a <a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><tt class="xref py py-meth docutils literal"><span class="pre">__nonzero__()</span></tt></a> method and whose <a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> method returns zero is considered to be false in a Boolean context.</p> </dd></dl> <dl class="method"> <dt id="object.__getitem__"> <tt class="descclassname">object.</tt><tt class="descname">__getitem__</tt><big>(</big><em>self</em>, <em>key</em><big>)</big><a class="headerlink" href="#object.__getitem__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-89">Called to implement evaluation of <tt class="docutils literal"><span class="pre">self[key]</span></tt>. 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method. If <em>key</em> is of an inappropriate type, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></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#exceptions.IndexError" title="exceptions.IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></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#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></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"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loops expect that an <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></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.__setitem__"> <tt class="descclassname">object.</tt><tt class="descname">__setitem__</tt><big>(</big><em>self</em>, <em>key</em>, <em>value</em><big>)</big><a class="headerlink" href="#object.__setitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Called to implement assignment to <tt class="docutils literal"><span class="pre">self[key]</span></tt>. Same note as for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method.</p> </dd></dl> <dl class="method"> <dt id="object.__delitem__"> <tt class="descclassname">object.</tt><tt class="descname">__delitem__</tt><big>(</big><em>self</em>, <em>key</em><big>)</big><a class="headerlink" href="#object.__delitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Called to implement deletion of <tt class="docutils literal"><span class="pre">self[key]</span></tt>. Same note as for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method.</p> </dd></dl> <dl class="method"> <dt id="object.__iter__"> <tt class="descclassname">object.</tt><tt class="descname">__iter__</tt><big>(</big><em>self</em><big>)</big><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, and should also be made available as the method <tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt>.</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"><em>Iterator Types</em></a>.</p> </dd></dl> <dl class="method"> <dt id="object.__reversed__"> <tt class="descclassname">object.</tt><tt class="descname">__reversed__</tt><big>(</big><em>self</em><big>)</big><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"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></tt></a> method is not provided, the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a> built-in will fall back to using the sequence protocol (<a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> and <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>). Objects that support the sequence protocol should only provide <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><tt class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></tt></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"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a>.</p> <p class="versionadded"> <span class="versionmodified">New in version 2.6.</span></p> </dd></dl> <p>The membership test operators (<a class="reference internal" href="expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> and <a class="reference internal" href="expressions.html#not-in"><tt class="xref std std-keyword docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt></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__"> <tt class="descclassname">object.</tt><tt class="descname">__contains__</tt><big>(</big><em>self</em>, <em>item</em><big>)</big><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’t define <a class="reference internal" href="#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a>, the membership test first tries iteration via <a class="reference internal" href="#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a>, then the old sequence iteration protocol via <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, see <a class="reference internal" href="expressions.html#membership-test-details"><em>this section in the language reference</em></a>.</p> </dd></dl> </div> <div class="section" id="additional-methods-for-emulation-of-sequence-types"> <span id="sequence-methods"></span><h3>3.4.7. Additional methods for emulation of sequence types<a class="headerlink" href="#additional-methods-for-emulation-of-sequence-types" title="Permalink to this headline">¶</a></h3> <p>The following optional methods can be defined to further emulate sequence objects. Immutable sequences methods should at most only define <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></tt></a>; mutable sequences might define all three methods.</p> <dl class="method"> <dt id="object.__getslice__"> <tt class="descclassname">object.</tt><tt class="descname">__getslice__</tt><big>(</big><em>self</em>, <em>i</em>, <em>j</em><big>)</big><a class="headerlink" href="#object.__getslice__" title="Permalink to this definition">¶</a></dt> <dd><p class="deprecated"> <span class="versionmodified">Deprecated since version 2.0: </span>Support slice objects as parameters to the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method. (However, built-in types in CPython currently still implement <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></tt></a>. Therefore, you have to override it in derived classes when implementing slicing.)</p> <p>Called to implement evaluation of <tt class="docutils literal"><span class="pre">self[i:j]</span></tt>. The returned object should be of the same type as <em>self</em>. Note that missing <em>i</em> or <em>j</em> in the slice expression are replaced by zero or <tt class="docutils literal"><span class="pre">sys.maxint</span></tt>, respectively. If negative indexes are used in the slice, the length of the sequence is added to that index. If the instance does not implement the <a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> method, an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> is raised. No guarantee is made that indexes adjusted this way are not still negative. Indexes which are greater than the length of the sequence are not modified. If no <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></tt></a> is found, a slice object is created instead, and passed to <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> instead.</p> </dd></dl> <dl class="method"> <dt id="object.__setslice__"> <tt class="descclassname">object.</tt><tt class="descname">__setslice__</tt><big>(</big><em>self</em>, <em>i</em>, <em>j</em>, <em>sequence</em><big>)</big><a class="headerlink" href="#object.__setslice__" title="Permalink to this definition">¶</a></dt> <dd><p>Called to implement assignment to <tt class="docutils literal"><span class="pre">self[i:j]</span></tt>. Same notes for <em>i</em> and <em>j</em> as for <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></tt></a>.</p> <p>This method is deprecated. If no <a class="reference internal" href="#object.__setslice__" title="object.__setslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__setslice__()</span></tt></a> is found, or for extended slicing of the form <tt class="docutils literal"><span class="pre">self[i:j:k]</span></tt>, a slice object is created, and passed to <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></tt></a>, instead of <a class="reference internal" href="#object.__setslice__" title="object.__setslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__setslice__()</span></tt></a> being called.</p> </dd></dl> <dl class="method"> <dt id="object.__delslice__"> <tt class="descclassname">object.</tt><tt class="descname">__delslice__</tt><big>(</big><em>self</em>, <em>i</em>, <em>j</em><big>)</big><a class="headerlink" href="#object.__delslice__" title="Permalink to this definition">¶</a></dt> <dd><p>Called to implement deletion of <tt class="docutils literal"><span class="pre">self[i:j]</span></tt>. Same notes for <em>i</em> and <em>j</em> as for <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></tt></a>. This method is deprecated. If no <a class="reference internal" href="#object.__delslice__" title="object.__delslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__delslice__()</span></tt></a> is found, or for extended slicing of the form <tt class="docutils literal"><span class="pre">self[i:j:k]</span></tt>, a slice object is created, and passed to <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></tt></a>, instead of <a class="reference internal" href="#object.__delslice__" title="object.__delslice__"><tt class="xref py py-meth docutils literal"><span class="pre">__delslice__()</span></tt></a> being called.</p> </dd></dl> <p>Notice that these methods are only invoked when a single slice with a single colon is used, and the slice method is available. For slice operations involving extended slice notation, or in absence of the slice methods, <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></tt></a> or <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></tt></a> is called with a slice object as argument.</p> <p>The following example demonstrate how to make your program or module compatible with earlier versions of Python (assuming that methods <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></tt></a> and <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></tt></a> support slice objects as arguments):</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span> <span class="o">...</span> <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span> <span class="nf">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span> <span class="o">...</span> <span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span> <span class="o"><</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">):</span> <span class="c"># They won't be defined if version is at least 2.0 final</span> <span class="k">def</span> <span class="nf">__getslice__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">j</span><span class="p">):]</span> <span class="k">def</span> <span class="nf">__setslice__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">,</span> <span class="n">seq</span><span class="p">):</span> <span class="bp">self</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">j</span><span class="p">):]</span> <span class="o">=</span> <span class="n">seq</span> <span class="k">def</span> <span class="nf">__delslice__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">):</span> <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">j</span><span class="p">):]</span> <span class="o">...</span> </pre></div> </div> <p>Note the calls to <a class="reference internal" href="../library/functions.html#max" title="max"><tt class="xref py py-func docutils literal"><span class="pre">max()</span></tt></a>; these are necessary because of the handling of negative indices before the <tt class="xref py py-meth docutils literal"><span class="pre">__*slice__()</span></tt> methods are called. When negative indexes are used, the <tt class="xref py py-meth docutils literal"><span class="pre">__*item__()</span></tt> methods receive them as provided, but the <tt class="xref py py-meth docutils literal"><span class="pre">__*slice__()</span></tt> methods get a “cooked” form of the index values. For each negative index value, the length of the sequence is added to the index before calling the method (which may still result in a negative index); this is the customary handling of negative indexes by the built-in sequence types, and the <tt class="xref py py-meth docutils literal"><span class="pre">__*item__()</span></tt> methods are expected to do this as well. However, since they should already be doing that, negative indexes cannot be passed in; they must be constrained to the bounds of the sequence before being passed to the <tt class="xref py py-meth docutils literal"><span class="pre">__*item__()</span></tt> methods. Calling <tt class="docutils literal"><span class="pre">max(0,</span> <span class="pre">i)</span></tt> conveniently returns the proper value.</p> </div> <div class="section" id="emulating-numeric-types"> <span id="numeric-types"></span><h3>3.4.8. 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__"> <tt class="descclassname">object.</tt><tt class="descname">__add__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__add__" title="Permalink to this definition">¶</a></dt> <dt id="object.__sub__"> <tt class="descclassname">object.</tt><tt class="descname">__sub__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__sub__" title="Permalink to this definition">¶</a></dt> <dt id="object.__mul__"> <tt class="descclassname">object.</tt><tt class="descname">__mul__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__mul__" title="Permalink to this definition">¶</a></dt> <dt id="object.__floordiv__"> <tt class="descclassname">object.</tt><tt class="descname">__floordiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__floordiv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__mod__"> <tt class="descclassname">object.</tt><tt class="descname">__mod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__mod__" title="Permalink to this definition">¶</a></dt> <dt id="object.__divmod__"> <tt class="descclassname">object.</tt><tt class="descname">__divmod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__divmod__" title="Permalink to this definition">¶</a></dt> <dt id="object.__pow__"> <tt class="descclassname">object.</tt><tt class="descname">__pow__</tt><big>(</big><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__pow__" title="Permalink to this definition">¶</a></dt> <dt id="object.__lshift__"> <tt class="descclassname">object.</tt><tt class="descname">__lshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__lshift__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rshift__"> <tt class="descclassname">object.</tt><tt class="descname">__rshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rshift__" title="Permalink to this definition">¶</a></dt> <dt id="object.__and__"> <tt class="descclassname">object.</tt><tt class="descname">__and__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__and__" title="Permalink to this definition">¶</a></dt> <dt id="object.__xor__"> <tt class="descclassname">object.</tt><tt class="descname">__xor__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__xor__" title="Permalink to this definition">¶</a></dt> <dt id="object.__or__"> <tt class="descclassname">object.</tt><tt class="descname">__or__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__or__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-90">These methods are called to implement the binary arithmetic operations (<tt class="docutils literal"><span class="pre">+</span></tt>, <tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">//</span></tt>, <tt class="docutils literal"><span class="pre">%</span></tt>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><tt class="xref py py-func docutils literal"><span class="pre">divmod()</span></tt></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a>, <tt class="docutils literal"><span class="pre">**</span></tt>, <tt class="docutils literal"><span class="pre"><<</span></tt>, <tt class="docutils literal"><span class="pre">>></span></tt>, <tt class="docutils literal"><span class="pre">&</span></tt>, <tt class="docutils literal"><span class="pre">^</span></tt>, <tt class="docutils literal"><span class="pre">|</span></tt>). For instance, to evaluate the expression <tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt>, where <em>x</em> is an instance of a class that has an <a class="reference internal" href="#object.__add__" title="object.__add__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></a> method, <tt class="docutils literal"><span class="pre">x.__add__(y)</span></tt> is called. The <a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><tt class="xref py py-meth docutils literal"><span class="pre">__divmod__()</span></tt></a> method should be the equivalent to using <a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><tt class="xref py py-meth docutils literal"><span class="pre">__floordiv__()</span></tt></a> and <a class="reference internal" href="#object.__mod__" title="object.__mod__"><tt class="xref py py-meth docutils literal"><span class="pre">__mod__()</span></tt></a>; it should not be related to <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><tt class="xref py py-meth docutils literal"><span class="pre">__truediv__()</span></tt></a> (described below). Note that <a class="reference internal" href="#object.__pow__" title="object.__pow__"><tt class="xref py py-meth docutils literal"><span class="pre">__pow__()</span></tt></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"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></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 <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="object.__div__"> <tt class="descclassname">object.</tt><tt class="descname">__div__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__div__" title="Permalink to this definition">¶</a></dt> <dt id="object.__truediv__"> <tt class="descclassname">object.</tt><tt class="descname">__truediv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__truediv__" title="Permalink to this definition">¶</a></dt> <dd><p>The division operator (<tt class="docutils literal"><span class="pre">/</span></tt>) is implemented by these methods. The <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><tt class="xref py py-meth docutils literal"><span class="pre">__truediv__()</span></tt></a> method is used when <tt class="docutils literal"><span class="pre">__future__.division</span></tt> is in effect, otherwise <a class="reference internal" href="#object.__div__" title="object.__div__"><tt class="xref py py-meth docutils literal"><span class="pre">__div__()</span></tt></a> is used. If only one of these two methods is defined, the object will not support division in the alternate context; <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> will be raised instead.</p> </dd></dl> <dl class="method"> <dt id="object.__radd__"> <tt class="descclassname">object.</tt><tt class="descname">__radd__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__radd__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rsub__"> <tt class="descclassname">object.</tt><tt class="descname">__rsub__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rsub__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rmul__"> <tt class="descclassname">object.</tt><tt class="descname">__rmul__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rmul__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rdiv__"> <tt class="descclassname">object.</tt><tt class="descname">__rdiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rdiv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rtruediv__"> <tt class="descclassname">object.</tt><tt class="descname">__rtruediv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rtruediv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rfloordiv__"> <tt class="descclassname">object.</tt><tt class="descname">__rfloordiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rfloordiv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rmod__"> <tt class="descclassname">object.</tt><tt class="descname">__rmod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rmod__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rdivmod__"> <tt class="descclassname">object.</tt><tt class="descname">__rdivmod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rdivmod__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rpow__"> <tt class="descclassname">object.</tt><tt class="descname">__rpow__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rpow__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rlshift__"> <tt class="descclassname">object.</tt><tt class="descname">__rlshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rlshift__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rrshift__"> <tt class="descclassname">object.</tt><tt class="descname">__rrshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rrshift__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rand__"> <tt class="descclassname">object.</tt><tt class="descname">__rand__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rand__" title="Permalink to this definition">¶</a></dt> <dt id="object.__rxor__"> <tt class="descclassname">object.</tt><tt class="descname">__rxor__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rxor__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ror__"> <tt class="descclassname">object.</tt><tt class="descname">__ror__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ror__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-91">These methods are called to implement the binary arithmetic operations (<tt class="docutils literal"><span class="pre">+</span></tt>, <tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">/</span></tt>, <tt class="docutils literal"><span class="pre">%</span></tt>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><tt class="xref py py-func docutils literal"><span class="pre">divmod()</span></tt></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a>, <tt class="docutils literal"><span class="pre">**</span></tt>, <tt class="docutils literal"><span class="pre"><<</span></tt>, <tt class="docutils literal"><span class="pre">>></span></tt>, <tt class="docutils literal"><span class="pre">&</span></tt>, <tt class="docutils literal"><span class="pre">^</span></tt>, <tt class="docutils literal"><span class="pre">|</span></tt>) 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 <tt class="docutils literal"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></tt>, where <em>y</em> is an instance of a class that has an <a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><tt class="xref py py-meth docutils literal"><span class="pre">__rsub__()</span></tt></a> method, <tt class="docutils literal"><span class="pre">y.__rsub__(x)</span></tt> is called if <tt class="docutils literal"><span class="pre">x.__sub__(y)</span></tt> returns <em>NotImplemented</em>.</p> <p id="index-92">Note that ternary <a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a> will not try calling <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><tt class="xref py py-meth docutils literal"><span class="pre">__rpow__()</span></tt></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’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.</p> </div> </dd></dl> <dl class="method"> <dt id="object.__iadd__"> <tt class="descclassname">object.</tt><tt class="descname">__iadd__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__iadd__" title="Permalink to this definition">¶</a></dt> <dt id="object.__isub__"> <tt class="descclassname">object.</tt><tt class="descname">__isub__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__isub__" title="Permalink to this definition">¶</a></dt> <dt id="object.__imul__"> <tt class="descclassname">object.</tt><tt class="descname">__imul__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__imul__" title="Permalink to this definition">¶</a></dt> <dt id="object.__idiv__"> <tt class="descclassname">object.</tt><tt class="descname">__idiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__idiv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__itruediv__"> <tt class="descclassname">object.</tt><tt class="descname">__itruediv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__itruediv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ifloordiv__"> <tt class="descclassname">object.</tt><tt class="descname">__ifloordiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ifloordiv__" title="Permalink to this definition">¶</a></dt> <dt id="object.__imod__"> <tt class="descclassname">object.</tt><tt class="descname">__imod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__imod__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ipow__"> <tt class="descclassname">object.</tt><tt class="descname">__ipow__</tt><big>(</big><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__ipow__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ilshift__"> <tt class="descclassname">object.</tt><tt class="descname">__ilshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ilshift__" title="Permalink to this definition">¶</a></dt> <dt id="object.__irshift__"> <tt class="descclassname">object.</tt><tt class="descname">__irshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__irshift__" title="Permalink to this definition">¶</a></dt> <dt id="object.__iand__"> <tt class="descclassname">object.</tt><tt class="descname">__iand__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__iand__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ixor__"> <tt class="descclassname">object.</tt><tt class="descname">__ixor__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ixor__" title="Permalink to this definition">¶</a></dt> <dt id="object.__ior__"> <tt class="descclassname">object.</tt><tt class="descname">__ior__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><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 (<tt class="docutils literal"><span class="pre">+=</span></tt>, <tt class="docutils literal"><span class="pre">-=</span></tt>, <tt class="docutils literal"><span class="pre">*=</span></tt>, <tt class="docutils literal"><span class="pre">/=</span></tt>, <tt class="docutils literal"><span class="pre">//=</span></tt>, <tt class="docutils literal"><span class="pre">%=</span></tt>, <tt class="docutils literal"><span class="pre">**=</span></tt>, <tt class="docutils literal"><span class="pre"><<=</span></tt>, <tt class="docutils literal"><span class="pre">>>=</span></tt>, <tt class="docutils literal"><span class="pre">&=</span></tt>, <tt class="docutils literal"><span class="pre">^=</span></tt>, <tt class="docutils literal"><span class="pre">|=</span></tt>). 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, to execute the statement <tt class="docutils literal"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></tt>, where <em>x</em> is an instance of a class that has an <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><tt class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></tt></a> method, <tt class="docutils literal"><span class="pre">x.__iadd__(y)</span></tt> is called. If <em>x</em> is an instance of a class that does not define a <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><tt class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></tt></a> method, <tt class="docutils literal"><span class="pre">x.__add__(y)</span></tt> and <tt class="docutils literal"><span class="pre">y.__radd__(x)</span></tt> are considered, as with the evaluation of <tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="object.__neg__"> <tt class="descclassname">object.</tt><tt class="descname">__neg__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__neg__" title="Permalink to this definition">¶</a></dt> <dt id="object.__pos__"> <tt class="descclassname">object.</tt><tt class="descname">__pos__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__pos__" title="Permalink to this definition">¶</a></dt> <dt id="object.__abs__"> <tt class="descclassname">object.</tt><tt class="descname">__abs__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__abs__" title="Permalink to this definition">¶</a></dt> <dt id="object.__invert__"> <tt class="descclassname">object.</tt><tt class="descname">__invert__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__invert__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-93">Called to implement the unary arithmetic operations (<tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">+</span></tt>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><tt class="xref py py-func docutils literal"><span class="pre">abs()</span></tt></a> and <tt class="docutils literal"><span class="pre">~</span></tt>).</p> </dd></dl> <dl class="method"> <dt id="object.__complex__"> <tt class="descclassname">object.</tt><tt class="descname">__complex__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__complex__" title="Permalink to this definition">¶</a></dt> <dt id="object.__int__"> <tt class="descclassname">object.</tt><tt class="descname">__int__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__int__" title="Permalink to this definition">¶</a></dt> <dt id="object.__long__"> <tt class="descclassname">object.</tt><tt class="descname">__long__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__long__" title="Permalink to this definition">¶</a></dt> <dt id="object.__float__"> <tt class="descclassname">object.</tt><tt class="descname">__float__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__float__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-94">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#complex" title="complex"><tt class="xref py py-func docutils literal"><span class="pre">complex()</span></tt></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a>, <a class="reference internal" href="../library/functions.html#long" title="long"><tt class="xref py py-func docutils literal"><span class="pre">long()</span></tt></a>, and <a class="reference internal" href="../library/functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a>. Should return a value of the appropriate type.</p> </dd></dl> <dl class="method"> <dt id="object.__oct__"> <tt class="descclassname">object.</tt><tt class="descname">__oct__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__oct__" title="Permalink to this definition">¶</a></dt> <dt id="object.__hex__"> <tt class="descclassname">object.</tt><tt class="descname">__hex__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__hex__" title="Permalink to this definition">¶</a></dt> <dd><p id="index-95">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#oct" title="oct"><tt class="xref py py-func docutils literal"><span class="pre">oct()</span></tt></a> and <a class="reference internal" href="../library/functions.html#hex" title="hex"><tt class="xref py py-func docutils literal"><span class="pre">hex()</span></tt></a>. Should return a string value.</p> </dd></dl> <dl class="method"> <dt id="object.__index__"> <tt class="descclassname">object.</tt><tt class="descname">__index__</tt><big>(</big><em>self</em><big>)</big><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"><tt class="xref py py-func docutils literal"><span class="pre">operator.index()</span></tt></a>. Also called whenever Python needs an integer object (such as in slicing). Must return an integer (int or long).</p> <p class="versionadded"> <span class="versionmodified">New in version 2.5.</span></p> </dd></dl> <dl class="method"> <dt id="object.__coerce__"> <tt class="descclassname">object.</tt><tt class="descname">__coerce__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__coerce__" title="Permalink to this definition">¶</a></dt> <dd><p>Called to implement “mixed-mode” numeric arithmetic. Should either return a 2-tuple containing <em>self</em> and <em>other</em> converted to a common numeric type, or <tt class="docutils literal"><span class="pre">None</span></tt> if conversion is impossible. When the common type would be the type of <tt class="docutils literal"><span class="pre">other</span></tt>, it is sufficient to return <tt class="docutils literal"><span class="pre">None</span></tt>, since the interpreter will also ask the other object to attempt a coercion (but sometimes, if the implementation of the other type cannot be changed, it is useful to do the conversion to the other type here). A return value of <tt class="docutils literal"><span class="pre">NotImplemented</span></tt> is equivalent to returning <tt class="docutils literal"><span class="pre">None</span></tt>.</p> </dd></dl> </div> <div class="section" id="coercion-rules"> <span id="id4"></span><h3>3.4.9. Coercion rules<a class="headerlink" href="#coercion-rules" title="Permalink to this headline">¶</a></h3> <p>This section used to document the rules for coercion. As the language has evolved, the coercion rules have become hard to document precisely; documenting what one version of one particular implementation does is undesirable. Instead, here are some informal guidelines regarding coercion. In Python 3, coercion will not be supported.</p> <ul> <li><p class="first">If the left operand of a % operator is a string or Unicode object, no coercion takes place and the string formatting operation is invoked instead.</p> </li> <li><p class="first">It is no longer recommended to define a coercion operation. Mixed-mode operations on types that don’t define coercion pass the original arguments to the operation.</p> </li> <li><p class="first">New-style classes (those derived from <a class="reference internal" href="../library/functions.html#object" title="object"><tt class="xref py py-class docutils literal"><span class="pre">object</span></tt></a>) never invoke the <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><tt class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></tt></a> method in response to a binary operator; the only time <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><tt class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></tt></a> is invoked is when the built-in function <a class="reference internal" href="../library/functions.html#coerce" title="coerce"><tt class="xref py py-func docutils literal"><span class="pre">coerce()</span></tt></a> is called.</p> </li> <li><p class="first">For most intents and purposes, an operator that returns <tt class="docutils literal"><span class="pre">NotImplemented</span></tt> is treated the same as one that is not implemented at all.</p> </li> <li><p class="first">Below, <tt class="xref py py-meth docutils literal"><span class="pre">__op__()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></tt> are used to signify the generic method names corresponding to an operator; <tt class="xref py py-meth docutils literal"><span class="pre">__iop__()</span></tt> is used for the corresponding in-place operator. For example, for the operator ‘<tt class="docutils literal"><span class="pre">+</span></tt>‘, <a class="reference internal" href="#object.__add__" title="object.__add__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></a> and <a class="reference internal" href="#object.__radd__" title="object.__radd__"><tt class="xref py py-meth docutils literal"><span class="pre">__radd__()</span></tt></a> are used for the left and right variant of the binary operator, and <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><tt class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></tt></a> for the in-place variant.</p> </li> <li><p class="first">For objects <em>x</em> and <em>y</em>, first <tt class="docutils literal"><span class="pre">x.__op__(y)</span></tt> is tried. If this is not implemented or returns <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>, <tt class="docutils literal"><span class="pre">y.__rop__(x)</span></tt> is tried. If this is also not implemented or returns <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> exception is raised. But see the following exception:</p> </li> <li><p class="first">Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base’s <tt class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></tt> method, the right operand’s <tt class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></tt> method is tried <em>before</em> the left operand’s <tt class="xref py py-meth docutils literal"><span class="pre">__op__()</span></tt> method.</p> <p>This is done so that a subclass can completely override binary operators. Otherwise, the left operand’s <tt class="xref py py-meth docutils literal"><span class="pre">__op__()</span></tt> method would always accept the right operand: when an instance of a given class is expected, an instance of a subclass of that class is always acceptable.</p> </li> <li><p class="first">When either operand type defines a coercion, this coercion is called before that type’s <tt class="xref py py-meth docutils literal"><span class="pre">__op__()</span></tt> or <tt class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></tt> method is called, but no sooner. If the coercion returns an object of a different type for the operand whose coercion is invoked, part of the process is redone using the new object.</p> </li> <li><p class="first">When an in-place operator (like ‘<tt class="docutils literal"><span class="pre">+=</span></tt>‘) is used, if the left operand implements <tt class="xref py py-meth docutils literal"><span class="pre">__iop__()</span></tt>, it is invoked without any coercion. When the operation falls back to <tt class="xref py py-meth docutils literal"><span class="pre">__op__()</span></tt> and/or <tt class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></tt>, the normal coercion rules apply.</p> </li> <li><p class="first">In <tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt>, if <em>x</em> is a sequence that implements sequence concatenation, sequence concatenation is invoked.</p> </li> <li><p class="first">In <tt class="docutils literal"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></tt>, if one operand is a sequence that implements sequence repetition, and the other is an integer (<a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> or <a class="reference internal" href="../library/functions.html#long" title="long"><tt class="xref py py-class docutils literal"><span class="pre">long</span></tt></a>), sequence repetition is invoked.</p> </li> <li><p class="first">Rich comparisons (implemented by methods <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> and so on) never use coercion. Three-way comparison (implemented by <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><tt class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></tt></a>) does use coercion under the same conditions as other binary operations use it.</p> </li> <li><p class="first">In the current implementation, the built-in numeric types <a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>, <a class="reference internal" href="../library/functions.html#long" title="long"><tt class="xref py py-class docutils literal"><span class="pre">long</span></tt></a>, <a class="reference internal" href="../library/functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>, and <a class="reference internal" href="../library/functions.html#complex" title="complex"><tt class="xref py py-class docutils literal"><span class="pre">complex</span></tt></a> do not use coercion. All these types implement a <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><tt class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></tt></a> method, for use by the built-in <a class="reference internal" href="../library/functions.html#coerce" title="coerce"><tt class="xref py py-func docutils literal"><span class="pre">coerce()</span></tt></a> function.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 2.7.</span></p> </li> </ul> </div> <div class="section" id="with-statement-context-managers"> <span id="context-managers"></span><h3>3.4.10. With Statement Context Managers<a class="headerlink" href="#with-statement-context-managers" title="Permalink to this headline">¶</a></h3> <p class="versionadded"> <span class="versionmodified">New in version 2.5.</span></p> <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"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></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"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement (described in section <a class="reference internal" href="compound_stmts.html#with"><em>The with statement</em></a>), but can also be used by directly invoking their methods.</p> <p id="index-96">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"><em>Context Manager Types</em></a>.</p> <dl class="method"> <dt id="object.__enter__"> <tt class="descclassname">object.</tt><tt class="descname">__enter__</tt><big>(</big><em>self</em><big>)</big><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"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement will bind this method’s return value to the target(s) specified in the <a class="reference internal" href="compound_stmts.html#as"><tt class="xref std std-keyword docutils literal"><span class="pre">as</span></tt></a> clause of the statement, if any.</p> </dd></dl> <dl class="method"> <dt id="object.__exit__"> <tt class="descclassname">object.</tt><tt class="descname">__exit__</tt><big>(</big><em>self</em>, <em>exc_type</em>, <em>exc_value</em>, <em>traceback</em><big>)</big><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"><tt class="xref py py-const docutils literal"><span class="pre">None</span></tt></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__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> methods should not reraise the passed-in exception; this is the caller’s responsibility.</p> </dd></dl> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><span class="target" id="index-97"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0343"><strong>PEP 0343</strong></a> - The “with” statement</dt> <dd>The specification, background, and examples for the Python <a class="reference internal" href="compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</dd> </dl> </div> </div> <div class="section" id="special-method-lookup-for-old-style-classes"> <span id="old-style-special-lookup"></span><h3>3.4.11. Special method lookup for old-style classes<a class="headerlink" href="#special-method-lookup-for-old-style-classes" title="Permalink to this headline">¶</a></h3> <p>For old-style classes, special methods are always looked up in exactly the same way as any other method or attribute. This is the case regardless of whether the method is being looked up explicitly as in <tt class="docutils literal"><span class="pre">x.__getitem__(i)</span></tt> or implicitly as in <tt class="docutils literal"><span class="pre">x[i]</span></tt>.</p> <p>This behaviour means that special methods may exhibit different behaviour for different instances of a single old-style class if the appropriate special attributes are set differently:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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">>>> </span><span class="n">c1</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c2</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c1</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">>>> </span><span class="n">c2</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">9</span> <span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c1</span><span class="p">)</span> <span class="go">5</span> <span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c2</span><span class="p">)</span> <span class="go">9</span> </pre></div> </div> </div> <div class="section" id="special-method-lookup-for-new-style-classes"> <span id="new-style-special-lookup"></span><h3>3.4.12. Special method lookup for new-style classes<a class="headerlink" href="#special-method-lookup-for-new-style-classes" title="Permalink to this headline">¶</a></h3> <p>For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception (unlike the equivalent example with old-style classes):</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">>>> </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">>>> </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">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span> <span class="gr">TypeError</span>: <span class="n">object of type 'C' 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__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> and <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></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-python"><div class="highlight"><pre><span class="gp">>>> </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">>>> </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">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span> <span class="gr">TypeError</span>: <span class="n">descriptor '__hash__' of 'int' 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 ‘metaclass confusion’, and is avoided by bypassing the instance when looking up special methods:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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">>>> </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__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> method even of the object’s metaclass:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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="k">print</span> <span class="s">"Metaclass getattribute invoked"</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">>>> </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="gp">... </span> <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">Meta</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="k">print</span> <span class="s">"Class getattribute invoked"</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">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">__len__</span><span class="p">()</span> <span class="c"># Explicit lookup via instance</span> <span class="go">Class getattribute invoked</span> <span class="go">10</span> <span class="gp">>>> </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="c"># Explicit lookup via type</span> <span class="go">Metaclass getattribute invoked</span> <span class="go">10</span> <span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c"># Implicit lookup</span> <span class="go">10</span> </pre></div> </div> <p>Bypassing the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></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> <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’s type, under certain controlled conditions. It generally isn’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__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></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"> <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="#new-style-and-classic-classes">3.3. New-style and classic classes</a></li> <li><a class="reference internal" href="#special-method-names">3.4. Special method names</a><ul> <li><a class="reference internal" href="#basic-customization">3.4.1. Basic customization</a></li> <li><a class="reference internal" href="#customizing-attribute-access">3.4.2. Customizing attribute access</a><ul> <li><a class="reference internal" href="#more-attribute-access-for-new-style-classes">3.4.2.1. More attribute access for new-style classes</a></li> <li><a class="reference internal" href="#implementing-descriptors">3.4.2.2. Implementing Descriptors</a></li> <li><a class="reference internal" href="#invoking-descriptors">3.4.2.3. Invoking Descriptors</a></li> <li><a class="reference internal" href="#slots">3.4.2.4. __slots__</a></li> </ul> </li> <li><a class="reference internal" href="#customizing-class-creation">3.4.3. Customizing class creation</a></li> <li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.4.4. Customizing instance and subclass checks</a></li> <li><a class="reference internal" href="#emulating-callable-objects">3.4.5. Emulating callable objects</a></li> <li><a class="reference internal" href="#emulating-container-types">3.4.6. Emulating container types</a></li> <li><a class="reference internal" href="#additional-methods-for-emulation-of-sequence-types">3.4.7. Additional methods for emulation of sequence types</a></li> <li><a class="reference internal" href="#emulating-numeric-types">3.4.8. Emulating numeric types</a></li> <li><a class="reference internal" href="#coercion-rules">3.4.9. Coercion rules</a></li> <li><a class="reference internal" href="#with-statement-context-managers">3.4.10. With Statement Context Managers</a></li> <li><a class="reference internal" href="#special-method-lookup-for-old-style-classes">3.4.11. Special method lookup for old-style classes</a></li> <li><a class="reference internal" href="#special-method-lookup-for-new-style-classes">3.4.12. Special method lookup for new-style classes</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> <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 id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input 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> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <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="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" >The Python Language Reference</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2020, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Oct 13, 2020. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>