blob: 7d36cbd34fa5da190164ed6382f57bc3061f2a76 [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 Drake2829f1c2001-06-23 05:27:20 +00003
Fred Drake61c77281998-07-28 19:34:22 +00004\section{Objects, values and types\label{objects}}
Fred Drakef6669171998-05-06 19:52:49 +00005
6\dfn{Objects} are Python's abstraction for data. All data in a Python
7program is represented by objects or by relations between objects.
8(In a sense, and in conformance to Von Neumann's model of a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00009``stored program computer,'' code is also represented by objects.)
Fred Drakef6669171998-05-06 19:52:49 +000010\index{object}
11\index{data}
12
13Every object has an identity, a type and a value. An object's
14\emph{identity} never changes once it has been created; you may think
Fred Drake293dd4b2002-06-04 16:25:57 +000015of it as the object's address in memory. The `\keyword{is}' operator
Fred Drake82385871998-10-01 20:40:43 +000016compares the identity of two objects; the
17\function{id()}\bifuncindex{id} function returns an integer
18representing its identity (currently implemented as its address).
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000019An object's \dfn{type} is
Raymond Hettingere701dcb2003-01-19 13:08:18 +000020also unchangeable.\footnote{Since Python 2.2, a gradual merging of
21types and classes has been started that makes this and a few other
22assertions made in this manual not 100\% accurate and complete:
23for example, it \emph{is} now possible in some cases to change an
24object's type, under certain controlled conditions. Until this manual
25undergoes extensive revision, it must now be taken as authoritative
26only regarding ``classic classes'', that are still the default, for
Armin Rigoddddd2f2005-12-26 18:06:17 +000027compatibility purposes, in Python 2.2 and 2.3. For more information,
28see \url{http://www.python.org/doc/newstyle.html}.}
Raymond Hettingere701dcb2003-01-19 13:08:18 +000029An object's type determines the operations that the object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000030supports (e.g., ``does it have a length?'') and also defines the
Fred Drake82385871998-10-01 20:40:43 +000031possible values for objects of that type. The
32\function{type()}\bifuncindex{type} function returns an object's type
33(which is an object itself). The \emph{value} of some
Fred Drakef6669171998-05-06 19:52:49 +000034objects can change. Objects whose value can change are said to be
35\emph{mutable}; objects whose value is unchangeable once they are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000036created are called \emph{immutable}.
Guido van Rossum264bd591999-02-23 16:40:55 +000037(The value of an immutable container object that contains a reference
38to a mutable object can change when the latter's value is changed;
39however the container is still considered immutable, because the
40collection of objects it contains cannot be changed. So, immutability
41is not strictly the same as having an unchangeable value, it is more
42subtle.)
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000043An object's mutability is determined by its type; for instance,
44numbers, strings and tuples are immutable, while dictionaries and
45lists are mutable.
Fred Drakef6669171998-05-06 19:52:49 +000046\index{identity of an object}
47\index{value of an object}
48\index{type of an object}
49\index{mutable object}
50\index{immutable object}
51
52Objects are never explicitly destroyed; however, when they become
53unreachable they may be garbage-collected. An implementation is
Barry Warsaw92a6ed91998-08-07 16:33:51 +000054allowed to postpone garbage collection or omit it altogether --- it is
55a matter of implementation quality how garbage collection is
Fred Drakef6669171998-05-06 19:52:49 +000056implemented, as long as no objects are collected that are still
57reachable. (Implementation note: the current implementation uses a
Fred Drakec8e82812001-01-22 17:46:18 +000058reference-counting scheme with (optional) delayed detection of
Raymond Hettingere701dcb2003-01-19 13:08:18 +000059cyclically linked garbage, which collects most objects as soon as they
Fred Drakec8e82812001-01-22 17:46:18 +000060become unreachable, but is not guaranteed to collect garbage
61containing circular references. See the
62\citetitle[../lib/module-gc.html]{Python Library Reference} for
63information on controlling the collection of cyclic garbage.)
Fred Drakef6669171998-05-06 19:52:49 +000064\index{garbage collection}
65\index{reference counting}
66\index{unreachable object}
67
68Note that the use of the implementation's tracing or debugging
69facilities may keep objects alive that would normally be collectable.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000070Also note that catching an exception with a
Fred Drake4856d011999-01-12 04:15:20 +000071`\keyword{try}...\keyword{except}' statement may keep objects alive.
Fred Drakef6669171998-05-06 19:52:49 +000072
73Some objects contain references to ``external'' resources such as open
74files or windows. It is understood that these resources are freed
75when the object is garbage-collected, but since garbage collection is
76not guaranteed to happen, such objects also provide an explicit way to
77release the external resource, usually a \method{close()} method.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000078Programs are strongly recommended to explicitly close such
Fred Drake4856d011999-01-12 04:15:20 +000079objects. The `\keyword{try}...\keyword{finally}' statement provides
80a convenient way to do this.
Fred Drakef6669171998-05-06 19:52:49 +000081
82Some objects contain references to other objects; these are called
83\emph{containers}. Examples of containers are tuples, lists and
84dictionaries. The references are part of a container's value. In
85most cases, when we talk about the value of a container, we imply the
86values, not the identities of the contained objects; however, when we
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000087talk about the mutability of a container, only the identities of
88the immediately contained objects are implied. So, if an immutable
89container (like a tuple)
90contains a reference to a mutable object, its value changes
91if that mutable object is changed.
Fred Drakef6669171998-05-06 19:52:49 +000092\index{container}
93
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000094Types affect almost all aspects of object behavior. Even the importance
Fred Drakef6669171998-05-06 19:52:49 +000095of object identity is affected in some sense: for immutable types,
96operations that compute new values may actually return a reference to
97any existing object with the same type and value, while for mutable
Guido van Rossum83b2f8a1998-07-23 17:12:46 +000098objects this is not allowed. E.g., after
Fred Drake82385871998-10-01 20:40:43 +000099\samp{a = 1; b = 1},
Fred Drakef6669171998-05-06 19:52:49 +0000100\code{a} and \code{b} may or may not refer to the same object with the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000101value one, depending on the implementation, but after
Fred Drake82385871998-10-01 20:40:43 +0000102\samp{c = []; d = []}, \code{c} and \code{d}
Fred Drakef6669171998-05-06 19:52:49 +0000103are guaranteed to refer to two different, unique, newly created empty
104lists.
Fred Drake82385871998-10-01 20:40:43 +0000105(Note that \samp{c = d = []} assigns the same object to both
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000106\code{c} and \code{d}.)
Fred Drakef6669171998-05-06 19:52:49 +0000107
Fred Drake2829f1c2001-06-23 05:27:20 +0000108
Fred Drake61c77281998-07-28 19:34:22 +0000109\section{The standard type hierarchy\label{types}}
Fred Drakef6669171998-05-06 19:52:49 +0000110
111Below is a list of the types that are built into Python. Extension
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000112modules (written in C, Java, or other languages, depending on
113the implementation) can define additional types. Future versions of
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000114Python may add types to the type hierarchy (e.g., rational
Fred Drakef6669171998-05-06 19:52:49 +0000115numbers, efficiently stored arrays of integers, etc.).
116\index{type}
117\indexii{data}{type}
118\indexii{type}{hierarchy}
119\indexii{extension}{module}
120\indexii{C}{language}
121
122Some of the type descriptions below contain a paragraph listing
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000123`special attributes.' These are attributes that provide access to the
Fred Drakef6669171998-05-06 19:52:49 +0000124implementation and are not intended for general use. Their definition
Fred Drake35705512001-12-03 17:32:27 +0000125may change in the future.
Fred Drakef6669171998-05-06 19:52:49 +0000126\index{attribute}
127\indexii{special}{attribute}
128\indexiii{generic}{special}{attribute}
Fred Drakef6669171998-05-06 19:52:49 +0000129
130\begin{description}
131
132\item[None]
133This type has a single value. There is a single object with this value.
134This object is accessed through the built-in name \code{None}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000135It is used to signify the absence of a value in many situations, e.g.,
136it is returned from functions that don't explicitly return anything.
137Its truth value is false.
Fred Drake7a700b82004-01-01 05:43:53 +0000138\obindex{None}
Fred Drakef6669171998-05-06 19:52:49 +0000139
Neil Schemenauer48c2eb92001-01-04 01:25:50 +0000140\item[NotImplemented]
141This type has a single value. There is a single object with this value.
142This object is accessed through the built-in name \code{NotImplemented}.
Guido van Rossumab782dd2001-01-18 15:17:06 +0000143Numeric methods and rich comparison methods may return this value if
144they do not implement the operation for the operands provided. (The
145interpreter will then try the reflected operation, or some other
146fallback, depending on the operator.) Its truth value is true.
Fred Drake7a700b82004-01-01 05:43:53 +0000147\obindex{NotImplemented}
Neil Schemenauer48c2eb92001-01-04 01:25:50 +0000148
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000149\item[Ellipsis]
150This type has a single value. There is a single object with this value.
151This object is accessed through the built-in name \code{Ellipsis}.
Fred Drake82385871998-10-01 20:40:43 +0000152It is used to indicate the presence of the \samp{...} syntax in a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000153slice. Its truth value is true.
Fred Drakec0a02c02002-04-16 02:03:05 +0000154\obindex{Ellipsis}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000155
Fred Drakef6669171998-05-06 19:52:49 +0000156\item[Numbers]
157These are created by numeric literals and returned as results by
158arithmetic operators and arithmetic built-in functions. Numeric
159objects are immutable; once created their value never changes. Python
160numbers are of course strongly related to mathematical numbers, but
161subject to the limitations of numerical representation in computers.
Fred Drakef6669171998-05-06 19:52:49 +0000162\obindex{numeric}
163
Fred Drakeb3384d32001-05-14 16:04:22 +0000164Python distinguishes between integers, floating point numbers, and
165complex numbers:
Fred Drakef6669171998-05-06 19:52:49 +0000166
167\begin{description}
168\item[Integers]
Georg Brandld4307262005-09-12 12:49:38 +0000169These represent elements from the mathematical set of integers
170(positive and negative).
Fred Drakef6669171998-05-06 19:52:49 +0000171\obindex{integer}
172
Guido van Rossum77f6a652002-04-03 22:41:51 +0000173There are three types of integers:
Fred Drakef6669171998-05-06 19:52:49 +0000174
175\begin{description}
176
177\item[Plain integers]
178These represent numbers in the range -2147483648 through 2147483647.
179(The range may be larger on machines with a larger natural word
180size, but not smaller.)
Fred Drakee15956b2000-04-03 04:51:13 +0000181When the result of an operation would fall outside this range, the
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000182result is normally returned as a long integer (in some cases, the
183exception \exception{OverflowError} is raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000184For the purpose of shift and mask operations, integers are assumed to
185have a binary, 2's complement notation using 32 or more bits, and
186hiding no bits from the user (i.e., all 4294967296 different bit
187patterns correspond to different values).
188\obindex{plain integer}
189\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
190
191\item[Long integers]
192These represent numbers in an unlimited range, subject to available
193(virtual) memory only. For the purpose of shift and mask operations,
194a binary representation is assumed, and negative numbers are
195represented in a variant of 2's complement which gives the illusion of
196an infinite string of sign bits extending to the left.
197\obindex{long integer}
198
Guido van Rossum77f6a652002-04-03 22:41:51 +0000199\item[Booleans]
200These represent the truth values False and True. The two objects
201representing the values False and True are the only Boolean objects.
202The Boolean type is a subtype of plain integers, and Boolean values
203behave like the values 0 and 1, respectively, in almost all contexts,
204the exception being that when converted to a string, the strings
205\code{"False"} or \code{"True"} are returned, respectively.
206\obindex{Boolean}
207\ttindex{False}
208\ttindex{True}
209
Fred Drakef6669171998-05-06 19:52:49 +0000210\end{description} % Integers
211
212The rules for integer representation are intended to give the most
213meaningful interpretation of shift and mask operations involving
214negative integers and the least surprises when switching between the
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000215plain and long integer domains. Any operation except left shift,
Fred Drakef6669171998-05-06 19:52:49 +0000216if it yields a result in the plain integer domain without causing
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000217overflow, will yield the same result in the long integer domain or
Fred Drakef6669171998-05-06 19:52:49 +0000218when using mixed operands.
219\indexii{integer}{representation}
220
221\item[Floating point numbers]
222These represent machine-level double precision floating point numbers.
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000223You are at the mercy of the underlying machine architecture (and
224C or Java implementation) for the accepted range and handling of overflow.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000225Python does not support single-precision floating point numbers; the
Fred Drake6e5e1d92001-07-14 02:12:27 +0000226savings in processor and memory usage that are usually the reason for using
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000227these is dwarfed by the overhead of using objects in Python, so there
228is no reason to complicate the language with two kinds of floating
229point numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000230\obindex{floating point}
231\indexii{floating point}{number}
232\indexii{C}{language}
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000233\indexii{Java}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000234
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000235\item[Complex numbers]
236These represent complex numbers as a pair of machine-level double
237precision floating point numbers. The same caveats apply as for
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000238floating point numbers. The real and imaginary parts of a complex
239number \code{z} can be retrieved through the read-only attributes
240\code{z.real} and \code{z.imag}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000241\obindex{complex}
242\indexii{complex}{number}
243
Fred Drakef6669171998-05-06 19:52:49 +0000244\end{description} % Numbers
245
Guido van Rossum77f6a652002-04-03 22:41:51 +0000246
Fred Drakef6669171998-05-06 19:52:49 +0000247\item[Sequences]
Fred Drake230d17d2001-02-22 21:28:04 +0000248These represent finite ordered sets indexed by non-negative numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000249The built-in function \function{len()}\bifuncindex{len} returns the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000250number of items of a sequence.
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000251When the length of a sequence is \var{n}, the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000252index set contains the numbers 0, 1, \ldots, \var{n}-1. Item
Fred Drakef6669171998-05-06 19:52:49 +0000253\var{i} of sequence \var{a} is selected by \code{\var{a}[\var{i}]}.
Fred Drakee15956b2000-04-03 04:51:13 +0000254\obindex{sequence}
Fred Drakef6669171998-05-06 19:52:49 +0000255\index{index operation}
256\index{item selection}
257\index{subscription}
258
259Sequences also support slicing: \code{\var{a}[\var{i}:\var{j}]}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000260selects all items with index \var{k} such that \var{i} \code{<=}
Fred Drakef6669171998-05-06 19:52:49 +0000261\var{k} \code{<} \var{j}. When used as an expression, a slice is a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000262sequence of the same type. This implies that the index set is
263renumbered so that it starts at 0.
Fred Drakef6669171998-05-06 19:52:49 +0000264\index{slicing}
265
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000266Some sequences also support ``extended slicing'' with a third ``step''
267parameter: \code{\var{a}[\var{i}:\var{j}:\var{k}]} selects all items
268of \var{a} with index \var{x} where \code{\var{x} = \var{i} +
269\var{n}*\var{k}}, \var{n} \code{>=} \code{0} and \var{i} \code{<=}
270\var{x} \code{<} \var{j}.
271\index{extended slicing}
272
Fred Drakef6669171998-05-06 19:52:49 +0000273Sequences are distinguished according to their mutability:
274
275\begin{description}
Fred Drake4856d011999-01-12 04:15:20 +0000276
Fred Drakef6669171998-05-06 19:52:49 +0000277\item[Immutable sequences]
278An object of an immutable sequence type cannot change once it is
279created. (If the object contains references to other objects,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000280these other objects may be mutable and may be changed; however,
Fred Drakef6669171998-05-06 19:52:49 +0000281the collection of objects directly referenced by an immutable object
282cannot change.)
283\obindex{immutable sequence}
284\obindex{immutable}
285
286The following types are immutable sequences:
287
288\begin{description}
289
290\item[Strings]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000291The items of a string are characters. There is no separate
292character type; a character is represented by a string of one item.
Fred Drakef6669171998-05-06 19:52:49 +0000293Characters represent (at least) 8-bit bytes. The built-in
294functions \function{chr()}\bifuncindex{chr} and
295\function{ord()}\bifuncindex{ord} convert between characters and
296nonnegative integers representing the byte values. Bytes with the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000297values 0-127 usually represent the corresponding \ASCII{} values, but
298the interpretation of values is up to the program. The string
299data type is also used to represent arrays of bytes, e.g., to hold data
Fred Drakef6669171998-05-06 19:52:49 +0000300read from a file.
301\obindex{string}
302\index{character}
303\index{byte}
Fred Drakec37b65e2001-11-28 07:26:15 +0000304\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000305
Fred Drakec37b65e2001-11-28 07:26:15 +0000306(On systems whose native character set is not \ASCII, strings may use
Fred Drakef6669171998-05-06 19:52:49 +0000307EBCDIC in their internal representation, provided the functions
308\function{chr()} and \function{ord()} implement a mapping between \ASCII{} and
309EBCDIC, and string comparison preserves the \ASCII{} order.
310Or perhaps someone can propose a better rule?)
Fred Drakec37b65e2001-11-28 07:26:15 +0000311\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000312\index{EBCDIC}
313\index{character set}
314\indexii{string}{comparison}
315\bifuncindex{chr}
316\bifuncindex{ord}
317
Fred Drakef0aff8e2000-04-06 13:57:21 +0000318\item[Unicode]
Fred Drake5ec22f22002-09-24 21:09:13 +0000319The items of a Unicode object are Unicode code units. A Unicode code
320unit is represented by a Unicode object of one item and can hold
321either a 16-bit or 32-bit value representing a Unicode ordinal (the
322maximum value for the ordinal is given in \code{sys.maxunicode}, and
323depends on how Python is configured at compile time). Surrogate pairs
324may be present in the Unicode object, and will be reported as two
325separate items. The built-in functions
Fred Drakef0aff8e2000-04-06 13:57:21 +0000326\function{unichr()}\bifuncindex{unichr} and
Fred Drake5ec22f22002-09-24 21:09:13 +0000327\function{ord()}\bifuncindex{ord} convert between code units and
Fred Drakef0aff8e2000-04-06 13:57:21 +0000328nonnegative integers representing the Unicode ordinals as defined in
329the Unicode Standard 3.0. Conversion from and to other encodings are
Fred Drakeb3dfc0a2005-09-07 04:57:56 +0000330possible through the Unicode method \method{encode()} and the built-in
Fred Drake5ec22f22002-09-24 21:09:13 +0000331function \function{unicode()}.\bifuncindex{unicode}
Fred Drakef0aff8e2000-04-06 13:57:21 +0000332\obindex{unicode}
333\index{character}
334\index{integer}
Fred Drake8b3ce9e2000-04-06 14:00:14 +0000335\index{Unicode}
Fred Drakef0aff8e2000-04-06 13:57:21 +0000336
Fred Drakef6669171998-05-06 19:52:49 +0000337\item[Tuples]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000338The items of a tuple are arbitrary Python objects.
339Tuples of two or more items are formed by comma-separated lists
340of expressions. A tuple of one item (a `singleton') can be formed
Fred Drakef6669171998-05-06 19:52:49 +0000341by affixing a comma to an expression (an expression by itself does
342not create a tuple, since parentheses must be usable for grouping of
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000343expressions). An empty tuple can be formed by an empty pair of
Fred Drakef6669171998-05-06 19:52:49 +0000344parentheses.
345\obindex{tuple}
346\indexii{singleton}{tuple}
347\indexii{empty}{tuple}
348
349\end{description} % Immutable sequences
350
351\item[Mutable sequences]
352Mutable sequences can be changed after they are created. The
353subscription and slicing notations can be used as the target of
354assignment and \keyword{del} (delete) statements.
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000355\obindex{mutable sequence}
Fred Drakef6669171998-05-06 19:52:49 +0000356\obindex{mutable}
357\indexii{assignment}{statement}
358\index{delete}
359\stindex{del}
360\index{subscription}
361\index{slicing}
362
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000363There is currently a single intrinsic mutable sequence type:
Fred Drakef6669171998-05-06 19:52:49 +0000364
365\begin{description}
366
367\item[Lists]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000368The items of a list are arbitrary Python objects. Lists are formed
Fred Drakef6669171998-05-06 19:52:49 +0000369by placing a comma-separated list of expressions in square brackets.
370(Note that there are no special cases needed to form lists of length 0
371or 1.)
372\obindex{list}
373
374\end{description} % Mutable sequences
375
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000376The extension module \module{array}\refstmodindex{array} provides an
377additional example of a mutable sequence type.
378
379
Fred Drakef6669171998-05-06 19:52:49 +0000380\end{description} % Sequences
381
Georg Brandla4c8e322006-10-12 08:22:53 +0000382
383\item[Set types]
384These represent unordered, finite sets of unique, immutable objects.
385As such, they cannot be indexed by any subscript. However, they can be
386iterated over, and the built-in function \function{len()} returns the
387number of items in a set. Common uses for sets are
388fast membership testing, removing duplicates from a sequence, and
389computing mathematical operations such as intersection, union, difference,
390and symmetric difference.
391\bifuncindex{len}
392\obindex{set type}
393
394For set elements, the same immutability rules apply as for dictionary
395keys. Note that numeric types obey the normal rules for numeric
396comparison: if two numbers compare equal (e.g., \code{1} and
397\code{1.0}), only one of them can be contained in a set.
398
399There are currently two intrinsic set types:
400
401\begin{description}
402
403\item[Sets]
404These\obindex{set} represent a mutable set. They are created by the
405built-in \function{set()} constructor and can be modified afterwards
406by several methods, such as \method{add()}.
407
408\item[Frozen sets]
409These\obindex{frozenset} represent an immutable set. They are created by
410the built-in \function{frozenset()} constructor. As a frozenset is
411immutable and hashable, it can be used again as an element of another set,
412or as a dictionary key.
413
414\end{description} % Set types
415
416
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000417\item[Mappings]
Fred Drakef6669171998-05-06 19:52:49 +0000418These represent finite sets of objects indexed by arbitrary index sets.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000419The subscript notation \code{a[k]} selects the item indexed
Fred Drakef6669171998-05-06 19:52:49 +0000420by \code{k} from the mapping \code{a}; this can be used in
421expressions and as the target of assignments or \keyword{del} statements.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000422The built-in function \function{len()} returns the number of items
Fred Drakef6669171998-05-06 19:52:49 +0000423in a mapping.
424\bifuncindex{len}
425\index{subscription}
426\obindex{mapping}
427
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000428There is currently a single intrinsic mapping type:
Fred Drakef6669171998-05-06 19:52:49 +0000429
430\begin{description}
431
432\item[Dictionaries]
Fred Drake8cdee961999-02-23 18:50:38 +0000433These\obindex{dictionary} represent finite sets of objects indexed by
434nearly arbitrary values. The only types of values not acceptable as
435keys are values containing lists or dictionaries or other mutable
436types that are compared by value rather than by object identity, the
437reason being that the efficient implementation of dictionaries
438requires a key's hash value to remain constant.
Fred Drakef6669171998-05-06 19:52:49 +0000439Numeric types used for keys obey the normal rules for numeric
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000440comparison: if two numbers compare equal (e.g., \code{1} and
Fred Drakef6669171998-05-06 19:52:49 +0000441\code{1.0}) then they can be used interchangeably to index the same
442dictionary entry.
443
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000444Dictionaries are mutable; they can be created by the
Fred Drake62364ff2003-03-20 18:17:16 +0000445\code{\{...\}} notation (see section~\ref{dict}, ``Dictionary
Fred Drake8cdee961999-02-23 18:50:38 +0000446Displays'').
Fred Drakef6669171998-05-06 19:52:49 +0000447
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000448The extension modules \module{dbm}\refstmodindex{dbm},
Fred Drake59c61912005-10-30 04:29:49 +0000449\module{gdbm}\refstmodindex{gdbm}, and
450\module{bsddb}\refstmodindex{bsddb} provide additional examples of
451mapping types.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000452
Fred Drakef6669171998-05-06 19:52:49 +0000453\end{description} % Mapping types
454
455\item[Callable types]
Fred Drake8cdee961999-02-23 18:50:38 +0000456These\obindex{callable} are the types to which the function call
Fred Drake62364ff2003-03-20 18:17:16 +0000457operation (see section~\ref{calls}, ``Calls'') can be applied:
Fred Drakef6669171998-05-06 19:52:49 +0000458\indexii{function}{call}
459\index{invocation}
460\indexii{function}{argument}
Fred Drakef6669171998-05-06 19:52:49 +0000461
462\begin{description}
463
464\item[User-defined functions]
465A user-defined function object is created by a function definition
Fred Drake62364ff2003-03-20 18:17:16 +0000466(see section~\ref{function}, ``Function definitions''). It should be
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000467called with an argument
Fred Drakef6669171998-05-06 19:52:49 +0000468list containing the same number of items as the function's formal
469parameter list.
470\indexii{user-defined}{function}
471\obindex{function}
472\obindex{user-defined function}
473
Michael W. Hudson5e897952004-08-12 18:12:44 +0000474Special attributes:
Barry Warsaw7a5e80e2001-02-27 03:36:30 +0000475
Michael W. Hudson5e897952004-08-12 18:12:44 +0000476\begin{tableiii}{lll}{member}{Attribute}{Meaning}{}
477 \lineiii{func_doc}{The function's documentation string, or
478 \code{None} if unavailable}{Writable}
479
480 \lineiii{__doc__}{Another way of spelling
481 \member{func_doc}}{Writable}
482
483 \lineiii{func_name}{The function's name}{Writable}
484
485 \lineiii{__name__}{Another way of spelling
486 \member{func_name}}{Writable}
487
488 \lineiii{__module__}{The name of the module the function was defined
489 in, or \code{None} if unavailable.}{Writable}
490
Raymond Hettingerf21569e2005-04-26 05:18:53 +0000491 \lineiii{func_defaults}{A tuple containing default argument values
Michael W. Hudson5e897952004-08-12 18:12:44 +0000492 for those arguments that have defaults, or \code{None} if no
493 arguments have a default value}{Writable}
494
495 \lineiii{func_code}{The code object representing the compiled
496 function body.}{Writable}
497
498 \lineiii{func_globals}{A reference to the dictionary that holds the
499 function's global variables --- the global namespace of the module
500 in which the function was defined.}{Read-only}
501
502 \lineiii{func_dict}{The namespace supporting arbitrary function
503 attributes.}{Writable}
504
505 \lineiii{func_closure}{\code{None} or a tuple of cells that contain
506 bindings for the function's free variables.}{Read-only}
507\end{tableiii}
508
509Most of the attributes labelled ``Writable'' check the type of the
510assigned value.
511
512\versionchanged[\code{func_name} is now writable]{2.4}
513
514Function objects also support getting and setting arbitrary
515attributes, which can be used, for example, to attach metadata to
516functions. Regular attribute dot-notation is used to get and set such
517attributes. \emph{Note that the current implementation only supports
518function attributes on user-defined functions. Function attributes on
519built-in functions may be supported in the future.}
520
521Additional information about a function's definition can be retrieved
522from its code object; see the description of internal types below.
Jeremy Hyltonaa90adc2001-03-23 17:23:50 +0000523
Fred Drake4856d011999-01-12 04:15:20 +0000524\withsubitem{(function attribute)}{
525 \ttindex{func_doc}
526 \ttindex{__doc__}
527 \ttindex{__name__}
Jeremy Hyltonf9b0cc72003-01-31 18:52:45 +0000528 \ttindex{__module__}
Barry Warsaw7a5e80e2001-02-27 03:36:30 +0000529 \ttindex{__dict__}
Fred Drake4856d011999-01-12 04:15:20 +0000530 \ttindex{func_defaults}
Jeremy Hylton26c49b62002-04-01 17:58:39 +0000531 \ttindex{func_closure}
Fred Drake4856d011999-01-12 04:15:20 +0000532 \ttindex{func_code}
Barry Warsaw7a5e80e2001-02-27 03:36:30 +0000533 \ttindex{func_globals}
534 \ttindex{func_dict}}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000535\indexii{global}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000536
537\item[User-defined methods]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000538A user-defined method object combines a class, a class instance (or
Fred Drake8dd6ffd2001-08-02 21:34:53 +0000539\code{None}) and any callable object (normally a user-defined
540function).
Fred Drakef6669171998-05-06 19:52:49 +0000541\obindex{method}
542\obindex{user-defined method}
543\indexii{user-defined}{method}
Fred Drakef6669171998-05-06 19:52:49 +0000544
545Special read-only attributes: \member{im_self} is the class instance
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000546object, \member{im_func} is the function object;
Raymond Hettinger03ec6d52003-06-25 18:29:36 +0000547\member{im_class} is the class of \member{im_self} for bound methods
548or the class that asked for the method for unbound methods;
Fred Drake82385871998-10-01 20:40:43 +0000549\member{__doc__} is the method's documentation (same as
550\code{im_func.__doc__}); \member{__name__} is the method name (same as
Jeremy Hyltonf9b0cc72003-01-31 18:52:45 +0000551\code{im_func.__name__}); \member{__module__} is the name of the
552module the method was defined in, or \code{None} if unavailable.
Fred Drakef9d58032001-12-07 23:13:53 +0000553\versionchanged[\member{im_self} used to refer to the class that
554 defined the method]{2.2}
Fred Drake4856d011999-01-12 04:15:20 +0000555\withsubitem{(method attribute)}{
Jeremy Hyltonf9b0cc72003-01-31 18:52:45 +0000556 \ttindex{__doc__}
557 \ttindex{__name__}
558 \ttindex{__module__}
Fred Drake4856d011999-01-12 04:15:20 +0000559 \ttindex{im_func}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000560 \ttindex{im_self}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000561
Barry Warsaw7a5e80e2001-02-27 03:36:30 +0000562Methods also support accessing (but not setting) the arbitrary
563function attributes on the underlying function object.
564
Fred Drakeea690c42003-07-17 05:26:53 +0000565User-defined method objects may be created when getting an attribute
566of a class (perhaps via an instance of that class), if that attribute
567is a user-defined function object, an unbound user-defined method object,
568or a class method object.
569When the attribute is a user-defined method object, a new
570method object is only created if the class from which it is being
571retrieved is the same as, or a derived class of, the class stored
572in the original method object; otherwise, the original method object
573is used as it is.
574
575When a user-defined method object is created by retrieving
576a user-defined function object from a class, its \member{im_self}
577attribute is \code{None} and the method object is said to be unbound.
578When one is created by retrieving a user-defined function object
579from a class via one of its instances, its \member{im_self} attribute
580is the instance, and the method object is said to be bound.
581In either case, the new method's \member{im_class} attribute
582is the class from which the retrieval takes place, and
583its \member{im_func} attribute is the original function object.
584\withsubitem{(method attribute)}{
585 \ttindex{im_class}\ttindex{im_func}\ttindex{im_self}}
586
587When a user-defined method object is created by retrieving another
588method object from a class or instance, the behaviour is the same
589as for a function object, except that the \member{im_func} attribute
590of the new instance is not the original method object but its
591\member{im_func} attribute.
592\withsubitem{(method attribute)}{
593 \ttindex{im_func}}
594
595When a user-defined method object is created by retrieving a
596class method object from a class or instance, its \member{im_self}
597attribute is the class itself (the same as the \member{im_class}
598attribute), and its \member{im_func} attribute is the function
599object underlying the class method.
Fred Drake4856d011999-01-12 04:15:20 +0000600\withsubitem{(method attribute)}{
Fred Drake35c09f22000-06-28 20:15:47 +0000601 \ttindex{im_class}\ttindex{im_func}\ttindex{im_self}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000602
603When an unbound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000604function (\member{im_func}) is called, with the restriction that the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000605first argument must be an instance of the proper class
Fred Drake82385871998-10-01 20:40:43 +0000606(\member{im_class}) or of a derived class thereof.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000607
608When a bound user-defined method object is called, the underlying
Fred Drake82385871998-10-01 20:40:43 +0000609function (\member{im_func}) is called, inserting the class instance
610(\member{im_self}) in front of the argument list. For instance, when
611\class{C} is a class which contains a definition for a function
612\method{f()}, and \code{x} is an instance of \class{C}, calling
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000613\code{x.f(1)} is equivalent to calling \code{C.f(x, 1)}.
614
Fred Drakeea690c42003-07-17 05:26:53 +0000615When a user-defined method object is derived from a class method object,
616the ``class instance'' stored in \member{im_self} will actually be the
617class itself, so that calling either \code{x.f(1)} or \code{C.f(1)} is
618equivalent to calling \code{f(C,1)} where \code{f} is the underlying
619function.
620
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000621Note that the transformation from function object to (unbound or
622bound) method object happens each time the attribute is retrieved from
623the class or instance. In some cases, a fruitful optimization is to
624assign the attribute to a local variable and call that local variable.
625Also notice that this transformation only happens for user-defined
626functions; other callable objects (and all non-callable objects) are
Fred Drake35c09f22000-06-28 20:15:47 +0000627retrieved without transformation. It is also important to note that
628user-defined functions which are attributes of a class instance are
629not converted to bound methods; this \emph{only} happens when the
630function is an attribute of the class.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000631
Fred Drakee31e9ce2001-12-11 21:10:08 +0000632\item[Generator functions\index{generator!function}\index{generator!iterator}]
633A function or method which uses the \keyword{yield} statement (see
634section~\ref{yield}, ``The \keyword{yield} statement'') is called a
635\dfn{generator function}. Such a function, when called, always
636returns an iterator object which can be used to execute the body of
637the function: calling the iterator's \method{next()} method will
638cause the function to execute until it provides a value using the
639\keyword{yield} statement. When the function executes a
640\keyword{return} statement or falls off the end, a
641\exception{StopIteration} exception is raised and the iterator will
642have reached the end of the set of values to be returned.
643
Fred Drakef6669171998-05-06 19:52:49 +0000644\item[Built-in functions]
Georg Brandl1c330eb2005-07-02 10:27:31 +0000645A built-in function object is a wrapper around a C function. Examples
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000646of built-in functions are \function{len()} and \function{math.sin()}
647(\module{math} is a standard built-in module).
648The number and type of the arguments are
Fred Drakef6669171998-05-06 19:52:49 +0000649determined by the C function.
Fred Drake82385871998-10-01 20:40:43 +0000650Special read-only attributes: \member{__doc__} is the function's
651documentation string, or \code{None} if unavailable; \member{__name__}
652is the function's name; \member{__self__} is set to \code{None} (but see
Jeremy Hyltonf9b0cc72003-01-31 18:52:45 +0000653the next item); \member{__module__} is the name of the module the
654function was defined in or \code{None} if unavailable.
Fred Drakef6669171998-05-06 19:52:49 +0000655\obindex{built-in function}
656\obindex{function}
657\indexii{C}{language}
658
659\item[Built-in methods]
660This is really a different disguise of a built-in function, this time
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000661containing an object passed to the C function as an implicit extra
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000662argument. An example of a built-in method is
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000663\code{\var{alist}.append()}, assuming
664\var{alist} is a list object.
Fred Drake82385871998-10-01 20:40:43 +0000665In this case, the special read-only attribute \member{__self__} is set
Fred Drakee31e9ce2001-12-11 21:10:08 +0000666to the object denoted by \var{list}.
Fred Drakef6669171998-05-06 19:52:49 +0000667\obindex{built-in method}
668\obindex{method}
669\indexii{built-in}{method}
670
Fred Drakee37b4ed2003-07-15 20:45:16 +0000671\item[Class Types]
672Class types, or ``new-style classes,'' are callable. These objects
673normally act as factories for new instances of themselves, but
674variations are possible for class types that override
675\method{__new__()}. The arguments of the call are passed to
676\method{__new__()} and, in the typical case, to \method{__init__()} to
677initialize the new instance.
678
679\item[Classic Classes]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000680Class objects are described below. When a class object is called,
681a new class instance (also described below) is created and
Fred Drakef6669171998-05-06 19:52:49 +0000682returned. This implies a call to the class's \method{__init__()} method
683if it has one. Any arguments are passed on to the \method{__init__()}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000684method. If there is no \method{__init__()} method, the class must be called
Fred Drakef6669171998-05-06 19:52:49 +0000685without arguments.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000686\withsubitem{(object method)}{\ttindex{__init__()}}
Fred Drakef6669171998-05-06 19:52:49 +0000687\obindex{class}
688\obindex{class instance}
689\obindex{instance}
690\indexii{class object}{call}
691
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000692\item[Class instances]
693Class instances are described below. Class instances are callable
Fred Drake82385871998-10-01 20:40:43 +0000694only when the class has a \method{__call__()} method; \code{x(arguments)}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000695is a shorthand for \code{x.__call__(arguments)}.
696
Fred Drakef6669171998-05-06 19:52:49 +0000697\end{description}
698
699\item[Modules]
Fred Drake62364ff2003-03-20 18:17:16 +0000700Modules are imported by the \keyword{import} statement (see
Fred Draked51ce7d2003-07-15 22:03:00 +0000701section~\ref{import}, ``The \keyword{import} statement'').%
702\stindex{import}\obindex{module}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000703A module object has a namespace implemented by a dictionary object
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000704(this is the dictionary referenced by the func_globals attribute of
705functions defined in the module). Attribute references are translated
706to lookups in this dictionary, e.g., \code{m.x} is equivalent to
707\code{m.__dict__["x"]}.
708A module object does not contain the code object used to
Fred Drakef6669171998-05-06 19:52:49 +0000709initialize the module (since it isn't needed once the initialization
710is done).
Fred Drakef6669171998-05-06 19:52:49 +0000711
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000712Attribute assignment updates the module's namespace dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000713e.g., \samp{m.x = 1} is equivalent to \samp{m.__dict__["x"] = 1}.
Fred Drakef6669171998-05-06 19:52:49 +0000714
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000715Special read-only attribute: \member{__dict__} is the module's
716namespace as a dictionary object.
Fred Drake1e42d8a1998-11-25 17:58:50 +0000717\withsubitem{(module attribute)}{\ttindex{__dict__}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000718
719Predefined (writable) attributes: \member{__name__}
720is the module's name; \member{__doc__} is the
721module's documentation string, or
Fred Drake82385871998-10-01 20:40:43 +0000722\code{None} if unavailable; \member{__file__} is the pathname of the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000723file from which the module was loaded, if it was loaded from a file.
Fred Drake82385871998-10-01 20:40:43 +0000724The \member{__file__} attribute is not present for C{} modules that are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000725statically linked into the interpreter; for extension modules loaded
726dynamically from a shared library, it is the pathname of the shared
727library file.
Fred Drake4856d011999-01-12 04:15:20 +0000728\withsubitem{(module attribute)}{
729 \ttindex{__name__}
730 \ttindex{__doc__}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000731 \ttindex{__file__}}
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000732\indexii{module}{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000733
734\item[Classes]
Fred Drake62364ff2003-03-20 18:17:16 +0000735Class objects are created by class definitions (see
736section~\ref{class}, ``Class definitions'').
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000737A class has a namespace implemented by a dictionary object.
738Class attribute references are translated to
739lookups in this dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000740e.g., \samp{C.x} is translated to \samp{C.__dict__["x"]}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000741When the attribute name is not found
Fred Drakef6669171998-05-06 19:52:49 +0000742there, the attribute search continues in the base classes. The search
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000743is depth-first, left-to-right in the order of occurrence in the
Fred Drakef6669171998-05-06 19:52:49 +0000744base class list.
Fred Drakeea690c42003-07-17 05:26:53 +0000745
746When a class attribute reference (for class \class{C}, say)
747would yield a user-defined function object or
748an unbound user-defined method object whose associated class is either
749\class{C} or one of its base classes, it is transformed into an unbound
750user-defined method object whose \member{im_class} attribute is~\class{C}.
751When it would yield a class method object, it is transformed into
752a bound user-defined method object whose \member{im_class} and
753\member{im_self} attributes are both~\class{C}. When it would yield
754a static method object, it is transformed into the object wrapped
755by the static method object. See section~\ref{descriptors} for another
756way in which attributes retrieved from a class may differ from those
757actually contained in its \member{__dict__}.
Fred Drakef6669171998-05-06 19:52:49 +0000758\obindex{class}
759\obindex{class instance}
760\obindex{instance}
761\indexii{class object}{call}
762\index{container}
763\obindex{dictionary}
764\indexii{class}{attribute}
765
766Class attribute assignments update the class's dictionary, never the
767dictionary of a base class.
768\indexiii{class}{attribute}{assignment}
769
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000770A class object can be called (see above) to yield a class instance (see
771below).
Fred Drakef6669171998-05-06 19:52:49 +0000772\indexii{class object}{call}
773
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000774Special attributes: \member{__name__} is the class name;
775\member{__module__} is the module name in which the class was defined;
Guido van Rossumdfb658c1998-07-23 17:54:36 +0000776\member{__dict__} is the dictionary containing the class's namespace;
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000777\member{__bases__} is a tuple (possibly empty or a singleton)
778containing the base classes, in the order of their occurrence in the
Fred Drake82385871998-10-01 20:40:43 +0000779base class list; \member{__doc__} is the class's documentation string,
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000780or None if undefined.
Fred Drake4856d011999-01-12 04:15:20 +0000781\withsubitem{(class attribute)}{
782 \ttindex{__name__}
783 \ttindex{__module__}
784 \ttindex{__dict__}
785 \ttindex{__bases__}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000786 \ttindex{__doc__}}
Fred Drakef6669171998-05-06 19:52:49 +0000787
788\item[Class instances]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000789A class instance is created by calling a class object (see above).
790A class instance has a namespace implemented as a dictionary which
791is the first place in which
Fred Drakef6669171998-05-06 19:52:49 +0000792attribute references are searched. When an attribute is not found
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000793there, and the instance's class has an attribute by that name,
794the search continues with the class attributes. If a class attribute
Fred Drakeea690c42003-07-17 05:26:53 +0000795is found that is a user-defined function object or an unbound
796user-defined method object whose associated class is the class
797(call it~\class{C}) of the instance for which the attribute reference
798was initiated or one of its bases,
799it is transformed into a bound user-defined method object whose
Neal Norwitzd7df7122006-09-02 02:43:17 +0000800\member{im_class} attribute is~\class{C} and whose \member{im_self} attribute
Fred Drakeea690c42003-07-17 05:26:53 +0000801is the instance. Static method and class method objects are also
802transformed, as if they had been retrieved from class~\class{C};
803see above under ``Classes''. See section~\ref{descriptors} for
804another way in which attributes of a class retrieved via its
805instances may differ from the objects actually stored in the
806class's \member{__dict__}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000807If no class attribute is found, and the object's class has a
Fred Drake82385871998-10-01 20:40:43 +0000808\method{__getattr__()} method, that is called to satisfy the lookup.
Fred Drakef6669171998-05-06 19:52:49 +0000809\obindex{class instance}
810\obindex{instance}
811\indexii{class}{instance}
812\indexii{class instance}{attribute}
813
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000814Attribute assignments and deletions update the instance's dictionary,
Fred Drake82385871998-10-01 20:40:43 +0000815never a class's dictionary. If the class has a \method{__setattr__()} or
816\method{__delattr__()} method, this is called instead of updating the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000817instance dictionary directly.
Fred Drakef6669171998-05-06 19:52:49 +0000818\indexiii{class instance}{attribute}{assignment}
819
820Class instances can pretend to be numbers, sequences, or mappings if
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000821they have methods with certain special names. See
Fred Drake62364ff2003-03-20 18:17:16 +0000822section~\ref{specialnames}, ``Special method names.''
Fred Drakee15956b2000-04-03 04:51:13 +0000823\obindex{numeric}
Fred Drakef6669171998-05-06 19:52:49 +0000824\obindex{sequence}
825\obindex{mapping}
826
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000827Special attributes: \member{__dict__} is the attribute
828dictionary; \member{__class__} is the instance's class.
Fred Drake4856d011999-01-12 04:15:20 +0000829\withsubitem{(instance attribute)}{
830 \ttindex{__dict__}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000831 \ttindex{__class__}}
Fred Drakef6669171998-05-06 19:52:49 +0000832
833\item[Files]
Fred Drakee15eb351999-11-10 16:13:25 +0000834A file\obindex{file} object represents an open file. File objects are
835created by the \function{open()}\bifuncindex{open} built-in function,
836and also by
837\withsubitem{(in module os)}{\ttindex{popen()}}\function{os.popen()},
838\function{os.fdopen()}, and the
839\method{makefile()}\withsubitem{(socket method)}{\ttindex{makefile()}}
840method of socket objects (and perhaps by other functions or methods
841provided by extension modules). The objects
842\ttindex{sys.stdin}\code{sys.stdin},
843\ttindex{sys.stdout}\code{sys.stdout} and
844\ttindex{sys.stderr}\code{sys.stderr} are initialized to file objects
845corresponding to the interpreter's standard\index{stdio} input, output
846and error streams. See the \citetitle[../lib/lib.html]{Python Library
847Reference} for complete documentation of file objects.
Fred Drake4856d011999-01-12 04:15:20 +0000848\withsubitem{(in module sys)}{
849 \ttindex{stdin}
850 \ttindex{stdout}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000851 \ttindex{stderr}}
Fred Drakee15eb351999-11-10 16:13:25 +0000852
Fred Drakef6669171998-05-06 19:52:49 +0000853
854\item[Internal types]
855A few types used internally by the interpreter are exposed to the user.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000856Their definitions may change with future versions of the interpreter,
Fred Drakef6669171998-05-06 19:52:49 +0000857but they are mentioned here for completeness.
858\index{internal type}
859\index{types, internal}
860
861\begin{description}
862
863\item[Code objects]
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000864Code objects represent \emph{byte-compiled} executable Python code, or
865\emph{bytecode}.
Fred Drakef6669171998-05-06 19:52:49 +0000866The difference between a code
867object and a function object is that the function object contains an
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000868explicit reference to the function's globals (the module in which it
869was defined), while a code object contains no context;
870also the default argument values are stored in the function object,
871not in the code object (because they represent values calculated at
872run-time). Unlike function objects, code objects are immutable and
873contain no references (directly or indirectly) to mutable objects.
874\index{bytecode}
Fred Drakef6669171998-05-06 19:52:49 +0000875\obindex{code}
876
Fred Drake1e42d8a1998-11-25 17:58:50 +0000877Special read-only attributes: \member{co_name} gives the function
878name; \member{co_argcount} is the number of positional arguments
879(including arguments with default values); \member{co_nlocals} is the
880number of local variables used by the function (including arguments);
881\member{co_varnames} is a tuple containing the names of the local
Jeremy Hyltonaa90adc2001-03-23 17:23:50 +0000882variables (starting with the argument names); \member{co_cellvars} is
883a tuple containing the names of local variables that are referenced by
884nested functions; \member{co_freevars} is a tuple containing the names
Jeremy Hylton8392f362002-04-01 18:53:36 +0000885of free variables; \member{co_code} is a string representing the
886sequence of bytecode instructions;
Fred Drake1e42d8a1998-11-25 17:58:50 +0000887\member{co_consts} is a tuple containing the literals used by the
888bytecode; \member{co_names} is a tuple containing the names used by
889the bytecode; \member{co_filename} is the filename from which the code
890was compiled; \member{co_firstlineno} is the first line number of the
891function; \member{co_lnotab} is a string encoding the mapping from
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000892byte code offsets to line numbers (for details see the source code of
Fred Drake1e42d8a1998-11-25 17:58:50 +0000893the interpreter); \member{co_stacksize} is the required stack size
894(including local variables); \member{co_flags} is an integer encoding
895a number of flags for the interpreter.
Jeremy Hyltonaa90adc2001-03-23 17:23:50 +0000896
Fred Drake4856d011999-01-12 04:15:20 +0000897\withsubitem{(code object attribute)}{
898 \ttindex{co_argcount}
899 \ttindex{co_code}
900 \ttindex{co_consts}
901 \ttindex{co_filename}
902 \ttindex{co_firstlineno}
903 \ttindex{co_flags}
904 \ttindex{co_lnotab}
905 \ttindex{co_name}
906 \ttindex{co_names}
907 \ttindex{co_nlocals}
908 \ttindex{co_stacksize}
Jeremy Hyltonaa90adc2001-03-23 17:23:50 +0000909 \ttindex{co_varnames}
910 \ttindex{co_cellvars}
911 \ttindex{co_freevars}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000912
Fred Drakee15956b2000-04-03 04:51:13 +0000913The following flag bits are defined for \member{co_flags}: bit
914\code{0x04} is set if the function uses the \samp{*arguments} syntax
915to accept an arbitrary number of positional arguments; bit
916\code{0x08} is set if the function uses the \samp{**keywords} syntax
Jeremy Hylton8392f362002-04-01 18:53:36 +0000917to accept arbitrary keyword arguments; bit \code{0x20} is set if the
Brett Cannon9e6fedd2003-06-15 22:57:44 +0000918function is a generator.
919\obindex{generator}
Jeremy Hylton8392f362002-04-01 18:53:36 +0000920
921Future feature declarations (\samp{from __future__ import division})
922also use bits in \member{co_flags} to indicate whether a code object
923was compiled with a particular feature enabled: bit \code{0x2000} is
924set if the function was compiled with future division enabled; bits
925\code{0x10} and \code{0x1000} were used in earlier versions of Python.
926
927Other bits in \member{co_flags} are reserved for internal use.
928
929If\index{documentation string} a code object represents a function,
930the first item in
Jeremy Hyltonaa90adc2001-03-23 17:23:50 +0000931\member{co_consts} is the documentation string of the function, or
932\code{None} if undefined.
Fred Drakef6669171998-05-06 19:52:49 +0000933
934\item[Frame objects]
935Frame objects represent execution frames. They may occur in traceback
936objects (see below).
937\obindex{frame}
938
939Special read-only attributes: \member{f_back} is to the previous
940stack frame (towards the caller), or \code{None} if this is the bottom
941stack frame; \member{f_code} is the code object being executed in this
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000942frame; \member{f_locals} is the dictionary used to look up local
943variables; \member{f_globals} is used for global variables;
Fred Drake82385871998-10-01 20:40:43 +0000944\member{f_builtins} is used for built-in (intrinsic) names;
945\member{f_restricted} is a flag indicating whether the function is
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000946executing in restricted execution mode; \member{f_lasti} gives the
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000947precise instruction (this is an index into the bytecode string of
Fred Drakef6669171998-05-06 19:52:49 +0000948the code object).
Fred Drake4856d011999-01-12 04:15:20 +0000949\withsubitem{(frame attribute)}{
950 \ttindex{f_back}
951 \ttindex{f_code}
952 \ttindex{f_globals}
953 \ttindex{f_locals}
Fred Drake4856d011999-01-12 04:15:20 +0000954 \ttindex{f_lasti}
955 \ttindex{f_builtins}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000956 \ttindex{f_restricted}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000957
Georg Brandl1c330eb2005-07-02 10:27:31 +0000958Special writable attributes: \member{f_trace}, if not \code{None}, is
959a function called at the start of each source code line (this is used
960by the debugger); \member{f_exc_type}, \member{f_exc_value},
961\member{f_exc_traceback} represent the last exception raised in the
962parent frame provided another exception was ever raised in the current
963frame (in all other cases they are None); \member{f_lineno} is the
964current line number of the frame --- writing to this from within a
965trace function jumps to the given line (only for the bottom-most
966frame). A debugger can implement a Jump command (aka Set Next
967Statement) by writing to f_lineno.
Fred Drake4856d011999-01-12 04:15:20 +0000968\withsubitem{(frame attribute)}{
969 \ttindex{f_trace}
970 \ttindex{f_exc_type}
971 \ttindex{f_exc_value}
Michael W. Hudsoncfd38842002-12-17 16:15:34 +0000972 \ttindex{f_exc_traceback}
973 \ttindex{f_lineno}}
Fred Drakef6669171998-05-06 19:52:49 +0000974
975\item[Traceback objects] \label{traceback}
976Traceback objects represent a stack trace of an exception. A
977traceback object is created when an exception occurs. When the search
978for an exception handler unwinds the execution stack, at each unwound
979level a traceback object is inserted in front of the current
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000980traceback. When an exception handler is entered, the stack trace is
981made available to the program.
Fred Drake62364ff2003-03-20 18:17:16 +0000982(See section~\ref{try}, ``The \code{try} statement.'')
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000983It is accessible as \code{sys.exc_traceback}, and also as the third
984item of the tuple returned by \code{sys.exc_info()}. The latter is
985the preferred interface, since it works correctly when the program is
986using multiple threads.
987When the program contains no suitable handler, the stack trace is written
Fred Drakef6669171998-05-06 19:52:49 +0000988(nicely formatted) to the standard error stream; if the interpreter is
989interactive, it is also made available to the user as
990\code{sys.last_traceback}.
991\obindex{traceback}
992\indexii{stack}{trace}
993\indexii{exception}{handler}
994\indexii{execution}{stack}
Fred Drake4856d011999-01-12 04:15:20 +0000995\withsubitem{(in module sys)}{
996 \ttindex{exc_info}
997 \ttindex{exc_traceback}
Fred Drake1e42d8a1998-11-25 17:58:50 +0000998 \ttindex{last_traceback}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +0000999\ttindex{sys.exc_info}
Fred Drakef6669171998-05-06 19:52:49 +00001000\ttindex{sys.exc_traceback}
1001\ttindex{sys.last_traceback}
1002
1003Special read-only attributes: \member{tb_next} is the next level in the
1004stack trace (towards the frame where the exception occurred), or
1005\code{None} if there is no next level; \member{tb_frame} points to the
1006execution frame of the current level; \member{tb_lineno} gives the line
1007number where the exception occurred; \member{tb_lasti} indicates the
1008precise instruction. The line number and last instruction in the
1009traceback may differ from the line number of its frame object if the
1010exception occurred in a \keyword{try} statement with no matching
1011except clause or with a finally clause.
Fred Drake4856d011999-01-12 04:15:20 +00001012\withsubitem{(traceback attribute)}{
1013 \ttindex{tb_next}
1014 \ttindex{tb_frame}
1015 \ttindex{tb_lineno}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001016 \ttindex{tb_lasti}}
Fred Drakef6669171998-05-06 19:52:49 +00001017\stindex{try}
1018
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001019\item[Slice objects]
1020Slice objects are used to represent slices when \emph{extended slice
1021syntax} is used. This is a slice using two colons, or multiple slices
1022or ellipses separated by commas, e.g., \code{a[i:j:step]}, \code{a[i:j,
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001023k:l]}, or \code{a[..., i:j]}. They are also created by the built-in
Fred Drake1e42d8a1998-11-25 17:58:50 +00001024\function{slice()}\bifuncindex{slice} function.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001025
Thomas Woutersf9b526d2000-07-16 19:05:38 +00001026Special read-only attributes: \member{start} is the lower bound;
1027\member{stop} is the upper bound; \member{step} is the step value; each is
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001028\code{None} if omitted. These attributes can have any type.
Fred Drake4856d011999-01-12 04:15:20 +00001029\withsubitem{(slice object attribute)}{
1030 \ttindex{start}
1031 \ttindex{stop}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001032 \ttindex{step}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001033
Fred Drake5ec22f22002-09-24 21:09:13 +00001034Slice objects support one method:
1035
1036\begin{methoddesc}[slice]{indices}{self, length}
1037This method takes a single integer argument \var{length} and computes
1038information about the extended slice that the slice object would
1039describe if applied to a sequence of \var{length} items. It returns a
1040tuple of three integers; respectively these are the \var{start} and
1041\var{stop} indices and the \var{step} or stride length of the slice.
1042Missing or out-of-bounds indices are handled in a manner consistent
1043with regular slices.
Michael W. Hudsonf0d777c2002-07-19 15:47:06 +00001044\versionadded{2.3}
Fred Drake5ec22f22002-09-24 21:09:13 +00001045\end{methoddesc}
Michael W. Hudsonf0d777c2002-07-19 15:47:06 +00001046
Fred Drakeea690c42003-07-17 05:26:53 +00001047\item[Static method objects]
1048Static method objects provide a way of defeating the transformation
1049of function objects to method objects described above. A static method
1050object is a wrapper around any other object, usually a user-defined
1051method object. When a static method object is retrieved from a class
1052or a class instance, the object actually returned is the wrapped object,
1053which is not subject to any further transformation. Static method
1054objects are not themselves callable, although the objects they
1055wrap usually are. Static method objects are created by the built-in
1056\function{staticmethod()} constructor.
1057
1058\item[Class method objects]
1059A class method object, like a static method object, is a wrapper
1060around another object that alters the way in which that object
1061is retrieved from classes and class instances. The behaviour of
1062class method objects upon such retrieval is described above,
1063under ``User-defined methods''. Class method objects are created
1064by the built-in \function{classmethod()} constructor.
1065
Fred Drakef6669171998-05-06 19:52:49 +00001066\end{description} % Internal types
1067
1068\end{description} % Types
1069
Andrew M. Kuchling6af52392005-12-04 16:07:15 +00001070%=========================================================================
1071\section{New-style and classic classes}
Fred Drakef6669171998-05-06 19:52:49 +00001072
Georg Brandl76a2cae2006-03-31 16:12:34 +00001073Classes and instances come in two flavors: old-style or classic, and new-style.
Andrew M. Kuchling6af52392005-12-04 16:07:15 +00001074
Armin Rigoddddd2f2005-12-26 18:06:17 +00001075Up to Python 2.1, old-style classes were the only flavour available to the
1076user. The concept of (old-style) class is unrelated to the concept of type: if
1077\var{x} is an instance of an old-style class, then \code{x.__class__}
1078designates the class of \var{x}, but \code{type(x)} is always \code{<type
1079'instance'>}. This reflects the fact that all old-style instances,
1080independently of their class, are implemented with a single built-in type,
1081called \code{instance}.
Andrew M. Kuchling6af52392005-12-04 16:07:15 +00001082
Armin Rigoddddd2f2005-12-26 18:06:17 +00001083New-style classes were introduced in Python 2.2 to unify classes and types. A
1084new-style class neither more nor less than a user-defined type. If \var{x} is
1085an instance of a new-style class, then \code{type(x)} is the same as
1086\code{x.__class__}.
1087
1088The major motivation for introducing new-style classes is to provide a unified
1089object model with a full meta-model. It also has a number of immediate
1090benefits, like the ability to subclass most built-in types, or the introduction
1091of "descriptors", which enable computed properties.
1092
1093For compatibility reasons, classes are still old-style by default. New-style
1094classes are created by specifying another new-style class (i.e.\ a type) as a
1095parent class, or the "top-level type" \class{object} if no other parent is
1096needed. The behaviour of new-style classes differs from that of old-style
1097classes in a number of important details in addition to what \function{type}
1098returns. Some of these changes are fundamental to the new object model, like
1099the way special methods are invoked. Others are "fixes" that could not be
1100implemented before for compatibility concerns, like the method resolution order
1101in case of multiple inheritance.
1102
Georg Brandl76a2cae2006-03-31 16:12:34 +00001103This manual is not up-to-date with respect to new-style classes. For now,
Armin Rigoddddd2f2005-12-26 18:06:17 +00001104please see \url{http://www.python.org/doc/newstyle.html} for more information.
Andrew M. Kuchling6af52392005-12-04 16:07:15 +00001105
Georg Brandl4c974982006-03-31 15:12:16 +00001106The plan is to eventually drop old-style classes, leaving only the semantics of
1107new-style classes. This change will probably only be feasible in Python 3.0.
1108\index{class}{new-style}
1109\index{class}{classic}
1110\index{class}{old-style}
Andrew M. Kuchling6af52392005-12-04 16:07:15 +00001111
Andrew M. Kuchling6af52392005-12-04 16:07:15 +00001112%=========================================================================
Fred Drake61c77281998-07-28 19:34:22 +00001113\section{Special method names\label{specialnames}}
Fred Drakef6669171998-05-06 19:52:49 +00001114
1115A class can implement certain operations that are invoked by special
Fred Draked82575d1998-08-28 20:03:12 +00001116syntax (such as arithmetic operations or subscripting and slicing) by
Fred Drake7af9f4d2003-05-12 13:50:11 +00001117defining methods with special names.\indexii{operator}{overloading}
1118This is Python's approach to \dfn{operator overloading}, allowing
1119classes to define their own behavior with respect to language
1120operators. For instance, if a class defines
Fred Draked82575d1998-08-28 20:03:12 +00001121a method named \method{__getitem__()}, and \code{x} is an instance of
Armin Rigoddddd2f2005-12-26 18:06:17 +00001122this class, then \code{x[i]} is equivalent\footnote{This, and other
1123statements, are only roughly true for instances of new-style
1124classes.} to
Raymond Hettinger94153092002-05-12 03:09:25 +00001125\code{x.__getitem__(i)}. Except where mentioned, attempts to execute
1126an operation raise an exception when no appropriate method is defined.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001127\withsubitem{(mapping object method)}{\ttindex{__getitem__()}}
Fred Drakef6669171998-05-06 19:52:49 +00001128
Fred Drake0c475592000-12-07 04:49:34 +00001129When implementing a class that emulates any built-in type, it is
1130important that the emulation only be implemented to the degree that it
1131makes sense for the object being modelled. For example, some
1132sequences may work well with retrieval of individual elements, but
1133extracting a slice may not make sense. (One example of this is the
1134\class{NodeList} interface in the W3C's Document Object Model.)
1135
Fred Drakef6669171998-05-06 19:52:49 +00001136
Fred Drake61c77281998-07-28 19:34:22 +00001137\subsection{Basic customization\label{customization}}
Fred Drakef6669171998-05-06 19:52:49 +00001138
Greg Wardff564d32005-03-08 01:10:20 +00001139\begin{methoddesc}[object]{__new__}{cls\optional{, \moreargs}}
1140Called to create a new instance of class \var{cls}. \method{__new__()}
Georg Brandl15ad9352005-08-26 12:56:22 +00001141is a static method (special-cased so you need not declare it as such)
Greg Wardff564d32005-03-08 01:10:20 +00001142that takes the class of which an instance was requested as its first
1143argument. The remaining arguments are those passed to the object
1144constructor expression (the call to the class). The return value of
1145\method{__new__()} should be the new object instance (usually an
1146instance of \var{cls}).
1147
1148Typical implementations create a new instance of the class by invoking
1149the superclass's \method{__new__()} method using
1150\samp{super(\var{currentclass}, \var{cls}).__new__(\var{cls}[, ...])}
1151with appropriate arguments and then modifying the newly-created instance
1152as necessary before returning it.
1153
1154If \method{__new__()} returns an instance of \var{cls}, then the new
1155instance's \method{__init__()} method will be invoked like
1156\samp{__init__(\var{self}[, ...])}, where \var{self} is the new instance
1157and the remaining arguments are the same as were passed to
1158\method{__new__()}.
1159
1160If \method{__new__()} does not return an instance of \var{cls}, then the
1161new instance's \method{__init__()} method will not be invoked.
1162
1163\method{__new__()} is intended mainly to allow subclasses of
1164immutable types (like int, str, or tuple) to customize instance
1165creation.
1166\end{methoddesc}
1167
Fred Drake044bb4d2001-08-02 15:53:05 +00001168\begin{methoddesc}[object]{__init__}{self\optional{, \moreargs}}
1169Called\indexii{class}{constructor} when the instance is created. The
1170arguments are those passed to the class constructor expression. If a
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001171base class has an \method{__init__()} method, the derived class's
1172\method{__init__()} method, if any, must explicitly call it to ensure proper
Fred Drake044bb4d2001-08-02 15:53:05 +00001173initialization of the base class part of the instance; for example:
1174\samp{BaseClass.__init__(\var{self}, [\var{args}...])}. As a special
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001175constraint on constructors, no value may be returned; doing so will
Fred Drake044bb4d2001-08-02 15:53:05 +00001176cause a \exception{TypeError} to be raised at runtime.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001177\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001178
1179
Fred Drake1e42d8a1998-11-25 17:58:50 +00001180\begin{methoddesc}[object]{__del__}{self}
Guido van Rossum7c0240f1998-07-24 15:36:43 +00001181Called when the instance is about to be destroyed. This is also
1182called a destructor\index{destructor}. If a base class
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001183has a \method{__del__()} method, the derived class's \method{__del__()}
1184method, if any,
Fred Drakef6669171998-05-06 19:52:49 +00001185must explicitly call it to ensure proper deletion of the base class
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001186part of the instance. Note that it is possible (though not recommended!)
1187for the \method{__del__()}
Fred Drakef6669171998-05-06 19:52:49 +00001188method to postpone destruction of the instance by creating a new
1189reference to it. It may then be called at a later time when this new
1190reference is deleted. It is not guaranteed that
1191\method{__del__()} methods are called for objects that still exist when
1192the interpreter exits.
Fred Drakef6669171998-05-06 19:52:49 +00001193\stindex{del}
1194
Fred Drake591dd8f2001-12-14 22:52:41 +00001195\begin{notice}
1196\samp{del x} doesn't directly call
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001197\code{x.__del__()} --- the former decrements the reference count for
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001198\code{x} by one, and the latter is only called when \code{x}'s reference
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001199count reaches zero. Some common situations that may prevent the
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001200reference count of an object from going to zero include: circular
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001201references between objects (e.g., a doubly-linked list or a tree data
1202structure with parent and child pointers); a reference to the object
1203on the stack frame of a function that caught an exception (the
1204traceback stored in \code{sys.exc_traceback} keeps the stack frame
1205alive); or a reference to the object on the stack frame that raised an
1206unhandled exception in interactive mode (the traceback stored in
1207\code{sys.last_traceback} keeps the stack frame alive). The first
1208situation can only be remedied by explicitly breaking the cycles; the
Fred Drake591dd8f2001-12-14 22:52:41 +00001209latter two situations can be resolved by storing \code{None} in
1210\code{sys.exc_traceback} or \code{sys.last_traceback}. Circular
1211references which are garbage are detected when the option cycle
1212detector is enabled (it's on by default), but can only be cleaned up
1213if there are no Python-level \method{__del__()} methods involved.
1214Refer to the documentation for the \ulink{\module{gc}
1215module}{../lib/module-gc.html} for more information about how
1216\method{__del__()} methods are handled by the cycle detector,
1217particularly the description of the \code{garbage} value.
1218\end{notice}
Fred Drakef6669171998-05-06 19:52:49 +00001219
Fred Drake591dd8f2001-12-14 22:52:41 +00001220\begin{notice}[warning]
1221Due to the precarious circumstances under which
Fred Draked82575d1998-08-28 20:03:12 +00001222\method{__del__()} methods are invoked, exceptions that occur during their
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001223execution are ignored, and a warning is printed to \code{sys.stderr}
Fred Drake591dd8f2001-12-14 22:52:41 +00001224instead. Also, when \method{__del__()} is invoked in response to a module
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001225being deleted (e.g., when execution of the program is done), other
Fred Draked82575d1998-08-28 20:03:12 +00001226globals referenced by the \method{__del__()} method may already have been
1227deleted. For this reason, \method{__del__()} methods should do the
Raymond Hettingera0e4d6c2002-09-08 21:10:54 +00001228absolute minimum needed to maintain external invariants. Starting with
1229version 1.5, Python guarantees that globals whose name begins with a single
1230underscore are deleted from their module before other globals are deleted;
1231if no other references to such globals exist, this may help in assuring that
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001232imported modules are still available at the time when the
Fred Drake591dd8f2001-12-14 22:52:41 +00001233\method{__del__()} method is called.
1234\end{notice}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001235\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001236
Fred Drake1e42d8a1998-11-25 17:58:50 +00001237\begin{methoddesc}[object]{__repr__}{self}
Fred Drake82385871998-10-01 20:40:43 +00001238Called by the \function{repr()}\bifuncindex{repr} built-in function
1239and by string conversions (reverse quotes) to compute the ``official''
Andrew M. Kuchling68abe832000-12-19 14:09:21 +00001240string representation of an object. If at all possible, this should
Guido van Rossum035f7e82000-12-19 04:18:13 +00001241look like a valid Python expression that could be used to recreate an
1242object with the same value (given an appropriate environment). If
1243this is not possible, a string of the form \samp{<\var{...some useful
1244description...}>} should be returned. The return value must be a
1245string object.
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001246If a class defines \method{__repr__()} but not \method{__str__()},
1247then \method{__repr__()} is also used when an ``informal'' string
1248representation of instances of that class is required.
Guido van Rossum035f7e82000-12-19 04:18:13 +00001249
1250This is typically used for debugging, so it is important that the
1251representation is information-rich and unambiguous.
Fred Drakef6669171998-05-06 19:52:49 +00001252\indexii{string}{conversion}
1253\indexii{reverse}{quotes}
1254\indexii{backward}{quotes}
1255\index{back-quotes}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001256\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001257
Fred Drake1e42d8a1998-11-25 17:58:50 +00001258\begin{methoddesc}[object]{__str__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001259Called by the \function{str()}\bifuncindex{str} built-in function and
1260by the \keyword{print}\stindex{print} statement to compute the
Fred Drake82385871998-10-01 20:40:43 +00001261``informal'' string representation of an object. This differs from
1262\method{__repr__()} in that it does not have to be a valid Python
1263expression: a more convenient or concise representation may be used
Guido van Rossum035f7e82000-12-19 04:18:13 +00001264instead. The return value must be a string object.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001265\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001266
Guido van Rossumab782dd2001-01-18 15:17:06 +00001267\begin{methoddesc}[object]{__lt__}{self, other}
1268\methodline[object]{__le__}{self, other}
1269\methodline[object]{__eq__}{self, other}
1270\methodline[object]{__ne__}{self, other}
1271\methodline[object]{__gt__}{self, other}
1272\methodline[object]{__ge__}{self, other}
1273\versionadded{2.1}
1274These are the so-called ``rich comparison'' methods, and are called
1275for comparison operators in preference to \method{__cmp__()} below.
1276The correspondence between operator symbols and method names is as
1277follows:
1278\code{\var{x}<\var{y}} calls \code{\var{x}.__lt__(\var{y})},
1279\code{\var{x}<=\var{y}} calls \code{\var{x}.__le__(\var{y})},
1280\code{\var{x}==\var{y}} calls \code{\var{x}.__eq__(\var{y})},
1281\code{\var{x}!=\var{y}} and \code{\var{x}<>\var{y}} call
1282\code{\var{x}.__ne__(\var{y})},
1283\code{\var{x}>\var{y}} calls \code{\var{x}.__gt__(\var{y})}, and
1284\code{\var{x}>=\var{y}} calls \code{\var{x}.__ge__(\var{y})}.
1285These methods can return any value, but if the comparison operator is
1286used in a Boolean context, the return value should be interpretable as
1287a Boolean value, else a \exception{TypeError} will be raised.
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001288By convention, \code{False} is used for false and \code{True} for true.
Guido van Rossumab782dd2001-01-18 15:17:06 +00001289
Raymond Hettinger4d6e8fe2003-07-16 19:40:23 +00001290There are no implied relationships among the comparison operators.
Raymond Hettinger943277e2003-07-17 14:47:12 +00001291The truth of \code{\var{x}==\var{y}} does not imply that \code{\var{x}!=\var{y}}
Fred Drakeb3dfc0a2005-09-07 04:57:56 +00001292is false. Accordingly, when defining \method{__eq__()}, one should also
1293define \method{__ne__()} so that the operators will behave as expected.
Raymond Hettinger4d6e8fe2003-07-16 19:40:23 +00001294
Guido van Rossumab782dd2001-01-18 15:17:06 +00001295There are no reflected (swapped-argument) versions of these methods
1296(to be used when the left argument does not support the operation but
1297the right argument does); rather, \method{__lt__()} and
1298\method{__gt__()} are each other's reflection, \method{__le__()} and
1299\method{__ge__()} are each other's reflection, and \method{__eq__()}
1300and \method{__ne__()} are their own reflection.
1301
1302Arguments to rich comparison methods are never coerced. A rich
1303comparison method may return \code{NotImplemented} if it does not
1304implement the operation for a given pair of arguments.
1305\end{methoddesc}
1306
Fred Drake1e42d8a1998-11-25 17:58:50 +00001307\begin{methoddesc}[object]{__cmp__}{self, other}
Guido van Rossumab782dd2001-01-18 15:17:06 +00001308Called by comparison operations if rich comparison (see above) is not
Fred Drake597bc1d2001-05-29 16:02:35 +00001309defined. Should return a negative integer if \code{self < other},
1310zero if \code{self == other}, a positive integer if \code{self >
1311other}. If no \method{__cmp__()}, \method{__eq__()} or
1312\method{__ne__()} operation is defined, class instances are compared
1313by object identity (``address''). See also the description of
1314\method{__hash__()} for some important notes on creating objects which
1315support custom comparison operations and are usable as dictionary
1316keys.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001317(Note: the restriction that exceptions are not propagated by
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001318\method{__cmp__()} has been removed since Python 1.5.)
Fred Drakef6669171998-05-06 19:52:49 +00001319\bifuncindex{cmp}
1320\index{comparisons}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001321\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001322
Fred Drakee57a1142000-06-15 20:07:25 +00001323\begin{methoddesc}[object]{__rcmp__}{self, other}
Fred Drake445f8322001-01-04 15:11:48 +00001324 \versionchanged[No longer supported]{2.1}
Fred Drakee57a1142000-06-15 20:07:25 +00001325\end{methoddesc}
1326
Fred Drake1e42d8a1998-11-25 17:58:50 +00001327\begin{methoddesc}[object]{__hash__}{self}
Brett Cannona031a082004-06-29 04:14:02 +00001328Called for the key object for dictionary \obindex{dictionary}
Fred Draked82575d1998-08-28 20:03:12 +00001329operations, and by the built-in function
Fred Drakef6669171998-05-06 19:52:49 +00001330\function{hash()}\bifuncindex{hash}. Should return a 32-bit integer
1331usable as a hash value
1332for dictionary operations. The only required property is that objects
1333which compare equal have the same hash value; it is advised to somehow
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001334mix together (e.g., using exclusive or) the hash values for the
Fred Drakef6669171998-05-06 19:52:49 +00001335components of the object that also play a part in comparison of
1336objects. If a class does not define a \method{__cmp__()} method it should
1337not define a \method{__hash__()} operation either; if it defines
Fred Drake597bc1d2001-05-29 16:02:35 +00001338\method{__cmp__()} or \method{__eq__()} but not \method{__hash__()},
1339its instances will not be usable as dictionary keys. If a class
1340defines mutable objects and implements a \method{__cmp__()} or
1341\method{__eq__()} method, it should not implement \method{__hash__()},
1342since the dictionary implementation requires that a key's hash value
1343is immutable (if the object's hash value changes, it will be in the
1344wrong hash bucket).
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00001345
1346\versionchanged[\method{__hash__()} may now also return a long
1347integer object; the 32-bit integer is then derived from the hash
1348of that object]{2.5}
1349
Fred Drake1e42d8a1998-11-25 17:58:50 +00001350\withsubitem{(object method)}{\ttindex{__cmp__()}}
1351\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001352
Fred Drake1e42d8a1998-11-25 17:58:50 +00001353\begin{methoddesc}[object]{__nonzero__}{self}
Guido van Rossum77f6a652002-04-03 22:41:51 +00001354Called to implement truth value testing, and the built-in operation
1355\code{bool()}; should return \code{False} or \code{True}, or their
1356integer equivalents \code{0} or \code{1}.
1357When this method is not defined, \method{__len__()} is
Fred Draked82575d1998-08-28 20:03:12 +00001358called, if it is defined (see below). If a class defines neither
1359\method{__len__()} nor \method{__nonzero__()}, all its instances are
1360considered true.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001361\withsubitem{(mapping object method)}{\ttindex{__len__()}}
1362\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001363
Martin v. Löwis2a519f82002-04-11 12:39:35 +00001364\begin{methoddesc}[object]{__unicode__}{self}
1365Called to implement \function{unicode()}\bifuncindex{unicode} builtin;
1366should return a Unicode object. When this method is not defined, string
1367conversion is attempted, and the result of string conversion is converted
1368to Unicode using the system default encoding.
1369\end{methoddesc}
1370
Fred Drakef6669171998-05-06 19:52:49 +00001371
Fred Drake61c77281998-07-28 19:34:22 +00001372\subsection{Customizing attribute access\label{attribute-access}}
Fred Drakef6669171998-05-06 19:52:49 +00001373
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001374The following methods can be defined to customize the meaning of
1375attribute access (use of, assignment to, or deletion of \code{x.name})
1376for class instances.
Fred Drakef6669171998-05-06 19:52:49 +00001377
Fred Drake1e42d8a1998-11-25 17:58:50 +00001378\begin{methoddesc}[object]{__getattr__}{self, name}
Fred Drakef6669171998-05-06 19:52:49 +00001379Called when an attribute lookup has not found the attribute in the
1380usual places (i.e. it is not an instance attribute nor is it found in
1381the class tree for \code{self}). \code{name} is the attribute name.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001382This method should return the (computed) attribute value or raise an
Fred Draked82575d1998-08-28 20:03:12 +00001383\exception{AttributeError} exception.
Fred Drakef6669171998-05-06 19:52:49 +00001384
1385Note that if the attribute is found through the normal mechanism,
Fred Draked82575d1998-08-28 20:03:12 +00001386\method{__getattr__()} is not called. (This is an intentional
1387asymmetry between \method{__getattr__()} and \method{__setattr__()}.)
Fred Drakef6669171998-05-06 19:52:49 +00001388This is done both for efficiency reasons and because otherwise
Fred Draked82575d1998-08-28 20:03:12 +00001389\method{__setattr__()} would have no way to access other attributes of
Guido van Rossumd41eea02003-02-28 14:11:45 +00001390the instance. Note that at least for instance variables, you can fake
1391total control by not inserting any values in the instance attribute
1392dictionary (but instead inserting them in another object). See the
1393\method{__getattribute__()} method below for a way to actually get
1394total control in new-style classes.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001395\withsubitem{(object method)}{\ttindex{__setattr__()}}
1396\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001397
Fred Drake1e42d8a1998-11-25 17:58:50 +00001398\begin{methoddesc}[object]{__setattr__}{self, name, value}
Fred Drakef6669171998-05-06 19:52:49 +00001399Called when an attribute assignment is attempted. This is called
Fred Draked82575d1998-08-28 20:03:12 +00001400instead of the normal mechanism (i.e.\ store the value in the instance
1401dictionary). \var{name} is the attribute name, \var{value} is the
Fred Drakef6669171998-05-06 19:52:49 +00001402value to be assigned to it.
Fred Drakef6669171998-05-06 19:52:49 +00001403
Fred Draked82575d1998-08-28 20:03:12 +00001404If \method{__setattr__()} wants to assign to an instance attribute, it
1405should not simply execute \samp{self.\var{name} = value} --- this
1406would cause a recursive call to itself. Instead, it should insert the
1407value in the dictionary of instance attributes, e.g.,
Guido van Rossumd41eea02003-02-28 14:11:45 +00001408\samp{self.__dict__[\var{name}] = value}. For new-style classes,
1409rather than accessing the instance dictionary, it should call the base
1410class method with the same name, for example,
1411\samp{object.__setattr__(self, name, value)}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001412\withsubitem{(instance attribute)}{\ttindex{__dict__}}
1413\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001414
Fred Drake1e42d8a1998-11-25 17:58:50 +00001415\begin{methoddesc}[object]{__delattr__}{self, name}
Fred Draked82575d1998-08-28 20:03:12 +00001416Like \method{__setattr__()} but for attribute deletion instead of
Fred Drake1e42d8a1998-11-25 17:58:50 +00001417assignment. This should only be implemented if \samp{del
1418obj.\var{name}} is meaningful for the object.
1419\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001420
Michael W. Hudson2ab1d082003-03-05 14:20:58 +00001421\subsubsection{More attribute access for new-style classes \label{new-style-attribute-access}}
Guido van Rossumd41eea02003-02-28 14:11:45 +00001422
1423The following methods only apply to new-style classes.
1424
1425\begin{methoddesc}[object]{__getattribute__}{self, name}
1426Called unconditionally to implement attribute accesses for instances
Fred Drakeb3dfc0a2005-09-07 04:57:56 +00001427of the class. If the class also defines \method{__getattr__()}, the latter
Georg Brandl1c330eb2005-07-02 10:27:31 +00001428will not be called unless \method{__getattribute__()} either calls it
1429explicitly or raises an \exception{AttributeError}.
Guido van Rossumd41eea02003-02-28 14:11:45 +00001430This method should return the (computed) attribute
1431value or raise an \exception{AttributeError} exception.
1432In order to avoid infinite recursion in this method, its
1433implementation should always call the base class method with the same
Fred Drake62364ff2003-03-20 18:17:16 +00001434name to access any attributes it needs, for example,
Guido van Rossumd41eea02003-02-28 14:11:45 +00001435\samp{object.__getattribute__(self, name)}.
1436\end{methoddesc}
1437
Michael W. Hudson2ab1d082003-03-05 14:20:58 +00001438\subsubsection{Implementing Descriptors \label{descriptors}}
Guido van Rossumd41eea02003-02-28 14:11:45 +00001439
1440The following methods only apply when an instance of the class
Fred Drake62364ff2003-03-20 18:17:16 +00001441containing the method (a so-called \emph{descriptor} class) appears in
Guido van Rossumd41eea02003-02-28 14:11:45 +00001442the class dictionary of another new-style class, known as the
1443\emph{owner} class. In the examples below, ``the attribute'' refers to
Fred Drake62364ff2003-03-20 18:17:16 +00001444the attribute whose name is the key of the property in the owner
Fred Drake67a521e2004-05-06 12:44:29 +00001445class' \code{__dict__}. Descriptors can only be implemented as
1446new-style classes themselves.
Guido van Rossumd41eea02003-02-28 14:11:45 +00001447
1448\begin{methoddesc}[object]{__get__}{self, instance, owner}
Fred Drake62364ff2003-03-20 18:17:16 +00001449Called to get the attribute of the owner class (class attribute access)
Raymond Hettinger68804312005-01-01 00:28:46 +00001450or of an instance of that class (instance attribute access).
Guido van Rossumd41eea02003-02-28 14:11:45 +00001451\var{owner} is always the owner class, while \var{instance} is the
1452instance that the attribute was accessed through, or \code{None} when
1453the attribute is accessed through the \var{owner}. This method should
1454return the (computed) attribute value or raise an
1455\exception{AttributeError} exception.
1456\end{methoddesc}
1457
1458\begin{methoddesc}[object]{__set__}{self, instance, value}
Michael W. Hudson2ab1d082003-03-05 14:20:58 +00001459Called to set the attribute on an instance \var{instance} of the owner
Guido van Rossumd41eea02003-02-28 14:11:45 +00001460class to a new value, \var{value}.
1461\end{methoddesc}
1462
1463\begin{methoddesc}[object]{__delete__}{self, instance}
Michael W. Hudson2ab1d082003-03-05 14:20:58 +00001464Called to delete the attribute on an instance \var{instance} of the
1465owner class.
Guido van Rossumd41eea02003-02-28 14:11:45 +00001466\end{methoddesc}
1467
Fred Drakef6669171998-05-06 19:52:49 +00001468
Fred Drake4db36612003-06-26 03:11:20 +00001469\subsubsection{Invoking Descriptors \label{descriptor-invocation}}
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001470
1471In general, a descriptor is an object attribute with ``binding behavior'',
1472one whose attribute access has been overridden by methods in the descriptor
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001473protocol: \method{__get__()}, \method{__set__()}, and \method{__delete__()}.
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001474If any of those methods are defined for an object, it is said to be a
1475descriptor.
1476
1477The default behavior for attribute access is to get, set, or delete the
1478attribute from an object's dictionary. For instance, \code{a.x} has a
1479lookup chain starting with \code{a.__dict__['x']}, then
1480\code{type(a).__dict__['x']}, and continuing
1481through the base classes of \code{type(a)} excluding metaclasses.
1482
1483However, if the looked-up value is an object defining one of the descriptor
1484methods, then Python may override the default behavior and invoke the
1485descriptor method instead. Where this occurs in the precedence chain depends
1486on which descriptor methods were defined and how they were called. Note that
1487descriptors are only invoked for new style objects or classes
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001488(ones that subclass \class{object()} or \class{type()}).
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001489
1490The starting point for descriptor invocation is a binding, \code{a.x}.
1491How the arguments are assembled depends on \code{a}:
1492
1493\begin{itemize}
1494
1495 \item[Direct Call] The simplest and least common call is when user code
1496 directly invokes a descriptor method: \code{x.__get__(a)}.
1497
1498 \item[Instance Binding] If binding to a new-style object instance,
1499 \code{a.x} is transformed into the call:
1500 \code{type(a).__dict__['x'].__get__(a, type(a))}.
1501
1502 \item[Class Binding] If binding to a new-style class, \code{A.x}
1503 is transformed into the call: \code{A.__dict__['x'].__get__(None, A)}.
1504
1505 \item[Super Binding] If \code{a} is an instance of \class{super},
1506 then the binding \code{super(B, obj).m()} searches
1507 \code{obj.__class__.__mro__} for the base class \code{A} immediately
1508 preceding \code{B} and then invokes the descriptor with the call:
1509 \code{A.__dict__['m'].__get__(obj, A)}.
1510
1511\end{itemize}
1512
1513For instance bindings, the precedence of descriptor invocation depends
1514on the which descriptor methods are defined. Data descriptors define
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001515both \method{__get__()} and \method{__set__()}. Non-data descriptors have
1516just the \method{__get__()} method. Data descriptors always override
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001517a redefinition in an instance dictionary. In contrast, non-data
1518descriptors can be overridden by instances.
1519
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001520Python methods (including \function{staticmethod()} and \function{classmethod()})
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001521are implemented as non-data descriptors. Accordingly, instances can
1522redefine and override methods. This allows individual instances to acquire
1523behaviors that differ from other instances of the same class.
1524
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001525The \function{property()} function is implemented as a data descriptor.
1526Accordingly, instances cannot override the behavior of a property.
1527
1528
1529\subsubsection{__slots__\label{slots}}
1530
1531By default, instances of both old and new-style classes have a dictionary
1532for attribute storage. This wastes space for objects having very few instance
1533variables. The space consumption can become acute when creating large numbers
1534of instances.
1535
1536The default can be overridden by defining \var{__slots__} in a new-style class
1537definition. The \var{__slots__} declaration takes a sequence of instance
1538variables and reserves just enough space in each instance to hold a value
1539for each variable. Space is saved because \var{__dict__} is not created for
1540each instance.
1541
1542\begin{datadesc}{__slots__}
1543This class variable can be assigned a string, iterable, or sequence of strings
Raymond Hettinger5918f8d2003-06-29 04:53:23 +00001544with variable names used by instances. If defined in a new-style class,
1545\var{__slots__} reserves space for the declared variables
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001546and prevents the automatic creation of \var{__dict__} and \var{__weakref__}
1547for each instance.
1548\versionadded{2.2}
1549\end{datadesc}
1550
1551\noindent
Raymond Hettinger5918f8d2003-06-29 04:53:23 +00001552Notes on using \var{__slots__}
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001553
1554\begin{itemize}
1555
1556\item Without a \var{__dict__} variable, instances cannot be assigned new
1557variables not listed in the \var{__slots__} definition. Attempts to assign
1558to an unlisted variable name raises \exception{AttributeError}. If dynamic
1559assignment of new variables is desired, then add \code{'__dict__'} to the
1560sequence of strings in the \var{__slots__} declaration.
1561\versionchanged[Previously, adding \code{'__dict__'} to the \var{__slots__}
1562declaration would not enable the assignment of new attributes not
1563specifically listed in the sequence of instance variable names]{2.3}
1564
1565\item Without a \var{__weakref__} variable for each instance, classes
1566defining \var{__slots__} do not support weak references to its instances.
1567If weak reference support is needed, then add \code{'__weakref__'} to the
1568sequence of strings in the \var{__slots__} declaration.
Raymond Hettinger5918f8d2003-06-29 04:53:23 +00001569\versionchanged[Previously, adding \code{'__weakref__'} to the \var{__slots__}
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001570declaration would not enable support for weak references]{2.3}
1571
1572\item \var{__slots__} are implemented at the class level by creating
1573descriptors (\ref{descriptors}) for each variable name. As a result,
1574class attributes cannot be used to set default values for instance
1575variables defined by \var{__slots__}; otherwise, the class attribute would
1576overwrite the descriptor assignment.
1577
1578\item If a class defines a slot also defined in a base class, the instance
1579variable defined by the base class slot is inaccessible (except by retrieving
1580its descriptor directly from the base class). This renders the meaning of the
1581program undefined. In the future, a check may be added to prevent this.
1582
1583\item The action of a \var{__slots__} declaration is limited to the class
1584where it is defined. As a result, subclasses will have a \var{__dict__}
1585unless they also define \var{__slots__}.
1586
1587\item \var{__slots__} do not work for classes derived from ``variable-length''
1588built-in types such as \class{long}, \class{str} and \class{tuple}.
1589
Raymond Hettinger5918f8d2003-06-29 04:53:23 +00001590\item Any non-string iterable may be assigned to \var{__slots__}.
Raymond Hettingerdf9eff02003-06-27 06:57:56 +00001591Mappings may also be used; however, in the future, special meaning may
1592be assigned to the values corresponding to each key.
1593
1594\end{itemize}
1595
1596
1597\subsection{Customizing class creation\label{metaclasses}}
1598
1599By default, new-style classes are constructed using \function{type()}.
1600A class definition is read into a separate namespace and the value
1601of class name is bound to the result of \code{type(name, bases, dict)}.
1602
1603When the class definition is read, if \var{__metaclass__} is defined
1604then the callable assigned to it will be called instead of \function{type()}.
1605The allows classes or functions to be written which monitor or alter the class
1606creation process:
1607
1608\begin{itemize}
1609\item Modifying the class dictionary prior to the class being created.
1610\item Returning an instance of another class -- essentially performing
1611the role of a factory function.
1612\end{itemize}
1613
1614\begin{datadesc}{__metaclass__}
1615This variable can be any callable accepting arguments for \code{name},
1616\code{bases}, and \code{dict}. Upon class creation, the callable is
1617used instead of the built-in \function{type()}.
1618\versionadded{2.2}
1619\end{datadesc}
1620
1621The appropriate metaclass is determined by the following precedence rules:
1622
1623\begin{itemize}
1624
1625\item If \code{dict['__metaclass__']} exists, it is used.
1626
1627\item Otherwise, if there is at least one base class, its metaclass is used
1628(this looks for a \var{__class__} attribute first and if not found, uses its
1629type).
1630
1631\item Otherwise, if a global variable named __metaclass__ exists, it is used.
1632
1633\item Otherwise, the old-style, classic metaclass (types.ClassType) is used.
1634
1635\end{itemize}
1636
1637The potential uses for metaclasses are boundless. Some ideas that have
1638been explored including logging, interface checking, automatic delegation,
1639automatic property creation, proxies, frameworks, and automatic resource
1640locking/synchronization.
Raymond Hettinger03ec6d52003-06-25 18:29:36 +00001641
1642
Fred Drake61c77281998-07-28 19:34:22 +00001643\subsection{Emulating callable objects\label{callable-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001644
Fred Drake1e42d8a1998-11-25 17:58:50 +00001645\begin{methoddesc}[object]{__call__}{self\optional{, args...}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001646Called when the instance is ``called'' as a function; if this method
Fred Draked82575d1998-08-28 20:03:12 +00001647is defined, \code{\var{x}(arg1, arg2, ...)} is a shorthand for
1648\code{\var{x}.__call__(arg1, arg2, ...)}.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001649\indexii{call}{instance}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001650\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001651
1652
Fred Drake73921b02001-10-01 16:32:13 +00001653\subsection{Emulating container types\label{sequence-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001654
Fred Drake73921b02001-10-01 16:32:13 +00001655The following methods can be defined to implement container
1656objects. Containers usually are sequences (such as lists or tuples)
1657or mappings (like dictionaries), but can represent other containers as
1658well. The first set of methods is used either to emulate a
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001659sequence or to emulate a mapping; the difference is that for a
1660sequence, the allowable keys should be the integers \var{k} for which
1661\code{0 <= \var{k} < \var{N}} where \var{N} is the length of the
Thomas Wouters1d75a792000-08-17 22:37:32 +00001662sequence, or slice objects, which define a range of items. (For backwards
1663compatibility, the method \method{__getslice__()} (see below) can also be
1664defined to handle simple, but not extended slices.) It is also recommended
Fred Drakea0073822000-08-18 02:42:14 +00001665that mappings provide the methods \method{keys()}, \method{values()},
Thomas Wouters1d75a792000-08-17 22:37:32 +00001666\method{items()}, \method{has_key()}, \method{get()}, \method{clear()},
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001667\method{setdefault()}, \method{iterkeys()}, \method{itervalues()},
Raymond Hettingerf4ca5a22003-01-19 14:57:12 +00001668\method{iteritems()}, \method{pop()}, \method{popitem()},
Thomas Wouters1d75a792000-08-17 22:37:32 +00001669\method{copy()}, and \method{update()} behaving similar to those for
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001670Python's standard dictionary objects. The \module{UserDict} module
1671provides a \class{DictMixin} class to help create those methods
1672from a base set of \method{__getitem__()}, \method{__setitem__()},
1673\method{__delitem__()}, and \method{keys()}.
1674Mutable sequences should provide
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001675methods \method{append()}, \method{count()}, \method{index()},
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001676\method{extend()},
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001677\method{insert()}, \method{pop()}, \method{remove()}, \method{reverse()}
1678and \method{sort()}, like Python standard list objects. Finally,
1679sequence types should implement addition (meaning concatenation) and
1680multiplication (meaning repetition) by defining the methods
Thomas Wouters12bba852000-08-24 20:06:04 +00001681\method{__add__()}, \method{__radd__()}, \method{__iadd__()},
1682\method{__mul__()}, \method{__rmul__()} and \method{__imul__()} described
1683below; they should not define \method{__coerce__()} or other numerical
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001684operators. It is recommended that both mappings and sequences
Fred Drake18d8d5a2001-09-18 17:58:20 +00001685implement the \method{__contains__()} method to allow efficient use of
1686the \code{in} operator; for mappings, \code{in} should be equivalent
1687of \method{has_key()}; for sequences, it should search through the
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001688values. It is further recommended that both mappings and sequences
1689implement the \method{__iter__()} method to allow efficient iteration
1690through the container; for mappings, \method{__iter__()} should be
1691the same as \method{iterkeys()}; for sequences, it should iterate
1692through the values.
Fred Drake4856d011999-01-12 04:15:20 +00001693\withsubitem{(mapping object method)}{
1694 \ttindex{keys()}
1695 \ttindex{values()}
1696 \ttindex{items()}
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001697 \ttindex{iterkeys()}
1698 \ttindex{itervalues()}
1699 \ttindex{iteritems()}
Fred Drake4856d011999-01-12 04:15:20 +00001700 \ttindex{has_key()}
1701 \ttindex{get()}
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001702 \ttindex{setdefault()}
1703 \ttindex{pop()}
1704 \ttindex{popitem()}
Fred Drake4856d011999-01-12 04:15:20 +00001705 \ttindex{clear()}
1706 \ttindex{copy()}
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001707 \ttindex{update()}
1708 \ttindex{__contains__()}}
Fred Drake4856d011999-01-12 04:15:20 +00001709\withsubitem{(sequence object method)}{
1710 \ttindex{append()}
1711 \ttindex{count()}
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001712 \ttindex{extend()}
Fred Drake4856d011999-01-12 04:15:20 +00001713 \ttindex{index()}
1714 \ttindex{insert()}
1715 \ttindex{pop()}
1716 \ttindex{remove()}
1717 \ttindex{reverse()}
1718 \ttindex{sort()}
1719 \ttindex{__add__()}
1720 \ttindex{__radd__()}
Thomas Wouters12bba852000-08-24 20:06:04 +00001721 \ttindex{__iadd__()}
Fred Drake4856d011999-01-12 04:15:20 +00001722 \ttindex{__mul__()}
Thomas Wouters12bba852000-08-24 20:06:04 +00001723 \ttindex{__rmul__()}
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001724 \ttindex{__imul__()}
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001725 \ttindex{__contains__()}
1726 \ttindex{__iter__()}}
Fred Drakeae3e5741999-01-28 23:21:49 +00001727\withsubitem{(numeric object method)}{\ttindex{__coerce__()}}
Fred Drakef6669171998-05-06 19:52:49 +00001728
Fred Drake73921b02001-10-01 16:32:13 +00001729\begin{methoddesc}[container object]{__len__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00001730Called to implement the built-in function
1731\function{len()}\bifuncindex{len}. Should return the length of the
1732object, an integer \code{>=} 0. Also, an object that doesn't define a
1733\method{__nonzero__()} method and whose \method{__len__()} method
1734returns zero is considered to be false in a Boolean context.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001735\withsubitem{(object method)}{\ttindex{__nonzero__()}}
1736\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001737
Fred Drake73921b02001-10-01 16:32:13 +00001738\begin{methoddesc}[container object]{__getitem__}{self, key}
Fred Draked82575d1998-08-28 20:03:12 +00001739Called to implement evaluation of \code{\var{self}[\var{key}]}.
Fred Drake31575ce2000-09-21 05:28:26 +00001740For sequence types, the accepted keys should be integers and slice
1741objects.\obindex{slice} Note that
1742the special interpretation of negative indexes (if the class wishes to
Fred Drakef6669171998-05-06 19:52:49 +00001743emulate a sequence type) is up to the \method{__getitem__()} method.
Fred Drake91826ed2000-07-13 04:57:58 +00001744If \var{key} is of an inappropriate type, \exception{TypeError} may be
1745raised; if of a value outside the set of indexes for the sequence
1746(after any special interpretation of negative values),
1747\exception{IndexError} should be raised.
Raymond Hettingera30616a2005-08-21 11:26:14 +00001748For mapping types, if \var{key} is missing (not in the container),
1749\exception{KeyError} should be raised.
Fred Drake0aa811c2001-10-20 04:24:09 +00001750\note{\keyword{for} loops expect that an
Fred Drake91826ed2000-07-13 04:57:58 +00001751\exception{IndexError} will be raised for illegal indexes to allow
Fred Drake0aa811c2001-10-20 04:24:09 +00001752proper detection of the end of the sequence.}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001753\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001754
Fred Drake73921b02001-10-01 16:32:13 +00001755\begin{methoddesc}[container object]{__setitem__}{self, key, value}
Fred Draked82575d1998-08-28 20:03:12 +00001756Called to implement assignment to \code{\var{self}[\var{key}]}. Same
Fred Drake1e42d8a1998-11-25 17:58:50 +00001757note as for \method{__getitem__()}. This should only be implemented
1758for mappings if the objects support changes to the values for keys, or
1759if new keys can be added, or for sequences if elements can be
Fred Drake91826ed2000-07-13 04:57:58 +00001760replaced. The same exceptions should be raised for improper
1761\var{key} values as for the \method{__getitem__()} method.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001762\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001763
Fred Drake73921b02001-10-01 16:32:13 +00001764\begin{methoddesc}[container object]{__delitem__}{self, key}
Fred Draked82575d1998-08-28 20:03:12 +00001765Called to implement deletion of \code{\var{self}[\var{key}]}. Same
Fred Drake1e42d8a1998-11-25 17:58:50 +00001766note as for \method{__getitem__()}. This should only be implemented
1767for mappings if the objects support removal of keys, or for sequences
Fred Drake91826ed2000-07-13 04:57:58 +00001768if elements can be removed from the sequence. The same exceptions
1769should be raised for improper \var{key} values as for the
1770\method{__getitem__()} method.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001771\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001772
Fred Drake73921b02001-10-01 16:32:13 +00001773\begin{methoddesc}[container object]{__iter__}{self}
1774This method is called when an iterator is required for a container.
1775This method should return a new iterator object that can iterate over
1776all the objects in the container. For mappings, it should iterate
1777over the keys of the container, and should also be made available as
1778the method \method{iterkeys()}.
1779
1780Iterator objects also need to implement this method; they are required
1781to return themselves. For more information on iterator objects, see
1782``\ulink{Iterator Types}{../lib/typeiter.html}'' in the
1783\citetitle[../lib/lib.html]{Python Library Reference}.
1784\end{methoddesc}
1785
1786The membership test operators (\keyword{in} and \keyword{not in}) are
1787normally implemented as an iteration through a sequence. However,
1788container objects can supply the following special method with a more
1789efficient implementation, which also does not require the object be a
1790sequence.
1791
1792\begin{methoddesc}[container object]{__contains__}{self, item}
1793Called to implement membership test operators. Should return true if
1794\var{item} is in \var{self}, false otherwise. For mapping objects,
1795this should consider the keys of the mapping rather than the values or
1796the key-item pairs.
1797\end{methoddesc}
1798
Fred Drakef6669171998-05-06 19:52:49 +00001799
Fred Drake3041b071998-10-21 00:25:32 +00001800\subsection{Additional methods for emulation of sequence types
Fred Drake61c77281998-07-28 19:34:22 +00001801 \label{sequence-methods}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001802
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001803The following optional methods can be defined to further emulate sequence
1804objects. Immutable sequences methods should at most only define
1805\method{__getslice__()}; mutable sequences might define all three
Raymond Hettinger92016dc2003-09-22 15:27:11 +00001806methods.
Fred Drakef6669171998-05-06 19:52:49 +00001807
Fred Drake1e42d8a1998-11-25 17:58:50 +00001808\begin{methoddesc}[sequence object]{__getslice__}{self, i, j}
Fred Drakea0073822000-08-18 02:42:14 +00001809\deprecated{2.0}{Support slice objects as parameters to the
1810\method{__getitem__()} method.}
Fred Draked82575d1998-08-28 20:03:12 +00001811Called to implement evaluation of \code{\var{self}[\var{i}:\var{j}]}.
1812The returned object should be of the same type as \var{self}. Note
1813that missing \var{i} or \var{j} in the slice expression are replaced
Fred Drakee15956b2000-04-03 04:51:13 +00001814by zero or \code{sys.maxint}, respectively. If negative indexes are
1815used in the slice, the length of the sequence is added to that index.
1816If the instance does not implement the \method{__len__()} method, an
1817\exception{AttributeError} is raised.
1818No guarantee is made that indexes adjusted this way are not still
1819negative. Indexes which are greater than the length of the sequence
1820are not modified.
Fred Drakea0073822000-08-18 02:42:14 +00001821If no \method{__getslice__()} is found, a slice
Thomas Wouters1d75a792000-08-17 22:37:32 +00001822object is created instead, and passed to \method{__getitem__()} instead.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001823\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001824
Fred Drake1e42d8a1998-11-25 17:58:50 +00001825\begin{methoddesc}[sequence object]{__setslice__}{self, i, j, sequence}
Fred Draked82575d1998-08-28 20:03:12 +00001826Called to implement assignment to \code{\var{self}[\var{i}:\var{j}]}.
1827Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Thomas Wouters1d75a792000-08-17 22:37:32 +00001828
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001829This method is deprecated. If no \method{__setslice__()} is found,
1830or for extended slicing of the form
1831\code{\var{self}[\var{i}:\var{j}:\var{k}]}, a
1832slice object is created, and passed to \method{__setitem__()},
1833instead of \method{__setslice__()} being called.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001834\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001835
Fred Drake1e42d8a1998-11-25 17:58:50 +00001836\begin{methoddesc}[sequence object]{__delslice__}{self, i, j}
Fred Draked82575d1998-08-28 20:03:12 +00001837Called to implement deletion of \code{\var{self}[\var{i}:\var{j}]}.
1838Same notes for \var{i} and \var{j} as for \method{__getslice__()}.
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001839This method is deprecated. If no \method{__delslice__()} is found,
1840or for extended slicing of the form
1841\code{\var{self}[\var{i}:\var{j}:\var{k}]}, a
1842slice object is created, and passed to \method{__delitem__()},
1843instead of \method{__delslice__()} being called.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001844\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001845
Fred Drakefb8ffe62001-04-13 15:54:41 +00001846Notice that these methods are only invoked when a single slice with a
1847single colon is used, and the slice method is available. For slice
1848operations involving extended slice notation, or in absence of the
1849slice methods, \method{__getitem__()}, \method{__setitem__()} or
1850\method{__delitem__()} is called with a slice object as argument.
Fred Drakef6669171998-05-06 19:52:49 +00001851
Fred Drakef89259782000-09-21 22:27:16 +00001852The following example demonstrate how to make your program or module
1853compatible with earlier versions of Python (assuming that methods
1854\method{__getitem__()}, \method{__setitem__()} and \method{__delitem__()}
1855support slice objects as arguments):
1856
1857\begin{verbatim}
1858class MyClass:
1859 ...
1860 def __getitem__(self, index):
1861 ...
1862 def __setitem__(self, index, value):
1863 ...
1864 def __delitem__(self, index):
1865 ...
1866
1867 if sys.version_info < (2, 0):
1868 # They won't be defined if version is at least 2.0 final
1869
1870 def __getslice__(self, i, j):
1871 return self[max(0, i):max(0, j):]
1872 def __setslice__(self, i, j, seq):
1873 self[max(0, i):max(0, j):] = seq
1874 def __delslice__(self, i, j):
1875 del self[max(0, i):max(0, j):]
1876 ...
1877\end{verbatim}
1878
Raymond Hettingere701dcb2003-01-19 13:08:18 +00001879Note the calls to \function{max()}; these are necessary because of
1880the handling of negative indices before the
Fred Drakef89259782000-09-21 22:27:16 +00001881\method{__*slice__()} methods are called. When negative indexes are
1882used, the \method{__*item__()} methods receive them as provided, but
1883the \method{__*slice__()} methods get a ``cooked'' form of the index
1884values. For each negative index value, the length of the sequence is
1885added to the index before calling the method (which may still result
1886in a negative index); this is the customary handling of negative
1887indexes by the built-in sequence types, and the \method{__*item__()}
1888methods are expected to do this as well. However, since they should
1889already be doing that, negative indexes cannot be passed in; they must
Raymond Hettingere41d4c82003-08-25 04:39:55 +00001890be constrained to the bounds of the sequence before being passed to
Fred Drakef89259782000-09-21 22:27:16 +00001891the \method{__*item__()} methods.
1892Calling \code{max(0, i)} conveniently returns the proper value.
1893
Fred Drake15988fd1999-02-12 18:14:57 +00001894
Fred Drake61c77281998-07-28 19:34:22 +00001895\subsection{Emulating numeric types\label{numeric-types}}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001896
1897The following methods can be defined to emulate numeric objects.
1898Methods corresponding to operations that are not supported by the
1899particular kind of number implemented (e.g., bitwise operations for
1900non-integral numbers) should be left undefined.
Fred Drakef6669171998-05-06 19:52:49 +00001901
Fred Drakeb8943701999-05-10 13:43:22 +00001902\begin{methoddesc}[numeric object]{__add__}{self, other}
1903\methodline[numeric object]{__sub__}{self, other}
1904\methodline[numeric object]{__mul__}{self, other}
Fred Drake3e2aca42001-08-14 20:28:08 +00001905\methodline[numeric object]{__floordiv__}{self, other}
Fred Drakeb8943701999-05-10 13:43:22 +00001906\methodline[numeric object]{__mod__}{self, other}
1907\methodline[numeric object]{__divmod__}{self, other}
1908\methodline[numeric object]{__pow__}{self, other\optional{, modulo}}
1909\methodline[numeric object]{__lshift__}{self, other}
1910\methodline[numeric object]{__rshift__}{self, other}
1911\methodline[numeric object]{__and__}{self, other}
1912\methodline[numeric object]{__xor__}{self, other}
1913\methodline[numeric object]{__or__}{self, other}
Fred Drake3e2aca42001-08-14 20:28:08 +00001914These methods are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001915called to implement the binary arithmetic operations (\code{+},
Fred Drake3e2aca42001-08-14 20:28:08 +00001916\code{-}, \code{*}, \code{//}, \code{\%},
Fred Draked82575d1998-08-28 20:03:12 +00001917\function{divmod()}\bifuncindex{divmod},
Fred Drakef25fa6d2006-05-03 02:04:40 +00001918\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<},
1919\code{>>}, \code{\&}, \code{\^}, \code{|}). For instance, to
Fred Drakefb8ffe62001-04-13 15:54:41 +00001920evaluate the expression \var{x}\code{+}\var{y}, where \var{x} is an
1921instance of a class that has an \method{__add__()} method,
Fred Drake3e2aca42001-08-14 20:28:08 +00001922\code{\var{x}.__add__(\var{y})} is called. The \method{__divmod__()}
1923method should be the equivalent to using \method{__floordiv__()} and
1924\method{__mod__()}; it should not be related to \method{__truediv__()}
1925(described below). Note that
Fred Draked82575d1998-08-28 20:03:12 +00001926\method{__pow__()} should be defined to accept an optional third
1927argument if the ternary version of the built-in
1928\function{pow()}\bifuncindex{pow} function is to be supported.
Georg Brandlad6911b2006-07-30 10:53:32 +00001929
1930If one of those methods does not support the operation with the
1931supplied arguments, it should return \code{NotImplemented}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00001932\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001933
Fred Drake3e2aca42001-08-14 20:28:08 +00001934\begin{methoddesc}[numeric object]{__div__}{self, other}
1935\methodline[numeric object]{__truediv__}{self, other}
1936The division operator (\code{/}) is implemented by these methods. The
1937\method{__truediv__()} method is used when \code{__future__.division}
1938is in effect, otherwise \method{__div__()} is used. If only one of
1939these two methods is defined, the object will not support division in
1940the alternate context; \exception{TypeError} will be raised instead.
1941\end{methoddesc}
1942
Fred Drakeb8943701999-05-10 13:43:22 +00001943\begin{methoddesc}[numeric object]{__radd__}{self, other}
1944\methodline[numeric object]{__rsub__}{self, other}
1945\methodline[numeric object]{__rmul__}{self, other}
1946\methodline[numeric object]{__rdiv__}{self, other}
Raymond Hettinger10cbe8d2002-06-20 06:12:37 +00001947\methodline[numeric object]{__rtruediv__}{self, other}
1948\methodline[numeric object]{__rfloordiv__}{self, other}
Fred Drakeb8943701999-05-10 13:43:22 +00001949\methodline[numeric object]{__rmod__}{self, other}
1950\methodline[numeric object]{__rdivmod__}{self, other}
1951\methodline[numeric object]{__rpow__}{self, other}
1952\methodline[numeric object]{__rlshift__}{self, other}
1953\methodline[numeric object]{__rrshift__}{self, other}
1954\methodline[numeric object]{__rand__}{self, other}
1955\methodline[numeric object]{__rxor__}{self, other}
1956\methodline[numeric object]{__ror__}{self, other}
Fred Drake3e2aca42001-08-14 20:28:08 +00001957These methods are
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001958called to implement the binary arithmetic operations (\code{+},
Fred Draked82575d1998-08-28 20:03:12 +00001959\code{-}, \code{*}, \code{/}, \code{\%},
1960\function{divmod()}\bifuncindex{divmod},
Fred Drakef25fa6d2006-05-03 02:04:40 +00001961\function{pow()}\bifuncindex{pow}, \code{**}, \code{<<},
1962\code{>>}, \code{\&}, \code{\^}, \code{|}) with reflected
Fred Drakefb8ffe62001-04-13 15:54:41 +00001963(swapped) operands. These functions are only called if the left
Georg Brandlc54173c2006-06-14 08:31:39 +00001964operand does not support the corresponding operation and the
1965operands are of different types.\footnote{
1966 For operands of the same type, it is assumed that if the
1967 non-reflected method (such as \method{__add__()}) fails the
1968 operation is not supported, which is why the reflected method
1969 is not called.}
1970For instance, to evaluate the expression \var{x}\code{-}\var{y},
1971where \var{y} is an instance of a class that has an
1972\method{__rsub__()} method, \code{\var{y}.__rsub__(\var{x})}
1973is called if \code{\var{x}.__sub__(\var{y})} returns
1974\var{NotImplemented}.
1975
1976Note that ternary
Fred Drakefb8ffe62001-04-13 15:54:41 +00001977\function{pow()}\bifuncindex{pow} will not try calling
1978\method{__rpow__()} (the coercion rules would become too
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00001979complicated).
Georg Brandlc54173c2006-06-14 08:31:39 +00001980
1981\note{If the right operand's type is a subclass of the left operand's
1982 type and that subclass provides the reflected method for the
Georg Brandl5b654ea2006-07-30 20:18:51 +00001983 operation, this method will be called before the left operand's
Georg Brandlc54173c2006-06-14 08:31:39 +00001984 non-reflected method. This behavior allows subclasses to
1985 override their ancestors' operations.}
Fred Drake1e42d8a1998-11-25 17:58:50 +00001986\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00001987
Thomas Woutersdc90cc22000-12-11 23:11:51 +00001988\begin{methoddesc}[numeric object]{__iadd__}{self, other}
1989\methodline[numeric object]{__isub__}{self, other}
1990\methodline[numeric object]{__imul__}{self, other}
1991\methodline[numeric object]{__idiv__}{self, other}
Raymond Hettinger10cbe8d2002-06-20 06:12:37 +00001992\methodline[numeric object]{__itruediv__}{self, other}
1993\methodline[numeric object]{__ifloordiv__}{self, other}
1994\methodline[numeric object]{__imod__}{self, other}
Thomas Woutersdc90cc22000-12-11 23:11:51 +00001995\methodline[numeric object]{__ipow__}{self, other\optional{, modulo}}
1996\methodline[numeric object]{__ilshift__}{self, other}
1997\methodline[numeric object]{__irshift__}{self, other}
1998\methodline[numeric object]{__iand__}{self, other}
1999\methodline[numeric object]{__ixor__}{self, other}
2000\methodline[numeric object]{__ior__}{self, other}
Fred Drakefb8ffe62001-04-13 15:54:41 +00002001These methods are called to implement the augmented arithmetic
Georg Brandl45dc1f22007-01-17 21:09:04 +00002002operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{//=},
2003\code{\%=}, \code{**=}, \code{<<=}, \code{>>=}, \code{\&=},
Fred Drakea3788642003-07-23 15:18:03 +00002004\code{\textasciicircum=}, \code{|=}). These methods should attempt to do the
Fred Drakefb8ffe62001-04-13 15:54:41 +00002005operation in-place (modifying \var{self}) and return the result (which
2006could be, but does not have to be, \var{self}). If a specific method
2007is not defined, the augmented operation falls back to the normal
2008methods. For instance, to evaluate the expression
2009\var{x}\code{+=}\var{y}, where \var{x} is an instance of a class that
2010has an \method{__iadd__()} method, \code{\var{x}.__iadd__(\var{y})} is
2011called. If \var{x} is an instance of a class that does not define a
Fred Drakeb3dfc0a2005-09-07 04:57:56 +00002012\method{__iadd__()} method, \code{\var{x}.__add__(\var{y})} and
Fred Drakefb8ffe62001-04-13 15:54:41 +00002013\code{\var{y}.__radd__(\var{x})} are considered, as with the
2014evaluation of \var{x}\code{+}\var{y}.
Thomas Woutersdc90cc22000-12-11 23:11:51 +00002015\end{methoddesc}
2016
Fred Drakeb8943701999-05-10 13:43:22 +00002017\begin{methoddesc}[numeric object]{__neg__}{self}
2018\methodline[numeric object]{__pos__}{self}
2019\methodline[numeric object]{__abs__}{self}
2020\methodline[numeric object]{__invert__}{self}
Fred Drakefb8ffe62001-04-13 15:54:41 +00002021Called to implement the unary arithmetic operations (\code{-},
2022\code{+}, \function{abs()}\bifuncindex{abs} and \code{\~{}}).
Fred Drake1e42d8a1998-11-25 17:58:50 +00002023\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00002024
Fred Drakeb8943701999-05-10 13:43:22 +00002025\begin{methoddesc}[numeric object]{__complex__}{self}
2026\methodline[numeric object]{__int__}{self}
2027\methodline[numeric object]{__long__}{self}
2028\methodline[numeric object]{__float__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00002029Called to implement the built-in functions
Fred Drake15988fd1999-02-12 18:14:57 +00002030\function{complex()}\bifuncindex{complex},
2031\function{int()}\bifuncindex{int}, \function{long()}\bifuncindex{long},
Fred Draked82575d1998-08-28 20:03:12 +00002032and \function{float()}\bifuncindex{float}. Should return a value of
2033the appropriate type.
Fred Drake1e42d8a1998-11-25 17:58:50 +00002034\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00002035
Fred Drakeb8943701999-05-10 13:43:22 +00002036\begin{methoddesc}[numeric object]{__oct__}{self}
2037\methodline[numeric object]{__hex__}{self}
Fred Draked82575d1998-08-28 20:03:12 +00002038Called to implement the built-in functions
2039\function{oct()}\bifuncindex{oct} and
2040\function{hex()}\bifuncindex{hex}. Should return a string value.
Fred Drake1e42d8a1998-11-25 17:58:50 +00002041\end{methoddesc}
Fred Drakef6669171998-05-06 19:52:49 +00002042
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002043\begin{methoddesc}[numeric object]{__index__}{self}
George Yoshida5e0b8822006-05-27 16:32:44 +00002044Called to implement \function{operator.index()}. Also called whenever
2045Python needs an integer object (such as in slicing). Must return an
2046integer (int or long).
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002047\versionadded{2.5}
2048\end{methoddesc}
2049
Fred Drakeb8943701999-05-10 13:43:22 +00002050\begin{methoddesc}[numeric object]{__coerce__}{self, other}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002051Called to implement ``mixed-mode'' numeric arithmetic. Should either
Fred Draked82575d1998-08-28 20:03:12 +00002052return a 2-tuple containing \var{self} and \var{other} converted to
Fred Drakeb8943701999-05-10 13:43:22 +00002053a common numeric type, or \code{None} if conversion is impossible. When
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002054the common type would be the type of \code{other}, it is sufficient to
2055return \code{None}, since the interpreter will also ask the other
2056object to attempt a coercion (but sometimes, if the implementation of
2057the other type cannot be changed, it is useful to do the conversion to
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002058the other type here). A return value of \code{NotImplemented} is
2059equivalent to returning \code{None}.
Fred Drake1e42d8a1998-11-25 17:58:50 +00002060\end{methoddesc}
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002061
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002062\subsection{Coercion rules\label{coercion-rules}}
2063
2064This section used to document the rules for coercion. As the language
2065has evolved, the coercion rules have become hard to document
2066precisely; documenting what one version of one particular
2067implementation does is undesirable. Instead, here are some informal
2068guidelines regarding coercion. In Python 3.0, coercion will not be
2069supported.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002070
2071\begin{itemize}
2072
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002073\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002074
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002075If the left operand of a \% operator is a string or Unicode object, no
2076coercion takes place and the string formatting operation is invoked
2077instead.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002078
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002079\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002080
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002081It is no longer recommended to define a coercion operation.
2082Mixed-mode operations on types that don't define coercion pass the
2083original arguments to the operation.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002084
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002085\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002086
Fred Drake293dd4b2002-06-04 16:25:57 +00002087New-style classes (those derived from \class{object}) never invoke the
2088\method{__coerce__()} method in response to a binary operator; the only
2089time \method{__coerce__()} is invoked is when the built-in function
2090\function{coerce()} is called.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002091
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002092\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002093
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002094For most intents and purposes, an operator that returns
2095\code{NotImplemented} is treated the same as one that is not
2096implemented at all.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002097
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002098\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002099
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002100Below, \method{__op__()} and \method{__rop__()} are used to signify
2101the generic method names corresponding to an operator;
Fred Drakeb3dfc0a2005-09-07 04:57:56 +00002102\method{__iop__()} is used for the corresponding in-place operator. For
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002103example, for the operator `\code{+}', \method{__add__()} and
2104\method{__radd__()} are used for the left and right variant of the
Fred Drakeb3dfc0a2005-09-07 04:57:56 +00002105binary operator, and \method{__iadd__()} for the in-place variant.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002106
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002107\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002108
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002109For objects \var{x} and \var{y}, first \code{\var{x}.__op__(\var{y})}
2110is tried. If this is not implemented or returns \code{NotImplemented},
2111\code{\var{y}.__rop__(\var{x})} is tried. If this is also not
Fred Drake293dd4b2002-06-04 16:25:57 +00002112implemented or returns \code{NotImplemented}, a \exception{TypeError}
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002113exception is raised. But see the following exception:
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002114
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002115\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002116
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002117Exception to the previous item: if the left operand is an instance of
Georg Brandle071b002006-04-01 07:23:08 +00002118a built-in type or a new-style class, and the right operand is an instance
2119of a proper subclass of that type or class and overrides the base's
2120\method{__rop__()} method, the right operand's \method{__rop__()} method
2121is tried \emph{before} the left operand's \method{__op__()} method.
2122
2123This is done so that a subclass can completely override binary operators.
2124Otherwise, the left operand's \method{__op__()} method would always
2125accept the right operand: when an instance of a given class is expected,
2126an instance of a subclass of that class is always acceptable.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002127
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002128\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002129
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002130When either operand type defines a coercion, this coercion is called
Fred Drake293dd4b2002-06-04 16:25:57 +00002131before that type's \method{__op__()} or \method{__rop__()} method is
2132called, but no sooner. If the coercion returns an object of a
2133different type for the operand whose coercion is invoked, part of the
2134process is redone using the new object.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002135
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002136\item
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002137
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002138When an in-place operator (like `\code{+=}') is used, if the left
Fred Drake293dd4b2002-06-04 16:25:57 +00002139operand implements \method{__iop__()}, it is invoked without any
2140coercion. When the operation falls back to \method{__op__()} and/or
2141\method{__rop__()}, the normal coercion rules apply.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002142
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002143\item
2144
2145In \var{x}\code{+}\var{y}, if \var{x} is a sequence that implements
2146sequence concatenation, sequence concatenation is invoked.
2147
2148\item
2149
2150In \var{x}\code{*}\var{y}, if one operator is a sequence that
2151implements sequence repetition, and the other is an integer
Fred Drake293dd4b2002-06-04 16:25:57 +00002152(\class{int} or \class{long}), sequence repetition is invoked.
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002153
2154\item
2155
Fred Drake293dd4b2002-06-04 16:25:57 +00002156Rich comparisons (implemented by methods \method{__eq__()} and so on)
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002157never use coercion. Three-way comparison (implemented by
Fred Drake293dd4b2002-06-04 16:25:57 +00002158\method{__cmp__()}) does use coercion under the same conditions as
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002159other binary operations use it.
2160
2161\item
2162
Fred Drake293dd4b2002-06-04 16:25:57 +00002163In the current implementation, the built-in numeric types \class{int},
2164\class{long} and \class{float} do not use coercion; the type
2165\class{complex} however does use it. The difference can become
Guido van Rossum92cf95f2002-06-03 19:06:41 +00002166apparent when subclassing these types. Over time, the type
Fred Drake293dd4b2002-06-04 16:25:57 +00002167\class{complex} may be fixed to avoid coercion. All these types
2168implement a \method{__coerce__()} method, for use by the built-in
2169\function{coerce()} function.
Guido van Rossum83b2f8a1998-07-23 17:12:46 +00002170
2171\end{itemize}
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002172
Nick Coghlanafd5e632006-05-03 13:02:47 +00002173\subsection{With Statement Context Managers\label{context-managers}}
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002174
Neal Norwitzd03b0732006-03-28 05:51:02 +00002175\versionadded{2.5}
2176
Nick Coghlana7e820a2006-04-25 10:56:51 +00002177A \dfn{context manager} is an object that defines the runtime
Nick Coghlan877cf232006-04-24 04:17:02 +00002178context to be established when executing a \keyword{with}
Nick Coghlanafd5e632006-05-03 13:02:47 +00002179statement. The context manager handles the entry into,
Nick Coghlana7e820a2006-04-25 10:56:51 +00002180and the exit from, the desired runtime context for the execution
2181of the block of code. Context managers are normally invoked using
2182the \keyword{with} statement (described in section~\ref{with}), but
2183can also be used by directly invoking their methods.
Nick Coghlanfee3dfc2006-04-23 15:39:16 +00002184
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002185\stindex{with}
2186\index{context manager}
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002187
Nick Coghlanafd5e632006-05-03 13:02:47 +00002188Typical uses of context managers include saving and
Nick Coghlanfee3dfc2006-04-23 15:39:16 +00002189restoring various kinds of global state, locking and unlocking
2190resources, closing opened files, etc.
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002191
Nick Coghlanafd5e632006-05-03 13:02:47 +00002192For more information on context managers, see
2193``\ulink{Context Types}{../lib/typecontextmanager.html}'' in the
Nick Coghlanfee3dfc2006-04-23 15:39:16 +00002194\citetitle[../lib/lib.html]{Python Library Reference}.
2195
Nick Coghlanafd5e632006-05-03 13:02:47 +00002196\begin{methoddesc}[context manager]{__enter__}{self}
Nick Coghlana7e820a2006-04-25 10:56:51 +00002197Enter the runtime context related to this object. The \keyword{with}
2198statement will bind this method's return value to the target(s)
2199specified in the \keyword{as} clause of the statement, if any.
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002200\end{methoddesc}
2201
Nick Coghlanfee3dfc2006-04-23 15:39:16 +00002202\begin{methoddesc}[context manager]{__exit__}
2203{self, exc_type, exc_value, traceback}
Nick Coghlana7e820a2006-04-25 10:56:51 +00002204Exit the runtime context related to this object. The parameters
2205describe the exception that caused the context to be exited. If
2206the context was exited without an exception, all three arguments
2207will be \constant{None}.
Phillip J. Eby5d0f4c62006-03-27 19:59:34 +00002208
2209If an exception is supplied, and the method wishes to suppress the
2210exception (i.e., prevent it from being propagated), it should return a
2211true value. Otherwise, the exception will be processed normally upon
2212exit from this method.
2213
2214Note that \method{__exit__} methods should not reraise the passed-in
2215exception; this is the caller's responsibility.
2216\end{methoddesc}
2217
2218\begin{seealso}
2219 \seepep{0343}{The "with" statement}
2220 {The specification, background, and examples for the
2221 Python \keyword{with} statement.}
2222\end{seealso}
2223