blob: 7b0d0d6e0113a0db1c72c8a1b8d7cf974a052c71 [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}
113\ttindex{__methods__}
114\ttindex{__members__}
115
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}
125\obindex{None@{\tt None}}
126
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}
133\obindex{Ellipsis@{\tt Ellipsis}}
134
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}
233%
234\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.
390\ttindex{func_doc}
391\ttindex{__doc__}
392\ttindex{__name__}
393\ttindex{func_defaults}
Fred Drakef6669171998-05-06 19:52:49 +0000394\ttindex{func_code}
395\ttindex{func_globals}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000396\indexii{global}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000397
398\item[User-defined methods]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000399A user-defined method object combines a class, a class instance (or
400\code{None}) and a user-defined function.
Fred Drakef6669171998-05-06 19:52:49 +0000401\obindex{method}
402\obindex{user-defined method}
403\indexii{user-defined}{method}
Fred Drakef6669171998-05-06 19:52:49 +0000404
405Special read-only attributes: \member{im_self} is the class instance
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000406object, \member{im_func} is the function object;
Fred Drake82385871998-10-01 20:40:43 +0000407\member{im_class} is the class that defined the method (which may be a
408base class of the class of which \member{im_self} is an instance);
409\member{__doc__} is the method's documentation (same as
410\code{im_func.__doc__}); \member{__name__} is the method name (same as
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000411\code{im_func.__name__}).
412
413User-defined method objects are created in two ways: when getting an
414attribute of a class that is a user-defined function object, or when
415getting an attributes of a class instance that is a user-defined
416function object. In the former case (class attribute), the
Fred Drake82385871998-10-01 20:40:43 +0000417\member{im_self} attribute is \code{None}, and the method object is said
418to be unbound; in the latter case (instance attribute), \method{im_self}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000419is the instance, and the method object is said to be bound. For
Fred Drake82385871998-10-01 20:40:43 +0000420instance, when \class{C} is a class which contains a definition for a
421function \method{f()}, \code{C.f} does not yield the function object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000422\code{f}; rather, it yields an unbound method object \code{m} where
Fred Drake82385871998-10-01 20:40:43 +0000423\code{m.im_class} is \class{C}, \code{m.im_func} is \method{f()}, and
424\code{m.im_self} is \code{None}. When \code{x} is a \class{C}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000425instance, \code{x.f} yields a bound method object \code{m} where
Fred Drake82385871998-10-01 20:40:43 +0000426\code{m.im_class} is \code{C}, \code{m.im_func} is \method{f()}, and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000427\code{m.im_self} is \code{x}.
428
429When an unbound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000430function (\member{im_func}) is called, with the restriction that the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000431first argument must be an instance of the proper class
Fred Drake82385871998-10-01 20:40:43 +0000432(\member{im_class}) or of a derived class thereof.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000433
434When a bound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000435function (\member{im_func}) is called, inserting the class instance
436(\member{im_self}) in front of the argument list. For instance, when
437\class{C} is a class which contains a definition for a function
438\method{f()}, and \code{x} is an instance of \class{C}, calling
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000439\code{x.f(1)} is equivalent to calling \code{C.f(x, 1)}.
440
441Note that the transformation from function object to (unbound or
442bound) method object happens each time the attribute is retrieved from
443the class or instance. In some cases, a fruitful optimization is to
444assign the attribute to a local variable and call that local variable.
445Also notice that this transformation only happens for user-defined
446functions; other callable objects (and all non-callable objects) are
447retrieved without transformation.
448
Fred Drakef6669171998-05-06 19:52:49 +0000449\ttindex{im_func}
450\ttindex{im_self}
451
452\item[Built-in functions]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000453A built-in function object is a wrapper around a \C{} function. Examples
454of built-in functions are \function{len()} and \function{math.sin()}
455(\module{math} is a standard built-in module).
456The number and type of the arguments are
Fred Drakef6669171998-05-06 19:52:49 +0000457determined by the C function.
Fred Drake82385871998-10-01 20:40:43 +0000458Special read-only attributes: \member{__doc__} is the function's
459documentation string, or \code{None} if unavailable; \member{__name__}
460is the function's name; \member{__self__} is set to \code{None} (but see
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000461the next item).
Fred Drakef6669171998-05-06 19:52:49 +0000462\obindex{built-in function}
463\obindex{function}
464\indexii{C}{language}
465
466\item[Built-in methods]
467This is really a different disguise of a built-in function, this time
468containing an object passed to the \C{} function as an implicit extra
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000469argument. An example of a built-in method is
470\code{\var{list}.append()}, assuming
Fred Drakef6669171998-05-06 19:52:49 +0000471\var{list} is a list object.
Fred Drake82385871998-10-01 20:40:43 +0000472In this case, the special read-only attribute \member{__self__} is set
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000473to the object denoted by \code{list}.
Fred Drakef6669171998-05-06 19:52:49 +0000474\obindex{built-in method}
475\obindex{method}
476\indexii{built-in}{method}
477
478\item[Classes]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000479Class objects are described below. When a class object is called,
480a new class instance (also described below) is created and
Fred Drakef6669171998-05-06 19:52:49 +0000481returned. This implies a call to the class's \method{__init__()} method
482if it has one. Any arguments are passed on to the \method{__init__()}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000483method. If there is no \method{__init__()} method, the class must be called
Fred Drakef6669171998-05-06 19:52:49 +0000484without arguments.
485\ttindex{__init__}
486\obindex{class}
487\obindex{class instance}
488\obindex{instance}
489\indexii{class object}{call}
490
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000491\item[Class instances]
492Class instances are described below. Class instances are callable
Fred Drake82385871998-10-01 20:40:43 +0000493only when the class has a \method{__call__()} method; \code{x(arguments)}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000494is a shorthand for \code{x.__call__(arguments)}.
495
Fred Drakef6669171998-05-06 19:52:49 +0000496\end{description}
497
498\item[Modules]
499Modules are imported by the \keyword{import} statement (see section
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000500\ref{import}, ``The \keyword{import} statement'').
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000501A module object has a namespace implemented by a dictionary object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000502(this is the dictionary referenced by the func_globals attribute of
503functions defined in the module). Attribute references are translated
504to lookups in this dictionary, e.g., \code{m.x} is equivalent to
505\code{m.__dict__["x"]}.
506A module object does not contain the code object used to
Fred Drakef6669171998-05-06 19:52:49 +0000507initialize the module (since it isn't needed once the initialization
508is done).
509\stindex{import}
510\obindex{module}
511
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000512Attribute assignment updates the module's namespace dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000513e.g., \samp{m.x = 1} is equivalent to \samp{m.__dict__["x"] = 1}.
Fred Drakef6669171998-05-06 19:52:49 +0000514
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000515Special read-only attribute: \member{__dict__} is the module's
516namespace as a dictionary object.
Fred Drakef6669171998-05-06 19:52:49 +0000517\ttindex{__dict__}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000518
519Predefined (writable) attributes: \member{__name__}
520is the module's name; \member{__doc__} is the
521module's documentation string, or
Fred Drake82385871998-10-01 20:40:43 +0000522\code{None} if unavailable; \member{__file__} is the pathname of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000523file from which the module was loaded, if it was loaded from a file.
Fred Drake82385871998-10-01 20:40:43 +0000524The \member{__file__} attribute is not present for C{} modules that are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000525statically linked into the interpreter; for extension modules loaded
526dynamically from a shared library, it is the pathname of the shared
527library file.
Fred Drakef6669171998-05-06 19:52:49 +0000528\ttindex{__name__}
529\ttindex{__doc__}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000530\ttindex{__file__}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000531\indexii{module}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000532
533\item[Classes]
534Class objects are created by class definitions (see section
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000535\ref{class}, ``Class definitions'').
536A class has a namespace implemented by a dictionary object.
537Class attribute references are translated to
538lookups in this dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000539e.g., \samp{C.x} is translated to \samp{C.__dict__["x"]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000540When the attribute name is not found
Fred Drakef6669171998-05-06 19:52:49 +0000541there, the attribute search continues in the base classes. The search
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000542is depth-first, left-to-right in the order of occurrence in the
Fred Drakef6669171998-05-06 19:52:49 +0000543base class list.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000544When a class attribute reference would yield a user-defined function
545object, it is transformed into an unbound user-defined method object
Fred Drake82385871998-10-01 20:40:43 +0000546(see above). The \member{im_class} attribute of this method object is the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000547class in which the function object was found, not necessarily the
548class for which the attribute reference was initiated.
Fred Drakef6669171998-05-06 19:52:49 +0000549\obindex{class}
550\obindex{class instance}
551\obindex{instance}
552\indexii{class object}{call}
553\index{container}
554\obindex{dictionary}
555\indexii{class}{attribute}
556
557Class attribute assignments update the class's dictionary, never the
558dictionary of a base class.
559\indexiii{class}{attribute}{assignment}
560
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000561A class object can be called (see above) to yield a class instance (see
562below).
Fred Drakef6669171998-05-06 19:52:49 +0000563\indexii{class object}{call}
564
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000565Special attributes: \member{__name__} is the class name;
566\member{__module__} is the module name in which the class was defined;
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000567\member{__dict__} is the dictionary containing the class's namespace;
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000568\member{__bases__} is a tuple (possibly empty or a singleton)
569containing the base classes, in the order of their occurrence in the
Fred Drake82385871998-10-01 20:40:43 +0000570base class list; \member{__doc__} is the class's documentation string,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000571or None if undefined.
572\ttindex{__name__}
573\ttindex{__module__}
Fred Drakef6669171998-05-06 19:52:49 +0000574\ttindex{__dict__}
575\ttindex{__bases__}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000576\ttindex{__doc__}
Fred Drakef6669171998-05-06 19:52:49 +0000577
578\item[Class instances]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000579A class instance is created by calling a class object (see above).
580A class instance has a namespace implemented as a dictionary which
581is the first place in which
Fred Drakef6669171998-05-06 19:52:49 +0000582attribute references are searched. When an attribute is not found
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000583there, and the instance's class has an attribute by that name,
584the search continues with the class attributes. If a class attribute
585is found that is a user-defined function object (and in no other
586case), it is transformed into an unbound user-defined method object
Fred Drake82385871998-10-01 20:40:43 +0000587(see above). The \member{im_class} attribute of this method object is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000588the class in which the function object was found, not necessarily the
589class of the instance for which the attribute reference was initiated.
590If no class attribute is found, and the object's class has a
Fred Drake82385871998-10-01 20:40:43 +0000591\method{__getattr__()} method, that is called to satisfy the lookup.
Fred Drakef6669171998-05-06 19:52:49 +0000592\obindex{class instance}
593\obindex{instance}
594\indexii{class}{instance}
595\indexii{class instance}{attribute}
596
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000597Attribute assignments and deletions update the instance's dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000598never a class's dictionary. If the class has a \method{__setattr__()} or
599\method{__delattr__()} method, this is called instead of updating the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000600instance dictionary directly.
Fred Drakef6669171998-05-06 19:52:49 +0000601\indexiii{class instance}{attribute}{assignment}
602
603Class instances can pretend to be numbers, sequences, or mappings if
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000604they have methods with certain special names. See
605section \ref{specialnames}, ``Special method names.''
Fred Drakef6669171998-05-06 19:52:49 +0000606\obindex{number}
607\obindex{sequence}
608\obindex{mapping}
609
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000610Special attributes: \member{__dict__} is the attribute
611dictionary; \member{__class__} is the instance's class.
Fred Drakef6669171998-05-06 19:52:49 +0000612\ttindex{__dict__}
613\ttindex{__class__}
614
615\item[Files]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000616A file object represents an open file. File objects are created by the
617\function{open()} built-in function, and also by
618\function{os.popen()}, \function{os.fdopen()}, and the
619\method{makefile()} method of socket objects (and perhaps by other
620functions or methods provided by extension modules). The objects
621\code{sys.stdin}, \code{sys.stdout} and \code{sys.stderr} are
622initialized to file objects corresponding to the interpreter's
623standard input, output and error streams. See the \emph{Python
624Library Reference} for complete documentation of file objects.
Fred Drakef6669171998-05-06 19:52:49 +0000625\obindex{file}
626\indexii{C}{language}
627\index{stdio}
628\bifuncindex{open}
629\bifuncindex{popen}
630\bifuncindex{makefile}
631\ttindex{stdin}
632\ttindex{stdout}
633\ttindex{stderr}
634\ttindex{sys.stdin}
635\ttindex{sys.stdout}
636\ttindex{sys.stderr}
637
638\item[Internal types]
639A few types used internally by the interpreter are exposed to the user.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000640Their definitions may change with future versions of the interpreter,
Fred Drakef6669171998-05-06 19:52:49 +0000641but they are mentioned here for completeness.
642\index{internal type}
643\index{types, internal}
644
645\begin{description}
646
647\item[Code objects]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000648Code objects represent \emph{byte-compiled} executable Python code, or
649\emph{bytecode}.
Fred Drakef6669171998-05-06 19:52:49 +0000650The difference between a code
651object and a function object is that the function object contains an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000652explicit reference to the function's globals (the module in which it
653was defined), while a code object contains no context;
654also the default argument values are stored in the function object,
655not in the code object (because they represent values calculated at
656run-time). Unlike function objects, code objects are immutable and
657contain no references (directly or indirectly) to mutable objects.
658\index{bytecode}
Fred Drakef6669171998-05-06 19:52:49 +0000659\obindex{code}
660
Fred Drake82385871998-10-01 20:40:43 +0000661Special read-only attributes: \member{co_name}\ttindex{co_name} gives
662the function name; \member{co_argcount}\ttindex{co_argcount}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000663is the number of positional arguments (including arguments with
Fred Drake82385871998-10-01 20:40:43 +0000664default values); \member{co_nlocals}\ttindex{co_nlocals} is the number
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000665of local variables used by the function (including arguments);
Fred Drake82385871998-10-01 20:40:43 +0000666\member{co_varnames}\ttindex{co_varnames} is a tuple containing the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000667names of the local variables (starting with the argument names);
Fred Drake82385871998-10-01 20:40:43 +0000668\member{co_code}\ttindex{co_code} is a string representing the sequence
669of bytecode instructions; \member{co_consts}\ttindex{co_consts} is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000670tuple containing the literals used by the bytecode;
Fred Drake82385871998-10-01 20:40:43 +0000671\member{co_names}\ttindex{co_names} is a tuple containing the names used
672by the bytecode; \member{co_filename}\ttindex{co_filename} is the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000673filename from which the code was compiled;
Fred Drake82385871998-10-01 20:40:43 +0000674\member{co_firstlineno}\ttindex{co_firstlineno} is the first line number
675of the function; \member{co_lnotab}\ttindex{co_lnotab} is a string
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000676encoding the mapping from byte code offsets to line numbers (for
677detais see the source code of the interpreter);
Fred Drake82385871998-10-01 20:40:43 +0000678\member{co_stacksize}\ttindex{co_stacksize} is the required stack size
679(including local variables); \member{co_flags}\ttindex{co_flags} is an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000680integer encoding a number of flags for the interpreter.
681
Fred Drake82385871998-10-01 20:40:43 +0000682The following flag bits are defined for \member{co_flags}: bit 2 is set
683if the function uses the \samp{*arguments} syntax to accept an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000684arbitrary number of positional arguments; bit 3 is set if the function
Fred Drake82385871998-10-01 20:40:43 +0000685uses the \samp{**keywords} syntax to accept arbitrary keyword
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000686arguments; other bits are used internally or reserved for future use.
687If a code object represents a function, the first item in
Fred Drake82385871998-10-01 20:40:43 +0000688\member{co_consts} is the documentation string of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000689function, or \code{None} if undefined.
Fred Drakef6669171998-05-06 19:52:49 +0000690
691\item[Frame objects]
692Frame objects represent execution frames. They may occur in traceback
693objects (see below).
694\obindex{frame}
695
696Special read-only attributes: \member{f_back} is to the previous
697stack frame (towards the caller), or \code{None} if this is the bottom
698stack frame; \member{f_code} is the code object being executed in this
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000699frame; \member{f_locals} is the dictionary used to look up local
700variables; \member{f_globals} is used for global variables;
Fred Drake82385871998-10-01 20:40:43 +0000701\member{f_builtins} is used for built-in (intrinsic) names;
702\member{f_restricted} is a flag indicating whether the function is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000703executing in restricted execution mode;
Fred Drakef6669171998-05-06 19:52:49 +0000704\member{f_lineno} gives the line number and \member{f_lasti} gives the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000705precise instruction (this is an index into the bytecode string of
Fred Drakef6669171998-05-06 19:52:49 +0000706the code object).
707\ttindex{f_back}
708\ttindex{f_code}
709\ttindex{f_globals}
710\ttindex{f_locals}
711\ttindex{f_lineno}
712\ttindex{f_lasti}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000713\ttindex{f_builtins}
714\ttindex{f_restricted}
715
Fred Drake82385871998-10-01 20:40:43 +0000716Special writable attributes: \member{f_trace}, if not \code{None}, is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000717function called at the start of each source code line (this is used by
Fred Drake82385871998-10-01 20:40:43 +0000718the debugger); \member{f_exc_type}, \member{f_exc_value},
719\member{f_exc_traceback} represent the most recent exception caught in
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000720this frame.
721\ttindex{f_trace}
722\ttindex{f_exc_type}
723\ttindex{f_exc_value}
724\ttindex{f_exc_traceback}
Fred Drakef6669171998-05-06 19:52:49 +0000725
726\item[Traceback objects] \label{traceback}
727Traceback objects represent a stack trace of an exception. A
728traceback object is created when an exception occurs. When the search
729for an exception handler unwinds the execution stack, at each unwound
730level a traceback object is inserted in front of the current
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000731traceback. When an exception handler is entered, the stack trace is
732made available to the program.
733(See section \ref{try}, ``The \code{try} statement.'')
734It is accessible as \code{sys.exc_traceback}, and also as the third
735item of the tuple returned by \code{sys.exc_info()}. The latter is
736the preferred interface, since it works correctly when the program is
737using multiple threads.
738When the program contains no suitable handler, the stack trace is written
Fred Drakef6669171998-05-06 19:52:49 +0000739(nicely formatted) to the standard error stream; if the interpreter is
740interactive, it is also made available to the user as
741\code{sys.last_traceback}.
742\obindex{traceback}
743\indexii{stack}{trace}
744\indexii{exception}{handler}
745\indexii{execution}{stack}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000746\ttindex{exc_info}
Fred Drakef6669171998-05-06 19:52:49 +0000747\ttindex{exc_traceback}
748\ttindex{last_traceback}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000749\ttindex{sys.exc_info}
Fred Drakef6669171998-05-06 19:52:49 +0000750\ttindex{sys.exc_traceback}
751\ttindex{sys.last_traceback}
752
753Special read-only attributes: \member{tb_next} is the next level in the
754stack trace (towards the frame where the exception occurred), or
755\code{None} if there is no next level; \member{tb_frame} points to the
756execution frame of the current level; \member{tb_lineno} gives the line
757number where the exception occurred; \member{tb_lasti} indicates the
758precise instruction. The line number and last instruction in the
759traceback may differ from the line number of its frame object if the
760exception occurred in a \keyword{try} statement with no matching
761except clause or with a finally clause.
762\ttindex{tb_next}
763\ttindex{tb_frame}
764\ttindex{tb_lineno}
765\ttindex{tb_lasti}
766\stindex{try}
767
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000768\item[Slice objects]
769Slice objects are used to represent slices when \emph{extended slice
770syntax} is used. This is a slice using two colons, or multiple slices
771or ellipses separated by commas, e.g., \code{a[i:j:step]}, \code{a[i:j,
772k:l]}, or \code{a[..., i:j])}. They are also created by the built-in
773\function{slice()} function.
774
Fred Drake82385871998-10-01 20:40:43 +0000775Special read-only attributes: \member{start} is the lowerbound;
776\member{stop} is the upperbound; \member{step} is the step value; each is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000777\code{None} if omitted. These attributes can have any type.
778
Fred Drakef6669171998-05-06 19:52:49 +0000779\end{description} % Internal types
780
781\end{description} % Types
782
783
Fred Drake61c77281998-07-28 19:34:22 +0000784\section{Special method names\label{specialnames}}
Fred Drakef6669171998-05-06 19:52:49 +0000785
786A class can implement certain operations that are invoked by special
Fred Draked82575d1998-08-28 20:03:12 +0000787syntax (such as arithmetic operations or subscripting and slicing) by
788defining methods with special names. For instance, if a class defines
789a method named \method{__getitem__()}, and \code{x} is an instance of
790this class, then \code{x[i]} is equivalent to
791\code{x.__getitem__(i)}. (The reverse is not true --- if \code{x} is
792a list object, \code{x.__getitem__(i)} is not equivalent to
793\code{x[i]}.) Except where mentioned, attempts to execute an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000794operation raise an exception when no appropriate method is defined.
Fred Drakef6669171998-05-06 19:52:49 +0000795\ttindex{__getitem__}
796
Fred Drakef6669171998-05-06 19:52:49 +0000797
Fred Drake61c77281998-07-28 19:34:22 +0000798\subsection{Basic customization\label{customization}}
Fred Drakef6669171998-05-06 19:52:49 +0000799
Fred Draked82575d1998-08-28 20:03:12 +0000800\begin{methoddescni}{__init__}{self\optional{, args...}}
Fred Drakef6669171998-05-06 19:52:49 +0000801Called when the instance is created. The arguments are those passed
802to the class constructor expression. If a base class has an
Fred Drake82385871998-10-01 20:40:43 +0000803\method{__init__()} method the derived class's \method{__init__()} method must
Fred Drakef6669171998-05-06 19:52:49 +0000804explicitly call it to ensure proper initialization of the base class
Fred Draked82575d1998-08-28 20:03:12 +0000805part of the instance, e.g., \samp{BaseClass.__init__(\var{self},
806[\var{args}...])}.
Fred Drakef6669171998-05-06 19:52:49 +0000807\ttindex{__init__}
808\indexii{class}{constructor}
Fred Draked82575d1998-08-28 20:03:12 +0000809\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000810
811
Fred Draked82575d1998-08-28 20:03:12 +0000812\begin{methoddescni}{__del__}{self}
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000813Called when the instance is about to be destroyed. This is also
814called a destructor\index{destructor}. If a base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000815has a \method{__del__()} method, the derived class's \method{__del__()} method
Fred Drakef6669171998-05-06 19:52:49 +0000816must explicitly call it to ensure proper deletion of the base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000817part of the instance. Note that it is possible (though not recommended!)
818for the \method{__del__()}
Fred Drakef6669171998-05-06 19:52:49 +0000819method to postpone destruction of the instance by creating a new
820reference to it. It may then be called at a later time when this new
821reference is deleted. It is not guaranteed that
822\method{__del__()} methods are called for objects that still exist when
823the interpreter exits.
Fred Drakef6669171998-05-06 19:52:49 +0000824\ttindex{__del__}
825\stindex{del}
826
Fred Drake82385871998-10-01 20:40:43 +0000827\strong{Programmer's note:} \samp{del x} doesn't directly call
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000828\code{x.__del__()} --- the former decrements the reference count for
829\code{x} by one, and the latter is only called when its reference
830count reaches zero. Some common situations that may prevent the
831reference count of an object to go to zero include: circular
832references between objects (e.g., a doubly-linked list or a tree data
833structure with parent and child pointers); a reference to the object
834on the stack frame of a function that caught an exception (the
835traceback stored in \code{sys.exc_traceback} keeps the stack frame
836alive); or a reference to the object on the stack frame that raised an
837unhandled exception in interactive mode (the traceback stored in
838\code{sys.last_traceback} keeps the stack frame alive). The first
839situation can only be remedied by explicitly breaking the cycles; the
840latter two situations can be resolved by storing None in
841\code{sys.exc_traceback} or \code{sys.last_traceback}.
Fred Drakef6669171998-05-06 19:52:49 +0000842
843\strong{Warning:} due to the precarious circumstances under which
Fred Draked82575d1998-08-28 20:03:12 +0000844\method{__del__()} methods are invoked, exceptions that occur during their
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000845execution are ignored, and a warning is printed to \code{sys.stderr}
Fred Draked82575d1998-08-28 20:03:12 +0000846instead. Also, when \method{__del__()} is invoked is response to a module
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000847being deleted (e.g., when execution of the program is done), other
Fred Draked82575d1998-08-28 20:03:12 +0000848globals referenced by the \method{__del__()} method may already have been
849deleted. For this reason, \method{__del__()} methods should do the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000850absolute minimum needed to maintain external invariants. Python 1.5
851guarantees that globals whose name begins with a single underscore are
852deleted from their module before other globals are deleted; if no
853other references to such globals exist, this may help in assuring that
854imported modules are still available at the time when the
Fred Draked82575d1998-08-28 20:03:12 +0000855\method{__del__()} method is called.
856\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000857
Fred Draked82575d1998-08-28 20:03:12 +0000858\begin{methoddescni}{__repr__}{self}
Fred Drake82385871998-10-01 20:40:43 +0000859Called by the \function{repr()}\bifuncindex{repr} built-in function
860and by string conversions (reverse quotes) to compute the ``official''
861string representation of an object. This should normally look like a
862valid Python expression that can be used to recreate an object with
863the same value. By convention, objects which cannot be trivially
864converted to strings which can be used to create a similar object
865produce a string of the form \samp{<\var{...some useful
866description...}>}.
Fred Drakef6669171998-05-06 19:52:49 +0000867\ttindex{__repr__}
Fred Drakef6669171998-05-06 19:52:49 +0000868\indexii{string}{conversion}
869\indexii{reverse}{quotes}
870\indexii{backward}{quotes}
871\index{back-quotes}
Fred Draked82575d1998-08-28 20:03:12 +0000872\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000873
Fred Draked82575d1998-08-28 20:03:12 +0000874\begin{methoddescni}{__str__}{self}
875Called by the \function{str()}\bifuncindex{str} built-in function and
876by the \keyword{print}\stindex{print} statement to compute the
Fred Drake82385871998-10-01 20:40:43 +0000877``informal'' string representation of an object. This differs from
878\method{__repr__()} in that it does not have to be a valid Python
879expression: a more convenient or concise representation may be used
880instead.
Fred Drakef6669171998-05-06 19:52:49 +0000881\ttindex{__str__}
Fred Draked82575d1998-08-28 20:03:12 +0000882\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000883
Fred Draked82575d1998-08-28 20:03:12 +0000884\begin{methoddescni}{__cmp__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000885Called by all comparison operations. Should return a negative integer if
886\code{self < other}, zero if \code{self == other}, a positive integer if
Fred Drakef6669171998-05-06 19:52:49 +0000887\code{self > other}. If no \method{__cmp__()} operation is defined, class
888instances are compared by object identity (``address'').
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000889(Note: the restriction that exceptions are not propagated by
Fred Drake82385871998-10-01 20:40:43 +0000890\method{__cmp__()} has been removed in Python 1.5.)
Fred Drakef6669171998-05-06 19:52:49 +0000891\ttindex{__cmp__}
892\bifuncindex{cmp}
893\index{comparisons}
Fred Draked82575d1998-08-28 20:03:12 +0000894\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000895
Fred Draked82575d1998-08-28 20:03:12 +0000896\begin{methoddescni}{__hash__}{self}
897Called for the key object for dictionary\obindex{dictionary}
898operations, and by the built-in function
Fred Drakef6669171998-05-06 19:52:49 +0000899\function{hash()}\bifuncindex{hash}. Should return a 32-bit integer
900usable as a hash value
901for dictionary operations. The only required property is that objects
902which compare equal have the same hash value; it is advised to somehow
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000903mix together (e.g., using exclusive or) the hash values for the
Fred Drakef6669171998-05-06 19:52:49 +0000904components of the object that also play a part in comparison of
905objects. If a class does not define a \method{__cmp__()} method it should
906not define a \method{__hash__()} operation either; if it defines
907\method{__cmp__()} but not \method{__hash__()} its instances will not be
908usable as dictionary keys. If a class defines mutable objects and
909implements a \method{__cmp__()} method it should not implement
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000910\method{__hash__()}, since the dictionary implementation requires that
911a key's hash value is immutable (if the object's hash value changes, it
912will be in the wrong hash bucket).
Fred Drakef6669171998-05-06 19:52:49 +0000913\ttindex{__cmp__}
914\ttindex{__hash__}
Fred Draked82575d1998-08-28 20:03:12 +0000915\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000916
Fred Draked82575d1998-08-28 20:03:12 +0000917\begin{methoddescni}{__nonzero__}{self}
918Called to implement truth value testing; should return \code{0} or
919\code{1}. When this method is not defined, \method{__len__()} is
920called, if it is defined (see below). If a class defines neither
921\method{__len__()} nor \method{__nonzero__()}, all its instances are
922considered true.
923\ttindex{__nonzero__}
924\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000925
926
Fred Drake61c77281998-07-28 19:34:22 +0000927\subsection{Customizing attribute access\label{attribute-access}}
Fred Drakef6669171998-05-06 19:52:49 +0000928
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000929The following methods can be defined to customize the meaning of
930attribute access (use of, assignment to, or deletion of \code{x.name})
931for class instances.
932For performance reasons, these methods are cached in the class object
933at class definition time; therefore, they cannot be changed after the
934class definition is executed.
Fred Drakef6669171998-05-06 19:52:49 +0000935
Fred Draked82575d1998-08-28 20:03:12 +0000936\begin{methoddescni}{__getattr__}{self, name}
Fred Drakef6669171998-05-06 19:52:49 +0000937Called when an attribute lookup has not found the attribute in the
938usual places (i.e. it is not an instance attribute nor is it found in
939the class tree for \code{self}). \code{name} is the attribute name.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000940This method should return the (computed) attribute value or raise an
Fred Draked82575d1998-08-28 20:03:12 +0000941\exception{AttributeError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000942\ttindex{__getattr__}
943
944Note that if the attribute is found through the normal mechanism,
Fred Draked82575d1998-08-28 20:03:12 +0000945\method{__getattr__()} is not called. (This is an intentional
946asymmetry between \method{__getattr__()} and \method{__setattr__()}.)
Fred Drakef6669171998-05-06 19:52:49 +0000947This is done both for efficiency reasons and because otherwise
Fred Draked82575d1998-08-28 20:03:12 +0000948\method{__setattr__()} would have no way to access other attributes of
949the instance.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000950Note that at least for instance variables, you can fake
951total control by not inserting any values in the instance
952attribute dictionary (but instead inserting them in another object).
Fred Drakef6669171998-05-06 19:52:49 +0000953\ttindex{__setattr__}
Fred Draked82575d1998-08-28 20:03:12 +0000954\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000955
Fred Draked82575d1998-08-28 20:03:12 +0000956\begin{methoddescni}{__setattr__}{self, name, value}
Fred Drakef6669171998-05-06 19:52:49 +0000957Called when an attribute assignment is attempted. This is called
Fred Draked82575d1998-08-28 20:03:12 +0000958instead of the normal mechanism (i.e.\ store the value in the instance
959dictionary). \var{name} is the attribute name, \var{value} is the
Fred Drakef6669171998-05-06 19:52:49 +0000960value to be assigned to it.
961\ttindex{__setattr__}
962
Fred Draked82575d1998-08-28 20:03:12 +0000963If \method{__setattr__()} wants to assign to an instance attribute, it
964should not simply execute \samp{self.\var{name} = value} --- this
965would cause a recursive call to itself. Instead, it should insert the
966value in the dictionary of instance attributes, e.g.,
967\samp{self.__dict__[\var{name}] = value}.
Fred Drakef6669171998-05-06 19:52:49 +0000968\ttindex{__dict__}
Fred Draked82575d1998-08-28 20:03:12 +0000969\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000970
Fred Draked82575d1998-08-28 20:03:12 +0000971\begin{methoddescni}{__delattr__}{self, name}
972Like \method{__setattr__()} but for attribute deletion instead of
Fred Drakef6669171998-05-06 19:52:49 +0000973assignment.
974\ttindex{__delattr__}
Fred Draked82575d1998-08-28 20:03:12 +0000975\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +0000976
977
Fred Drake61c77281998-07-28 19:34:22 +0000978\subsection{Emulating callable objects\label{callable-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000979
Fred Draked82575d1998-08-28 20:03:12 +0000980\begin{methoddescni}{__call__}{self\optional{, args...}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000981Called when the instance is ``called'' as a function; if this method
Fred Draked82575d1998-08-28 20:03:12 +0000982is defined, \code{\var{x}(arg1, arg2, ...)} is a shorthand for
983\code{\var{x}.__call__(arg1, arg2, ...)}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000984\ttindex{__call__}
985\indexii{call}{instance}
Fred Draked82575d1998-08-28 20:03:12 +0000986\end{methoddescni}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000987
988
Fred Drake61c77281998-07-28 19:34:22 +0000989\subsection{Emulating sequence and mapping types\label{sequence-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000990
991The following methods can be defined to emulate sequence or mapping
992objects. The first set of methods is used either to emulate a
993sequence or to emulate a mapping; the difference is that for a
994sequence, the allowable keys should be the integers \var{k} for which
995\code{0 <= \var{k} < \var{N}} where \var{N} is the length of the
996sequence, and the method \method{__getslice__()} (see below) should be
997defined. It is also recommended that mappings provide methods
998\method{keys()}, \method{values()}, \method{items()},
999\method{has_key()}, \method{get()}, \method{clear()}, \method{copy()},
Fred Draked82575d1998-08-28 20:03:12 +00001000and \method{update()} behaving similar to those for
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001001Python's standard dictionary objects; mutable sequences should provide
1002methods \method{append()}, \method{count()}, \method{index()},
1003\method{insert()}, \method{pop()}, \method{remove()}, \method{reverse()}
1004and \method{sort()}, like Python standard list objects. Finally,
1005sequence types should implement addition (meaning concatenation) and
1006multiplication (meaning repetition) by defining the methods
1007\method{__add__()}, \method{__radd__()}, \method{__mul__()} and
1008\method{__rmul__()} described below; they should not define
1009\method{__coerce__()} or other numerical operators.
1010\ttindex{keys}
1011\ttindex{values}
1012\ttindex{items}
1013\ttindex{has_key}
1014\ttindex{get}
1015\ttindex{clear}
1016\ttindex{copy}
1017\ttindex{update}
1018\ttindex{append}
1019\ttindex{count}
1020\ttindex{index}
1021\ttindex{insert}
1022\ttindex{pop}
1023\ttindex{remove}
1024\ttindex{reverse}
1025\ttindex{sort}
1026\ttindex{__add__}
1027\ttindex{__radd__}
1028\ttindex{__mul__}
1029\ttindex{__rmul__}
1030\ttindex{__coerce__}
Fred Drakef6669171998-05-06 19:52:49 +00001031
Fred Draked82575d1998-08-28 20:03:12 +00001032\begin{methoddescni}{__len__}{self}
1033Called to implement the built-in function
1034\function{len()}\bifuncindex{len}. Should return the length of the
1035object, an integer \code{>=} 0. Also, an object that doesn't define a
1036\method{__nonzero__()} method and whose \method{__len__()} method
1037returns zero is considered to be false in a Boolean context.
Fred Drakef6669171998-05-06 19:52:49 +00001038\ttindex{__len__}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001039\ttindex{__nonzero__}
Fred Draked82575d1998-08-28 20:03:12 +00001040\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001041
Fred Draked82575d1998-08-28 20:03:12 +00001042\begin{methoddescni}{__getitem__}{self, key}
1043Called to implement evaluation of \code{\var{self}[\var{key}]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001044For a sequence types, the accepted keys should be integers. Note that the
1045special interpretation of negative indices (if the class wishes to
Fred Drakef6669171998-05-06 19:52:49 +00001046emulate a sequence type) is up to the \method{__getitem__()} method.
1047\ttindex{__getitem__}
Fred Draked82575d1998-08-28 20:03:12 +00001048\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001049
Fred Draked82575d1998-08-28 20:03:12 +00001050\begin{methoddescni}{__setitem__}{self, key, value}
1051Called to implement assignment to \code{\var{self}[\var{key}]}. Same
1052note as for \method{__getitem__()}.
Fred Drakef6669171998-05-06 19:52:49 +00001053\ttindex{__setitem__}
Fred Draked82575d1998-08-28 20:03:12 +00001054\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001055
Fred Draked82575d1998-08-28 20:03:12 +00001056\begin{methoddescni}{__delitem__}{self, key}
1057Called to implement deletion of \code{\var{self}[\var{key}]}. Same
1058note as for \method{__getitem__()}.
Fred Drakef6669171998-05-06 19:52:49 +00001059\ttindex{__delitem__}
Fred Draked82575d1998-08-28 20:03:12 +00001060\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001061
1062
Fred Drake61c77281998-07-28 19:34:22 +00001063\subsection{Additional methods for emulation of sequence types%
1064 \label{sequence-methods}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001065
1066The following methods can be defined to further emulate sequence
1067objects. Immutable sequences methods should only define
1068\method{__getslice__()}; mutable sequences, should define all three
1069three methods.
Fred Drakef6669171998-05-06 19:52:49 +00001070
Fred Draked82575d1998-08-28 20:03:12 +00001071\begin{methoddescni}{__getslice__}{self, i, j}
1072Called to implement evaluation of \code{\var{self}[\var{i}:\var{j}]}.
1073The returned object should be of the same type as \var{self}. Note
1074that missing \var{i} or \var{j} in the slice expression are replaced
1075by zero or \code{sys.maxint}, respectively, and no further
1076transformations on the indices is performed. The interpretation of
1077negative indices and indices larger than the length of the sequence is
1078up to the method.
Fred Drakef6669171998-05-06 19:52:49 +00001079\ttindex{__getslice__}
Fred Draked82575d1998-08-28 20:03:12 +00001080\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001081
Fred Draked82575d1998-08-28 20:03:12 +00001082\begin{methoddescni}{__setslice__}{self, i, j, sequence}
1083Called to implement assignment to \code{\var{self}[\var{i}:\var{j}]}.
1084Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Fred Drakef6669171998-05-06 19:52:49 +00001085\ttindex{__setslice__}
Fred Draked82575d1998-08-28 20:03:12 +00001086\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001087
Fred Draked82575d1998-08-28 20:03:12 +00001088\begin{methoddescni}{__delslice__}{self, i, j}
1089Called to implement deletion of \code{\var{self}[\var{i}:\var{j}]}.
1090Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Fred Drakef6669171998-05-06 19:52:49 +00001091\ttindex{__delslice__}
Fred Draked82575d1998-08-28 20:03:12 +00001092\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001093
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001094Notice that these methods are only invoked when a single slice with a
1095single colon is used. For slice operations involving extended slice
1096notation, \method{__getitem__()}, \method{__setitem__()}
1097or\method{__delitem__()} is called.
Fred Drakef6669171998-05-06 19:52:49 +00001098
Fred Drake61c77281998-07-28 19:34:22 +00001099\subsection{Emulating numeric types\label{numeric-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001100
1101The following methods can be defined to emulate numeric objects.
1102Methods corresponding to operations that are not supported by the
1103particular kind of number implemented (e.g., bitwise operations for
1104non-integral numbers) should be left undefined.
Fred Drakef6669171998-05-06 19:52:49 +00001105
Fred Draked82575d1998-08-28 20:03:12 +00001106\begin{methoddescni}{__add__}{self, other}
1107\methodlineni{__sub__}{self, other}
1108\methodlineni{__mul__}{self, other}
1109\methodlineni{__div__}{self, other}
1110\methodlineni{__mod__}{self, other}
1111\methodlineni{__divmod__}{self, other}
1112\methodlineni{__pow__}{self, other\optional{, modulo}}
1113\methodlineni{__lshift__}{self, other}
1114\methodlineni{__rshift__}{self, other}
1115\methodlineni{__and__}{self, other}
1116\methodlineni{__xor__}{self, other}
1117\methodlineni{__or__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001118These functions are
1119called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001120\code{-}, \code{*}, \code{/}, \code{\%},
1121\function{divmod()}\bifuncindex{divmod},
1122\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<}, \code{>>},
1123\code{\&}, \code{\^}, \code{|}). For instance, to evaluate the
1124expression \var{x}\code{+}\var{y}, where \var{x} is an instance of a
1125class that has an \method{__add__()} method,
1126\code{\var{x}.__add__(\var{y})} is called. Note that
1127\method{__pow__()} should be defined to accept an optional third
1128argument if the ternary version of the built-in
1129\function{pow()}\bifuncindex{pow} function is to be supported.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001130\ttindex{__or__}
1131\ttindex{__xor__}
1132\ttindex{__and__}
1133\ttindex{__rshift__}
1134\ttindex{__lshift__}
1135\ttindex{__pow__}
1136\ttindex{__divmod__}
1137\ttindex{__mod__}
1138\ttindex{__div__}
1139\ttindex{__mul__}
1140\ttindex{__sub__}
1141\ttindex{__add__}
Fred Draked82575d1998-08-28 20:03:12 +00001142\end{methoddescni}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001143
Fred Draked82575d1998-08-28 20:03:12 +00001144\begin{methoddescni}{__radd__}{self, other}
1145\methodlineni{__rsub__}{self, other}
1146\methodlineni{__rmul__}{self, other}
1147\methodlineni{__rdiv__}{self, other}
1148\methodlineni{__rmod__}{self, other}
1149\methodlineni{__rdivmod__}{self, other}
1150\methodlineni{__rpow__}{self, other}
1151\methodlineni{__rlshift__}{self, other}
1152\methodlineni{__rrshift__}{self, other}
1153\methodlineni{__rand__}{self, other}
1154\methodlineni{__rxor__}{self, other}
1155\methodlineni{__ror__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001156These functions are
1157called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001158\code{-}, \code{*}, \code{/}, \code{\%},
1159\function{divmod()}\bifuncindex{divmod},
1160\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<}, \code{>>},
1161\code{\&}, \code{\^}, \code{|}) with reversed operands. These
1162functions are only called if the left operand does not support the
1163corresponding operation. For instance, to evaluate the expression
1164\var{x}\code{-}\var{y}, where \var{y} is an instance of a class that
1165has an \method{__rsub__()} method, \code{\var{y}.__rsub__(\var{x})} is
1166called. Note that ternary \function{pow()}\bifuncindex{pow} will not
1167try calling \method{__rpow__()} (the coercion rules would become too
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001168complicated).
Fred Drakef6669171998-05-06 19:52:49 +00001169\ttindex{__or__}
1170\ttindex{__xor__}
1171\ttindex{__and__}
1172\ttindex{__rshift__}
1173\ttindex{__lshift__}
1174\ttindex{__pow__}
1175\ttindex{__divmod__}
1176\ttindex{__mod__}
1177\ttindex{__div__}
1178\ttindex{__mul__}
1179\ttindex{__sub__}
1180\ttindex{__add__}
Fred Draked82575d1998-08-28 20:03:12 +00001181\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001182
Fred Draked82575d1998-08-28 20:03:12 +00001183\begin{methoddescni}{__neg__}{self}
1184\methodlineni{__pos__}{self}
1185\methodlineni{__abs__}{self}
1186\methodlineni{__invert__}{self}
Fred Drakef6669171998-05-06 19:52:49 +00001187Called to implement the unary arithmetic operations (\code{-}, \code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001188\function{abs()}\bifuncindex{abs} and \code{~}).
Fred Drakef6669171998-05-06 19:52:49 +00001189\ttindex{__invert__}
1190\ttindex{__abs__}
1191\ttindex{__pos__}
1192\ttindex{__neg__}
Fred Draked82575d1998-08-28 20:03:12 +00001193\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001194
Fred Draked82575d1998-08-28 20:03:12 +00001195\begin{methoddescni}{__int__}{self}
1196\methodlineni{__long__}{self}
1197\methodlineni{__float__}{self}
1198Called to implement the built-in functions
1199\function{int()}\bifuncindex{int}, \function{long()}\bifuncindex{long}
1200and \function{float()}\bifuncindex{float}. Should return a value of
1201the appropriate type.
Fred Drakef6669171998-05-06 19:52:49 +00001202\ttindex{__float__}
1203\ttindex{__long__}
1204\ttindex{__int__}
Fred Draked82575d1998-08-28 20:03:12 +00001205\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001206
Fred Draked82575d1998-08-28 20:03:12 +00001207\begin{methoddescni}{__oct__}{self}
1208\methodlineni{__hex__}{self}
1209Called to implement the built-in functions
1210\function{oct()}\bifuncindex{oct} and
1211\function{hex()}\bifuncindex{hex}. Should return a string value.
Fred Drakef6669171998-05-06 19:52:49 +00001212\ttindex{__hex__}
1213\ttindex{__oct__}
Fred Draked82575d1998-08-28 20:03:12 +00001214\end{methoddescni}
Fred Drakef6669171998-05-06 19:52:49 +00001215
Fred Draked82575d1998-08-28 20:03:12 +00001216\begin{methoddescni}{__coerce__}{self, other}
1217\ttindex{__coerce__}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001218Called to implement ``mixed-mode'' numeric arithmetic. Should either
Fred Draked82575d1998-08-28 20:03:12 +00001219return a 2-tuple containing \var{self} and \var{other} converted to
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001220a common numeric type, or \code{None} if conversion is possible. When
1221the common type would be the type of \code{other}, it is sufficient to
1222return \code{None}, since the interpreter will also ask the other
1223object to attempt a coercion (but sometimes, if the implementation of
1224the other type cannot be changed, it is useful to do the conversion to
1225the other type here).
Fred Draked82575d1998-08-28 20:03:12 +00001226\end{methoddescni}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001227
1228\strong{Coercion rules}: to evaluate \var{x} \var{op} \var{y}, the
1229following steps are taken (where \method{__op__()} and
1230\method{__rop__()} are the method names corresponding to \var{op},
Guido van Rossum7c0240f1998-07-24 15:36:43 +00001231e.g., if var{op} is `\code{+}', \method{__add__()} and
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001232\method{__radd__()} are used). If an exception occurs at any point,
1233the evaluation is abandoned and exception handling takes over.
1234
1235\begin{itemize}
1236
1237\item[0.] If \var{x} is a string object and op is the modulo operator (\%),
1238the string formatting operation is invoked and the remaining steps are
1239skipped.
1240
1241\item[1.] If \var{x} is a class instance:
1242
1243 \begin{itemize}
1244
1245 \item[1a.] If \var{x} has a \method{__coerce__()} method:
1246 replace \var{x} and \var{y} with the 2-tuple returned by
1247 \code{\var{x}.__coerce__(\var{y})}; skip to step 2 if the
1248 coercion returns \code{None}.
1249
1250 \item[1b.] If neither \var{x} nor \var{y} is a class instance
1251 after coercion, go to step 3.
1252
1253 \item[1c.] If \var{x} has a method \method{__op__()}, return
1254 \code{\var{x}.__op__(\var{y})}; otherwise, restore \var{x} and
1255 \var{y} to their value before step 1a.
1256
1257 \end{itemize}
1258
1259\item[2.] If \var{y} is a class instance:
1260
1261 \begin{itemize}
1262
1263 \item[2a.] If \var{y} has a \method{__coerce__()} method:
1264 replace \var{y} and \var{x} with the 2-tuple returned by
1265 \code{\var{y}.__coerce__(\var{x})}; skip to step 3 if the
1266 coercion returns \code{None}.
1267
1268 \item[2b.] If neither \var{x} nor \var{y} is a class instance
1269 after coercion, go to step 3.
1270
1271 \item[2b.] If \var{y} has a method \method{__rop__()}, return
1272 \code{\var{y}.__rop__(\var{x})}; otherwise, restore \var{x}
1273 and \var{y} to their value before step 2a.
1274
1275 \end{itemize}
1276
1277\item[3.] We only get here if neither \var{x} nor \var{y} is a class
1278instance.
1279
1280 \begin{itemize}
1281
1282 \item[3a.] If op is `\code{+}' and \var{x} is a sequence,
1283 sequence concatenation is invoked.
1284
1285 \item[3b.] If op is `\code{*}' and one operand is a sequence
1286 and the other an integer, sequence repetition is invoked.
1287
1288 \item[3c.] Otherwise, both operands must be numbers; they are
1289 coerced to a common type if possible, and the numeric
1290 operation is invoked for that type.
1291
1292 \end{itemize}
1293
1294\end{itemize}