1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5
<html xmlns="http://www.w3.org/1999/xhtml">
7
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
9
<title>3. Data model — Python 2.7.12 documentation</title>
11
<link rel="stylesheet" href="../_static/classic.css" type="text/css" />
12
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
14
<script type="text/javascript">
15
var DOCUMENTATION_OPTIONS = {
18
COLLAPSE_INDEX: false,
23
<script type="text/javascript" src="../_static/jquery.js"></script>
24
<script type="text/javascript" src="../_static/underscore.js"></script>
25
<script type="text/javascript" src="../_static/doctools.js"></script>
26
<script type="text/javascript" src="../_static/sidebar.js"></script>
27
<link rel="search" type="application/opensearchdescription+xml"
28
title="Search within Python 2.7.12 documentation"
29
href="../_static/opensearch.xml"/>
30
<link rel="author" title="About these documents" href="../about.html" />
31
<link rel="copyright" title="Copyright" href="../copyright.html" />
32
<link rel="top" title="Python 2.7.12 documentation" href="../contents.html" />
33
<link rel="up" title="The Python Language Reference" href="index.html" />
34
<link rel="next" title="4. Execution model" href="executionmodel.html" />
35
<link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" />
36
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
37
<script type="text/javascript" src="../_static/copybutton.js"></script>
38
<script type="text/javascript" src="../_static/version_switch.js"></script>
43
<body role="document">
44
<div class="related" role="navigation" aria-label="related navigation">
47
<li class="right" style="margin-right: 10px">
48
<a href="../genindex.html" title="General Index"
49
accesskey="I">index</a></li>
51
<a href="../py-modindex.html" title="Python Module Index"
54
<a href="executionmodel.html" title="4. Execution model"
55
accesskey="N">next</a> |</li>
57
<a href="lexical_analysis.html" title="2. Lexical analysis"
58
accesskey="P">previous</a> |</li>
59
<li><img src="../_static/py.png" alt=""
60
style="vertical-align: middle; margin-top: -1px"/></li>
61
<li><a href="https://www.python.org/">Python</a> »</li>
63
<span class="version_switcher_placeholder">2.7.12</span>
64
<a href="../index.html">Documentation</a> »
67
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> »</li>
71
<div class="document">
72
<div class="documentwrapper">
73
<div class="bodywrapper">
74
<div class="body" role="main">
76
<div class="section" id="data-model">
77
<span id="datamodel"></span><h1>3. Data model<a class="headerlink" href="#data-model" title="Permalink to this headline">¶</a></h1>
78
<div class="section" id="objects-values-and-types">
79
<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>
80
<p id="index-0"><em class="dfn">Objects</em> are Python’s abstraction for data. All data in a Python program
81
is represented by objects or by relations between objects. (In a sense, and in
82
conformance to Von Neumann’s model of a “stored program computer,” code is also
83
represented by objects.)</p>
84
<p id="index-1">Every object has an identity, a type and a value. An object’s <em>identity</em> never
85
changes once it has been created; you may think of it as the object’s address in
86
memory. The ‘<a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal"><span class="pre">is</span></code></a>‘ operator compares the identity of two objects; the
87
<a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal"><span class="pre">id()</span></code></a> function returns an integer representing its identity (currently
88
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>
89
An object’s type determines the operations that the object supports (e.g., “does
90
it have a length?”) and also defines the possible values for objects of that
91
type. The <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a> function returns an object’s type (which is an object
92
itself). The <em>value</em> of some objects can change. Objects whose value can
93
change are said to be <em>mutable</em>; objects whose value is unchangeable once they
94
are created are called <em>immutable</em>. (The value of an immutable container object
95
that contains a reference to a mutable object can change when the latter’s value
96
is changed; however the container is still considered immutable, because the
97
collection of objects it contains cannot be changed. So, immutability is not
98
strictly the same as having an unchangeable value, it is more subtle.) An
99
object’s mutability is determined by its type; for instance, numbers, strings
100
and tuples are immutable, while dictionaries and lists are mutable.</p>
101
<p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable
102
they may be garbage-collected. An implementation is allowed to postpone garbage
103
collection or omit it altogether — it is a matter of implementation quality
104
how garbage collection is implemented, as long as no objects are collected that
105
are still reachable.</p>
106
<div class="impl-detail compound">
107
<p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed
108
detection of cyclically linked garbage, which collects most objects as soon
109
as they become unreachable, but is not guaranteed to collect garbage
110
containing circular references. See the documentation of the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal"><span class="pre">gc</span></code></a>
111
module for information on controlling the collection of cyclic garbage.
112
Other implementations act differently and CPython may change.
113
Do not depend on immediate finalization of objects when they become
114
unreachable (ex: always close files).</p>
116
<p>Note that the use of the implementation’s tracing or debugging facilities may
117
keep objects alive that would normally be collectable. Also note that catching
118
an exception with a ‘<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a>...<a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal"><span class="pre">except</span></code></a>‘ statement may keep
120
<p>Some objects contain references to “external” resources such as open files or
121
windows. It is understood that these resources are freed when the object is
122
garbage-collected, but since garbage collection is not guaranteed to happen,
123
such objects also provide an explicit way to release the external resource,
124
usually a <code class="xref py py-meth docutils literal"><span class="pre">close()</span></code> method. Programs are strongly recommended to explicitly
125
close such objects. The ‘<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a>...<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal"><span class="pre">finally</span></code></a>‘ statement
126
provides a convenient way to do this.</p>
127
<p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>.
128
Examples of containers are tuples, lists and dictionaries. The references are
129
part of a container’s value. In most cases, when we talk about the value of a
130
container, we imply the values, not the identities of the contained objects;
131
however, when we talk about the mutability of a container, only the identities
132
of the immediately contained objects are implied. So, if an immutable container
133
(like a tuple) contains a reference to a mutable object, its value changes if
134
that mutable object is changed.</p>
135
<p>Types affect almost all aspects of object behavior. Even the importance of
136
object identity is affected in some sense: for immutable types, operations that
137
compute new values may actually return a reference to any existing object with
138
the same type and value, while for mutable objects this is not allowed. E.g.,
139
after <code class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></code>, <code class="docutils literal"><span class="pre">a</span></code> and <code class="docutils literal"><span class="pre">b</span></code> may or may not refer to the same object
140
with the value one, depending on the implementation, but after <code class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span>
141
<span class="pre">[]</span></code>, <code class="docutils literal"><span class="pre">c</span></code> and <code class="docutils literal"><span class="pre">d</span></code> are guaranteed to refer to two different, unique, newly
142
created empty lists. (Note that <code class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> assigns the same object to both
143
<code class="docutils literal"><span class="pre">c</span></code> and <code class="docutils literal"><span class="pre">d</span></code>.)</p>
145
<div class="section" id="the-standard-type-hierarchy">
146
<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>
147
<p id="index-4">Below is a list of the types that are built into Python. Extension modules
148
(written in C, Java, or other languages, depending on the implementation) can
149
define additional types. Future versions of Python may add types to the type
150
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).</p>
151
<p id="index-5">Some of the type descriptions below contain a paragraph listing ‘special
152
attributes.’ These are attributes that provide access to the implementation and
153
are not intended for general use. Their definition may change in the future.</p>
154
<dl class="docutils">
156
<dd><p class="first last" id="index-6">This type has a single value. There is a single object with this value. This
157
object is accessed through the built-in name <code class="docutils literal"><span class="pre">None</span></code>. It is used to signify the
158
absence of a value in many situations, e.g., it is returned from functions that
159
don’t explicitly return anything. Its truth value is false.</p>
161
<dt>NotImplemented</dt>
162
<dd><p class="first last" id="index-7">This type has a single value. There is a single object with this value. This
163
object is accessed through the built-in name <code class="docutils literal"><span class="pre">NotImplemented</span></code>. Numeric methods
164
and rich comparison methods may return this value if they do not implement the
165
operation for the operands provided. (The interpreter will then try the
166
reflected operation, or some other fallback, depending on the operator.) Its
167
truth value is true.</p>
170
<dd><p class="first last" id="index-8">This type has a single value. There is a single object with this value. This
171
object is accessed through the built-in name <code class="docutils literal"><span class="pre">Ellipsis</span></code>. It is used to
172
indicate the presence of the <code class="docutils literal"><span class="pre">...</span></code> syntax in a slice. Its truth value is
175
<dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><code class="xref py py-class docutils literal"><span class="pre">numbers.Number</span></code></a></dt>
176
<dd><p class="first" id="index-9">These are created by numeric literals and returned as results by arithmetic
177
operators and arithmetic built-in functions. Numeric objects are immutable;
178
once created their value never changes. Python numbers are of course strongly
179
related to mathematical numbers, but subject to the limitations of numerical
180
representation in computers.</p>
181
<p>Python distinguishes between integers, floating point numbers, and complex
183
<dl class="last docutils">
184
<dt><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal"><span class="pre">numbers.Integral</span></code></a></dt>
185
<dd><p class="first" id="index-10">These represent elements from the mathematical set of integers (positive and
187
<p>There are three types of integers:</p>
188
<dl class="docutils">
189
<dt>Plain integers</dt>
190
<dd><p class="first last" id="index-11">These represent numbers in the range -2147483648 through 2147483647.
191
(The range may be larger on machines with a larger natural word size,
192
but not smaller.) When the result of an operation would fall outside
193
this range, the result is normally returned as a long integer (in some
194
cases, the exception <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></code></a> is raised instead). For the
195
purpose of shift and mask operations, integers are assumed to have a
196
binary, 2’s complement notation using 32 or more bits, and hiding no
197
bits from the user (i.e., all 4294967296 different bit patterns
198
correspond to different values).</p>
200
<dt>Long integers</dt>
201
<dd><p class="first last" id="index-12">These represent numbers in an unlimited range, subject to available
202
(virtual) memory only. For the purpose of shift and mask operations, a
203
binary representation is assumed, and negative numbers are represented
204
in a variant of 2’s complement which gives the illusion of an infinite
205
string of sign bits extending to the left.</p>
208
<dd><p class="first last" id="index-13">These represent the truth values False and True. The two objects
209
representing the values <code class="docutils literal"><span class="pre">False</span></code> and <code class="docutils literal"><span class="pre">True</span></code> are the only Boolean objects.
210
The Boolean type is a subtype of plain integers, and Boolean values
211
behave like the values 0 and 1, respectively, in almost all contexts,
212
the exception being that when converted to a string, the strings
213
<code class="docutils literal"><span class="pre">"False"</span></code> or <code class="docutils literal"><span class="pre">"True"</span></code> are returned, respectively.</p>
216
<p class="last" id="index-14">The rules for integer representation are intended to give the most
217
meaningful interpretation of shift and mask operations involving negative
218
integers and the least surprises when switching between the plain and long
219
integer domains. Any operation, if it yields a result in the plain
220
integer domain, will yield the same result in the long integer domain or
221
when using mixed operands. The switch between domains is transparent to
224
<dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></code></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal"><span class="pre">float</span></code></a>)</dt>
225
<dd><p class="first last" id="index-15">These represent machine-level double precision floating point numbers. You are
226
at the mercy of the underlying machine architecture (and C or Java
227
implementation) for the accepted range and handling of overflow. Python does not
228
support single-precision floating point numbers; the savings in processor and
229
memory usage that are usually the reason for using these are dwarfed by the
230
overhead of using objects in Python, so there is no reason to complicate the
231
language with two kinds of floating point numbers.</p>
233
<dt><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal"><span class="pre">numbers.Complex</span></code></a></dt>
234
<dd><p class="first last" id="index-16">These represent complex numbers as a pair of machine-level double precision
235
floating point numbers. The same caveats apply as for floating point numbers.
236
The real and imaginary parts of a complex number <code class="docutils literal"><span class="pre">z</span></code> can be retrieved through
237
the read-only attributes <code class="docutils literal"><span class="pre">z.real</span></code> and <code class="docutils literal"><span class="pre">z.imag</span></code>.</p>
242
<dd><p class="first" id="index-17">These represent finite ordered sets indexed by non-negative numbers. The
243
built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> returns the number of items of a sequence. When
244
the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1,
245
..., <em>n</em>-1. Item <em>i</em> of sequence <em>a</em> is selected by <code class="docutils literal"><span class="pre">a[i]</span></code>.</p>
246
<p id="index-18">Sequences also support slicing: <code class="docutils literal"><span class="pre">a[i:j]</span></code> selects all items with index <em>k</em> such
247
that <em>i</em> <code class="docutils literal"><span class="pre"><=</span></code> <em>k</em> <code class="docutils literal"><span class="pre"><</span></code> <em>j</em>. When used as an expression, a slice is a
248
sequence of the same type. This implies that the index set is renumbered so
249
that it starts at 0.</p>
250
<p id="index-19">Some sequences also support “extended slicing” with a third “step” parameter:
251
<code class="docutils literal"><span class="pre">a[i:j:k]</span></code> selects all items of <em>a</em> with index <em>x</em> where <code class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code>, <em>n</em>
252
<code class="docutils literal"><span class="pre">>=</span></code> <code class="docutils literal"><span class="pre">0</span></code> and <em>i</em> <code class="docutils literal"><span class="pre"><=</span></code> <em>x</em> <code class="docutils literal"><span class="pre"><</span></code> <em>j</em>.</p>
253
<p>Sequences are distinguished according to their mutability:</p>
254
<dl class="last docutils">
255
<dt>Immutable sequences</dt>
256
<dd><p class="first" id="index-20">An object of an immutable sequence type cannot change once it is created. (If
257
the object contains references to other objects, these other objects may be
258
mutable and may be changed; however, the collection of objects directly
259
referenced by an immutable object cannot change.)</p>
260
<p>The following types are immutable sequences:</p>
261
<dl class="last docutils">
263
<dd><p class="first" id="index-21">The items of a string are characters. There is no separate character type; a
264
character is represented by a string of one item. Characters represent (at
265
least) 8-bit bytes. The built-in functions <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal"><span class="pre">chr()</span></code></a> and <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal"><span class="pre">ord()</span></code></a> convert
266
between characters and nonnegative integers representing the byte values. Bytes
267
with the values 0–127 usually represent the corresponding ASCII values, but the
268
interpretation of values is up to the program. The string data type is also
269
used to represent arrays of bytes, e.g., to hold data read from a file.</p>
270
<p class="last" id="index-22">(On systems whose native character set is not ASCII, strings may use EBCDIC in
271
their internal representation, provided the functions <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal"><span class="pre">chr()</span></code></a> and
272
<a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal"><span class="pre">ord()</span></code></a> implement a mapping between ASCII and EBCDIC, and string comparison
273
preserves the ASCII order. Or perhaps someone can propose a better rule?)</p>
276
<dd><p class="first last" id="index-23">The items of a Unicode object are Unicode code units. A Unicode code unit is
277
represented by a Unicode object of one item and can hold either a 16-bit or
278
32-bit value representing a Unicode ordinal (the maximum value for the ordinal
279
is given in <code class="docutils literal"><span class="pre">sys.maxunicode</span></code>, and depends on how Python is configured at
280
compile time). Surrogate pairs may be present in the Unicode object, and will
281
be reported as two separate items. The built-in functions <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><code class="xref py py-func docutils literal"><span class="pre">unichr()</span></code></a> and
282
<a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal"><span class="pre">ord()</span></code></a> convert between code units and nonnegative integers representing the
283
Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to
284
other encodings are possible through the Unicode method <code class="xref py py-meth docutils literal"><span class="pre">encode()</span></code> and the
285
built-in function <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal"><span class="pre">unicode()</span></code></a>.</p>
288
<dd><p class="first last" id="index-24">The items of a tuple are arbitrary Python objects. Tuples of two or more items
289
are formed by comma-separated lists of expressions. A tuple of one item (a
290
‘singleton’) can be formed by affixing a comma to an expression (an expression
291
by itself does not create a tuple, since parentheses must be usable for grouping
292
of expressions). An empty tuple can be formed by an empty pair of parentheses.</p>
296
<dt>Mutable sequences</dt>
297
<dd><p class="first" id="index-25">Mutable sequences can be changed after they are created. The subscription and
298
slicing notations can be used as the target of assignment and <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal"><span class="pre">del</span></code></a>
299
(delete) statements.</p>
300
<p>There are currently two intrinsic mutable sequence types:</p>
301
<dl class="docutils">
303
<dd><p class="first last" id="index-26">The items of a list are arbitrary Python objects. Lists are formed by placing a
304
comma-separated list of expressions in square brackets. (Note that there are no
305
special cases needed to form lists of length 0 or 1.)</p>
308
<dd><p class="first last" id="index-27">A bytearray object is a mutable array. They are created by the built-in
309
<a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal"><span class="pre">bytearray()</span></code></a> constructor. Aside from being mutable (and hence
310
unhashable), byte arrays otherwise provide the same interface and
311
functionality as immutable bytes objects.</p>
314
<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."><code class="xref py py-mod docutils literal"><span class="pre">array</span></code></a> provides an additional example of a mutable
320
<dd><p class="first" id="index-29">These represent unordered, finite sets of unique, immutable objects. As such,
321
they cannot be indexed by any subscript. However, they can be iterated over, and
322
the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> returns the number of items in a set. Common
323
uses for sets are fast membership testing, removing duplicates from a sequence,
324
and computing mathematical operations such as intersection, union, difference,
325
and symmetric difference.</p>
326
<p>For set elements, the same immutability rules apply as for dictionary keys. Note
327
that numeric types obey the normal rules for numeric comparison: if two numbers
328
compare equal (e.g., <code class="docutils literal"><span class="pre">1</span></code> and <code class="docutils literal"><span class="pre">1.0</span></code>), only one of them can be contained in a
330
<p>There are currently two intrinsic set types:</p>
331
<dl class="last docutils">
333
<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"><code class="xref py py-func docutils literal"><span class="pre">set()</span></code></a>
334
constructor and can be modified afterwards by several methods, such as
335
<a class="reference internal" href="../library/stdtypes.html#set.add" title="set.add"><code class="xref py py-meth docutils literal"><span class="pre">add()</span></code></a>.</p>
338
<dd><p class="first last" id="index-31">These represent an immutable set. They are created by the built-in
339
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal"><span class="pre">frozenset()</span></code></a> constructor. As a frozenset is immutable and
340
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, it can be used again as an element of another set, or as
341
a dictionary key.</p>
346
<dd><p class="first" id="index-32">These represent finite sets of objects indexed by arbitrary index sets. The
347
subscript notation <code class="docutils literal"><span class="pre">a[k]</span></code> selects the item indexed by <code class="docutils literal"><span class="pre">k</span></code> from the mapping
348
<code class="docutils literal"><span class="pre">a</span></code>; this can be used in expressions and as the target of assignments or
349
<a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal"><span class="pre">del</span></code></a> statements. The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> returns the number
350
of items in a mapping.</p>
351
<p>There is currently a single intrinsic mapping type:</p>
352
<dl class="last docutils">
353
<dt>Dictionaries</dt>
354
<dd><p class="first" id="index-33">These represent finite sets of objects indexed by nearly arbitrary values. The
355
only types of values not acceptable as keys are values containing lists or
356
dictionaries or other mutable types that are compared by value rather than by
357
object identity, the reason being that the efficient implementation of
358
dictionaries requires a key’s hash value to remain constant. Numeric types used
359
for keys obey the normal rules for numeric comparison: if two numbers compare
360
equal (e.g., <code class="docutils literal"><span class="pre">1</span></code> and <code class="docutils literal"><span class="pre">1.0</span></code>) then they can be used interchangeably to index
361
the same dictionary entry.</p>
362
<p>Dictionaries are mutable; they can be created by the <code class="docutils literal"><span class="pre">{...}</span></code> notation (see
363
section <a class="reference internal" href="expressions.html#dict"><span>Dictionary displays</span></a>).</p>
364
<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)"><code class="xref py py-mod docutils literal"><span class="pre">dbm</span></code></a>, <a class="reference internal" href="../library/gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal"><span class="pre">gdbm</span></code></a>, and <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal"><span class="pre">bsddb</span></code></a> provide
365
additional examples of mapping types.</p>
369
<dt>Callable types</dt>
370
<dd><p class="first" id="index-35">These are the types to which the function call operation (see section
371
<a class="reference internal" href="expressions.html#calls"><span>Calls</span></a>) can be applied:</p>
372
<dl class="last docutils">
373
<dt>User-defined functions</dt>
374
<dd><p class="first" id="index-36">A user-defined function object is created by a function definition (see
375
section <a class="reference internal" href="compound_stmts.html#function"><span>Function definitions</span></a>). It should be called with an argument list
376
containing the same number of items as the function’s formal parameter
378
<p>Special attributes:</p>
379
<table border="1" class="docutils" id="index-37">
385
<thead valign="bottom">
386
<tr class="row-odd"><th class="head">Attribute</th>
387
<th class="head">Meaning</th>
388
<th class="head"> </th>
392
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code>
393
<code class="xref py py-attr docutils literal"><span class="pre">func_doc</span></code></td>
394
<td>The function’s documentation
395
string, or <code class="docutils literal"><span class="pre">None</span></code> if
399
<tr class="row-odd"><td><a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a>
400
<code class="xref py py-attr docutils literal"><span class="pre">func_name</span></code></td>
401
<td>The function’s name</td>
404
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code></td>
405
<td>The name of the module the
406
function was defined in, or
407
<code class="docutils literal"><span class="pre">None</span></code> if unavailable.</td>
410
<tr class="row-odd"><td><code class="xref py py-attr docutils literal"><span class="pre">__defaults__</span></code>
411
<code class="xref py py-attr docutils literal"><span class="pre">func_defaults</span></code></td>
412
<td>A tuple containing default
413
argument values for those
414
arguments that have defaults,
415
or <code class="docutils literal"><span class="pre">None</span></code> if no arguments
416
have a default value.</td>
419
<tr class="row-even"><td><code class="xref py py-attr docutils literal"><span class="pre">__code__</span></code>
420
<code class="xref py py-attr docutils literal"><span class="pre">func_code</span></code></td>
421
<td>The code object representing
422
the compiled function body.</td>
425
<tr class="row-odd"><td><code class="xref py py-attr docutils literal"><span class="pre">__globals__</span></code>
426
<code class="xref py py-attr docutils literal"><span class="pre">func_globals</span></code></td>
427
<td>A reference to the dictionary
428
that holds the function’s
429
global variables — the
430
global namespace of the
431
module in which the function
435
<tr class="row-even"><td><a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a>
436
<code class="xref py py-attr docutils literal"><span class="pre">func_dict</span></code></td>
437
<td>The namespace supporting
442
<tr class="row-odd"><td><code class="xref py py-attr docutils literal"><span class="pre">__closure__</span></code>
443
<code class="xref py py-attr docutils literal"><span class="pre">func_closure</span></code></td>
444
<td><code class="docutils literal"><span class="pre">None</span></code> or a tuple of cells
445
that contain bindings for the
446
function’s free variables.</td>
451
<p>Most of the attributes labelled “Writable” check the type of the assigned value.</p>
452
<div class="versionchanged">
453
<p><span class="versionmodified">Changed in version 2.4: </span><code class="docutils literal"><span class="pre">func_name</span></code> is now writable.</p>
455
<div class="versionchanged">
456
<p><span class="versionmodified">Changed in version 2.6: </span>The double-underscore attributes <code class="docutils literal"><span class="pre">__closure__</span></code>, <code class="docutils literal"><span class="pre">__code__</span></code>,
457
<code class="docutils literal"><span class="pre">__defaults__</span></code>, and <code class="docutils literal"><span class="pre">__globals__</span></code> were introduced as aliases for
458
the corresponding <code class="docutils literal"><span class="pre">func_*</span></code> attributes for forwards compatibility
461
<p>Function objects also support getting and setting arbitrary attributes, which
462
can be used, for example, to attach metadata to functions. Regular attribute
463
dot-notation is used to get and set such attributes. <em>Note that the current
464
implementation only supports function attributes on user-defined functions.
465
Function attributes on built-in functions may be supported in the future.</em></p>
466
<p class="last">Additional information about a function’s definition can be retrieved from its
467
code object; see the description of internal types below.</p>
469
<dt>User-defined methods</dt>
470
<dd><p class="first" id="index-38">A user-defined method object combines a class, a class instance (or <code class="docutils literal"><span class="pre">None</span></code>)
471
and any callable object (normally a user-defined function).</p>
472
<p>Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> is the class instance object,
473
<code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code> is the function object; <code class="xref py py-attr docutils literal"><span class="pre">im_class</span></code> is the class of
474
<code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> for bound methods or the class that asked for the method for
475
unbound methods; <code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the method’s documentation (same as
476
<code class="docutils literal"><span class="pre">im_func.__doc__</span></code>); <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the method name (same as
477
<code class="docutils literal"><span class="pre">im_func.__name__</span></code>); <code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code> is the name of the module the method
478
was defined in, or <code class="docutils literal"><span class="pre">None</span></code> if unavailable.</p>
479
<div class="versionchanged">
480
<p><span class="versionmodified">Changed in version 2.2: </span><code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> used to refer to the class that defined the method.</p>
482
<div class="versionchanged">
483
<p><span class="versionmodified">Changed in version 2.6: </span>For Python 3 forward-compatibility, <code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code> is also available as
484
<code class="xref py py-attr docutils literal"><span class="pre">__func__</span></code>, and <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> as <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code>.</p>
486
<p id="index-39">Methods also support accessing (but not setting) the arbitrary function
487
attributes on the underlying function object.</p>
488
<p>User-defined method objects may be created when getting an attribute of a class
489
(perhaps via an instance of that class), if that attribute is a user-defined
490
function object, an unbound user-defined method object, or a class method
491
object. When the attribute is a user-defined method object, a new method object
492
is only created if the class from which it is being retrieved is the same as, or
493
a derived class of, the class stored in the original method object; otherwise,
494
the original method object is used as it is.</p>
495
<p id="index-40">When a user-defined method object is created by retrieving a user-defined
496
function object from a class, its <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> attribute is <code class="docutils literal"><span class="pre">None</span></code>
497
and the method object is said to be unbound. When one is created by
498
retrieving a user-defined function object from a class via one of its
499
instances, its <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> attribute is the instance, and the method
500
object is said to be bound. In either case, the new method’s
501
<code class="xref py py-attr docutils literal"><span class="pre">im_class</span></code> attribute is the class from which the retrieval takes
502
place, and its <code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code> attribute is the original function object.</p>
503
<p id="index-41">When a user-defined method object is created by retrieving another method object
504
from a class or instance, the behaviour is the same as for a function object,
505
except that the <code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code> attribute of the new instance is not the
506
original method object but its <code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code> attribute.</p>
507
<p id="index-42">When a user-defined method object is created by retrieving a class method object
508
from a class or instance, its <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> attribute is the class itself, and
509
its <code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code> attribute is the function object underlying the class method.</p>
510
<p>When an unbound user-defined method object is called, the underlying function
511
(<code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code>) is called, with the restriction that the first argument must
512
be an instance of the proper class (<code class="xref py py-attr docutils literal"><span class="pre">im_class</span></code>) or of a derived class
514
<p>When a bound user-defined method object is called, the underlying function
515
(<code class="xref py py-attr docutils literal"><span class="pre">im_func</span></code>) is called, inserting the class instance (<code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code>) in
516
front of the argument list. For instance, when <code class="xref py py-class docutils literal"><span class="pre">C</span></code> is a class which
517
contains a definition for a function <code class="xref py py-meth docutils literal"><span class="pre">f()</span></code>, and <code class="docutils literal"><span class="pre">x</span></code> is an instance of
518
<code class="xref py py-class docutils literal"><span class="pre">C</span></code>, calling <code class="docutils literal"><span class="pre">x.f(1)</span></code> is equivalent to calling <code class="docutils literal"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>.</p>
519
<p>When a user-defined method object is derived from a class method object, the
520
“class instance” stored in <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> will actually be the class itself, so
521
that calling either <code class="docutils literal"><span class="pre">x.f(1)</span></code> or <code class="docutils literal"><span class="pre">C.f(1)</span></code> is equivalent to calling <code class="docutils literal"><span class="pre">f(C,1)</span></code>
522
where <code class="docutils literal"><span class="pre">f</span></code> is the underlying function.</p>
523
<p class="last">Note that the transformation from function object to (unbound or bound) method
524
object happens each time the attribute is retrieved from the class or instance.
525
In some cases, a fruitful optimization is to assign the attribute to a local
526
variable and call that local variable. Also notice that this transformation only
527
happens for user-defined functions; other callable objects (and all non-callable
528
objects) are retrieved without transformation. It is also important to note
529
that user-defined functions which are attributes of a class instance are not
530
converted to bound methods; this <em>only</em> happens when the function is an
531
attribute of the class.</p>
533
<dt>Generator functions</dt>
534
<dd><p class="first last" id="index-43">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal"><span class="pre">yield</span></code></a> statement (see section
535
<a class="reference internal" href="simple_stmts.html#yield"><span>The yield statement</span></a>) is called a <em class="dfn">generator
536
function</em>. Such a function, when called, always returns an iterator object
537
which can be used to execute the body of the function: calling the iterator’s
538
<a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal"><span class="pre">next()</span></code></a> method will cause the function to execute until
540
using the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal"><span class="pre">yield</span></code></a> statement. When the function executes a
541
<a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal"><span class="pre">return</span></code></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></code></a>
542
exception is raised and the iterator will have reached the end of the set of
543
values to be returned.</p>
545
<dt>Built-in functions</dt>
546
<dd><p class="first last" id="index-44">A built-in function object is a wrapper around a C function. Examples of
547
built-in functions are <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal"><span class="pre">math.sin()</span></code></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal"><span class="pre">math</span></code></a> is a
548
standard built-in module). The number and type of the arguments are
549
determined by the C function. Special read-only attributes:
550
<code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the function’s documentation string, or <code class="docutils literal"><span class="pre">None</span></code> if
551
unavailable; <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the function’s name; <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> is
552
set to <code class="docutils literal"><span class="pre">None</span></code> (but see the next item); <code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code> is the name of
553
the module the function was defined in or <code class="docutils literal"><span class="pre">None</span></code> if unavailable.</p>
555
<dt>Built-in methods</dt>
556
<dd><p class="first last" id="index-45">This is really a different disguise of a built-in function, this time containing
557
an object passed to the C function as an implicit extra argument. An example of
558
a built-in method is <code class="docutils literal"><span class="pre">alist.append()</span></code>, assuming <em>alist</em> is a list object. In
559
this case, the special read-only attribute <code class="xref py py-attr docutils literal"><span class="pre">__self__</span></code> is set to the object
560
denoted by <em>alist</em>.</p>
563
<dd>Class types, or “new-style classes,” are callable. These objects normally act
564
as factories for new instances of themselves, but variations are possible for
565
class types that override <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a>. The arguments of the call are passed
566
to <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> to initialize
567
the new instance.</dd>
568
<dt>Classic Classes</dt>
569
<dd><p class="first last" id="index-46">Class objects are described below. When a class object is called, a new class
570
instance (also described below) is created and returned. This implies a call to
571
the class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method if it has one. Any arguments are passed on
572
to the <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method. If there is no <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method, the
573
class must be called without arguments.</p>
575
<dt>Class instances</dt>
576
<dd>Class instances are described below. Class instances are callable only when the
577
class has a <a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal"><span class="pre">__call__()</span></code></a> method; <code class="docutils literal"><span class="pre">x(arguments)</span></code> is a shorthand for
578
<code class="docutils literal"><span class="pre">x.__call__(arguments)</span></code>.</dd>
582
<dd><p class="first" id="index-47">Modules are imported by the <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal"><span class="pre">import</span></code></a> statement (see section
583
<a class="reference internal" href="simple_stmts.html#import"><span>The import statement</span></a>). A module object has a
584
namespace implemented by a dictionary object (this is the dictionary referenced
585
by the func_globals attribute of functions defined in the module). Attribute
586
references are translated to lookups in this dictionary, e.g., <code class="docutils literal"><span class="pre">m.x</span></code> is
587
equivalent to <code class="docutils literal"><span class="pre">m.__dict__["x"]</span></code>. A module object does not contain the code
588
object used to initialize the module (since it isn’t needed once the
589
initialization is done).</p>
590
<p>Attribute assignment updates the module’s namespace dictionary, e.g., <code class="docutils literal"><span class="pre">m.x</span> <span class="pre">=</span>
591
<span class="pre">1</span></code> is equivalent to <code class="docutils literal"><span class="pre">m.__dict__["x"]</span> <span class="pre">=</span> <span class="pre">1</span></code>.</p>
592
<p id="index-48">Special read-only attribute: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> is the module’s namespace as a
593
dictionary object.</p>
594
<div class="impl-detail compound">
595
<p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module
596
dictionary will be cleared when the module falls out of scope even if the
597
dictionary still has live references. To avoid this, copy the dictionary
598
or keep the module around while using its dictionary directly.</p>
600
<p class="last" id="index-49">Predefined (writable) attributes: <code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code> is the module’s name;
601
<code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the module’s documentation string, or <code class="docutils literal"><span class="pre">None</span></code> if
602
unavailable; <code class="xref py py-attr docutils literal"><span class="pre">__file__</span></code> is the pathname of the file from which the module
603
was loaded, if it was loaded from a file. The <code class="xref py py-attr docutils literal"><span class="pre">__file__</span></code> attribute is not
604
present for C modules that are statically linked into the interpreter; for
605
extension modules loaded dynamically from a shared library, it is the pathname
606
of the shared library file.</p>
609
<dd><p class="first">Both class types (new-style classes) and class objects (old-style/classic
610
classes) are typically created by class definitions (see section
611
<a class="reference internal" href="compound_stmts.html#class"><span>Class definitions</span></a>). A class has a namespace implemented by a dictionary object.
612
Class attribute references are translated to lookups in this dictionary, e.g.,
613
<code class="docutils literal"><span class="pre">C.x</span></code> is translated to <code class="docutils literal"><span class="pre">C.__dict__["x"]</span></code> (although for new-style classes
614
in particular there are a number of hooks which allow for other means of
615
locating attributes). When the attribute name is not found there, the
616
attribute search continues in the base classes. For old-style classes, the
617
search is depth-first, left-to-right in the order of occurrence in the base
618
class list. New-style classes use the more complex C3 method resolution
619
order which behaves correctly even in the presence of ‘diamond’
620
inheritance structures where there are multiple inheritance paths
621
leading back to a common ancestor. Additional details on the C3 MRO used by
622
new-style classes can be found in the documentation accompanying the
623
2.3 release at <a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
624
<p id="index-50">When a class attribute reference (for class <code class="xref py py-class docutils literal"><span class="pre">C</span></code>, say) would yield a
625
user-defined function object or an unbound user-defined method object whose
626
associated class is either <code class="xref py py-class docutils literal"><span class="pre">C</span></code> or one of its base classes, it is
627
transformed into an unbound user-defined method object whose <code class="xref py py-attr docutils literal"><span class="pre">im_class</span></code>
628
attribute is <code class="xref py py-class docutils literal"><span class="pre">C</span></code>. When it would yield a class method object, it is
629
transformed into a bound user-defined method object whose
630
<code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> attribute is <code class="xref py py-class docutils literal"><span class="pre">C</span></code>. When it would yield a
631
static method object, it is transformed into the object wrapped by the static
632
method object. See section <a class="reference internal" href="#descriptors"><span>Implementing Descriptors</span></a> for another way in which
633
attributes retrieved from a class may differ from those actually contained in
634
its <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> (note that only new-style classes support descriptors).</p>
635
<p id="index-51">Class attribute assignments update the class’s dictionary, never the dictionary
637
<p id="index-52">A class object can be called (see above) to yield a class instance (see below).</p>
638
<p class="last" id="index-53">Special attributes: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal"><span class="pre">__name__</span></code></a> is the class name; <code class="xref py py-attr docutils literal"><span class="pre">__module__</span></code> is
639
the module name in which the class was defined; <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> is the
640
dictionary containing the class’s namespace; <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal"><span class="pre">__bases__</span></code></a> is a
641
tuple (possibly empty or a singleton) containing the base classes, in the
642
order of their occurrence in the base class list; <code class="xref py py-attr docutils literal"><span class="pre">__doc__</span></code> is the
643
class’s documentation string, or <code class="docutils literal"><span class="pre">None</span></code> if undefined.</p>
645
<dt>Class instances</dt>
646
<dd><p class="first" id="index-54">A class instance is created by calling a class object (see above). A class
647
instance has a namespace implemented as a dictionary which is the first place in
648
which attribute references are searched. When an attribute is not found there,
649
and the instance’s class has an attribute by that name, the search continues
650
with the class attributes. If a class attribute is found that is a user-defined
651
function object or an unbound user-defined method object whose associated class
652
is the class (call it <code class="xref py py-class docutils literal"><span class="pre">C</span></code>) of the instance for which the attribute
653
reference was initiated or one of its bases, it is transformed into a bound
654
user-defined method object whose <code class="xref py py-attr docutils literal"><span class="pre">im_class</span></code> attribute is <code class="xref py py-class docutils literal"><span class="pre">C</span></code> and
655
whose <code class="xref py py-attr docutils literal"><span class="pre">im_self</span></code> attribute is the instance. Static method and class method
656
objects are also transformed, as if they had been retrieved from class
657
<code class="xref py py-class docutils literal"><span class="pre">C</span></code>; see above under “Classes”. See section <a class="reference internal" href="#descriptors"><span>Implementing Descriptors</span></a> for
658
another way in which attributes of a class retrieved via its instances may
659
differ from the objects actually stored in the class’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a>. If no
660
class attribute is found, and the object’s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a>
661
method, that is called to satisfy the lookup.</p>
662
<p id="index-55">Attribute assignments and deletions update the instance’s dictionary, never a
663
class’s dictionary. If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a> or
664
<a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal"><span class="pre">__delattr__()</span></code></a> method, this is called instead of updating the instance
665
dictionary directly.</p>
666
<p id="index-56">Class instances can pretend to be numbers, sequences, or mappings if they have
667
methods with certain special names. See section <a class="reference internal" href="#specialnames"><span>Special method names</span></a>.</p>
668
<p class="last" id="index-57">Special attributes: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a> is the attribute dictionary;
669
<a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal"><span class="pre">__class__</span></code></a> is the instance’s class.</p>
672
<dd><p class="first last" id="index-58">A file object represents an open file. File objects are created by the
673
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal"><span class="pre">open()</span></code></a> built-in function, and also by <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal"><span class="pre">os.popen()</span></code></a>,
674
<a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal"><span class="pre">os.fdopen()</span></code></a>, and the <code class="xref py py-meth docutils literal"><span class="pre">makefile()</span></code> method of socket objects (and
675
perhaps by other functions or methods provided by extension modules). The
676
objects <code class="docutils literal"><span class="pre">sys.stdin</span></code>, <code class="docutils literal"><span class="pre">sys.stdout</span></code> and <code class="docutils literal"><span class="pre">sys.stderr</span></code> are initialized to
677
file objects corresponding to the interpreter’s standard input, output and
678
error streams. See <a class="reference internal" href="../library/stdtypes.html#bltin-file-objects"><span>File Objects</span></a> for complete documentation of
681
<dt>Internal types</dt>
682
<dd><p class="first" id="index-59">A few types used internally by the interpreter are exposed to the user. Their
683
definitions may change with future versions of the interpreter, but they are
684
mentioned here for completeness.</p>
685
<dl class="docutils" id="index-60">
686
<dt>Code objects</dt>
687
<dd><p class="first">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>.
688
The difference between a code object and a function object is that the function
689
object contains an explicit reference to the function’s globals (the module in
690
which it was defined), while a code object contains no context; also the default
691
argument values are stored in the function object, not in the code object
692
(because they represent values calculated at run-time). Unlike function
693
objects, code objects are immutable and contain no references (directly or
694
indirectly) to mutable objects.</p>
695
<p id="index-61">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">co_name</span></code> gives the function name;
696
<code class="xref py py-attr docutils literal"><span class="pre">co_argcount</span></code> is the number of positional arguments (including arguments
697
with default values); <code class="xref py py-attr docutils literal"><span class="pre">co_nlocals</span></code> is the number of local variables used
698
by the function (including arguments); <code class="xref py py-attr docutils literal"><span class="pre">co_varnames</span></code> is a tuple containing
699
the names of the local variables (starting with the argument names);
700
<code class="xref py py-attr docutils literal"><span class="pre">co_cellvars</span></code> is a tuple containing the names of local variables that are
701
referenced by nested functions; <code class="xref py py-attr docutils literal"><span class="pre">co_freevars</span></code> is a tuple containing the
702
names of free variables; <code class="xref py py-attr docutils literal"><span class="pre">co_code</span></code> is a string representing the sequence
703
of bytecode instructions; <code class="xref py py-attr docutils literal"><span class="pre">co_consts</span></code> is a tuple containing the literals
704
used by the bytecode; <code class="xref py py-attr docutils literal"><span class="pre">co_names</span></code> is a tuple containing the names used by
705
the bytecode; <code class="xref py py-attr docutils literal"><span class="pre">co_filename</span></code> is the filename from which the code was
706
compiled; <code class="xref py py-attr docutils literal"><span class="pre">co_firstlineno</span></code> is the first line number of the function;
707
<code class="xref py py-attr docutils literal"><span class="pre">co_lnotab</span></code> is a string encoding the mapping from bytecode offsets to
708
line numbers (for details see the source code of the interpreter);
709
<code class="xref py py-attr docutils literal"><span class="pre">co_stacksize</span></code> is the required stack size (including local variables);
710
<code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code> is an integer encoding a number of flags for the interpreter.</p>
711
<p id="index-62">The following flag bits are defined for <code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code>: bit <code class="docutils literal"><span class="pre">0x04</span></code> is set if
712
the function uses the <code class="docutils literal"><span class="pre">*arguments</span></code> syntax to accept an arbitrary number of
713
positional arguments; bit <code class="docutils literal"><span class="pre">0x08</span></code> is set if the function uses the
714
<code class="docutils literal"><span class="pre">**keywords</span></code> syntax to accept arbitrary keyword arguments; bit <code class="docutils literal"><span class="pre">0x20</span></code> is set
715
if the function is a generator.</p>
716
<p>Future feature declarations (<code class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code>) also use bits
717
in <code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code> to indicate whether a code object was compiled with a
718
particular feature enabled: bit <code class="docutils literal"><span class="pre">0x2000</span></code> is set if the function was compiled
719
with future division enabled; bits <code class="docutils literal"><span class="pre">0x10</span></code> and <code class="docutils literal"><span class="pre">0x1000</span></code> were used in earlier
720
versions of Python.</p>
721
<p>Other bits in <code class="xref py py-attr docutils literal"><span class="pre">co_flags</span></code> are reserved for internal use.</p>
722
<p class="last" id="index-63">If a code object represents a function, the first item in <code class="xref py py-attr docutils literal"><span class="pre">co_consts</span></code> is
723
the documentation string of the function, or <code class="docutils literal"><span class="pre">None</span></code> if undefined.</p>
726
<dl class="last docutils" id="frame-objects">
727
<dt>Frame objects</dt>
728
<dd><p class="first" id="index-64">Frame objects represent execution frames. They may occur in traceback objects
730
<p id="index-65">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">f_back</span></code> is to the previous stack frame
731
(towards the caller), or <code class="docutils literal"><span class="pre">None</span></code> if this is the bottom stack frame;
732
<code class="xref py py-attr docutils literal"><span class="pre">f_code</span></code> is the code object being executed in this frame; <code class="xref py py-attr docutils literal"><span class="pre">f_locals</span></code>
733
is the dictionary used to look up local variables; <code class="xref py py-attr docutils literal"><span class="pre">f_globals</span></code> is used for
734
global variables; <code class="xref py py-attr docutils literal"><span class="pre">f_builtins</span></code> is used for built-in (intrinsic) names;
735
<code class="xref py py-attr docutils literal"><span class="pre">f_restricted</span></code> is a flag indicating whether the function is executing in
736
restricted execution mode; <code class="xref py py-attr docutils literal"><span class="pre">f_lasti</span></code> gives the precise instruction (this
737
is an index into the bytecode string of the code object).</p>
738
<p class="last" id="index-66">Special writable attributes: <code class="xref py py-attr docutils literal"><span class="pre">f_trace</span></code>, if not <code class="docutils literal"><span class="pre">None</span></code>, is a function
739
called at the start of each source code line (this is used by the debugger);
740
<code class="xref py py-attr docutils literal"><span class="pre">f_exc_type</span></code>, <code class="xref py py-attr docutils literal"><span class="pre">f_exc_value</span></code>, <code class="xref py py-attr docutils literal"><span class="pre">f_exc_traceback</span></code> represent the
741
last exception raised in the parent frame provided another exception was ever
742
raised in the current frame (in all other cases they are <code class="docutils literal"><span class="pre">None</span></code>); <code class="xref py py-attr docutils literal"><span class="pre">f_lineno</span></code>
743
is the current line number of the frame — writing to this from within a trace
744
function jumps to the given line (only for the bottom-most frame). A debugger
745
can implement a Jump command (aka Set Next Statement) by writing to f_lineno.</p>
747
<dt>Traceback objects</dt>
748
<dd><p class="first" id="index-67">Traceback objects represent a stack trace of an exception. A traceback object
749
is created when an exception occurs. When the search for an exception handler
750
unwinds the execution stack, at each unwound level a traceback object is
751
inserted in front of the current traceback. When an exception handler is
752
entered, the stack trace is made available to the program. (See section
753
<a class="reference internal" href="compound_stmts.html#try"><span>The try statement</span></a>.) It is accessible as <code class="docutils literal"><span class="pre">sys.exc_traceback</span></code>,
754
and also as the third item of the tuple returned by <code class="docutils literal"><span class="pre">sys.exc_info()</span></code>. The
755
latter is the preferred interface, since it works correctly when the program is
756
using multiple threads. When the program contains no suitable handler, the stack
757
trace is written (nicely formatted) to the standard error stream; if the
758
interpreter is interactive, it is also made available to the user as
759
<code class="docutils literal"><span class="pre">sys.last_traceback</span></code>.</p>
760
<p class="last" id="index-68">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">tb_next</span></code> is the next level in the stack
761
trace (towards the frame where the exception occurred), or <code class="docutils literal"><span class="pre">None</span></code> if there is
762
no next level; <code class="xref py py-attr docutils literal"><span class="pre">tb_frame</span></code> points to the execution frame of the current
763
level; <code class="xref py py-attr docutils literal"><span class="pre">tb_lineno</span></code> gives the line number where the exception occurred;
764
<code class="xref py py-attr docutils literal"><span class="pre">tb_lasti</span></code> indicates the precise instruction. The line number and last
765
instruction in the traceback may differ from the line number of its frame object
766
if the exception occurred in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a> statement with no matching except
767
clause or with a finally clause.</p>
769
<dt>Slice objects</dt>
770
<dd><p class="first" id="index-69">Slice objects are used to represent slices when <em>extended slice syntax</em> is used.
771
This is a slice using two colons, or multiple slices or ellipses separated by
772
commas, e.g., <code class="docutils literal"><span class="pre">a[i:j:step]</span></code>, <code class="docutils literal"><span class="pre">a[i:j,</span> <span class="pre">k:l]</span></code>, or <code class="docutils literal"><span class="pre">a[...,</span> <span class="pre">i:j]</span></code>. They are
773
also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-func docutils literal"><span class="pre">slice()</span></code></a> function.</p>
774
<p id="index-70">Special read-only attributes: <code class="xref py py-attr docutils literal"><span class="pre">start</span></code> is the lower bound;
775
<code class="xref py py-attr docutils literal"><span class="pre">stop</span></code> is the upper bound; <code class="xref py py-attr docutils literal"><span class="pre">step</span></code> is the step
776
value; each is <code class="docutils literal"><span class="pre">None</span></code> if omitted. These attributes can have any type.</p>
777
<p>Slice objects support one method:</p>
778
<dl class="last method">
779
<dt id="slice.indices">
780
<code class="descclassname">slice.</code><code class="descname">indices</code><span class="sig-paren">(</span><em>self</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#slice.indices" title="Permalink to this definition">¶</a></dt>
781
<dd><p>This method takes a single integer argument <em>length</em> and computes information
782
about the extended slice that the slice object would describe if applied to a
783
sequence of <em>length</em> items. It returns a tuple of three integers; respectively
784
these are the <em>start</em> and <em>stop</em> indices and the <em>step</em> or stride length of the
785
slice. Missing or out-of-bounds indices are handled in a manner consistent with
787
<div class="versionadded">
788
<p><span class="versionmodified">New in version 2.3.</span></p>
793
<dt>Static method objects</dt>
794
<dd>Static method objects provide a way of defeating the transformation of function
795
objects to method objects described above. A static method object is a wrapper
796
around any other object, usually a user-defined method object. When a static
797
method object is retrieved from a class or a class instance, the object actually
798
returned is the wrapped object, which is not subject to any further
799
transformation. Static method objects are not themselves callable, although the
800
objects they wrap usually are. Static method objects are created by the built-in
801
<a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></code></a> constructor.</dd>
802
<dt>Class method objects</dt>
803
<dd>A class method object, like a static method object, is a wrapper around another
804
object that alters the way in which that object is retrieved from classes and
805
class instances. The behaviour of class method objects upon such retrieval is
806
described above, under “User-defined methods”. Class method objects are created
807
by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal"><span class="pre">classmethod()</span></code></a> constructor.</dd>
812
<div class="section" id="new-style-and-classic-classes">
813
<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>
814
<p>Classes and instances come in two flavors: old-style (or classic) and new-style.</p>
815
<p>Up to Python 2.1 the concept of <code class="docutils literal"><span class="pre">class</span></code> was unrelated to the concept of
816
<code class="docutils literal"><span class="pre">type</span></code>, and old-style classes were the only flavor available. For an
817
old-style class, the statement <code class="docutils literal"><span class="pre">x.__class__</span></code> provides the class of <em>x</em>, but
818
<code class="docutils literal"><span class="pre">type(x)</span></code> is always <code class="docutils literal"><span class="pre"><type</span> <span class="pre">'instance'></span></code>. This reflects the fact that all
819
old-style instances, independent of their class, are implemented with a single
820
built-in type, called <code class="docutils literal"><span class="pre">instance</span></code>.</p>
821
<p>New-style classes were introduced in Python 2.2 to unify the concepts of
822
<code class="docutils literal"><span class="pre">class</span></code> and <code class="docutils literal"><span class="pre">type</span></code>. A new-style class is simply a user-defined type,
823
no more, no less. If <em>x</em> is an instance of a new-style class, then <code class="docutils literal"><span class="pre">type(x)</span></code>
824
is typically the same as <code class="docutils literal"><span class="pre">x.__class__</span></code> (although this is not guaranteed – a
825
new-style class instance is permitted to override the value returned for
826
<code class="docutils literal"><span class="pre">x.__class__</span></code>).</p>
827
<p>The major motivation for introducing new-style classes is to provide a unified
828
object model with a full meta-model. It also has a number of practical
829
benefits, like the ability to subclass most built-in types, or the introduction
830
of “descriptors”, which enable computed properties.</p>
831
<p>For compatibility reasons, classes are still old-style by default. New-style
832
classes are created by specifying another new-style class (i.e. a type) as a
833
parent class, or the “top-level type” <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a> if no other parent is
834
needed. The behaviour of new-style classes differs from that of old-style
835
classes in a number of important details in addition to what <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a>
836
returns. Some of these changes are fundamental to the new object model, like
837
the way special methods are invoked. Others are “fixes” that could not be
838
implemented before for compatibility concerns, like the method resolution order
839
in case of multiple inheritance.</p>
840
<p>While this manual aims to provide comprehensive coverage of Python’s class
841
mechanics, it may still be lacking in some areas when it comes to its coverage
842
of new-style classes. Please see <a class="reference external" href="https://www.python.org/doc/newstyle/">https://www.python.org/doc/newstyle/</a> for
843
sources of additional information.</p>
844
<p id="index-71">Old-style classes are removed in Python 3, leaving only new-style classes.</p>
846
<div class="section" id="special-method-names">
847
<span id="specialnames"></span><h2>3.4. Special method names<a class="headerlink" href="#special-method-names" title="Permalink to this headline">¶</a></h2>
848
<p id="index-72">A class can implement certain operations that are invoked by special syntax
849
(such as arithmetic operations or subscripting and slicing) by defining methods
850
with special names. This is Python’s approach to <em class="dfn">operator overloading</em>,
851
allowing classes to define their own behavior with respect to language
852
operators. For instance, if a class defines a method named <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>,
853
and <code class="docutils literal"><span class="pre">x</span></code> is an instance of this class, then <code class="docutils literal"><span class="pre">x[i]</span></code> is roughly equivalent
854
to <code class="docutils literal"><span class="pre">x.__getitem__(i)</span></code> for old-style classes and <code class="docutils literal"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></code>
855
for new-style classes. Except where mentioned, attempts to execute an
856
operation raise an exception when no appropriate method is defined (typically
857
<a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a>).</p>
858
<p>When implementing a class that emulates any built-in type, it is important that
859
the emulation only be implemented to the degree that it makes sense for the
860
object being modelled. For example, some sequences may work well with retrieval
861
of individual elements, but extracting a slice may not make sense. (One example
862
of this is the <code class="xref py py-class docutils literal"><span class="pre">NodeList</span></code> interface in the W3C’s Document
864
<div class="section" id="basic-customization">
865
<span id="customization"></span><h3>3.4.1. Basic customization<a class="headerlink" href="#basic-customization" title="Permalink to this headline">¶</a></h3>
867
<dt id="object.__new__">
868
<code class="descclassname">object.</code><code class="descname">__new__</code><span class="sig-paren">(</span><em>cls</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__new__" title="Permalink to this definition">¶</a></dt>
869
<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__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> is a static
870
method (special-cased so you need not declare it as such) that takes the class
871
of which an instance was requested as its first argument. The remaining
872
arguments are those passed to the object constructor expression (the call to the
873
class). The return value of <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> should be the new object instance
874
(usually an instance of <em>cls</em>).</p>
875
<p>Typical implementations create a new instance of the class by invoking the
876
superclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> method using <code class="docutils literal"><span class="pre">super(currentclass,</span>
877
<span class="pre">cls).__new__(cls[,</span> <span class="pre">...])</span></code> with appropriate arguments and then modifying the
878
newly-created instance as necessary before returning it.</p>
879
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> returns an instance of <em>cls</em>, then the new instance’s
880
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method will be invoked like <code class="docutils literal"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></code>, where
881
<em>self</em> is the new instance and the remaining arguments are the same as were
882
passed to <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a>.</p>
883
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> does not return an instance of <em>cls</em>, then the new instance’s
884
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method will not be invoked.</p>
885
<p><a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> is intended mainly to allow subclasses of immutable types (like
886
int, str, or tuple) to customize instance creation. It is also commonly
887
overridden in custom metaclasses in order to customize class creation.</p>
891
<dt id="object.__init__">
892
<code class="descclassname">object.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__init__" title="Permalink to this definition">¶</a></dt>
893
<dd><p id="index-74">Called after the instance has been created (by <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a>), but before
894
it is returned to the caller. The arguments are those passed to the
895
class constructor expression. If a base class has an <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method,
896
the derived class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> method, if any, must explicitly call it to
897
ensure proper initialization of the base class part of the instance; for
898
example: <code class="docutils literal"><span class="pre">BaseClass.__init__(self,</span> <span class="pre">[args...])</span></code>.</p>
899
<p>Because <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> work together in constructing
900
objects (<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> to create it, and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a> to customise it),
901
no non-<code class="docutils literal"><span class="pre">None</span></code> value may be returned by <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal"><span class="pre">__init__()</span></code></a>; doing so will
902
cause a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> to be raised at runtime.</p>
906
<dt id="object.__del__">
907
<code class="descclassname">object.</code><code class="descname">__del__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__del__" title="Permalink to this definition">¶</a></dt>
908
<dd><p id="index-75">Called when the instance is about to be destroyed. This is also called a
909
destructor. If a base class has a <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method, the derived class’s
910
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method, if any, must explicitly call it to ensure proper
911
deletion of the base class part of the instance. Note that it is possible
912
(though not recommended!) for the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method to postpone destruction
913
of the instance by creating a new reference to it. It may then be called at a
914
later time when this new reference is deleted. It is not guaranteed that
915
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods are called for objects that still exist when the
916
interpreter exits.</p>
917
<div class="admonition note">
918
<p class="first admonition-title">Note</p>
919
<p class="last"><code class="docutils literal"><span class="pre">del</span> <span class="pre">x</span></code> doesn’t directly call <code class="docutils literal"><span class="pre">x.__del__()</span></code> — the former decrements
920
the reference count for <code class="docutils literal"><span class="pre">x</span></code> by one, and the latter is only called when
921
<code class="docutils literal"><span class="pre">x</span></code>‘s reference count reaches zero. Some common situations that may
922
prevent the reference count of an object from going to zero include:
923
circular references between objects (e.g., a doubly-linked list or a tree
924
data structure with parent and child pointers); a reference to the object
925
on the stack frame of a function that caught an exception (the traceback
926
stored in <code class="docutils literal"><span class="pre">sys.exc_traceback</span></code> keeps the stack frame alive); or a
927
reference to the object on the stack frame that raised an unhandled
928
exception in interactive mode (the traceback stored in
929
<code class="docutils literal"><span class="pre">sys.last_traceback</span></code> keeps the stack frame alive). The first situation
930
can only be remedied by explicitly breaking the cycles; the latter two
931
situations can be resolved by storing <code class="docutils literal"><span class="pre">None</span></code> in <code class="docutils literal"><span class="pre">sys.exc_traceback</span></code> or
932
<code class="docutils literal"><span class="pre">sys.last_traceback</span></code>. Circular references which are garbage are
933
detected when the option cycle detector is enabled (it’s on by default),
934
but can only be cleaned up if there are no Python-level <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a>
935
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."><code class="xref py py-mod docutils literal"><span class="pre">gc</span></code></a> module for
936
more information about how <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods are handled by the
937
cycle detector, particularly the description of the <code class="docutils literal"><span class="pre">garbage</span></code> value.</p>
939
<div class="admonition warning">
940
<p class="first admonition-title">Warning</p>
941
<p class="last">Due to the precarious circumstances under which <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods are
942
invoked, exceptions that occur during their execution are ignored, and a warning
943
is printed to <code class="docutils literal"><span class="pre">sys.stderr</span></code> instead. Also, when <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> is invoked in
944
response to a module being deleted (e.g., when execution of the program is
945
done), other globals referenced by the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method may already have
946
been deleted or in the process of being torn down (e.g. the import
947
machinery shutting down). For this reason, <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> methods
948
should do the absolute
949
minimum needed to maintain external invariants. Starting with version 1.5,
950
Python guarantees that globals whose name begins with a single underscore are
951
deleted from their module before other globals are deleted; if no other
952
references to such globals exist, this may help in assuring that imported
953
modules are still available at the time when the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal"><span class="pre">__del__()</span></code></a> method is
956
<p>See also the <a class="reference internal" href="../using/cmdline.html#cmdoption-R"><code class="xref std std-option docutils literal"><span class="pre">-R</span></code></a> command-line option.</p>
960
<dt id="object.__repr__">
961
<code class="descclassname">object.</code><code class="descname">__repr__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__repr__" title="Permalink to this definition">¶</a></dt>
962
<dd><p id="index-76">Called by the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal"><span class="pre">repr()</span></code></a> built-in function and by string conversions (reverse
963
quotes) to compute the “official” string representation of an object. If at all
964
possible, this should look like a valid Python expression that could be used to
965
recreate an object with the same value (given an appropriate environment). If
966
this is not possible, a string of the form <code class="docutils literal"><span class="pre"><...some</span> <span class="pre">useful</span> <span class="pre">description...></span></code>
967
should be returned. The return value must be a string object. If a class
968
defines <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a> but not <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal"><span class="pre">__str__()</span></code></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a> is also
969
used when an “informal” string representation of instances of that class is
971
<p id="index-77">This is typically used for debugging, so it is important that the representation
972
is information-rich and unambiguous.</p>
976
<dt id="object.__str__">
977
<code class="descclassname">object.</code><code class="descname">__str__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__str__" title="Permalink to this definition">¶</a></dt>
978
<dd><p id="index-78">Called by the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal"><span class="pre">str()</span></code></a> built-in function and by the <a class="reference internal" href="simple_stmts.html#print"><code class="xref std std-keyword docutils literal"><span class="pre">print</span></code></a>
979
statement to compute the “informal” string representation of an object. This
980
differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a> in that it does not have to be a valid Python
981
expression: a more convenient or concise representation may be used instead.
982
The return value must be a string object.</p>
986
<dt id="object.__lt__">
987
<code class="descclassname">object.</code><code class="descname">__lt__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lt__" title="Permalink to this definition">¶</a></dt>
988
<dt id="object.__le__">
989
<code class="descclassname">object.</code><code class="descname">__le__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__le__" title="Permalink to this definition">¶</a></dt>
990
<dt id="object.__eq__">
991
<code class="descclassname">object.</code><code class="descname">__eq__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__eq__" title="Permalink to this definition">¶</a></dt>
992
<dt id="object.__ne__">
993
<code class="descclassname">object.</code><code class="descname">__ne__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ne__" title="Permalink to this definition">¶</a></dt>
994
<dt id="object.__gt__">
995
<code class="descclassname">object.</code><code class="descname">__gt__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__gt__" title="Permalink to this definition">¶</a></dt>
996
<dt id="object.__ge__">
997
<code class="descclassname">object.</code><code class="descname">__ge__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ge__" title="Permalink to this definition">¶</a></dt>
998
<dd><div class="versionadded">
999
<p><span class="versionmodified">New in version 2.1.</span></p>
1001
<p id="index-79">These are the so-called “rich comparison” methods, and are called for comparison
1002
operators in preference to <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> below. The correspondence between
1003
operator symbols and method names is as follows: <code class="docutils literal"><span class="pre">x<y</span></code> calls <code class="docutils literal"><span class="pre">x.__lt__(y)</span></code>,
1004
<code class="docutils literal"><span class="pre">x<=y</span></code> calls <code class="docutils literal"><span class="pre">x.__le__(y)</span></code>, <code class="docutils literal"><span class="pre">x==y</span></code> calls <code class="docutils literal"><span class="pre">x.__eq__(y)</span></code>, <code class="docutils literal"><span class="pre">x!=y</span></code> and
1005
<code class="docutils literal"><span class="pre">x<>y</span></code> call <code class="docutils literal"><span class="pre">x.__ne__(y)</span></code>, <code class="docutils literal"><span class="pre">x>y</span></code> calls <code class="docutils literal"><span class="pre">x.__gt__(y)</span></code>, and <code class="docutils literal"><span class="pre">x>=y</span></code> calls
1006
<code class="docutils literal"><span class="pre">x.__ge__(y)</span></code>.</p>
1007
<p>A rich comparison method may return the singleton <code class="docutils literal"><span class="pre">NotImplemented</span></code> if it does
1008
not implement the operation for a given pair of arguments. By convention,
1009
<code class="docutils literal"><span class="pre">False</span></code> and <code class="docutils literal"><span class="pre">True</span></code> are returned for a successful comparison. However, these
1010
methods can return any value, so if the comparison operator is used in a Boolean
1011
context (e.g., in the condition of an <code class="docutils literal"><span class="pre">if</span></code> statement), Python will call
1012
<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-func docutils literal"><span class="pre">bool()</span></code></a> on the value to determine if the result is true or false.</p>
1013
<p>There are no implied relationships among the comparison operators. The truth
1014
of <code class="docutils literal"><span class="pre">x==y</span></code> does not imply that <code class="docutils literal"><span class="pre">x!=y</span></code> is false. Accordingly, when
1015
defining <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a>, one should also define <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></code></a> so that the
1016
operators will behave as expected. See the paragraph on <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> for
1017
some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects which support
1018
custom comparison operations and are usable as dictionary keys.</p>
1019
<p>There are no swapped-argument versions of these methods (to be used when the
1020
left argument does not support the operation but the right argument does);
1021
rather, <a class="reference internal" href="#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal"><span class="pre">__lt__()</span></code></a> and <a class="reference internal" href="#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal"><span class="pre">__gt__()</span></code></a> are each other’s reflection,
1022
<a class="reference internal" href="#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal"><span class="pre">__le__()</span></code></a> and <a class="reference internal" href="#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal"><span class="pre">__ge__()</span></code></a> are each other’s reflection, and
1023
<a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></code></a> are their own reflection.</p>
1024
<p>Arguments to rich comparison methods are never coerced.</p>
1025
<p>To automatically generate ordering operations from a single root operation,
1026
see <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal"><span class="pre">functools.total_ordering()</span></code></a>.</p>
1030
<dt id="object.__cmp__">
1031
<code class="descclassname">object.</code><code class="descname">__cmp__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__cmp__" title="Permalink to this definition">¶</a></dt>
1032
<dd><p id="index-80">Called by comparison operations if rich comparison (see above) is not
1033
defined. Should return a negative integer if <code class="docutils literal"><span class="pre">self</span> <span class="pre"><</span> <span class="pre">other</span></code>, zero if
1034
<code class="docutils literal"><span class="pre">self</span> <span class="pre">==</span> <span class="pre">other</span></code>, a positive integer if <code class="docutils literal"><span class="pre">self</span> <span class="pre">></span> <span class="pre">other</span></code>. If no
1035
<a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a>, <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> or <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></code></a> operation is defined, class
1036
instances are compared by object identity (“address”). See also the
1037
description of <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> for some important notes on creating
1038
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects which support custom comparison operations and are
1039
usable as dictionary keys. (Note: the restriction that exceptions are not
1040
propagated by <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> has been removed since Python 1.5.)</p>
1044
<dt id="object.__rcmp__">
1045
<code class="descclassname">object.</code><code class="descname">__rcmp__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rcmp__" title="Permalink to this definition">¶</a></dt>
1046
<dd><div class="versionchanged">
1047
<p><span class="versionmodified">Changed in version 2.1: </span>No longer supported.</p>
1052
<dt id="object.__hash__">
1053
<code class="descclassname">object.</code><code class="descname">__hash__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hash__" title="Permalink to this definition">¶</a></dt>
1054
<dd><p id="index-81">Called by built-in function <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal"><span class="pre">hash()</span></code></a> and for operations on members of
1055
hashed collections including <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal"><span class="pre">set</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal"><span class="pre">frozenset</span></code></a>, and
1056
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal"><span class="pre">dict</span></code></a>. <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> should return an integer. The only required
1057
property is that objects which compare equal have the same hash value; it is
1058
advised to somehow mix together (e.g. using exclusive or) the hash values for
1059
the components of the object that also play a part in comparison of objects.</p>
1060
<p>If a class does not define a <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> method it
1061
should not define a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> operation either; if it defines
1062
<a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> but not <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a>, its instances
1063
will not be usable in hashed collections. If a class defines mutable objects
1064
and implements a <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> method, it should not
1065
implement <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a>, since hashable collection implementations require
1066
that an object’s hash value is immutable (if the object’s hash value changes,
1067
it will be in the wrong hash bucket).</p>
1068
<p>User-defined classes have <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> and <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> methods
1069
by default; with them, all objects compare unequal (except with themselves)
1070
and <code class="docutils literal"><span class="pre">x.__hash__()</span></code> returns a result derived from <code class="docutils literal"><span class="pre">id(x)</span></code>.</p>
1071
<p>Classes which inherit a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> method from a parent class but
1072
change the meaning of <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> such that the hash
1073
value returned is no longer appropriate (e.g. by switching to a value-based
1074
concept of equality instead of the default identity based equality) can
1075
explicitly flag themselves as being unhashable by setting <code class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code>
1076
in the class definition. Doing so means that not only will instances of the
1077
class raise an appropriate <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> when a program attempts to
1078
retrieve their hash value, but they will also be correctly identified as
1079
unhashable when checking <code class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable)</span></code> (unlike
1080
classes which define their own <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> to explicitly raise
1081
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a>).</p>
1082
<div class="versionchanged">
1083
<p><span class="versionmodified">Changed in version 2.5: </span><a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> may now also return a long integer object; the 32-bit
1084
integer is then derived from the hash of that object.</p>
1086
<div class="versionchanged">
1087
<p><span class="versionmodified">Changed in version 2.6: </span><a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-attr docutils literal"><span class="pre">__hash__</span></code></a> may now be set to <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a> to explicitly flag
1088
instances of a class as unhashable.</p>
1093
<dt id="object.__nonzero__">
1094
<code class="descclassname">object.</code><code class="descname">__nonzero__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__nonzero__" title="Permalink to this definition">¶</a></dt>
1095
<dd><p id="index-82">Called to implement truth value testing and the built-in operation <code class="docutils literal"><span class="pre">bool()</span></code>;
1096
should return <code class="docutils literal"><span class="pre">False</span></code> or <code class="docutils literal"><span class="pre">True</span></code>, or their integer equivalents <code class="docutils literal"><span class="pre">0</span></code> or
1097
<code class="docutils literal"><span class="pre">1</span></code>. When this method is not defined, <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> is called, if it is
1098
defined, and the object is considered true if its result is nonzero.
1099
If a class defines neither <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> nor <a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal"><span class="pre">__nonzero__()</span></code></a>, all its
1100
instances are considered true.</p>
1104
<dt id="object.__unicode__">
1105
<code class="descclassname">object.</code><code class="descname">__unicode__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__unicode__" title="Permalink to this definition">¶</a></dt>
1106
<dd><p id="index-83">Called to implement <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal"><span class="pre">unicode()</span></code></a> built-in; should return a Unicode object.
1107
When this method is not defined, string conversion is attempted, and the result
1108
of string conversion is converted to Unicode using the system default encoding.</p>
1112
<div class="section" id="customizing-attribute-access">
1113
<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>
1114
<p>The following methods can be defined to customize the meaning of attribute
1115
access (use of, assignment to, or deletion of <code class="docutils literal"><span class="pre">x.name</span></code>) for class instances.</p>
1117
<dt id="object.__getattr__">
1118
<code class="descclassname">object.</code><code class="descname">__getattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattr__" title="Permalink to this definition">¶</a></dt>
1119
<dd><p>Called when an attribute lookup has not found the attribute in the usual places
1120
(i.e. it is not an instance attribute nor is it found in the class tree for
1121
<code class="docutils literal"><span class="pre">self</span></code>). <code class="docutils literal"><span class="pre">name</span></code> is the attribute name. This method should return the
1122
(computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> exception.</p>
1123
<p id="index-84">Note that if the attribute is found through the normal mechanism,
1124
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> is not called. (This is an intentional asymmetry between
1125
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> and <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a>.) This is done both for efficiency
1126
reasons and because otherwise <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a> would have no way to access
1127
other attributes of the instance. Note that at least for instance variables,
1128
you can fake total control by not inserting any values in the instance attribute
1129
dictionary (but instead inserting them in another object). See the
1130
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> method below for a way to actually get total control in
1131
new-style classes.</p>
1135
<dt id="object.__setattr__">
1136
<code class="descclassname">object.</code><code class="descname">__setattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setattr__" title="Permalink to this definition">¶</a></dt>
1137
<dd><p>Called when an attribute assignment is attempted. This is called instead of the
1138
normal mechanism (i.e. store the value in the instance dictionary). <em>name</em> is
1139
the attribute name, <em>value</em> is the value to be assigned to it.</p>
1140
<p id="index-85">If <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a> wants to assign to an instance attribute, it should not
1141
simply execute <code class="docutils literal"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></code> — this would cause a recursive call to
1142
itself. Instead, it should insert the value in the dictionary of instance
1143
attributes, e.g., <code class="docutils literal"><span class="pre">self.__dict__[name]</span> <span class="pre">=</span> <span class="pre">value</span></code>. For new-style classes,
1144
rather than accessing the instance dictionary, it should call the base class
1145
method with the same name, for example, <code class="docutils literal"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span>
1146
<span class="pre">value)</span></code>.</p>
1150
<dt id="object.__delattr__">
1151
<code class="descclassname">object.</code><code class="descname">__delattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delattr__" title="Permalink to this definition">¶</a></dt>
1152
<dd><p>Like <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></code></a> but for attribute deletion instead of assignment. This
1153
should only be implemented if <code class="docutils literal"><span class="pre">del</span> <span class="pre">obj.name</span></code> is meaningful for the object.</p>
1156
<div class="section" id="more-attribute-access-for-new-style-classes">
1157
<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>
1158
<p>The following methods only apply to new-style classes.</p>
1160
<dt id="object.__getattribute__">
1161
<code class="descclassname">object.</code><code class="descname">__getattribute__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattribute__" title="Permalink to this definition">¶</a></dt>
1162
<dd><p>Called unconditionally to implement attribute accesses for instances of the
1163
class. If the class also defines <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></code></a>, the latter will not be
1164
called unless <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> either calls it explicitly or raises an
1165
<a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a>. This method should return the (computed) attribute value
1166
or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> exception. In order to avoid infinite
1167
recursion in this method, its implementation should always call the base class
1168
method with the same name to access any attributes it needs, for example,
1169
<code class="docutils literal"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></code>.</p>
1170
<div class="admonition note">
1171
<p class="first admonition-title">Note</p>
1172
<p class="last">This method may still be bypassed when looking up special methods as the
1173
result of implicit invocation via language syntax or built-in functions.
1174
See <a class="reference internal" href="#new-style-special-lookup"><span>Special method lookup for new-style classes</span></a>.</p>
1179
<div class="section" id="implementing-descriptors">
1180
<span id="descriptors"></span><h4>3.4.2.2. Implementing Descriptors<a class="headerlink" href="#implementing-descriptors" title="Permalink to this headline">¶</a></h4>
1181
<p>The following methods only apply when an instance of the class containing the
1182
method (a so-called <em>descriptor</em> class) appears in an <em>owner</em> class (the
1183
descriptor must be in either the owner’s class dictionary or in the class
1184
dictionary for one of its parents). In the examples below, “the attribute”
1185
refers to the attribute whose name is the key of the property in the owner
1186
class’ <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal"><span class="pre">__dict__</span></code></a>.</p>
1188
<dt id="object.__get__">
1189
<code class="descclassname">object.</code><code class="descname">__get__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em>, <em>owner</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__get__" title="Permalink to this definition">¶</a></dt>
1190
<dd><p>Called to get the attribute of the owner class (class attribute access) or of an
1191
instance of that class (instance attribute access). <em>owner</em> is always the owner
1192
class, while <em>instance</em> is the instance that the attribute was accessed through,
1193
or <code class="docutils literal"><span class="pre">None</span></code> when the attribute is accessed through the <em>owner</em>. This method
1194
should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a>
1199
<dt id="object.__set__">
1200
<code class="descclassname">object.</code><code class="descname">__set__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set__" title="Permalink to this definition">¶</a></dt>
1201
<dd><p>Called to set the attribute on an instance <em>instance</em> of the owner class to a
1202
new value, <em>value</em>.</p>
1206
<dt id="object.__delete__">
1207
<code class="descclassname">object.</code><code class="descname">__delete__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delete__" title="Permalink to this definition">¶</a></dt>
1208
<dd><p>Called to delete the attribute on an instance <em>instance</em> of the owner class.</p>
1212
<div class="section" id="invoking-descriptors">
1213
<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>
1214
<p>In general, a descriptor is an object attribute with “binding behavior”, one
1215
whose attribute access has been overridden by methods in the descriptor
1216
protocol: <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a>, and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></code></a>. If any of
1217
those methods are defined for an object, it is said to be a descriptor.</p>
1218
<p>The default behavior for attribute access is to get, set, or delete the
1219
attribute from an object’s dictionary. For instance, <code class="docutils literal"><span class="pre">a.x</span></code> has a lookup chain
1220
starting with <code class="docutils literal"><span class="pre">a.__dict__['x']</span></code>, then <code class="docutils literal"><span class="pre">type(a).__dict__['x']</span></code>, and
1221
continuing through the base classes of <code class="docutils literal"><span class="pre">type(a)</span></code> excluding metaclasses.</p>
1222
<p>However, if the looked-up value is an object defining one of the descriptor
1223
methods, then Python may override the default behavior and invoke the descriptor
1224
method instead. Where this occurs in the precedence chain depends on which
1225
descriptor methods were defined and how they were called. Note that descriptors
1226
are only invoked for new style objects or classes (ones that subclass
1227
<a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal"><span class="pre">object()</span></code></a> or <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal"><span class="pre">type()</span></code></a>).</p>
1228
<p>The starting point for descriptor invocation is a binding, <code class="docutils literal"><span class="pre">a.x</span></code>. How the
1229
arguments are assembled depends on <code class="docutils literal"><span class="pre">a</span></code>:</p>
1230
<dl class="docutils">
1231
<dt>Direct Call</dt>
1232
<dd>The simplest and least common call is when user code directly invokes a
1233
descriptor method: <code class="docutils literal"><span class="pre">x.__get__(a)</span></code>.</dd>
1234
<dt>Instance Binding</dt>
1235
<dd>If binding to a new-style object instance, <code class="docutils literal"><span class="pre">a.x</span></code> is transformed into the call:
1236
<code class="docutils literal"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></code>.</dd>
1237
<dt>Class Binding</dt>
1238
<dd>If binding to a new-style class, <code class="docutils literal"><span class="pre">A.x</span></code> is transformed into the call:
1239
<code class="docutils literal"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></code>.</dd>
1240
<dt>Super Binding</dt>
1241
<dd>If <code class="docutils literal"><span class="pre">a</span></code> is an instance of <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-class docutils literal"><span class="pre">super</span></code></a>, then the binding <code class="docutils literal"><span class="pre">super(B,</span>
1242
<span class="pre">obj).m()</span></code> searches <code class="docutils literal"><span class="pre">obj.__class__.__mro__</span></code> for the base class <code class="docutils literal"><span class="pre">A</span></code>
1243
immediately preceding <code class="docutils literal"><span class="pre">B</span></code> and then invokes the descriptor with the call:
1244
<code class="docutils literal"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">obj.__class__)</span></code>.</dd>
1246
<p>For instance bindings, the precedence of descriptor invocation depends on the
1247
which descriptor methods are defined. A descriptor can define any combination
1248
of <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></code></a>. If it does not
1249
define <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a>, then accessing the attribute will return the descriptor
1250
object itself unless there is a value in the object’s instance dictionary. If
1251
the descriptor defines <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a> and/or <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></code></a>, it is a data
1252
descriptor; if it defines neither, it is a non-data descriptor. Normally, data
1253
descriptors define both <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a> and <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a>, while non-data
1254
descriptors have just the <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a> method. Data descriptors with
1255
<a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal"><span class="pre">__get__()</span></code></a> defined always override a redefinition in an
1256
instance dictionary. In contrast, non-data descriptors can be overridden by
1258
<p>Python methods (including <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></code></a> and <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal"><span class="pre">classmethod()</span></code></a>) are
1259
implemented as non-data descriptors. Accordingly, instances can redefine and
1260
override methods. This allows individual instances to acquire behaviors that
1261
differ from other instances of the same class.</p>
1262
<p>The <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal"><span class="pre">property()</span></code></a> function is implemented as a data descriptor. Accordingly,
1263
instances cannot override the behavior of a property.</p>
1265
<div class="section" id="slots">
1266
<span id="id2"></span><h4>3.4.2.4. __slots__<a class="headerlink" href="#slots" title="Permalink to this headline">¶</a></h4>
1267
<p>By default, instances of both old and new-style classes have a dictionary for
1268
attribute storage. This wastes space for objects having very few instance
1269
variables. The space consumption can become acute when creating large numbers
1271
<p>The default can be overridden by defining <em>__slots__</em> in a new-style class
1272
definition. The <em>__slots__</em> declaration takes a sequence of instance variables
1273
and reserves just enough space in each instance to hold a value for each
1274
variable. Space is saved because <em>__dict__</em> is not created for each instance.</p>
1277
<code class="descname">__slots__</code><a class="headerlink" href="#__slots__" title="Permalink to this definition">¶</a></dt>
1278
<dd><p>This class variable can be assigned a string, iterable, or sequence of strings
1279
with variable names used by instances. If defined in a new-style class,
1280
<em>__slots__</em> reserves space for the declared variables and prevents the automatic
1281
creation of <em>__dict__</em> and <em>__weakref__</em> for each instance.</p>
1282
<div class="versionadded">
1283
<p><span class="versionmodified">New in version 2.2.</span></p>
1287
<p>Notes on using <em>__slots__</em></p>
1289
<li><p class="first">When inheriting from a class without <em>__slots__</em>, the <em>__dict__</em> attribute of
1290
that class will always be accessible, so a <em>__slots__</em> definition in the
1291
subclass is meaningless.</p>
1293
<li><p class="first">Without a <em>__dict__</em> variable, instances cannot be assigned new variables not
1294
listed in the <em>__slots__</em> definition. Attempts to assign to an unlisted
1295
variable name raises <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a>. If dynamic assignment of new
1296
variables is desired, then add <code class="docutils literal"><span class="pre">'__dict__'</span></code> to the sequence of strings in the
1297
<em>__slots__</em> declaration.</p>
1298
<div class="versionchanged">
1299
<p><span class="versionmodified">Changed in version 2.3: </span>Previously, adding <code class="docutils literal"><span class="pre">'__dict__'</span></code> to the <em>__slots__</em> declaration would not
1300
enable the assignment of new attributes not specifically listed in the sequence
1301
of instance variable names.</p>
1304
<li><p class="first">Without a <em>__weakref__</em> variable for each instance, classes defining
1305
<em>__slots__</em> do not support weak references to its instances. If weak reference
1306
support is needed, then add <code class="docutils literal"><span class="pre">'__weakref__'</span></code> to the sequence of strings in the
1307
<em>__slots__</em> declaration.</p>
1308
<div class="versionchanged">
1309
<p><span class="versionmodified">Changed in version 2.3: </span>Previously, adding <code class="docutils literal"><span class="pre">'__weakref__'</span></code> to the <em>__slots__</em> declaration would not
1310
enable support for weak references.</p>
1313
<li><p class="first"><em>__slots__</em> are implemented at the class level by creating descriptors
1314
(<a class="reference internal" href="#descriptors"><span>Implementing Descriptors</span></a>) for each variable name. As a result, class attributes
1315
cannot be used to set default values for instance variables defined by
1316
<em>__slots__</em>; otherwise, the class attribute would overwrite the descriptor
1319
<li><p class="first">The action of a <em>__slots__</em> declaration is limited to the class where it is
1320
defined. As a result, subclasses will have a <em>__dict__</em> unless they also define
1321
<em>__slots__</em> (which must only contain names of any <em>additional</em> slots).</p>
1323
<li><p class="first">If a class defines a slot also defined in a base class, the instance variable
1324
defined by the base class slot is inaccessible (except by retrieving its
1325
descriptor directly from the base class). This renders the meaning of the
1326
program undefined. In the future, a check may be added to prevent this.</p>
1328
<li><p class="first">Nonempty <em>__slots__</em> does not work for classes derived from “variable-length”
1329
built-in types such as <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-class docutils literal"><span class="pre">long</span></code></a>, <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal"><span class="pre">str</span></code></a> and <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal"><span class="pre">tuple</span></code></a>.</p>
1331
<li><p class="first">Any non-string iterable may be assigned to <em>__slots__</em>. Mappings may also be
1332
used; however, in the future, special meaning may be assigned to the values
1333
corresponding to each key.</p>
1335
<li><p class="first"><em>__class__</em> assignment works only if both classes have the same <em>__slots__</em>.</p>
1336
<div class="versionchanged">
1337
<p><span class="versionmodified">Changed in version 2.6: </span>Previously, <em>__class__</em> assignment raised an error if either new or old class
1338
had <em>__slots__</em>.</p>
1344
<div class="section" id="customizing-class-creation">
1345
<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>
1346
<p>By default, new-style classes are constructed using <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a>. A class
1347
definition is read into a separate namespace and the value of class name is
1348
bound to the result of <code class="docutils literal"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">dict)</span></code>.</p>
1349
<p>When the class definition is read, if <em>__metaclass__</em> is defined then the
1350
callable assigned to it will be called instead of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a>. This allows
1351
classes or functions to be written which monitor or alter the class creation
1354
<li>Modifying the class dictionary prior to the class being created.</li>
1355
<li>Returning an instance of another class – essentially performing the role of a
1356
factory function.</li>
1358
<p>These steps will have to be performed in the metaclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal"><span class="pre">__new__()</span></code></a> method
1359
– <code class="xref py py-meth docutils literal"><span class="pre">type.__new__()</span></code> can then be called from this method to create a class
1360
with different properties. This example adds a new element to the class
1361
dictionary before creating the class:</p>
1362
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">metacls</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
1363
<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>
1364
<span class="nb">dict</span><span class="p">[</span><span class="s1">'foo'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'metacls was here'</span>
1365
<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>
1368
<p>You can of course also override other class methods (or add new methods); for
1369
example defining a custom <a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal"><span class="pre">__call__()</span></code></a> method in the metaclass allows custom
1370
behavior when the class is called, e.g. not always creating a new instance.</p>
1372
<dt id="__metaclass__">
1373
<code class="descname">__metaclass__</code><a class="headerlink" href="#__metaclass__" title="Permalink to this definition">¶</a></dt>
1374
<dd><p>This variable can be any callable accepting arguments for <code class="docutils literal"><span class="pre">name</span></code>, <code class="docutils literal"><span class="pre">bases</span></code>,
1375
and <code class="docutils literal"><span class="pre">dict</span></code>. Upon class creation, the callable is used instead of the built-in
1376
<a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal"><span class="pre">type()</span></code></a>.</p>
1377
<div class="versionadded">
1378
<p><span class="versionmodified">New in version 2.2.</span></p>
1382
<p>The appropriate metaclass is determined by the following precedence rules:</p>
1384
<li>If <code class="docutils literal"><span class="pre">dict['__metaclass__']</span></code> exists, it is used.</li>
1385
<li>Otherwise, if there is at least one base class, its metaclass is used (this
1386
looks for a <em>__class__</em> attribute first and if not found, uses its type).</li>
1387
<li>Otherwise, if a global variable named __metaclass__ exists, it is used.</li>
1388
<li>Otherwise, the old-style, classic metaclass (types.ClassType) is used.</li>
1390
<p>The potential uses for metaclasses are boundless. Some ideas that have been
1391
explored including logging, interface checking, automatic delegation, automatic
1392
property creation, proxies, frameworks, and automatic resource
1393
locking/synchronization.</p>
1395
<div class="section" id="customizing-instance-and-subclass-checks">
1396
<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>
1397
<div class="versionadded">
1398
<p><span class="versionmodified">New in version 2.6.</span></p>
1400
<p>The following methods are used to override the default behavior of the
1401
<a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal"><span class="pre">issubclass()</span></code></a> built-in functions.</p>
1402
<p>In particular, the metaclass <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal"><span class="pre">abc.ABCMeta</span></code></a> implements these methods in
1403
order to allow the addition of Abstract Base Classes (ABCs) as “virtual base
1404
classes” to any class or type (including built-in types), including other
1407
<dt id="class.__instancecheck__">
1408
<code class="descclassname">class.</code><code class="descname">__instancecheck__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__instancecheck__" title="Permalink to this definition">¶</a></dt>
1409
<dd><p>Return true if <em>instance</em> should be considered a (direct or indirect)
1410
instance of <em>class</em>. If defined, called to implement <code class="docutils literal"><span class="pre">isinstance(instance,</span>
1411
<span class="pre">class)</span></code>.</p>
1415
<dt id="class.__subclasscheck__">
1416
<code class="descclassname">class.</code><code class="descname">__subclasscheck__</code><span class="sig-paren">(</span><em>self</em>, <em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__subclasscheck__" title="Permalink to this definition">¶</a></dt>
1417
<dd><p>Return true if <em>subclass</em> should be considered a (direct or indirect)
1418
subclass of <em>class</em>. If defined, called to implement <code class="docutils literal"><span class="pre">issubclass(subclass,</span>
1419
<span class="pre">class)</span></code>.</p>
1422
<p>Note that these methods are looked up on the type (metaclass) of a class. They
1423
cannot be defined as class methods in the actual class. This is consistent with
1424
the lookup of special methods that are called on instances, only in this
1425
case the instance is itself a class.</p>
1426
<div class="admonition seealso">
1427
<p class="first admonition-title">See also</p>
1428
<dl class="last docutils">
1429
<dt><span class="target" id="index-86"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt>
1430
<dd>Includes the specification for customizing <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal"><span class="pre">isinstance()</span></code></a> and
1431
<a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal"><span class="pre">issubclass()</span></code></a> behavior through <a class="reference internal" href="#class.__instancecheck__" title="class.__instancecheck__"><code class="xref py py-meth docutils literal"><span class="pre">__instancecheck__()</span></code></a> and
1432
<a class="reference internal" href="#class.__subclasscheck__" title="class.__subclasscheck__"><code class="xref py py-meth docutils literal"><span class="pre">__subclasscheck__()</span></code></a>, with motivation for this functionality
1433
in the context of adding Abstract Base Classes (see the <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal"><span class="pre">abc</span></code></a>
1434
module) to the language.</dd>
1438
<div class="section" id="emulating-callable-objects">
1439
<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>
1441
<dt id="object.__call__">
1442
<code class="descclassname">object.</code><code class="descname">__call__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>args...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__call__" title="Permalink to this definition">¶</a></dt>
1443
<dd><p id="index-87">Called when the instance is “called” as a function; if this method is defined,
1444
<code class="docutils literal"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> is a shorthand for <code class="docutils literal"><span class="pre">x.__call__(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code>.</p>
1448
<div class="section" id="emulating-container-types">
1449
<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>
1450
<p>The following methods can be defined to implement container objects. Containers
1451
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
1452
but can represent other containers as well. The first set of methods is used
1453
either to emulate a sequence or to emulate a mapping; the difference is that for
1454
a sequence, the allowable keys should be the integers <em>k</em> for which <code class="docutils literal"><span class="pre">0</span> <span class="pre"><=</span> <span class="pre">k</span> <span class="pre"><</span>
1455
<span class="pre">N</span></code> where <em>N</em> is the length of the sequence, or slice objects, which define a
1456
range of items. (For backwards compatibility, the method <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></code></a>
1457
(see below) can also be defined to handle simple, but not extended slices.) It
1458
is also recommended that mappings provide the methods <code class="xref py py-meth docutils literal"><span class="pre">keys()</span></code>,
1459
<code class="xref py py-meth docutils literal"><span class="pre">values()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">items()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">has_key()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">get()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">clear()</span></code>,
1460
<code class="xref py py-meth docutils literal"><span class="pre">setdefault()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">itervalues()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">iteritems()</span></code>,
1461
<code class="xref py py-meth docutils literal"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">popitem()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">copy()</span></code>, and <code class="xref py py-meth docutils literal"><span class="pre">update()</span></code> behaving similar
1462
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."><code class="xref py py-mod docutils literal"><span class="pre">UserDict</span></code></a> module
1463
provides a <code class="xref py py-class docutils literal"><span class="pre">DictMixin</span></code> class to help create those methods from a base set
1464
of <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></code></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></code></a>, and
1465
<code class="xref py py-meth docutils literal"><span class="pre">keys()</span></code>. Mutable sequences should provide methods <code class="xref py py-meth docutils literal"><span class="pre">append()</span></code>,
1466
<code class="xref py py-meth docutils literal"><span class="pre">count()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">index()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">extend()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">insert()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">pop()</span></code>,
1467
<code class="xref py py-meth docutils literal"><span class="pre">remove()</span></code>, <code class="xref py py-meth docutils literal"><span class="pre">reverse()</span></code> and <code class="xref py py-meth docutils literal"><span class="pre">sort()</span></code>, like Python standard list
1468
objects. Finally, sequence types should implement addition (meaning
1469
concatenation) and multiplication (meaning repetition) by defining the methods
1470
<a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a>, <a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal"><span class="pre">__radd__()</span></code></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></code></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal"><span class="pre">__mul__()</span></code></a>,
1471
<a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal"><span class="pre">__rmul__()</span></code></a> and <a class="reference internal" href="#object.__imul__" title="object.__imul__"><code class="xref py py-meth docutils literal"><span class="pre">__imul__()</span></code></a> described below; they should not define
1472
<a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></code></a> or other numerical operators. It is recommended that both
1473
mappings and sequences implement the <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></code></a> method to allow
1474
efficient use of the <code class="docutils literal"><span class="pre">in</span></code> operator; for mappings, <code class="docutils literal"><span class="pre">in</span></code> should be equivalent
1475
of <code class="xref py py-meth docutils literal"><span class="pre">has_key()</span></code>; for sequences, it should search through the values. It is
1476
further recommended that both mappings and sequences implement the
1477
<a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a> method to allow efficient iteration through the container; for
1478
mappings, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a> should be the same as <code class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></code>; for
1479
sequences, it should iterate through the values.</p>
1481
<dt id="object.__len__">
1482
<code class="descclassname">object.</code><code class="descname">__len__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__len__" title="Permalink to this definition">¶</a></dt>
1483
<dd><p id="index-88">Called to implement the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal"><span class="pre">len()</span></code></a>. Should return the length
1484
of the object, an integer <code class="docutils literal"><span class="pre">>=</span></code> 0. Also, an object that doesn’t define a
1485
<a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal"><span class="pre">__nonzero__()</span></code></a> method and whose <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> method returns zero is
1486
considered to be false in a Boolean context.</p>
1490
<dt id="object.__getitem__">
1491
<code class="descclassname">object.</code><code class="descname">__getitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getitem__" title="Permalink to this definition">¶</a></dt>
1492
<dd><p id="index-89">Called to implement evaluation of <code class="docutils literal"><span class="pre">self[key]</span></code>. For sequence types, the
1493
accepted keys should be integers and slice objects. Note that the special
1494
interpretation of negative indexes (if the class wishes to emulate a sequence
1495
type) is up to the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method. If <em>key</em> is of an inappropriate
1496
type, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a> may be raised; if of a value outside the set of indexes
1497
for the sequence (after any special interpretation of negative values),
1498
<a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal"><span class="pre">IndexError</span></code></a> should be raised. For mapping types, if <em>key</em> is missing (not
1499
in the container), <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal"><span class="pre">KeyError</span></code></a> should be raised.</p>
1500
<div class="admonition note">
1501
<p class="first admonition-title">Note</p>
1502
<p class="last"><a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal"><span class="pre">for</span></code></a> loops expect that an <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal"><span class="pre">IndexError</span></code></a> will be raised for illegal
1503
indexes to allow proper detection of the end of the sequence.</p>
1508
<dt id="object.__missing__">
1509
<code class="descclassname">object.</code><code class="descname">__missing__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__missing__" title="Permalink to this definition">¶</a></dt>
1510
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal"><span class="pre">dict</span></code></a>.<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> to implement <code class="docutils literal"><span class="pre">self[key]</span></code> for dict subclasses
1511
when key is not in the dictionary.</p>
1515
<dt id="object.__setitem__">
1516
<code class="descclassname">object.</code><code class="descname">__setitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setitem__" title="Permalink to this definition">¶</a></dt>
1517
<dd><p>Called to implement assignment to <code class="docutils literal"><span class="pre">self[key]</span></code>. Same note as for
1518
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>. This should only be implemented for mappings if the
1519
objects support changes to the values for keys, or if new keys can be added, or
1520
for sequences if elements can be replaced. The same exceptions should be raised
1521
for improper <em>key</em> values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method.</p>
1525
<dt id="object.__delitem__">
1526
<code class="descclassname">object.</code><code class="descname">__delitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delitem__" title="Permalink to this definition">¶</a></dt>
1527
<dd><p>Called to implement deletion of <code class="docutils literal"><span class="pre">self[key]</span></code>. Same note as for
1528
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>. This should only be implemented for mappings if the
1529
objects support removal of keys, or for sequences if elements can be removed
1530
from the sequence. The same exceptions should be raised for improper <em>key</em>
1531
values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method.</p>
1535
<dt id="object.__iter__">
1536
<code class="descclassname">object.</code><code class="descname">__iter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iter__" title="Permalink to this definition">¶</a></dt>
1537
<dd><p>This method is called when an iterator is required for a container. This method
1538
should return a new iterator object that can iterate over all the objects in the
1539
container. For mappings, it should iterate over the keys of the container, and
1540
should also be made available as the method <code class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></code>.</p>
1541
<p>Iterator objects also need to implement this method; they are required to return
1542
themselves. For more information on iterator objects, see <a class="reference internal" href="../library/stdtypes.html#typeiter"><span>Iterator Types</span></a>.</p>
1546
<dt id="object.__reversed__">
1547
<code class="descclassname">object.</code><code class="descname">__reversed__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reversed__" title="Permalink to this definition">¶</a></dt>
1548
<dd><p>Called (if present) by the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal"><span class="pre">reversed()</span></code></a> built-in to implement
1549
reverse iteration. It should return a new iterator object that iterates
1550
over all the objects in the container in reverse order.</p>
1551
<p>If the <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></code></a> method is not provided, the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal"><span class="pre">reversed()</span></code></a>
1552
built-in will fall back to using the sequence protocol (<a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> and
1553
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>). Objects that support the sequence protocol should
1554
only provide <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></code></a> if they can provide an implementation
1555
that is more efficient than the one provided by <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal"><span class="pre">reversed()</span></code></a>.</p>
1556
<div class="versionadded">
1557
<p><span class="versionmodified">New in version 2.6.</span></p>
1561
<p>The membership test operators (<a class="reference internal" href="expressions.html#in"><code class="xref std std-keyword docutils literal"><span class="pre">in</span></code></a> and <a class="reference internal" href="expressions.html#not-in"><code class="xref std std-keyword docutils literal"><span class="pre">not</span> <span class="pre">in</span></code></a>) are normally
1562
implemented as an iteration through a sequence. However, container objects can
1563
supply the following special method with a more efficient implementation, which
1564
also does not require the object be a sequence.</p>
1566
<dt id="object.__contains__">
1567
<code class="descclassname">object.</code><code class="descname">__contains__</code><span class="sig-paren">(</span><em>self</em>, <em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__contains__" title="Permalink to this definition">¶</a></dt>
1568
<dd><p>Called to implement membership test operators. Should return true if <em>item</em>
1569
is in <em>self</em>, false otherwise. For mapping objects, this should consider the
1570
keys of the mapping rather than the values or the key-item pairs.</p>
1571
<p>For objects that don’t define <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></code></a>, the membership test first
1572
tries iteration via <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></code></a>, then the old sequence iteration
1573
protocol via <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>, see <a class="reference internal" href="expressions.html#membership-test-details"><span>this section in the language
1574
reference</span></a>.</p>
1578
<div class="section" id="additional-methods-for-emulation-of-sequence-types">
1579
<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>
1580
<p>The following optional methods can be defined to further emulate sequence
1581
objects. Immutable sequences methods should at most only define
1582
<a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></code></a>; mutable sequences might define all three methods.</p>
1584
<dt id="object.__getslice__">
1585
<code class="descclassname">object.</code><code class="descname">__getslice__</code><span class="sig-paren">(</span><em>self</em>, <em>i</em>, <em>j</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getslice__" title="Permalink to this definition">¶</a></dt>
1586
<dd><div class="deprecated">
1587
<p><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__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> method.
1588
(However, built-in types in CPython currently still implement
1589
<a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></code></a>. Therefore, you have to override it in derived
1590
classes when implementing slicing.)</p>
1592
<p>Called to implement evaluation of <code class="docutils literal"><span class="pre">self[i:j]</span></code>. The returned object should
1593
be of the same type as <em>self</em>. Note that missing <em>i</em> or <em>j</em> in the slice
1594
expression are replaced by zero or <a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal"><span class="pre">sys.maxsize</span></code></a>, respectively. If
1595
negative indexes are used in the slice, the length of the sequence is added
1596
to that index. If the instance does not implement the <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal"><span class="pre">__len__()</span></code></a> method,
1597
an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></code></a> is raised. No guarantee is made that indexes
1598
adjusted this way are not still negative. Indexes which are greater than the
1599
length of the sequence are not modified. If no <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></code></a> is found,
1600
a slice object is created instead, and passed to <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a> instead.</p>
1604
<dt id="object.__setslice__">
1605
<code class="descclassname">object.</code><code class="descname">__setslice__</code><span class="sig-paren">(</span><em>self</em>, <em>i</em>, <em>j</em>, <em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setslice__" title="Permalink to this definition">¶</a></dt>
1606
<dd><p>Called to implement assignment to <code class="docutils literal"><span class="pre">self[i:j]</span></code>. Same notes for <em>i</em> and <em>j</em> as
1607
for <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></code></a>.</p>
1608
<p>This method is deprecated. If no <a class="reference internal" href="#object.__setslice__" title="object.__setslice__"><code class="xref py py-meth docutils literal"><span class="pre">__setslice__()</span></code></a> is found, or for extended
1609
slicing of the form <code class="docutils literal"><span class="pre">self[i:j:k]</span></code>, a slice object is created, and passed to
1610
<a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></code></a>, instead of <a class="reference internal" href="#object.__setslice__" title="object.__setslice__"><code class="xref py py-meth docutils literal"><span class="pre">__setslice__()</span></code></a> being called.</p>
1614
<dt id="object.__delslice__">
1615
<code class="descclassname">object.</code><code class="descname">__delslice__</code><span class="sig-paren">(</span><em>self</em>, <em>i</em>, <em>j</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delslice__" title="Permalink to this definition">¶</a></dt>
1616
<dd><p>Called to implement deletion of <code class="docutils literal"><span class="pre">self[i:j]</span></code>. Same notes for <em>i</em> and <em>j</em> as for
1617
<a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal"><span class="pre">__getslice__()</span></code></a>. This method is deprecated. If no <a class="reference internal" href="#object.__delslice__" title="object.__delslice__"><code class="xref py py-meth docutils literal"><span class="pre">__delslice__()</span></code></a> is
1618
found, or for extended slicing of the form <code class="docutils literal"><span class="pre">self[i:j:k]</span></code>, a slice object is
1619
created, and passed to <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></code></a>, instead of <a class="reference internal" href="#object.__delslice__" title="object.__delslice__"><code class="xref py py-meth docutils literal"><span class="pre">__delslice__()</span></code></a>
1623
<p>Notice that these methods are only invoked when a single slice with a single
1624
colon is used, and the slice method is available. For slice operations
1625
involving extended slice notation, or in absence of the slice methods,
1626
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></code></a> or <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></code></a> is called with a
1627
slice object as argument.</p>
1628
<p>The following example demonstrate how to make your program or module compatible
1629
with earlier versions of Python (assuming that methods <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></code></a>,
1630
<a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></code></a> and <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></code></a> support slice objects as
1632
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
1633
<span class="o">...</span>
1634
<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>
1635
<span class="o">...</span>
1636
<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>
1637
<span class="o">...</span>
1638
<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>
1639
<span class="o">...</span>
1641
<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>
1642
<span class="c1"># They won't be defined if version is at least 2.0 final</span>
1644
<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>
1645
<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>
1646
<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>
1647
<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>
1648
<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>
1649
<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>
1650
<span class="o">...</span>
1653
<p>Note the calls to <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal"><span class="pre">max()</span></code></a>; these are necessary because of the handling of
1654
negative indices before the <code class="xref py py-meth docutils literal"><span class="pre">__*slice__()</span></code> methods are called. When
1655
negative indexes are used, the <code class="xref py py-meth docutils literal"><span class="pre">__*item__()</span></code> methods receive them as
1656
provided, but the <code class="xref py py-meth docutils literal"><span class="pre">__*slice__()</span></code> methods get a “cooked” form of the index
1657
values. For each negative index value, the length of the sequence is added to
1658
the index before calling the method (which may still result in a negative
1659
index); this is the customary handling of negative indexes by the built-in
1660
sequence types, and the <code class="xref py py-meth docutils literal"><span class="pre">__*item__()</span></code> methods are expected to do this as
1661
well. However, since they should already be doing that, negative indexes cannot
1662
be passed in; they must be constrained to the bounds of the sequence before
1663
being passed to the <code class="xref py py-meth docutils literal"><span class="pre">__*item__()</span></code> methods. Calling <code class="docutils literal"><span class="pre">max(0,</span> <span class="pre">i)</span></code>
1664
conveniently returns the proper value.</p>
1666
<div class="section" id="emulating-numeric-types">
1667
<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>
1668
<p>The following methods can be defined to emulate numeric objects. Methods
1669
corresponding to operations that are not supported by the particular kind of
1670
number implemented (e.g., bitwise operations for non-integral numbers) should be
1673
<dt id="object.__add__">
1674
<code class="descclassname">object.</code><code class="descname">__add__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__add__" title="Permalink to this definition">¶</a></dt>
1675
<dt id="object.__sub__">
1676
<code class="descclassname">object.</code><code class="descname">__sub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__sub__" title="Permalink to this definition">¶</a></dt>
1677
<dt id="object.__mul__">
1678
<code class="descclassname">object.</code><code class="descname">__mul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mul__" title="Permalink to this definition">¶</a></dt>
1679
<dt id="object.__floordiv__">
1680
<code class="descclassname">object.</code><code class="descname">__floordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floordiv__" title="Permalink to this definition">¶</a></dt>
1681
<dt id="object.__mod__">
1682
<code class="descclassname">object.</code><code class="descname">__mod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mod__" title="Permalink to this definition">¶</a></dt>
1683
<dt id="object.__divmod__">
1684
<code class="descclassname">object.</code><code class="descname">__divmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__divmod__" title="Permalink to this definition">¶</a></dt>
1685
<dt id="object.__pow__">
1686
<code class="descclassname">object.</code><code class="descname">__pow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__pow__" title="Permalink to this definition">¶</a></dt>
1687
<dt id="object.__lshift__">
1688
<code class="descclassname">object.</code><code class="descname">__lshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lshift__" title="Permalink to this definition">¶</a></dt>
1689
<dt id="object.__rshift__">
1690
<code class="descclassname">object.</code><code class="descname">__rshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rshift__" title="Permalink to this definition">¶</a></dt>
1691
<dt id="object.__and__">
1692
<code class="descclassname">object.</code><code class="descname">__and__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__and__" title="Permalink to this definition">¶</a></dt>
1693
<dt id="object.__xor__">
1694
<code class="descclassname">object.</code><code class="descname">__xor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__xor__" title="Permalink to this definition">¶</a></dt>
1695
<dt id="object.__or__">
1696
<code class="descclassname">object.</code><code class="descname">__or__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__or__" title="Permalink to this definition">¶</a></dt>
1697
<dd><p id="index-90">These methods are called to implement the binary arithmetic operations (<code class="docutils literal"><span class="pre">+</span></code>,
1698
<code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">*</span></code>, <code class="docutils literal"><span class="pre">//</span></code>, <code class="docutils literal"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a>, <code class="docutils literal"><span class="pre">**</span></code>, <code class="docutils literal"><span class="pre"><<</span></code>,
1699
<code class="docutils literal"><span class="pre">>></span></code>, <code class="docutils literal"><span class="pre">&</span></code>, <code class="docutils literal"><span class="pre">^</span></code>, <code class="docutils literal"><span class="pre">|</span></code>). For instance, to evaluate the expression
1700
<code class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>, where <em>x</em> is an instance of a class that has an <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a>
1701
method, <code class="docutils literal"><span class="pre">x.__add__(y)</span></code> is called. The <a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><code class="xref py py-meth docutils literal"><span class="pre">__divmod__()</span></code></a> method should be the
1702
equivalent to using <a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal"><span class="pre">__floordiv__()</span></code></a> and <a class="reference internal" href="#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal"><span class="pre">__mod__()</span></code></a>; it should not be
1703
related to <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal"><span class="pre">__truediv__()</span></code></a> (described below). Note that <a class="reference internal" href="#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal"><span class="pre">__pow__()</span></code></a>
1704
should be defined to accept an optional third argument if the ternary version of
1705
the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a> function is to be supported.</p>
1706
<p>If one of those methods does not support the operation with the supplied
1707
arguments, it should return <code class="docutils literal"><span class="pre">NotImplemented</span></code>.</p>
1711
<dt id="object.__div__">
1712
<code class="descclassname">object.</code><code class="descname">__div__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__div__" title="Permalink to this definition">¶</a></dt>
1713
<dt id="object.__truediv__">
1714
<code class="descclassname">object.</code><code class="descname">__truediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__truediv__" title="Permalink to this definition">¶</a></dt>
1715
<dd><p>The division operator (<code class="docutils literal"><span class="pre">/</span></code>) is implemented by these methods. The
1716
<a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal"><span class="pre">__truediv__()</span></code></a> method is used when <code class="docutils literal"><span class="pre">__future__.division</span></code> is in effect,
1717
otherwise <a class="reference internal" href="#object.__div__" title="object.__div__"><code class="xref py py-meth docutils literal"><span class="pre">__div__()</span></code></a> is used. If only one of these two methods is defined,
1718
the object will not support division in the alternate context; <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a>
1719
will be raised instead.</p>
1723
<dt id="object.__radd__">
1724
<code class="descclassname">object.</code><code class="descname">__radd__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__radd__" title="Permalink to this definition">¶</a></dt>
1725
<dt id="object.__rsub__">
1726
<code class="descclassname">object.</code><code class="descname">__rsub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rsub__" title="Permalink to this definition">¶</a></dt>
1727
<dt id="object.__rmul__">
1728
<code class="descclassname">object.</code><code class="descname">__rmul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmul__" title="Permalink to this definition">¶</a></dt>
1729
<dt id="object.__rdiv__">
1730
<code class="descclassname">object.</code><code class="descname">__rdiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdiv__" title="Permalink to this definition">¶</a></dt>
1731
<dt id="object.__rtruediv__">
1732
<code class="descclassname">object.</code><code class="descname">__rtruediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rtruediv__" title="Permalink to this definition">¶</a></dt>
1733
<dt id="object.__rfloordiv__">
1734
<code class="descclassname">object.</code><code class="descname">__rfloordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rfloordiv__" title="Permalink to this definition">¶</a></dt>
1735
<dt id="object.__rmod__">
1736
<code class="descclassname">object.</code><code class="descname">__rmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmod__" title="Permalink to this definition">¶</a></dt>
1737
<dt id="object.__rdivmod__">
1738
<code class="descclassname">object.</code><code class="descname">__rdivmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdivmod__" title="Permalink to this definition">¶</a></dt>
1739
<dt id="object.__rpow__">
1740
<code class="descclassname">object.</code><code class="descname">__rpow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rpow__" title="Permalink to this definition">¶</a></dt>
1741
<dt id="object.__rlshift__">
1742
<code class="descclassname">object.</code><code class="descname">__rlshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rlshift__" title="Permalink to this definition">¶</a></dt>
1743
<dt id="object.__rrshift__">
1744
<code class="descclassname">object.</code><code class="descname">__rrshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rrshift__" title="Permalink to this definition">¶</a></dt>
1745
<dt id="object.__rand__">
1746
<code class="descclassname">object.</code><code class="descname">__rand__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rand__" title="Permalink to this definition">¶</a></dt>
1747
<dt id="object.__rxor__">
1748
<code class="descclassname">object.</code><code class="descname">__rxor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rxor__" title="Permalink to this definition">¶</a></dt>
1749
<dt id="object.__ror__">
1750
<code class="descclassname">object.</code><code class="descname">__ror__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ror__" title="Permalink to this definition">¶</a></dt>
1751
<dd><p id="index-91">These methods are called to implement the binary arithmetic operations (<code class="docutils literal"><span class="pre">+</span></code>,
1752
<code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">*</span></code>, <code class="docutils literal"><span class="pre">/</span></code>, <code class="docutils literal"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a>, <code class="docutils literal"><span class="pre">**</span></code>, <code class="docutils literal"><span class="pre"><<</span></code>, <code class="docutils literal"><span class="pre">>></span></code>,
1753
<code class="docutils literal"><span class="pre">&</span></code>, <code class="docutils literal"><span class="pre">^</span></code>, <code class="docutils literal"><span class="pre">|</span></code>) with reflected (swapped) operands. These functions are
1754
only called if the left operand does not support the corresponding operation and
1755
the operands are of different types. <a class="footnote-reference" href="#id6" id="id3">[2]</a> For instance, to evaluate the
1756
expression <code class="docutils literal"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code>, where <em>y</em> is an instance of a class that has an
1757
<a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><code class="xref py py-meth docutils literal"><span class="pre">__rsub__()</span></code></a> method, <code class="docutils literal"><span class="pre">y.__rsub__(x)</span></code> is called if <code class="docutils literal"><span class="pre">x.__sub__(y)</span></code> returns
1758
<em>NotImplemented</em>.</p>
1759
<p id="index-92">Note that ternary <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal"><span class="pre">pow()</span></code></a> will not try calling <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><code class="xref py py-meth docutils literal"><span class="pre">__rpow__()</span></code></a> (the
1760
coercion rules would become too complicated).</p>
1761
<div class="admonition note">
1762
<p class="first admonition-title">Note</p>
1763
<p class="last">If the right operand’s type is a subclass of the left operand’s type and that
1764
subclass provides the reflected method for the operation, this method will be
1765
called before the left operand’s non-reflected method. This behavior allows
1766
subclasses to override their ancestors’ operations.</p>
1771
<dt id="object.__iadd__">
1772
<code class="descclassname">object.</code><code class="descname">__iadd__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iadd__" title="Permalink to this definition">¶</a></dt>
1773
<dt id="object.__isub__">
1774
<code class="descclassname">object.</code><code class="descname">__isub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__isub__" title="Permalink to this definition">¶</a></dt>
1775
<dt id="object.__imul__">
1776
<code class="descclassname">object.</code><code class="descname">__imul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imul__" title="Permalink to this definition">¶</a></dt>
1777
<dt id="object.__idiv__">
1778
<code class="descclassname">object.</code><code class="descname">__idiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__idiv__" title="Permalink to this definition">¶</a></dt>
1779
<dt id="object.__itruediv__">
1780
<code class="descclassname">object.</code><code class="descname">__itruediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__itruediv__" title="Permalink to this definition">¶</a></dt>
1781
<dt id="object.__ifloordiv__">
1782
<code class="descclassname">object.</code><code class="descname">__ifloordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ifloordiv__" title="Permalink to this definition">¶</a></dt>
1783
<dt id="object.__imod__">
1784
<code class="descclassname">object.</code><code class="descname">__imod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imod__" title="Permalink to this definition">¶</a></dt>
1785
<dt id="object.__ipow__">
1786
<code class="descclassname">object.</code><code class="descname">__ipow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__ipow__" title="Permalink to this definition">¶</a></dt>
1787
<dt id="object.__ilshift__">
1788
<code class="descclassname">object.</code><code class="descname">__ilshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ilshift__" title="Permalink to this definition">¶</a></dt>
1789
<dt id="object.__irshift__">
1790
<code class="descclassname">object.</code><code class="descname">__irshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__irshift__" title="Permalink to this definition">¶</a></dt>
1791
<dt id="object.__iand__">
1792
<code class="descclassname">object.</code><code class="descname">__iand__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iand__" title="Permalink to this definition">¶</a></dt>
1793
<dt id="object.__ixor__">
1794
<code class="descclassname">object.</code><code class="descname">__ixor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ixor__" title="Permalink to this definition">¶</a></dt>
1795
<dt id="object.__ior__">
1796
<code class="descclassname">object.</code><code class="descname">__ior__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ior__" title="Permalink to this definition">¶</a></dt>
1797
<dd><p>These methods are called to implement the augmented arithmetic assignments
1798
(<code class="docutils literal"><span class="pre">+=</span></code>, <code class="docutils literal"><span class="pre">-=</span></code>, <code class="docutils literal"><span class="pre">*=</span></code>, <code class="docutils literal"><span class="pre">/=</span></code>, <code class="docutils literal"><span class="pre">//=</span></code>, <code class="docutils literal"><span class="pre">%=</span></code>, <code class="docutils literal"><span class="pre">**=</span></code>, <code class="docutils literal"><span class="pre"><<=</span></code>, <code class="docutils literal"><span class="pre">>>=</span></code>,
1799
<code class="docutils literal"><span class="pre">&=</span></code>, <code class="docutils literal"><span class="pre">^=</span></code>, <code class="docutils literal"><span class="pre">|=</span></code>). These methods should attempt to do the operation
1800
in-place (modifying <em>self</em>) and return the result (which could be, but does
1801
not have to be, <em>self</em>). If a specific method is not defined, the augmented
1802
assignment falls back to the normal methods. For instance, to execute the
1803
statement <code class="docutils literal"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></code>, where <em>x</em> is an instance of a class that has an
1804
<a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></code></a> method, <code class="docutils literal"><span class="pre">x.__iadd__(y)</span></code> is called. If <em>x</em> is an instance
1805
of a class that does not define a <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></code></a> method, <code class="docutils literal"><span class="pre">x.__add__(y)</span></code>
1806
and <code class="docutils literal"><span class="pre">y.__radd__(x)</span></code> are considered, as with the evaluation of <code class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>.</p>
1810
<dt id="object.__neg__">
1811
<code class="descclassname">object.</code><code class="descname">__neg__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__neg__" title="Permalink to this definition">¶</a></dt>
1812
<dt id="object.__pos__">
1813
<code class="descclassname">object.</code><code class="descname">__pos__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__pos__" title="Permalink to this definition">¶</a></dt>
1814
<dt id="object.__abs__">
1815
<code class="descclassname">object.</code><code class="descname">__abs__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__abs__" title="Permalink to this definition">¶</a></dt>
1816
<dt id="object.__invert__">
1817
<code class="descclassname">object.</code><code class="descname">__invert__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__invert__" title="Permalink to this definition">¶</a></dt>
1818
<dd><p id="index-93">Called to implement the unary arithmetic operations (<code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">+</span></code>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal"><span class="pre">abs()</span></code></a>
1819
and <code class="docutils literal"><span class="pre">~</span></code>).</p>
1823
<dt id="object.__complex__">
1824
<code class="descclassname">object.</code><code class="descname">__complex__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__complex__" title="Permalink to this definition">¶</a></dt>
1825
<dt id="object.__int__">
1826
<code class="descclassname">object.</code><code class="descname">__int__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__int__" title="Permalink to this definition">¶</a></dt>
1827
<dt id="object.__long__">
1828
<code class="descclassname">object.</code><code class="descname">__long__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__long__" title="Permalink to this definition">¶</a></dt>
1829
<dt id="object.__float__">
1830
<code class="descclassname">object.</code><code class="descname">__float__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__float__" title="Permalink to this definition">¶</a></dt>
1831
<dd><p id="index-94">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal"><span class="pre">complex()</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal"><span class="pre">int()</span></code></a>,
1832
<a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal"><span class="pre">long()</span></code></a>, and <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal"><span class="pre">float()</span></code></a>. Should return a value of the appropriate type.</p>
1836
<dt id="object.__oct__">
1837
<code class="descclassname">object.</code><code class="descname">__oct__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__oct__" title="Permalink to this definition">¶</a></dt>
1838
<dt id="object.__hex__">
1839
<code class="descclassname">object.</code><code class="descname">__hex__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hex__" title="Permalink to this definition">¶</a></dt>
1840
<dd><p id="index-95">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal"><span class="pre">oct()</span></code></a> and <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal"><span class="pre">hex()</span></code></a>. Should
1841
return a string value.</p>
1845
<dt id="object.__index__">
1846
<code class="descclassname">object.</code><code class="descname">__index__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__index__" title="Permalink to this definition">¶</a></dt>
1847
<dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.index" title="operator.index"><code class="xref py py-func docutils literal"><span class="pre">operator.index()</span></code></a>. Also called whenever Python needs
1848
an integer object (such as in slicing). Must return an integer (int or long).</p>
1849
<div class="versionadded">
1850
<p><span class="versionmodified">New in version 2.5.</span></p>
1855
<dt id="object.__coerce__">
1856
<code class="descclassname">object.</code><code class="descname">__coerce__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__coerce__" title="Permalink to this definition">¶</a></dt>
1857
<dd><p>Called to implement “mixed-mode” numeric arithmetic. Should either return a
1858
2-tuple containing <em>self</em> and <em>other</em> converted to a common numeric type, or
1859
<code class="docutils literal"><span class="pre">None</span></code> if conversion is impossible. When the common type would be the type of
1860
<code class="docutils literal"><span class="pre">other</span></code>, it is sufficient to return <code class="docutils literal"><span class="pre">None</span></code>, since the interpreter will also
1861
ask the other object to attempt a coercion (but sometimes, if the implementation
1862
of the other type cannot be changed, it is useful to do the conversion to the
1863
other type here). A return value of <code class="docutils literal"><span class="pre">NotImplemented</span></code> is equivalent to
1864
returning <code class="docutils literal"><span class="pre">None</span></code>.</p>
1868
<div class="section" id="coercion-rules">
1869
<span id="id4"></span><h3>3.4.9. Coercion rules<a class="headerlink" href="#coercion-rules" title="Permalink to this headline">¶</a></h3>
1870
<p>This section used to document the rules for coercion. As the language has
1871
evolved, the coercion rules have become hard to document precisely; documenting
1872
what one version of one particular implementation does is undesirable. Instead,
1873
here are some informal guidelines regarding coercion. In Python 3, coercion
1874
will not be supported.</p>
1876
<li><p class="first">If the left operand of a % operator is a string or Unicode object, no coercion
1877
takes place and the string formatting operation is invoked instead.</p>
1879
<li><p class="first">It is no longer recommended to define a coercion operation. Mixed-mode
1880
operations on types that don’t define coercion pass the original arguments to
1883
<li><p class="first">New-style classes (those derived from <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal"><span class="pre">object</span></code></a>) never invoke the
1884
<a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></code></a> method in response to a binary operator; the only time
1885
<a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></code></a> is invoked is when the built-in function <a class="reference internal" href="../library/functions.html#coerce" title="coerce"><code class="xref py py-func docutils literal"><span class="pre">coerce()</span></code></a> is
1888
<li><p class="first">For most intents and purposes, an operator that returns <code class="docutils literal"><span class="pre">NotImplemented</span></code> is
1889
treated the same as one that is not implemented at all.</p>
1891
<li><p class="first">Below, <code class="xref py py-meth docutils literal"><span class="pre">__op__()</span></code> and <code class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></code> are used to signify the generic method
1892
names corresponding to an operator; <code class="xref py py-meth docutils literal"><span class="pre">__iop__()</span></code> is used for the
1893
corresponding in-place operator. For example, for the operator ‘<code class="docutils literal"><span class="pre">+</span></code>‘,
1894
<a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a> and <a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal"><span class="pre">__radd__()</span></code></a> are used for the left and right variant of
1895
the binary operator, and <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></code></a> for the in-place variant.</p>
1897
<li><p class="first">For objects <em>x</em> and <em>y</em>, first <code class="docutils literal"><span class="pre">x.__op__(y)</span></code> is tried. If this is not
1898
implemented or returns <code class="docutils literal"><span class="pre">NotImplemented</span></code>, <code class="docutils literal"><span class="pre">y.__rop__(x)</span></code> is tried. If this
1899
is also not implemented or returns <code class="docutils literal"><span class="pre">NotImplemented</span></code>, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code></a>
1900
exception is raised. But see the following exception:</p>
1902
<li><p class="first">Exception to the previous item: if the left operand is an instance of a built-in
1903
type or a new-style class, and the right operand is an instance of a proper
1904
subclass of that type or class and overrides the base’s <code class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></code> method,
1905
the right operand’s <code class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></code> method is tried <em>before</em> the left operand’s
1906
<code class="xref py py-meth docutils literal"><span class="pre">__op__()</span></code> method.</p>
1907
<p>This is done so that a subclass can completely override binary operators.
1908
Otherwise, the left operand’s <code class="xref py py-meth docutils literal"><span class="pre">__op__()</span></code> method would always accept the
1909
right operand: when an instance of a given class is expected, an instance of a
1910
subclass of that class is always acceptable.</p>
1912
<li><p class="first">When either operand type defines a coercion, this coercion is called before that
1913
type’s <code class="xref py py-meth docutils literal"><span class="pre">__op__()</span></code> or <code class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></code> method is called, but no sooner. If
1914
the coercion returns an object of a different type for the operand whose
1915
coercion is invoked, part of the process is redone using the new object.</p>
1917
<li><p class="first">When an in-place operator (like ‘<code class="docutils literal"><span class="pre">+=</span></code>‘) is used, if the left operand
1918
implements <code class="xref py py-meth docutils literal"><span class="pre">__iop__()</span></code>, it is invoked without any coercion. When the
1919
operation falls back to <code class="xref py py-meth docutils literal"><span class="pre">__op__()</span></code> and/or <code class="xref py py-meth docutils literal"><span class="pre">__rop__()</span></code>, the normal
1920
coercion rules apply.</p>
1922
<li><p class="first">In <code class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>, if <em>x</em> is a sequence that implements sequence concatenation,
1923
sequence concatenation is invoked.</p>
1925
<li><p class="first">In <code class="docutils literal"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></code>, if one operand is a sequence that implements sequence
1926
repetition, and the other is an integer (<a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal"><span class="pre">int</span></code></a> or <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-class docutils literal"><span class="pre">long</span></code></a>),
1927
sequence repetition is invoked.</p>
1929
<li><p class="first">Rich comparisons (implemented by methods <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></code></a> and so on) never use
1930
coercion. Three-way comparison (implemented by <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal"><span class="pre">__cmp__()</span></code></a>) does use
1931
coercion under the same conditions as other binary operations use it.</p>
1933
<li><p class="first">In the current implementation, the built-in numeric types <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal"><span class="pre">int</span></code></a>,
1934
<a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-class docutils literal"><span class="pre">long</span></code></a>, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal"><span class="pre">float</span></code></a>, and <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal"><span class="pre">complex</span></code></a> do not use coercion.
1935
All these types implement a <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></code></a> method, for use by the built-in
1936
<a class="reference internal" href="../library/functions.html#coerce" title="coerce"><code class="xref py py-func docutils literal"><span class="pre">coerce()</span></code></a> function.</p>
1937
<div class="versionchanged">
1938
<p><span class="versionmodified">Changed in version 2.7: </span>The complex type no longer makes implicit calls to the <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal"><span class="pre">__coerce__()</span></code></a>
1939
method for mixed-type binary arithmetic operations.</p>
1944
<div class="section" id="with-statement-context-managers">
1945
<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>
1946
<div class="versionadded">
1947
<p><span class="versionmodified">New in version 2.5.</span></p>
1949
<p>A <em class="dfn">context manager</em> is an object that defines the runtime context to be
1950
established when executing a <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a> statement. The context manager
1951
handles the entry into, and the exit from, the desired runtime context for the
1952
execution of the block of code. Context managers are normally invoked using the
1953
<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a> statement (described in section <a class="reference internal" href="compound_stmts.html#with"><span>The with statement</span></a>), but can also be
1954
used by directly invoking their methods.</p>
1955
<p id="index-96">Typical uses of context managers include saving and restoring various kinds of
1956
global state, locking and unlocking resources, closing opened files, etc.</p>
1957
<p>For more information on context managers, see <a class="reference internal" href="../library/stdtypes.html#typecontextmanager"><span>Context Manager Types</span></a>.</p>
1959
<dt id="object.__enter__">
1960
<code class="descclassname">object.</code><code class="descname">__enter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__enter__" title="Permalink to this definition">¶</a></dt>
1961
<dd><p>Enter the runtime context related to this object. The <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a> statement
1962
will bind this method’s return value to the target(s) specified in the
1963
<a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal"><span class="pre">as</span></code></a> clause of the statement, if any.</p>
1967
<dt id="object.__exit__">
1968
<code class="descclassname">object.</code><code class="descname">__exit__</code><span class="sig-paren">(</span><em>self</em>, <em>exc_type</em>, <em>exc_value</em>, <em>traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__exit__" title="Permalink to this definition">¶</a></dt>
1969
<dd><p>Exit the runtime context related to this object. The parameters describe the
1970
exception that caused the context to be exited. If the context was exited
1971
without an exception, all three arguments will be <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>.</p>
1972
<p>If an exception is supplied, and the method wishes to suppress the exception
1973
(i.e., prevent it from being propagated), it should return a true value.
1974
Otherwise, the exception will be processed normally upon exit from this method.</p>
1975
<p>Note that <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></code></a> methods should not reraise the passed-in exception;
1976
this is the caller’s responsibility.</p>
1979
<div class="admonition seealso">
1980
<p class="first admonition-title">See also</p>
1981
<dl class="last docutils">
1982
<dt><span class="target" id="index-97"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt>
1983
<dd>The specification, background, and examples for the Python <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><span class="pre">with</span></code></a>
1988
<div class="section" id="special-method-lookup-for-old-style-classes">
1989
<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>
1990
<p>For old-style classes, special methods are always looked up in exactly the
1991
same way as any other method or attribute. This is the case regardless of
1992
whether the method is being looked up explicitly as in <code class="docutils literal"><span class="pre">x.__getitem__(i)</span></code>
1993
or implicitly as in <code class="docutils literal"><span class="pre">x[i]</span></code>.</p>
1994
<p>This behaviour means that special methods may exhibit different behaviour
1995
for different instances of a single old-style class if the appropriate
1996
special attributes are set differently:</p>
1997
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
1998
<span class="gp">... </span> <span class="k">pass</span>
1999
<span class="gp">...</span>
2000
<span class="gp">>>> </span><span class="n">c1</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
2001
<span class="gp">>>> </span><span class="n">c2</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
2002
<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>
2003
<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>
2004
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c1</span><span class="p">)</span>
2005
<span class="go">5</span>
2006
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c2</span><span class="p">)</span>
2007
<span class="go">9</span>
2011
<div class="section" id="special-method-lookup-for-new-style-classes">
2012
<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>
2013
<p>For new-style classes, implicit invocations of special methods are only guaranteed
2014
to work correctly if defined on an object’s type, not in the object’s instance
2015
dictionary. That behaviour is the reason why the following code raises an
2016
exception (unlike the equivalent example with old-style classes):</p>
2017
<div class="highlight-python"><div class="highlight"><pre><span></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>
2018
<span class="gp">... </span> <span class="k">pass</span>
2019
<span class="gp">...</span>
2020
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
2021
<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>
2022
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
2023
<span class="gt">Traceback (most recent call last):</span>
2024
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
2025
<span class="gr">TypeError</span>: <span class="n">object of type 'C' has no len()</span>
2028
<p>The rationale behind this behaviour lies with a number of special methods such
2029
as <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></code></a> and <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></code></a> that are implemented by all objects,
2030
including type objects. If the implicit lookup of these methods used the
2031
conventional lookup process, they would fail when invoked on the type object
2033
<div class="highlight-python"><div class="highlight"><pre><span></span><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>
2034
<span class="go">True</span>
2035
<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>
2036
<span class="gt">Traceback (most recent call last):</span>
2037
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
2038
<span class="gr">TypeError</span>: <span class="n">descriptor '__hash__' of 'int' object needs an argument</span>
2041
<p>Incorrectly attempting to invoke an unbound method of a class in this way is
2042
sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing
2043
the instance when looking up special methods:</p>
2044
<div class="highlight-python"><div class="highlight"><pre><span></span><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>
2045
<span class="go">True</span>
2046
<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>
2047
<span class="go">True</span>
2050
<p>In addition to bypassing any instance attributes in the interest of
2051
correctness, implicit special method lookup generally also bypasses the
2052
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> method even of the object’s metaclass:</p>
2053
<div class="highlight-python"><div class="highlight"><pre><span></span><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>
2054
<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>
2055
<span class="gp">... </span> <span class="k">print</span> <span class="s2">"Metaclass getattribute invoked"</span>
2056
<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>
2057
<span class="gp">...</span>
2058
<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>
2059
<span class="gp">... </span> <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">Meta</span>
2060
<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>
2061
<span class="gp">... </span> <span class="k">return</span> <span class="mi">10</span>
2062
<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>
2063
<span class="gp">... </span> <span class="k">print</span> <span class="s2">"Class getattribute invoked"</span>
2064
<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>
2065
<span class="gp">...</span>
2066
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
2067
<span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">__len__</span><span class="p">()</span> <span class="c1"># Explicit lookup via instance</span>
2068
<span class="go">Class getattribute invoked</span>
2069
<span class="go">10</span>
2070
<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="c1"># Explicit lookup via type</span>
2071
<span class="go">Metaclass getattribute invoked</span>
2072
<span class="go">10</span>
2073
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># Implicit lookup</span>
2074
<span class="go">10</span>
2077
<p>Bypassing the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></code></a> machinery in this fashion
2078
provides significant scope for speed optimisations within the
2079
interpreter, at the cost of some flexibility in the handling of
2080
special methods (the special method <em>must</em> be set on the class
2081
object itself in order to be consistently invoked by the interpreter).</p>
2082
<p class="rubric">Footnotes</p>
2083
<table class="docutils footnote" frame="void" id="id5" rules="none">
2084
<colgroup><col class="label" /><col /></colgroup>
2085
<tbody valign="top">
2086
<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
2087
controlled conditions. It generally isn’t a good idea though, since it can
2088
lead to some very strange behaviour if it is handled incorrectly.</td></tr>
2091
<table class="docutils footnote" frame="void" id="id6" rules="none">
2092
<colgroup><col class="label" /><col /></colgroup>
2093
<tbody valign="top">
2094
<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
2095
(such as <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal"><span class="pre">__add__()</span></code></a>) fails the operation is not supported, which is why the
2096
reflected method is not called.</td></tr>
2107
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
2108
<div class="sphinxsidebarwrapper">
2109
<h3><a href="../contents.html">Table Of Contents</a></h3>
2111
<li><a class="reference internal" href="#">3. Data model</a><ul>
2112
<li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li>
2113
<li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
2114
<li><a class="reference internal" href="#new-style-and-classic-classes">3.3. New-style and classic classes</a></li>
2115
<li><a class="reference internal" href="#special-method-names">3.4. Special method names</a><ul>
2116
<li><a class="reference internal" href="#basic-customization">3.4.1. Basic customization</a></li>
2117
<li><a class="reference internal" href="#customizing-attribute-access">3.4.2. Customizing attribute access</a><ul>
2118
<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>
2119
<li><a class="reference internal" href="#implementing-descriptors">3.4.2.2. Implementing Descriptors</a></li>
2120
<li><a class="reference internal" href="#invoking-descriptors">3.4.2.3. Invoking Descriptors</a></li>
2121
<li><a class="reference internal" href="#slots">3.4.2.4. __slots__</a></li>
2124
<li><a class="reference internal" href="#customizing-class-creation">3.4.3. Customizing class creation</a></li>
2125
<li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.4.4. Customizing instance and subclass checks</a></li>
2126
<li><a class="reference internal" href="#emulating-callable-objects">3.4.5. Emulating callable objects</a></li>
2127
<li><a class="reference internal" href="#emulating-container-types">3.4.6. Emulating container types</a></li>
2128
<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>
2129
<li><a class="reference internal" href="#emulating-numeric-types">3.4.8. Emulating numeric types</a></li>
2130
<li><a class="reference internal" href="#coercion-rules">3.4.9. Coercion rules</a></li>
2131
<li><a class="reference internal" href="#with-statement-context-managers">3.4.10. With Statement Context Managers</a></li>
2132
<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>
2133
<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>
2140
<h4>Previous topic</h4>
2141
<p class="topless"><a href="lexical_analysis.html"
2142
title="previous chapter">2. Lexical analysis</a></p>
2144
<p class="topless"><a href="executionmodel.html"
2145
title="next chapter">4. Execution model</a></p>
2147
<ul class="this-page-menu">
2148
<li><a href="../bugs.html">Report a Bug</a></li>
2149
<li><a href="../_sources/reference/datamodel.txt"
2150
rel="nofollow">Show Source</a></li>
2153
<div id="searchbox" style="display: none" role="search">
2154
<h3>Quick search</h3>
2155
<form class="search" action="../search.html" method="get">
2156
<input type="text" name="q" />
2157
<input type="submit" value="Go" />
2158
<input type="hidden" name="check_keywords" value="yes" />
2159
<input type="hidden" name="area" value="default" />
2161
<p class="searchtip" style="font-size: 90%">
2162
Enter search terms or a module, class or function name.
2165
<script type="text/javascript">$('#searchbox').show(0);</script>
2168
<div class="clearer"></div>
2170
<div class="related" role="navigation" aria-label="related navigation">
2173
<li class="right" style="margin-right: 10px">
2174
<a href="../genindex.html" title="General Index"
2177
<a href="../py-modindex.html" title="Python Module Index"
2180
<a href="executionmodel.html" title="4. Execution model"
2183
<a href="lexical_analysis.html" title="2. Lexical analysis"
2184
>previous</a> |</li>
2185
<li><img src="../_static/py.png" alt=""
2186
style="vertical-align: middle; margin-top: -1px"/></li>
2187
<li><a href="https://www.python.org/">Python</a> »</li>
2189
<span class="version_switcher_placeholder">2.7.12</span>
2190
<a href="../index.html">Documentation</a> »
2193
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> »</li>
2196
<div class="footer">
2197
© <a href="../copyright.html">Copyright</a> 1990-2016, Python Software Foundation.
2199
The Python Software Foundation is a non-profit corporation.
2200
<a href="https://www.python.org/psf/donations/">Please donate.</a>
2202
Last updated on Nov 26, 2016.
2203
<a href="../bugs.html">Found a bug</a>?
2205
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
b'\\ No newline at end of file'