blob: da7ef0d15c679655b6174a5b6737d6ee34e8debf [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
5several others, including types themselves. There is no explicit
6Boolean type; use integers instead.
7\indexii{built-in}{types}
8\indexii{Boolean}{type}
9
10Some operations are supported by several object types; in particular,
11all objects can be compared, tested for truth value, and converted to
Fred Drake84538cd1998-11-30 21:51:25 +000012a string (with the \code{`\textrm{\ldots}`} notation). The latter
13conversion is implicitly used when an object is written by the
14\keyword{print}\stindex{print} statement.
Fred Drake64e3b431998-07-24 13:56:11 +000015
16
Fred Drake7a2f0661998-09-10 18:25:58 +000017\subsection{Truth Value Testing \label{truth}}
Fred Drake64e3b431998-07-24 13:56:11 +000018
Fred Drake84538cd1998-11-30 21:51:25 +000019Any object can be tested for truth value, for use in an \keyword{if} or
20\keyword{while} condition or as operand of the Boolean operations below.
Fred Drake64e3b431998-07-24 13:56:11 +000021The following values are considered false:
22\stindex{if}
23\stindex{while}
24\indexii{truth}{value}
25\indexii{Boolean}{operations}
26\index{false}
27
Fred Drake64e3b431998-07-24 13:56:11 +000028\begin{itemize}
29
30\item \code{None}
Fred Drake7a2f0661998-09-10 18:25:58 +000031 \withsubitem{(Built-in object)}{\ttindex{None}}
Fred Drake64e3b431998-07-24 13:56:11 +000032
Fred Drake38e5d272000-04-03 20:13:55 +000033\item zero of any numeric type, for example, \code{0}, \code{0L},
34 \code{0.0}, \code{0j}.
Fred Drake64e3b431998-07-24 13:56:11 +000035
Fred Drake38e5d272000-04-03 20:13:55 +000036\item any empty sequence, for example, \code{''}, \code{()}, \code{[]}.
Fred Drake64e3b431998-07-24 13:56:11 +000037
Fred Drake38e5d272000-04-03 20:13:55 +000038\item any empty mapping, for example, \code{\{\}}.
Fred Drake64e3b431998-07-24 13:56:11 +000039
40\item instances of user-defined classes, if the class defines a
Fred Drake7a2f0661998-09-10 18:25:58 +000041 \method{__nonzero__()} or \method{__len__()} method, when that
Fred Drake38e5d272000-04-03 20:13:55 +000042 method returns zero.\footnote{Additional information on these
Fred Drake66571cc2000-09-09 03:30:34 +000043special methods may be found in the \citetitle[../ref/ref.html]{Python
44Reference Manual}.}
Fred Drake64e3b431998-07-24 13:56:11 +000045
46\end{itemize}
47
48All other values are considered true --- so objects of many types are
49always true.
50\index{true}
51
52Operations and built-in functions that have a Boolean result always
53return \code{0} for false and \code{1} for true, unless otherwise
54stated. (Important exception: the Boolean operations
55\samp{or}\opindex{or} and \samp{and}\opindex{and} always return one of
56their operands.)
57
58
Fred Drake7a2f0661998-09-10 18:25:58 +000059\subsection{Boolean Operations \label{boolean}}
Fred Drake64e3b431998-07-24 13:56:11 +000060
61These are the Boolean operations, ordered by ascending priority:
62\indexii{Boolean}{operations}
63
64\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
65 \lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)}
66 \lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)}
67 \hline
68 \lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{(2)}
69\end{tableiii}
70\opindex{and}
71\opindex{or}
72\opindex{not}
73
74\noindent
75Notes:
76
77\begin{description}
78
79\item[(1)]
80These only evaluate their second argument if needed for their outcome.
81
82\item[(2)]
Fred Drake38e5d272000-04-03 20:13:55 +000083\samp{not} has a lower priority than non-Boolean operators, so
84\code{not \var{a} == \var{b}} is interpreted as \code{not (\var{a} ==
85\var{b})}, and \code{\var{a} == not \var{b}} is a syntax error.
Fred Drake64e3b431998-07-24 13:56:11 +000086
87\end{description}
88
89
Fred Drake7a2f0661998-09-10 18:25:58 +000090\subsection{Comparisons \label{comparisons}}
Fred Drake64e3b431998-07-24 13:56:11 +000091
92Comparison operations are supported by all objects. They all have the
93same priority (which is higher than that of the Boolean operations).
Fred Drake38e5d272000-04-03 20:13:55 +000094Comparisons can be chained arbitrarily; for example, \code{\var{x} <
95\var{y} <= \var{z}} is equivalent to \code{\var{x} < \var{y} and
96\var{y} <= \var{z}}, except that \var{y} is evaluated only once (but
97in both cases \var{z} is not evaluated at all when \code{\var{x} <
98\var{y}} is found to be false).
Fred Drake64e3b431998-07-24 13:56:11 +000099\indexii{chaining}{comparisons}
100
101This table summarizes the comparison operations:
102
103\begin{tableiii}{c|l|c}{code}{Operation}{Meaning}{Notes}
104 \lineiii{<}{strictly less than}{}
105 \lineiii{<=}{less than or equal}{}
106 \lineiii{>}{strictly greater than}{}
107 \lineiii{>=}{greater than or equal}{}
108 \lineiii{==}{equal}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000109 \lineiii{!=}{not equal}{(1)}
Fred Drake512bb722000-08-18 03:12:38 +0000110 \lineiii{<>}{not equal}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000111 \lineiii{is}{object identity}{}
112 \lineiii{is not}{negated object identity}{}
113\end{tableiii}
114\indexii{operator}{comparison}
115\opindex{==} % XXX *All* others have funny characters < ! >
116\opindex{is}
117\opindex{is not}
118
119\noindent
120Notes:
121
122\begin{description}
123
124\item[(1)]
125\code{<>} and \code{!=} are alternate spellings for the same operator.
Fred Drake4de96c22000-08-12 03:36:23 +0000126(I couldn't choose between \ABC{} and C! :-)
Fred Drake64e3b431998-07-24 13:56:11 +0000127\index{ABC language@\ABC{} language}
128\index{language!ABC@\ABC{}}
Fred Drake4de96c22000-08-12 03:36:23 +0000129\indexii{C}{language}
Fred Drake38e5d272000-04-03 20:13:55 +0000130\code{!=} is the preferred spelling; \code{<>} is obsolescent.
Fred Drake64e3b431998-07-24 13:56:11 +0000131
132\end{description}
133
134Objects of different types, except different numeric types, never
135compare equal; such objects are ordered consistently but arbitrarily
136(so that sorting a heterogeneous array yields a consistent result).
Fred Drake38e5d272000-04-03 20:13:55 +0000137Furthermore, some types (for example, file objects) support only a
138degenerate notion of comparison where any two objects of that type are
139unequal. Again, such objects are ordered arbitrarily but
140consistently.
141\indexii{object}{numeric}
Fred Drake64e3b431998-07-24 13:56:11 +0000142\indexii{objects}{comparing}
143
Fred Drake38e5d272000-04-03 20:13:55 +0000144Instances of a class normally compare as non-equal unless the class
145\withsubitem{(instance method)}{\ttindex{__cmp__()}}
Fred Drake66571cc2000-09-09 03:30:34 +0000146defines the \method{__cmp__()} method. Refer to the
147\citetitle[../ref/customization.html]{Python Reference Manual} for
148information on the use of this method to effect object comparisons.
Fred Drake64e3b431998-07-24 13:56:11 +0000149
Fred Drake38e5d272000-04-03 20:13:55 +0000150\strong{Implementation note:} Objects of different types except
151numbers are ordered by their type names; objects of the same types
152that don't support proper comparison are ordered by their address.
153
154Two more operations with the same syntactic priority,
155\samp{in}\opindex{in} and \samp{not in}\opindex{not in}, are supported
156only by sequence types (below).
Fred Drake64e3b431998-07-24 13:56:11 +0000157
158
Fred Drake7a2f0661998-09-10 18:25:58 +0000159\subsection{Numeric Types \label{typesnumeric}}
Fred Drake64e3b431998-07-24 13:56:11 +0000160
161There are four numeric types: \dfn{plain integers}, \dfn{long integers},
162\dfn{floating point numbers}, and \dfn{complex numbers}.
163Plain integers (also just called \dfn{integers})
Fred Drake38e5d272000-04-03 20:13:55 +0000164are implemented using \ctype{long} in C, which gives them at least 32
Fred Drake64e3b431998-07-24 13:56:11 +0000165bits of precision. Long integers have unlimited precision. Floating
Fred Drake38e5d272000-04-03 20:13:55 +0000166point numbers are implemented using \ctype{double} in C. All bets on
Fred Drake64e3b431998-07-24 13:56:11 +0000167their precision are off unless you happen to know the machine you are
168working with.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000169\obindex{numeric}
170\obindex{integer}
171\obindex{long integer}
172\obindex{floating point}
173\obindex{complex number}
Fred Drake38e5d272000-04-03 20:13:55 +0000174\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000175
176Complex numbers have a real and imaginary part, which are both
Fred Drake38e5d272000-04-03 20:13:55 +0000177implemented using \ctype{double} in C. To extract these parts from
Fred Drake64e3b431998-07-24 13:56:11 +0000178a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
179
180Numbers are created by numeric literals or as the result of built-in
181functions and operators. Unadorned integer literals (including hex
Fred Drake38e5d272000-04-03 20:13:55 +0000182and octal numbers) yield plain integers. Integer literals with an
183\character{L} or \character{l} suffix yield long integers
184(\character{L} is preferred because \samp{1l} looks too much like
185eleven!). Numeric literals containing a decimal point or an exponent
186sign yield floating point numbers. Appending \character{j} or
187\character{J} to a numeric literal yields a complex number.
Fred Drake64e3b431998-07-24 13:56:11 +0000188\indexii{numeric}{literals}
189\indexii{integer}{literals}
190\indexiii{long}{integer}{literals}
191\indexii{floating point}{literals}
192\indexii{complex number}{literals}
193\indexii{hexadecimal}{literals}
194\indexii{octal}{literals}
195
196Python fully supports mixed arithmetic: when a binary arithmetic
197operator has operands of different numeric types, the operand with the
198``smaller'' type is converted to that of the other, where plain
199integer is smaller than long integer is smaller than floating point is
200smaller than complex.
Fred Drakeea003fc1999-04-05 21:59:15 +0000201Comparisons between numbers of mixed type use the same rule.\footnote{
202 As a consequence, the list \code{[1, 2]} is considered equal
Fred Drake82ac24f1999-07-02 14:29:14 +0000203 to \code{[1.0, 2.0]}, and similar for tuples.
204} The functions \function{int()}, \function{long()}, \function{float()},
Fred Drake84538cd1998-11-30 21:51:25 +0000205and \function{complex()} can be used
Fred Drake64e3b431998-07-24 13:56:11 +0000206to coerce numbers to a specific type.
207\index{arithmetic}
208\bifuncindex{int}
209\bifuncindex{long}
210\bifuncindex{float}
211\bifuncindex{complex}
212
213All numeric types support the following operations, sorted by
214ascending priority (operations in the same box have the same
215priority; all numeric operations have a higher priority than
216comparison operations):
217
218\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
219 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
220 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
221 \hline
222 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
223 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
224 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
225 \hline
226 \lineiii{-\var{x}}{\var{x} negated}{}
227 \lineiii{+\var{x}}{\var{x} unchanged}{}
228 \hline
229 \lineiii{abs(\var{x})}{absolute value or magnitude of \var{x}}{}
230 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
231 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
232 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
233 \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 +0000234 \lineiii{\var{c}.conjugate()}{conjugate of the complex number \var{c}}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000235 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
236 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
237 \lineiii{\var{x} ** \var{y}}{\var{x} to the power \var{y}}{}
238\end{tableiii}
239\indexiii{operations on}{numeric}{types}
Fred Drake26b698f1999-02-12 18:27:31 +0000240\withsubitem{(complex number method)}{\ttindex{conjugate()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000241
242\noindent
243Notes:
244\begin{description}
245
246\item[(1)]
247For (plain or long) integer division, the result is an integer.
248The result is always rounded towards minus infinity: 1/2 is 0,
Fred Drake38e5d272000-04-03 20:13:55 +0000249(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
250is a long integer if either operand is a long integer, regardless of
251the numeric value.
Fred Drake64e3b431998-07-24 13:56:11 +0000252\indexii{integer}{division}
253\indexiii{long}{integer}{division}
254
255\item[(2)]
256Conversion from floating point to (long or plain) integer may round or
Fred Drake4de96c22000-08-12 03:36:23 +0000257truncate as in C; see functions \function{floor()} and
258\function{ceil()} in the \refmodule{math}\refbimodindex{math} module
259for well-defined conversions.
Fred Drake9474d861999-02-12 22:05:33 +0000260\withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000261\indexii{numeric}{conversions}
Fred Drake4de96c22000-08-12 03:36:23 +0000262\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000263
264\item[(3)]
Fred Drake38e5d272000-04-03 20:13:55 +0000265See section \ref{built-in-funcs}, ``Built-in Functions,'' for a full
266description.
Fred Drake64e3b431998-07-24 13:56:11 +0000267
268\end{description}
269% XXXJH exceptions: overflow (when? what operations?) zerodivision
270
Fred Drake4e7c2051999-02-19 15:30:25 +0000271\subsubsection{Bit-string Operations on Integer Types \label{bitstring-ops}}
Fred Drake64e3b431998-07-24 13:56:11 +0000272\nodename{Bit-string Operations}
273
274Plain and long integer types support additional operations that make
275sense only for bit-strings. Negative numbers are treated as their 2's
276complement value (for long integers, this assumes a sufficiently large
277number of bits that no overflow occurs during the operation).
278
279The priorities of the binary bit-wise operations are all lower than
280the numeric operations and higher than the comparisons; the unary
281operation \samp{\~} has the same priority as the other unary numeric
282operations (\samp{+} and \samp{-}).
283
284This table lists the bit-string operations sorted in ascending
285priority (operations in the same box have the same priority):
286
287\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
288 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
289 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
290 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
291 \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
292 \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
293 \hline
294 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
295\end{tableiii}
296\indexiii{operations on}{integer}{types}
297\indexii{bit-string}{operations}
298\indexii{shifting}{operations}
299\indexii{masking}{operations}
300
301\noindent
302Notes:
303\begin{description}
304\item[(1)] Negative shift counts are illegal and cause a
305\exception{ValueError} to be raised.
306\item[(2)] A left shift by \var{n} bits is equivalent to
307multiplication by \code{pow(2, \var{n})} without overflow check.
308\item[(3)] A right shift by \var{n} bits is equivalent to
309division by \code{pow(2, \var{n})} without overflow check.
310\end{description}
311
312
Fred Drake7a2f0661998-09-10 18:25:58 +0000313\subsection{Sequence Types \label{typesseq}}
Fred Drake64e3b431998-07-24 13:56:11 +0000314
Fred Drake107b9672000-08-14 15:37:59 +0000315There are six sequence types: strings, Unicode strings, lists,
Fred Drake512bb722000-08-18 03:12:38 +0000316tuples, buffers, and xrange objects.
Fred Drake64e3b431998-07-24 13:56:11 +0000317
318Strings literals are written in single or double quotes:
Fred Drake38e5d272000-04-03 20:13:55 +0000319\code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
Fred Drake4de96c22000-08-12 03:36:23 +0000320\citetitle[../ref/strings.html]{Python Reference Manual} for more about
321string literals. Unicode strings are much like strings, but are
322specified in the syntax using a preceeding \character{u} character:
323\code{u'abc'}, \code{u"def"}. Lists are constructed with square brackets,
Fred Drake37f15741999-11-10 16:21:37 +0000324separating items with commas: \code{[a, b, c]}. Tuples are
325constructed by the comma operator (not within square brackets), with
326or without enclosing parentheses, but an empty tuple must have the
327enclosing parentheses, e.g., \code{a, b, c} or \code{()}. A single
Fred Drake4de96c22000-08-12 03:36:23 +0000328item tuple must have a trailing comma, e.g., \code{(d,)}. Buffers are
Fred Drakefffe5db2000-09-21 05:25:30 +0000329not directly supported by Python syntax, but can be created by calling the
Fred Drake512bb722000-08-18 03:12:38 +0000330builtin function \function{buffer()}.\bifuncindex{buffer} XRanges
331objects are similar to buffers in that there is no specific syntax to
332create them, but they are created using the \function{xrange()}
Fred Drake107b9672000-08-14 15:37:59 +0000333function.\bifuncindex{xrange}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000334\obindex{sequence}
335\obindex{string}
336\obindex{Unicode}
337\obindex{buffer}
338\obindex{tuple}
339\obindex{list}
340\obindex{xrange}
Fred Drake64e3b431998-07-24 13:56:11 +0000341
342Sequence types support the following operations. The \samp{in} and
343\samp{not in} operations have the same priorities as the comparison
344operations. The \samp{+} and \samp{*} operations have the same
345priority as the corresponding numeric operations.\footnote{They must
346have since the parser can't tell the type of the operands.}
347
348This table lists the sequence operations sorted in ascending priority
349(operations in the same box have the same priority). In the table,
350\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
351and \var{j} are integers:
352
353\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
354 \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
355 \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is
356equal to \var{x}, else \code{1}}{}
357 \hline
358 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
Fred Drake38e5d272000-04-03 20:13:55 +0000359 \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000360 \hline
Fred Drake38e5d272000-04-03 20:13:55 +0000361 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(2)}
362 \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 +0000363 \hline
364 \lineiii{len(\var{s})}{length of \var{s}}{}
365 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
366 \lineiii{max(\var{s})}{largest item of \var{s}}{}
367\end{tableiii}
368\indexiii{operations on}{sequence}{types}
369\bifuncindex{len}
370\bifuncindex{min}
371\bifuncindex{max}
372\indexii{concatenation}{operation}
373\indexii{repetition}{operation}
374\indexii{subscript}{operation}
375\indexii{slice}{operation}
376\opindex{in}
377\opindex{not in}
378
379\noindent
380Notes:
381
382\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000383\item[(1)] Values of \var{n} less than \code{0} are treated as
384 \code{0} (which yields an empty sequence of the same type as
385 \var{s}).
386
387\item[(2)] If \var{i} or \var{j} is negative, the index is relative to
Fred Drake64e3b431998-07-24 13:56:11 +0000388 the end of the string, i.e., \code{len(\var{s}) + \var{i}} or
389 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
390 still \code{0}.
391
Fred Drake38e5d272000-04-03 20:13:55 +0000392\item[(3)] The slice of \var{s} from \var{i} to \var{j} is defined as
Fred Drake64e3b431998-07-24 13:56:11 +0000393 the sequence of items with index \var{k} such that \code{\var{i} <=
394 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
395 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
396 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
397 \var{i} is greater than or equal to \var{j}, the slice is empty.
Fred Drake64e3b431998-07-24 13:56:11 +0000398\end{description}
399
Fred Drake9474d861999-02-12 22:05:33 +0000400
Fred Drake4de96c22000-08-12 03:36:23 +0000401\subsubsection{String Methods \label{string-methods}}
402
403These are the string methods which both 8-bit strings and Unicode
404objects support:
405
406\begin{methoddesc}[string]{capitalize}{}
407Return a copy of the string with only its first character capitalized.
408\end{methoddesc}
409
410\begin{methoddesc}[string]{center}{width}
411Return centered in a string of length \var{width}. Padding is done
412using spaces.
413\end{methoddesc}
414
415\begin{methoddesc}[string]{count}{sub\optional{, start\optional{, end}}}
416Return the number of occurrences of substring \var{sub} in string
417S\code{[\var{start}:\var{end}]}. Optional arguments \var{start} and
418\var{end} are interpreted as in slice notation.
419\end{methoddesc}
420
421\begin{methoddesc}[string]{encode}{\optional{encoding\optional{,errors}}}
422Return an encoded version of the string. Default encoding is the current
423default string encoding. \var{errors} may be given to set a different
424error handling scheme. The default for \var{errors} is
425\code{'strict'}, meaning that encoding errors raise a
426\exception{ValueError}. Other possible values are \code{'ignore'} and
427\code{'replace'}.
Fred Drake1dba66c2000-10-25 21:03:55 +0000428\versionadded{2.0}
Fred Drake4de96c22000-08-12 03:36:23 +0000429\end{methoddesc}
430
431\begin{methoddesc}[string]{endswith}{suffix\optional{, start\optional{, end}}}
432Return true if the string ends with the specified \var{suffix},
433otherwise return false. With optional \var{start}, test beginning at
434that position. With optional \var{end}, stop comparing at that position.
435\end{methoddesc}
436
437\begin{methoddesc}[string]{expandtabs}{\optional{tabsize}}
438Return a copy of the string where all tab characters are expanded
439using spaces. If \var{tabsize} is not given, a tab size of \code{8}
440characters is assumed.
441\end{methoddesc}
442
443\begin{methoddesc}[string]{find}{sub\optional{, start\optional{, end}}}
444Return the lowest index in the string where substring \var{sub} is
445found, such that \var{sub} is contained in the range [\var{start},
446\var{end}). Optional arguments \var{start} and \var{end} are
447interpreted as in slice notation. Return \code{-1} if \var{sub} is
448not found.
449\end{methoddesc}
450
451\begin{methoddesc}[string]{index}{sub\optional{, start\optional{, end}}}
452Like \method{find()}, but raise \exception{ValueError} when the
453substring is not found.
454\end{methoddesc}
455
456\begin{methoddesc}[string]{isalnum}{}
457Return true if all characters in the string are alphanumeric and there
458is at least one character, false otherwise.
459\end{methoddesc}
460
461\begin{methoddesc}[string]{isalpha}{}
462Return true if all characters in the string are alphabetic and there
463is at least one character, false otherwise.
464\end{methoddesc}
465
466\begin{methoddesc}[string]{isdigit}{}
467Return true if there are only digit characters, false otherwise.
468\end{methoddesc}
469
470\begin{methoddesc}[string]{islower}{}
471Return true if all cased characters in the string are lowercase and
472there is at least one cased character, false otherwise.
473\end{methoddesc}
474
475\begin{methoddesc}[string]{isspace}{}
476Return true if there are only whitespace characters in the string and
477the string is not empty, false otherwise.
478\end{methoddesc}
479
480\begin{methoddesc}[string]{istitle}{}
481Return true if the string is a titlecased string, i.e.\ uppercase
482characters may only follow uncased characters and lowercase characters
483only cased ones. Return false otherwise.
484\end{methoddesc}
485
486\begin{methoddesc}[string]{isupper}{}
487Return true if all cased characters in the string are uppercase and
488there is at least one cased character, false otherwise.
489\end{methoddesc}
490
491\begin{methoddesc}[string]{join}{seq}
492Return a string which is the concatenation of the strings in the
493sequence \var{seq}. The separator between elements is the string
494providing this method.
495\end{methoddesc}
496
497\begin{methoddesc}[string]{ljust}{width}
498Return the string left justified in a string of length \var{width}.
499Padding is done using spaces. The original string is returned if
500\var{width} is less than \code{len(\var{s})}.
501\end{methoddesc}
502
503\begin{methoddesc}[string]{lower}{}
504Return a copy of the string converted to lowercase.
505\end{methoddesc}
506
507\begin{methoddesc}[string]{lstrip}{}
508Return a copy of the string with leading whitespace removed.
509\end{methoddesc}
510
511\begin{methoddesc}[string]{replace}{old, new\optional{, maxsplit}}
512Return a copy of the string with all occurrences of substring
513\var{old} replaced by \var{new}. If the optional argument
514\var{maxsplit} is given, only the first \var{maxsplit} occurrences are
515replaced.
516\end{methoddesc}
517
518\begin{methoddesc}[string]{rfind}{sub \optional{,start \optional{,end}}}
519Return the highest index in the string where substring \var{sub} is
520found, such that \var{sub} is contained within s[start,end]. Optional
521arguments \var{start} and \var{end} are interpreted as in slice
522notation. Return \code{-1} on failure.
523\end{methoddesc}
524
525\begin{methoddesc}[string]{rindex}{sub\optional{, start\optional{, end}}}
526Like \method{rfind()} but raises \exception{ValueError} when the
527substring \var{sub} is not found.
528\end{methoddesc}
529
530\begin{methoddesc}[string]{rjust}{width}
531Return the string right justified in a string of length \var{width}.
532Padding is done using spaces. The original string is returned if
533\var{width} is less than \code{len(\var{s})}.
534\end{methoddesc}
535
536\begin{methoddesc}[string]{rstrip}{}
537Return a copy of the string with trailing whitespace removed.
538\end{methoddesc}
539
540\begin{methoddesc}[string]{split}{\optional{sep \optional{,maxsplit}}}
541Return a list of the words in the string, using \var{sep} as the
542delimiter string. If \var{maxsplit} is given, at most \var{maxsplit}
543splits are done. If \var{sep} is not specified or \code{None}, any
544whitespace string is a separator.
545\end{methoddesc}
546
547\begin{methoddesc}[string]{splitlines}{\optional{keepends}}
548Return a list of the lines in the string, breaking at line
549boundaries. Line breaks are not included in the resulting list unless
550\var{keepends} is given and true.
551\end{methoddesc}
552
553\begin{methoddesc}[string]{startswith}{prefix\optional{, start\optional{, end}}}
554Return true if string starts with the \var{prefix}, otherwise
555return false. With optional \var{start}, test string beginning at
556that position. With optional \var{end}, stop comparing string at that
557position.
558\end{methoddesc}
559
560\begin{methoddesc}[string]{strip}{}
561Return a copy of the string with leading and trailing whitespace
562removed.
563\end{methoddesc}
564
565\begin{methoddesc}[string]{swapcase}{}
566Return a copy of the string with uppercase characters converted to
567lowercase and vice versa.
568\end{methoddesc}
569
570\begin{methoddesc}[string]{title}{}
571Return a titlecased version of, i.e.\ words start with uppercase
572characters, all remaining cased characters are lowercase.
573\end{methoddesc}
574
575\begin{methoddesc}[string]{translate}{table\optional{, deletechars}}
576Return a copy of the string where all characters occurring in the
577optional argument \var{deletechars} are removed, and the remaining
578characters have been mapped through the given translation table, which
579must be a string of length 256.
580\end{methoddesc}
581
582\begin{methoddesc}[string]{upper}{}
583Return a copy of the string converted to uppercase.
584\end{methoddesc}
585
586
587\subsubsection{String Formatting Operations \label{typesseq-strings}}
Fred Drake64e3b431998-07-24 13:56:11 +0000588
Fred Drake66d32b12000-09-14 17:57:42 +0000589\index{formatting, string}
590\index{string!formatting}
591\index{printf-style formatting}
592\index{sprintf-style formatting}
593
Fred Drake64e3b431998-07-24 13:56:11 +0000594String objects have one unique built-in operation: the \code{\%}
595operator (modulo) with a string left argument interprets this string
Fred Drake4de96c22000-08-12 03:36:23 +0000596as a C \cfunction{sprintf()} format string to be applied to the
Fred Drake64e3b431998-07-24 13:56:11 +0000597right argument, and returns the string resulting from this formatting
598operation.
599
600The right argument should be a tuple with one item for each argument
601required by the format string; if the string requires a single
Fred Drakeea003fc1999-04-05 21:59:15 +0000602argument, the right argument may also be a single non-tuple
Fred Drake4de96c22000-08-12 03:36:23 +0000603object.\footnote{A tuple object in this case should be a singleton.
Fred Drake17383b92000-11-17 19:44:14 +0000604} The following format characters are understood: \code{\%},
605\code{c}, \code{r}, \code{s}, \code{i}, \code{d}, \code{u}, \code{o},
606\code{x}, \code{X}, \code{e}, \code{E}, \code{f}, \code{g}, \code{G}.
Fred Drake64e3b431998-07-24 13:56:11 +0000607Width and precision may be a \code{*} to specify that an integer argument
608specifies the actual width or precision. The flag characters
Fred Drake6d20caa1999-04-21 18:17:11 +0000609\code{-}, \code{+}, blank, \code{\#} and \code{0} are understood. The
610size specifiers \code{h}, \code{l} or \code{L} may be present but are
611ignored. The \code{\%s} conversion takes any Python object and
Fred Drake17383b92000-11-17 19:44:14 +0000612converts it to a string using \code{str()} before formatting it; the
613\code{\%r} conversion is similar but applies the \function{repr()}
614function instead. The
Fred Drake6d20caa1999-04-21 18:17:11 +0000615ANSI features \code{\%p} and \code{\%n} are not supported. Since
616Python strings have an explicit length, \code{\%s} conversions don't
617assume that \code{'\e0'} is the end of the string.
Fred Drake64e3b431998-07-24 13:56:11 +0000618
619For safety reasons, floating point precisions are clipped to 50;
620\code{\%f} conversions for numbers whose absolute value is over 1e25
Fred Drakeea003fc1999-04-05 21:59:15 +0000621are replaced by \code{\%g} conversions.\footnote{
622 These numbers are fairly arbitrary. They are intended to
623 avoid printing endless strings of meaningless digits without hampering
624 correct use and without having to know the exact precision of floating
Fred Drake4de96c22000-08-12 03:36:23 +0000625 point values on a particular machine.
626} All other errors raise exceptions.
Fred Drake64e3b431998-07-24 13:56:11 +0000627
628If the right argument is a dictionary (or any kind of mapping), then
629the formats in the string must have a parenthesized key into that
630dictionary inserted immediately after the \character{\%} character,
631and each format formats the corresponding entry from the mapping.
632For example:
633
634\begin{verbatim}
635>>> count = 2
636>>> language = 'Python'
637>>> print '%(language)s has %(count)03d quote types.' % vars()
638Python has 002 quote types.
639\end{verbatim}
640
641In this case no \code{*} specifiers may occur in a format (since they
642require a sequential parameter list).
643
644Additional string operations are defined in standard module
Fred Drake107b9672000-08-14 15:37:59 +0000645\refmodule{string} and in built-in module \refmodule{re}.
Fred Drake64e3b431998-07-24 13:56:11 +0000646\refstmodindex{string}
Fred Drake66da9d61998-08-07 18:57:18 +0000647\refstmodindex{re}
Fred Drake64e3b431998-07-24 13:56:11 +0000648
Fred Drake107b9672000-08-14 15:37:59 +0000649
Fred Drake512bb722000-08-18 03:12:38 +0000650\subsubsection{XRange Type \label{typesseq-xrange}}
Fred Drake107b9672000-08-14 15:37:59 +0000651
Fred Drake0b4e25d2000-10-04 04:21:19 +0000652The xrange\obindex{xrange} type is an immutable sequence which is
Fred Drake512bb722000-08-18 03:12:38 +0000653commonly used for looping. The advantage of the xrange type is that an
654xrange object will always take the same amount of memory, no matter the
Fred Drake107b9672000-08-14 15:37:59 +0000655size of the range it represents. There are no consistent performance
656advantages.
657
Fred Drake512bb722000-08-18 03:12:38 +0000658XRange objects behave like tuples, and offer a single method:
Fred Drake107b9672000-08-14 15:37:59 +0000659
Fred Drake512bb722000-08-18 03:12:38 +0000660\begin{methoddesc}[xrange]{tolist}{}
661 Return a list object which represents the same values as the xrange
Fred Drake107b9672000-08-14 15:37:59 +0000662 object.
663\end{methoddesc}
664
665
Fred Drake9474d861999-02-12 22:05:33 +0000666\subsubsection{Mutable Sequence Types \label{typesseq-mutable}}
Fred Drake64e3b431998-07-24 13:56:11 +0000667
668List objects support additional operations that allow in-place
669modification of the object.
670These operations would be supported by other mutable sequence types
671(when added to the language) as well.
672Strings and tuples are immutable sequence types and such objects cannot
673be modified once created.
674The following operations are defined on mutable sequence types (where
675\var{x} is an arbitrary object):
676\indexiii{mutable}{sequence}{types}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000677\obindex{list}
Fred Drake64e3b431998-07-24 13:56:11 +0000678
679\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
680 \lineiii{\var{s}[\var{i}] = \var{x}}
681 {item \var{i} of \var{s} is replaced by \var{x}}{}
682 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
683 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
684 \lineiii{del \var{s}[\var{i}:\var{j}]}
685 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
686 \lineiii{\var{s}.append(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000687 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{(1)}
Barry Warsawafd974c1998-10-09 16:39:58 +0000688 \lineiii{\var{s}.extend(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000689 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +0000690 \lineiii{\var{s}.count(\var{x})}
691 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
692 \lineiii{\var{s}.index(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000693 {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000694 \lineiii{\var{s}.insert(\var{i}, \var{x})}
695 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
696 if \code{\var{i} >= 0}}{}
697 \lineiii{\var{s}.pop(\optional{\var{i}})}
698 {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(4)}
699 \lineiii{\var{s}.remove(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000700 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000701 \lineiii{\var{s}.reverse()}
Fred Drake38e5d272000-04-03 20:13:55 +0000702 {reverses the items of \var{s} in place}{(5)}
Fred Drake64e3b431998-07-24 13:56:11 +0000703 \lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
Fred Drake38e5d272000-04-03 20:13:55 +0000704 {sort the items of \var{s} in place}{(5), (6)}
Fred Drake64e3b431998-07-24 13:56:11 +0000705\end{tableiii}
706\indexiv{operations on}{mutable}{sequence}{types}
707\indexiii{operations on}{sequence}{types}
708\indexiii{operations on}{list}{type}
709\indexii{subscript}{assignment}
710\indexii{slice}{assignment}
711\stindex{del}
Fred Drake9474d861999-02-12 22:05:33 +0000712\withsubitem{(list method)}{
Fred Drake68921df1999-08-09 17:05:12 +0000713 \ttindex{append()}\ttindex{extend()}\ttindex{count()}\ttindex{index()}
714 \ttindex{insert()}\ttindex{pop()}\ttindex{remove()}\ttindex{reverse()}
Fred Drakee8391991998-11-25 17:09:19 +0000715 \ttindex{sort()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000716\noindent
717Notes:
718\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000719\item[(1)] The C implementation of Python has historically accepted
720 multiple parameters and implicitly joined them into a tuple; this
Fred Drake30f76ff2000-06-30 16:06:19 +0000721 no longer works in Python 2.0. Use of this misfeature has been
Fred Drake38e5d272000-04-03 20:13:55 +0000722 deprecated since Python 1.4.
723
724\item[(2)] Raises an exception when \var{x} is not a list object. The
725 \method{extend()} method is experimental and not supported by
726 mutable sequence types other than lists.
727
728\item[(3)] Raises \exception{ValueError} when \var{x} is not found in
Fred Drake68921df1999-08-09 17:05:12 +0000729 \var{s}.
730
Peter Schneider-Kampf917bf62000-08-01 00:07:17 +0000731\item[(4)] The \method{pop()} method is only supported by the list and
Fred Drakefbd3b452000-07-31 23:42:23 +0000732 array types. The optional argument \var{i} defaults to \code{-1},
733 so that by default the last item is removed and returned.
Fred Drake38e5d272000-04-03 20:13:55 +0000734
735\item[(5)] The \method{sort()} and \method{reverse()} methods modify the
736 list in place for economy of space when sorting or reversing a large
737 list. They don't return the sorted or reversed list to remind you
738 of this side effect.
739
740\item[(6)] The \method{sort()} method takes an optional argument
Fred Drake64e3b431998-07-24 13:56:11 +0000741 specifying a comparison function of two arguments (list items) which
Fred Drake68921df1999-08-09 17:05:12 +0000742 should return \code{-1}, \code{0} or \code{1} depending on whether
743 the first argument is considered smaller than, equal to, or larger
744 than the second argument. Note that this slows the sorting process
745 down considerably; e.g. to sort a list in reverse order it is much
746 faster to use calls to the methods \method{sort()} and
747 \method{reverse()} than to use the built-in function
748 \function{sort()} with a comparison function that reverses the
749 ordering of the elements.
Fred Drake64e3b431998-07-24 13:56:11 +0000750\end{description}
751
752
Fred Drake7a2f0661998-09-10 18:25:58 +0000753\subsection{Mapping Types \label{typesmapping}}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000754\obindex{mapping}
755\obindex{dictionary}
Fred Drake64e3b431998-07-24 13:56:11 +0000756
757A \dfn{mapping} object maps values of one type (the key type) to
758arbitrary objects. Mappings are mutable objects. There is currently
759only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
760almost arbitrary values. The only types of values not acceptable as
761keys are values containing lists or dictionaries or other mutable
762types that are compared by value rather than by object identity.
763Numeric types used for keys obey the normal rules for numeric
764comparison: if two numbers compare equal (e.g. \code{1} and
765\code{1.0}) then they can be used interchangeably to index the same
766dictionary entry.
767
Fred Drake64e3b431998-07-24 13:56:11 +0000768Dictionaries are created by placing a comma-separated list of
769\code{\var{key}: \var{value}} pairs within braces, for example:
770\code{\{'jack': 4098, 'sjoerd': 4127\}} or
771\code{\{4098: 'jack', 4127: 'sjoerd'\}}.
772
Fred Drake9c5cc141999-06-10 22:37:34 +0000773The following operations are defined on mappings (where \var{a} and
774\var{b} are mappings, \var{k} is a key, and \var{v} and \var{x} are
775arbitrary objects):
Fred Drake64e3b431998-07-24 13:56:11 +0000776\indexiii{operations on}{mapping}{types}
777\indexiii{operations on}{dictionary}{type}
778\stindex{del}
779\bifuncindex{len}
Fred Drake9474d861999-02-12 22:05:33 +0000780\withsubitem{(dictionary method)}{
781 \ttindex{clear()}
782 \ttindex{copy()}
783 \ttindex{has_key()}
784 \ttindex{items()}
785 \ttindex{keys()}
786 \ttindex{update()}
787 \ttindex{values()}
Fred Drakee8391991998-11-25 17:09:19 +0000788 \ttindex{get()}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000789
790\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
791 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
792 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
Fred Drake1e75e172000-07-31 16:34:46 +0000793 \lineiii{\var{a}[\var{k}] = \var{v}}
794 {set \code{\var{a}[\var{k}]} to \var{v}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000795 {}
796 \lineiii{del \var{a}[\var{k}]}
797 {remove \code{\var{a}[\var{k}]} from \var{a}}
798 {(1)}
799 \lineiii{\var{a}.clear()}{remove all items from \code{a}}{}
800 \lineiii{\var{a}.copy()}{a (shallow) copy of \code{a}}{}
801 \lineiii{\var{a}.has_key(\var{k})}
802 {\code{1} if \var{a} has a key \var{k}, else \code{0}}
803 {}
804 \lineiii{\var{a}.items()}
805 {a copy of \var{a}'s list of (\var{key}, \var{value}) pairs}
806 {(2)}
807 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)}
808 \lineiii{\var{a}.update(\var{b})}
Fred Drake1e75e172000-07-31 16:34:46 +0000809 {\code{for k in \var{b}.keys(): \var{a}[k] = \var{b}[k]}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000810 {(3)}
811 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)}
812 \lineiii{\var{a}.get(\var{k}\optional{, \var{x}})}
813 {\code{\var{a}[\var{k}]} if \code{\var{a}.has_key(\var{k})},
814 else \var{x}}
815 {(4)}
Guido van Rossum8141cf52000-08-08 16:15:49 +0000816 \lineiii{\var{a}.setdefault(\var{k}\optional{, \var{x}})}
817 {\code{\var{a}[\var{k}]} if \code{\var{a}.has_key(\var{k})},
818 else \var{x} (also setting it)}
819 {(5)}
Guido van Rossumff63f202000-12-12 22:03:47 +0000820 \lineiii{\var{a}.popitem()}
821 {remove and return an arbitrary (\var{key}, \var{value}) pair}
822 {(6)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000823\end{tableiii}
824
Fred Drake64e3b431998-07-24 13:56:11 +0000825\noindent
826Notes:
827\begin{description}
Fred Drake9c5cc141999-06-10 22:37:34 +0000828\item[(1)] Raises a \exception{KeyError} exception if \var{k} is not
829in the map.
Fred Drake64e3b431998-07-24 13:56:11 +0000830
Fred Drake38e5d272000-04-03 20:13:55 +0000831\item[(2)] Keys and values are listed in random order. If
832\method{keys()} and \method{values()} are called with no intervening
833modifications to the dictionary, the two lists will directly
834correspond. This allows the creation of \code{(\var{value},
835\var{key})} pairs using \function{map()}: \samp{pairs = map(None,
836\var{a}.values(), \var{a}.keys())}.
Fred Drake64e3b431998-07-24 13:56:11 +0000837
838\item[(3)] \var{b} must be of the same type as \var{a}.
839
840\item[(4)] Never raises an exception if \var{k} is not in the map,
Fred Drake38e5d272000-04-03 20:13:55 +0000841instead it returns \var{x}. \var{x} is optional; when \var{x} is not
Fred Drake9c5cc141999-06-10 22:37:34 +0000842provided and \var{k} is not in the map, \code{None} is returned.
Guido van Rossum8141cf52000-08-08 16:15:49 +0000843
844\item[(5)] \function{setdefault()} is like \function{get()}, except
845that if \var{k} is missing, \var{x} is both returned and inserted into
846the dictionary as the value of \var{k}.
Guido van Rossumff63f202000-12-12 22:03:47 +0000847
848\item[(6)] \function{popitem()} is useful to destructively iterate
849over a dictionary, as often used in set algorithms.
Fred Drake64e3b431998-07-24 13:56:11 +0000850\end{description}
851
852
Fred Drake7a2f0661998-09-10 18:25:58 +0000853\subsection{Other Built-in Types \label{typesother}}
Fred Drake64e3b431998-07-24 13:56:11 +0000854
855The interpreter supports several other kinds of objects.
856Most of these support only one or two operations.
857
Fred Drake4e7c2051999-02-19 15:30:25 +0000858
Fred Drake9474d861999-02-12 22:05:33 +0000859\subsubsection{Modules \label{typesmodules}}
Fred Drake64e3b431998-07-24 13:56:11 +0000860
861The only special operation on a module is attribute access:
862\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name}
863accesses a name defined in \var{m}'s symbol table. Module attributes
Fred Drake84538cd1998-11-30 21:51:25 +0000864can be assigned to. (Note that the \keyword{import} statement is not,
Fred Draked0421dd1998-08-24 17:57:20 +0000865strictly speaking, an operation on a module object; \code{import
Fred Drake64e3b431998-07-24 13:56:11 +0000866\var{foo}} does not require a module object named \var{foo} to exist,
867rather it requires an (external) \emph{definition} for a module named
868\var{foo} somewhere.)
869
Fred Drake84538cd1998-11-30 21:51:25 +0000870A special member of every module is \member{__dict__}.
Fred Drake64e3b431998-07-24 13:56:11 +0000871This is the dictionary containing the module's symbol table.
872Modifying this dictionary will actually change the module's symbol
Fred Drake84538cd1998-11-30 21:51:25 +0000873table, but direct assignment to the \member{__dict__} attribute is not
Fred Drake64e3b431998-07-24 13:56:11 +0000874possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which
875defines \code{\var{m}.a} to be \code{1}, but you can't write
876\code{\var{m}.__dict__ = \{\}}.
877
Fred Drake4e7c2051999-02-19 15:30:25 +0000878Modules built into the interpreter are written like this:
879\code{<module 'sys' (built-in)>}. If loaded from a file, they are
Fred Draked5d04352000-09-14 20:24:17 +0000880written as \code{<module 'os' from
881'/usr/local/lib/python\shortversion/os.pyc'>}.
Fred Drake4e7c2051999-02-19 15:30:25 +0000882
Fred Drake64e3b431998-07-24 13:56:11 +0000883
Fred Drake9474d861999-02-12 22:05:33 +0000884\subsubsection{Classes and Class Instances \label{typesobjects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000885\nodename{Classes and Instances}
886
Fred Drake38e5d272000-04-03 20:13:55 +0000887See chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python
Fred Drake37f15741999-11-10 16:21:37 +0000888Reference Manual} for these.
Fred Drake64e3b431998-07-24 13:56:11 +0000889
Fred Drake4e7c2051999-02-19 15:30:25 +0000890
Fred Drake9474d861999-02-12 22:05:33 +0000891\subsubsection{Functions \label{typesfunctions}}
Fred Drake64e3b431998-07-24 13:56:11 +0000892
893Function objects are created by function definitions. The only
894operation on a function object is to call it:
895\code{\var{func}(\var{argument-list})}.
896
897There are really two flavors of function objects: built-in functions
898and user-defined functions. Both support the same operation (to call
899the function), but the implementation is different, hence the
900different object types.
901
902The implementation adds two special read-only attributes:
903\code{\var{f}.func_code} is a function's \dfn{code
904object}\obindex{code} (see below) and \code{\var{f}.func_globals} is
Fred Drake13494372000-09-12 16:23:48 +0000905the dictionary used as the function's global namespace (this is the
Fred Drake64e3b431998-07-24 13:56:11 +0000906same as \code{\var{m}.__dict__} where \var{m} is the module in which
907the function \var{f} was defined).
908
909
Fred Drake9474d861999-02-12 22:05:33 +0000910\subsubsection{Methods \label{typesmethods}}
Fred Drake64e3b431998-07-24 13:56:11 +0000911\obindex{method}
912
913Methods are functions that are called using the attribute notation.
Fred Drake84538cd1998-11-30 21:51:25 +0000914There are two flavors: built-in methods (such as \method{append()} on
Fred Drake64e3b431998-07-24 13:56:11 +0000915lists) and class instance methods. Built-in methods are described
916with the types that support them.
917
918The implementation adds two special read-only attributes to class
Fred Draked0421dd1998-08-24 17:57:20 +0000919instance methods: \code{\var{m}.im_self} is the object on which the
920method operates, and \code{\var{m}.im_func} is the function
921implementing the method. Calling \code{\var{m}(\var{arg-1},
Fred Drake84538cd1998-11-30 21:51:25 +0000922\var{arg-2}, \textrm{\ldots}, \var{arg-n})} is completely equivalent to
Fred Draked0421dd1998-08-24 17:57:20 +0000923calling \code{\var{m}.im_func(\var{m}.im_self, \var{arg-1},
Fred Drake84538cd1998-11-30 21:51:25 +0000924\var{arg-2}, \textrm{\ldots}, \var{arg-n})}.
Fred Drake64e3b431998-07-24 13:56:11 +0000925
Fred Drake37f15741999-11-10 16:21:37 +0000926See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
927information.
Fred Drake64e3b431998-07-24 13:56:11 +0000928
Fred Drake7a2f0661998-09-10 18:25:58 +0000929
930\subsubsection{Code Objects \label{bltin-code-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000931\obindex{code}
932
933Code objects are used by the implementation to represent
934``pseudo-compiled'' executable Python code such as a function body.
935They differ from function objects because they don't contain a
936reference to their global execution environment. Code objects are
Fred Drake84538cd1998-11-30 21:51:25 +0000937returned by the built-in \function{compile()} function and can be
938extracted from function objects through their \member{func_code}
Fred Drake64e3b431998-07-24 13:56:11 +0000939attribute.
940\bifuncindex{compile}
Fred Drakee8391991998-11-25 17:09:19 +0000941\withsubitem{(function object attribute)}{\ttindex{func_code}}
Fred Drake64e3b431998-07-24 13:56:11 +0000942
943A code object can be executed or evaluated by passing it (instead of a
Fred Drake84538cd1998-11-30 21:51:25 +0000944source string) to the \keyword{exec} statement or the built-in
945\function{eval()} function.
Fred Drake64e3b431998-07-24 13:56:11 +0000946\stindex{exec}
947\bifuncindex{eval}
948
Fred Drake37f15741999-11-10 16:21:37 +0000949See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
950information.
Fred Drake64e3b431998-07-24 13:56:11 +0000951
Fred Drake7a2f0661998-09-10 18:25:58 +0000952
953\subsubsection{Type Objects \label{bltin-type-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000954
955Type objects represent the various object types. An object's type is
Fred Drake84538cd1998-11-30 21:51:25 +0000956accessed by the built-in function \function{type()}. There are no special
957operations on types. The standard module \module{types} defines names
Fred Drake64e3b431998-07-24 13:56:11 +0000958for all standard built-in types.
959\bifuncindex{type}
960\refstmodindex{types}
961
962Types are written like this: \code{<type 'int'>}.
963
Fred Drake7a2f0661998-09-10 18:25:58 +0000964
965\subsubsection{The Null Object \label{bltin-null-object}}
Fred Drake64e3b431998-07-24 13:56:11 +0000966
967This object is returned by functions that don't explicitly return a
968value. It supports no special operations. There is exactly one null
969object, named \code{None} (a built-in name).
970
971It is written as \code{None}.
972
Fred Drake7a2f0661998-09-10 18:25:58 +0000973
974\subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
Guido van Rossumb193c951998-07-24 15:02:02 +0000975
Fred Drake37f15741999-11-10 16:21:37 +0000976This object is used by extended slice notation (see the
977\citetitle[../ref/ref.html]{Python Reference Manual}). It supports no
978special operations. There is exactly one ellipsis object, named
979\constant{Ellipsis} (a built-in name).
Guido van Rossumb193c951998-07-24 15:02:02 +0000980
981It is written as \code{Ellipsis}.
982
Fred Drakea776cea2000-11-06 20:17:37 +0000983
Fred Drakec3fcd6f1999-04-21 13:58:17 +0000984\subsubsection{File Objects\obindex{file}
985 \label{bltin-file-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000986
Fred Drake4de96c22000-08-12 03:36:23 +0000987File objects are implemented using C's \code{stdio} package and can be
988created with the built-in function
989\function{open()}\bifuncindex{open} described in section
Fred Drake130072d1998-10-28 20:08:35 +0000990\ref{built-in-funcs}, ``Built-in Functions.'' They are also returned
991by some other built-in functions and methods, e.g.,
Fred Drake4de96c22000-08-12 03:36:23 +0000992\function{os.popen()} and \function{os.fdopen()} and the
Fred Drake130072d1998-10-28 20:08:35 +0000993\method{makefile()} method of socket objects.
Fred Drake4de96c22000-08-12 03:36:23 +0000994\refstmodindex{os}
Fred Drake64e3b431998-07-24 13:56:11 +0000995\refbimodindex{socket}
996
997When a file operation fails for an I/O-related reason, the exception
Fred Drake84538cd1998-11-30 21:51:25 +0000998\exception{IOError} is raised. This includes situations where the
999operation is not defined for some reason, like \method{seek()} on a tty
Fred Drake64e3b431998-07-24 13:56:11 +00001000device or writing a file opened for reading.
1001
1002Files have the following methods:
1003
1004
1005\begin{methoddesc}[file]{close}{}
1006 Close the file. A closed file cannot be read or written anymore.
Fred Drakea776cea2000-11-06 20:17:37 +00001007 Any operation which requires that the file be open will raise a
1008 \exception{ValueError} after the file has been closed. Calling
Fred Drake752ba392000-09-19 15:18:51 +00001009 \method{close()} more than once is allowed.
Fred Drake64e3b431998-07-24 13:56:11 +00001010\end{methoddesc}
1011
1012\begin{methoddesc}[file]{flush}{}
Fred Drake752ba392000-09-19 15:18:51 +00001013 Flush the internal buffer, like \code{stdio}'s
1014 \cfunction{fflush()}. This may be a no-op on some file-like
1015 objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001016\end{methoddesc}
1017
1018\begin{methoddesc}[file]{isatty}{}
Fred Drake752ba392000-09-19 15:18:51 +00001019 Return true if the file is connected to a tty(-like) device, else
1020 false. \strong{Note:} If a file-like object is not associated
1021 with a real file, this method should \emph{not} be implemented.
Fred Drake64e3b431998-07-24 13:56:11 +00001022\end{methoddesc}
1023
1024\begin{methoddesc}[file]{fileno}{}
Fred Drake752ba392000-09-19 15:18:51 +00001025 \index{file descriptor}
1026 \index{descriptor, file}
1027 Return the integer ``file descriptor'' that is used by the
1028 underlying implementation to request I/O operations from the
1029 operating system. This can be useful for other, lower level
1030 interfaces that use file descriptors, e.g.\ module
1031 \refmodule{fcntl}\refbimodindex{fcntl} or \function{os.read()} and
1032 friends. \strong{Note:} File-like objects which do not have a real
1033 file descriptor should \emph{not} provide this method!
Fred Drake64e3b431998-07-24 13:56:11 +00001034\end{methoddesc}
1035
1036\begin{methoddesc}[file]{read}{\optional{size}}
1037 Read at most \var{size} bytes from the file (less if the read hits
Fred Drakef4cbada1999-04-14 14:31:53 +00001038 \EOF{} before obtaining \var{size} bytes). If the \var{size}
1039 argument is negative or omitted, read all data until \EOF{} is
1040 reached. The bytes are returned as a string object. An empty
1041 string is returned when \EOF{} is encountered immediately. (For
1042 certain files, like ttys, it makes sense to continue reading after
1043 an \EOF{} is hit.) Note that this method may call the underlying
1044 C function \cfunction{fread()} more than once in an effort to
1045 acquire as close to \var{size} bytes as possible.
Fred Drake64e3b431998-07-24 13:56:11 +00001046\end{methoddesc}
1047
1048\begin{methoddesc}[file]{readline}{\optional{size}}
1049 Read one entire line from the file. A trailing newline character is
Fred Drakeea003fc1999-04-05 21:59:15 +00001050 kept in the string\footnote{
1051 The advantage of leaving the newline on is that an empty string
Fred Drake64e3b431998-07-24 13:56:11 +00001052 can be returned to mean \EOF{} without being ambiguous. Another
1053 advantage is that (in cases where it might matter, e.g. if you
1054 want to make an exact copy of a file while scanning its lines)
1055 you can tell whether the last line of a file ended in a newline
Fred Drake4de96c22000-08-12 03:36:23 +00001056 or not (yes this happens!).
1057 } (but may be absent when a file ends with an
Fred Drake64e3b431998-07-24 13:56:11 +00001058 incomplete line). If the \var{size} argument is present and
1059 non-negative, it is a maximum byte count (including the trailing
1060 newline) and an incomplete line may be returned.
1061 An empty string is returned when \EOF{} is hit
Fred Drake752ba392000-09-19 15:18:51 +00001062 immediately. Note: Unlike \code{stdio}'s \cfunction{fgets()}, the
1063 returned string contains null characters (\code{'\e 0'}) if they
1064 occurred in the input.
Fred Drake64e3b431998-07-24 13:56:11 +00001065\end{methoddesc}
1066
1067\begin{methoddesc}[file]{readlines}{\optional{sizehint}}
1068 Read until \EOF{} using \method{readline()} and return a list containing
1069 the lines thus read. If the optional \var{sizehint} argument is
1070 present, instead of reading up to \EOF{}, whole lines totalling
1071 approximately \var{sizehint} bytes (possibly after rounding up to an
Fred Drake752ba392000-09-19 15:18:51 +00001072 internal buffer size) are read. Objects implementing a file-like
1073 interface may choose to ignore \var{sizehint} if it cannot be
1074 implemented, or cannot be implemented efficiently.
Fred Drake64e3b431998-07-24 13:56:11 +00001075\end{methoddesc}
1076
1077\begin{methoddesc}[file]{seek}{offset\optional{, whence}}
1078 Set the file's current position, like \code{stdio}'s \cfunction{fseek()}.
1079 The \var{whence} argument is optional and defaults to \code{0}
1080 (absolute file positioning); other values are \code{1} (seek
1081 relative to the current position) and \code{2} (seek relative to the
1082 file's end). There is no return value.
1083\end{methoddesc}
1084
1085\begin{methoddesc}[file]{tell}{}
1086 Return the file's current position, like \code{stdio}'s
1087 \cfunction{ftell()}.
1088\end{methoddesc}
1089
1090\begin{methoddesc}[file]{truncate}{\optional{size}}
Fred Drake752ba392000-09-19 15:18:51 +00001091 Truncate the file's size. If the optional \var{size} argument
1092 present, the file is truncated to (at most) that size. The size
1093 defaults to the current position. Availability of this function
1094 depends on the operating system version (for example, not all
1095 \UNIX{} versions support this operation).
Fred Drake64e3b431998-07-24 13:56:11 +00001096\end{methoddesc}
1097
1098\begin{methoddesc}[file]{write}{str}
Fred Drake38e5d272000-04-03 20:13:55 +00001099Write a string to the file. There is no return value. Note: Due to
Fred Drake64e3b431998-07-24 13:56:11 +00001100buffering, the string may not actually show up in the file until
1101the \method{flush()} or \method{close()} method is called.
1102\end{methoddesc}
1103
1104\begin{methoddesc}[file]{writelines}{list}
1105Write a list of strings to the file. There is no return value.
1106(The name is intended to match \method{readlines()};
1107\method{writelines()} does not add line separators.)
1108\end{methoddesc}
1109
1110
Fred Drake752ba392000-09-19 15:18:51 +00001111File objects also offer a number of other interesting attributes.
1112These are not required for file-like objects, but should be
1113implemented if they make sense for the particular object.
Fred Drake64e3b431998-07-24 13:56:11 +00001114
1115\begin{memberdesc}[file]{closed}
1116Boolean indicating the current state of the file object. This is a
1117read-only attribute; the \method{close()} method changes the value.
Fred Drake752ba392000-09-19 15:18:51 +00001118It may not be available on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001119\end{memberdesc}
1120
1121\begin{memberdesc}[file]{mode}
1122The I/O mode for the file. If the file was created using the
1123\function{open()} built-in function, this will be the value of the
Fred Drake752ba392000-09-19 15:18:51 +00001124\var{mode} parameter. This is a read-only attribute and may not be
1125present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001126\end{memberdesc}
1127
1128\begin{memberdesc}[file]{name}
1129If the file object was created using \function{open()}, the name of
1130the file. Otherwise, some string that indicates the source of the
1131file object, of the form \samp{<\mbox{\ldots}>}. This is a read-only
Fred Drake752ba392000-09-19 15:18:51 +00001132attribute and may not be present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001133\end{memberdesc}
1134
1135\begin{memberdesc}[file]{softspace}
1136Boolean that indicates whether a space character needs to be printed
1137before another value when using the \keyword{print} statement.
1138Classes that are trying to simulate a file object should also have a
1139writable \member{softspace} attribute, which should be initialized to
Fred Drake66571cc2000-09-09 03:30:34 +00001140zero. This will be automatic for most classes implemented in Python
1141(care may be needed for objects that override attribute access); types
1142implemented in C will have to provide a writable
1143\member{softspace} attribute.
Fred Drake51f53df2000-09-20 04:48:20 +00001144\strong{Note:} This attribute is not used to control the
1145\keyword{print} statement, but to allow the implementation of
1146\keyword{print} to keep track of its internal state.
Fred Drake64e3b431998-07-24 13:56:11 +00001147\end{memberdesc}
1148
Fred Drakea776cea2000-11-06 20:17:37 +00001149
Fred Drake9474d861999-02-12 22:05:33 +00001150\subsubsection{Internal Objects \label{typesinternal}}
Fred Drake64e3b431998-07-24 13:56:11 +00001151
Fred Drake37f15741999-11-10 16:21:37 +00001152See the \citetitle[../ref/ref.html]{Python Reference Manual} for this
Fred Drake512bb722000-08-18 03:12:38 +00001153information. It describes stack frame objects, traceback objects, and
1154slice objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001155
1156
Fred Drake7a2f0661998-09-10 18:25:58 +00001157\subsection{Special Attributes \label{specialattrs}}
Fred Drake64e3b431998-07-24 13:56:11 +00001158
1159The implementation adds a few special read-only attributes to several
1160object types, where they are relevant:
1161
Fred Drakea776cea2000-11-06 20:17:37 +00001162\begin{memberdesc}[object]{__dict__}
1163A dictionary or other mapping object used to store an
Fred Drake7a2f0661998-09-10 18:25:58 +00001164object's (writable) attributes.
Fred Drakea776cea2000-11-06 20:17:37 +00001165\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001166
Fred Drakea776cea2000-11-06 20:17:37 +00001167\begin{memberdesc}[object]{__methods__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001168List of the methods of many built-in object types,
Fred Drake64e3b431998-07-24 13:56:11 +00001169e.g., \code{[].__methods__} yields
Fred Drake7a2f0661998-09-10 18:25:58 +00001170\code{['append', 'count', 'index', 'insert', 'pop', 'remove',
Fred Drakea776cea2000-11-06 20:17:37 +00001171'reverse', 'sort']}. This usually does not need to be explicitly
1172provided by the object.
1173\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001174
Fred Drakea776cea2000-11-06 20:17:37 +00001175\begin{memberdesc}[object]{__members__}
1176Similar to \member{__methods__}, but lists data attributes. This
1177usually does not need to be explicitly provided by the object.
1178\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001179
Fred Drakea776cea2000-11-06 20:17:37 +00001180\begin{memberdesc}[instance]{__class__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001181The class to which a class instance belongs.
Fred Drakea776cea2000-11-06 20:17:37 +00001182\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001183
Fred Drakea776cea2000-11-06 20:17:37 +00001184\begin{memberdesc}[class]{__bases__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001185The tuple of base classes of a class object.
Fred Drakea776cea2000-11-06 20:17:37 +00001186\end{memberdesc}