blob: 5f9a0d85f98d0d12ebcf5d571eaa5914e1a65605 [file] [log] [blame]
Guido van Rossum46f3e001992-08-14 09:11:01 +00001\chapter{Data model}
2
3\section{Objects, values and types}
4
5{\em 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
8``stored program computer'', code is also represented by objects.)
9\index{object}
10\index{data}
11
12Every object has an identity, a type and a value. An object's {\em
13identity} never changes once it has been created; you may think of it
14as the object's address in memory. An object's {\em type} is also
15unchangeable. It determines the operations that an object supports
16(e.g. ``does it have a length?'') and also defines the possible
17values for objects of that type. The {\em value} of some objects can
18change. Objects whose value can change are said to be {\em mutable};
19objects whose value is unchangeable once they are created are called
20{\em immutable}. The type determines an object's (im)mutability.
21\index{identity of an object}
22\index{value of an object}
23\index{type of an object}
24\index{mutable object}
25\index{immutable object}
26
27Objects are never explicitly destroyed; however, when they become
28unreachable they may be garbage-collected. An implementation is
29allowed to delay garbage collection or omit it altogether --- it is a
30matter of implementation quality how garbage collection is
31implemented, as long as no objects are collected that are still
32reachable. (Implementation note: the current implementation uses a
33reference-counting scheme which collects most objects as soon as they
34become unreachable, but never collects garbage containing circular
35references.)
36\index{garbage collection}
37\index{reference counting}
38\index{unreachable object}
39
40Note that the use of the implementation's tracing or debugging
41facilities may keep objects alive that would normally be collectable.
42
43Some objects contain references to ``external'' resources such as open
44files or windows. It is understood that these resources are freed
45when the object is garbage-collected, but since garbage collection is
46not guaranteed to happen, such objects also provide an explicit way to
Guido van Rossum6938f061994-08-01 12:22:53 +000047release the external resource, usually a \verb@close@ method.
Guido van Rossum46f3e001992-08-14 09:11:01 +000048Programs are strongly recommended to always explicitly close such
49objects.
50
51Some objects contain references to other objects; these are called
52{\em containers}. Examples of containers are tuples, lists and
53dictionaries. The references are part of a container's value. In
54most cases, when we talk about the value of a container, we imply the
55values, not the identities of the contained objects; however, when we
56talk about the (im)mutability of a container, only the identities of
57the immediately contained objects are implied. (So, if an immutable
58container contains a reference to a mutable object, its value changes
59if that mutable object is changed.)
60\index{container}
61
62Types affect almost all aspects of objects' lives. Even the meaning
63of object identity is affected in some sense: for immutable types,
64operations that compute new values may actually return a reference to
65any existing object with the same type and value, while for mutable
66objects this is not allowed. E.g. after
67
68\begin{verbatim}
69a = 1; b = 1; c = []; d = []
70\end{verbatim}
71
Guido van Rossum6938f061994-08-01 12:22:53 +000072\verb@a@ and \verb@b@ may or may not refer to the same object with the
73value one, depending on the implementation, but \verb@c@ and \verb@d@
Guido van Rossum46f3e001992-08-14 09:11:01 +000074are guaranteed to refer to two different, unique, newly created empty
75lists.
76
77\section{The standard type hierarchy} \label{types}
78
79Below is a list of the types that are built into Python. Extension
80modules written in C can define additional types. Future versions of
81Python may add types to the type hierarchy (e.g. rational or complex
82numbers, efficiently stored arrays of integers, etc.).
83\index{type}
84\indexii{data}{type}
85\indexii{type}{hierarchy}
86\indexii{extension}{module}
87\index{C}
88
89Some of the type descriptions below contain a paragraph listing
90`special attributes'. These are attributes that provide access to the
91implementation and are not intended for general use. Their definition
92may change in the future. There are also some `generic' special
Guido van Rossum6938f061994-08-01 12:22:53 +000093attributes, not listed with the individual objects: \verb@__methods__@
Guido van Rossum46f3e001992-08-14 09:11:01 +000094is a list of the method names of a built-in object, if it has any;
Guido van Rossum6938f061994-08-01 12:22:53 +000095\verb@__members__@ is a list of the data attribute names of a built-in
Guido van Rossum46f3e001992-08-14 09:11:01 +000096object, if it has any.
97\index{attribute}
98\indexii{special}{attribute}
99\indexiii{generic}{special}{attribute}
100\ttindex{__methods__}
101\ttindex{__members__}
102
103\begin{description}
104
105\item[None]
106This type has a single value. There is a single object with this value.
Guido van Rossum6938f061994-08-01 12:22:53 +0000107This object is accessed through the built-in name \verb@None@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000108It is returned from functions that don't explicitly return an object.
109\ttindex{None}
110\obindex{None@{\tt None}}
111
112\item[Numbers]
113These are created by numeric literals and returned as results by
114arithmetic operators and arithmetic built-in functions. Numeric
115objects are immutable; once created their value never changes. Python
116numbers are of course strongly related to mathematical numbers, but
117subject to the limitations of numerical representation in computers.
118\obindex{number}
119\obindex{numeric}
120
121Python distinguishes between integers and floating point numbers:
122
123\begin{description}
124\item[Integers]
125These represent elements from the mathematical set of whole numbers.
126\obindex{integer}
127
128There are two types of integers:
129
130\begin{description}
131
132\item[Plain integers]
133These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
134(The range may be larger on machines with a larger natural word
135size, but not smaller.)
136When the result of an operation falls outside this range, the
Guido van Rossum6938f061994-08-01 12:22:53 +0000137exception \verb@OverflowError@ is raised.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000138For the purpose of shift and mask operations, integers are assumed to
139have a binary, 2's complement notation using 32 or more bits, and
140hiding no bits from the user (i.e., all $2^{32}$ different bit
141patterns correspond to different values).
142\obindex{plain integer}
143
144\item[Long integers]
145These represent numbers in an unlimited range, subject to available
146(virtual) memory only. For the purpose of shift and mask operations,
147a binary representation is assumed, and negative numbers are
148represented in a variant of 2's complement which gives the illusion of
149an infinite string of sign bits extending to the left.
150\obindex{long integer}
151
152\end{description} % Integers
153
154The rules for integer representation are intended to give the most
155meaningful interpretation of shift and mask operations involving
156negative integers and the least surprises when switching between the
157plain and long integer domains. For any operation except left shift,
158if it yields a result in the plain integer domain without causing
159overflow, it will yield the same result in the long integer domain or
160when using mixed operands.
161\indexii{integer}{representation}
162
163\item[Floating point numbers]
164These represent machine-level double precision floating point numbers.
165You are at the mercy of the underlying machine architecture and
166C implementation for the accepted range and handling of overflow.
167\obindex{floating point}
168\indexii{floating point}{number}
169\index{C}
170
171\end{description} % Numbers
172
173\item[Sequences]
174These represent finite ordered sets indexed by natural numbers.
Guido van Rossum6938f061994-08-01 12:22:53 +0000175The built-in function \verb@len()@ returns the number of elements
Guido van Rossum46f3e001992-08-14 09:11:01 +0000176of a sequence. When this number is $n$, the index set contains
Guido van Rossum6938f061994-08-01 12:22:53 +0000177the numbers $0, 1, \ldots, n-1$. Element \verb@i@ of sequence
178\verb@a@ is selected by \verb@a[i]@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000179\obindex{seqence}
180\bifuncindex{len}
181\index{index operation}
182\index{item selection}
183\index{subscription}
184
Guido van Rossum6938f061994-08-01 12:22:53 +0000185Sequences also support slicing: \verb@a[i:j]@ selects all elements
Guido van Rossum46f3e001992-08-14 09:11:01 +0000186with index $k$ such that $i <= k < j$. When used as an expression,
187a slice is a sequence of the same type --- this implies that the
188index set is renumbered so that it starts at 0 again.
189\index{slicing}
190
191Sequences are distinguished according to their mutability:
192
193\begin{description}
194%
195\item[Immutable sequences]
196An object of an immutable sequence type cannot change once it is
197created. (If the object contains references to other objects,
198these other objects may be mutable and may be changed; however
199the collection of objects directly referenced by an immutable object
200cannot change.)
201\obindex{immutable sequence}
202\obindex{immutable}
203
204The following types are immutable sequences:
205
206\begin{description}
207
208\item[Strings]
209The elements of a string are characters. There is no separate
210character type; a character is represented by a string of one element.
211Characters represent (at least) 8-bit bytes. The built-in
Guido van Rossum6938f061994-08-01 12:22:53 +0000212functions \verb@chr()@ and \verb@ord()@ convert between characters
Guido van Rossum46f3e001992-08-14 09:11:01 +0000213and nonnegative integers representing the byte values.
214Bytes with the values 0-127 represent the corresponding ASCII values.
215The string data type is also used to represent arrays of bytes, e.g.
216to hold data read from a file.
217\obindex{string}
218\index{character}
219\index{byte}
220\index{ASCII}
221\bifuncindex{chr}
222\bifuncindex{ord}
223
224(On systems whose native character set is not ASCII, strings may use
225EBCDIC in their internal representation, provided the functions
Guido van Rossum6938f061994-08-01 12:22:53 +0000226\verb@chr()@ and \verb@ord()@ implement a mapping between ASCII and
Guido van Rossum46f3e001992-08-14 09:11:01 +0000227EBCDIC, and string comparison preserves the ASCII order.
228Or perhaps someone can propose a better rule?)
229\index{ASCII}
230\index{EBCDIC}
231\index{character set}
232\indexii{string}{comparison}
233\bifuncindex{chr}
234\bifuncindex{ord}
235
236\item[Tuples]
237The elements of a tuple are arbitrary Python objects.
238Tuples of two or more elements are formed by comma-separated lists
239of expressions. A tuple of one element (a `singleton') can be formed
240by affixing a comma to an expression (an expression by itself does
241not create a tuple, since parentheses must be usable for grouping of
242expressions). An empty tuple can be formed by enclosing `nothing' in
243parentheses.
244\obindex{tuple}
245\indexii{singleton}{tuple}
246\indexii{empty}{tuple}
247
248\end{description} % Immutable sequences
249
250\item[Mutable sequences]
251Mutable sequences can be changed after they are created. The
252subscription and slicing notations can be used as the target of
Guido van Rossum6938f061994-08-01 12:22:53 +0000253assignment and \verb@del@ (delete) statements.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000254\obindex{mutable sequece}
255\obindex{mutable}
256\indexii{assignment}{statement}
257\index{delete}
258\stindex{del}
259\index{subscription}
260\index{slicing}
261
262There is currently a single mutable sequence type:
263
264\begin{description}
265
266\item[Lists]
267The elements of a list are arbitrary Python objects. Lists are formed
268by placing a comma-separated list of expressions in square brackets.
269(Note that there are no special cases needed to form lists of length 0
270or 1.)
271\obindex{list}
272
273\end{description} % Mutable sequences
274
275\end{description} % Sequences
276
277\item[Mapping types]
278These represent finite sets of objects indexed by arbitrary index sets.
Guido van Rossum6938f061994-08-01 12:22:53 +0000279The subscript notation \verb@a[k]@ selects the element indexed
280by \verb@k@ from the mapping \verb@a@; this can be used in
281expressions and as the target of assignments or \verb@del@ statements.
282The built-in function \verb@len()@ returns the number of elements
Guido van Rossum46f3e001992-08-14 09:11:01 +0000283in a mapping.
284\bifuncindex{len}
285\index{subscription}
286\obindex{mapping}
287
288There is currently a single mapping type:
289
290\begin{description}
291
292\item[Dictionaries]
Guido van Rossumb2c65561993-05-12 08:53:36 +0000293These represent finite sets of objects indexed by almost arbitrary
294values. The only types of values not acceptable as keys are values
295containing lists or dictionaries or other mutable types that are
296compared by value rather than by object identity --- the reason being
297that the implementation requires that a key's hash value be constant.
298Numeric types used for keys obey the normal rules for numeric
299comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
300can be used interchangeably to index the same dictionary entry.
301
Guido van Rossum6938f061994-08-01 12:22:53 +0000302Dictionaries are mutable; they are created by the \verb@{...}@
Guido van Rossumb2c65561993-05-12 08:53:36 +0000303notation (see section \ref{dict}).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000304\obindex{dictionary}
305\obindex{mutable}
306
307\end{description} % Mapping types
308
309\item[Callable types]
310These are the types to which the function call (invocation) operation,
Guido van Rossum6938f061994-08-01 12:22:53 +0000311written as \verb@function(argument, argument, ...)@, can be applied:
Guido van Rossum46f3e001992-08-14 09:11:01 +0000312\indexii{function}{call}
313\index{invocation}
314\indexii{function}{argument}
315\obindex{callable}
316
317\begin{description}
318
319\item[User-defined functions]
320A user-defined function object is created by a function definition
321(see section \ref{function}). It should be called with an argument
322list containing the same number of items as the function's formal
323parameter list.
324\indexii{user-defined}{function}
325\obindex{function}
326\obindex{user-defined function}
327
Guido van Rossum6938f061994-08-01 12:22:53 +0000328Special read-only attributes: \verb@func_code@ is the code object
329representing the compiled function body, and \verb@func_globals@ is (a
Guido van Rossum46f3e001992-08-14 09:11:01 +0000330reference to) the dictionary that holds the function's global
331variables --- it implements the global name space of the module in
332which the function was defined.
333\ttindex{func_code}
334\ttindex{func_globals}
335\indexii{global}{name space}
336
337\item[User-defined methods]
338A user-defined method (a.k.a. {\em object closure}) is a pair of a
339class instance object and a user-defined function. It should be
340called with an argument list containing one item less than the number
341of items in the function's formal parameter list. When called, the
342class instance becomes the first argument, and the call arguments are
343shifted one to the right.
344\obindex{method}
345\obindex{user-defined method}
346\indexii{user-defined}{method}
347\index{object closure}
348
Guido van Rossum6938f061994-08-01 12:22:53 +0000349Special read-only attributes: \verb@im_self@ is the class instance
350object, \verb@im_func@ is the function object.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000351\ttindex{im_func}
352\ttindex{im_self}
353
354\item[Built-in functions]
355A built-in function object is a wrapper around a C function. Examples
Guido van Rossum6938f061994-08-01 12:22:53 +0000356of built-in functions are \verb@len@ and \verb@math.sin@. There
Guido van Rossum46f3e001992-08-14 09:11:01 +0000357are no special attributes. The number and type of the arguments are
358determined by the C function.
359\obindex{built-in function}
360\obindex{function}
361\index{C}
362
363\item[Built-in methods]
364This is really a different disguise of a built-in function, this time
365containing an object passed to the C function as an implicit extra
Guido van Rossum6938f061994-08-01 12:22:53 +0000366argument. An example of a built-in method is \verb@list.append@ if
367\verb@list@ is a list object.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000368\obindex{built-in method}
369\obindex{method}
370\indexii{built-in}{method}
371
372\item[Classes]
373Class objects are described below. When a class object is called as a
Guido van Rossum6938f061994-08-01 12:22:53 +0000374function, a new class instance (also described below) is created and
375returned. This implies a call to the class's \verb@__init__@ method
376if it has one. Any arguments are passed on to the \verb@__init__@
377method -- if there is \verb@__init__@ method, the class must be called
378without arguments.
379\ttindex{__init__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000380\obindex{class}
381\obindex{class instance}
382\obindex{instance}
383\indexii{class object}{call}
384
385\end{description}
386
387\item[Modules]
Guido van Rossum6938f061994-08-01 12:22:53 +0000388Modules are imported by the \verb@import@ statement (see section
Guido van Rossum46f3e001992-08-14 09:11:01 +0000389\ref{import}). A module object is a container for a module's name
390space, which is a dictionary (the same dictionary as referenced by the
Guido van Rossum6938f061994-08-01 12:22:53 +0000391\verb@func_globals@ attribute of functions defined in the module).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000392Module attribute references are translated to lookups in this
393dictionary. A module object does not contain the code object used to
394initialize the module (since it isn't needed once the initialization
395is done).
396\stindex{import}
397\obindex{module}
398
399Attribute assignment update the module's name space dictionary.
400
Guido van Rossum6938f061994-08-01 12:22:53 +0000401Special read-only attributes: \verb@__dict__@ yields the module's name
402space as a dictionary object; \verb@__name__@ yields the module's name
Guido van Rossum46f3e001992-08-14 09:11:01 +0000403as a string object.
404\ttindex{__dict__}
405\ttindex{__name__}
406\indexii{module}{name space}
407
408\item[Classes]
409Class objects are created by class definitions (see section
410\ref{class}). A class is a container for a dictionary containing the
411class's name space. Class attribute references are translated to
412lookups in this dictionary. When an attribute name is not found
413there, the attribute search continues in the base classes. The search
414is depth-first, left-to-right in the order of their occurrence in the
415base class list.
416\obindex{class}
417\obindex{class instance}
418\obindex{instance}
419\indexii{class object}{call}
420\index{container}
Guido van Rossumb2c65561993-05-12 08:53:36 +0000421\obindex{dictionary}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000422\indexii{class}{attribute}
423
424Class attribute assignments update the class's dictionary, never the
425dictionary of a base class.
426\indexiii{class}{attribute}{assignment}
427
Guido van Rossum6938f061994-08-01 12:22:53 +0000428A class can be called as a function to yield a class instance (see
429above).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000430\indexii{class object}{call}
431
Guido van Rossum6938f061994-08-01 12:22:53 +0000432Special read-only attributes: \verb@__dict__@ yields the dictionary
433containing the class's name space; \verb@__bases__@ yields a tuple
Guido van Rossum46f3e001992-08-14 09:11:01 +0000434(possibly empty or a singleton) containing the base classes, in the
435order of their occurrence in the base class list.
436\ttindex{__dict__}
437\ttindex{__bases__}
438
439\item[Class instances]
440A class instance is created by calling a class object as a
Guido van Rossum6938f061994-08-01 12:22:53 +0000441function. A class instance has a dictionary in which
Guido van Rossum46f3e001992-08-14 09:11:01 +0000442attribute references are searched. When an attribute is not found
443there, and the instance's class has an attribute by that name, and
444that class attribute is a user-defined function (and in no other
445cases), the instance attribute reference yields a user-defined method
446object (see above) constructed from the instance and the function.
447\obindex{class instance}
448\obindex{instance}
449\indexii{class}{instance}
450\indexii{class instance}{attribute}
451
452Attribute assignments update the instance's dictionary.
453\indexiii{class instance}{attribute}{assignment}
454
455Class instances can pretend to be numbers, sequences, or mappings if
456they have methods with certain special names. These are described in
457section \ref{specialnames}.
458\obindex{number}
459\obindex{sequence}
460\obindex{mapping}
461
Guido van Rossum6938f061994-08-01 12:22:53 +0000462Special read-only attributes: \verb@__dict__@ yields the attribute
463dictionary; \verb@__class__@ yields the instance's class.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000464\ttindex{__dict__}
465\ttindex{__class__}
466
467\item[Files]
468A file object represents an open file. (It is a wrapper around a C
469{\tt stdio} file pointer.) File objects are created by the
Guido van Rossum6938f061994-08-01 12:22:53 +0000470\verb@open()@ built-in function, and also by \verb@posix.popen()@ and
471the \verb@makefile@ method of socket objects. \verb@sys.stdin@,
472\verb@sys.stdout@ and \verb@sys.stderr@ are file objects corresponding
Guido van Rossum46f3e001992-08-14 09:11:01 +0000473the the interpreter's standard input, output and error streams.
474See the Python Library Reference for methods of file objects and other
475details.
476\obindex{file}
477\index{C}
478\index{stdio}
479\bifuncindex{open}
480\bifuncindex{popen}
481\bifuncindex{makefile}
482\ttindex{stdin}
483\ttindex{stdout}
484\ttindex{stderr}
485\ttindex{sys.stdin}
486\ttindex{sys.stdout}
487\ttindex{sys.stderr}
488
489\item[Internal types]
490A few types used internally by the interpreter are exposed to the user.
491Their definition may change with future versions of the interpreter,
492but they are mentioned here for completeness.
493\index{internal type}
494
495\begin{description}
496
497\item[Code objects]
498Code objects represent executable code. The difference between a code
499object and a function object is that the function object contains an
500explicit reference to the function's context (the module in which it
501was defined) which a code object contains no context. There is no way
502to execute a bare code object.
503\obindex{code}
504
Guido van Rossum6938f061994-08-01 12:22:53 +0000505Special read-only attributes: \verb@co_code@ is a string representing
506the sequence of instructions; \verb@co_consts@ is a list of literals
507used by the code; \verb@co_names@ is a list of names (strings) used by
508the code; \verb@co_filename@ is the filename from which the code was
Guido van Rossum46f3e001992-08-14 09:11:01 +0000509compiled. (To find out the line numbers, you would have to decode the
Guido van Rossum6938f061994-08-01 12:22:53 +0000510instructions; the standard library module \verb@dis@ contains an
Guido van Rossum46f3e001992-08-14 09:11:01 +0000511example of how to do this.)
512\ttindex{co_code}
513\ttindex{co_consts}
514\ttindex{co_names}
515\ttindex{co_filename}
516
517\item[Frame objects]
518Frame objects represent execution frames. They may occur in traceback
519objects (see below).
520\obindex{frame}
521
Guido van Rossum6938f061994-08-01 12:22:53 +0000522Special read-only attributes: \verb@f_back@ is to the previous
523stack frame (towards the caller), or \verb@None@ if this is the bottom
524stack frame; \verb@f_code@ is the code object being executed in this
525frame; \verb@f_globals@ is the dictionary used to look up global
526variables; \verb@f_locals@ is used for local variables;
527\verb@f_lineno@ gives the line number and \verb@f_lasti@ gives the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000528precise instruction (this is an index into the instruction string of
529the code object).
530\ttindex{f_back}
531\ttindex{f_code}
532\ttindex{f_globals}
533\ttindex{f_locals}
534\ttindex{f_lineno}
535\ttindex{f_lasti}
536
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000537\item[Traceback objects] \label{traceback}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000538Traceback objects represent a stack trace of an exception. A
539traceback object is created when an exception occurs. When the search
540for an exception handler unwinds the execution stack, at each unwound
541level a traceback object is inserted in front of the current
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000542traceback. When an exception handler is entered
543(see also section \ref{try}), the stack trace is
Guido van Rossum6938f061994-08-01 12:22:53 +0000544made available to the program as \verb@sys.exc_traceback@. When the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000545program contains no suitable handler, the stack trace is written
546(nicely formatted) to the standard error stream; if the interpreter is
547interactive, it is also made available to the user as
Guido van Rossum6938f061994-08-01 12:22:53 +0000548\verb@sys.last_traceback@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000549\obindex{traceback}
550\indexii{stack}{trace}
551\indexii{exception}{handler}
552\indexii{execution}{stack}
553\ttindex{exc_traceback}
554\ttindex{last_traceback}
555\ttindex{sys.exc_traceback}
556\ttindex{sys.last_traceback}
557
Guido van Rossum6938f061994-08-01 12:22:53 +0000558Special read-only attributes: \verb@tb_next@ is the next level in the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000559stack trace (towards the frame where the exception occurred), or
Guido van Rossum6938f061994-08-01 12:22:53 +0000560\verb@None@ if there is no next level; \verb@tb_frame@ points to the
561execution frame of the current level; \verb@tb_lineno@ gives the line
562number where the exception occurred; \verb@tb_lasti@ indicates the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000563precise instruction. The line number and last instruction in the
564traceback may differ from the line number of its frame object if the
Guido van Rossum6938f061994-08-01 12:22:53 +0000565exception occurred in a \verb@try@ statement with no matching
566\verb@except@ clause or with a \verb@finally@ clause.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000567\ttindex{tb_next}
568\ttindex{tb_frame}
569\ttindex{tb_lineno}
570\ttindex{tb_lasti}
571\stindex{try}
572
573\end{description} % Internal types
574
575\end{description} % Types
576
577
578\section{Special method names} \label{specialnames}
579
580A class can implement certain operations that are invoked by special
581syntax (such as subscription or arithmetic operations) by defining
582methods with special names. For instance, if a class defines a
Guido van Rossum6938f061994-08-01 12:22:53 +0000583method named \verb@__getitem__@, and \verb@x@ is an instance of this
584class, then \verb@x[i]@ is equivalent to \verb@x.__getitem__(i)@.
585(The reverse is not true --- if \verb@x@ is a list object,
586\verb@x.__getitem__(i)@ is not equivalent to \verb@x[i]@.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000587
Guido van Rossum6938f061994-08-01 12:22:53 +0000588Except for \verb@__repr__@, \verb@__str__@ and \verb@__cmp__@,
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000589attempts to execute an
Guido van Rossum46f3e001992-08-14 09:11:01 +0000590operation raise an exception when no appropriate method is defined.
Guido van Rossum6938f061994-08-01 12:22:53 +0000591For \verb@__repr__@, the default is to return a string describing the
592object's class and address.
593For \verb@__cmp__@, the default is to compare instances based on their
594address.
595For \verb@__str__@, the default is to use \verb@__repr__@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000596
597
598\subsection{Special methods for any type}
599
600\begin{description}
601
Guido van Rossum23301a91993-05-24 14:19:37 +0000602\item[\tt __init__(self, args...)]
603Called when the instance is created. The arguments are those passed
604to the class constructor expression. If a base class has an
605\code{__init__} method the derived class's \code{__init__} method must
606explicitly call it to ensure proper initialization of the base class
607part of the instance.
608
609\item[\tt __del__(self)]
610Called when the instance is about to be destroyed. If a base class
611has an \code{__del__} method the derived class's \code{__del__} method
612must explicitly call it to ensure proper deletion of the base class
613part of the instance. Note that it is possible for the \code{__del__}
614method to postpone destruction of the instance by creating a new
615reference to it. It may then be called at a later time when this new
616reference is deleted. Also note that it is not guaranteed that
617\code{__del__} methods are called for objects that still exist when
618the interpreter exits.
619
Guido van Rossum46f3e001992-08-14 09:11:01 +0000620\item[\tt __repr__(self)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000621Called by the \verb@repr()@ built-in function and by conversions
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000622(reverse quotes) to compute the string representation of an object.
623
624\item[\tt __str__(self)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000625Called by the \verb@str()@ built-in function and by the \verb@print@
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000626statement compute the string representation of an object.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000627
Guido van Rossumb2c65561993-05-12 08:53:36 +0000628\item[\tt __cmp__(self, other)]
Guido van Rossum46f3e001992-08-14 09:11:01 +0000629Called by all comparison operations. Should return -1 if
Guido van Rossum6938f061994-08-01 12:22:53 +0000630\verb@self < other@, 0 if \verb@self == other@, +1 if
631\verb@self > other@. If no \code{__cmp__} operation is defined, class
Guido van Rossumb2c65561993-05-12 08:53:36 +0000632instances are compared by object identity (``address'').
633(Implementation note: due to limitations in the interpreter,
634exceptions raised by comparisons are ignored, and the objects will be
635considered equal in this case.)
636
637\item[\tt __hash__(self)]
638Called by dictionary operations and by the built-in function
639\code{hash()}. Should return a 32-bit integer usable as a hash value
640for dictionary operations. The only required property is that objects
641which compare equal have the same hash value; it is advised to somehow
642mix together (e.g. using exclusing or) the hash values for the
643components of the object that also play a part in comparison of
644objects. If a class does not define a \code{__cmp__} method it should
645not define a \code{__hash__} operation either; if it defines
646\code{__cmp__} but not \code{__hash__} its instances will not be
647usable as dictionary keys. If a class defines mutable objects and
648implements a \code{__cmp__} method it should not implement
649\code{__hash__}, since the dictionary implementation assumes that a
650key's hash value is a constant.
651\obindex{dictionary}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000652
653\end{description}
654
655
656\subsection{Special methods for sequence and mapping types}
657
658\begin{description}
659
660\item[\tt __len__(self)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000661Called to implement the built-in function \verb@len()@. Should return
662the length of the object, an integer \verb@>=@ 0. Also, an object
663whose \verb@__len__()@ method returns 0 is considered to be false in a
Guido van Rossum46f3e001992-08-14 09:11:01 +0000664Boolean context.
665
666\item[\tt __getitem__(self, key)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000667Called to implement evaluation of \verb@self[key]@. Note that the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000668special interpretation of negative keys (if the class wishes to
Guido van Rossum6938f061994-08-01 12:22:53 +0000669emulate a sequence type) is up to the \verb@__getitem__@ method.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000670
671\item[\tt __setitem__(self, key, value)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000672Called to implement assignment to \verb@self[key]@. Same note as for
673\verb@__getitem__@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000674
675\item[\tt __delitem__(self, key)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000676Called to implement deletion of \verb@self[key]@. Same note as for
677\verb@__getitem__@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000678
679\end{description}
680
681
682\subsection{Special methods for sequence types}
683
684\begin{description}
685
686\item[\tt __getslice__(self, i, j)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000687Called to implement evaluation of \verb@self[i:j]@. Note that missing
688\verb@i@ or \verb@j@ are replaced by 0 or \verb@len(self)@,
689respectively, and \verb@len(self)@ has been added (once) to originally
690negative \verb@i@ or \verb@j@ by the time this function is called
691(unlike for \verb@__getitem__@).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000692
693\item[\tt __setslice__(self, i, j, sequence)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000694Called to implement assignment to \verb@self[i:j]@. Same notes as for
695\verb@__getslice__@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000696
697\item[\tt __delslice__(self, i, j)]
Guido van Rossum6938f061994-08-01 12:22:53 +0000698Called to implement deletion of \verb@self[i:j]@. Same notes as for
699\verb@__getslice__@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000700
701\end{description}
702
703
704\subsection{Special methods for numeric types}
705
706\begin{description}
707
708\item[\tt __add__(self, other)]\itemjoin
709\item[\tt __sub__(self, other)]\itemjoin
710\item[\tt __mul__(self, other)]\itemjoin
711\item[\tt __div__(self, other)]\itemjoin
712\item[\tt __mod__(self, other)]\itemjoin
713\item[\tt __divmod__(self, other)]\itemjoin
714\item[\tt __pow__(self, other)]\itemjoin
715\item[\tt __lshift__(self, other)]\itemjoin
716\item[\tt __rshift__(self, other)]\itemjoin
717\item[\tt __and__(self, other)]\itemjoin
718\item[\tt __xor__(self, other)]\itemjoin
719\item[\tt __or__(self, other)]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000720Called to implement the binary arithmetic operations (\verb@+@,
721\verb@-@, \verb@*@, \verb@/@, \verb@%@, \verb@divmod()@, \verb@pow()@,
722\verb@<<@, \verb@>>@, \verb@&@, \verb@^@, \verb@|@).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000723
724\item[\tt __neg__(self)]\itemjoin
725\item[\tt __pos__(self)]\itemjoin
726\item[\tt __abs__(self)]\itemjoin
727\item[\tt __invert__(self)]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000728Called to implement the unary arithmetic operations (\verb@-@, \verb@+@,
729\verb@abs()@ and \verb@~@).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000730
731\item[\tt __nonzero__(self)]
732Called to implement boolean testing; should return 0 or 1. An
Guido van Rossum6938f061994-08-01 12:22:53 +0000733alternative name for this method is \verb@__len__@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000734
735\item[\tt __coerce__(self, other)]
736Called to implement ``mixed-mode'' numeric arithmetic. Should either
737return a tuple containing self and other converted to a common numeric
738type, or None if no way of conversion is known. When the common type
739would be the type of other, it is sufficient to return None, since the
740interpreter will also ask the other object to attempt a coercion (but
741sometimes, if the implementation of the other type cannot be changed,
742it is useful to do the conversion to the other type here).
743
Guido van Rossum6938f061994-08-01 12:22:53 +0000744Note that this method is not called to coerce the arguments to \verb@+@
745and \verb@*@, because these are also used to implement sequence
Guido van Rossum46f3e001992-08-14 09:11:01 +0000746concatenation and repetition, respectively. Also note that, for the
Guido van Rossum6938f061994-08-01 12:22:53 +0000747same reason, in \verb@n*x@, where \verb@n@ is a built-in number and
748\verb@x@ is an instance, a call to \verb@x.__mul__(n)@ is made.%
Guido van Rossum46f3e001992-08-14 09:11:01 +0000749\footnote{The interpreter should really distinguish between
750user-defined classes implementing sequences, mappings or numbers, but
751currently it doesn't --- hence this strange exception.}
752
753\item[\tt __int__(self)]\itemjoin
754\item[\tt __long__(self)]\itemjoin
755\item[\tt __float__(self)]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000756Called to implement the built-in functions \verb@int()@, \verb@long()@
757and \verb@float()@. Should return a value of the appropriate type.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000758
Guido van Rossum66122d21992-09-20 21:43:47 +0000759\item[\tt __oct__(self)]\itemjoin
760\item[\tt __hex__(self)]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000761Called to implement the built-in functions \verb@oct()@ and
762\verb@hex()@. Should return a string value.
Guido van Rossum66122d21992-09-20 21:43:47 +0000763
Guido van Rossum46f3e001992-08-14 09:11:01 +0000764\end{description}