blob: 6f819e959e4cfdb7a3a591105eda024399efc2bf [file] [log] [blame]
Fred Drake7a2f0661998-09-10 18:25:58 +00001\section{Built-in Types \label{types}}
Fred Drake64e3b431998-07-24 13:56:11 +00002
3The following sections describe the standard types that are built into
4the interpreter. These are the numeric types, sequence types, and
Guido van Rossum77f6a652002-04-03 22:41:51 +00005several others, including types themselves.
Fred Drake64e3b431998-07-24 13:56:11 +00006\indexii{built-in}{types}
Fred Drake64e3b431998-07-24 13:56:11 +00007
8Some operations are supported by several object types; in particular,
9all objects can be compared, tested for truth value, and converted to
Fred Drake84538cd1998-11-30 21:51:25 +000010a string (with the \code{`\textrm{\ldots}`} notation). The latter
11conversion is implicitly used when an object is written by the
12\keyword{print}\stindex{print} statement.
Fred Drake64e3b431998-07-24 13:56:11 +000013
14
Fred Drake7a2f0661998-09-10 18:25:58 +000015\subsection{Truth Value Testing \label{truth}}
Fred Drake64e3b431998-07-24 13:56:11 +000016
Fred Drake84538cd1998-11-30 21:51:25 +000017Any object can be tested for truth value, for use in an \keyword{if} or
18\keyword{while} condition or as operand of the Boolean operations below.
Fred Drake64e3b431998-07-24 13:56:11 +000019The following values are considered false:
20\stindex{if}
21\stindex{while}
22\indexii{truth}{value}
23\indexii{Boolean}{operations}
24\index{false}
25
Fred Drake64e3b431998-07-24 13:56:11 +000026\begin{itemize}
27
28\item \code{None}
Fred Drake7a2f0661998-09-10 18:25:58 +000029 \withsubitem{(Built-in object)}{\ttindex{None}}
Fred Drake64e3b431998-07-24 13:56:11 +000030
Guido van Rossum77f6a652002-04-03 22:41:51 +000031\item \code{False}
32 \withsubitem{(Built-in object)}{\ttindex{False}}
33
Fred Drake38e5d272000-04-03 20:13:55 +000034\item zero of any numeric type, for example, \code{0}, \code{0L},
35 \code{0.0}, \code{0j}.
Fred Drake64e3b431998-07-24 13:56:11 +000036
Fred Drake38e5d272000-04-03 20:13:55 +000037\item any empty sequence, for example, \code{''}, \code{()}, \code{[]}.
Fred Drake64e3b431998-07-24 13:56:11 +000038
Fred Drake38e5d272000-04-03 20:13:55 +000039\item any empty mapping, for example, \code{\{\}}.
Fred Drake64e3b431998-07-24 13:56:11 +000040
41\item instances of user-defined classes, if the class defines a
Fred Drake7a2f0661998-09-10 18:25:58 +000042 \method{__nonzero__()} or \method{__len__()} method, when that
Fred Drake38e5d272000-04-03 20:13:55 +000043 method returns zero.\footnote{Additional information on these
Fred Drake66571cc2000-09-09 03:30:34 +000044special methods may be found in the \citetitle[../ref/ref.html]{Python
45Reference Manual}.}
Fred Drake64e3b431998-07-24 13:56:11 +000046
47\end{itemize}
48
49All other values are considered true --- so objects of many types are
50always true.
51\index{true}
52
53Operations and built-in functions that have a Boolean result always
Guido van Rossum77f6a652002-04-03 22:41:51 +000054return \code{0} or \code{False} for false and \code{1} or \code{True}
55for true, unless otherwise stated. (Important exception: the Boolean
56operations \samp{or}\opindex{or} and \samp{and}\opindex{and} always
57return one of their operands.)
58\index{False}
59\index{True}
Fred Drake64e3b431998-07-24 13:56:11 +000060
Fred Drake7a2f0661998-09-10 18:25:58 +000061\subsection{Boolean Operations \label{boolean}}
Fred Drake64e3b431998-07-24 13:56:11 +000062
63These are the Boolean operations, ordered by ascending priority:
64\indexii{Boolean}{operations}
65
66\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
Fred Drake8c071d42001-01-26 20:48:35 +000067 \lineiii{\var{x} or \var{y}}
68 {if \var{x} is false, then \var{y}, else \var{x}}{(1)}
69 \lineiii{\var{x} and \var{y}}
70 {if \var{x} is false, then \var{x}, else \var{y}}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +000071 \hline
Fred Drake8c071d42001-01-26 20:48:35 +000072 \lineiii{not \var{x}}
Guido van Rossum77f6a652002-04-03 22:41:51 +000073 {if \var{x} is false, then \code{True}, else \code{False}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +000074\end{tableiii}
75\opindex{and}
76\opindex{or}
77\opindex{not}
78
79\noindent
80Notes:
81
82\begin{description}
83
84\item[(1)]
85These only evaluate their second argument if needed for their outcome.
86
87\item[(2)]
Fred Drake38e5d272000-04-03 20:13:55 +000088\samp{not} has a lower priority than non-Boolean operators, so
89\code{not \var{a} == \var{b}} is interpreted as \code{not (\var{a} ==
90\var{b})}, and \code{\var{a} == not \var{b}} is a syntax error.
Fred Drake64e3b431998-07-24 13:56:11 +000091
92\end{description}
93
94
Fred Drake7a2f0661998-09-10 18:25:58 +000095\subsection{Comparisons \label{comparisons}}
Fred Drake64e3b431998-07-24 13:56:11 +000096
97Comparison operations are supported by all objects. They all have the
98same priority (which is higher than that of the Boolean operations).
Fred Drake38e5d272000-04-03 20:13:55 +000099Comparisons can be chained arbitrarily; for example, \code{\var{x} <
100\var{y} <= \var{z}} is equivalent to \code{\var{x} < \var{y} and
101\var{y} <= \var{z}}, except that \var{y} is evaluated only once (but
102in both cases \var{z} is not evaluated at all when \code{\var{x} <
103\var{y}} is found to be false).
Fred Drake64e3b431998-07-24 13:56:11 +0000104\indexii{chaining}{comparisons}
105
106This table summarizes the comparison operations:
107
108\begin{tableiii}{c|l|c}{code}{Operation}{Meaning}{Notes}
109 \lineiii{<}{strictly less than}{}
110 \lineiii{<=}{less than or equal}{}
111 \lineiii{>}{strictly greater than}{}
112 \lineiii{>=}{greater than or equal}{}
113 \lineiii{==}{equal}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000114 \lineiii{!=}{not equal}{(1)}
Fred Drake512bb722000-08-18 03:12:38 +0000115 \lineiii{<>}{not equal}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000116 \lineiii{is}{object identity}{}
117 \lineiii{is not}{negated object identity}{}
118\end{tableiii}
119\indexii{operator}{comparison}
120\opindex{==} % XXX *All* others have funny characters < ! >
121\opindex{is}
122\opindex{is not}
123
124\noindent
125Notes:
126
127\begin{description}
128
129\item[(1)]
130\code{<>} and \code{!=} are alternate spellings for the same operator.
Fred Drake4de96c22000-08-12 03:36:23 +0000131(I couldn't choose between \ABC{} and C! :-)
Fred Drake64e3b431998-07-24 13:56:11 +0000132\index{ABC language@\ABC{} language}
Fred Drakec37b65e2001-11-28 07:26:15 +0000133\index{language!ABC@\ABC}
Fred Drake4de96c22000-08-12 03:36:23 +0000134\indexii{C}{language}
Fred Drake38e5d272000-04-03 20:13:55 +0000135\code{!=} is the preferred spelling; \code{<>} is obsolescent.
Fred Drake64e3b431998-07-24 13:56:11 +0000136
137\end{description}
138
139Objects of different types, except different numeric types, never
140compare equal; such objects are ordered consistently but arbitrarily
141(so that sorting a heterogeneous array yields a consistent result).
Fred Drake38e5d272000-04-03 20:13:55 +0000142Furthermore, some types (for example, file objects) support only a
143degenerate notion of comparison where any two objects of that type are
144unequal. Again, such objects are ordered arbitrarily but
145consistently.
146\indexii{object}{numeric}
Fred Drake64e3b431998-07-24 13:56:11 +0000147\indexii{objects}{comparing}
148
Fred Drake38e5d272000-04-03 20:13:55 +0000149Instances of a class normally compare as non-equal unless the class
150\withsubitem{(instance method)}{\ttindex{__cmp__()}}
Fred Drake66571cc2000-09-09 03:30:34 +0000151defines the \method{__cmp__()} method. Refer to the
152\citetitle[../ref/customization.html]{Python Reference Manual} for
153information on the use of this method to effect object comparisons.
Fred Drake64e3b431998-07-24 13:56:11 +0000154
Fred Drake38e5d272000-04-03 20:13:55 +0000155\strong{Implementation note:} Objects of different types except
156numbers are ordered by their type names; objects of the same types
157that don't support proper comparison are ordered by their address.
158
159Two more operations with the same syntactic priority,
160\samp{in}\opindex{in} and \samp{not in}\opindex{not in}, are supported
161only by sequence types (below).
Fred Drake64e3b431998-07-24 13:56:11 +0000162
163
Fred Drake7a2f0661998-09-10 18:25:58 +0000164\subsection{Numeric Types \label{typesnumeric}}
Fred Drake64e3b431998-07-24 13:56:11 +0000165
Guido van Rossum77f6a652002-04-03 22:41:51 +0000166There are four distinct numeric types: \dfn{plain integers},
167\dfn{long integers},
Fred Drake64e3b431998-07-24 13:56:11 +0000168\dfn{floating point numbers}, and \dfn{complex numbers}.
Guido van Rossum77f6a652002-04-03 22:41:51 +0000169In addition, Booleans are a subtype of plain integers.
Fred Drake64e3b431998-07-24 13:56:11 +0000170Plain integers (also just called \dfn{integers})
Fred Drake38e5d272000-04-03 20:13:55 +0000171are implemented using \ctype{long} in C, which gives them at least 32
Fred Drake64e3b431998-07-24 13:56:11 +0000172bits of precision. Long integers have unlimited precision. Floating
Fred Drake38e5d272000-04-03 20:13:55 +0000173point numbers are implemented using \ctype{double} in C. All bets on
Fred Drake64e3b431998-07-24 13:56:11 +0000174their precision are off unless you happen to know the machine you are
175working with.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000176\obindex{numeric}
Guido van Rossum77f6a652002-04-03 22:41:51 +0000177\obindex{Boolean}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000178\obindex{integer}
179\obindex{long integer}
180\obindex{floating point}
181\obindex{complex number}
Fred Drake38e5d272000-04-03 20:13:55 +0000182\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000183
184Complex numbers have a real and imaginary part, which are both
Fred Drake38e5d272000-04-03 20:13:55 +0000185implemented using \ctype{double} in C. To extract these parts from
Tim Peters8f01b682002-03-12 03:04:44 +0000186a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Fred Drake64e3b431998-07-24 13:56:11 +0000187
188Numbers are created by numeric literals or as the result of built-in
189functions and operators. Unadorned integer literals (including hex
Fred Drake38e5d272000-04-03 20:13:55 +0000190and octal numbers) yield plain integers. Integer literals with an
191\character{L} or \character{l} suffix yield long integers
192(\character{L} is preferred because \samp{1l} looks too much like
193eleven!). Numeric literals containing a decimal point or an exponent
194sign yield floating point numbers. Appending \character{j} or
195\character{J} to a numeric literal yields a complex number.
Fred Drake64e3b431998-07-24 13:56:11 +0000196\indexii{numeric}{literals}
197\indexii{integer}{literals}
198\indexiii{long}{integer}{literals}
199\indexii{floating point}{literals}
200\indexii{complex number}{literals}
201\indexii{hexadecimal}{literals}
202\indexii{octal}{literals}
203
204Python fully supports mixed arithmetic: when a binary arithmetic
205operator has operands of different numeric types, the operand with the
206``smaller'' type is converted to that of the other, where plain
207integer is smaller than long integer is smaller than floating point is
208smaller than complex.
Fred Drakeea003fc1999-04-05 21:59:15 +0000209Comparisons between numbers of mixed type use the same rule.\footnote{
210 As a consequence, the list \code{[1, 2]} is considered equal
Fred Drake82ac24f1999-07-02 14:29:14 +0000211 to \code{[1.0, 2.0]}, and similar for tuples.
212} The functions \function{int()}, \function{long()}, \function{float()},
Fred Drake84538cd1998-11-30 21:51:25 +0000213and \function{complex()} can be used
Fred Drake64e3b431998-07-24 13:56:11 +0000214to coerce numbers to a specific type.
215\index{arithmetic}
216\bifuncindex{int}
217\bifuncindex{long}
218\bifuncindex{float}
219\bifuncindex{complex}
220
221All numeric types support the following operations, sorted by
222ascending priority (operations in the same box have the same
223priority; all numeric operations have a higher priority than
224comparison operations):
225
226\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
227 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
228 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
229 \hline
230 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
231 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
232 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
233 \hline
234 \lineiii{-\var{x}}{\var{x} negated}{}
235 \lineiii{+\var{x}}{\var{x} unchanged}{}
236 \hline
237 \lineiii{abs(\var{x})}{absolute value or magnitude of \var{x}}{}
238 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
239 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
240 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
241 \lineiii{complex(\var{re},\var{im})}{a complex number with real part \var{re}, imaginary part \var{im}. \var{im} defaults to zero.}{}
Fred Drake26b698f1999-02-12 18:27:31 +0000242 \lineiii{\var{c}.conjugate()}{conjugate of the complex number \var{c}}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000243 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
244 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
245 \lineiii{\var{x} ** \var{y}}{\var{x} to the power \var{y}}{}
246\end{tableiii}
247\indexiii{operations on}{numeric}{types}
Fred Drake26b698f1999-02-12 18:27:31 +0000248\withsubitem{(complex number method)}{\ttindex{conjugate()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000249
250\noindent
251Notes:
252\begin{description}
253
254\item[(1)]
255For (plain or long) integer division, the result is an integer.
Tim Peters8f01b682002-03-12 03:04:44 +0000256The result is always rounded towards minus infinity: 1/2 is 0,
Fred Drake38e5d272000-04-03 20:13:55 +0000257(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
258is a long integer if either operand is a long integer, regardless of
259the numeric value.
Fred Drake64e3b431998-07-24 13:56:11 +0000260\indexii{integer}{division}
261\indexiii{long}{integer}{division}
262
263\item[(2)]
264Conversion from floating point to (long or plain) integer may round or
Fred Drake4de96c22000-08-12 03:36:23 +0000265truncate as in C; see functions \function{floor()} and
266\function{ceil()} in the \refmodule{math}\refbimodindex{math} module
267for well-defined conversions.
Fred Drake9474d861999-02-12 22:05:33 +0000268\withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000269\indexii{numeric}{conversions}
Fred Drake4de96c22000-08-12 03:36:23 +0000270\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000271
272\item[(3)]
Fred Drake38e5d272000-04-03 20:13:55 +0000273See section \ref{built-in-funcs}, ``Built-in Functions,'' for a full
274description.
Fred Drake64e3b431998-07-24 13:56:11 +0000275
276\end{description}
277% XXXJH exceptions: overflow (when? what operations?) zerodivision
278
Fred Drake4e7c2051999-02-19 15:30:25 +0000279\subsubsection{Bit-string Operations on Integer Types \label{bitstring-ops}}
Fred Drake64e3b431998-07-24 13:56:11 +0000280\nodename{Bit-string Operations}
281
282Plain and long integer types support additional operations that make
283sense only for bit-strings. Negative numbers are treated as their 2's
284complement value (for long integers, this assumes a sufficiently large
285number of bits that no overflow occurs during the operation).
286
287The priorities of the binary bit-wise operations are all lower than
288the numeric operations and higher than the comparisons; the unary
289operation \samp{\~} has the same priority as the other unary numeric
290operations (\samp{+} and \samp{-}).
291
292This table lists the bit-string operations sorted in ascending
293priority (operations in the same box have the same priority):
294
295\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
296 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
297 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
298 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
299 \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
300 \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
301 \hline
302 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
303\end{tableiii}
304\indexiii{operations on}{integer}{types}
305\indexii{bit-string}{operations}
306\indexii{shifting}{operations}
307\indexii{masking}{operations}
308
309\noindent
310Notes:
311\begin{description}
312\item[(1)] Negative shift counts are illegal and cause a
313\exception{ValueError} to be raised.
314\item[(2)] A left shift by \var{n} bits is equivalent to
315multiplication by \code{pow(2, \var{n})} without overflow check.
316\item[(3)] A right shift by \var{n} bits is equivalent to
317division by \code{pow(2, \var{n})} without overflow check.
318\end{description}
319
320
Fred Drake93656e72001-05-02 20:18:03 +0000321\subsection{Iterator Types \label{typeiter}}
322
Fred Drakef42cc452001-05-03 04:39:10 +0000323\versionadded{2.2}
Fred Drake93656e72001-05-02 20:18:03 +0000324\index{iterator protocol}
325\index{protocol!iterator}
326\index{sequence!iteration}
327\index{container!iteration over}
328
329Python supports a concept of iteration over containers. This is
330implemented using two distinct methods; these are used to allow
331user-defined classes to support iteration. Sequences, described below
332in more detail, always support the iteration methods.
333
334One method needs to be defined for container objects to provide
335iteration support:
336
337\begin{methoddesc}[container]{__iter__}{}
Greg Ward54f65092001-07-26 21:01:21 +0000338 Return an iterator object. The object is required to support the
Fred Drake93656e72001-05-02 20:18:03 +0000339 iterator protocol described below. If a container supports
340 different types of iteration, additional methods can be provided to
341 specifically request iterators for those iteration types. (An
342 example of an object supporting multiple forms of iteration would be
343 a tree structure which supports both breadth-first and depth-first
344 traversal.) This method corresponds to the \member{tp_iter} slot of
345 the type structure for Python objects in the Python/C API.
346\end{methoddesc}
347
348The iterator objects themselves are required to support the following
349two methods, which together form the \dfn{iterator protocol}:
350
351\begin{methoddesc}[iterator]{__iter__}{}
352 Return the iterator object itself. This is required to allow both
353 containers and iterators to be used with the \keyword{for} and
354 \keyword{in} statements. This method corresponds to the
355 \member{tp_iter} slot of the type structure for Python objects in
356 the Python/C API.
357\end{methoddesc}
358
Fred Drakef42cc452001-05-03 04:39:10 +0000359\begin{methoddesc}[iterator]{next}{}
Fred Drake93656e72001-05-02 20:18:03 +0000360 Return the next item from the container. If there are no further
361 items, raise the \exception{StopIteration} exception. This method
362 corresponds to the \member{tp_iternext} slot of the type structure
363 for Python objects in the Python/C API.
364\end{methoddesc}
365
366Python defines several iterator objects to support iteration over
367general and specific sequence types, dictionaries, and other more
368specialized forms. The specific types are not important beyond their
369implementation of the iterator protocol.
370
371
Fred Drake7a2f0661998-09-10 18:25:58 +0000372\subsection{Sequence Types \label{typesseq}}
Fred Drake64e3b431998-07-24 13:56:11 +0000373
Fred Drake107b9672000-08-14 15:37:59 +0000374There are six sequence types: strings, Unicode strings, lists,
Fred Drake512bb722000-08-18 03:12:38 +0000375tuples, buffers, and xrange objects.
Fred Drake64e3b431998-07-24 13:56:11 +0000376
377Strings literals are written in single or double quotes:
Fred Drake38e5d272000-04-03 20:13:55 +0000378\code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
Fred Drake4de96c22000-08-12 03:36:23 +0000379\citetitle[../ref/strings.html]{Python Reference Manual} for more about
380string literals. Unicode strings are much like strings, but are
381specified in the syntax using a preceeding \character{u} character:
382\code{u'abc'}, \code{u"def"}. Lists are constructed with square brackets,
Fred Drake37f15741999-11-10 16:21:37 +0000383separating items with commas: \code{[a, b, c]}. Tuples are
384constructed by the comma operator (not within square brackets), with
385or without enclosing parentheses, but an empty tuple must have the
386enclosing parentheses, e.g., \code{a, b, c} or \code{()}. A single
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000387item tuple must have a trailing comma, e.g., \code{(d,)}.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000388\obindex{sequence}
389\obindex{string}
390\obindex{Unicode}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000391\obindex{tuple}
392\obindex{list}
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000393
394Buffer objects are not directly supported by Python syntax, but can be
395created by calling the builtin function
396\function{buffer()}.\bifuncindex{buffer}. They don't support
397concatenation or repetition.
398\obindex{buffer}
399
400Xrange objects are similar to buffers in that there is no specific
401syntax to create them, but they are created using the \function{xrange()}
402function.\bifuncindex{xrange} They don't support slicing,
403concatenation or repetition, and using \code{in}, \code{not in},
404\function{min()} or \function{max()} on them is inefficient.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000405\obindex{xrange}
Fred Drake64e3b431998-07-24 13:56:11 +0000406
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000407Most sequence types support the following operations. The \samp{in} and
Fred Drake64e3b431998-07-24 13:56:11 +0000408\samp{not in} operations have the same priorities as the comparison
409operations. The \samp{+} and \samp{*} operations have the same
410priority as the corresponding numeric operations.\footnote{They must
411have since the parser can't tell the type of the operands.}
412
413This table lists the sequence operations sorted in ascending priority
414(operations in the same box have the same priority). In the table,
415\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
416and \var{j} are integers:
417
418\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
419 \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
420 \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is
421equal to \var{x}, else \code{1}}{}
422 \hline
423 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
Fred Draked800cff2001-08-28 14:56:05 +0000424 \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} shallow copies of \var{s} concatenated}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000425 \hline
Fred Drake38e5d272000-04-03 20:13:55 +0000426 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(2)}
427 \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(2), (3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000428 \hline
429 \lineiii{len(\var{s})}{length of \var{s}}{}
430 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
431 \lineiii{max(\var{s})}{largest item of \var{s}}{}
432\end{tableiii}
433\indexiii{operations on}{sequence}{types}
434\bifuncindex{len}
435\bifuncindex{min}
436\bifuncindex{max}
437\indexii{concatenation}{operation}
438\indexii{repetition}{operation}
439\indexii{subscript}{operation}
440\indexii{slice}{operation}
441\opindex{in}
442\opindex{not in}
443
444\noindent
445Notes:
446
447\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000448\item[(1)] Values of \var{n} less than \code{0} are treated as
449 \code{0} (which yields an empty sequence of the same type as
Fred Draked800cff2001-08-28 14:56:05 +0000450 \var{s}). Note also that the copies are shallow; nested structures
451 are not copied. This often haunts new Python programmers; consider:
452
453\begin{verbatim}
454>>> lists = [[]] * 3
455>>> lists
456[[], [], []]
457>>> lists[0].append(3)
458>>> lists
459[[3], [3], [3]]
460\end{verbatim}
461
462 What has happened is that \code{lists} is a list containing three
463 copies of the list \code{[[]]} (a one-element list containing an
464 empty list), but the contained list is shared by each copy. You can
465 create a list of different lists this way:
466
467\begin{verbatim}
468>>> lists = [[] for i in range(3)]
469>>> lists[0].append(3)
470>>> lists[1].append(5)
471>>> lists[2].append(7)
472>>> lists
473[[3], [5], [7]]
474\end{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000475
476\item[(2)] If \var{i} or \var{j} is negative, the index is relative to
Fred Drake907e76b2001-07-06 20:30:11 +0000477 the end of the string: \code{len(\var{s}) + \var{i}} or
Fred Drake64e3b431998-07-24 13:56:11 +0000478 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
479 still \code{0}.
Tim Peters8f01b682002-03-12 03:04:44 +0000480
Fred Drake38e5d272000-04-03 20:13:55 +0000481\item[(3)] The slice of \var{s} from \var{i} to \var{j} is defined as
Fred Drake64e3b431998-07-24 13:56:11 +0000482 the sequence of items with index \var{k} such that \code{\var{i} <=
483 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
484 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
485 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
486 \var{i} is greater than or equal to \var{j}, the slice is empty.
Fred Drake64e3b431998-07-24 13:56:11 +0000487\end{description}
488
Fred Drake9474d861999-02-12 22:05:33 +0000489
Fred Drake4de96c22000-08-12 03:36:23 +0000490\subsubsection{String Methods \label{string-methods}}
491
492These are the string methods which both 8-bit strings and Unicode
493objects support:
494
495\begin{methoddesc}[string]{capitalize}{}
496Return a copy of the string with only its first character capitalized.
497\end{methoddesc}
498
499\begin{methoddesc}[string]{center}{width}
500Return centered in a string of length \var{width}. Padding is done
501using spaces.
502\end{methoddesc}
503
504\begin{methoddesc}[string]{count}{sub\optional{, start\optional{, end}}}
505Return the number of occurrences of substring \var{sub} in string
506S\code{[\var{start}:\var{end}]}. Optional arguments \var{start} and
507\var{end} are interpreted as in slice notation.
508\end{methoddesc}
509
Fred Drake6048ce92001-12-10 16:43:08 +0000510\begin{methoddesc}[string]{decode}{\optional{encoding\optional{, errors}}}
511Decodes the string using the codec registered for \var{encoding}.
512\var{encoding} defaults to the default string encoding. \var{errors}
513may be given to set a different error handling scheme. The default is
514\code{'strict'}, meaning that encoding errors raise
515\exception{ValueError}. Other possible values are \code{'ignore'} and
516\code{replace'}.
517\versionadded{2.2}
518\end{methoddesc}
519
Fred Drake4de96c22000-08-12 03:36:23 +0000520\begin{methoddesc}[string]{encode}{\optional{encoding\optional{,errors}}}
521Return an encoded version of the string. Default encoding is the current
522default string encoding. \var{errors} may be given to set a different
523error handling scheme. The default for \var{errors} is
524\code{'strict'}, meaning that encoding errors raise a
525\exception{ValueError}. Other possible values are \code{'ignore'} and
526\code{'replace'}.
Fred Drake1dba66c2000-10-25 21:03:55 +0000527\versionadded{2.0}
Fred Drake4de96c22000-08-12 03:36:23 +0000528\end{methoddesc}
529
530\begin{methoddesc}[string]{endswith}{suffix\optional{, start\optional{, end}}}
531Return true if the string ends with the specified \var{suffix},
532otherwise return false. With optional \var{start}, test beginning at
533that position. With optional \var{end}, stop comparing at that position.
534\end{methoddesc}
535
536\begin{methoddesc}[string]{expandtabs}{\optional{tabsize}}
537Return a copy of the string where all tab characters are expanded
538using spaces. If \var{tabsize} is not given, a tab size of \code{8}
539characters is assumed.
540\end{methoddesc}
541
542\begin{methoddesc}[string]{find}{sub\optional{, start\optional{, end}}}
543Return the lowest index in the string where substring \var{sub} is
544found, such that \var{sub} is contained in the range [\var{start},
545\var{end}). Optional arguments \var{start} and \var{end} are
546interpreted as in slice notation. Return \code{-1} if \var{sub} is
547not found.
548\end{methoddesc}
549
550\begin{methoddesc}[string]{index}{sub\optional{, start\optional{, end}}}
551Like \method{find()}, but raise \exception{ValueError} when the
552substring is not found.
553\end{methoddesc}
554
555\begin{methoddesc}[string]{isalnum}{}
556Return true if all characters in the string are alphanumeric and there
557is at least one character, false otherwise.
558\end{methoddesc}
559
560\begin{methoddesc}[string]{isalpha}{}
561Return true if all characters in the string are alphabetic and there
562is at least one character, false otherwise.
563\end{methoddesc}
564
565\begin{methoddesc}[string]{isdigit}{}
566Return true if there are only digit characters, false otherwise.
567\end{methoddesc}
568
569\begin{methoddesc}[string]{islower}{}
570Return true if all cased characters in the string are lowercase and
571there is at least one cased character, false otherwise.
572\end{methoddesc}
573
574\begin{methoddesc}[string]{isspace}{}
575Return true if there are only whitespace characters in the string and
576the string is not empty, false otherwise.
577\end{methoddesc}
578
579\begin{methoddesc}[string]{istitle}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000580Return true if the string is a titlecased string: uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000581characters may only follow uncased characters and lowercase characters
582only cased ones. Return false otherwise.
583\end{methoddesc}
584
585\begin{methoddesc}[string]{isupper}{}
586Return true if all cased characters in the string are uppercase and
587there is at least one cased character, false otherwise.
588\end{methoddesc}
589
590\begin{methoddesc}[string]{join}{seq}
591Return a string which is the concatenation of the strings in the
592sequence \var{seq}. The separator between elements is the string
593providing this method.
594\end{methoddesc}
595
596\begin{methoddesc}[string]{ljust}{width}
597Return the string left justified in a string of length \var{width}.
598Padding is done using spaces. The original string is returned if
599\var{width} is less than \code{len(\var{s})}.
600\end{methoddesc}
601
602\begin{methoddesc}[string]{lower}{}
603Return a copy of the string converted to lowercase.
604\end{methoddesc}
605
Fred Drake8b1c47b2002-04-13 02:43:39 +0000606\begin{methoddesc}[string]{lstrip}{\optional{chars}}
607Return a copy of the string with leading characters removed. If
608\var{chars} is omitted or \code{None}, whitespace characters are
609removed. If given and not \code{None}, \var{chars} must be a string;
610the characters in the string will be stripped from the beginning of
611the string this method is called on.
Fred Drake4de96c22000-08-12 03:36:23 +0000612\end{methoddesc}
613
614\begin{methoddesc}[string]{replace}{old, new\optional{, maxsplit}}
615Return a copy of the string with all occurrences of substring
616\var{old} replaced by \var{new}. If the optional argument
617\var{maxsplit} is given, only the first \var{maxsplit} occurrences are
618replaced.
619\end{methoddesc}
620
621\begin{methoddesc}[string]{rfind}{sub \optional{,start \optional{,end}}}
622Return the highest index in the string where substring \var{sub} is
623found, such that \var{sub} is contained within s[start,end]. Optional
624arguments \var{start} and \var{end} are interpreted as in slice
625notation. Return \code{-1} on failure.
626\end{methoddesc}
627
628\begin{methoddesc}[string]{rindex}{sub\optional{, start\optional{, end}}}
629Like \method{rfind()} but raises \exception{ValueError} when the
630substring \var{sub} is not found.
631\end{methoddesc}
632
633\begin{methoddesc}[string]{rjust}{width}
634Return the string right justified in a string of length \var{width}.
635Padding is done using spaces. The original string is returned if
636\var{width} is less than \code{len(\var{s})}.
637\end{methoddesc}
638
Fred Drake8b1c47b2002-04-13 02:43:39 +0000639\begin{methoddesc}[string]{rstrip}{\optional{chars}}
640Return a copy of the string with trailing characters removed. If
641\var{chars} is omitted or \code{None}, whitespace characters are
642removed. If given and not \code{None}, \var{chars} must be a string;
643the characters in the string will be stripped from the end of the
644string this method is called on.
Fred Drake4de96c22000-08-12 03:36:23 +0000645\end{methoddesc}
646
647\begin{methoddesc}[string]{split}{\optional{sep \optional{,maxsplit}}}
648Return a list of the words in the string, using \var{sep} as the
649delimiter string. If \var{maxsplit} is given, at most \var{maxsplit}
650splits are done. If \var{sep} is not specified or \code{None}, any
651whitespace string is a separator.
652\end{methoddesc}
653
654\begin{methoddesc}[string]{splitlines}{\optional{keepends}}
655Return a list of the lines in the string, breaking at line
656boundaries. Line breaks are not included in the resulting list unless
657\var{keepends} is given and true.
658\end{methoddesc}
659
Fred Drake8b1c47b2002-04-13 02:43:39 +0000660\begin{methoddesc}[string]{startswith}{prefix\optional{,
661 start\optional{, end}}}
Fred Drake4de96c22000-08-12 03:36:23 +0000662Return true if string starts with the \var{prefix}, otherwise
663return false. With optional \var{start}, test string beginning at
664that position. With optional \var{end}, stop comparing string at that
665position.
666\end{methoddesc}
667
Fred Drake8b1c47b2002-04-13 02:43:39 +0000668\begin{methoddesc}[string]{strip}{\optional{chars}}
669Return a copy of the string with leading and trailing characters
670removed. If \var{chars} is omitted or \code{None}, whitespace
671characters are removed. If given and not \code{None}, \var{chars}
672must be a string; the characters in the string will be stripped from
673the both ends of the string this method is called on.
Fred Drake4de96c22000-08-12 03:36:23 +0000674\end{methoddesc}
675
676\begin{methoddesc}[string]{swapcase}{}
677Return a copy of the string with uppercase characters converted to
678lowercase and vice versa.
679\end{methoddesc}
680
681\begin{methoddesc}[string]{title}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000682Return a titlecased version of the string: words start with uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000683characters, all remaining cased characters are lowercase.
684\end{methoddesc}
685
686\begin{methoddesc}[string]{translate}{table\optional{, deletechars}}
687Return a copy of the string where all characters occurring in the
688optional argument \var{deletechars} are removed, and the remaining
689characters have been mapped through the given translation table, which
690must be a string of length 256.
691\end{methoddesc}
692
693\begin{methoddesc}[string]{upper}{}
694Return a copy of the string converted to uppercase.
695\end{methoddesc}
696
697
698\subsubsection{String Formatting Operations \label{typesseq-strings}}
Fred Drake64e3b431998-07-24 13:56:11 +0000699
Fred Drakeb38784e2001-12-03 22:15:56 +0000700\index{formatting, string (\%{})}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000701\index{interpolation, string (\%{})}
Fred Drake66d32b12000-09-14 17:57:42 +0000702\index{string!formatting}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000703\index{string!interpolation}
Fred Drake66d32b12000-09-14 17:57:42 +0000704\index{printf-style formatting}
705\index{sprintf-style formatting}
Fred Drakeb38784e2001-12-03 22:15:56 +0000706\index{\protect\%{} formatting}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000707\index{\protect\%{} interpolation}
Fred Drake66d32b12000-09-14 17:57:42 +0000708
Fred Drake8c071d42001-01-26 20:48:35 +0000709String and Unicode objects have one unique built-in operation: the
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000710\code{\%} operator (modulo). This is also known as the string
711\emph{formatting} or \emph{interpolation} operator. Given
712\code{\var{format} \% \var{values}} (where \var{format} is a string or
713Unicode object), \code{\%} conversion specifications in \var{format}
714are replaced with zero or more elements of \var{values}. The effect
715is similar to the using \cfunction{sprintf()} in the C language. If
716\var{format} is a Unicode object, or if any of the objects being
717converted using the \code{\%s} conversion are Unicode objects, the
718result will be a Unicode object as well.
Fred Drake64e3b431998-07-24 13:56:11 +0000719
Fred Drake8c071d42001-01-26 20:48:35 +0000720If \var{format} requires a single argument, \var{values} may be a
721single non-tuple object. \footnote{A tuple object in this case should
722 be a singleton.} Otherwise, \var{values} must be a tuple with
723exactly the number of items specified by the format string, or a
724single mapping object (for example, a dictionary).
Fred Drake64e3b431998-07-24 13:56:11 +0000725
Fred Drake8c071d42001-01-26 20:48:35 +0000726A conversion specifier contains two or more characters and has the
727following components, which must occur in this order:
728
729\begin{enumerate}
730 \item The \character{\%} character, which marks the start of the
731 specifier.
732 \item Mapping key value (optional), consisting of an identifier in
733 parentheses (for example, \code{(somename)}).
734 \item Conversion flags (optional), which affect the result of some
735 conversion types.
736 \item Minimum field width (optional). If specified as an
737 \character{*} (asterisk), the actual width is read from the
738 next element of the tuple in \var{values}, and the object to
739 convert comes after the minimum field width and optional
740 precision.
741 \item Precision (optional), given as a \character{.} (dot) followed
742 by the precision. If specified as \character{*} (an
743 asterisk), the actual width is read from the next element of
744 the tuple in \var{values}, and the value to convert comes after
745 the precision.
746 \item Length modifier (optional).
747 \item Conversion type.
748\end{enumerate}
Fred Drake64e3b431998-07-24 13:56:11 +0000749
750If the right argument is a dictionary (or any kind of mapping), then
Fred Drake8c071d42001-01-26 20:48:35 +0000751the formats in the string \emph{must} have a parenthesized key into
752that dictionary inserted immediately after the \character{\%}
753character, and each format formats the corresponding entry from the
754mapping. For example:
Fred Drake64e3b431998-07-24 13:56:11 +0000755
756\begin{verbatim}
757>>> count = 2
758>>> language = 'Python'
759>>> print '%(language)s has %(count)03d quote types.' % vars()
760Python has 002 quote types.
761\end{verbatim}
762
763In this case no \code{*} specifiers may occur in a format (since they
764require a sequential parameter list).
765
Fred Drake8c071d42001-01-26 20:48:35 +0000766The conversion flag characters are:
767
768\begin{tableii}{c|l}{character}{Flag}{Meaning}
769 \lineii{\#}{The value conversion will use the ``alternate form''
770 (where defined below).}
771 \lineii{0}{The conversion will be zero padded.}
772 \lineii{-}{The converted value is left adjusted (overrides
773 \character{-}).}
774 \lineii{{~}}{(a space) A blank should be left before a positive number
775 (or empty string) produced by a signed conversion.}
776 \lineii{+}{A sign character (\character{+} or \character{-}) will
777 precede the conversion (overrides a "space" flag).}
778\end{tableii}
779
780The length modifier may be \code{h}, \code{l}, and \code{L} may be
781present, but are ignored as they are not necessary for Python.
782
783The conversion types are:
784
785\begin{tableii}{c|l}{character}{Conversion}{Meaning}
786 \lineii{d}{Signed integer decimal.}
787 \lineii{i}{Signed integer decimal.}
788 \lineii{o}{Unsigned octal.}
789 \lineii{u}{Unsigned decimal.}
790 \lineii{x}{Unsigned hexidecimal (lowercase).}
791 \lineii{X}{Unsigned hexidecimal (uppercase).}
792 \lineii{e}{Floating point exponential format (lowercase).}
793 \lineii{E}{Floating point exponential format (uppercase).}
794 \lineii{f}{Floating point decimal format.}
795 \lineii{F}{Floating point decimal format.}
796 \lineii{g}{Same as \character{e} if exponent is greater than -4 or
797 less than precision, \character{f} otherwise.}
798 \lineii{G}{Same as \character{E} if exponent is greater than -4 or
799 less than precision, \character{F} otherwise.}
800 \lineii{c}{Single character (accepts integer or single character
801 string).}
802 \lineii{r}{String (converts any python object using
803 \function{repr()}).}
804 \lineii{s}{String (converts any python object using
805 \function{str()}).}
806 \lineii{\%}{No argument is converted, results in a \character{\%}
807 character in the result. (The complete specification is
808 \code{\%\%}.)}
809\end{tableii}
810
811% XXX Examples?
812
813
814Since Python strings have an explicit length, \code{\%s} conversions
815do not assume that \code{'\e0'} is the end of the string.
816
817For safety reasons, floating point precisions are clipped to 50;
818\code{\%f} conversions for numbers whose absolute value is over 1e25
819are replaced by \code{\%g} conversions.\footnote{
820 These numbers are fairly arbitrary. They are intended to
821 avoid printing endless strings of meaningless digits without hampering
822 correct use and without having to know the exact precision of floating
823 point values on a particular machine.
824} All other errors raise exceptions.
825
Fred Drake14f5c5f2001-12-03 18:33:13 +0000826Additional string operations are defined in standard modules
827\refmodule{string}\refstmodindex{string} and
Tim Peters8f01b682002-03-12 03:04:44 +0000828\refmodule{re}.\refstmodindex{re}
Fred Drake64e3b431998-07-24 13:56:11 +0000829
Fred Drake107b9672000-08-14 15:37:59 +0000830
Fred Drake512bb722000-08-18 03:12:38 +0000831\subsubsection{XRange Type \label{typesseq-xrange}}
Fred Drake107b9672000-08-14 15:37:59 +0000832
Fred Drake0b4e25d2000-10-04 04:21:19 +0000833The xrange\obindex{xrange} type is an immutable sequence which is
Fred Drake512bb722000-08-18 03:12:38 +0000834commonly used for looping. The advantage of the xrange type is that an
835xrange object will always take the same amount of memory, no matter the
Fred Drake107b9672000-08-14 15:37:59 +0000836size of the range it represents. There are no consistent performance
837advantages.
838
Guido van Rossum3f561662001-07-05 13:27:48 +0000839XRange objects have very little behavior: they only support indexing
840and the \function{len()} function.
Fred Drake107b9672000-08-14 15:37:59 +0000841
842
Fred Drake9474d861999-02-12 22:05:33 +0000843\subsubsection{Mutable Sequence Types \label{typesseq-mutable}}
Fred Drake64e3b431998-07-24 13:56:11 +0000844
845List objects support additional operations that allow in-place
846modification of the object.
847These operations would be supported by other mutable sequence types
848(when added to the language) as well.
849Strings and tuples are immutable sequence types and such objects cannot
850be modified once created.
851The following operations are defined on mutable sequence types (where
852\var{x} is an arbitrary object):
853\indexiii{mutable}{sequence}{types}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000854\obindex{list}
Fred Drake64e3b431998-07-24 13:56:11 +0000855
856\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
857 \lineiii{\var{s}[\var{i}] = \var{x}}
858 {item \var{i} of \var{s} is replaced by \var{x}}{}
859 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
860 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
861 \lineiii{del \var{s}[\var{i}:\var{j}]}
862 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
863 \lineiii{\var{s}.append(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000864 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{(1)}
Barry Warsawafd974c1998-10-09 16:39:58 +0000865 \lineiii{\var{s}.extend(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000866 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +0000867 \lineiii{\var{s}.count(\var{x})}
868 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
869 \lineiii{\var{s}.index(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000870 {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000871 \lineiii{\var{s}.insert(\var{i}, \var{x})}
872 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
Fred Drakeef428a22001-10-26 18:57:14 +0000873 if \code{\var{i} >= 0}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000874 \lineiii{\var{s}.pop(\optional{\var{i}})}
Fred Drakeef428a22001-10-26 18:57:14 +0000875 {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(5)}
Fred Drake64e3b431998-07-24 13:56:11 +0000876 \lineiii{\var{s}.remove(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000877 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000878 \lineiii{\var{s}.reverse()}
Fred Drakeef428a22001-10-26 18:57:14 +0000879 {reverses the items of \var{s} in place}{(6)}
Fred Drake64e3b431998-07-24 13:56:11 +0000880 \lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
Fred Drakeef428a22001-10-26 18:57:14 +0000881 {sort the items of \var{s} in place}{(6), (7)}
Fred Drake64e3b431998-07-24 13:56:11 +0000882\end{tableiii}
883\indexiv{operations on}{mutable}{sequence}{types}
884\indexiii{operations on}{sequence}{types}
885\indexiii{operations on}{list}{type}
886\indexii{subscript}{assignment}
887\indexii{slice}{assignment}
888\stindex{del}
Fred Drake9474d861999-02-12 22:05:33 +0000889\withsubitem{(list method)}{
Fred Drake68921df1999-08-09 17:05:12 +0000890 \ttindex{append()}\ttindex{extend()}\ttindex{count()}\ttindex{index()}
891 \ttindex{insert()}\ttindex{pop()}\ttindex{remove()}\ttindex{reverse()}
Fred Drakee8391991998-11-25 17:09:19 +0000892 \ttindex{sort()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000893\noindent
894Notes:
895\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000896\item[(1)] The C implementation of Python has historically accepted
897 multiple parameters and implicitly joined them into a tuple; this
Fred Drake30f76ff2000-06-30 16:06:19 +0000898 no longer works in Python 2.0. Use of this misfeature has been
Fred Drake38e5d272000-04-03 20:13:55 +0000899 deprecated since Python 1.4.
900
Tim Peters8f01b682002-03-12 03:04:44 +0000901\item[(2)] Raises an exception when \var{x} is not a list object. The
Fred Drake38e5d272000-04-03 20:13:55 +0000902 \method{extend()} method is experimental and not supported by
903 mutable sequence types other than lists.
904
905\item[(3)] Raises \exception{ValueError} when \var{x} is not found in
Fred Drake68921df1999-08-09 17:05:12 +0000906 \var{s}.
907
Fred Drakeef428a22001-10-26 18:57:14 +0000908\item[(4)] When a negative index is passed as the first parameter to
909 the \method{insert()} method, the new element is prepended to the
910 sequence.
911
912\item[(5)] The \method{pop()} method is only supported by the list and
Fred Drakefbd3b452000-07-31 23:42:23 +0000913 array types. The optional argument \var{i} defaults to \code{-1},
914 so that by default the last item is removed and returned.
Fred Drake38e5d272000-04-03 20:13:55 +0000915
Fred Drakeef428a22001-10-26 18:57:14 +0000916\item[(6)] The \method{sort()} and \method{reverse()} methods modify the
Fred Drake38e5d272000-04-03 20:13:55 +0000917 list in place for economy of space when sorting or reversing a large
Skip Montanaro41d7d582001-07-25 16:18:19 +0000918 list. To remind you that they operate by side effect, they don't return
919 the sorted or reversed list.
Fred Drake38e5d272000-04-03 20:13:55 +0000920
Fred Drakeef428a22001-10-26 18:57:14 +0000921\item[(7)] The \method{sort()} method takes an optional argument
Fred Drake64e3b431998-07-24 13:56:11 +0000922 specifying a comparison function of two arguments (list items) which
Tim Peters599db7d2001-09-29 01:08:19 +0000923 should return a negative, zero or positive number depending on whether
Fred Drake68921df1999-08-09 17:05:12 +0000924 the first argument is considered smaller than, equal to, or larger
925 than the second argument. Note that this slows the sorting process
926 down considerably; e.g. to sort a list in reverse order it is much
927 faster to use calls to the methods \method{sort()} and
928 \method{reverse()} than to use the built-in function
929 \function{sort()} with a comparison function that reverses the
930 ordering of the elements.
Fred Drake64e3b431998-07-24 13:56:11 +0000931\end{description}
932
933
Fred Drake7a2f0661998-09-10 18:25:58 +0000934\subsection{Mapping Types \label{typesmapping}}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000935\obindex{mapping}
936\obindex{dictionary}
Fred Drake64e3b431998-07-24 13:56:11 +0000937
938A \dfn{mapping} object maps values of one type (the key type) to
939arbitrary objects. Mappings are mutable objects. There is currently
940only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
941almost arbitrary values. The only types of values not acceptable as
942keys are values containing lists or dictionaries or other mutable
943types that are compared by value rather than by object identity.
944Numeric types used for keys obey the normal rules for numeric
945comparison: if two numbers compare equal (e.g. \code{1} and
946\code{1.0}) then they can be used interchangeably to index the same
947dictionary entry.
948
Fred Drake64e3b431998-07-24 13:56:11 +0000949Dictionaries are created by placing a comma-separated list of
950\code{\var{key}: \var{value}} pairs within braces, for example:
951\code{\{'jack': 4098, 'sjoerd': 4127\}} or
952\code{\{4098: 'jack', 4127: 'sjoerd'\}}.
953
Fred Drake9c5cc141999-06-10 22:37:34 +0000954The following operations are defined on mappings (where \var{a} and
955\var{b} are mappings, \var{k} is a key, and \var{v} and \var{x} are
956arbitrary objects):
Fred Drake64e3b431998-07-24 13:56:11 +0000957\indexiii{operations on}{mapping}{types}
958\indexiii{operations on}{dictionary}{type}
959\stindex{del}
960\bifuncindex{len}
Fred Drake9474d861999-02-12 22:05:33 +0000961\withsubitem{(dictionary method)}{
962 \ttindex{clear()}
963 \ttindex{copy()}
964 \ttindex{has_key()}
965 \ttindex{items()}
966 \ttindex{keys()}
967 \ttindex{update()}
968 \ttindex{values()}
Fred Drakee8391991998-11-25 17:09:19 +0000969 \ttindex{get()}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000970
971\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
972 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
973 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
Fred Drake1e75e172000-07-31 16:34:46 +0000974 \lineiii{\var{a}[\var{k}] = \var{v}}
975 {set \code{\var{a}[\var{k}]} to \var{v}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000976 {}
977 \lineiii{del \var{a}[\var{k}]}
978 {remove \code{\var{a}[\var{k}]} from \var{a}}
979 {(1)}
980 \lineiii{\var{a}.clear()}{remove all items from \code{a}}{}
981 \lineiii{\var{a}.copy()}{a (shallow) copy of \code{a}}{}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +0000982 \lineiii{\var{a}.has_key(\var{k})}
Fred Drake9c5cc141999-06-10 22:37:34 +0000983 {\code{1} if \var{a} has a key \var{k}, else \code{0}}
984 {}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +0000985 \lineiii{\var{k} \code{in} \var{a}}
986 {Equivalent to \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000987 {(2)}
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000988 \lineiii{\var{k} not in \var{a}}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +0000989 {Equivalent to \code{not} \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000990 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000991 \lineiii{\var{a}.items()}
992 {a copy of \var{a}'s list of (\var{key}, \var{value}) pairs}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000993 {(3)}
Fred Drake4a6c5c52001-06-12 03:31:56 +0000994 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000995 \lineiii{\var{a}.update(\var{b})}
Fred Drake1e75e172000-07-31 16:34:46 +0000996 {\code{for k in \var{b}.keys(): \var{a}[k] = \var{b}[k]}}
Barry Warsawe9218a12001-06-26 20:32:59 +0000997 {}
Fred Drake4a6c5c52001-06-12 03:31:56 +0000998 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000999 \lineiii{\var{a}.get(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +00001000 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Fred Drake9c5cc141999-06-10 22:37:34 +00001001 else \var{x}}
Barry Warsawe9218a12001-06-26 20:32:59 +00001002 {(4)}
Guido van Rossum8141cf52000-08-08 16:15:49 +00001003 \lineiii{\var{a}.setdefault(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +00001004 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Guido van Rossum8141cf52000-08-08 16:15:49 +00001005 else \var{x} (also setting it)}
Barry Warsawe9218a12001-06-26 20:32:59 +00001006 {(5)}
Guido van Rossume027d982002-04-12 15:11:59 +00001007 \lineiii{\var{a}.pop(\var{k})}
1008 {remove specified \var{key} and return corresponding \var{value}}
1009 {}
Guido van Rossumff63f202000-12-12 22:03:47 +00001010 \lineiii{\var{a}.popitem()}
1011 {remove and return an arbitrary (\var{key}, \var{value}) pair}
Barry Warsawe9218a12001-06-26 20:32:59 +00001012 {(6)}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001013 \lineiii{\var{a}.iteritems()}
1014 {return an iterator over (\var{key}, \var{value}) pairs}
1015 {(2)}
1016 \lineiii{\var{a}.iterkeys()}
1017 {return an iterator over the mapping's keys}
1018 {(2)}
1019 \lineiii{\var{a}.itervalues()}
1020 {return an iterator over the mapping's values}
1021 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001022\end{tableiii}
1023
Fred Drake64e3b431998-07-24 13:56:11 +00001024\noindent
1025Notes:
1026\begin{description}
Fred Drake9c5cc141999-06-10 22:37:34 +00001027\item[(1)] Raises a \exception{KeyError} exception if \var{k} is not
1028in the map.
Fred Drake64e3b431998-07-24 13:56:11 +00001029
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001030\item[(2)] \versionadded{2.2}
1031
1032\item[(3)] Keys and values are listed in random order. If
Fred Drake38e5d272000-04-03 20:13:55 +00001033\method{keys()} and \method{values()} are called with no intervening
1034modifications to the dictionary, the two lists will directly
1035correspond. This allows the creation of \code{(\var{value},
Fred Drake4a6c5c52001-06-12 03:31:56 +00001036\var{key})} pairs using \function{zip()}: \samp{pairs =
1037zip(\var{a}.values(), \var{a}.keys())}.
Fred Drake64e3b431998-07-24 13:56:11 +00001038
Barry Warsawe9218a12001-06-26 20:32:59 +00001039\item[(4)] Never raises an exception if \var{k} is not in the map,
Fred Drake38e5d272000-04-03 20:13:55 +00001040instead it returns \var{x}. \var{x} is optional; when \var{x} is not
Fred Drake9c5cc141999-06-10 22:37:34 +00001041provided and \var{k} is not in the map, \code{None} is returned.
Guido van Rossum8141cf52000-08-08 16:15:49 +00001042
Barry Warsawe9218a12001-06-26 20:32:59 +00001043\item[(5)] \function{setdefault()} is like \function{get()}, except
Guido van Rossum8141cf52000-08-08 16:15:49 +00001044that if \var{k} is missing, \var{x} is both returned and inserted into
1045the dictionary as the value of \var{k}.
Guido van Rossumff63f202000-12-12 22:03:47 +00001046
Barry Warsawe9218a12001-06-26 20:32:59 +00001047\item[(6)] \function{popitem()} is useful to destructively iterate
Guido van Rossumff63f202000-12-12 22:03:47 +00001048over a dictionary, as often used in set algorithms.
Fred Drake64e3b431998-07-24 13:56:11 +00001049\end{description}
1050
1051
Fred Drake99de2182001-10-30 06:23:14 +00001052\subsection{File Objects
1053 \label{bltin-file-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +00001054
Fred Drake99de2182001-10-30 06:23:14 +00001055File objects\obindex{file} are implemented using C's \code{stdio}
1056package and can be created with the built-in constructor
Tim Peters8f01b682002-03-12 03:04:44 +00001057\function{file()}\bifuncindex{file} described in section
Tim Peters003047a2001-10-30 05:54:04 +00001058\ref{built-in-funcs}, ``Built-in Functions.''\footnote{\function{file()}
1059is new in Python 2.2. The older built-in \function{open()} is an
1060alias for \function{file()}.}
1061They are also returned
Fred Drake907e76b2001-07-06 20:30:11 +00001062by some other built-in functions and methods, such as
Fred Drake4de96c22000-08-12 03:36:23 +00001063\function{os.popen()} and \function{os.fdopen()} and the
Fred Drake130072d1998-10-28 20:08:35 +00001064\method{makefile()} method of socket objects.
Fred Drake4de96c22000-08-12 03:36:23 +00001065\refstmodindex{os}
Fred Drake64e3b431998-07-24 13:56:11 +00001066\refbimodindex{socket}
1067
1068When a file operation fails for an I/O-related reason, the exception
Fred Drake84538cd1998-11-30 21:51:25 +00001069\exception{IOError} is raised. This includes situations where the
1070operation is not defined for some reason, like \method{seek()} on a tty
Fred Drake64e3b431998-07-24 13:56:11 +00001071device or writing a file opened for reading.
1072
1073Files have the following methods:
1074
1075
1076\begin{methoddesc}[file]{close}{}
1077 Close the file. A closed file cannot be read or written anymore.
Fred Drakea776cea2000-11-06 20:17:37 +00001078 Any operation which requires that the file be open will raise a
1079 \exception{ValueError} after the file has been closed. Calling
Fred Drake752ba392000-09-19 15:18:51 +00001080 \method{close()} more than once is allowed.
Fred Drake64e3b431998-07-24 13:56:11 +00001081\end{methoddesc}
1082
1083\begin{methoddesc}[file]{flush}{}
Fred Drake752ba392000-09-19 15:18:51 +00001084 Flush the internal buffer, like \code{stdio}'s
1085 \cfunction{fflush()}. This may be a no-op on some file-like
1086 objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001087\end{methoddesc}
1088
1089\begin{methoddesc}[file]{isatty}{}
Neal Norwitz6b353702002-04-09 18:15:00 +00001090 Return \code{True} if the file is connected to a tty(-like) device, else
1091 \code{False}. \note{If a file-like object is not associated
Fred Drake0aa811c2001-10-20 04:24:09 +00001092 with a real file, this method should \emph{not} be implemented.}
Fred Drake64e3b431998-07-24 13:56:11 +00001093\end{methoddesc}
1094
1095\begin{methoddesc}[file]{fileno}{}
Fred Drake752ba392000-09-19 15:18:51 +00001096 \index{file descriptor}
1097 \index{descriptor, file}
1098 Return the integer ``file descriptor'' that is used by the
1099 underlying implementation to request I/O operations from the
1100 operating system. This can be useful for other, lower level
Fred Drake907e76b2001-07-06 20:30:11 +00001101 interfaces that use file descriptors, such as the
1102 \refmodule{fcntl}\refbimodindex{fcntl} module or
Fred Drake0aa811c2001-10-20 04:24:09 +00001103 \function{os.read()} and friends. \note{File-like objects
Fred Drake907e76b2001-07-06 20:30:11 +00001104 which do not have a real file descriptor should \emph{not} provide
Fred Drake0aa811c2001-10-20 04:24:09 +00001105 this method!}
Fred Drake64e3b431998-07-24 13:56:11 +00001106\end{methoddesc}
1107
1108\begin{methoddesc}[file]{read}{\optional{size}}
1109 Read at most \var{size} bytes from the file (less if the read hits
Fred Drakef4cbada1999-04-14 14:31:53 +00001110 \EOF{} before obtaining \var{size} bytes). If the \var{size}
1111 argument is negative or omitted, read all data until \EOF{} is
1112 reached. The bytes are returned as a string object. An empty
1113 string is returned when \EOF{} is encountered immediately. (For
1114 certain files, like ttys, it makes sense to continue reading after
1115 an \EOF{} is hit.) Note that this method may call the underlying
1116 C function \cfunction{fread()} more than once in an effort to
1117 acquire as close to \var{size} bytes as possible.
Fred Drake64e3b431998-07-24 13:56:11 +00001118\end{methoddesc}
1119
1120\begin{methoddesc}[file]{readline}{\optional{size}}
1121 Read one entire line from the file. A trailing newline character is
Fred Drakeea003fc1999-04-05 21:59:15 +00001122 kept in the string\footnote{
Tim Peters8f01b682002-03-12 03:04:44 +00001123 The advantage of leaving the newline on is that an empty string
1124 can be returned to mean \EOF{} without being ambiguous. Another
1125 advantage is that (in cases where it might matter, for example. if you
1126 want to make an exact copy of a file while scanning its lines)
Fred Drake64e3b431998-07-24 13:56:11 +00001127 you can tell whether the last line of a file ended in a newline
Fred Drake4de96c22000-08-12 03:36:23 +00001128 or not (yes this happens!).
1129 } (but may be absent when a file ends with an
Fred Drake64e3b431998-07-24 13:56:11 +00001130 incomplete line). If the \var{size} argument is present and
1131 non-negative, it is a maximum byte count (including the trailing
1132 newline) and an incomplete line may be returned.
1133 An empty string is returned when \EOF{} is hit
Fred Drake0aa811c2001-10-20 04:24:09 +00001134 immediately. \note{Unlike \code{stdio}'s \cfunction{fgets()}, the
Fred Drake752ba392000-09-19 15:18:51 +00001135 returned string contains null characters (\code{'\e 0'}) if they
Fred Drake0aa811c2001-10-20 04:24:09 +00001136 occurred in the input.}
Fred Drake64e3b431998-07-24 13:56:11 +00001137\end{methoddesc}
1138
1139\begin{methoddesc}[file]{readlines}{\optional{sizehint}}
1140 Read until \EOF{} using \method{readline()} and return a list containing
1141 the lines thus read. If the optional \var{sizehint} argument is
Fred Drakec37b65e2001-11-28 07:26:15 +00001142 present, instead of reading up to \EOF, whole lines totalling
Fred Drake64e3b431998-07-24 13:56:11 +00001143 approximately \var{sizehint} bytes (possibly after rounding up to an
Fred Drake752ba392000-09-19 15:18:51 +00001144 internal buffer size) are read. Objects implementing a file-like
1145 interface may choose to ignore \var{sizehint} if it cannot be
1146 implemented, or cannot be implemented efficiently.
Fred Drake64e3b431998-07-24 13:56:11 +00001147\end{methoddesc}
1148
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001149\begin{methoddesc}[file]{xreadlines}{}
Fred Drake82f93c62001-04-22 01:56:51 +00001150 Equivalent to
1151 \function{xreadlines.xreadlines(\var{file})}.\refstmodindex{xreadlines}
1152 (See the \refmodule{xreadlines} module for more information.)
1153 \versionadded{2.1}
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001154\end{methoddesc}
1155
Fred Drake64e3b431998-07-24 13:56:11 +00001156\begin{methoddesc}[file]{seek}{offset\optional{, whence}}
1157 Set the file's current position, like \code{stdio}'s \cfunction{fseek()}.
1158 The \var{whence} argument is optional and defaults to \code{0}
1159 (absolute file positioning); other values are \code{1} (seek
1160 relative to the current position) and \code{2} (seek relative to the
Fred Drake19ae7832001-01-04 05:16:39 +00001161 file's end). There is no return value. Note that if the file is
1162 opened for appending (mode \code{'a'} or \code{'a+'}), any
1163 \method{seek()} operations will be undone at the next write. If the
1164 file is only opened for writing in append mode (mode \code{'a'}),
1165 this method is essentially a no-op, but it remains useful for files
1166 opened in append mode with reading enabled (mode \code{'a+'}).
Fred Drake64e3b431998-07-24 13:56:11 +00001167\end{methoddesc}
1168
1169\begin{methoddesc}[file]{tell}{}
1170 Return the file's current position, like \code{stdio}'s
1171 \cfunction{ftell()}.
1172\end{methoddesc}
1173
1174\begin{methoddesc}[file]{truncate}{\optional{size}}
Tim Peters8f01b682002-03-12 03:04:44 +00001175 Truncate the file's size. If the optional \var{size} argument is
Fred Drake752ba392000-09-19 15:18:51 +00001176 present, the file is truncated to (at most) that size. The size
Tim Peters8f01b682002-03-12 03:04:44 +00001177 defaults to the current position. The current file position is
1178 not changed. Note that if a specified size exceeds the file's
1179 current size, the result is platform-dependent: possibilities
1180 include that file may remain unchanged, increase to the specified
1181 size as if zero-filled, or increase to the specified size with
1182 undefined new content.
Tim Petersfb05db22002-03-11 00:24:00 +00001183 Availability: Windows, many \UNIX variants.
Fred Drake64e3b431998-07-24 13:56:11 +00001184\end{methoddesc}
1185
1186\begin{methoddesc}[file]{write}{str}
Fred Drake0aa811c2001-10-20 04:24:09 +00001187 Write a string to the file. There is no return value. Due to
Fred Drake3c48ef72001-01-09 22:47:46 +00001188 buffering, the string may not actually show up in the file until
1189 the \method{flush()} or \method{close()} method is called.
Fred Drake64e3b431998-07-24 13:56:11 +00001190\end{methoddesc}
1191
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001192\begin{methoddesc}[file]{writelines}{sequence}
1193 Write a sequence of strings to the file. The sequence can be any
1194 iterable object producing strings, typically a list of strings.
1195 There is no return value.
Fred Drake3c48ef72001-01-09 22:47:46 +00001196 (The name is intended to match \method{readlines()};
1197 \method{writelines()} does not add line separators.)
1198\end{methoddesc}
1199
Fred Drake64e3b431998-07-24 13:56:11 +00001200
Fred Drake038d2642001-09-22 04:34:48 +00001201Files support the iterator protocol. Each iteration returns the same
1202result as \code{\var{file}.readline()}, and iteration ends when the
1203\method{readline()} method returns an empty string.
1204
1205
Fred Drake752ba392000-09-19 15:18:51 +00001206File objects also offer a number of other interesting attributes.
1207These are not required for file-like objects, but should be
1208implemented if they make sense for the particular object.
Fred Drake64e3b431998-07-24 13:56:11 +00001209
1210\begin{memberdesc}[file]{closed}
Neal Norwitz6b353702002-04-09 18:15:00 +00001211bool indicating the current state of the file object. This is a
Fred Drake64e3b431998-07-24 13:56:11 +00001212read-only attribute; the \method{close()} method changes the value.
Fred Drake752ba392000-09-19 15:18:51 +00001213It may not be available on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001214\end{memberdesc}
1215
1216\begin{memberdesc}[file]{mode}
1217The I/O mode for the file. If the file was created using the
1218\function{open()} built-in function, this will be the value of the
Fred Drake752ba392000-09-19 15:18:51 +00001219\var{mode} parameter. This is a read-only attribute and may not be
1220present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001221\end{memberdesc}
1222
1223\begin{memberdesc}[file]{name}
1224If the file object was created using \function{open()}, the name of
1225the file. Otherwise, some string that indicates the source of the
1226file object, of the form \samp{<\mbox{\ldots}>}. This is a read-only
Fred Drake752ba392000-09-19 15:18:51 +00001227attribute and may not be present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001228\end{memberdesc}
1229
1230\begin{memberdesc}[file]{softspace}
1231Boolean that indicates whether a space character needs to be printed
1232before another value when using the \keyword{print} statement.
1233Classes that are trying to simulate a file object should also have a
1234writable \member{softspace} attribute, which should be initialized to
Fred Drake66571cc2000-09-09 03:30:34 +00001235zero. This will be automatic for most classes implemented in Python
1236(care may be needed for objects that override attribute access); types
1237implemented in C will have to provide a writable
1238\member{softspace} attribute.
Fred Drake0aa811c2001-10-20 04:24:09 +00001239\note{This attribute is not used to control the
Fred Drake51f53df2000-09-20 04:48:20 +00001240\keyword{print} statement, but to allow the implementation of
Fred Drake0aa811c2001-10-20 04:24:09 +00001241\keyword{print} to keep track of its internal state.}
Fred Drake64e3b431998-07-24 13:56:11 +00001242\end{memberdesc}
1243
Fred Drakea776cea2000-11-06 20:17:37 +00001244
Fred Drake99de2182001-10-30 06:23:14 +00001245\subsection{Other Built-in Types \label{typesother}}
1246
1247The interpreter supports several other kinds of objects.
1248Most of these support only one or two operations.
1249
1250
1251\subsubsection{Modules \label{typesmodules}}
1252
1253The only special operation on a module is attribute access:
1254\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name}
1255accesses a name defined in \var{m}'s symbol table. Module attributes
1256can be assigned to. (Note that the \keyword{import} statement is not,
1257strictly speaking, an operation on a module object; \code{import
1258\var{foo}} does not require a module object named \var{foo} to exist,
1259rather it requires an (external) \emph{definition} for a module named
1260\var{foo} somewhere.)
1261
1262A special member of every module is \member{__dict__}.
1263This is the dictionary containing the module's symbol table.
1264Modifying this dictionary will actually change the module's symbol
1265table, but direct assignment to the \member{__dict__} attribute is not
1266possible (you can write \code{\var{m}.__dict__['a'] = 1}, which
1267defines \code{\var{m}.a} to be \code{1}, but you can't write
1268\code{\var{m}.__dict__ = \{\}}.
1269
1270Modules built into the interpreter are written like this:
1271\code{<module 'sys' (built-in)>}. If loaded from a file, they are
1272written as \code{<module 'os' from
1273'/usr/local/lib/python\shortversion/os.pyc'>}.
1274
1275
1276\subsubsection{Classes and Class Instances \label{typesobjects}}
1277\nodename{Classes and Instances}
1278
1279See chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python
1280Reference Manual} for these.
1281
1282
1283\subsubsection{Functions \label{typesfunctions}}
1284
1285Function objects are created by function definitions. The only
1286operation on a function object is to call it:
1287\code{\var{func}(\var{argument-list})}.
1288
1289There are really two flavors of function objects: built-in functions
1290and user-defined functions. Both support the same operation (to call
1291the function), but the implementation is different, hence the
1292different object types.
1293
1294The implementation adds two special read-only attributes:
1295\code{\var{f}.func_code} is a function's \dfn{code
1296object}\obindex{code} (see below) and \code{\var{f}.func_globals} is
1297the dictionary used as the function's global namespace (this is the
1298same as \code{\var{m}.__dict__} where \var{m} is the module in which
1299the function \var{f} was defined).
1300
1301Function objects also support getting and setting arbitrary
1302attributes, which can be used to, e.g. attach metadata to functions.
1303Regular attribute dot-notation is used to get and set such
1304attributes. \emph{Note that the current implementation only supports
1305function attributes on user-defined functions. Function attributes on
1306built-in functions may be supported in the future.}
1307
1308Functions have another special attribute \code{\var{f}.__dict__}
1309(a.k.a. \code{\var{f}.func_dict}) which contains the namespace used to
1310support function attributes. \code{__dict__} and \code{func_dict} can
1311be accessed directly or set to a dictionary object. A function's
1312dictionary cannot be deleted.
1313
1314\subsubsection{Methods \label{typesmethods}}
1315\obindex{method}
1316
1317Methods are functions that are called using the attribute notation.
1318There are two flavors: built-in methods (such as \method{append()} on
1319lists) and class instance methods. Built-in methods are described
1320with the types that support them.
1321
1322The implementation adds two special read-only attributes to class
1323instance methods: \code{\var{m}.im_self} is the object on which the
1324method operates, and \code{\var{m}.im_func} is the function
1325implementing the method. Calling \code{\var{m}(\var{arg-1},
1326\var{arg-2}, \textrm{\ldots}, \var{arg-n})} is completely equivalent to
1327calling \code{\var{m}.im_func(\var{m}.im_self, \var{arg-1},
1328\var{arg-2}, \textrm{\ldots}, \var{arg-n})}.
1329
1330Class instance methods are either \emph{bound} or \emph{unbound},
1331referring to whether the method was accessed through an instance or a
1332class, respectively. When a method is unbound, its \code{im_self}
1333attribute will be \code{None} and if called, an explicit \code{self}
1334object must be passed as the first argument. In this case,
1335\code{self} must be an instance of the unbound method's class (or a
1336subclass of that class), otherwise a \code{TypeError} is raised.
1337
1338Like function objects, methods objects support getting
1339arbitrary attributes. However, since method attributes are actually
1340stored on the underlying function object (\code{meth.im_func}),
1341setting method attributes on either bound or unbound methods is
1342disallowed. Attempting to set a method attribute results in a
1343\code{TypeError} being raised. In order to set a method attribute,
1344you need to explicitly set it on the underlying function object:
1345
1346\begin{verbatim}
1347class C:
1348 def method(self):
1349 pass
1350
1351c = C()
1352c.method.im_func.whoami = 'my name is c'
1353\end{verbatim}
1354
1355See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1356information.
1357
1358
1359\subsubsection{Code Objects \label{bltin-code-objects}}
1360\obindex{code}
1361
1362Code objects are used by the implementation to represent
1363``pseudo-compiled'' executable Python code such as a function body.
1364They differ from function objects because they don't contain a
1365reference to their global execution environment. Code objects are
1366returned by the built-in \function{compile()} function and can be
1367extracted from function objects through their \member{func_code}
1368attribute.
1369\bifuncindex{compile}
1370\withsubitem{(function object attribute)}{\ttindex{func_code}}
1371
1372A code object can be executed or evaluated by passing it (instead of a
1373source string) to the \keyword{exec} statement or the built-in
1374\function{eval()} function.
1375\stindex{exec}
1376\bifuncindex{eval}
1377
1378See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1379information.
1380
1381
1382\subsubsection{Type Objects \label{bltin-type-objects}}
1383
1384Type objects represent the various object types. An object's type is
1385accessed by the built-in function \function{type()}. There are no special
1386operations on types. The standard module \module{types} defines names
1387for all standard built-in types.
1388\bifuncindex{type}
1389\refstmodindex{types}
1390
1391Types are written like this: \code{<type 'int'>}.
1392
1393
1394\subsubsection{The Null Object \label{bltin-null-object}}
1395
1396This object is returned by functions that don't explicitly return a
1397value. It supports no special operations. There is exactly one null
1398object, named \code{None} (a built-in name).
1399
1400It is written as \code{None}.
1401
1402
1403\subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
1404
1405This object is used by extended slice notation (see the
1406\citetitle[../ref/ref.html]{Python Reference Manual}). It supports no
1407special operations. There is exactly one ellipsis object, named
1408\constant{Ellipsis} (a built-in name).
1409
1410It is written as \code{Ellipsis}.
1411
Guido van Rossum77f6a652002-04-03 22:41:51 +00001412\subsubsection{Boolean Values}
1413
1414Boolean values are the two constant objects \code{False} and
1415\code{True}. They are used to represent truth values (although other
1416values can also be considered false or true). In numeric contexts
1417(for example when used as the argument to an arithmetic operator),
1418they behave like the integers 0 and 1, respectively. The built-in
1419function \function{bool()} can be used to cast any value to a Boolean,
1420if the value can be interpreted as a truth value (see section Truth
1421Value Testing above).
1422
1423They are written as \code{False} and \code{True}, respectively.
1424\index{False}
1425\index{True}
1426\indexii{Boolean}{values}
1427
Fred Drake99de2182001-10-30 06:23:14 +00001428
Fred Drake9474d861999-02-12 22:05:33 +00001429\subsubsection{Internal Objects \label{typesinternal}}
Fred Drake64e3b431998-07-24 13:56:11 +00001430
Fred Drake37f15741999-11-10 16:21:37 +00001431See the \citetitle[../ref/ref.html]{Python Reference Manual} for this
Fred Drake512bb722000-08-18 03:12:38 +00001432information. It describes stack frame objects, traceback objects, and
1433slice objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001434
1435
Fred Drake7a2f0661998-09-10 18:25:58 +00001436\subsection{Special Attributes \label{specialattrs}}
Fred Drake64e3b431998-07-24 13:56:11 +00001437
1438The implementation adds a few special read-only attributes to several
1439object types, where they are relevant:
1440
Fred Drakea776cea2000-11-06 20:17:37 +00001441\begin{memberdesc}[object]{__dict__}
1442A dictionary or other mapping object used to store an
Fred Drake7a2f0661998-09-10 18:25:58 +00001443object's (writable) attributes.
Fred Drakea776cea2000-11-06 20:17:37 +00001444\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001445
Fred Drakea776cea2000-11-06 20:17:37 +00001446\begin{memberdesc}[object]{__methods__}
Fred Drake35705512001-12-03 17:32:27 +00001447\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1448list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001449\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001450
Fred Drakea776cea2000-11-06 20:17:37 +00001451\begin{memberdesc}[object]{__members__}
Fred Drake35705512001-12-03 17:32:27 +00001452\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1453list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001454\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001455
Fred Drakea776cea2000-11-06 20:17:37 +00001456\begin{memberdesc}[instance]{__class__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001457The class to which a class instance belongs.
Fred Drakea776cea2000-11-06 20:17:37 +00001458\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001459
Fred Drakea776cea2000-11-06 20:17:37 +00001460\begin{memberdesc}[class]{__bases__}
Fred Drake907e76b2001-07-06 20:30:11 +00001461The tuple of base classes of a class object. If there are no base
1462classes, this will be an empty tuple.
Fred Drakea776cea2000-11-06 20:17:37 +00001463\end{memberdesc}