blob: 60af2dc94a0eeb63cb1654e639358018307c27b1 [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]
Guido van Rossuma5475471995-03-16 14:44:07 +0000133These represent numbers in the range -2147483648 through 2147483647.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000134(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
Guido van Rossuma5475471995-03-16 14:44:07 +0000140hiding no bits from the user (i.e., all 4294967296 different bit
Guido van Rossum46f3e001992-08-14 09:11:01 +0000141patterns 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 Rossuma5475471995-03-16 14:44:07 +0000176of a sequence. When this number is \var{n}, the index set contains
177the numbers 0, 1, \ldots, \var{n}-1. Element \var{i} of sequence
178\var{a} is selected by \code{\var{a}[\var{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 Rossuma5475471995-03-16 14:44:07 +0000186with index \var{k} such that \var{i} \code{<=} \var{k} \code{<}
187\var{j}. When used as an expression, a slice is a sequence of the
188same type --- this implies that the index set is renumbered so that it
189starts at 0 again.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000190\index{slicing}
191
192Sequences are distinguished according to their mutability:
193
194\begin{description}
195%
196\item[Immutable sequences]
197An object of an immutable sequence type cannot change once it is
198created. (If the object contains references to other objects,
199these other objects may be mutable and may be changed; however
200the collection of objects directly referenced by an immutable object
201cannot change.)
202\obindex{immutable sequence}
203\obindex{immutable}
204
205The following types are immutable sequences:
206
207\begin{description}
208
209\item[Strings]
210The elements of a string are characters. There is no separate
211character type; a character is represented by a string of one element.
212Characters represent (at least) 8-bit bytes. The built-in
Guido van Rossum6938f061994-08-01 12:22:53 +0000213functions \verb@chr()@ and \verb@ord()@ convert between characters
Guido van Rossum46f3e001992-08-14 09:11:01 +0000214and nonnegative integers representing the byte values.
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000215Bytes with the values 0-127 represent the corresponding \ASCII{} values.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000216The string data type is also used to represent arrays of bytes, e.g.
217to hold data read from a file.
218\obindex{string}
219\index{character}
220\index{byte}
221\index{ASCII}
222\bifuncindex{chr}
223\bifuncindex{ord}
224
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000225(On systems whose native character set is not \ASCII{}, strings may use
Guido van Rossum46f3e001992-08-14 09:11:01 +0000226EBCDIC in their internal representation, provided the functions
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000227\verb@chr()@ and \verb@ord()@ implement a mapping between \ASCII{} and
228EBCDIC, and string comparison preserves the \ASCII{} order.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000229Or perhaps someone can propose a better rule?)
230\index{ASCII}
231\index{EBCDIC}
232\index{character set}
233\indexii{string}{comparison}
234\bifuncindex{chr}
235\bifuncindex{ord}
236
237\item[Tuples]
238The elements of a tuple are arbitrary Python objects.
239Tuples of two or more elements are formed by comma-separated lists
240of expressions. A tuple of one element (a `singleton') can be formed
241by affixing a comma to an expression (an expression by itself does
242not create a tuple, since parentheses must be usable for grouping of
243expressions). An empty tuple can be formed by enclosing `nothing' in
244parentheses.
245\obindex{tuple}
246\indexii{singleton}{tuple}
247\indexii{empty}{tuple}
248
249\end{description} % Immutable sequences
250
251\item[Mutable sequences]
252Mutable sequences can be changed after they are created. The
253subscription and slicing notations can be used as the target of
Guido van Rossum6938f061994-08-01 12:22:53 +0000254assignment and \verb@del@ (delete) statements.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000255\obindex{mutable sequece}
256\obindex{mutable}
257\indexii{assignment}{statement}
258\index{delete}
259\stindex{del}
260\index{subscription}
261\index{slicing}
262
263There is currently a single mutable sequence type:
264
265\begin{description}
266
267\item[Lists]
268The elements of a list are arbitrary Python objects. Lists are formed
269by placing a comma-separated list of expressions in square brackets.
270(Note that there are no special cases needed to form lists of length 0
271or 1.)
272\obindex{list}
273
274\end{description} % Mutable sequences
275
276\end{description} % Sequences
277
278\item[Mapping types]
279These represent finite sets of objects indexed by arbitrary index sets.
Guido van Rossum6938f061994-08-01 12:22:53 +0000280The subscript notation \verb@a[k]@ selects the element indexed
281by \verb@k@ from the mapping \verb@a@; this can be used in
282expressions and as the target of assignments or \verb@del@ statements.
283The built-in function \verb@len()@ returns the number of elements
Guido van Rossum46f3e001992-08-14 09:11:01 +0000284in a mapping.
285\bifuncindex{len}
286\index{subscription}
287\obindex{mapping}
288
289There is currently a single mapping type:
290
291\begin{description}
292
293\item[Dictionaries]
Guido van Rossumb2c65561993-05-12 08:53:36 +0000294These represent finite sets of objects indexed by almost arbitrary
295values. The only types of values not acceptable as keys are values
296containing lists or dictionaries or other mutable types that are
297compared by value rather than by object identity --- the reason being
298that the implementation requires that a key's hash value be constant.
299Numeric types used for keys obey the normal rules for numeric
300comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
301can be used interchangeably to index the same dictionary entry.
302
Guido van Rossum6938f061994-08-01 12:22:53 +0000303Dictionaries are mutable; they are created by the \verb@{...}@
Guido van Rossumb2c65561993-05-12 08:53:36 +0000304notation (see section \ref{dict}).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000305\obindex{dictionary}
306\obindex{mutable}
307
308\end{description} % Mapping types
309
310\item[Callable types]
311These are the types to which the function call (invocation) operation,
Guido van Rossum6938f061994-08-01 12:22:53 +0000312written as \verb@function(argument, argument, ...)@, can be applied:
Guido van Rossum46f3e001992-08-14 09:11:01 +0000313\indexii{function}{call}
314\index{invocation}
315\indexii{function}{argument}
316\obindex{callable}
317
318\begin{description}
319
320\item[User-defined functions]
321A user-defined function object is created by a function definition
322(see section \ref{function}). It should be called with an argument
323list containing the same number of items as the function's formal
324parameter list.
325\indexii{user-defined}{function}
326\obindex{function}
327\obindex{user-defined function}
328
Guido van Rossum6938f061994-08-01 12:22:53 +0000329Special read-only attributes: \verb@func_code@ is the code object
330representing the compiled function body, and \verb@func_globals@ is (a
Guido van Rossum46f3e001992-08-14 09:11:01 +0000331reference to) the dictionary that holds the function's global
332variables --- it implements the global name space of the module in
333which the function was defined.
334\ttindex{func_code}
335\ttindex{func_globals}
336\indexii{global}{name space}
337
338\item[User-defined methods]
339A user-defined method (a.k.a. {\em object closure}) is a pair of a
340class instance object and a user-defined function. It should be
341called with an argument list containing one item less than the number
342of items in the function's formal parameter list. When called, the
343class instance becomes the first argument, and the call arguments are
344shifted one to the right.
345\obindex{method}
346\obindex{user-defined method}
347\indexii{user-defined}{method}
348\index{object closure}
349
Guido van Rossum6938f061994-08-01 12:22:53 +0000350Special read-only attributes: \verb@im_self@ is the class instance
351object, \verb@im_func@ is the function object.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000352\ttindex{im_func}
353\ttindex{im_self}
354
355\item[Built-in functions]
356A built-in function object is a wrapper around a C function. Examples
Guido van Rossum6938f061994-08-01 12:22:53 +0000357of built-in functions are \verb@len@ and \verb@math.sin@. There
Guido van Rossum46f3e001992-08-14 09:11:01 +0000358are no special attributes. The number and type of the arguments are
359determined by the C function.
360\obindex{built-in function}
361\obindex{function}
362\index{C}
363
364\item[Built-in methods]
365This is really a different disguise of a built-in function, this time
366containing an object passed to the C function as an implicit extra
Guido van Rossum6938f061994-08-01 12:22:53 +0000367argument. An example of a built-in method is \verb@list.append@ if
368\verb@list@ is a list object.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000369\obindex{built-in method}
370\obindex{method}
371\indexii{built-in}{method}
372
373\item[Classes]
374Class objects are described below. When a class object is called as a
Guido van Rossum6938f061994-08-01 12:22:53 +0000375function, a new class instance (also described below) is created and
376returned. This implies a call to the class's \verb@__init__@ method
377if it has one. Any arguments are passed on to the \verb@__init__@
Guido van Rossum8fd02191995-07-07 23:05:13 +0000378method --- if there is no \verb@__init__@ method, the class must be called
Guido van Rossum6938f061994-08-01 12:22:53 +0000379without arguments.
380\ttindex{__init__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000381\obindex{class}
382\obindex{class instance}
383\obindex{instance}
384\indexii{class object}{call}
385
386\end{description}
387
388\item[Modules]
Guido van Rossum6938f061994-08-01 12:22:53 +0000389Modules are imported by the \verb@import@ statement (see section
Guido van Rossum46f3e001992-08-14 09:11:01 +0000390\ref{import}). A module object is a container for a module's name
391space, which is a dictionary (the same dictionary as referenced by the
Guido van Rossum6938f061994-08-01 12:22:53 +0000392\verb@func_globals@ attribute of functions defined in the module).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000393Module attribute references are translated to lookups in this
394dictionary. A module object does not contain the code object used to
395initialize the module (since it isn't needed once the initialization
396is done).
397\stindex{import}
398\obindex{module}
399
400Attribute assignment update the module's name space dictionary.
401
Guido van Rossum6938f061994-08-01 12:22:53 +0000402Special read-only attributes: \verb@__dict__@ yields the module's name
403space as a dictionary object; \verb@__name__@ yields the module's name
Guido van Rossum46f3e001992-08-14 09:11:01 +0000404as a string object.
405\ttindex{__dict__}
406\ttindex{__name__}
407\indexii{module}{name space}
408
409\item[Classes]
410Class objects are created by class definitions (see section
411\ref{class}). A class is a container for a dictionary containing the
412class's name space. Class attribute references are translated to
413lookups in this dictionary. When an attribute name is not found
414there, the attribute search continues in the base classes. The search
415is depth-first, left-to-right in the order of their occurrence in the
416base class list.
417\obindex{class}
418\obindex{class instance}
419\obindex{instance}
420\indexii{class object}{call}
421\index{container}
Guido van Rossumb2c65561993-05-12 08:53:36 +0000422\obindex{dictionary}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000423\indexii{class}{attribute}
424
425Class attribute assignments update the class's dictionary, never the
426dictionary of a base class.
427\indexiii{class}{attribute}{assignment}
428
Guido van Rossum6938f061994-08-01 12:22:53 +0000429A class can be called as a function to yield a class instance (see
430above).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000431\indexii{class object}{call}
432
Guido van Rossum6938f061994-08-01 12:22:53 +0000433Special read-only attributes: \verb@__dict__@ yields the dictionary
434containing the class's name space; \verb@__bases__@ yields a tuple
Guido van Rossum46f3e001992-08-14 09:11:01 +0000435(possibly empty or a singleton) containing the base classes, in the
436order of their occurrence in the base class list.
437\ttindex{__dict__}
438\ttindex{__bases__}
439
440\item[Class instances]
441A class instance is created by calling a class object as a
Guido van Rossum6938f061994-08-01 12:22:53 +0000442function. A class instance has a dictionary in which
Guido van Rossum46f3e001992-08-14 09:11:01 +0000443attribute references are searched. When an attribute is not found
444there, and the instance's class has an attribute by that name, and
445that class attribute is a user-defined function (and in no other
446cases), the instance attribute reference yields a user-defined method
447object (see above) constructed from the instance and the function.
448\obindex{class instance}
449\obindex{instance}
450\indexii{class}{instance}
451\indexii{class instance}{attribute}
452
453Attribute assignments update the instance's dictionary.
454\indexiii{class instance}{attribute}{assignment}
455
456Class instances can pretend to be numbers, sequences, or mappings if
457they have methods with certain special names. These are described in
458section \ref{specialnames}.
459\obindex{number}
460\obindex{sequence}
461\obindex{mapping}
462
Guido van Rossum6938f061994-08-01 12:22:53 +0000463Special read-only attributes: \verb@__dict__@ yields the attribute
464dictionary; \verb@__class__@ yields the instance's class.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000465\ttindex{__dict__}
466\ttindex{__class__}
467
468\item[Files]
469A file object represents an open file. (It is a wrapper around a C
470{\tt stdio} file pointer.) File objects are created by the
Guido van Rossum6938f061994-08-01 12:22:53 +0000471\verb@open()@ built-in function, and also by \verb@posix.popen()@ and
472the \verb@makefile@ method of socket objects. \verb@sys.stdin@,
473\verb@sys.stdout@ and \verb@sys.stderr@ are file objects corresponding
Guido van Rossum31cce971995-01-04 19:17:34 +0000474to the interpreter's standard input, output and error streams.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000475See the Python Library Reference for methods of file objects and other
476details.
477\obindex{file}
478\index{C}
479\index{stdio}
480\bifuncindex{open}
481\bifuncindex{popen}
482\bifuncindex{makefile}
483\ttindex{stdin}
484\ttindex{stdout}
485\ttindex{stderr}
486\ttindex{sys.stdin}
487\ttindex{sys.stdout}
488\ttindex{sys.stderr}
489
490\item[Internal types]
491A few types used internally by the interpreter are exposed to the user.
492Their definition may change with future versions of the interpreter,
493but they are mentioned here for completeness.
494\index{internal type}
495
496\begin{description}
497
498\item[Code objects]
Guido van Rossum3d54de21995-03-07 10:09:55 +0000499Code objects represent ``pseudo-compiled'' executable Python code.
500The difference between a code
Guido van Rossum46f3e001992-08-14 09:11:01 +0000501object and a function object is that the function object contains an
502explicit reference to the function's context (the module in which it
Guido van Rossum3d54de21995-03-07 10:09:55 +0000503was defined) while a code object contains no context.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000504\obindex{code}
505
Guido van Rossum6938f061994-08-01 12:22:53 +0000506Special read-only attributes: \verb@co_code@ is a string representing
507the sequence of instructions; \verb@co_consts@ is a list of literals
508used by the code; \verb@co_names@ is a list of names (strings) used by
509the code; \verb@co_filename@ is the filename from which the code was
Guido van Rossum46f3e001992-08-14 09:11:01 +0000510compiled. (To find out the line numbers, you would have to decode the
Guido van Rossum6938f061994-08-01 12:22:53 +0000511instructions; the standard library module \verb@dis@ contains an
Guido van Rossum46f3e001992-08-14 09:11:01 +0000512example of how to do this.)
513\ttindex{co_code}
514\ttindex{co_consts}
515\ttindex{co_names}
516\ttindex{co_filename}
517
518\item[Frame objects]
519Frame objects represent execution frames. They may occur in traceback
520objects (see below).
521\obindex{frame}
522
Guido van Rossum6938f061994-08-01 12:22:53 +0000523Special read-only attributes: \verb@f_back@ is to the previous
524stack frame (towards the caller), or \verb@None@ if this is the bottom
525stack frame; \verb@f_code@ is the code object being executed in this
526frame; \verb@f_globals@ is the dictionary used to look up global
527variables; \verb@f_locals@ is used for local variables;
528\verb@f_lineno@ gives the line number and \verb@f_lasti@ gives the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000529precise instruction (this is an index into the instruction string of
530the code object).
531\ttindex{f_back}
532\ttindex{f_code}
533\ttindex{f_globals}
534\ttindex{f_locals}
535\ttindex{f_lineno}
536\ttindex{f_lasti}
537
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000538\item[Traceback objects] \label{traceback}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000539Traceback objects represent a stack trace of an exception. A
540traceback object is created when an exception occurs. When the search
541for an exception handler unwinds the execution stack, at each unwound
542level a traceback object is inserted in front of the current
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000543traceback. When an exception handler is entered
544(see also section \ref{try}), the stack trace is
Guido van Rossum6938f061994-08-01 12:22:53 +0000545made available to the program as \verb@sys.exc_traceback@. When the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000546program contains no suitable handler, the stack trace is written
547(nicely formatted) to the standard error stream; if the interpreter is
548interactive, it is also made available to the user as
Guido van Rossum6938f061994-08-01 12:22:53 +0000549\verb@sys.last_traceback@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000550\obindex{traceback}
551\indexii{stack}{trace}
552\indexii{exception}{handler}
553\indexii{execution}{stack}
554\ttindex{exc_traceback}
555\ttindex{last_traceback}
556\ttindex{sys.exc_traceback}
557\ttindex{sys.last_traceback}
558
Guido van Rossum6938f061994-08-01 12:22:53 +0000559Special read-only attributes: \verb@tb_next@ is the next level in the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000560stack trace (towards the frame where the exception occurred), or
Guido van Rossum6938f061994-08-01 12:22:53 +0000561\verb@None@ if there is no next level; \verb@tb_frame@ points to the
562execution frame of the current level; \verb@tb_lineno@ gives the line
563number where the exception occurred; \verb@tb_lasti@ indicates the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000564precise instruction. The line number and last instruction in the
565traceback may differ from the line number of its frame object if the
Guido van Rossum6938f061994-08-01 12:22:53 +0000566exception occurred in a \verb@try@ statement with no matching
567\verb@except@ clause or with a \verb@finally@ clause.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000568\ttindex{tb_next}
569\ttindex{tb_frame}
570\ttindex{tb_lineno}
571\ttindex{tb_lasti}
572\stindex{try}
573
574\end{description} % Internal types
575
576\end{description} % Types
577
578
579\section{Special method names} \label{specialnames}
580
581A class can implement certain operations that are invoked by special
582syntax (such as subscription or arithmetic operations) by defining
583methods with special names. For instance, if a class defines a
Guido van Rossum6938f061994-08-01 12:22:53 +0000584method named \verb@__getitem__@, and \verb@x@ is an instance of this
585class, then \verb@x[i]@ is equivalent to \verb@x.__getitem__(i)@.
586(The reverse is not true --- if \verb@x@ is a list object,
587\verb@x.__getitem__(i)@ is not equivalent to \verb@x[i]@.)
Guido van Rossumaaec4031995-03-21 14:41:57 +0000588\ttindex{__getitem__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000589
Guido van Rossum6938f061994-08-01 12:22:53 +0000590Except for \verb@__repr__@, \verb@__str__@ and \verb@__cmp__@,
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000591attempts to execute an
Guido van Rossum46f3e001992-08-14 09:11:01 +0000592operation raise an exception when no appropriate method is defined.
Guido van Rossum6938f061994-08-01 12:22:53 +0000593For \verb@__repr__@, the default is to return a string describing the
594object's class and address.
595For \verb@__cmp__@, the default is to compare instances based on their
596address.
597For \verb@__str__@, the default is to use \verb@__repr__@.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000598\ttindex{__repr__}
599\ttindex{__str__}
600\ttindex{__cmp__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000601
602
603\subsection{Special methods for any type}
604
605\begin{description}
606
Guido van Rossuma5475471995-03-16 14:44:07 +0000607\item[{\tt __init__(self, args...)}]
Guido van Rossum23301a91993-05-24 14:19:37 +0000608Called when the instance is created. The arguments are those passed
609to the class constructor expression. If a base class has an
610\code{__init__} method the derived class's \code{__init__} method must
611explicitly call it to ensure proper initialization of the base class
612part of the instance.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000613\ttindex{__init__}
614\indexii{class}{constructor}
615
Guido van Rossum23301a91993-05-24 14:19:37 +0000616
Guido van Rossuma5475471995-03-16 14:44:07 +0000617\item[{\tt __del__(self)}]
Guido van Rossum23301a91993-05-24 14:19:37 +0000618Called when the instance is about to be destroyed. If a base class
619has an \code{__del__} method the derived class's \code{__del__} method
620must explicitly call it to ensure proper deletion of the base class
621part of the instance. Note that it is possible for the \code{__del__}
622method to postpone destruction of the instance by creating a new
623reference to it. It may then be called at a later time when this new
Guido van Rossum29c1b971994-10-09 22:56:16 +0000624reference is deleted. It is not guaranteed that
Guido van Rossum23301a91993-05-24 14:19:37 +0000625\code{__del__} methods are called for objects that still exist when
626the interpreter exits.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000627\ttindex{__del__}
628\stindex{del}
Guido van Rossum23301a91993-05-24 14:19:37 +0000629
Guido van Rossum86751151995-02-28 17:14:32 +0000630Note that \code{del x} doesn't directly call \code{x.__del__} --- the
Guido van Rossum29c1b971994-10-09 22:56:16 +0000631former decrements the reference count for \code{x} by one, but
Guido van Rossum8fd02191995-07-07 23:05:13 +0000632\code{x.__del__} is only called when its reference count reaches zero.
Guido van Rossum29c1b971994-10-09 22:56:16 +0000633
Guido van Rossuma5475471995-03-16 14:44:07 +0000634\item[{\tt __repr__(self)}]
Guido van Rossum31cce971995-01-04 19:17:34 +0000635Called by the \verb@repr()@ built-in function and by string conversions
636(reverse or backward quotes) to compute the string representation of an object.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000637\ttindex{__repr__}
638\bifuncindex{repr}
Guido van Rossum31cce971995-01-04 19:17:34 +0000639\indexii{string}{conversion}
640\indexii{reverse}{quotes}
641\indexii{backward}{quotes}
642\index{back-quotes}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000643
Guido van Rossuma5475471995-03-16 14:44:07 +0000644\item[{\tt __str__(self)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000645Called by the \verb@str()@ built-in function and by the \verb@print@
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000646statement compute the string representation of an object.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000647\ttindex{__str__}
648\bifuncindex{str}
649\stindex{print}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000650
Guido van Rossuma5475471995-03-16 14:44:07 +0000651\item[{\tt __cmp__(self, other)}]
Guido van Rossum46f3e001992-08-14 09:11:01 +0000652Called by all comparison operations. Should return -1 if
Guido van Rossum6938f061994-08-01 12:22:53 +0000653\verb@self < other@, 0 if \verb@self == other@, +1 if
654\verb@self > other@. If no \code{__cmp__} operation is defined, class
Guido van Rossumb2c65561993-05-12 08:53:36 +0000655instances are compared by object identity (``address'').
656(Implementation note: due to limitations in the interpreter,
657exceptions raised by comparisons are ignored, and the objects will be
658considered equal in this case.)
Guido van Rossumaaec4031995-03-21 14:41:57 +0000659\ttindex{__cmp__}
660\bifuncindex{cmp}
661\index{comparisons}
Guido van Rossumb2c65561993-05-12 08:53:36 +0000662
Guido van Rossuma5475471995-03-16 14:44:07 +0000663\item[{\tt __hash__(self)}]
Guido van Rossum29c1b971994-10-09 22:56:16 +0000664Called for the key object for dictionary operations,
665and by the built-in function
Guido van Rossumb2c65561993-05-12 08:53:36 +0000666\code{hash()}. Should return a 32-bit integer usable as a hash value
667for dictionary operations. The only required property is that objects
668which compare equal have the same hash value; it is advised to somehow
Guido van Rossum8fd02191995-07-07 23:05:13 +0000669mix together (e.g. using exclusive or) the hash values for the
Guido van Rossumb2c65561993-05-12 08:53:36 +0000670components of the object that also play a part in comparison of
671objects. If a class does not define a \code{__cmp__} method it should
672not define a \code{__hash__} operation either; if it defines
673\code{__cmp__} but not \code{__hash__} its instances will not be
674usable as dictionary keys. If a class defines mutable objects and
675implements a \code{__cmp__} method it should not implement
676\code{__hash__}, since the dictionary implementation assumes that a
677key's hash value is a constant.
678\obindex{dictionary}
Guido van Rossumaaec4031995-03-21 14:41:57 +0000679\ttindex{__cmp__}
680\ttindex{__hash__}
681\bifuncindex{hash}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000682
Guido van Rossuma5475471995-03-16 14:44:07 +0000683\item[{\tt __call__(self, *args)}]
Guido van Rossum29c1b971994-10-09 22:56:16 +0000684Called when the instance is ``called'' as a function.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000685\ttindex{__call__}
686\indexii{call}{instance}
Guido van Rossum29c1b971994-10-09 22:56:16 +0000687
688\end{description}
689
690
691\subsection{Special methods for attribute access}
692
693The following methods can be used to change the meaning of attribute
694access for class instances.
695
696\begin{description}
697
Guido van Rossuma5475471995-03-16 14:44:07 +0000698\item[{\tt __getattr__(self, name)}]
Guido van Rossum29c1b971994-10-09 22:56:16 +0000699Called when an attribute lookup has not found the attribute in the
700usual places (i.e. it is not an instance attribute nor is it found in
701the class tree for \code{self}). \code{name} is the attribute name.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000702\ttindex{__getattr__}
Guido van Rossum29c1b971994-10-09 22:56:16 +0000703
704Note that if the attribute is found through the normal mechanism,
705\code{__getattr__} is not called. (This is an asymmetry between
706\code{__getattr__} and \code{__setattr__}.)
707This is done both for efficiency reasons and because otherwise
708\code{__getattr__} would have no way to access other attributes of the
709instance.
710Note that at least for instance variables, \code{__getattr__} can fake
711total control by simply not inserting any values in the instance
712attribute dictionary.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000713\ttindex{__setattr__}
Guido van Rossum29c1b971994-10-09 22:56:16 +0000714
Guido van Rossuma5475471995-03-16 14:44:07 +0000715\item[{\tt __setattr__(self, name, value)}]
Guido van Rossum29c1b971994-10-09 22:56:16 +0000716Called when an attribute assignment is attempted. This is called
717instead of the normal mechanism (i.e. store the value as an instance
718attribute). \code{name} is the attribute name, \code{value} is the
719value to be assigned to it.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000720\ttindex{__setattr__}
Guido van Rossum29c1b971994-10-09 22:56:16 +0000721
722If \code{__setattr__} wants to assign to an instance attribute, it
Guido van Rossum86751151995-02-28 17:14:32 +0000723should not simply execute \code{self.\var{name} = value} --- this would
Guido van Rossum29c1b971994-10-09 22:56:16 +0000724cause a recursive call. Instead, it should insert the value in the
725dictionary of instance attributes, e.g. \code{self.__dict__[name] =
726value}.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000727\ttindex{__dict__}
Guido van Rossum29c1b971994-10-09 22:56:16 +0000728
Guido van Rossuma5475471995-03-16 14:44:07 +0000729\item[{\tt __delattr__(self, name)}]
Guido van Rossum29c1b971994-10-09 22:56:16 +0000730Like \code{__setattr__} but for attribute deletion instead of
731assignment.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000732\ttindex{__delattr__}
Guido van Rossum29c1b971994-10-09 22:56:16 +0000733
Guido van Rossum46f3e001992-08-14 09:11:01 +0000734\end{description}
735
736
737\subsection{Special methods for sequence and mapping types}
738
739\begin{description}
740
Guido van Rossuma5475471995-03-16 14:44:07 +0000741\item[{\tt __len__(self)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000742Called to implement the built-in function \verb@len()@. Should return
743the length of the object, an integer \verb@>=@ 0. Also, an object
744whose \verb@__len__()@ method returns 0 is considered to be false in a
Guido van Rossum46f3e001992-08-14 09:11:01 +0000745Boolean context.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000746\ttindex{__len__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000747
Guido van Rossuma5475471995-03-16 14:44:07 +0000748\item[{\tt __getitem__(self, key)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000749Called to implement evaluation of \verb@self[key]@. Note that the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000750special interpretation of negative keys (if the class wishes to
Guido van Rossum6938f061994-08-01 12:22:53 +0000751emulate a sequence type) is up to the \verb@__getitem__@ method.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000752\ttindex{__getitem__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000753
Guido van Rossuma5475471995-03-16 14:44:07 +0000754\item[{\tt __setitem__(self, key, value)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000755Called to implement assignment to \verb@self[key]@. Same note as for
756\verb@__getitem__@.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000757\ttindex{__setitem__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000758
Guido van Rossuma5475471995-03-16 14:44:07 +0000759\item[{\tt __delitem__(self, key)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000760Called to implement deletion of \verb@self[key]@. Same note as for
761\verb@__getitem__@.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000762\ttindex{__delitem__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000763
764\end{description}
765
766
767\subsection{Special methods for sequence types}
768
769\begin{description}
770
Guido van Rossuma5475471995-03-16 14:44:07 +0000771\item[{\tt __getslice__(self, i, j)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000772Called to implement evaluation of \verb@self[i:j]@. Note that missing
773\verb@i@ or \verb@j@ are replaced by 0 or \verb@len(self)@,
774respectively, and \verb@len(self)@ has been added (once) to originally
775negative \verb@i@ or \verb@j@ by the time this function is called
776(unlike for \verb@__getitem__@).
Guido van Rossumaaec4031995-03-21 14:41:57 +0000777\ttindex{__getslice__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000778
Guido van Rossuma5475471995-03-16 14:44:07 +0000779\item[{\tt __setslice__(self, i, j, sequence)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000780Called to implement assignment to \verb@self[i:j]@. Same notes as for
781\verb@__getslice__@.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000782\ttindex{__setslice__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000783
Guido van Rossuma5475471995-03-16 14:44:07 +0000784\item[{\tt __delslice__(self, i, j)}]
Guido van Rossum6938f061994-08-01 12:22:53 +0000785Called to implement deletion of \verb@self[i:j]@. Same notes as for
786\verb@__getslice__@.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000787\ttindex{__delslice__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000788
789\end{description}
790
791
792\subsection{Special methods for numeric types}
793
794\begin{description}
795
Guido van Rossuma5475471995-03-16 14:44:07 +0000796\item[{\tt __add__(self, other)}]\itemjoin
797\item[{\tt __sub__(self, other)}]\itemjoin
798\item[{\tt __mul__(self, other)}]\itemjoin
799\item[{\tt __div__(self, other)}]\itemjoin
800\item[{\tt __mod__(self, other)}]\itemjoin
801\item[{\tt __divmod__(self, other)}]\itemjoin
802\item[{\tt __pow__(self, other)}]\itemjoin
803\item[{\tt __lshift__(self, other)}]\itemjoin
804\item[{\tt __rshift__(self, other)}]\itemjoin
805\item[{\tt __and__(self, other)}]\itemjoin
806\item[{\tt __xor__(self, other)}]\itemjoin
807\item[{\tt __or__(self, other)}]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000808Called to implement the binary arithmetic operations (\verb@+@,
809\verb@-@, \verb@*@, \verb@/@, \verb@%@, \verb@divmod()@, \verb@pow()@,
810\verb@<<@, \verb@>>@, \verb@&@, \verb@^@, \verb@|@).
Guido van Rossumaaec4031995-03-21 14:41:57 +0000811\ttindex{__or__}
812\ttindex{__xor__}
813\ttindex{__and__}
814\ttindex{__rshift__}
815\ttindex{__lshift__}
816\ttindex{__pow__}
817\ttindex{__divmod__}
818\ttindex{__mod__}
819\ttindex{__div__}
820\ttindex{__mul__}
821\ttindex{__sub__}
822\ttindex{__add__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000823
Guido van Rossuma5475471995-03-16 14:44:07 +0000824\item[{\tt __neg__(self)}]\itemjoin
825\item[{\tt __pos__(self)}]\itemjoin
826\item[{\tt __abs__(self)}]\itemjoin
827\item[{\tt __invert__(self)}]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000828Called to implement the unary arithmetic operations (\verb@-@, \verb@+@,
829\verb@abs()@ and \verb@~@).
Guido van Rossumaaec4031995-03-21 14:41:57 +0000830\ttindex{__invert__}
831\ttindex{__abs__}
832\ttindex{__pos__}
833\ttindex{__neg__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000834
Guido van Rossuma5475471995-03-16 14:44:07 +0000835\item[{\tt __nonzero__(self)}]
Guido van Rossum46f3e001992-08-14 09:11:01 +0000836Called to implement boolean testing; should return 0 or 1. An
Guido van Rossum6938f061994-08-01 12:22:53 +0000837alternative name for this method is \verb@__len__@.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000838\ttindex{__nonzero__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000839
Guido van Rossuma5475471995-03-16 14:44:07 +0000840\item[{\tt __coerce__(self, other)}]
Guido van Rossum46f3e001992-08-14 09:11:01 +0000841Called to implement ``mixed-mode'' numeric arithmetic. Should either
842return a tuple containing self and other converted to a common numeric
843type, or None if no way of conversion is known. When the common type
844would be the type of other, it is sufficient to return None, since the
845interpreter will also ask the other object to attempt a coercion (but
846sometimes, if the implementation of the other type cannot be changed,
847it is useful to do the conversion to the other type here).
Guido van Rossumaaec4031995-03-21 14:41:57 +0000848\ttindex{__coerce__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000849
Guido van Rossum6938f061994-08-01 12:22:53 +0000850Note that this method is not called to coerce the arguments to \verb@+@
851and \verb@*@, because these are also used to implement sequence
Guido van Rossum46f3e001992-08-14 09:11:01 +0000852concatenation and repetition, respectively. Also note that, for the
Guido van Rossum6938f061994-08-01 12:22:53 +0000853same reason, in \verb@n*x@, where \verb@n@ is a built-in number and
854\verb@x@ is an instance, a call to \verb@x.__mul__(n)@ is made.%
Guido van Rossum46f3e001992-08-14 09:11:01 +0000855\footnote{The interpreter should really distinguish between
856user-defined classes implementing sequences, mappings or numbers, but
857currently it doesn't --- hence this strange exception.}
Guido van Rossumaaec4031995-03-21 14:41:57 +0000858\ttindex{__mul__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000859
Guido van Rossuma5475471995-03-16 14:44:07 +0000860\item[{\tt __int__(self)}]\itemjoin
861\item[{\tt __long__(self)}]\itemjoin
862\item[{\tt __float__(self)}]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000863Called to implement the built-in functions \verb@int()@, \verb@long()@
864and \verb@float()@. Should return a value of the appropriate type.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000865\ttindex{__float__}
866\ttindex{__long__}
867\ttindex{__int__}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000868
Guido van Rossuma5475471995-03-16 14:44:07 +0000869\item[{\tt __oct__(self)}]\itemjoin
870\item[{\tt __hex__(self)}]\itembreak
Guido van Rossum6938f061994-08-01 12:22:53 +0000871Called to implement the built-in functions \verb@oct()@ and
872\verb@hex()@. Should return a string value.
Guido van Rossumaaec4031995-03-21 14:41:57 +0000873\ttindex{__hex__}
874\ttindex{__oct__}
Guido van Rossum66122d21992-09-20 21:43:47 +0000875
Guido van Rossum46f3e001992-08-14 09:11:01 +0000876\end{description}