blob: e522b82e4a1392401a1f913088dc8ce4b026b906 [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
52`\code{try}...\code{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 Drakef6669171998-05-06 19:52:49 +000060objects.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000061The `\code{try}...\code{finally}' statement provides a convenient way
62to do this.
Fred Drakef6669171998-05-06 19:52:49 +000063
64Some objects contain references to other objects; these are called
65\emph{containers}. Examples of containers are tuples, lists and
66dictionaries. The references are part of a container's value. In
67most cases, when we talk about the value of a container, we imply the
68values, not the identities of the contained objects; however, when we
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000069talk about the mutability of a container, only the identities of
70the immediately contained objects are implied. So, if an immutable
71container (like a tuple)
72contains a reference to a mutable object, its value changes
73if that mutable object is changed.
Fred Drakef6669171998-05-06 19:52:49 +000074\index{container}
75
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000076Types affect almost all aspects of object behavior. Even the importance
Fred Drakef6669171998-05-06 19:52:49 +000077of object identity is affected in some sense: for immutable types,
78operations that compute new values may actually return a reference to
79any existing object with the same type and value, while for mutable
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000080objects this is not allowed. E.g., after
Fred Drake82385871998-10-01 20:40:43 +000081\samp{a = 1; b = 1},
Fred Drakef6669171998-05-06 19:52:49 +000082\code{a} and \code{b} may or may not refer to the same object with the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000083value one, depending on the implementation, but after
Fred Drake82385871998-10-01 20:40:43 +000084\samp{c = []; d = []}, \code{c} and \code{d}
Fred Drakef6669171998-05-06 19:52:49 +000085are guaranteed to refer to two different, unique, newly created empty
86lists.
Fred Drake82385871998-10-01 20:40:43 +000087(Note that \samp{c = d = []} assigns the same object to both
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000088\code{c} and \code{d}.)
Fred Drakef6669171998-05-06 19:52:49 +000089
Fred Drake61c77281998-07-28 19:34:22 +000090\section{The standard type hierarchy\label{types}}
Fred Drakef6669171998-05-06 19:52:49 +000091
92Below is a list of the types that are built into Python. Extension
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000093modules written in \C{} can define additional types. Future versions of
94Python may add types to the type hierarchy (e.g., rational
Fred Drakef6669171998-05-06 19:52:49 +000095numbers, efficiently stored arrays of integers, etc.).
96\index{type}
97\indexii{data}{type}
98\indexii{type}{hierarchy}
99\indexii{extension}{module}
100\indexii{C}{language}
101
102Some of the type descriptions below contain a paragraph listing
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000103`special attributes.' These are attributes that provide access to the
Fred Drakef6669171998-05-06 19:52:49 +0000104implementation and are not intended for general use. Their definition
105may change in the future. There are also some `generic' special
106attributes, not listed with the individual objects: \member{__methods__}
107is a list of the method names of a built-in object, if it has any;
108\member{__members__} is a list of the data attribute names of a built-in
109object, if it has any.
110\index{attribute}
111\indexii{special}{attribute}
112\indexiii{generic}{special}{attribute}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000113\withsubitem{(built-in object attribute)}{%
114 \ttindex{__methods__}
115 \ttindex{__members__}}
Fred Drakef6669171998-05-06 19:52:49 +0000116
117\begin{description}
118
119\item[None]
120This type has a single value. There is a single object with this value.
121This object is accessed through the built-in name \code{None}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000122It is used to signify the absence of a value in many situations, e.g.,
123it is returned from functions that don't explicitly return anything.
124Its truth value is false.
Fred Drakef6669171998-05-06 19:52:49 +0000125\ttindex{None}
Fred Drake78eebfd1998-11-25 19:09:24 +0000126\obindex{None@{\texttt{None}}}
Fred Drakef6669171998-05-06 19:52:49 +0000127
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000128\item[Ellipsis]
129This type has a single value. There is a single object with this value.
130This object is accessed through the built-in name \code{Ellipsis}.
Fred Drake82385871998-10-01 20:40:43 +0000131It is used to indicate the presence of the \samp{...} syntax in a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000132slice. Its truth value is true.
133\ttindex{Ellipsis}
Fred Drake78eebfd1998-11-25 19:09:24 +0000134\obindex{Ellipsis@{\texttt{Ellipsis}}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000135
Fred Drakef6669171998-05-06 19:52:49 +0000136\item[Numbers]
137These are created by numeric literals and returned as results by
138arithmetic operators and arithmetic built-in functions. Numeric
139objects are immutable; once created their value never changes. Python
140numbers are of course strongly related to mathematical numbers, but
141subject to the limitations of numerical representation in computers.
142\obindex{number}
143\obindex{numeric}
144
145Python distinguishes between integers and floating point numbers:
146
147\begin{description}
148\item[Integers]
149These represent elements from the mathematical set of whole numbers.
150\obindex{integer}
151
152There are two types of integers:
153
154\begin{description}
155
156\item[Plain integers]
157These represent numbers in the range -2147483648 through 2147483647.
158(The range may be larger on machines with a larger natural word
159size, but not smaller.)
160When the result of an operation falls outside this range, the
161exception \exception{OverflowError} is raised.
162For the purpose of shift and mask operations, integers are assumed to
163have a binary, 2's complement notation using 32 or more bits, and
164hiding no bits from the user (i.e., all 4294967296 different bit
165patterns correspond to different values).
166\obindex{plain integer}
167\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
168
169\item[Long integers]
170These represent numbers in an unlimited range, subject to available
171(virtual) memory only. For the purpose of shift and mask operations,
172a binary representation is assumed, and negative numbers are
173represented in a variant of 2's complement which gives the illusion of
174an infinite string of sign bits extending to the left.
175\obindex{long integer}
176
177\end{description} % Integers
178
179The rules for integer representation are intended to give the most
180meaningful interpretation of shift and mask operations involving
181negative integers and the least surprises when switching between the
182plain and long integer domains. For any operation except left shift,
183if it yields a result in the plain integer domain without causing
184overflow, it will yield the same result in the long integer domain or
185when using mixed operands.
186\indexii{integer}{representation}
187
188\item[Floating point numbers]
189These represent machine-level double precision floating point numbers.
190You are at the mercy of the underlying machine architecture and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000191\C{} implementation for the accepted range and handling of overflow.
192Python does not support single-precision floating point numbers; the
193savings in CPU and memory usage that are usually the reason for using
194these is dwarfed by the overhead of using objects in Python, so there
195is no reason to complicate the language with two kinds of floating
196point numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000197\obindex{floating point}
198\indexii{floating point}{number}
199\indexii{C}{language}
200
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000201\item[Complex numbers]
202These represent complex numbers as a pair of machine-level double
203precision floating point numbers. The same caveats apply as for
204floating point numbers. The real and imaginary value of a complex
205number \code{z} can be retrieved through the attributes \code{z.real}
206and \code{z.imag}.
207\obindex{complex}
208\indexii{complex}{number}
209
Fred Drakef6669171998-05-06 19:52:49 +0000210\end{description} % Numbers
211
212\item[Sequences]
213These represent finite ordered sets indexed by natural numbers.
214The built-in function \function{len()}\bifuncindex{len} returns the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000215number of items of a sequence.
216When the lenth of a sequence is \var{n}, the
217index set contains the numbers 0, 1, \ldots, \var{n}-1. Item
Fred Drakef6669171998-05-06 19:52:49 +0000218\var{i} of sequence \var{a} is selected by \code{\var{a}[\var{i}]}.
219\obindex{seqence}
220\index{index operation}
221\index{item selection}
222\index{subscription}
223
224Sequences also support slicing: \code{\var{a}[\var{i}:\var{j}]}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000225selects all items with index \var{k} such that \var{i} \code{<=}
Fred Drakef6669171998-05-06 19:52:49 +0000226\var{k} \code{<} \var{j}. When used as an expression, a slice is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000227sequence of the same type. This implies that the index set is
228renumbered so that it starts at 0.
Fred Drakef6669171998-05-06 19:52:49 +0000229\index{slicing}
230
231Sequences are distinguished according to their mutability:
232
233\begin{description}
234%
235\item[Immutable sequences]
236An object of an immutable sequence type cannot change once it is
237created. (If the object contains references to other objects,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000238these other objects may be mutable and may be changed; however,
Fred Drakef6669171998-05-06 19:52:49 +0000239the collection of objects directly referenced by an immutable object
240cannot change.)
241\obindex{immutable sequence}
242\obindex{immutable}
243
244The following types are immutable sequences:
245
246\begin{description}
247
248\item[Strings]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000249The items of a string are characters. There is no separate
250character type; a character is represented by a string of one item.
Fred Drakef6669171998-05-06 19:52:49 +0000251Characters represent (at least) 8-bit bytes. The built-in
252functions \function{chr()}\bifuncindex{chr} and
253\function{ord()}\bifuncindex{ord} convert between characters and
254nonnegative integers representing the byte values. Bytes with the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000255values 0-127 usually represent the corresponding \ASCII{} values, but
256the interpretation of values is up to the program. The string
257data type is also used to represent arrays of bytes, e.g., to hold data
Fred Drakef6669171998-05-06 19:52:49 +0000258read from a file.
259\obindex{string}
260\index{character}
261\index{byte}
Fred Drake5c07d9b1998-05-14 19:37:06 +0000262\index{ASCII@\ASCII{}}
Fred Drakef6669171998-05-06 19:52:49 +0000263
264(On systems whose native character set is not \ASCII{}, strings may use
265EBCDIC in their internal representation, provided the functions
266\function{chr()} and \function{ord()} implement a mapping between \ASCII{} and
267EBCDIC, and string comparison preserves the \ASCII{} order.
268Or perhaps someone can propose a better rule?)
Fred Drake5c07d9b1998-05-14 19:37:06 +0000269\index{ASCII@\ASCII{}}
Fred Drakef6669171998-05-06 19:52:49 +0000270\index{EBCDIC}
271\index{character set}
272\indexii{string}{comparison}
273\bifuncindex{chr}
274\bifuncindex{ord}
275
276\item[Tuples]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000277The items of a tuple are arbitrary Python objects.
278Tuples of two or more items are formed by comma-separated lists
279of expressions. A tuple of one item (a `singleton') can be formed
Fred Drakef6669171998-05-06 19:52:49 +0000280by affixing a comma to an expression (an expression by itself does
281not create a tuple, since parentheses must be usable for grouping of
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000282expressions). An empty tuple can be formed by an empty pair of
Fred Drakef6669171998-05-06 19:52:49 +0000283parentheses.
284\obindex{tuple}
285\indexii{singleton}{tuple}
286\indexii{empty}{tuple}
287
288\end{description} % Immutable sequences
289
290\item[Mutable sequences]
291Mutable sequences can be changed after they are created. The
292subscription and slicing notations can be used as the target of
293assignment and \keyword{del} (delete) statements.
294\obindex{mutable sequece}
295\obindex{mutable}
296\indexii{assignment}{statement}
297\index{delete}
298\stindex{del}
299\index{subscription}
300\index{slicing}
301
302There is currently a single mutable sequence type:
303
304\begin{description}
305
306\item[Lists]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000307The items of a list are arbitrary Python objects. Lists are formed
Fred Drakef6669171998-05-06 19:52:49 +0000308by placing a comma-separated list of expressions in square brackets.
309(Note that there are no special cases needed to form lists of length 0
310or 1.)
311\obindex{list}
312
313\end{description} % Mutable sequences
314
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000315The extension module \module{array}\refstmodindex{array} provides an
316additional example of a mutable sequence type.
317
318
Fred Drakef6669171998-05-06 19:52:49 +0000319\end{description} % Sequences
320
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000321\item[Mappings]
Fred Drakef6669171998-05-06 19:52:49 +0000322These represent finite sets of objects indexed by arbitrary index sets.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000323The subscript notation \code{a[k]} selects the item indexed
Fred Drakef6669171998-05-06 19:52:49 +0000324by \code{k} from the mapping \code{a}; this can be used in
325expressions and as the target of assignments or \keyword{del} statements.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000326The built-in function \function{len()} returns the number of items
Fred Drakef6669171998-05-06 19:52:49 +0000327in a mapping.
328\bifuncindex{len}
329\index{subscription}
330\obindex{mapping}
331
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000332There is currently a single intrinsic mapping type:
Fred Drakef6669171998-05-06 19:52:49 +0000333
334\begin{description}
335
336\item[Dictionaries]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000337These represent finite sets of objects indexed by nearly arbitrary
Fred Drakef6669171998-05-06 19:52:49 +0000338values. The only types of values not acceptable as keys are values
339containing lists or dictionaries or other mutable types that are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000340compared by value rather than by object identity, the reason being
341that the efficient implementation of dictionaries requires a key's
342hash value to remain constant.
Fred Drakef6669171998-05-06 19:52:49 +0000343Numeric types used for keys obey the normal rules for numeric
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000344comparison: if two numbers compare equal (e.g., \code{1} and
Fred Drakef6669171998-05-06 19:52:49 +0000345\code{1.0}) then they can be used interchangeably to index the same
346dictionary entry.
347
348Dictionaries are mutable; they are created by the \code{...}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000349notation (see section \ref{dict}, ``Dictionary Displays'').
Fred Drakef6669171998-05-06 19:52:49 +0000350\obindex{dictionary}
351\obindex{mutable}
352
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000353The extension modules \module{dbm}\refstmodindex{dbm},
354\module{gdbm}\refstmodindex{gdbm}, \module{bsddb}\refstmodindex{bsddb}
355provide additional examples of mapping types.
356
Fred Drakef6669171998-05-06 19:52:49 +0000357\end{description} % Mapping types
358
359\item[Callable types]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000360These are the types to which the function call operation (see section
361\ref{calls}, ``Calls'') can be applied:
Fred Drakef6669171998-05-06 19:52:49 +0000362\indexii{function}{call}
363\index{invocation}
364\indexii{function}{argument}
365\obindex{callable}
366
367\begin{description}
368
369\item[User-defined functions]
370A user-defined function object is created by a function definition
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000371(see section \ref{function}, ``Function definitions''). It should be
372called with an argument
Fred Drakef6669171998-05-06 19:52:49 +0000373list containing the same number of items as the function's formal
374parameter list.
375\indexii{user-defined}{function}
376\obindex{function}
377\obindex{user-defined function}
378
Fred Drake82385871998-10-01 20:40:43 +0000379Special read-only attributes: \member{func_doc} or \member{__doc__} is the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000380function's documentation string, or None if unavailable;
Fred Drake82385871998-10-01 20:40:43 +0000381\member{func_name} or \member{__name__} is the function's name;
382\member{func_defaults} is a tuple containing default argument values for
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000383those arguments that have defaults, or \code{None} if no arguments
Fred Drake82385871998-10-01 20:40:43 +0000384have a default value; \member{func_code} is the code object representing
385the compiled function body; \member{func_globals} is (a reference to)
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000386the dictionary that holds the function's global variables --- it
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000387defines the global namespace of the module in which the function was
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000388defined. Additional information about a function's definition can be
389retrieved from its code object; see the description of internal types
390below.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000391\withsubitem{(function attribute)}{%
392 \ttindex{func_doc}%
393 \ttindex{__doc__}%
394 \ttindex{__name__}%
395 \ttindex{func_defaults}%
396 \ttindex{func_code}%
397 \ttindex{func_globals}}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000398\indexii{global}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000399
400\item[User-defined methods]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000401A user-defined method object combines a class, a class instance (or
402\code{None}) and a user-defined function.
Fred Drakef6669171998-05-06 19:52:49 +0000403\obindex{method}
404\obindex{user-defined method}
405\indexii{user-defined}{method}
Fred Drakef6669171998-05-06 19:52:49 +0000406
407Special read-only attributes: \member{im_self} is the class instance
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000408object, \member{im_func} is the function object;
Fred Drake82385871998-10-01 20:40:43 +0000409\member{im_class} is the class that defined the method (which may be a
410base class of the class of which \member{im_self} is an instance);
411\member{__doc__} is the method's documentation (same as
412\code{im_func.__doc__}); \member{__name__} is the method name (same as
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000413\code{im_func.__name__}).
Fred Drake1e42d8a1998-11-25 17:58:50 +0000414\withsubitem{(method attribute)}{%
415 \ttindex{im_func}%
416 \ttindex{im_self}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000417
418User-defined method objects are created in two ways: when getting an
419attribute of a class that is a user-defined function object, or when
420getting an attributes of a class instance that is a user-defined
421function object. In the former case (class attribute), the
Fred Drake82385871998-10-01 20:40:43 +0000422\member{im_self} attribute is \code{None}, and the method object is said
423to be unbound; in the latter case (instance attribute), \method{im_self}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000424is the instance, and the method object is said to be bound. For
Fred Drake82385871998-10-01 20:40:43 +0000425instance, when \class{C} is a class which contains a definition for a
426function \method{f()}, \code{C.f} does not yield the function object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000427\code{f}; rather, it yields an unbound method object \code{m} where
Fred Drake82385871998-10-01 20:40:43 +0000428\code{m.im_class} is \class{C}, \code{m.im_func} is \method{f()}, and
429\code{m.im_self} is \code{None}. When \code{x} is a \class{C}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000430instance, \code{x.f} yields a bound method object \code{m} where
Fred Drake82385871998-10-01 20:40:43 +0000431\code{m.im_class} is \code{C}, \code{m.im_func} is \method{f()}, and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000432\code{m.im_self} is \code{x}.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000433\withsubitem{(method attribute)}{%
434 \ttindex{im_class}%
435 \ttindex{im_func}%
436 \ttindex{im_self}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000437
438When an unbound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000439function (\member{im_func}) is called, with the restriction that the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000440first argument must be an instance of the proper class
Fred Drake82385871998-10-01 20:40:43 +0000441(\member{im_class}) or of a derived class thereof.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000442
443When a bound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000444function (\member{im_func}) is called, inserting the class instance
445(\member{im_self}) in front of the argument list. For instance, when
446\class{C} is a class which contains a definition for a function
447\method{f()}, and \code{x} is an instance of \class{C}, calling
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000448\code{x.f(1)} is equivalent to calling \code{C.f(x, 1)}.
449
450Note that the transformation from function object to (unbound or
451bound) method object happens each time the attribute is retrieved from
452the class or instance. In some cases, a fruitful optimization is to
453assign the attribute to a local variable and call that local variable.
454Also notice that this transformation only happens for user-defined
455functions; other callable objects (and all non-callable objects) are
456retrieved without transformation.
457
Fred Drakef6669171998-05-06 19:52:49 +0000458\item[Built-in functions]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000459A built-in function object is a wrapper around a \C{} function. Examples
460of built-in functions are \function{len()} and \function{math.sin()}
461(\module{math} is a standard built-in module).
462The number and type of the arguments are
Fred Drakef6669171998-05-06 19:52:49 +0000463determined by the C function.
Fred Drake82385871998-10-01 20:40:43 +0000464Special read-only attributes: \member{__doc__} is the function's
465documentation string, or \code{None} if unavailable; \member{__name__}
466is the function's name; \member{__self__} is set to \code{None} (but see
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000467the next item).
Fred Drakef6669171998-05-06 19:52:49 +0000468\obindex{built-in function}
469\obindex{function}
470\indexii{C}{language}
471
472\item[Built-in methods]
473This is really a different disguise of a built-in function, this time
474containing an object passed to the \C{} function as an implicit extra
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000475argument. An example of a built-in method is
476\code{\var{list}.append()}, assuming
Fred Drakef6669171998-05-06 19:52:49 +0000477\var{list} is a list object.
Fred Drake82385871998-10-01 20:40:43 +0000478In this case, the special read-only attribute \member{__self__} is set
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000479to the object denoted by \code{list}.
Fred Drakef6669171998-05-06 19:52:49 +0000480\obindex{built-in method}
481\obindex{method}
482\indexii{built-in}{method}
483
484\item[Classes]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000485Class objects are described below. When a class object is called,
486a new class instance (also described below) is created and
Fred Drakef6669171998-05-06 19:52:49 +0000487returned. This implies a call to the class's \method{__init__()} method
488if it has one. Any arguments are passed on to the \method{__init__()}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000489method. If there is no \method{__init__()} method, the class must be called
Fred Drakef6669171998-05-06 19:52:49 +0000490without arguments.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000491\withsubitem{(object method)}{\ttindex{__init__()}}
Fred Drakef6669171998-05-06 19:52:49 +0000492\obindex{class}
493\obindex{class instance}
494\obindex{instance}
495\indexii{class object}{call}
496
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000497\item[Class instances]
498Class instances are described below. Class instances are callable
Fred Drake82385871998-10-01 20:40:43 +0000499only when the class has a \method{__call__()} method; \code{x(arguments)}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000500is a shorthand for \code{x.__call__(arguments)}.
501
Fred Drakef6669171998-05-06 19:52:49 +0000502\end{description}
503
504\item[Modules]
505Modules are imported by the \keyword{import} statement (see section
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000506\ref{import}, ``The \keyword{import} statement'').
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000507A module object has a namespace implemented by a dictionary object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000508(this is the dictionary referenced by the func_globals attribute of
509functions defined in the module). Attribute references are translated
510to lookups in this dictionary, e.g., \code{m.x} is equivalent to
511\code{m.__dict__["x"]}.
512A module object does not contain the code object used to
Fred Drakef6669171998-05-06 19:52:49 +0000513initialize the module (since it isn't needed once the initialization
514is done).
515\stindex{import}
516\obindex{module}
517
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000518Attribute assignment updates the module's namespace dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000519e.g., \samp{m.x = 1} is equivalent to \samp{m.__dict__["x"] = 1}.
Fred Drakef6669171998-05-06 19:52:49 +0000520
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000521Special read-only attribute: \member{__dict__} is the module's
522namespace as a dictionary object.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000523\withsubitem{(module attribute)}{\ttindex{__dict__}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000524
525Predefined (writable) attributes: \member{__name__}
526is the module's name; \member{__doc__} is the
527module's documentation string, or
Fred Drake82385871998-10-01 20:40:43 +0000528\code{None} if unavailable; \member{__file__} is the pathname of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000529file from which the module was loaded, if it was loaded from a file.
Fred Drake82385871998-10-01 20:40:43 +0000530The \member{__file__} attribute is not present for C{} modules that are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000531statically linked into the interpreter; for extension modules loaded
532dynamically from a shared library, it is the pathname of the shared
533library file.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000534\withsubitem{(module attribute)}{%
535 \ttindex{__name__}%
536 \ttindex{__doc__}%
537 \ttindex{__file__}}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000538\indexii{module}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000539
540\item[Classes]
541Class objects are created by class definitions (see section
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000542\ref{class}, ``Class definitions'').
543A class has a namespace implemented by a dictionary object.
544Class attribute references are translated to
545lookups in this dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000546e.g., \samp{C.x} is translated to \samp{C.__dict__["x"]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000547When the attribute name is not found
Fred Drakef6669171998-05-06 19:52:49 +0000548there, the attribute search continues in the base classes. The search
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000549is depth-first, left-to-right in the order of occurrence in the
Fred Drakef6669171998-05-06 19:52:49 +0000550base class list.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000551When a class attribute reference would yield a user-defined function
552object, it is transformed into an unbound user-defined method object
Fred Drake82385871998-10-01 20:40:43 +0000553(see above). The \member{im_class} attribute of this method object is the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000554class in which the function object was found, not necessarily the
555class for which the attribute reference was initiated.
Fred Drakef6669171998-05-06 19:52:49 +0000556\obindex{class}
557\obindex{class instance}
558\obindex{instance}
559\indexii{class object}{call}
560\index{container}
561\obindex{dictionary}
562\indexii{class}{attribute}
563
564Class attribute assignments update the class's dictionary, never the
565dictionary of a base class.
566\indexiii{class}{attribute}{assignment}
567
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000568A class object can be called (see above) to yield a class instance (see
569below).
Fred Drakef6669171998-05-06 19:52:49 +0000570\indexii{class object}{call}
571
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000572Special attributes: \member{__name__} is the class name;
573\member{__module__} is the module name in which the class was defined;
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000574\member{__dict__} is the dictionary containing the class's namespace;
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000575\member{__bases__} is a tuple (possibly empty or a singleton)
576containing the base classes, in the order of their occurrence in the
Fred Drake82385871998-10-01 20:40:43 +0000577base class list; \member{__doc__} is the class's documentation string,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000578or None if undefined.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000579\withsubitem{(class attribute)}{%
580 \ttindex{__name__}%
581 \ttindex{__module__}%
582 \ttindex{__dict__}%
583 \ttindex{__bases__}%
584 \ttindex{__doc__}}
Fred Drakef6669171998-05-06 19:52:49 +0000585
586\item[Class instances]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000587A class instance is created by calling a class object (see above).
588A class instance has a namespace implemented as a dictionary which
589is the first place in which
Fred Drakef6669171998-05-06 19:52:49 +0000590attribute references are searched. When an attribute is not found
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000591there, and the instance's class has an attribute by that name,
592the search continues with the class attributes. If a class attribute
593is found that is a user-defined function object (and in no other
594case), it is transformed into an unbound user-defined method object
Fred Drake82385871998-10-01 20:40:43 +0000595(see above). The \member{im_class} attribute of this method object is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000596the class in which the function object was found, not necessarily the
597class of the instance for which the attribute reference was initiated.
598If no class attribute is found, and the object's class has a
Fred Drake82385871998-10-01 20:40:43 +0000599\method{__getattr__()} method, that is called to satisfy the lookup.
Fred Drakef6669171998-05-06 19:52:49 +0000600\obindex{class instance}
601\obindex{instance}
602\indexii{class}{instance}
603\indexii{class instance}{attribute}
604
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000605Attribute assignments and deletions update the instance's dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000606never a class's dictionary. If the class has a \method{__setattr__()} or
607\method{__delattr__()} method, this is called instead of updating the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000608instance dictionary directly.
Fred Drakef6669171998-05-06 19:52:49 +0000609\indexiii{class instance}{attribute}{assignment}
610
611Class instances can pretend to be numbers, sequences, or mappings if
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000612they have methods with certain special names. See
613section \ref{specialnames}, ``Special method names.''
Fred Drakef6669171998-05-06 19:52:49 +0000614\obindex{number}
615\obindex{sequence}
616\obindex{mapping}
617
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000618Special attributes: \member{__dict__} is the attribute
619dictionary; \member{__class__} is the instance's class.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000620\withsubitem{(instance attribute)}{%
621 \ttindex{__dict__}%
622 \ttindex{__class__}}
Fred Drakef6669171998-05-06 19:52:49 +0000623
624\item[Files]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000625A file object represents an open file. File objects are created by the
626\function{open()} built-in function, and also by
627\function{os.popen()}, \function{os.fdopen()}, and the
628\method{makefile()} method of socket objects (and perhaps by other
629functions or methods provided by extension modules). The objects
630\code{sys.stdin}, \code{sys.stdout} and \code{sys.stderr} are
631initialized to file objects corresponding to the interpreter's
632standard input, output and error streams. See the \emph{Python
633Library Reference} for complete documentation of file objects.
Fred Drakef6669171998-05-06 19:52:49 +0000634\obindex{file}
635\indexii{C}{language}
636\index{stdio}
637\bifuncindex{open}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000638\withsubitem{(in module os)}{\ttindex{popen()}}
639\withsubitem{(socket method)}{\ttindex{makefile()}}
640\withsubitem{(in module sys)}{%
641 \ttindex{stdin}%
642 \ttindex{stdout}%
643 \ttindex{stderr}}
Fred Drakef6669171998-05-06 19:52:49 +0000644\ttindex{sys.stdin}
645\ttindex{sys.stdout}
646\ttindex{sys.stderr}
647
648\item[Internal types]
649A few types used internally by the interpreter are exposed to the user.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000650Their definitions may change with future versions of the interpreter,
Fred Drakef6669171998-05-06 19:52:49 +0000651but they are mentioned here for completeness.
652\index{internal type}
653\index{types, internal}
654
655\begin{description}
656
657\item[Code objects]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000658Code objects represent \emph{byte-compiled} executable Python code, or
659\emph{bytecode}.
Fred Drakef6669171998-05-06 19:52:49 +0000660The difference between a code
661object and a function object is that the function object contains an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000662explicit reference to the function's globals (the module in which it
663was defined), while a code object contains no context;
664also the default argument values are stored in the function object,
665not in the code object (because they represent values calculated at
666run-time). Unlike function objects, code objects are immutable and
667contain no references (directly or indirectly) to mutable objects.
668\index{bytecode}
Fred Drakef6669171998-05-06 19:52:49 +0000669\obindex{code}
670
Fred Drake1e42d8a1998-11-25 17:58:50 +0000671Special read-only attributes: \member{co_name} gives the function
672name; \member{co_argcount} is the number of positional arguments
673(including arguments with default values); \member{co_nlocals} is the
674number of local variables used by the function (including arguments);
675\member{co_varnames} is a tuple containing the names of the local
676variables (starting with the argument names); \member{co_code} is a
677string representing the sequence of bytecode instructions;
678\member{co_consts} is a tuple containing the literals used by the
679bytecode; \member{co_names} is a tuple containing the names used by
680the bytecode; \member{co_filename} is the filename from which the code
681was compiled; \member{co_firstlineno} is the first line number of the
682function; \member{co_lnotab} is a string encoding the mapping from
683byte code offsets to line numbers (for detais see the source code of
684the interpreter); \member{co_stacksize} is the required stack size
685(including local variables); \member{co_flags} is an integer encoding
686a number of flags for the interpreter.
687\withsubitem{(code object attribute)}{%
688 \ttindex{co_argcount}%
689 \ttindex{co_code}%
690 \ttindex{co_consts}%
691 \ttindex{co_filename}%
692 \ttindex{co_firstlineno}%
693 \ttindex{co_flags}%
694 \ttindex{co_lnotab}%
695 \ttindex{co_name}%
696 \ttindex{co_names}%
697 \ttindex{co_nlocals}%
698 \ttindex{co_stacksize}%
699 \ttindex{co_varnames}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000700
Fred Drake82385871998-10-01 20:40:43 +0000701The following flag bits are defined for \member{co_flags}: bit 2 is set
702if the function uses the \samp{*arguments} syntax to accept an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000703arbitrary number of positional arguments; bit 3 is set if the function
Fred Drake82385871998-10-01 20:40:43 +0000704uses the \samp{**keywords} syntax to accept arbitrary keyword
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000705arguments; other bits are used internally or reserved for future use.
706If a code object represents a function, the first item in
Fred Drake82385871998-10-01 20:40:43 +0000707\member{co_consts} is the documentation string of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000708function, or \code{None} if undefined.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000709\index{documentation string}
Fred Drakef6669171998-05-06 19:52:49 +0000710
711\item[Frame objects]
712Frame objects represent execution frames. They may occur in traceback
713objects (see below).
714\obindex{frame}
715
716Special read-only attributes: \member{f_back} is to the previous
717stack frame (towards the caller), or \code{None} if this is the bottom
718stack frame; \member{f_code} is the code object being executed in this
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000719frame; \member{f_locals} is the dictionary used to look up local
720variables; \member{f_globals} is used for global variables;
Fred Drake82385871998-10-01 20:40:43 +0000721\member{f_builtins} is used for built-in (intrinsic) names;
722\member{f_restricted} is a flag indicating whether the function is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000723executing in restricted execution mode;
Fred Drakef6669171998-05-06 19:52:49 +0000724\member{f_lineno} gives the line number and \member{f_lasti} gives the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000725precise instruction (this is an index into the bytecode string of
Fred Drakef6669171998-05-06 19:52:49 +0000726the code object).
Fred Drake1e42d8a1998-11-25 17:58:50 +0000727\withsubitem{(frame attribute)}{%
728 \ttindex{f_back}%
729 \ttindex{f_code}%
730 \ttindex{f_globals}%
731 \ttindex{f_locals}%
732 \ttindex{f_lineno}%
733 \ttindex{f_lasti}%
734 \ttindex{f_builtins}%
735 \ttindex{f_restricted}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000736
Fred Drake82385871998-10-01 20:40:43 +0000737Special writable attributes: \member{f_trace}, if not \code{None}, is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000738function called at the start of each source code line (this is used by
Fred Drake82385871998-10-01 20:40:43 +0000739the debugger); \member{f_exc_type}, \member{f_exc_value},
740\member{f_exc_traceback} represent the most recent exception caught in
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000741this frame.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000742\withsubitem{(frame attribute)}{%
743 \ttindex{f_trace}%
744 \ttindex{f_exc_type}%
745 \ttindex{f_exc_value}%
746 \ttindex{f_exc_traceback}}
Fred Drakef6669171998-05-06 19:52:49 +0000747
748\item[Traceback objects] \label{traceback}
749Traceback objects represent a stack trace of an exception. A
750traceback object is created when an exception occurs. When the search
751for an exception handler unwinds the execution stack, at each unwound
752level a traceback object is inserted in front of the current
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000753traceback. When an exception handler is entered, the stack trace is
754made available to the program.
755(See section \ref{try}, ``The \code{try} statement.'')
756It is accessible as \code{sys.exc_traceback}, and also as the third
757item of the tuple returned by \code{sys.exc_info()}. The latter is
758the preferred interface, since it works correctly when the program is
759using multiple threads.
760When the program contains no suitable handler, the stack trace is written
Fred Drakef6669171998-05-06 19:52:49 +0000761(nicely formatted) to the standard error stream; if the interpreter is
762interactive, it is also made available to the user as
763\code{sys.last_traceback}.
764\obindex{traceback}
765\indexii{stack}{trace}
766\indexii{exception}{handler}
767\indexii{execution}{stack}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000768\withsubitem{(in module sys)}{%
769 \ttindex{exc_info}%
770 \ttindex{exc_traceback}%
771 \ttindex{last_traceback}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000772\ttindex{sys.exc_info}
Fred Drakef6669171998-05-06 19:52:49 +0000773\ttindex{sys.exc_traceback}
774\ttindex{sys.last_traceback}
775
776Special read-only attributes: \member{tb_next} is the next level in the
777stack trace (towards the frame where the exception occurred), or
778\code{None} if there is no next level; \member{tb_frame} points to the
779execution frame of the current level; \member{tb_lineno} gives the line
780number where the exception occurred; \member{tb_lasti} indicates the
781precise instruction. The line number and last instruction in the
782traceback may differ from the line number of its frame object if the
783exception occurred in a \keyword{try} statement with no matching
784except clause or with a finally clause.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000785\withsubitem{(traceback attribute)}{%
786 \ttindex{tb_next}%
787 \ttindex{tb_frame}%
788 \ttindex{tb_lineno}%
789 \ttindex{tb_lasti}}
Fred Drakef6669171998-05-06 19:52:49 +0000790\stindex{try}
791
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000792\item[Slice objects]
793Slice objects are used to represent slices when \emph{extended slice
794syntax} is used. This is a slice using two colons, or multiple slices
795or ellipses separated by commas, e.g., \code{a[i:j:step]}, \code{a[i:j,
796k:l]}, or \code{a[..., i:j])}. They are also created by the built-in
Fred Drake1e42d8a1998-11-25 17:58:50 +0000797\function{slice()}\bifuncindex{slice} function.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000798
Fred Drake82385871998-10-01 20:40:43 +0000799Special read-only attributes: \member{start} is the lowerbound;
800\member{stop} is the upperbound; \member{step} is the step value; each is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000801\code{None} if omitted. These attributes can have any type.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000802\withsubitem{(slice object attribute)}{%
803 \ttindex{start}%
804 \ttindex{stop}%
805 \ttindex{step}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000806
Fred Drakef6669171998-05-06 19:52:49 +0000807\end{description} % Internal types
808
809\end{description} % Types
810
811
Fred Drake61c77281998-07-28 19:34:22 +0000812\section{Special method names\label{specialnames}}
Fred Drakef6669171998-05-06 19:52:49 +0000813
814A class can implement certain operations that are invoked by special
Fred Draked82575d1998-08-28 20:03:12 +0000815syntax (such as arithmetic operations or subscripting and slicing) by
816defining methods with special names. For instance, if a class defines
817a method named \method{__getitem__()}, and \code{x} is an instance of
818this class, then \code{x[i]} is equivalent to
819\code{x.__getitem__(i)}. (The reverse is not true --- if \code{x} is
820a list object, \code{x.__getitem__(i)} is not equivalent to
821\code{x[i]}.) Except where mentioned, attempts to execute an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000822operation raise an exception when no appropriate method is defined.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000823\withsubitem{(mapping object method)}{\ttindex{__getitem__()}}
Fred Drakef6669171998-05-06 19:52:49 +0000824
Fred Drakef6669171998-05-06 19:52:49 +0000825
Fred Drake61c77281998-07-28 19:34:22 +0000826\subsection{Basic customization\label{customization}}
Fred Drakef6669171998-05-06 19:52:49 +0000827
Fred Drake1e42d8a1998-11-25 17:58:50 +0000828\begin{methoddesc}[object]{__init__}{self\optional{, args...}}
Fred Drakef6669171998-05-06 19:52:49 +0000829Called when the instance is created. The arguments are those passed
830to the class constructor expression. If a base class has an
Fred Drake82385871998-10-01 20:40:43 +0000831\method{__init__()} method the derived class's \method{__init__()} method must
Fred Drakef6669171998-05-06 19:52:49 +0000832explicitly call it to ensure proper initialization of the base class
Fred Draked82575d1998-08-28 20:03:12 +0000833part of the instance, e.g., \samp{BaseClass.__init__(\var{self},
834[\var{args}...])}.
Fred Drakef6669171998-05-06 19:52:49 +0000835\indexii{class}{constructor}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000836\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000837
838
Fred Drake1e42d8a1998-11-25 17:58:50 +0000839\begin{methoddesc}[object]{__del__}{self}
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000840Called when the instance is about to be destroyed. This is also
841called a destructor\index{destructor}. If a base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000842has a \method{__del__()} method, the derived class's \method{__del__()} method
Fred Drakef6669171998-05-06 19:52:49 +0000843must explicitly call it to ensure proper deletion of the base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000844part of the instance. Note that it is possible (though not recommended!)
845for the \method{__del__()}
Fred Drakef6669171998-05-06 19:52:49 +0000846method to postpone destruction of the instance by creating a new
847reference to it. It may then be called at a later time when this new
848reference is deleted. It is not guaranteed that
849\method{__del__()} methods are called for objects that still exist when
850the interpreter exits.
Fred Drakef6669171998-05-06 19:52:49 +0000851\stindex{del}
852
Fred Drake82385871998-10-01 20:40:43 +0000853\strong{Programmer's note:} \samp{del x} doesn't directly call
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000854\code{x.__del__()} --- the former decrements the reference count for
855\code{x} by one, and the latter is only called when its reference
856count reaches zero. Some common situations that may prevent the
857reference count of an object to go to zero include: circular
858references between objects (e.g., a doubly-linked list or a tree data
859structure with parent and child pointers); a reference to the object
860on the stack frame of a function that caught an exception (the
861traceback stored in \code{sys.exc_traceback} keeps the stack frame
862alive); or a reference to the object on the stack frame that raised an
863unhandled exception in interactive mode (the traceback stored in
864\code{sys.last_traceback} keeps the stack frame alive). The first
865situation can only be remedied by explicitly breaking the cycles; the
866latter two situations can be resolved by storing None in
867\code{sys.exc_traceback} or \code{sys.last_traceback}.
Fred Drakef6669171998-05-06 19:52:49 +0000868
869\strong{Warning:} due to the precarious circumstances under which
Fred Draked82575d1998-08-28 20:03:12 +0000870\method{__del__()} methods are invoked, exceptions that occur during their
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000871execution are ignored, and a warning is printed to \code{sys.stderr}
Fred Draked82575d1998-08-28 20:03:12 +0000872instead. Also, when \method{__del__()} is invoked is response to a module
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000873being deleted (e.g., when execution of the program is done), other
Fred Draked82575d1998-08-28 20:03:12 +0000874globals referenced by the \method{__del__()} method may already have been
875deleted. For this reason, \method{__del__()} methods should do the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000876absolute minimum needed to maintain external invariants. Python 1.5
877guarantees that globals whose name begins with a single underscore are
878deleted from their module before other globals are deleted; if no
879other references to such globals exist, this may help in assuring that
880imported modules are still available at the time when the
Fred Draked82575d1998-08-28 20:03:12 +0000881\method{__del__()} method is called.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000882\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000883
Fred Drake1e42d8a1998-11-25 17:58:50 +0000884\begin{methoddesc}[object]{__repr__}{self}
Fred Drake82385871998-10-01 20:40:43 +0000885Called by the \function{repr()}\bifuncindex{repr} built-in function
886and by string conversions (reverse quotes) to compute the ``official''
887string representation of an object. This should normally look like a
888valid Python expression that can be used to recreate an object with
889the same value. By convention, objects which cannot be trivially
890converted to strings which can be used to create a similar object
891produce a string of the form \samp{<\var{...some useful
892description...}>}.
Fred Drakef6669171998-05-06 19:52:49 +0000893\indexii{string}{conversion}
894\indexii{reverse}{quotes}
895\indexii{backward}{quotes}
896\index{back-quotes}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000897\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000898
Fred Drake1e42d8a1998-11-25 17:58:50 +0000899\begin{methoddesc}[object]{__str__}{self}
Fred Draked82575d1998-08-28 20:03:12 +0000900Called by the \function{str()}\bifuncindex{str} built-in function and
901by the \keyword{print}\stindex{print} statement to compute the
Fred Drake82385871998-10-01 20:40:43 +0000902``informal'' string representation of an object. This differs from
903\method{__repr__()} in that it does not have to be a valid Python
904expression: a more convenient or concise representation may be used
905instead.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000906\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000907
Fred Drake1e42d8a1998-11-25 17:58:50 +0000908\begin{methoddesc}[object]{__cmp__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000909Called by all comparison operations. Should return a negative integer if
910\code{self < other}, zero if \code{self == other}, a positive integer if
Fred Drakef6669171998-05-06 19:52:49 +0000911\code{self > other}. If no \method{__cmp__()} operation is defined, class
912instances are compared by object identity (``address'').
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000913(Note: the restriction that exceptions are not propagated by
Fred Drake82385871998-10-01 20:40:43 +0000914\method{__cmp__()} has been removed in Python 1.5.)
Fred Drakef6669171998-05-06 19:52:49 +0000915\bifuncindex{cmp}
916\index{comparisons}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000917\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000918
Fred Drake1e42d8a1998-11-25 17:58:50 +0000919\begin{methoddesc}[object]{__hash__}{self}
Fred Draked82575d1998-08-28 20:03:12 +0000920Called for the key object for dictionary\obindex{dictionary}
921operations, and by the built-in function
Fred Drakef6669171998-05-06 19:52:49 +0000922\function{hash()}\bifuncindex{hash}. Should return a 32-bit integer
923usable as a hash value
924for dictionary operations. The only required property is that objects
925which compare equal have the same hash value; it is advised to somehow
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000926mix together (e.g., using exclusive or) the hash values for the
Fred Drakef6669171998-05-06 19:52:49 +0000927components of the object that also play a part in comparison of
928objects. If a class does not define a \method{__cmp__()} method it should
929not define a \method{__hash__()} operation either; if it defines
930\method{__cmp__()} but not \method{__hash__()} its instances will not be
931usable as dictionary keys. If a class defines mutable objects and
932implements a \method{__cmp__()} method it should not implement
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000933\method{__hash__()}, since the dictionary implementation requires that
934a key's hash value is immutable (if the object's hash value changes, it
935will be in the wrong hash bucket).
Fred Drake1e42d8a1998-11-25 17:58:50 +0000936\withsubitem{(object method)}{\ttindex{__cmp__()}}
937\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000938
Fred Drake1e42d8a1998-11-25 17:58:50 +0000939\begin{methoddesc}[object]{__nonzero__}{self}
Fred Draked82575d1998-08-28 20:03:12 +0000940Called to implement truth value testing; should return \code{0} or
941\code{1}. When this method is not defined, \method{__len__()} is
942called, if it is defined (see below). If a class defines neither
943\method{__len__()} nor \method{__nonzero__()}, all its instances are
944considered true.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000945\withsubitem{(mapping object method)}{\ttindex{__len__()}}
946\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000947
948
Fred Drake61c77281998-07-28 19:34:22 +0000949\subsection{Customizing attribute access\label{attribute-access}}
Fred Drakef6669171998-05-06 19:52:49 +0000950
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000951The following methods can be defined to customize the meaning of
952attribute access (use of, assignment to, or deletion of \code{x.name})
953for class instances.
954For performance reasons, these methods are cached in the class object
955at class definition time; therefore, they cannot be changed after the
956class definition is executed.
Fred Drakef6669171998-05-06 19:52:49 +0000957
Fred Drake1e42d8a1998-11-25 17:58:50 +0000958\begin{methoddesc}[object]{__getattr__}{self, name}
Fred Drakef6669171998-05-06 19:52:49 +0000959Called when an attribute lookup has not found the attribute in the
960usual places (i.e. it is not an instance attribute nor is it found in
961the class tree for \code{self}). \code{name} is the attribute name.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000962This method should return the (computed) attribute value or raise an
Fred Draked82575d1998-08-28 20:03:12 +0000963\exception{AttributeError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000964
965Note that if the attribute is found through the normal mechanism,
Fred Draked82575d1998-08-28 20:03:12 +0000966\method{__getattr__()} is not called. (This is an intentional
967asymmetry between \method{__getattr__()} and \method{__setattr__()}.)
Fred Drakef6669171998-05-06 19:52:49 +0000968This is done both for efficiency reasons and because otherwise
Fred Draked82575d1998-08-28 20:03:12 +0000969\method{__setattr__()} would have no way to access other attributes of
970the instance.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000971Note that at least for instance variables, you can fake
972total control by not inserting any values in the instance
973attribute dictionary (but instead inserting them in another object).
Fred Drake1e42d8a1998-11-25 17:58:50 +0000974\withsubitem{(object method)}{\ttindex{__setattr__()}}
975\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000976
Fred Drake1e42d8a1998-11-25 17:58:50 +0000977\begin{methoddesc}[object]{__setattr__}{self, name, value}
Fred Drakef6669171998-05-06 19:52:49 +0000978Called when an attribute assignment is attempted. This is called
Fred Draked82575d1998-08-28 20:03:12 +0000979instead of the normal mechanism (i.e.\ store the value in the instance
980dictionary). \var{name} is the attribute name, \var{value} is the
Fred Drakef6669171998-05-06 19:52:49 +0000981value to be assigned to it.
Fred Drakef6669171998-05-06 19:52:49 +0000982
Fred Draked82575d1998-08-28 20:03:12 +0000983If \method{__setattr__()} wants to assign to an instance attribute, it
984should not simply execute \samp{self.\var{name} = value} --- this
985would cause a recursive call to itself. Instead, it should insert the
986value in the dictionary of instance attributes, e.g.,
987\samp{self.__dict__[\var{name}] = value}.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000988\withsubitem{(instance attribute)}{\ttindex{__dict__}}
989\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000990
Fred Drake1e42d8a1998-11-25 17:58:50 +0000991\begin{methoddesc}[object]{__delattr__}{self, name}
Fred Draked82575d1998-08-28 20:03:12 +0000992Like \method{__setattr__()} but for attribute deletion instead of
Fred Drake1e42d8a1998-11-25 17:58:50 +0000993assignment. This should only be implemented if \samp{del
994obj.\var{name}} is meaningful for the object.
995\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +0000996
997
Fred Drake61c77281998-07-28 19:34:22 +0000998\subsection{Emulating callable objects\label{callable-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000999
Fred Drake1e42d8a1998-11-25 17:58:50 +00001000\begin{methoddesc}[object]{__call__}{self\optional{, args...}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001001Called when the instance is ``called'' as a function; if this method
Fred Draked82575d1998-08-28 20:03:12 +00001002is defined, \code{\var{x}(arg1, arg2, ...)} is a shorthand for
1003\code{\var{x}.__call__(arg1, arg2, ...)}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001004\indexii{call}{instance}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001005\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001006
1007
Fred Drake61c77281998-07-28 19:34:22 +00001008\subsection{Emulating sequence and mapping types\label{sequence-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001009
1010The following methods can be defined to emulate sequence or mapping
1011objects. The first set of methods is used either to emulate a
1012sequence or to emulate a mapping; the difference is that for a
1013sequence, the allowable keys should be the integers \var{k} for which
1014\code{0 <= \var{k} < \var{N}} where \var{N} is the length of the
1015sequence, and the method \method{__getslice__()} (see below) should be
1016defined. It is also recommended that mappings provide methods
1017\method{keys()}, \method{values()}, \method{items()},
1018\method{has_key()}, \method{get()}, \method{clear()}, \method{copy()},
Fred Draked82575d1998-08-28 20:03:12 +00001019and \method{update()} behaving similar to those for
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001020Python's standard dictionary objects; mutable sequences should provide
1021methods \method{append()}, \method{count()}, \method{index()},
1022\method{insert()}, \method{pop()}, \method{remove()}, \method{reverse()}
1023and \method{sort()}, like Python standard list objects. Finally,
1024sequence types should implement addition (meaning concatenation) and
1025multiplication (meaning repetition) by defining the methods
1026\method{__add__()}, \method{__radd__()}, \method{__mul__()} and
1027\method{__rmul__()} described below; they should not define
1028\method{__coerce__()} or other numerical operators.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001029\withsubitem{(mapping object method)}{%
1030 \ttindex{keys()}%
1031 \ttindex{values()}%
1032 \ttindex{items()}%
1033 \ttindex{has_key()}%
1034 \ttindex{get()}%
1035 \ttindex{clear()}%
1036 \ttindex{copy()}%
1037 \ttindex{update()}}
1038\withsubitem{(sequence object method)}{%
1039 \ttindex{append()}%
1040 \ttindex{count()}%
1041 \ttindex{index()}%
1042 \ttindex{insert()}%
1043 \ttindex{pop()}%
1044 \ttindex{remove()}%
1045 \ttindex{reverse()}%
1046 \ttindex{sort()}%
1047 \ttindex{__add__()}%
1048 \ttindex{__radd__()}%
1049 \ttindex{__mul__()}%
1050 \ttindex{__rmul__()}}
1051\withsubitem{(numberic object method)}{\ttindex{__coerce__()}}
Fred Drakef6669171998-05-06 19:52:49 +00001052
Fred Drake1e42d8a1998-11-25 17:58:50 +00001053\begin{methoddesc}[mapping object]{__len__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001054Called to implement the built-in function
1055\function{len()}\bifuncindex{len}. Should return the length of the
1056object, an integer \code{>=} 0. Also, an object that doesn't define a
1057\method{__nonzero__()} method and whose \method{__len__()} method
1058returns zero is considered to be false in a Boolean context.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001059\withsubitem{(object method)}{\ttindex{__nonzero__()}}
1060\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001061
Fred Drake1e42d8a1998-11-25 17:58:50 +00001062\begin{methoddesc}[mapping object]{__getitem__}{self, key}
Fred Draked82575d1998-08-28 20:03:12 +00001063Called to implement evaluation of \code{\var{self}[\var{key}]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001064For a sequence types, the accepted keys should be integers. Note that the
1065special interpretation of negative indices (if the class wishes to
Fred Drakef6669171998-05-06 19:52:49 +00001066emulate a sequence type) is up to the \method{__getitem__()} method.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001067\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001068
Fred Drake1e42d8a1998-11-25 17:58:50 +00001069\begin{methoddesc}[mapping object]{__setitem__}{self, key, value}
Fred Draked82575d1998-08-28 20:03:12 +00001070Called to implement assignment to \code{\var{self}[\var{key}]}. Same
Fred Drake1e42d8a1998-11-25 17:58:50 +00001071note as for \method{__getitem__()}. This should only be implemented
1072for mappings if the objects support changes to the values for keys, or
1073if new keys can be added, or for sequences if elements can be
1074replaced.
1075\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001076
Fred Drake1e42d8a1998-11-25 17:58:50 +00001077\begin{methoddesc}[mapping object]{__delitem__}{self, key}
Fred Draked82575d1998-08-28 20:03:12 +00001078Called to implement deletion of \code{\var{self}[\var{key}]}. Same
Fred Drake1e42d8a1998-11-25 17:58:50 +00001079note as for \method{__getitem__()}. This should only be implemented
1080for mappings if the objects support removal of keys, or for sequences
1081if elements can be removed from the sequence.
1082\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001083
1084
Fred Drake3041b071998-10-21 00:25:32 +00001085\subsection{Additional methods for emulation of sequence types
Fred Drake61c77281998-07-28 19:34:22 +00001086 \label{sequence-methods}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001087
1088The following methods can be defined to further emulate sequence
1089objects. Immutable sequences methods should only define
1090\method{__getslice__()}; mutable sequences, should define all three
1091three methods.
Fred Drakef6669171998-05-06 19:52:49 +00001092
Fred Drake1e42d8a1998-11-25 17:58:50 +00001093\begin{methoddesc}[sequence object]{__getslice__}{self, i, j}
Fred Draked82575d1998-08-28 20:03:12 +00001094Called to implement evaluation of \code{\var{self}[\var{i}:\var{j}]}.
1095The returned object should be of the same type as \var{self}. Note
1096that missing \var{i} or \var{j} in the slice expression are replaced
1097by zero or \code{sys.maxint}, respectively, and no further
1098transformations on the indices is performed. The interpretation of
1099negative indices and indices larger than the length of the sequence is
1100up to the method.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001101\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001102
Fred Drake1e42d8a1998-11-25 17:58:50 +00001103\begin{methoddesc}[sequence object]{__setslice__}{self, i, j, sequence}
Fred Draked82575d1998-08-28 20:03:12 +00001104Called to implement assignment to \code{\var{self}[\var{i}:\var{j}]}.
1105Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001106\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001107
Fred Drake1e42d8a1998-11-25 17:58:50 +00001108\begin{methoddesc}[sequence object]{__delslice__}{self, i, j}
Fred Draked82575d1998-08-28 20:03:12 +00001109Called to implement deletion of \code{\var{self}[\var{i}:\var{j}]}.
1110Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001111\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001112
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001113Notice that these methods are only invoked when a single slice with a
1114single colon is used. For slice operations involving extended slice
1115notation, \method{__getitem__()}, \method{__setitem__()}
1116or\method{__delitem__()} is called.
Fred Drakef6669171998-05-06 19:52:49 +00001117
Fred Drake61c77281998-07-28 19:34:22 +00001118\subsection{Emulating numeric types\label{numeric-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001119
1120The following methods can be defined to emulate numeric objects.
1121Methods corresponding to operations that are not supported by the
1122particular kind of number implemented (e.g., bitwise operations for
1123non-integral numbers) should be left undefined.
Fred Drakef6669171998-05-06 19:52:49 +00001124
Fred Drake1e42d8a1998-11-25 17:58:50 +00001125\begin{methoddesc}[numberic interface]{__add__}{self, other}
1126\methodline{__sub__}{self, other}
1127\methodline{__mul__}{self, other}
1128\methodline{__div__}{self, other}
1129\methodline{__mod__}{self, other}
1130\methodline{__divmod__}{self, other}
1131\methodline{__pow__}{self, other\optional{, modulo}}
1132\methodline{__lshift__}{self, other}
1133\methodline{__rshift__}{self, other}
1134\methodline{__and__}{self, other}
1135\methodline{__xor__}{self, other}
1136\methodline{__or__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001137These functions are
1138called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001139\code{-}, \code{*}, \code{/}, \code{\%},
1140\function{divmod()}\bifuncindex{divmod},
1141\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<}, \code{>>},
1142\code{\&}, \code{\^}, \code{|}). For instance, to evaluate the
1143expression \var{x}\code{+}\var{y}, where \var{x} is an instance of a
1144class that has an \method{__add__()} method,
1145\code{\var{x}.__add__(\var{y})} is called. Note that
1146\method{__pow__()} should be defined to accept an optional third
1147argument if the ternary version of the built-in
1148\function{pow()}\bifuncindex{pow} function is to be supported.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001149\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001150
Fred Drake1e42d8a1998-11-25 17:58:50 +00001151\begin{methoddesc}[numeric interface]{__radd__}{self, other}
1152\methodline{__rsub__}{self, other}
1153\methodline{__rmul__}{self, other}
1154\methodline{__rdiv__}{self, other}
1155\methodline{__rmod__}{self, other}
1156\methodline{__rdivmod__}{self, other}
1157\methodline{__rpow__}{self, other}
1158\methodline{__rlshift__}{self, other}
1159\methodline{__rrshift__}{self, other}
1160\methodline{__rand__}{self, other}
1161\methodline{__rxor__}{self, other}
1162\methodline{__ror__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001163These functions are
1164called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001165\code{-}, \code{*}, \code{/}, \code{\%},
1166\function{divmod()}\bifuncindex{divmod},
1167\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<}, \code{>>},
1168\code{\&}, \code{\^}, \code{|}) with reversed operands. These
1169functions are only called if the left operand does not support the
1170corresponding operation. For instance, to evaluate the expression
1171\var{x}\code{-}\var{y}, where \var{y} is an instance of a class that
1172has an \method{__rsub__()} method, \code{\var{y}.__rsub__(\var{x})} is
1173called. Note that ternary \function{pow()}\bifuncindex{pow} will not
1174try calling \method{__rpow__()} (the coercion rules would become too
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001175complicated).
Fred Drake1e42d8a1998-11-25 17:58:50 +00001176\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001177
Fred Drake1e42d8a1998-11-25 17:58:50 +00001178\begin{methoddesc}[numeric interface]{__neg__}{self}
1179\methodline{__pos__}{self}
1180\methodline{__abs__}{self}
1181\methodline{__invert__}{self}
Fred Drakef6669171998-05-06 19:52:49 +00001182Called to implement the unary arithmetic operations (\code{-}, \code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001183\function{abs()}\bifuncindex{abs} and \code{~}).
Fred Drake1e42d8a1998-11-25 17:58:50 +00001184\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001185
Fred Drake1e42d8a1998-11-25 17:58:50 +00001186\begin{methoddesc}[numeric interface]{__int__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001187\methodlineni{__long__}{self}
1188\methodlineni{__float__}{self}
1189Called to implement the built-in functions
1190\function{int()}\bifuncindex{int}, \function{long()}\bifuncindex{long}
1191and \function{float()}\bifuncindex{float}. Should return a value of
1192the appropriate type.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001193\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001194
Fred Drake1e42d8a1998-11-25 17:58:50 +00001195\begin{methoddesc}[numeric interface]{__oct__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001196\methodlineni{__hex__}{self}
1197Called to implement the built-in functions
1198\function{oct()}\bifuncindex{oct} and
1199\function{hex()}\bifuncindex{hex}. Should return a string value.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001200\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001201
Fred Drake1e42d8a1998-11-25 17:58:50 +00001202\begin{methoddesc}[numeric interface]{__coerce__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001203Called to implement ``mixed-mode'' numeric arithmetic. Should either
Fred Draked82575d1998-08-28 20:03:12 +00001204return a 2-tuple containing \var{self} and \var{other} converted to
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001205a common numeric type, or \code{None} if conversion is possible. When
1206the common type would be the type of \code{other}, it is sufficient to
1207return \code{None}, since the interpreter will also ask the other
1208object to attempt a coercion (but sometimes, if the implementation of
1209the other type cannot be changed, it is useful to do the conversion to
1210the other type here).
Fred Drake1e42d8a1998-11-25 17:58:50 +00001211\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001212
1213\strong{Coercion rules}: to evaluate \var{x} \var{op} \var{y}, the
1214following steps are taken (where \method{__op__()} and
1215\method{__rop__()} are the method names corresponding to \var{op},
Guido van Rossum7c0240f1998-07-24 15:36:43 +00001216e.g., if var{op} is `\code{+}', \method{__add__()} and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001217\method{__radd__()} are used). If an exception occurs at any point,
1218the evaluation is abandoned and exception handling takes over.
1219
1220\begin{itemize}
1221
1222\item[0.] If \var{x} is a string object and op is the modulo operator (\%),
1223the string formatting operation is invoked and the remaining steps are
1224skipped.
1225
1226\item[1.] If \var{x} is a class instance:
1227
1228 \begin{itemize}
1229
1230 \item[1a.] If \var{x} has a \method{__coerce__()} method:
1231 replace \var{x} and \var{y} with the 2-tuple returned by
1232 \code{\var{x}.__coerce__(\var{y})}; skip to step 2 if the
1233 coercion returns \code{None}.
1234
1235 \item[1b.] If neither \var{x} nor \var{y} is a class instance
1236 after coercion, go to step 3.
1237
1238 \item[1c.] If \var{x} has a method \method{__op__()}, return
1239 \code{\var{x}.__op__(\var{y})}; otherwise, restore \var{x} and
1240 \var{y} to their value before step 1a.
1241
1242 \end{itemize}
1243
1244\item[2.] If \var{y} is a class instance:
1245
1246 \begin{itemize}
1247
1248 \item[2a.] If \var{y} has a \method{__coerce__()} method:
1249 replace \var{y} and \var{x} with the 2-tuple returned by
1250 \code{\var{y}.__coerce__(\var{x})}; skip to step 3 if the
1251 coercion returns \code{None}.
1252
1253 \item[2b.] If neither \var{x} nor \var{y} is a class instance
1254 after coercion, go to step 3.
1255
1256 \item[2b.] If \var{y} has a method \method{__rop__()}, return
1257 \code{\var{y}.__rop__(\var{x})}; otherwise, restore \var{x}
1258 and \var{y} to their value before step 2a.
1259
1260 \end{itemize}
1261
1262\item[3.] We only get here if neither \var{x} nor \var{y} is a class
1263instance.
1264
1265 \begin{itemize}
1266
1267 \item[3a.] If op is `\code{+}' and \var{x} is a sequence,
1268 sequence concatenation is invoked.
1269
1270 \item[3b.] If op is `\code{*}' and one operand is a sequence
1271 and the other an integer, sequence repetition is invoked.
1272
1273 \item[3c.] Otherwise, both operands must be numbers; they are
1274 coerced to a common type if possible, and the numeric
1275 operation is invoked for that type.
1276
1277 \end{itemize}
1278
1279\end{itemize}