blob: 75390f85535ba3fef799217859dc7700ba371473 [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Types}
2
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
12a string (with the \code{`{\rm \ldots}`} notation). The latter conversion is
13implicitly used when an object is written by the \code{print} statement.
14\stindex{print}
15
16\subsection{Truth Value Testing}
17
18Any object can be tested for truth value, for use in an \code{if} or
19\code{while} condition or as operand of the Boolean operations below.
Guido van Rossumecde7811995-03-28 13:35:14 +000020The following values are considered false:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000021\stindex{if}
22\stindex{while}
23\indexii{truth}{value}
24\indexii{Boolean}{operations}
25\index{false}
26
27\begin{itemize}
28\renewcommand{\indexsubitem}{(Built-in object)}
29
30\item \code{None}
31 \ttindex{None}
32
33\item zero of any numeric type, e.g., \code{0}, \code{0L}, \code{0.0}.
34
35\item any empty sequence, e.g., \code{''}, \code{()}, \code{[]}.
36
37\item any empty mapping, e.g., \code{\{\}}.
38
Guido van Rossumecde7811995-03-28 13:35:14 +000039\item instances of user-defined classes, if the class defines a
40 \code{__nonzero__()} or \code{__len__()} method, when that
41 method returns zero.
42
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000043\end{itemize}
44
Guido van Rossumecde7811995-03-28 13:35:14 +000045All other values are considered true --- so objects of many types are
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000046always true.
47\index{true}
48
Guido van Rossumecde7811995-03-28 13:35:14 +000049Operations and built-in functions that have a Boolean result always
50return \code{0} for false and \code{1} for true, unless otherwise
51stated. (Important exception: the Boolean operations \samp{or} and
52\samp{and} always return one of their operands.)
53
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000054\subsection{Boolean Operations}
55
Guido van Rossumecde7811995-03-28 13:35:14 +000056These are the Boolean operations, ordered by ascending priority:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000057\indexii{Boolean}{operations}
58
59\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
60 \lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)}
Guido van Rossumecde7811995-03-28 13:35:14 +000061 \hline
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000062 \lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)}
Guido van Rossumecde7811995-03-28 13:35:14 +000063 \hline
64 \lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{(2)}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000065\end{tableiii}
66\opindex{and}
67\opindex{or}
68\opindex{not}
69
70\noindent
71Notes:
72
73\begin{description}
74
75\item[(1)]
76These only evaluate their second argument if needed for their outcome.
77
Guido van Rossumecde7811995-03-28 13:35:14 +000078\item[(2)]
79\samp{not} has a lower priority than non-Boolean operators, so e.g.
80\code{not a == b} is interpreted as \code{not(a == b)}, and
81\code{a == not b} is a syntax error.
82
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000083\end{description}
84
85\subsection{Comparisons}
86
Guido van Rossumecde7811995-03-28 13:35:14 +000087Comparison operations are supported by all objects. They all have the
88same priority (which is higher than that of the Boolean operations).
89Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is
90equivalent to \code{x < y and y <= z}, except that \code{y} is
91evaluated only once (but in both cases \code{z} is not evaluated at
92all when \code{x < y} is found to be false).
93\indexii{chaining}{comparisons}
94
95This table summarizes the comparison operations:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000096
97\begin{tableiii}{|c|l|c|}{code}{Operation}{Meaning}{Notes}
98 \lineiii{<}{strictly less than}{}
99 \lineiii{<=}{less than or equal}{}
100 \lineiii{>}{strictly greater than}{}
101 \lineiii{>=}{greater than or equal}{}
102 \lineiii{==}{equal}{}
103 \lineiii{<>}{not equal}{(1)}
104 \lineiii{!=}{not equal}{(1)}
105 \lineiii{is}{object identity}{}
106 \lineiii{is not}{negated object identity}{}
107\end{tableiii}
108\indexii{operator}{comparison}
109\opindex{==} % XXX *All* others have funny characters < ! >
110\opindex{is}
111\opindex{is not}
112
113\noindent
114Notes:
115
116\begin{description}
117
118\item[(1)]
119\code{<>} and \code{!=} are alternate spellings for the same operator.
120(I couldn't choose between \ABC{} and \C{}! :-)
121\indexii{\ABC{}}{language}
122\indexii{\C{}}{language}
123
124\end{description}
125
126Objects of different types, except different numeric types, never
127compare equal; such objects are ordered consistently but arbitrarily
128(so that sorting a heterogeneous array yields a consistent result).
129Furthermore, some types (e.g., windows) support only a degenerate
130notion of comparison where any two objects of that type are unequal.
131Again, such objects are ordered arbitrarily but consistently.
132\indexii{types}{numeric}
133\indexii{objects}{comparing}
134
135(Implementation note: objects of different types except numbers are
136ordered by their type names; objects of the same types that don't
137support proper comparison are ordered by their address.)
138
139Two more operations with the same syntactic priority, \code{in} and
140\code{not in}, are supported only by sequence types (below).
141\opindex{in}
142\opindex{not in}
143
144\subsection{Numeric Types}
145
146There are three numeric types: \dfn{plain integers}, \dfn{long integers}, and
147\dfn{floating point numbers}. Plain integers (also just called \dfn{integers})
148are implemented using \code{long} in \C{}, which gives them at least 32
149bits of precision. Long integers have unlimited precision. Floating
150point numbers are implemented using \code{double} in \C{}. All bets on
151their precision are off unless you happen to know the machine you are
152working with.
153\indexii{numeric}{types}
154\indexii{integer}{types}
155\indexii{integer}{type}
156\indexiii{long}{integer}{type}
157\indexii{floating point}{type}
158\indexii{\C{}}{language}
159
160Numbers are created by numeric literals or as the result of built-in
161functions and operators. Unadorned integer literals (including hex
162and octal numbers) yield plain integers. Integer literals with an \samp{L}
163or \samp{l} suffix yield long integers
164(\samp{L} is preferred because \code{1l} looks too much like eleven!).
165Numeric literals containing a decimal point or an exponent sign yield
166floating point numbers.
167\indexii{numeric}{literals}
168\indexii{integer}{literals}
169\indexiii{long}{integer}{literals}
170\indexii{floating point}{literals}
171\indexii{hexadecimal}{literals}
172\indexii{octal}{literals}
173
174Python fully supports mixed arithmetic: when a binary arithmetic
175operator has operands of different numeric types, the operand with the
176``smaller'' type is converted to that of the other, where plain
177integer is smaller than long integer is smaller than floating point.
178Comparisons between numbers of mixed type use the same rule.%
179\footnote{As a consequence, the list \code{[1, 2]} is considered equal
180 to \code{[1.0, 2.0]}, and similar for tuples.}
181The functions \code{int()}, \code{long()} and \code{float()} can be used
182to coerce numbers to a specific type.
183\index{arithmetic}
184\bifuncindex{int}
185\bifuncindex{long}
186\bifuncindex{float}
187
Guido van Rossumecde7811995-03-28 13:35:14 +0000188All numeric types support the following operations, sorted by
189ascending priority (operations in the same box have the same
190priority; all numeric operations have a higher priority than
191comparison operations):
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000192
193\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000194 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
195 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
Guido van Rossumecde7811995-03-28 13:35:14 +0000196 \hline
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000197 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
Guido van Rossumecde7811995-03-28 13:35:14 +0000198 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000199 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
Guido van Rossumecde7811995-03-28 13:35:14 +0000200 \hline
201 \lineiii{-\var{x}}{\var{x} negated}{}
202 \lineiii{+\var{x}}{\var{x} unchanged}{}
203 \hline
204 \lineiii{abs(\var{x})}{absolute value of \var{x}}{}
205 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
206 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
207 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000208 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
209 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
210\end{tableiii}
211\indexiii{operations on}{numeric}{types}
212
213\noindent
214Notes:
215\begin{description}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000216
Guido van Rossumecde7811995-03-28 13:35:14 +0000217\item[(1)]
Guido van Rossum0dbd1fd1995-08-10 14:22:39 +0000218For (plain or long) integer division, the result is an integer.
219The result is always rounded towards minus infinity: 1/2 is 0,
220(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000221\indexii{integer}{division}
222\indexiii{long}{integer}{division}
223
Guido van Rossumecde7811995-03-28 13:35:14 +0000224\item[(2)]
225Conversion from floating point to (long or plain) integer may round or
226truncate as in \C{}; see functions \code{floor()} and \code{ceil()} in
227module \code{math} for well-defined conversions.
228\bifuncindex{floor}
229\bifuncindex{ceil}
230\indexii{numeric}{conversions}
231\stmodindex{math}
232\indexii{\C{}}{language}
233
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000234\item[(3)]
235See the section on built-in functions for an exact definition.
236
237\end{description}
238% XXXJH exceptions: overflow (when? what operations?) zerodivision
239
Guido van Rossum470be141995-03-17 16:07:09 +0000240\subsubsection{Bit-string Operations on Integer Types}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000241\nodename{Bit-string Operations}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000242
243Plain and long integer types support additional operations that make
244sense only for bit-strings. Negative numbers are treated as their 2's
Guido van Rossumecde7811995-03-28 13:35:14 +0000245complement value (for long integers, this assumes a sufficiently large
246number of bits that no overflow occurs during the operation).
247
248The priorities of the binary bit-wise operations are all lower than
249the numeric operations and higher than the comparisons; the unary
250operation \samp{~} has the same priority as the other unary numeric
251operations (\samp{+} and \samp{-}).
252
253This table lists the bit-string operations sorted in ascending
254priority (operations in the same box have the same priority):
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000255
256\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000257 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
Guido van Rossumecde7811995-03-28 13:35:14 +0000258 \hline
259 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
260 \hline
261 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
262 \hline
263 \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
264 \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
265 \hline
266 \hline
267 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000268\end{tableiii}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000269\indexiii{operations on}{integer}{types}
270\indexii{bit-string}{operations}
271\indexii{shifting}{operations}
272\indexii{masking}{operations}
273
Guido van Rossumecde7811995-03-28 13:35:14 +0000274\noindent
275Notes:
276\begin{description}
277\item[(1)] Negative shift counts are illegal.
278\item[(2)] A left shift by \var{n} bits is equivalent to
279multiplication by \code{pow(2, \var{n})} without overflow check.
280\item[(3)] A right shift by \var{n} bits is equivalent to
281division by \code{pow(2, \var{n})} without overflow check.
282\end{description}
283
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000284\subsection{Sequence Types}
285
286There are three sequence types: strings, lists and tuples.
Guido van Rossumecde7811995-03-28 13:35:14 +0000287
288Strings literals are written in single or double quotes:
289\code{'xyzzy'}, \code{"frobozz"}. See Chapter 2 of the Python
290Reference Manual for more about string literals. Lists are
291constructed with square brackets, separating items with commas:
292\code{[a, b, c]}. Tuples are constructed by the comma operator (not
293within square brackets), with or without enclosing parentheses, but an
294empty tuple must have the enclosing parentheses, e.g.,
295\code{a, b, c} or \code{()}. A single item tuple must have a trailing
296comma, e.g., \code{(d,)}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000297\indexii{sequence}{types}
298\indexii{string}{type}
299\indexii{tuple}{type}
300\indexii{list}{type}
301
Guido van Rossumecde7811995-03-28 13:35:14 +0000302Sequence types support the following operations. The \samp{in} and
303\samp{not\,in} operations have the same priorities as the comparison
304operations. The \samp{+} and \samp{*} operations have the same
305priority as the corresponding numeric operations.\footnote{They must
306have since the parser can't tell the type of the operands.}
307
Guido van Rossum96628a91995-04-10 11:34:00 +0000308This table lists the sequence operations sorted in ascending priority
Guido van Rossumecde7811995-03-28 13:35:14 +0000309(operations in the same box have the same priority). In the table,
310\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
311and \var{j} are integers:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000312
313\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
Guido van Rossumecde7811995-03-28 13:35:14 +0000314 \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
315 \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is
316equal to \var{x}, else \code{1}}{}
317 \hline
318 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
319 \hline
320 \lineiii{\var{s} * \var{n}{\rm ,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{}
321 \hline
322 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)}
323 \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)}
324 \hline
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000325 \lineiii{len(\var{s})}{length of \var{s}}{}
326 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
327 \lineiii{max(\var{s})}{largest item of \var{s}}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000328\end{tableiii}
329\indexiii{operations on}{sequence}{types}
330\bifuncindex{len}
331\bifuncindex{min}
332\bifuncindex{max}
333\indexii{concatenation}{operation}
334\indexii{repetition}{operation}
335\indexii{subscript}{operation}
336\indexii{slice}{operation}
337\opindex{in}
338\opindex{not in}
339
340\noindent
341Notes:
342
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000343\begin{description}
344
345\item[(1)] If \var{i} or \var{j} is negative, the index is relative to
346 the end of the string, i.e., \code{len(\var{s}) + \var{i}} or
347 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
348 still \code{0}.
349
350\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as
351 the sequence of items with index \var{k} such that \code{\var{i} <=
352 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
353 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
354 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
355 \var{i} is greater than or equal to \var{j}, the slice is empty.
356
357\end{description}
358
Guido van Rossum470be141995-03-17 16:07:09 +0000359\subsubsection{More String Operations}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000360
361String objects have one unique built-in operation: the \code{\%}
362operator (modulo) with a string left argument interprets this string
363as a C sprintf format string to be applied to the right argument, and
364returns the string resulting from this formatting operation.
365
Guido van Rossum8b605eb1994-06-23 12:14:07 +0000366The right argument should be a tuple with one item for each argument
367required by the format string; if the string requires a single
368argument, the right argument may also be a single non-tuple object.%
369\footnote{A tuple object in this case should be a singleton.}
370The following format characters are understood:
371\%, c, s, i, d, u, o, x, X, e, E, f, g, G.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000372Width and precision may be a * to specify that an integer argument
373specifies the actual width or precision. The flag characters -, +,
374blank, \# and 0 are understood. The size specifiers h, l or L may be
Guido van Rossum17383111994-04-21 10:32:28 +0000375present but are ignored. The \code{\%s} conversion takes any Python
376object and converts it to a string using \code{str()} before
377formatting it. The ANSI features \code{\%p} and \code{\%n}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000378are not supported. Since Python strings have an explicit length,
Guido van Rossum470be141995-03-17 16:07:09 +0000379\code{\%s} conversions don't assume that \code{'\e0'} is the end of
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000380the string.
381
Guido van Rossume6ef0321994-05-09 14:54:24 +0000382For safety reasons, floating point precisions are clipped to 50;
383\code{\%f} conversions for numbers whose absolute value is over 1e25
384are replaced by \code{\%g} conversions.%
385\footnote{These numbers are fairly arbitrary. They are intended to
386avoid printing endless strings of meaningless digits without hampering
387correct use and without having to know the exact precision of floating
388point values on a particular machine.}
389All other errors raise exceptions.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000390
Guido van Rossum17383111994-04-21 10:32:28 +0000391If the right argument is a dictionary (or any kind of mapping), then
392the formats in the string must have a parenthesized key into that
393dictionary inserted immediately after the \code{\%} character, and
394each format formats the corresponding entry from the mapping. E.g.
395\begin{verbatim}
396 >>> count = 2
397 >>> language = 'Python'
398 >>> print '%(language)s has %(count)03d quote types.' % vars()
399 Python has 002 quote types.
400 >>>
401\end{verbatim}
Fred Drake4bf12961996-10-11 16:33:48 +0000402In this case no * specifiers may occur in a format (since they
403require a sequential parameter list).
Guido van Rossum17383111994-04-21 10:32:28 +0000404
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000405Additional string operations are defined in standard module
406\code{string} and in built-in module \code{regex}.
407\index{string}
408\index{regex}
409
Guido van Rossum470be141995-03-17 16:07:09 +0000410\subsubsection{Mutable Sequence Types}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000411
412List objects support additional operations that allow in-place
413modification of the object.
414These operations would be supported by other mutable sequence types
415(when added to the language) as well.
416Strings and tuples are immutable sequence types and such objects cannot
417be modified once created.
418The following operations are defined on mutable sequence types (where
419\var{x} is an arbitrary object):
420\indexiii{mutable}{sequence}{types}
421\indexii{list}{type}
422
423\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
424 \lineiii{\var{s}[\var{i}] = \var{x}}
425 {item \var{i} of \var{s} is replaced by \var{x}}{}
426 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
427 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
428 \lineiii{del \var{s}[\var{i}:\var{j}]}
429 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
430 \lineiii{\var{s}.append(\var{x})}
Guido van Rossume6ef0321994-05-09 14:54:24 +0000431 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000432 \lineiii{\var{s}.count(\var{x})}
433 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
434 \lineiii{\var{s}.index(\var{x})}
435 {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)}
436 \lineiii{\var{s}.insert(\var{i}, \var{x})}
Guido van Rossum95a5b9c1995-07-07 23:03:07 +0000437 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
438 if \code{\var{i} >= 0}}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000439 \lineiii{\var{s}.remove(\var{x})}
440 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)}
441 \lineiii{\var{s}.reverse()}
442 {reverses the items of \var{s} in place}{}
443 \lineiii{\var{s}.sort()}
444 {permutes the items of \var{s} to satisfy
445 \code{\var{s}[\var{i}] <= \var{s}[\var{j}]},
446 for \code{\var{i} < \var{j}}}{(2)}
447\end{tableiii}
448\indexiv{operations on}{mutable}{sequence}{types}
449\indexiii{operations on}{sequence}{types}
450\indexiii{operations on}{list}{type}
451\indexii{subscript}{assignment}
452\indexii{slice}{assignment}
453\stindex{del}
454\renewcommand{\indexsubitem}{(list method)}
455\ttindex{append}
456\ttindex{count}
457\ttindex{index}
458\ttindex{insert}
459\ttindex{remove}
460\ttindex{reverse}
461\ttindex{sort}
462
463\noindent
464Notes:
465\begin{description}
466\item[(1)] Raises an exception when \var{x} is not found in \var{s}.
467
468\item[(2)] The \code{sort()} method takes an optional argument
469 specifying a comparison function of two arguments (list items) which
470 should return \code{-1}, \code{0} or \code{1} depending on whether the
471 first argument is considered smaller than, equal to, or larger than the
472 second argument. Note that this slows the sorting process down
Guido van Rossum470be141995-03-17 16:07:09 +0000473 considerably; e.g. to sort a list in reverse order it is much faster
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000474 to use calls to \code{sort()} and \code{reverse()} than to use
475 \code{sort()} with a comparison function that reverses the ordering of
476 the elements.
477\end{description}
478
479\subsection{Mapping Types}
480
481A \dfn{mapping} object maps values of one type (the key type) to
482arbitrary objects. Mappings are mutable objects. There is currently
Guido van Rossum470be141995-03-17 16:07:09 +0000483only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000484almost arbitrary values. The only types of values not acceptable as
485keys are values containing lists or dictionaries or other mutable
486types that are compared by value rather than by object identity.
487Numeric types used for keys obey the normal rules for numeric
488comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
489can be used interchangeably to index the same dictionary entry.
490
491\indexii{mapping}{types}
492\indexii{dictionary}{type}
493
494Dictionaries are created by placing a comma-separated list of
Guido van Rossum1dde7b71996-10-11 15:57:17 +0000495\code{\var{key}:\,\var{value}} pairs within braces, for example:
Guido van Rossumecde7811995-03-28 13:35:14 +0000496\code{\{'jack':\,4098, 'sjoerd':\,4127\}} or
497\code{\{4098:\,'jack', 4127:\,'sjoerd'\}}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000498
499The following operations are defined on mappings (where \var{a} is a
500mapping, \var{k} is a key and \var{x} is an arbitrary object):
501
502\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
503 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
504 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
505 \lineiii{\var{a}[\var{k}] = \var{x}}{set \code{\var{a}[\var{k}]} to \var{x}}{}
506 \lineiii{del \var{a}[\var{k}]}{remove \code{\var{a}[\var{k}]} from \var{a}}{(1)}
507 \lineiii{\var{a}.items()}{a copy of \var{a}'s list of (key, item) pairs}{(2)}
508 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)}
509 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)}
510 \lineiii{\var{a}.has_key(\var{k})}{\code{1} if \var{a} has a key \var{k}, else \code{0}}{}
511\end{tableiii}
512\indexiii{operations on}{mapping}{types}
513\indexiii{operations on}{dictionary}{type}
514\stindex{del}
515\bifuncindex{len}
516\renewcommand{\indexsubitem}{(dictionary method)}
517\ttindex{keys}
518\ttindex{has_key}
519
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000520\noindent
521Notes:
522\begin{description}
523\item[(1)] Raises an exception if \var{k} is not in the map.
524
Guido van Rossum470be141995-03-17 16:07:09 +0000525\item[(2)] Keys and values are listed in random order.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000526\end{description}
527
528\subsection{Other Built-in Types}
529
530The interpreter supports several other kinds of objects.
531Most of these support only one or two operations.
532
Guido van Rossum470be141995-03-17 16:07:09 +0000533\subsubsection{Modules}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000534
535The only special operation on a module is attribute access:
536\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name} accesses
537a name defined in \var{m}'s symbol table. Module attributes can be
538assigned to. (Note that the \code{import} statement is not, strictly
539spoken, an operation on a module object; \code{import \var{foo}} does not
540require a module object named \var{foo} to exist, rather it requires
541an (external) \emph{definition} for a module named \var{foo}
542somewhere.)
543
544A special member of every module is \code{__dict__}.
545This is the dictionary containing the module's symbol table.
546Modifying this dictionary will actually change the module's symbol
547table, but direct assignment to the \code{__dict__} attribute is not
548possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which
549defines \code{\var{m}.a} to be \code{1}, but you can't write \code{\var{m}.__dict__ = \{\}}.
550
551Modules are written like this: \code{<module 'sys'>}.
552
Guido van Rossum470be141995-03-17 16:07:09 +0000553\subsubsection{Classes and Class Instances}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000554\nodename{Classes and Instances}
Guido van Rossumecde7811995-03-28 13:35:14 +0000555
556(See Chapters 3 and 7 of the Python Reference Manual for these.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000557
Guido van Rossum470be141995-03-17 16:07:09 +0000558\subsubsection{Functions}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000559
560Function objects are created by function definitions. The only
561operation on a function object is to call it:
562\code{\var{func}(\var{argument-list})}.
563
564There are really two flavors of function objects: built-in functions
565and user-defined functions. Both support the same operation (to call
566the function), but the implementation is different, hence the
567different object types.
568
569The implementation adds two special read-only attributes:
570\code{\var{f}.func_code} is a function's \dfn{code object} (see below) and
571\code{\var{f}.func_globals} is the dictionary used as the function's
572global name space (this is the same as \code{\var{m}.__dict__} where
573\var{m} is the module in which the function \var{f} was defined).
574
Guido van Rossum470be141995-03-17 16:07:09 +0000575\subsubsection{Methods}
Guido van Rossumea6e19c1995-03-07 10:11:15 +0000576\obindex{method}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000577
578Methods are functions that are called using the attribute notation.
579There are two flavors: built-in methods (such as \code{append()} on
580lists) and class instance methods. Built-in methods are described
581with the types that support them.
582
583The implementation adds two special read-only attributes to class
584instance methods: \code{\var{m}.im_self} is the object whose method this
585is, and \code{\var{m}.im_func} is the function implementing the method.
586Calling \code{\var{m}(\var{arg-1}, \var{arg-2}, {\rm \ldots},
587\var{arg-n})} is completely equivalent to calling
588\code{\var{m}.im_func(\var{m}.im_self, \var{arg-1}, \var{arg-2}, {\rm
589\ldots}, \var{arg-n})}.
590
591(See the Python Reference Manual for more info.)
592
Guido van Rossum470be141995-03-17 16:07:09 +0000593\subsubsection{Code Objects}
Guido van Rossumea6e19c1995-03-07 10:11:15 +0000594\obindex{code}
595
596Code objects are used by the implementation to represent
597``pseudo-compiled'' executable Python code such as a function body.
598They differ from function objects because they don't contain a
599reference to their global execution environment. Code objects are
600returned by the built-in \code{compile()} function and can be
601extracted from function objects through their \code{func_code}
602attribute.
603\bifuncindex{compile}
604\ttindex{func_code}
605
606A code object can be executed or evaluated by passing it (instead of a
607source string) to the \code{exec} statement or the built-in
608\code{eval()} function.
609\stindex{exec}
610\bifuncindex{eval}
611
612(See the Python Reference Manual for more info.)
613
Guido van Rossum470be141995-03-17 16:07:09 +0000614\subsubsection{Type Objects}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000615
616Type objects represent the various object types. An object's type is
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000617accessed by the built-in function \code{type()}. There are no special
Guido van Rossumecde7811995-03-28 13:35:14 +0000618operations on types. The standard module \code{types} defines names
619for all standard built-in types.
620\bifuncindex{type}
621\stmodindex{types}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000622
623Types are written like this: \code{<type 'int'>}.
624
Guido van Rossum470be141995-03-17 16:07:09 +0000625\subsubsection{The Null Object}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000626
627This object is returned by functions that don't explicitly return a
628value. It supports no special operations. There is exactly one null
629object, named \code{None} (a built-in name).
630
631It is written as \code{None}.
632
Guido van Rossum470be141995-03-17 16:07:09 +0000633\subsubsection{File Objects}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000634
635File objects are implemented using \C{}'s \code{stdio} package and can be
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000636created with the built-in function \code{open()} described under
Guido van Rossumecde7811995-03-28 13:35:14 +0000637Built-in Functions below. They are also returned by some other
638built-in functions and methods, e.g.\ \code{posix.popen()} and
639\code{posix.fdopen()} and the \code{makefile()} method of socket
640objects.
641\bifuncindex{open}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000642
643When a file operation fails for an I/O-related reason, the exception
644\code{IOError} is raised. This includes situations where the
645operation is not defined for some reason, like \code{seek()} on a tty
646device or writing a file opened for reading.
647
648Files have the following methods:
649
650
651\renewcommand{\indexsubitem}{(file method)}
652
653\begin{funcdesc}{close}{}
654 Close the file. A closed file cannot be read or written anymore.
655\end{funcdesc}
656
657\begin{funcdesc}{flush}{}
658 Flush the internal buffer, like \code{stdio}'s \code{fflush()}.
659\end{funcdesc}
660
661\begin{funcdesc}{isatty}{}
662 Return \code{1} if the file is connected to a tty(-like) device, else
663 \code{0}.
664\end{funcdesc}
665
Guido van Rossum0dbd1fd1995-08-10 14:22:39 +0000666\begin{funcdesc}{read}{\optional{size}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000667 Read at most \var{size} bytes from the file (less if the read hits
668 \EOF{} or no more data is immediately available on a pipe, tty or
Guido van Rossum0dbd1fd1995-08-10 14:22:39 +0000669 similar device). If the \var{size} argument is negative or omitted,
670 read all data until \EOF{} is reached. The bytes are returned as a string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000671 object. An empty string is returned when \EOF{} is encountered
672 immediately. (For certain files, like ttys, it makes sense to
673 continue reading after an \EOF{} is hit.)
674\end{funcdesc}
675
Jack Jansen45185771995-08-14 13:38:36 +0000676\begin{funcdesc}{readline}{\optional{size}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000677 Read one entire line from the file. A trailing newline character is
Guido van Rossum31cce971995-01-04 19:17:34 +0000678 kept in the string%
679\footnote{The advantage of leaving the newline on is that an empty string
680 can be returned to mean \EOF{} without being ambiguous. Another
681 advantage is that (in cases where it might matter, e.g. if you
682 want to make an exact copy of a file while scanning its lines)
683 you can tell whether the last line of a file ended in a newline
684 or not (yes this happens!).}
685 (but may be absent when a file ends with an
Guido van Rossum1dde7b71996-10-11 15:57:17 +0000686 incomplete line). If the \var{size} argument is present and
Guido van Rossum0dbd1fd1995-08-10 14:22:39 +0000687 non-negative, it is a maximum byte count (including the trailing
688 newline) and an incomplete line may be returned.
689 An empty string is returned when \EOF{} is hit
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000690 immediately. Note: unlike \code{stdio}'s \code{fgets()}, the returned
691 string contains null characters (\code{'\e 0'}) if they occurred in the
692 input.
693\end{funcdesc}
694
695\begin{funcdesc}{readlines}{}
696 Read until \EOF{} using \code{readline()} and return a list containing
697 the lines thus read.
698\end{funcdesc}
699
700\begin{funcdesc}{seek}{offset\, whence}
701 Set the file's current position, like \code{stdio}'s \code{fseek()}.
702 The \var{whence} argument is optional and defaults to \code{0}
703 (absolute file positioning); other values are \code{1} (seek
704 relative to the current position) and \code{2} (seek relative to the
705 file's end). There is no return value.
706\end{funcdesc}
707
708\begin{funcdesc}{tell}{}
709 Return the file's current position, like \code{stdio}'s \code{ftell()}.
710\end{funcdesc}
711
Guido van Rossum316a4301996-05-02 15:28:53 +0000712\begin{funcdesc}{truncate}{\optional{size}}
713Truncate the file's size. If the optional size argument present, the
714file is truncated to (at most) that size. The size defaults to the
715current position. Availability of this function depends on the
Guido van Rossum1dde7b71996-10-11 15:57:17 +0000716operating system version (e.g., not all \UNIX{} versions support this
Guido van Rossum316a4301996-05-02 15:28:53 +0000717operation).
718\end{funcdesc}
719
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000720\begin{funcdesc}{write}{str}
Guido van Rossum316a4301996-05-02 15:28:53 +0000721Write a string to the file. There is no return value. Note: due to
722buffering, the string may not actually show up in the file until
723the \code{flush()} or \code{close()} method is called.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000724\end{funcdesc}
725
Guido van Rossum8b605eb1994-06-23 12:14:07 +0000726\begin{funcdesc}{writelines}{list}
727Write a list of strings to the file. There is no return value.
728(The name is intended to match \code{readlines}; \code{writelines}
729does not add line separators.)
730\end{funcdesc}
731
Guido van Rossum470be141995-03-17 16:07:09 +0000732\subsubsection{Internal Objects}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000733
734(See the Python Reference Manual for these.)
735
736\subsection{Special Attributes}
737
738The implementation adds a few special read-only attributes to several
739object types, where they are relevant:
740
741\begin{itemize}
742
743\item
744\code{\var{x}.__dict__} is a dictionary of some sort used to store an
745object's (writable) attributes;
746
747\item
748\code{\var{x}.__methods__} lists the methods of many built-in object types,
Guido van Rossumecde7811995-03-28 13:35:14 +0000749e.g., \code{[].__methods__} yields
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000750\code{['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']};
751
752\item
753\code{\var{x}.__members__} lists data attributes;
754
755\item
756\code{\var{x}.__class__} is the class to which a class instance belongs;
757
758\item
759\code{\var{x}.__bases__} is the tuple of base classes of a class object.
760
761\end{itemize}