blob: 5eb857a6719e6387bb66406f74ec01e13ed80834 [file] [log] [blame]
Fred Drake61c77281998-07-28 19:34:22 +00001\chapter{Data model\label{datamodel}}
Fred Drakef6669171998-05-06 19:52:49 +00002
Fred Drake61c77281998-07-28 19:34:22 +00003\section{Objects, values and types\label{objects}}
Fred Drakef6669171998-05-06 19:52:49 +00004
5\dfn{Objects} are Python's abstraction for data. All data in a Python
6program is represented by objects or by relations between objects.
7(In a sense, and in conformance to Von Neumann's model of a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00008``stored program computer,'' code is also represented by objects.)
Fred Drakef6669171998-05-06 19:52:49 +00009\index{object}
10\index{data}
11
12Every object has an identity, a type and a value. An object's
13\emph{identity} never changes once it has been created; you may think
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000014of it as the object's address in memory. The `\code{is}' operator
Fred Drake82385871998-10-01 20:40:43 +000015compares the identity of two objects; the
16\function{id()}\bifuncindex{id} function returns an integer
17representing its identity (currently implemented as its address).
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000018An object's \dfn{type} is
Fred Drakef6669171998-05-06 19:52:49 +000019also unchangeable. It determines the operations that an object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000020supports (e.g., ``does it have a length?'') and also defines the
Fred Drake82385871998-10-01 20:40:43 +000021possible values for objects of that type. The
22\function{type()}\bifuncindex{type} function returns an object's type
23(which is an object itself). The \emph{value} of some
Fred Drakef6669171998-05-06 19:52:49 +000024objects can change. Objects whose value can change are said to be
25\emph{mutable}; objects whose value is unchangeable once they are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000026created are called \emph{immutable}.
27An object's mutability is determined by its type; for instance,
28numbers, strings and tuples are immutable, while dictionaries and
29lists are mutable.
Fred Drakef6669171998-05-06 19:52:49 +000030\index{identity of an object}
31\index{value of an object}
32\index{type of an object}
33\index{mutable object}
34\index{immutable object}
35
36Objects are never explicitly destroyed; however, when they become
37unreachable they may be garbage-collected. An implementation is
Barry Warsaw92a6ed91998-08-07 16:33:51 +000038allowed to postpone garbage collection or omit it altogether --- it is
39a matter of implementation quality how garbage collection is
Fred Drakef6669171998-05-06 19:52:49 +000040implemented, as long as no objects are collected that are still
41reachable. (Implementation note: the current implementation uses a
42reference-counting scheme which collects most objects as soon as they
43become unreachable, but never collects garbage containing circular
44references.)
45\index{garbage collection}
46\index{reference counting}
47\index{unreachable object}
48
49Note that the use of the implementation's tracing or debugging
50facilities may keep objects alive that would normally be collectable.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000051Also note that catching an exception with a
Fred Drake4856d011999-01-12 04:15:20 +000052`\keyword{try}...\keyword{except}' statement may keep objects alive.
Fred Drakef6669171998-05-06 19:52:49 +000053
54Some objects contain references to ``external'' resources such as open
55files or windows. It is understood that these resources are freed
56when the object is garbage-collected, but since garbage collection is
57not guaranteed to happen, such objects also provide an explicit way to
58release the external resource, usually a \method{close()} method.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000059Programs are strongly recommended to explicitly close such
Fred Drake4856d011999-01-12 04:15:20 +000060objects. The `\keyword{try}...\keyword{finally}' statement provides
61a convenient way to do this.
Fred Drakef6669171998-05-06 19:52:49 +000062
63Some objects contain references to other objects; these are called
64\emph{containers}. Examples of containers are tuples, lists and
65dictionaries. The references are part of a container's value. In
66most cases, when we talk about the value of a container, we imply the
67values, not the identities of the contained objects; however, when we
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000068talk about the mutability of a container, only the identities of
69the immediately contained objects are implied. So, if an immutable
70container (like a tuple)
71contains a reference to a mutable object, its value changes
72if that mutable object is changed.
Fred Drakef6669171998-05-06 19:52:49 +000073\index{container}
74
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000075Types affect almost all aspects of object behavior. Even the importance
Fred Drakef6669171998-05-06 19:52:49 +000076of object identity is affected in some sense: for immutable types,
77operations that compute new values may actually return a reference to
78any existing object with the same type and value, while for mutable
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000079objects this is not allowed. E.g., after
Fred Drake82385871998-10-01 20:40:43 +000080\samp{a = 1; b = 1},
Fred Drakef6669171998-05-06 19:52:49 +000081\code{a} and \code{b} may or may not refer to the same object with the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000082value one, depending on the implementation, but after
Fred Drake82385871998-10-01 20:40:43 +000083\samp{c = []; d = []}, \code{c} and \code{d}
Fred Drakef6669171998-05-06 19:52:49 +000084are guaranteed to refer to two different, unique, newly created empty
85lists.
Fred Drake82385871998-10-01 20:40:43 +000086(Note that \samp{c = d = []} assigns the same object to both
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000087\code{c} and \code{d}.)
Fred Drakef6669171998-05-06 19:52:49 +000088
Fred Drake61c77281998-07-28 19:34:22 +000089\section{The standard type hierarchy\label{types}}
Fred Drakef6669171998-05-06 19:52:49 +000090
91Below is a list of the types that are built into Python. Extension
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000092modules written in \C{} can define additional types. Future versions of
93Python may add types to the type hierarchy (e.g., rational
Fred Drakef6669171998-05-06 19:52:49 +000094numbers, efficiently stored arrays of integers, etc.).
95\index{type}
96\indexii{data}{type}
97\indexii{type}{hierarchy}
98\indexii{extension}{module}
99\indexii{C}{language}
100
101Some of the type descriptions below contain a paragraph listing
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000102`special attributes.' These are attributes that provide access to the
Fred Drakef6669171998-05-06 19:52:49 +0000103implementation and are not intended for general use. Their definition
104may change in the future. There are also some `generic' special
105attributes, not listed with the individual objects: \member{__methods__}
106is a list of the method names of a built-in object, if it has any;
107\member{__members__} is a list of the data attribute names of a built-in
108object, if it has any.
109\index{attribute}
110\indexii{special}{attribute}
111\indexiii{generic}{special}{attribute}
Fred Drake4856d011999-01-12 04:15:20 +0000112\withsubitem{(built-in object attribute)}{
Fred Drake1e42d8a1998-11-25 17:58:50 +0000113 \ttindex{__methods__}
114 \ttindex{__members__}}
Fred Drakef6669171998-05-06 19:52:49 +0000115
116\begin{description}
117
118\item[None]
119This type has a single value. There is a single object with this value.
120This object is accessed through the built-in name \code{None}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000121It is used to signify the absence of a value in many situations, e.g.,
122it is returned from functions that don't explicitly return anything.
123Its truth value is false.
Fred Drakef6669171998-05-06 19:52:49 +0000124\ttindex{None}
Fred Drake78eebfd1998-11-25 19:09:24 +0000125\obindex{None@{\texttt{None}}}
Fred Drakef6669171998-05-06 19:52:49 +0000126
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000127\item[Ellipsis]
128This type has a single value. There is a single object with this value.
129This object is accessed through the built-in name \code{Ellipsis}.
Fred Drake82385871998-10-01 20:40:43 +0000130It is used to indicate the presence of the \samp{...} syntax in a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000131slice. Its truth value is true.
132\ttindex{Ellipsis}
Fred Drake78eebfd1998-11-25 19:09:24 +0000133\obindex{Ellipsis@{\texttt{Ellipsis}}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000134
Fred Drakef6669171998-05-06 19:52:49 +0000135\item[Numbers]
136These are created by numeric literals and returned as results by
137arithmetic operators and arithmetic built-in functions. Numeric
138objects are immutable; once created their value never changes. Python
139numbers are of course strongly related to mathematical numbers, but
140subject to the limitations of numerical representation in computers.
141\obindex{number}
142\obindex{numeric}
143
144Python distinguishes between integers and floating point numbers:
145
146\begin{description}
147\item[Integers]
148These represent elements from the mathematical set of whole numbers.
149\obindex{integer}
150
151There are two types of integers:
152
153\begin{description}
154
155\item[Plain integers]
156These represent numbers in the range -2147483648 through 2147483647.
157(The range may be larger on machines with a larger natural word
158size, but not smaller.)
159When the result of an operation falls outside this range, the
160exception \exception{OverflowError} is raised.
161For the purpose of shift and mask operations, integers are assumed to
162have a binary, 2's complement notation using 32 or more bits, and
163hiding no bits from the user (i.e., all 4294967296 different bit
164patterns correspond to different values).
165\obindex{plain integer}
166\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
167
168\item[Long integers]
169These represent numbers in an unlimited range, subject to available
170(virtual) memory only. For the purpose of shift and mask operations,
171a binary representation is assumed, and negative numbers are
172represented in a variant of 2's complement which gives the illusion of
173an infinite string of sign bits extending to the left.
174\obindex{long integer}
175
176\end{description} % Integers
177
178The rules for integer representation are intended to give the most
179meaningful interpretation of shift and mask operations involving
180negative integers and the least surprises when switching between the
181plain and long integer domains. For any operation except left shift,
182if it yields a result in the plain integer domain without causing
183overflow, it will yield the same result in the long integer domain or
184when using mixed operands.
185\indexii{integer}{representation}
186
187\item[Floating point numbers]
188These represent machine-level double precision floating point numbers.
189You are at the mercy of the underlying machine architecture and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000190\C{} implementation for the accepted range and handling of overflow.
191Python does not support single-precision floating point numbers; the
192savings in CPU and memory usage that are usually the reason for using
193these is dwarfed by the overhead of using objects in Python, so there
194is no reason to complicate the language with two kinds of floating
195point numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000196\obindex{floating point}
197\indexii{floating point}{number}
198\indexii{C}{language}
199
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000200\item[Complex numbers]
201These represent complex numbers as a pair of machine-level double
202precision floating point numbers. The same caveats apply as for
203floating point numbers. The real and imaginary value of a complex
204number \code{z} can be retrieved through the attributes \code{z.real}
205and \code{z.imag}.
206\obindex{complex}
207\indexii{complex}{number}
208
Fred Drakef6669171998-05-06 19:52:49 +0000209\end{description} % Numbers
210
211\item[Sequences]
212These represent finite ordered sets indexed by natural numbers.
213The built-in function \function{len()}\bifuncindex{len} returns the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000214number of items of a sequence.
215When the lenth of a sequence is \var{n}, the
216index set contains the numbers 0, 1, \ldots, \var{n}-1. Item
Fred Drakef6669171998-05-06 19:52:49 +0000217\var{i} of sequence \var{a} is selected by \code{\var{a}[\var{i}]}.
218\obindex{seqence}
219\index{index operation}
220\index{item selection}
221\index{subscription}
222
223Sequences also support slicing: \code{\var{a}[\var{i}:\var{j}]}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000224selects all items with index \var{k} such that \var{i} \code{<=}
Fred Drakef6669171998-05-06 19:52:49 +0000225\var{k} \code{<} \var{j}. When used as an expression, a slice is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000226sequence of the same type. This implies that the index set is
227renumbered so that it starts at 0.
Fred Drakef6669171998-05-06 19:52:49 +0000228\index{slicing}
229
230Sequences are distinguished according to their mutability:
231
232\begin{description}
Fred Drake4856d011999-01-12 04:15:20 +0000233
Fred Drakef6669171998-05-06 19:52:49 +0000234\item[Immutable sequences]
235An object of an immutable sequence type cannot change once it is
236created. (If the object contains references to other objects,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000237these other objects may be mutable and may be changed; however,
Fred Drakef6669171998-05-06 19:52:49 +0000238the collection of objects directly referenced by an immutable object
239cannot change.)
240\obindex{immutable sequence}
241\obindex{immutable}
242
243The following types are immutable sequences:
244
245\begin{description}
246
247\item[Strings]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000248The items of a string are characters. There is no separate
249character type; a character is represented by a string of one item.
Fred Drakef6669171998-05-06 19:52:49 +0000250Characters represent (at least) 8-bit bytes. The built-in
251functions \function{chr()}\bifuncindex{chr} and
252\function{ord()}\bifuncindex{ord} convert between characters and
253nonnegative integers representing the byte values. Bytes with the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000254values 0-127 usually represent the corresponding \ASCII{} values, but
255the interpretation of values is up to the program. The string
256data type is also used to represent arrays of bytes, e.g., to hold data
Fred Drakef6669171998-05-06 19:52:49 +0000257read from a file.
258\obindex{string}
259\index{character}
260\index{byte}
Fred Drake5c07d9b1998-05-14 19:37:06 +0000261\index{ASCII@\ASCII{}}
Fred Drakef6669171998-05-06 19:52:49 +0000262
263(On systems whose native character set is not \ASCII{}, strings may use
264EBCDIC in their internal representation, provided the functions
265\function{chr()} and \function{ord()} implement a mapping between \ASCII{} and
266EBCDIC, and string comparison preserves the \ASCII{} order.
267Or perhaps someone can propose a better rule?)
Fred Drake5c07d9b1998-05-14 19:37:06 +0000268\index{ASCII@\ASCII{}}
Fred Drakef6669171998-05-06 19:52:49 +0000269\index{EBCDIC}
270\index{character set}
271\indexii{string}{comparison}
272\bifuncindex{chr}
273\bifuncindex{ord}
274
275\item[Tuples]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000276The items of a tuple are arbitrary Python objects.
277Tuples of two or more items are formed by comma-separated lists
278of expressions. A tuple of one item (a `singleton') can be formed
Fred Drakef6669171998-05-06 19:52:49 +0000279by affixing a comma to an expression (an expression by itself does
280not create a tuple, since parentheses must be usable for grouping of
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000281expressions). An empty tuple can be formed by an empty pair of
Fred Drakef6669171998-05-06 19:52:49 +0000282parentheses.
283\obindex{tuple}
284\indexii{singleton}{tuple}
285\indexii{empty}{tuple}
286
287\end{description} % Immutable sequences
288
289\item[Mutable sequences]
290Mutable sequences can be changed after they are created. The
291subscription and slicing notations can be used as the target of
292assignment and \keyword{del} (delete) statements.
293\obindex{mutable sequece}
294\obindex{mutable}
295\indexii{assignment}{statement}
296\index{delete}
297\stindex{del}
298\index{subscription}
299\index{slicing}
300
301There is currently a single mutable sequence type:
302
303\begin{description}
304
305\item[Lists]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000306The items of a list are arbitrary Python objects. Lists are formed
Fred Drakef6669171998-05-06 19:52:49 +0000307by placing a comma-separated list of expressions in square brackets.
308(Note that there are no special cases needed to form lists of length 0
309or 1.)
310\obindex{list}
311
312\end{description} % Mutable sequences
313
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000314The extension module \module{array}\refstmodindex{array} provides an
315additional example of a mutable sequence type.
316
317
Fred Drakef6669171998-05-06 19:52:49 +0000318\end{description} % Sequences
319
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000320\item[Mappings]
Fred Drakef6669171998-05-06 19:52:49 +0000321These represent finite sets of objects indexed by arbitrary index sets.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000322The subscript notation \code{a[k]} selects the item indexed
Fred Drakef6669171998-05-06 19:52:49 +0000323by \code{k} from the mapping \code{a}; this can be used in
324expressions and as the target of assignments or \keyword{del} statements.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000325The built-in function \function{len()} returns the number of items
Fred Drakef6669171998-05-06 19:52:49 +0000326in a mapping.
327\bifuncindex{len}
328\index{subscription}
329\obindex{mapping}
330
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000331There is currently a single intrinsic mapping type:
Fred Drakef6669171998-05-06 19:52:49 +0000332
333\begin{description}
334
335\item[Dictionaries]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000336These represent finite sets of objects indexed by nearly arbitrary
Fred Drakef6669171998-05-06 19:52:49 +0000337values. The only types of values not acceptable as keys are values
338containing lists or dictionaries or other mutable types that are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000339compared by value rather than by object identity, the reason being
340that the efficient implementation of dictionaries requires a key's
341hash value to remain constant.
Fred Drakef6669171998-05-06 19:52:49 +0000342Numeric types used for keys obey the normal rules for numeric
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000343comparison: if two numbers compare equal (e.g., \code{1} and
Fred Drakef6669171998-05-06 19:52:49 +0000344\code{1.0}) then they can be used interchangeably to index the same
345dictionary entry.
346
347Dictionaries are mutable; they are created by the \code{...}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000348notation (see section \ref{dict}, ``Dictionary Displays'').
Fred Drakef6669171998-05-06 19:52:49 +0000349\obindex{dictionary}
350\obindex{mutable}
351
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000352The extension modules \module{dbm}\refstmodindex{dbm},
353\module{gdbm}\refstmodindex{gdbm}, \module{bsddb}\refstmodindex{bsddb}
354provide additional examples of mapping types.
355
Fred Drakef6669171998-05-06 19:52:49 +0000356\end{description} % Mapping types
357
358\item[Callable types]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000359These are the types to which the function call operation (see section
360\ref{calls}, ``Calls'') can be applied:
Fred Drakef6669171998-05-06 19:52:49 +0000361\indexii{function}{call}
362\index{invocation}
363\indexii{function}{argument}
364\obindex{callable}
365
366\begin{description}
367
368\item[User-defined functions]
369A user-defined function object is created by a function definition
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000370(see section \ref{function}, ``Function definitions''). It should be
371called with an argument
Fred Drakef6669171998-05-06 19:52:49 +0000372list containing the same number of items as the function's formal
373parameter list.
374\indexii{user-defined}{function}
375\obindex{function}
376\obindex{user-defined function}
377
Fred Drake82385871998-10-01 20:40:43 +0000378Special read-only attributes: \member{func_doc} or \member{__doc__} is the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000379function's documentation string, or None if unavailable;
Fred Drake82385871998-10-01 20:40:43 +0000380\member{func_name} or \member{__name__} is the function's name;
381\member{func_defaults} is a tuple containing default argument values for
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000382those arguments that have defaults, or \code{None} if no arguments
Fred Drake82385871998-10-01 20:40:43 +0000383have a default value; \member{func_code} is the code object representing
384the compiled function body; \member{func_globals} is (a reference to)
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000385the dictionary that holds the function's global variables --- it
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000386defines the global namespace of the module in which the function was
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000387defined. Additional information about a function's definition can be
388retrieved from its code object; see the description of internal types
389below.
Fred Drake4856d011999-01-12 04:15:20 +0000390\withsubitem{(function attribute)}{
391 \ttindex{func_doc}
392 \ttindex{__doc__}
393 \ttindex{__name__}
394 \ttindex{func_defaults}
395 \ttindex{func_code}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000396 \ttindex{func_globals}}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000397\indexii{global}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000398
399\item[User-defined methods]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000400A user-defined method object combines a class, a class instance (or
401\code{None}) and a user-defined function.
Fred Drakef6669171998-05-06 19:52:49 +0000402\obindex{method}
403\obindex{user-defined method}
404\indexii{user-defined}{method}
Fred Drakef6669171998-05-06 19:52:49 +0000405
406Special read-only attributes: \member{im_self} is the class instance
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000407object, \member{im_func} is the function object;
Fred Drake82385871998-10-01 20:40:43 +0000408\member{im_class} is the class that defined the method (which may be a
409base class of the class of which \member{im_self} is an instance);
410\member{__doc__} is the method's documentation (same as
411\code{im_func.__doc__}); \member{__name__} is the method name (same as
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000412\code{im_func.__name__}).
Fred Drake4856d011999-01-12 04:15:20 +0000413\withsubitem{(method attribute)}{
414 \ttindex{im_func}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000415 \ttindex{im_self}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000416
417User-defined method objects are created in two ways: when getting an
418attribute of a class that is a user-defined function object, or when
419getting an attributes of a class instance that is a user-defined
420function object. In the former case (class attribute), the
Fred Drake82385871998-10-01 20:40:43 +0000421\member{im_self} attribute is \code{None}, and the method object is said
422to be unbound; in the latter case (instance attribute), \method{im_self}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000423is the instance, and the method object is said to be bound. For
Fred Drake82385871998-10-01 20:40:43 +0000424instance, when \class{C} is a class which contains a definition for a
425function \method{f()}, \code{C.f} does not yield the function object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000426\code{f}; rather, it yields an unbound method object \code{m} where
Fred Drake82385871998-10-01 20:40:43 +0000427\code{m.im_class} is \class{C}, \code{m.im_func} is \method{f()}, and
428\code{m.im_self} is \code{None}. When \code{x} is a \class{C}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000429instance, \code{x.f} yields a bound method object \code{m} where
Fred Drake82385871998-10-01 20:40:43 +0000430\code{m.im_class} is \code{C}, \code{m.im_func} is \method{f()}, and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000431\code{m.im_self} is \code{x}.
Fred Drake4856d011999-01-12 04:15:20 +0000432\withsubitem{(method attribute)}{
433 \ttindex{im_class}
434 \ttindex{im_func}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000435 \ttindex{im_self}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000436
437When an unbound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000438function (\member{im_func}) is called, with the restriction that the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000439first argument must be an instance of the proper class
Fred Drake82385871998-10-01 20:40:43 +0000440(\member{im_class}) or of a derived class thereof.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000441
442When a bound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000443function (\member{im_func}) is called, inserting the class instance
444(\member{im_self}) in front of the argument list. For instance, when
445\class{C} is a class which contains a definition for a function
446\method{f()}, and \code{x} is an instance of \class{C}, calling
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000447\code{x.f(1)} is equivalent to calling \code{C.f(x, 1)}.
448
449Note that the transformation from function object to (unbound or
450bound) method object happens each time the attribute is retrieved from
451the class or instance. In some cases, a fruitful optimization is to
452assign the attribute to a local variable and call that local variable.
453Also notice that this transformation only happens for user-defined
454functions; other callable objects (and all non-callable objects) are
455retrieved without transformation.
456
Fred Drakef6669171998-05-06 19:52:49 +0000457\item[Built-in functions]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000458A built-in function object is a wrapper around a \C{} function. Examples
459of built-in functions are \function{len()} and \function{math.sin()}
460(\module{math} is a standard built-in module).
461The number and type of the arguments are
Fred Drakef6669171998-05-06 19:52:49 +0000462determined by the C function.
Fred Drake82385871998-10-01 20:40:43 +0000463Special read-only attributes: \member{__doc__} is the function's
464documentation string, or \code{None} if unavailable; \member{__name__}
465is the function's name; \member{__self__} is set to \code{None} (but see
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000466the next item).
Fred Drakef6669171998-05-06 19:52:49 +0000467\obindex{built-in function}
468\obindex{function}
469\indexii{C}{language}
470
471\item[Built-in methods]
472This is really a different disguise of a built-in function, this time
473containing an object passed to the \C{} function as an implicit extra
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000474argument. An example of a built-in method is
475\code{\var{list}.append()}, assuming
Fred Drakef6669171998-05-06 19:52:49 +0000476\var{list} is a list object.
Fred Drake82385871998-10-01 20:40:43 +0000477In this case, the special read-only attribute \member{__self__} is set
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000478to the object denoted by \code{list}.
Fred Drakef6669171998-05-06 19:52:49 +0000479\obindex{built-in method}
480\obindex{method}
481\indexii{built-in}{method}
482
483\item[Classes]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000484Class objects are described below. When a class object is called,
485a new class instance (also described below) is created and
Fred Drakef6669171998-05-06 19:52:49 +0000486returned. This implies a call to the class's \method{__init__()} method
487if it has one. Any arguments are passed on to the \method{__init__()}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000488method. If there is no \method{__init__()} method, the class must be called
Fred Drakef6669171998-05-06 19:52:49 +0000489without arguments.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000490\withsubitem{(object method)}{\ttindex{__init__()}}
Fred Drakef6669171998-05-06 19:52:49 +0000491\obindex{class}
492\obindex{class instance}
493\obindex{instance}
494\indexii{class object}{call}
495
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000496\item[Class instances]
497Class instances are described below. Class instances are callable
Fred Drake82385871998-10-01 20:40:43 +0000498only when the class has a \method{__call__()} method; \code{x(arguments)}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000499is a shorthand for \code{x.__call__(arguments)}.
500
Fred Drakef6669171998-05-06 19:52:49 +0000501\end{description}
502
503\item[Modules]
504Modules are imported by the \keyword{import} statement (see section
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000505\ref{import}, ``The \keyword{import} statement'').
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000506A module object has a namespace implemented by a dictionary object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000507(this is the dictionary referenced by the func_globals attribute of
508functions defined in the module). Attribute references are translated
509to lookups in this dictionary, e.g., \code{m.x} is equivalent to
510\code{m.__dict__["x"]}.
511A module object does not contain the code object used to
Fred Drakef6669171998-05-06 19:52:49 +0000512initialize the module (since it isn't needed once the initialization
513is done).
514\stindex{import}
515\obindex{module}
516
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000517Attribute assignment updates the module's namespace dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000518e.g., \samp{m.x = 1} is equivalent to \samp{m.__dict__["x"] = 1}.
Fred Drakef6669171998-05-06 19:52:49 +0000519
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000520Special read-only attribute: \member{__dict__} is the module's
521namespace as a dictionary object.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000522\withsubitem{(module attribute)}{\ttindex{__dict__}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000523
524Predefined (writable) attributes: \member{__name__}
525is the module's name; \member{__doc__} is the
526module's documentation string, or
Fred Drake82385871998-10-01 20:40:43 +0000527\code{None} if unavailable; \member{__file__} is the pathname of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000528file from which the module was loaded, if it was loaded from a file.
Fred Drake82385871998-10-01 20:40:43 +0000529The \member{__file__} attribute is not present for C{} modules that are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000530statically linked into the interpreter; for extension modules loaded
531dynamically from a shared library, it is the pathname of the shared
532library file.
Fred Drake4856d011999-01-12 04:15:20 +0000533\withsubitem{(module attribute)}{
534 \ttindex{__name__}
535 \ttindex{__doc__}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000536 \ttindex{__file__}}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000537\indexii{module}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000538
539\item[Classes]
540Class objects are created by class definitions (see section
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000541\ref{class}, ``Class definitions'').
542A class has a namespace implemented by a dictionary object.
543Class attribute references are translated to
544lookups in this dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000545e.g., \samp{C.x} is translated to \samp{C.__dict__["x"]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000546When the attribute name is not found
Fred Drakef6669171998-05-06 19:52:49 +0000547there, the attribute search continues in the base classes. The search
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000548is depth-first, left-to-right in the order of occurrence in the
Fred Drakef6669171998-05-06 19:52:49 +0000549base class list.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000550When a class attribute reference would yield a user-defined function
551object, it is transformed into an unbound user-defined method object
Fred Drake82385871998-10-01 20:40:43 +0000552(see above). The \member{im_class} attribute of this method object is the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000553class in which the function object was found, not necessarily the
554class for which the attribute reference was initiated.
Fred Drakef6669171998-05-06 19:52:49 +0000555\obindex{class}
556\obindex{class instance}
557\obindex{instance}
558\indexii{class object}{call}
559\index{container}
560\obindex{dictionary}
561\indexii{class}{attribute}
562
563Class attribute assignments update the class's dictionary, never the
564dictionary of a base class.
565\indexiii{class}{attribute}{assignment}
566
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000567A class object can be called (see above) to yield a class instance (see
568below).
Fred Drakef6669171998-05-06 19:52:49 +0000569\indexii{class object}{call}
570
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000571Special attributes: \member{__name__} is the class name;
572\member{__module__} is the module name in which the class was defined;
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000573\member{__dict__} is the dictionary containing the class's namespace;
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000574\member{__bases__} is a tuple (possibly empty or a singleton)
575containing the base classes, in the order of their occurrence in the
Fred Drake82385871998-10-01 20:40:43 +0000576base class list; \member{__doc__} is the class's documentation string,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000577or None if undefined.
Fred Drake4856d011999-01-12 04:15:20 +0000578\withsubitem{(class attribute)}{
579 \ttindex{__name__}
580 \ttindex{__module__}
581 \ttindex{__dict__}
582 \ttindex{__bases__}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000583 \ttindex{__doc__}}
Fred Drakef6669171998-05-06 19:52:49 +0000584
585\item[Class instances]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000586A class instance is created by calling a class object (see above).
587A class instance has a namespace implemented as a dictionary which
588is the first place in which
Fred Drakef6669171998-05-06 19:52:49 +0000589attribute references are searched. When an attribute is not found
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000590there, and the instance's class has an attribute by that name,
591the search continues with the class attributes. If a class attribute
592is found that is a user-defined function object (and in no other
593case), it is transformed into an unbound user-defined method object
Fred Drake82385871998-10-01 20:40:43 +0000594(see above). The \member{im_class} attribute of this method object is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000595the class in which the function object was found, not necessarily the
596class of the instance for which the attribute reference was initiated.
597If no class attribute is found, and the object's class has a
Fred Drake82385871998-10-01 20:40:43 +0000598\method{__getattr__()} method, that is called to satisfy the lookup.
Fred Drakef6669171998-05-06 19:52:49 +0000599\obindex{class instance}
600\obindex{instance}
601\indexii{class}{instance}
602\indexii{class instance}{attribute}
603
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000604Attribute assignments and deletions update the instance's dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000605never a class's dictionary. If the class has a \method{__setattr__()} or
606\method{__delattr__()} method, this is called instead of updating the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000607instance dictionary directly.
Fred Drakef6669171998-05-06 19:52:49 +0000608\indexiii{class instance}{attribute}{assignment}
609
610Class instances can pretend to be numbers, sequences, or mappings if
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000611they have methods with certain special names. See
612section \ref{specialnames}, ``Special method names.''
Fred Drakef6669171998-05-06 19:52:49 +0000613\obindex{number}
614\obindex{sequence}
615\obindex{mapping}
616
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000617Special attributes: \member{__dict__} is the attribute
618dictionary; \member{__class__} is the instance's class.
Fred Drake4856d011999-01-12 04:15:20 +0000619\withsubitem{(instance attribute)}{
620 \ttindex{__dict__}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000621 \ttindex{__class__}}
Fred Drakef6669171998-05-06 19:52:49 +0000622
623\item[Files]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000624A file object represents an open file. File objects are created by the
625\function{open()} built-in function, and also by
626\function{os.popen()}, \function{os.fdopen()}, and the
627\method{makefile()} method of socket objects (and perhaps by other
628functions or methods provided by extension modules). The objects
629\code{sys.stdin}, \code{sys.stdout} and \code{sys.stderr} are
630initialized to file objects corresponding to the interpreter's
631standard input, output and error streams. See the \emph{Python
632Library Reference} for complete documentation of file objects.
Fred Drakef6669171998-05-06 19:52:49 +0000633\obindex{file}
634\indexii{C}{language}
635\index{stdio}
636\bifuncindex{open}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000637\withsubitem{(in module os)}{\ttindex{popen()}}
638\withsubitem{(socket method)}{\ttindex{makefile()}}
Fred Drake4856d011999-01-12 04:15:20 +0000639\withsubitem{(in module sys)}{
640 \ttindex{stdin}
641 \ttindex{stdout}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000642 \ttindex{stderr}}
Fred Drakef6669171998-05-06 19:52:49 +0000643\ttindex{sys.stdin}
644\ttindex{sys.stdout}
645\ttindex{sys.stderr}
646
647\item[Internal types]
648A few types used internally by the interpreter are exposed to the user.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000649Their definitions may change with future versions of the interpreter,
Fred Drakef6669171998-05-06 19:52:49 +0000650but they are mentioned here for completeness.
651\index{internal type}
652\index{types, internal}
653
654\begin{description}
655
656\item[Code objects]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000657Code objects represent \emph{byte-compiled} executable Python code, or
658\emph{bytecode}.
Fred Drakef6669171998-05-06 19:52:49 +0000659The difference between a code
660object and a function object is that the function object contains an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000661explicit reference to the function's globals (the module in which it
662was defined), while a code object contains no context;
663also the default argument values are stored in the function object,
664not in the code object (because they represent values calculated at
665run-time). Unlike function objects, code objects are immutable and
666contain no references (directly or indirectly) to mutable objects.
667\index{bytecode}
Fred Drakef6669171998-05-06 19:52:49 +0000668\obindex{code}
669
Fred Drake1e42d8a1998-11-25 17:58:50 +0000670Special read-only attributes: \member{co_name} gives the function
671name; \member{co_argcount} is the number of positional arguments
672(including arguments with default values); \member{co_nlocals} is the
673number of local variables used by the function (including arguments);
674\member{co_varnames} is a tuple containing the names of the local
675variables (starting with the argument names); \member{co_code} is a
676string representing the sequence of bytecode instructions;
677\member{co_consts} is a tuple containing the literals used by the
678bytecode; \member{co_names} is a tuple containing the names used by
679the bytecode; \member{co_filename} is the filename from which the code
680was compiled; \member{co_firstlineno} is the first line number of the
681function; \member{co_lnotab} is a string encoding the mapping from
682byte code offsets to line numbers (for detais see the source code of
683the interpreter); \member{co_stacksize} is the required stack size
684(including local variables); \member{co_flags} is an integer encoding
685a number of flags for the interpreter.
Fred Drake4856d011999-01-12 04:15:20 +0000686\withsubitem{(code object attribute)}{
687 \ttindex{co_argcount}
688 \ttindex{co_code}
689 \ttindex{co_consts}
690 \ttindex{co_filename}
691 \ttindex{co_firstlineno}
692 \ttindex{co_flags}
693 \ttindex{co_lnotab}
694 \ttindex{co_name}
695 \ttindex{co_names}
696 \ttindex{co_nlocals}
697 \ttindex{co_stacksize}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000698 \ttindex{co_varnames}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000699
Fred Drake82385871998-10-01 20:40:43 +0000700The following flag bits are defined for \member{co_flags}: bit 2 is set
701if the function uses the \samp{*arguments} syntax to accept an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000702arbitrary number of positional arguments; bit 3 is set if the function
Fred Drake82385871998-10-01 20:40:43 +0000703uses the \samp{**keywords} syntax to accept arbitrary keyword
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000704arguments; other bits are used internally or reserved for future use.
705If a code object represents a function, the first item in
Fred Drake82385871998-10-01 20:40:43 +0000706\member{co_consts} is the documentation string of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000707function, or \code{None} if undefined.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000708\index{documentation string}
Fred Drakef6669171998-05-06 19:52:49 +0000709
710\item[Frame objects]
711Frame objects represent execution frames. They may occur in traceback
712objects (see below).
713\obindex{frame}
714
715Special read-only attributes: \member{f_back} is to the previous
716stack frame (towards the caller), or \code{None} if this is the bottom
717stack frame; \member{f_code} is the code object being executed in this
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000718frame; \member{f_locals} is the dictionary used to look up local
719variables; \member{f_globals} is used for global variables;
Fred Drake82385871998-10-01 20:40:43 +0000720\member{f_builtins} is used for built-in (intrinsic) names;
721\member{f_restricted} is a flag indicating whether the function is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000722executing in restricted execution mode;
Fred Drakef6669171998-05-06 19:52:49 +0000723\member{f_lineno} gives the line number and \member{f_lasti} gives the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000724precise instruction (this is an index into the bytecode string of
Fred Drakef6669171998-05-06 19:52:49 +0000725the code object).
Fred Drake4856d011999-01-12 04:15:20 +0000726\withsubitem{(frame attribute)}{
727 \ttindex{f_back}
728 \ttindex{f_code}
729 \ttindex{f_globals}
730 \ttindex{f_locals}
731 \ttindex{f_lineno}
732 \ttindex{f_lasti}
733 \ttindex{f_builtins}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000734 \ttindex{f_restricted}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000735
Fred Drake82385871998-10-01 20:40:43 +0000736Special writable attributes: \member{f_trace}, if not \code{None}, is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000737function called at the start of each source code line (this is used by
Fred Drake82385871998-10-01 20:40:43 +0000738the debugger); \member{f_exc_type}, \member{f_exc_value},
739\member{f_exc_traceback} represent the most recent exception caught in
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000740this frame.
Fred Drake4856d011999-01-12 04:15:20 +0000741\withsubitem{(frame attribute)}{
742 \ttindex{f_trace}
743 \ttindex{f_exc_type}
744 \ttindex{f_exc_value}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000745 \ttindex{f_exc_traceback}}
Fred Drakef6669171998-05-06 19:52:49 +0000746
747\item[Traceback objects] \label{traceback}
748Traceback objects represent a stack trace of an exception. A
749traceback object is created when an exception occurs. When the search
750for an exception handler unwinds the execution stack, at each unwound
751level a traceback object is inserted in front of the current
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000752traceback. When an exception handler is entered, the stack trace is
753made available to the program.
754(See section \ref{try}, ``The \code{try} statement.'')
755It is accessible as \code{sys.exc_traceback}, and also as the third
756item of the tuple returned by \code{sys.exc_info()}. The latter is
757the preferred interface, since it works correctly when the program is
758using multiple threads.
759When the program contains no suitable handler, the stack trace is written
Fred Drakef6669171998-05-06 19:52:49 +0000760(nicely formatted) to the standard error stream; if the interpreter is
761interactive, it is also made available to the user as
762\code{sys.last_traceback}.
763\obindex{traceback}
764\indexii{stack}{trace}
765\indexii{exception}{handler}
766\indexii{execution}{stack}
Fred Drake4856d011999-01-12 04:15:20 +0000767\withsubitem{(in module sys)}{
768 \ttindex{exc_info}
769 \ttindex{exc_traceback}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000770 \ttindex{last_traceback}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000771\ttindex{sys.exc_info}
Fred Drakef6669171998-05-06 19:52:49 +0000772\ttindex{sys.exc_traceback}
773\ttindex{sys.last_traceback}
774
775Special read-only attributes: \member{tb_next} is the next level in the
776stack trace (towards the frame where the exception occurred), or
777\code{None} if there is no next level; \member{tb_frame} points to the
778execution frame of the current level; \member{tb_lineno} gives the line
779number where the exception occurred; \member{tb_lasti} indicates the
780precise instruction. The line number and last instruction in the
781traceback may differ from the line number of its frame object if the
782exception occurred in a \keyword{try} statement with no matching
783except clause or with a finally clause.
Fred Drake4856d011999-01-12 04:15:20 +0000784\withsubitem{(traceback attribute)}{
785 \ttindex{tb_next}
786 \ttindex{tb_frame}
787 \ttindex{tb_lineno}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000788 \ttindex{tb_lasti}}
Fred Drakef6669171998-05-06 19:52:49 +0000789\stindex{try}
790
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000791\item[Slice objects]
792Slice objects are used to represent slices when \emph{extended slice
793syntax} is used. This is a slice using two colons, or multiple slices
794or ellipses separated by commas, e.g., \code{a[i:j:step]}, \code{a[i:j,
795k:l]}, or \code{a[..., i:j])}. They are also created by the built-in
Fred Drake1e42d8a1998-11-25 17:58:50 +0000796\function{slice()}\bifuncindex{slice} function.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000797
Fred Drake82385871998-10-01 20:40:43 +0000798Special read-only attributes: \member{start} is the lowerbound;
799\member{stop} is the upperbound; \member{step} is the step value; each is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000800\code{None} if omitted. These attributes can have any type.
Fred Drake4856d011999-01-12 04:15:20 +0000801\withsubitem{(slice object attribute)}{
802 \ttindex{start}
803 \ttindex{stop}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000804 \ttindex{step}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000805
Fred Drakef6669171998-05-06 19:52:49 +0000806\end{description} % Internal types
807
808\end{description} % Types
809
810
Fred Drake61c77281998-07-28 19:34:22 +0000811\section{Special method names\label{specialnames}}
Fred Drakef6669171998-05-06 19:52:49 +0000812
813A class can implement certain operations that are invoked by special
Fred Draked82575d1998-08-28 20:03:12 +0000814syntax (such as arithmetic operations or subscripting and slicing) by
815defining methods with special names. For instance, if a class defines
816a method named \method{__getitem__()}, and \code{x} is an instance of
817this class, then \code{x[i]} is equivalent to
818\code{x.__getitem__(i)}. (The reverse is not true --- if \code{x} is
819a list object, \code{x.__getitem__(i)} is not equivalent to
820\code{x[i]}.) Except where mentioned, attempts to execute an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000821operation raise an exception when no appropriate method is defined.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000822\withsubitem{(mapping object method)}{\ttindex{__getitem__()}}
Fred Drakef6669171998-05-06 19:52:49 +0000823
Fred Drakef6669171998-05-06 19:52:49 +0000824
Fred Drake61c77281998-07-28 19:34:22 +0000825\subsection{Basic customization\label{customization}}
Fred Drakef6669171998-05-06 19:52:49 +0000826
Fred Drake1e42d8a1998-11-25 17:58:50 +0000827\begin{methoddesc}[object]{__init__}{self\optional{, args...}}
Fred Drakef6669171998-05-06 19:52:49 +0000828Called when the instance is created. The arguments are those passed
829to the class constructor expression. If a base class has an
Fred Drake82385871998-10-01 20:40:43 +0000830\method{__init__()} method the derived class's \method{__init__()} method must
Fred Drakef6669171998-05-06 19:52:49 +0000831explicitly call it to ensure proper initialization of the base class
Fred Draked82575d1998-08-28 20:03:12 +0000832part of the instance, e.g., \samp{BaseClass.__init__(\var{self},
833[\var{args}...])}.
Fred Drakef6669171998-05-06 19:52:49 +0000834\indexii{class}{constructor}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000835\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000836
837
Fred Drake1e42d8a1998-11-25 17:58:50 +0000838\begin{methoddesc}[object]{__del__}{self}
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000839Called when the instance is about to be destroyed. This is also
840called a destructor\index{destructor}. If a base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000841has a \method{__del__()} method, the derived class's \method{__del__()} method
Fred Drakef6669171998-05-06 19:52:49 +0000842must explicitly call it to ensure proper deletion of the base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000843part of the instance. Note that it is possible (though not recommended!)
844for the \method{__del__()}
Fred Drakef6669171998-05-06 19:52:49 +0000845method to postpone destruction of the instance by creating a new
846reference to it. It may then be called at a later time when this new
847reference is deleted. It is not guaranteed that
848\method{__del__()} methods are called for objects that still exist when
849the interpreter exits.
Fred Drakef6669171998-05-06 19:52:49 +0000850\stindex{del}
851
Fred Drake82385871998-10-01 20:40:43 +0000852\strong{Programmer's note:} \samp{del x} doesn't directly call
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000853\code{x.__del__()} --- the former decrements the reference count for
854\code{x} by one, and the latter is only called when its reference
855count reaches zero. Some common situations that may prevent the
856reference count of an object to go to zero include: circular
857references between objects (e.g., a doubly-linked list or a tree data
858structure with parent and child pointers); a reference to the object
859on the stack frame of a function that caught an exception (the
860traceback stored in \code{sys.exc_traceback} keeps the stack frame
861alive); or a reference to the object on the stack frame that raised an
862unhandled exception in interactive mode (the traceback stored in
863\code{sys.last_traceback} keeps the stack frame alive). The first
864situation can only be remedied by explicitly breaking the cycles; the
865latter two situations can be resolved by storing None in
866\code{sys.exc_traceback} or \code{sys.last_traceback}.
Fred Drakef6669171998-05-06 19:52:49 +0000867
868\strong{Warning:} due to the precarious circumstances under which
Fred Draked82575d1998-08-28 20:03:12 +0000869\method{__del__()} methods are invoked, exceptions that occur during their
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000870execution are ignored, and a warning is printed to \code{sys.stderr}
Fred Draked82575d1998-08-28 20:03:12 +0000871instead. Also, when \method{__del__()} is invoked is response to a module
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000872being deleted (e.g., when execution of the program is done), other
Fred Draked82575d1998-08-28 20:03:12 +0000873globals referenced by the \method{__del__()} method may already have been
874deleted. For this reason, \method{__del__()} methods should do the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000875absolute minimum needed to maintain external invariants. Python 1.5
876guarantees that globals whose name begins with a single underscore are
877deleted from their module before other globals are deleted; if no
878other references to such globals exist, this may help in assuring that
879imported modules are still available at the time when the
Fred Draked82575d1998-08-28 20:03:12 +0000880\method{__del__()} method is called.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000881\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000882
Fred Drake1e42d8a1998-11-25 17:58:50 +0000883\begin{methoddesc}[object]{__repr__}{self}
Fred Drake82385871998-10-01 20:40:43 +0000884Called by the \function{repr()}\bifuncindex{repr} built-in function
885and by string conversions (reverse quotes) to compute the ``official''
886string representation of an object. This should normally look like a
887valid Python expression that can be used to recreate an object with
888the same value. By convention, objects which cannot be trivially
889converted to strings which can be used to create a similar object
890produce a string of the form \samp{<\var{...some useful
891description...}>}.
Fred Drakef6669171998-05-06 19:52:49 +0000892\indexii{string}{conversion}
893\indexii{reverse}{quotes}
894\indexii{backward}{quotes}
895\index{back-quotes}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000896\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000897
Fred Drake1e42d8a1998-11-25 17:58:50 +0000898\begin{methoddesc}[object]{__str__}{self}
Fred Draked82575d1998-08-28 20:03:12 +0000899Called by the \function{str()}\bifuncindex{str} built-in function and
900by the \keyword{print}\stindex{print} statement to compute the
Fred Drake82385871998-10-01 20:40:43 +0000901``informal'' string representation of an object. This differs from
902\method{__repr__()} in that it does not have to be a valid Python
903expression: a more convenient or concise representation may be used
904instead.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000905\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000906
Fred Drake1e42d8a1998-11-25 17:58:50 +0000907\begin{methoddesc}[object]{__cmp__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000908Called by all comparison operations. Should return a negative integer if
909\code{self < other}, zero if \code{self == other}, a positive integer if
Fred Drakef6669171998-05-06 19:52:49 +0000910\code{self > other}. If no \method{__cmp__()} operation is defined, class
911instances are compared by object identity (``address'').
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000912(Note: the restriction that exceptions are not propagated by
Fred Drake82385871998-10-01 20:40:43 +0000913\method{__cmp__()} has been removed in Python 1.5.)
Fred Drakef6669171998-05-06 19:52:49 +0000914\bifuncindex{cmp}
915\index{comparisons}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000916\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000917
Fred Drake1e42d8a1998-11-25 17:58:50 +0000918\begin{methoddesc}[object]{__hash__}{self}
Fred Draked82575d1998-08-28 20:03:12 +0000919Called for the key object for dictionary\obindex{dictionary}
920operations, and by the built-in function
Fred Drakef6669171998-05-06 19:52:49 +0000921\function{hash()}\bifuncindex{hash}. Should return a 32-bit integer
922usable as a hash value
923for dictionary operations. The only required property is that objects
924which compare equal have the same hash value; it is advised to somehow
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000925mix together (e.g., using exclusive or) the hash values for the
Fred Drakef6669171998-05-06 19:52:49 +0000926components of the object that also play a part in comparison of
927objects. If a class does not define a \method{__cmp__()} method it should
928not define a \method{__hash__()} operation either; if it defines
929\method{__cmp__()} but not \method{__hash__()} its instances will not be
930usable as dictionary keys. If a class defines mutable objects and
931implements a \method{__cmp__()} method it should not implement
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000932\method{__hash__()}, since the dictionary implementation requires that
933a key's hash value is immutable (if the object's hash value changes, it
934will be in the wrong hash bucket).
Fred Drake1e42d8a1998-11-25 17:58:50 +0000935\withsubitem{(object method)}{\ttindex{__cmp__()}}
936\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000937
Fred Drake1e42d8a1998-11-25 17:58:50 +0000938\begin{methoddesc}[object]{__nonzero__}{self}
Fred Draked82575d1998-08-28 20:03:12 +0000939Called to implement truth value testing; should return \code{0} or
940\code{1}. When this method is not defined, \method{__len__()} is
941called, if it is defined (see below). If a class defines neither
942\method{__len__()} nor \method{__nonzero__()}, all its instances are
943considered true.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000944\withsubitem{(mapping object method)}{\ttindex{__len__()}}
945\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000946
947
Fred Drake61c77281998-07-28 19:34:22 +0000948\subsection{Customizing attribute access\label{attribute-access}}
Fred Drakef6669171998-05-06 19:52:49 +0000949
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000950The following methods can be defined to customize the meaning of
951attribute access (use of, assignment to, or deletion of \code{x.name})
952for class instances.
953For performance reasons, these methods are cached in the class object
954at class definition time; therefore, they cannot be changed after the
955class definition is executed.
Fred Drakef6669171998-05-06 19:52:49 +0000956
Fred Drake1e42d8a1998-11-25 17:58:50 +0000957\begin{methoddesc}[object]{__getattr__}{self, name}
Fred Drakef6669171998-05-06 19:52:49 +0000958Called when an attribute lookup has not found the attribute in the
959usual places (i.e. it is not an instance attribute nor is it found in
960the class tree for \code{self}). \code{name} is the attribute name.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000961This method should return the (computed) attribute value or raise an
Fred Draked82575d1998-08-28 20:03:12 +0000962\exception{AttributeError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000963
964Note that if the attribute is found through the normal mechanism,
Fred Draked82575d1998-08-28 20:03:12 +0000965\method{__getattr__()} is not called. (This is an intentional
966asymmetry between \method{__getattr__()} and \method{__setattr__()}.)
Fred Drakef6669171998-05-06 19:52:49 +0000967This is done both for efficiency reasons and because otherwise
Fred Draked82575d1998-08-28 20:03:12 +0000968\method{__setattr__()} would have no way to access other attributes of
969the instance.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000970Note that at least for instance variables, you can fake
971total control by not inserting any values in the instance
972attribute dictionary (but instead inserting them in another object).
Fred Drake1e42d8a1998-11-25 17:58:50 +0000973\withsubitem{(object method)}{\ttindex{__setattr__()}}
974\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000975
Fred Drake1e42d8a1998-11-25 17:58:50 +0000976\begin{methoddesc}[object]{__setattr__}{self, name, value}
Fred Drakef6669171998-05-06 19:52:49 +0000977Called when an attribute assignment is attempted. This is called
Fred Draked82575d1998-08-28 20:03:12 +0000978instead of the normal mechanism (i.e.\ store the value in the instance
979dictionary). \var{name} is the attribute name, \var{value} is the
Fred Drakef6669171998-05-06 19:52:49 +0000980value to be assigned to it.
Fred Drakef6669171998-05-06 19:52:49 +0000981
Fred Draked82575d1998-08-28 20:03:12 +0000982If \method{__setattr__()} wants to assign to an instance attribute, it
983should not simply execute \samp{self.\var{name} = value} --- this
984would cause a recursive call to itself. Instead, it should insert the
985value in the dictionary of instance attributes, e.g.,
986\samp{self.__dict__[\var{name}] = value}.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000987\withsubitem{(instance attribute)}{\ttindex{__dict__}}
988\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000989
Fred Drake1e42d8a1998-11-25 17:58:50 +0000990\begin{methoddesc}[object]{__delattr__}{self, name}
Fred Draked82575d1998-08-28 20:03:12 +0000991Like \method{__setattr__()} but for attribute deletion instead of
Fred Drake1e42d8a1998-11-25 17:58:50 +0000992assignment. This should only be implemented if \samp{del
993obj.\var{name}} is meaningful for the object.
994\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000995
996
Fred Drake61c77281998-07-28 19:34:22 +0000997\subsection{Emulating callable objects\label{callable-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000998
Fred Drake1e42d8a1998-11-25 17:58:50 +0000999\begin{methoddesc}[object]{__call__}{self\optional{, args...}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001000Called when the instance is ``called'' as a function; if this method
Fred Draked82575d1998-08-28 20:03:12 +00001001is defined, \code{\var{x}(arg1, arg2, ...)} is a shorthand for
1002\code{\var{x}.__call__(arg1, arg2, ...)}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001003\indexii{call}{instance}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001004\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001005
1006
Fred Drake61c77281998-07-28 19:34:22 +00001007\subsection{Emulating sequence and mapping types\label{sequence-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001008
1009The following methods can be defined to emulate sequence or mapping
1010objects. The first set of methods is used either to emulate a
1011sequence or to emulate a mapping; the difference is that for a
1012sequence, the allowable keys should be the integers \var{k} for which
1013\code{0 <= \var{k} < \var{N}} where \var{N} is the length of the
1014sequence, and the method \method{__getslice__()} (see below) should be
1015defined. It is also recommended that mappings provide methods
1016\method{keys()}, \method{values()}, \method{items()},
1017\method{has_key()}, \method{get()}, \method{clear()}, \method{copy()},
Fred Draked82575d1998-08-28 20:03:12 +00001018and \method{update()} behaving similar to those for
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001019Python's standard dictionary objects; mutable sequences should provide
1020methods \method{append()}, \method{count()}, \method{index()},
1021\method{insert()}, \method{pop()}, \method{remove()}, \method{reverse()}
1022and \method{sort()}, like Python standard list objects. Finally,
1023sequence types should implement addition (meaning concatenation) and
1024multiplication (meaning repetition) by defining the methods
1025\method{__add__()}, \method{__radd__()}, \method{__mul__()} and
1026\method{__rmul__()} described below; they should not define
1027\method{__coerce__()} or other numerical operators.
Fred Drake4856d011999-01-12 04:15:20 +00001028\withsubitem{(mapping object method)}{
1029 \ttindex{keys()}
1030 \ttindex{values()}
1031 \ttindex{items()}
1032 \ttindex{has_key()}
1033 \ttindex{get()}
1034 \ttindex{clear()}
1035 \ttindex{copy()}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001036 \ttindex{update()}}
Fred Drake4856d011999-01-12 04:15:20 +00001037\withsubitem{(sequence object method)}{
1038 \ttindex{append()}
1039 \ttindex{count()}
1040 \ttindex{index()}
1041 \ttindex{insert()}
1042 \ttindex{pop()}
1043 \ttindex{remove()}
1044 \ttindex{reverse()}
1045 \ttindex{sort()}
1046 \ttindex{__add__()}
1047 \ttindex{__radd__()}
1048 \ttindex{__mul__()}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001049 \ttindex{__rmul__()}}
1050\withsubitem{(numberic object method)}{\ttindex{__coerce__()}}
Fred Drakef6669171998-05-06 19:52:49 +00001051
Fred Drake1e42d8a1998-11-25 17:58:50 +00001052\begin{methoddesc}[mapping object]{__len__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001053Called to implement the built-in function
1054\function{len()}\bifuncindex{len}. Should return the length of the
1055object, an integer \code{>=} 0. Also, an object that doesn't define a
1056\method{__nonzero__()} method and whose \method{__len__()} method
1057returns zero is considered to be false in a Boolean context.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001058\withsubitem{(object method)}{\ttindex{__nonzero__()}}
1059\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001060
Fred Drake1e42d8a1998-11-25 17:58:50 +00001061\begin{methoddesc}[mapping object]{__getitem__}{self, key}
Fred Draked82575d1998-08-28 20:03:12 +00001062Called to implement evaluation of \code{\var{self}[\var{key}]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001063For a sequence types, the accepted keys should be integers. Note that the
1064special interpretation of negative indices (if the class wishes to
Fred Drakef6669171998-05-06 19:52:49 +00001065emulate a sequence type) is up to the \method{__getitem__()} method.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001066\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001067
Fred Drake1e42d8a1998-11-25 17:58:50 +00001068\begin{methoddesc}[mapping object]{__setitem__}{self, key, value}
Fred Draked82575d1998-08-28 20:03:12 +00001069Called to implement assignment to \code{\var{self}[\var{key}]}. Same
Fred Drake1e42d8a1998-11-25 17:58:50 +00001070note as for \method{__getitem__()}. This should only be implemented
1071for mappings if the objects support changes to the values for keys, or
1072if new keys can be added, or for sequences if elements can be
1073replaced.
1074\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001075
Fred Drake1e42d8a1998-11-25 17:58:50 +00001076\begin{methoddesc}[mapping object]{__delitem__}{self, key}
Fred Draked82575d1998-08-28 20:03:12 +00001077Called to implement deletion of \code{\var{self}[\var{key}]}. Same
Fred Drake1e42d8a1998-11-25 17:58:50 +00001078note as for \method{__getitem__()}. This should only be implemented
1079for mappings if the objects support removal of keys, or for sequences
1080if elements can be removed from the sequence.
1081\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001082
1083
Fred Drake3041b071998-10-21 00:25:32 +00001084\subsection{Additional methods for emulation of sequence types
Fred Drake61c77281998-07-28 19:34:22 +00001085 \label{sequence-methods}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001086
1087The following methods can be defined to further emulate sequence
1088objects. Immutable sequences methods should only define
1089\method{__getslice__()}; mutable sequences, should define all three
1090three methods.
Fred Drakef6669171998-05-06 19:52:49 +00001091
Fred Drake1e42d8a1998-11-25 17:58:50 +00001092\begin{methoddesc}[sequence object]{__getslice__}{self, i, j}
Fred Draked82575d1998-08-28 20:03:12 +00001093Called to implement evaluation of \code{\var{self}[\var{i}:\var{j}]}.
1094The returned object should be of the same type as \var{self}. Note
1095that missing \var{i} or \var{j} in the slice expression are replaced
1096by zero or \code{sys.maxint}, respectively, and no further
1097transformations on the indices is performed. The interpretation of
1098negative indices and indices larger than the length of the sequence is
1099up to the method.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001100\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001101
Fred Drake1e42d8a1998-11-25 17:58:50 +00001102\begin{methoddesc}[sequence object]{__setslice__}{self, i, j, sequence}
Fred Draked82575d1998-08-28 20:03:12 +00001103Called to implement assignment to \code{\var{self}[\var{i}:\var{j}]}.
1104Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001105\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001106
Fred Drake1e42d8a1998-11-25 17:58:50 +00001107\begin{methoddesc}[sequence object]{__delslice__}{self, i, j}
Fred Draked82575d1998-08-28 20:03:12 +00001108Called to implement deletion of \code{\var{self}[\var{i}:\var{j}]}.
1109Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001110\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001111
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001112Notice that these methods are only invoked when a single slice with a
1113single colon is used. For slice operations involving extended slice
1114notation, \method{__getitem__()}, \method{__setitem__()}
1115or\method{__delitem__()} is called.
Fred Drakef6669171998-05-06 19:52:49 +00001116
Fred Drake61c77281998-07-28 19:34:22 +00001117\subsection{Emulating numeric types\label{numeric-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001118
1119The following methods can be defined to emulate numeric objects.
1120Methods corresponding to operations that are not supported by the
1121particular kind of number implemented (e.g., bitwise operations for
1122non-integral numbers) should be left undefined.
Fred Drakef6669171998-05-06 19:52:49 +00001123
Fred Drake1e42d8a1998-11-25 17:58:50 +00001124\begin{methoddesc}[numberic interface]{__add__}{self, other}
1125\methodline{__sub__}{self, other}
1126\methodline{__mul__}{self, other}
1127\methodline{__div__}{self, other}
1128\methodline{__mod__}{self, other}
1129\methodline{__divmod__}{self, other}
1130\methodline{__pow__}{self, other\optional{, modulo}}
1131\methodline{__lshift__}{self, other}
1132\methodline{__rshift__}{self, other}
1133\methodline{__and__}{self, other}
1134\methodline{__xor__}{self, other}
1135\methodline{__or__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001136These functions are
1137called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001138\code{-}, \code{*}, \code{/}, \code{\%},
1139\function{divmod()}\bifuncindex{divmod},
1140\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<}, \code{>>},
1141\code{\&}, \code{\^}, \code{|}). For instance, to evaluate the
1142expression \var{x}\code{+}\var{y}, where \var{x} is an instance of a
1143class that has an \method{__add__()} method,
1144\code{\var{x}.__add__(\var{y})} is called. Note that
1145\method{__pow__()} should be defined to accept an optional third
1146argument if the ternary version of the built-in
1147\function{pow()}\bifuncindex{pow} function is to be supported.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001148\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001149
Fred Drake1e42d8a1998-11-25 17:58:50 +00001150\begin{methoddesc}[numeric interface]{__radd__}{self, other}
1151\methodline{__rsub__}{self, other}
1152\methodline{__rmul__}{self, other}
1153\methodline{__rdiv__}{self, other}
1154\methodline{__rmod__}{self, other}
1155\methodline{__rdivmod__}{self, other}
1156\methodline{__rpow__}{self, other}
1157\methodline{__rlshift__}{self, other}
1158\methodline{__rrshift__}{self, other}
1159\methodline{__rand__}{self, other}
1160\methodline{__rxor__}{self, other}
1161\methodline{__ror__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001162These functions are
1163called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001164\code{-}, \code{*}, \code{/}, \code{\%},
1165\function{divmod()}\bifuncindex{divmod},
1166\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<}, \code{>>},
1167\code{\&}, \code{\^}, \code{|}) with reversed operands. These
1168functions are only called if the left operand does not support the
1169corresponding operation. For instance, to evaluate the expression
1170\var{x}\code{-}\var{y}, where \var{y} is an instance of a class that
1171has an \method{__rsub__()} method, \code{\var{y}.__rsub__(\var{x})} is
1172called. Note that ternary \function{pow()}\bifuncindex{pow} will not
1173try calling \method{__rpow__()} (the coercion rules would become too
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001174complicated).
Fred Drake1e42d8a1998-11-25 17:58:50 +00001175\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001176
Fred Drake1e42d8a1998-11-25 17:58:50 +00001177\begin{methoddesc}[numeric interface]{__neg__}{self}
1178\methodline{__pos__}{self}
1179\methodline{__abs__}{self}
1180\methodline{__invert__}{self}
Fred Drakef6669171998-05-06 19:52:49 +00001181Called to implement the unary arithmetic operations (\code{-}, \code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001182\function{abs()}\bifuncindex{abs} and \code{~}).
Fred Drake1e42d8a1998-11-25 17:58:50 +00001183\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001184
Fred Drake1e42d8a1998-11-25 17:58:50 +00001185\begin{methoddesc}[numeric interface]{__int__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001186\methodlineni{__long__}{self}
1187\methodlineni{__float__}{self}
1188Called to implement the built-in functions
1189\function{int()}\bifuncindex{int}, \function{long()}\bifuncindex{long}
1190and \function{float()}\bifuncindex{float}. Should return a value of
1191the appropriate type.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001192\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001193
Fred Drake1e42d8a1998-11-25 17:58:50 +00001194\begin{methoddesc}[numeric interface]{__oct__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001195\methodlineni{__hex__}{self}
1196Called to implement the built-in functions
1197\function{oct()}\bifuncindex{oct} and
1198\function{hex()}\bifuncindex{hex}. Should return a string value.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001199\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001200
Fred Drake1e42d8a1998-11-25 17:58:50 +00001201\begin{methoddesc}[numeric interface]{__coerce__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001202Called to implement ``mixed-mode'' numeric arithmetic. Should either
Fred Draked82575d1998-08-28 20:03:12 +00001203return a 2-tuple containing \var{self} and \var{other} converted to
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001204a common numeric type, or \code{None} if conversion is possible. When
1205the common type would be the type of \code{other}, it is sufficient to
1206return \code{None}, since the interpreter will also ask the other
1207object to attempt a coercion (but sometimes, if the implementation of
1208the other type cannot be changed, it is useful to do the conversion to
1209the other type here).
Fred Drake1e42d8a1998-11-25 17:58:50 +00001210\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001211
1212\strong{Coercion rules}: to evaluate \var{x} \var{op} \var{y}, the
1213following steps are taken (where \method{__op__()} and
1214\method{__rop__()} are the method names corresponding to \var{op},
Guido van Rossum7c0240f1998-07-24 15:36:43 +00001215e.g., if var{op} is `\code{+}', \method{__add__()} and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001216\method{__radd__()} are used). If an exception occurs at any point,
1217the evaluation is abandoned and exception handling takes over.
1218
1219\begin{itemize}
1220
1221\item[0.] If \var{x} is a string object and op is the modulo operator (\%),
1222the string formatting operation is invoked and the remaining steps are
1223skipped.
1224
1225\item[1.] If \var{x} is a class instance:
1226
1227 \begin{itemize}
1228
1229 \item[1a.] If \var{x} has a \method{__coerce__()} method:
1230 replace \var{x} and \var{y} with the 2-tuple returned by
1231 \code{\var{x}.__coerce__(\var{y})}; skip to step 2 if the
1232 coercion returns \code{None}.
1233
1234 \item[1b.] If neither \var{x} nor \var{y} is a class instance
1235 after coercion, go to step 3.
1236
1237 \item[1c.] If \var{x} has a method \method{__op__()}, return
1238 \code{\var{x}.__op__(\var{y})}; otherwise, restore \var{x} and
1239 \var{y} to their value before step 1a.
1240
1241 \end{itemize}
1242
1243\item[2.] If \var{y} is a class instance:
1244
1245 \begin{itemize}
1246
1247 \item[2a.] If \var{y} has a \method{__coerce__()} method:
1248 replace \var{y} and \var{x} with the 2-tuple returned by
1249 \code{\var{y}.__coerce__(\var{x})}; skip to step 3 if the
1250 coercion returns \code{None}.
1251
1252 \item[2b.] If neither \var{x} nor \var{y} is a class instance
1253 after coercion, go to step 3.
1254
1255 \item[2b.] If \var{y} has a method \method{__rop__()}, return
1256 \code{\var{y}.__rop__(\var{x})}; otherwise, restore \var{x}
1257 and \var{y} to their value before step 2a.
1258
1259 \end{itemize}
1260
1261\item[3.] We only get here if neither \var{x} nor \var{y} is a class
1262instance.
1263
1264 \begin{itemize}
1265
1266 \item[3a.] If op is `\code{+}' and \var{x} is a sequence,
1267 sequence concatenation is invoked.
1268
1269 \item[3b.] If op is `\code{*}' and one operand is a sequence
1270 and the other an integer, sequence repetition is invoked.
1271
1272 \item[3c.] Otherwise, both operands must be numbers; they are
1273 coerced to a common type if possible, and the numeric
1274 operation is invoked for that type.
1275
1276 \end{itemize}
1277
1278\end{itemize}