blob: ff31c5e353bc774a8a2cb7d125b0f81769c3e699 [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
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
Fred Drake7a2f0661998-09-10 18:25:58 +000017\subsection{Truth Value Testing \label{truth}}
Fred Drake64e3b431998-07-24 13:56:11 +000018
19Any object can be tested for truth value, for use in an \code{if} or
20\code{while} condition or as operand of the Boolean operations below.
21The 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
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
39\item instances of user-defined classes, if the class defines a
Fred Drake7a2f0661998-09-10 18:25:58 +000040 \method{__nonzero__()} or \method{__len__()} method, when that
Fred Drake64e3b431998-07-24 13:56:11 +000041 method returns zero.
42
43\end{itemize}
44
45All other values are considered true --- so objects of many types are
46always true.
47\index{true}
48
49Operations 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
52\samp{or}\opindex{or} and \samp{and}\opindex{and} always return one of
53their operands.)
54
55
Fred Drake7a2f0661998-09-10 18:25:58 +000056\subsection{Boolean Operations \label{boolean}}
Fred Drake64e3b431998-07-24 13:56:11 +000057
58These are the Boolean operations, ordered by ascending priority:
59\indexii{Boolean}{operations}
60
61\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
62 \lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)}
63 \lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)}
64 \hline
65 \lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{(2)}
66\end{tableiii}
67\opindex{and}
68\opindex{or}
69\opindex{not}
70
71\noindent
72Notes:
73
74\begin{description}
75
76\item[(1)]
77These only evaluate their second argument if needed for their outcome.
78
79\item[(2)]
80\samp{not} has a lower priority than non-Boolean operators, so e.g.
81\code{not a == b} is interpreted as \code{not(a == b)}, and
82\code{a == not b} is a syntax error.
83
84\end{description}
85
86
Fred Drake7a2f0661998-09-10 18:25:58 +000087\subsection{Comparisons \label{comparisons}}
Fred Drake64e3b431998-07-24 13:56:11 +000088
89Comparison operations are supported by all objects. They all have the
90same priority (which is higher than that of the Boolean operations).
91Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is
92equivalent to \code{x < y and y <= z}, except that \code{y} is
93evaluated only once (but in both cases \code{z} is not evaluated at
94all when \code{x < y} is found to be false).
95\indexii{chaining}{comparisons}
96
97This table summarizes the comparison operations:
98
99\begin{tableiii}{c|l|c}{code}{Operation}{Meaning}{Notes}
100 \lineiii{<}{strictly less than}{}
101 \lineiii{<=}{less than or equal}{}
102 \lineiii{>}{strictly greater than}{}
103 \lineiii{>=}{greater than or equal}{}
104 \lineiii{==}{equal}{}
105 \lineiii{<>}{not equal}{(1)}
106 \lineiii{!=}{not equal}{(1)}
107 \lineiii{is}{object identity}{}
108 \lineiii{is not}{negated object identity}{}
109\end{tableiii}
110\indexii{operator}{comparison}
111\opindex{==} % XXX *All* others have funny characters < ! >
112\opindex{is}
113\opindex{is not}
114
115\noindent
116Notes:
117
118\begin{description}
119
120\item[(1)]
121\code{<>} and \code{!=} are alternate spellings for the same operator.
122(I couldn't choose between \ABC{} and \C{}! :-)
123\index{ABC language@\ABC{} language}
124\index{language!ABC@\ABC{}}
125\indexii{C@\C{}}{language}
126
127\end{description}
128
129Objects of different types, except different numeric types, never
130compare equal; such objects are ordered consistently but arbitrarily
131(so that sorting a heterogeneous array yields a consistent result).
132Furthermore, some types (e.g., windows) support only a degenerate
133notion of comparison where any two objects of that type are unequal.
134Again, such objects are ordered arbitrarily but consistently.
135\indexii{types}{numeric}
136\indexii{objects}{comparing}
137
138(Implementation note: objects of different types except numbers are
139ordered by their type names; objects of the same types that don't
140support proper comparison are ordered by their address.)
141
142Two more operations with the same syntactic priority, \samp{in} and
143\samp{not in}, are supported only by sequence types (below).
144\opindex{in}
145\opindex{not in}
146
147
Fred Drake7a2f0661998-09-10 18:25:58 +0000148\subsection{Numeric Types \label{typesnumeric}}
Fred Drake64e3b431998-07-24 13:56:11 +0000149
150There are four numeric types: \dfn{plain integers}, \dfn{long integers},
151\dfn{floating point numbers}, and \dfn{complex numbers}.
152Plain integers (also just called \dfn{integers})
153are implemented using \code{long} in \C{}, which gives them at least 32
154bits of precision. Long integers have unlimited precision. Floating
155point numbers are implemented using \code{double} in \C{}. All bets on
156their precision are off unless you happen to know the machine you are
157working with.
158\indexii{numeric}{types}
159\indexii{integer}{types}
160\indexii{integer}{type}
161\indexiii{long}{integer}{type}
162\indexii{floating point}{type}
163\indexii{complex number}{type}
164\indexii{C@\C{}}{language}
165
166Complex numbers have a real and imaginary part, which are both
167implemented using \code{double} in \C{}. To extract these parts from
168a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
169
170Numbers are created by numeric literals or as the result of built-in
171functions and operators. Unadorned integer literals (including hex
172and octal numbers) yield plain integers. Integer literals with an \samp{L}
173or \samp{l} suffix yield long integers
174(\samp{L} is preferred because \samp{1l} looks too much like eleven!).
175Numeric literals containing a decimal point or an exponent sign yield
176floating point numbers. Appending \samp{j} or \samp{J} to a numeric
177literal yields a complex number.
178\indexii{numeric}{literals}
179\indexii{integer}{literals}
180\indexiii{long}{integer}{literals}
181\indexii{floating point}{literals}
182\indexii{complex number}{literals}
183\indexii{hexadecimal}{literals}
184\indexii{octal}{literals}
185
186Python fully supports mixed arithmetic: when a binary arithmetic
187operator has operands of different numeric types, the operand with the
188``smaller'' type is converted to that of the other, where plain
189integer is smaller than long integer is smaller than floating point is
190smaller than complex.
191Comparisons between numbers of mixed type use the same rule.%
192\footnote{As a consequence, the list \code{[1, 2]} is considered equal
193 to \code{[1.0, 2.0]}, and similar for tuples.}
194The functions \code{int()}, \code{long()}, \code{float()},
195and \code{complex()} can be used
196to coerce numbers to a specific type.
197\index{arithmetic}
198\bifuncindex{int}
199\bifuncindex{long}
200\bifuncindex{float}
201\bifuncindex{complex}
202
203All numeric types support the following operations, sorted by
204ascending priority (operations in the same box have the same
205priority; all numeric operations have a higher priority than
206comparison operations):
207
208\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
209 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
210 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
211 \hline
212 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
213 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
214 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
215 \hline
216 \lineiii{-\var{x}}{\var{x} negated}{}
217 \lineiii{+\var{x}}{\var{x} unchanged}{}
218 \hline
219 \lineiii{abs(\var{x})}{absolute value or magnitude of \var{x}}{}
220 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
221 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
222 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
223 \lineiii{complex(\var{re},\var{im})}{a complex number with real part \var{re}, imaginary part \var{im}. \var{im} defaults to zero.}{}
224 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
225 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
226 \lineiii{\var{x} ** \var{y}}{\var{x} to the power \var{y}}{}
227\end{tableiii}
228\indexiii{operations on}{numeric}{types}
229
230\noindent
231Notes:
232\begin{description}
233
234\item[(1)]
235For (plain or long) integer division, the result is an integer.
236The result is always rounded towards minus infinity: 1/2 is 0,
237(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.
238\indexii{integer}{division}
239\indexiii{long}{integer}{division}
240
241\item[(2)]
242Conversion from floating point to (long or plain) integer may round or
243truncate as in \C{}; see functions \code{floor()} and \code{ceil()} in
244module \code{math} for well-defined conversions.
245\bifuncindex{floor}
246\bifuncindex{ceil}
247\indexii{numeric}{conversions}
248\refbimodindex{math}
249\indexii{C@\C{}}{language}
250
251\item[(3)]
252See the section on built-in functions for an exact definition.
253
254\end{description}
255% XXXJH exceptions: overflow (when? what operations?) zerodivision
256
257\subsubsection{Bit-string Operations on Integer Types}
258\nodename{Bit-string Operations}
259
260Plain and long integer types support additional operations that make
261sense only for bit-strings. Negative numbers are treated as their 2's
262complement value (for long integers, this assumes a sufficiently large
263number of bits that no overflow occurs during the operation).
264
265The priorities of the binary bit-wise operations are all lower than
266the numeric operations and higher than the comparisons; the unary
267operation \samp{\~} has the same priority as the other unary numeric
268operations (\samp{+} and \samp{-}).
269
270This table lists the bit-string operations sorted in ascending
271priority (operations in the same box have the same priority):
272
273\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
274 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
275 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
276 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
277 \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
278 \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
279 \hline
280 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
281\end{tableiii}
282\indexiii{operations on}{integer}{types}
283\indexii{bit-string}{operations}
284\indexii{shifting}{operations}
285\indexii{masking}{operations}
286
287\noindent
288Notes:
289\begin{description}
290\item[(1)] Negative shift counts are illegal and cause a
291\exception{ValueError} to be raised.
292\item[(2)] A left shift by \var{n} bits is equivalent to
293multiplication by \code{pow(2, \var{n})} without overflow check.
294\item[(3)] A right shift by \var{n} bits is equivalent to
295division by \code{pow(2, \var{n})} without overflow check.
296\end{description}
297
298
Fred Drake7a2f0661998-09-10 18:25:58 +0000299\subsection{Sequence Types \label{typesseq}}
Fred Drake64e3b431998-07-24 13:56:11 +0000300
301There are three sequence types: strings, lists and tuples.
302
303Strings literals are written in single or double quotes:
304\code{'xyzzy'}, \code{"frobozz"}. See Chapter 2 of the \emph{Python
305Reference Manual} for more about string literals. Lists are
306constructed with square brackets, separating items with commas:
307\code{[a, b, c]}. Tuples are constructed by the comma operator (not
308within square brackets), with or without enclosing parentheses, but an
309empty tuple must have the enclosing parentheses, e.g.,
310\code{a, b, c} or \code{()}. A single item tuple must have a trailing
311comma, e.g., \code{(d,)}.
312\indexii{sequence}{types}
313\indexii{string}{type}
314\indexii{tuple}{type}
315\indexii{list}{type}
316
317Sequence types support the following operations. The \samp{in} and
318\samp{not in} operations have the same priorities as the comparison
319operations. The \samp{+} and \samp{*} operations have the same
320priority as the corresponding numeric operations.\footnote{They must
321have since the parser can't tell the type of the operands.}
322
323This table lists the sequence operations sorted in ascending priority
324(operations in the same box have the same priority). In the table,
325\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
326and \var{j} are integers:
327
328\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
329 \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
330 \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is
331equal to \var{x}, else \code{1}}{}
332 \hline
333 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
334 \lineiii{\var{s} * \var{n}{\rm ,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{(3)}
335 \hline
336 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)}
337 \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)}
338 \hline
339 \lineiii{len(\var{s})}{length of \var{s}}{}
340 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
341 \lineiii{max(\var{s})}{largest item of \var{s}}{}
342\end{tableiii}
343\indexiii{operations on}{sequence}{types}
344\bifuncindex{len}
345\bifuncindex{min}
346\bifuncindex{max}
347\indexii{concatenation}{operation}
348\indexii{repetition}{operation}
349\indexii{subscript}{operation}
350\indexii{slice}{operation}
351\opindex{in}
352\opindex{not in}
353
354\noindent
355Notes:
356
357\begin{description}
358
359\item[(1)] If \var{i} or \var{j} is negative, the index is relative to
360 the end of the string, i.e., \code{len(\var{s}) + \var{i}} or
361 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
362 still \code{0}.
363
364\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as
365 the sequence of items with index \var{k} such that \code{\var{i} <=
366 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
367 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
368 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
369 \var{i} is greater than or equal to \var{j}, the slice is empty.
370
371\item[(3)] Values of \var{n} less than \code{0} are treated as
372 \code{0} (which yields an empty sequence of the same type as
373 \var{s}).
374
375\end{description}
376
377\subsubsection{More String Operations}
378
379String objects have one unique built-in operation: the \code{\%}
380operator (modulo) with a string left argument interprets this string
381as a \C{} \cfunction{sprintf()} format string to be applied to the
382right argument, and returns the string resulting from this formatting
383operation.
384
385The right argument should be a tuple with one item for each argument
386required by the format string; if the string requires a single
387argument, the right argument may also be a single non-tuple object.%
388\footnote{A tuple object in this case should be a singleton.}
389The following format characters are understood:
390\code{\%}, \code{c}, \code{s}, \code{i}, \code{d}, \code{u}, \code{o},
391\code{x}, \code{X}, \code{e}, \code{E}, \code{f}, \code{g}, \code{G}.
392Width and precision may be a \code{*} to specify that an integer argument
393specifies the actual width or precision. The flag characters
394\code{-}, \code{+}, blank, \code{\#} and \code{0} are understood. The
395size specifiers \code{h}, \code{l} or \code{L} may be
396present but are ignored. The \code{\%s} conversion takes any Python
397object and converts it to a string using \code{str()} before
398formatting it. The ANSI features \code{\%p} and \code{\%n}
399are not supported. Since Python strings have an explicit length,
400\code{\%s} conversions don't assume that \code{'\e0'} is the end of
401the string.
402
403For safety reasons, floating point precisions are clipped to 50;
404\code{\%f} conversions for numbers whose absolute value is over 1e25
405are replaced by \code{\%g} conversions.%
406\footnote{These numbers are fairly arbitrary. They are intended to
407avoid printing endless strings of meaningless digits without hampering
408correct use and without having to know the exact precision of floating
409point values on a particular machine.}
410All other errors raise exceptions.
411
412If the right argument is a dictionary (or any kind of mapping), then
413the formats in the string must have a parenthesized key into that
414dictionary inserted immediately after the \character{\%} character,
415and each format formats the corresponding entry from the mapping.
416For example:
417
418\begin{verbatim}
419>>> count = 2
420>>> language = 'Python'
421>>> print '%(language)s has %(count)03d quote types.' % vars()
422Python has 002 quote types.
423\end{verbatim}
424
425In this case no \code{*} specifiers may occur in a format (since they
426require a sequential parameter list).
427
428Additional string operations are defined in standard module
429\module{string} and in built-in module \module{re}.
430\refstmodindex{string}
Fred Drake66da9d61998-08-07 18:57:18 +0000431\refstmodindex{re}
Fred Drake64e3b431998-07-24 13:56:11 +0000432
433\subsubsection{Mutable Sequence Types}
434
435List objects support additional operations that allow in-place
436modification of the object.
437These operations would be supported by other mutable sequence types
438(when added to the language) as well.
439Strings and tuples are immutable sequence types and such objects cannot
440be modified once created.
441The following operations are defined on mutable sequence types (where
442\var{x} is an arbitrary object):
443\indexiii{mutable}{sequence}{types}
444\indexii{list}{type}
445
446\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
447 \lineiii{\var{s}[\var{i}] = \var{x}}
448 {item \var{i} of \var{s} is replaced by \var{x}}{}
449 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
450 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
451 \lineiii{del \var{s}[\var{i}:\var{j}]}
452 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
453 \lineiii{\var{s}.append(\var{x})}
454 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{}
455 \lineiii{\var{s}.count(\var{x})}
456 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
457 \lineiii{\var{s}.index(\var{x})}
458 {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)}
459 \lineiii{\var{s}.insert(\var{i}, \var{x})}
460 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
461 if \code{\var{i} >= 0}}{}
462 \lineiii{\var{s}.pop(\optional{\var{i}})}
463 {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(4)}
464 \lineiii{\var{s}.remove(\var{x})}
465 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)}
466 \lineiii{\var{s}.reverse()}
467 {reverses the items of \var{s} in place}{(3)}
468 \lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
469 {sort the items of \var{s} in place}{(2), (3)}
470\end{tableiii}
471\indexiv{operations on}{mutable}{sequence}{types}
472\indexiii{operations on}{sequence}{types}
473\indexiii{operations on}{list}{type}
474\indexii{subscript}{assignment}
475\indexii{slice}{assignment}
476\stindex{del}
Fred Drake7a2f0661998-09-10 18:25:58 +0000477\withsubitem{(list method)}{%
478 \ttindex{append}%
479 \ttindex{count}%
480 \ttindex{index}%
481 \ttindex{insert}%
482 \ttindex{pop}%
483 \ttindex{remove}%
484 \ttindex{reverse}%
485 \ttindex{sort}%
486}
Fred Drake64e3b431998-07-24 13:56:11 +0000487\noindent
488Notes:
489\begin{description}
490\item[(1)] Raises an exception when \var{x} is not found in \var{s}.
491
492\item[(2)] The \code{sort()} method takes an optional argument
493 specifying a comparison function of two arguments (list items) which
494 should return \code{-1}, \code{0} or \code{1} depending on whether the
495 first argument is considered smaller than, equal to, or larger than the
496 second argument. Note that this slows the sorting process down
497 considerably; e.g. to sort a list in reverse order it is much faster
498 to use calls to \code{sort()} and \code{reverse()} than to use
499 \code{sort()} with a comparison function that reverses the ordering of
500 the elements.
501
502\item[(3)] The \code{sort()} and \code{reverse()} methods modify the
503list in place for economy of space when sorting or reversing a large
504list. They don't return the sorted or reversed list to remind you of
505this side effect.
506
507\item[(4)] The \method{pop()} method is experimental and not supported
508by other mutable sequence types than lists.
509The optional argument \var{i} defaults to \code{-1}, so that
510by default the last item is removed and returned.
511
512\end{description}
513
514
Fred Drake7a2f0661998-09-10 18:25:58 +0000515\subsection{Mapping Types \label{typesmapping}}
Fred Drake64e3b431998-07-24 13:56:11 +0000516
517A \dfn{mapping} object maps values of one type (the key type) to
518arbitrary objects. Mappings are mutable objects. There is currently
519only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
520almost arbitrary values. The only types of values not acceptable as
521keys are values containing lists or dictionaries or other mutable
522types that are compared by value rather than by object identity.
523Numeric types used for keys obey the normal rules for numeric
524comparison: if two numbers compare equal (e.g. \code{1} and
525\code{1.0}) then they can be used interchangeably to index the same
526dictionary entry.
527
528\indexii{mapping}{types}
529\indexii{dictionary}{type}
530
531Dictionaries are created by placing a comma-separated list of
532\code{\var{key}: \var{value}} pairs within braces, for example:
533\code{\{'jack': 4098, 'sjoerd': 4127\}} or
534\code{\{4098: 'jack', 4127: 'sjoerd'\}}.
535
536The following operations are defined on mappings (where \var{a} is a
537mapping, \var{k} is a key and \var{x} is an arbitrary object):
538
539\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
540 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
541 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
542 \lineiii{\var{a}[\var{k}] = \var{x}}{set \code{\var{a}[\var{k}]} to \var{x}}{}
543 \lineiii{del \var{a}[\var{k}]}{remove \code{\var{a}[\var{k}]} from \var{a}}{(1)}
544 \lineiii{\var{a}.clear()}{remove all items from \code{a}}{}
545 \lineiii{\var{a}.copy()}{a (shallow) copy of \code{a}}{}
546 \lineiii{\var{a}.has_key(\var{k})}{\code{1} if \var{a} has a key \var{k}, else \code{0}}{}
Fred Drake7a2f0661998-09-10 18:25:58 +0000547 \lineiii{\var{a}.items()}{a copy of \var{a}'s list of (\var{key}, \var{value}) pairs}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +0000548 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)}
549 \lineiii{\var{a}.update(\var{b})}{\code{for k, v in \var{b}.items(): \var{a}[k] = v}}{(3)}
550 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)}
Fred Drake7a2f0661998-09-10 18:25:58 +0000551 \lineiii{\var{a}.get(\var{k}\optional{, \var{f}})}{the value of \var{a} with key \var{k}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000552\end{tableiii}
553\indexiii{operations on}{mapping}{types}
554\indexiii{operations on}{dictionary}{type}
555\stindex{del}
556\bifuncindex{len}
Fred Drake7a2f0661998-09-10 18:25:58 +0000557\withsubitem{(dictionary method)}{%
558 \ttindex{clear}%
559 \ttindex{copy}%
560 \ttindex{has_key}%
561 \ttindex{items}%
562 \ttindex{keys}%
563 \ttindex{update}%
564 \ttindex{values}%
565 \ttindex{get}%
566}
Fred Drake64e3b431998-07-24 13:56:11 +0000567\noindent
568Notes:
569\begin{description}
570\item[(1)] Raises an exception if \var{k} is not in the map.
571
572\item[(2)] Keys and values are listed in random order.
573
574\item[(3)] \var{b} must be of the same type as \var{a}.
575
576\item[(4)] Never raises an exception if \var{k} is not in the map,
577instead it returns \var{f}. \var{f} is optional, when not provided
578and \var{k} is not in the map, \code{None} is returned.
579\end{description}
580
581
Fred Drake7a2f0661998-09-10 18:25:58 +0000582\subsection{Other Built-in Types \label{typesother}}
Fred Drake64e3b431998-07-24 13:56:11 +0000583
584The interpreter supports several other kinds of objects.
585Most of these support only one or two operations.
586
587\subsubsection{Modules}
588
589The only special operation on a module is attribute access:
590\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name}
591accesses a name defined in \var{m}'s symbol table. Module attributes
592can be assigned to. (Note that the \code{import} statement is not,
Fred Draked0421dd1998-08-24 17:57:20 +0000593strictly speaking, an operation on a module object; \code{import
Fred Drake64e3b431998-07-24 13:56:11 +0000594\var{foo}} does not require a module object named \var{foo} to exist,
595rather it requires an (external) \emph{definition} for a module named
596\var{foo} somewhere.)
597
598A special member of every module is \code{__dict__}.
599This is the dictionary containing the module's symbol table.
600Modifying this dictionary will actually change the module's symbol
601table, but direct assignment to the \code{__dict__} attribute is not
602possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which
603defines \code{\var{m}.a} to be \code{1}, but you can't write
604\code{\var{m}.__dict__ = \{\}}.
605
606Modules are written like this: \code{<module 'sys'>}.
607
608\subsubsection{Classes and Class Instances}
609\nodename{Classes and Instances}
610
611See Chapters 3 and 7 of the \emph{Python Reference Manual} for these.
612
613\subsubsection{Functions}
614
615Function objects are created by function definitions. The only
616operation on a function object is to call it:
617\code{\var{func}(\var{argument-list})}.
618
619There are really two flavors of function objects: built-in functions
620and user-defined functions. Both support the same operation (to call
621the function), but the implementation is different, hence the
622different object types.
623
624The implementation adds two special read-only attributes:
625\code{\var{f}.func_code} is a function's \dfn{code
626object}\obindex{code} (see below) and \code{\var{f}.func_globals} is
627the dictionary used as the function's global name space (this is the
628same as \code{\var{m}.__dict__} where \var{m} is the module in which
629the function \var{f} was defined).
630
631
632\subsubsection{Methods}
633\obindex{method}
634
635Methods are functions that are called using the attribute notation.
636There are two flavors: built-in methods (such as \code{append()} on
637lists) and class instance methods. Built-in methods are described
638with the types that support them.
639
640The implementation adds two special read-only attributes to class
Fred Draked0421dd1998-08-24 17:57:20 +0000641instance methods: \code{\var{m}.im_self} is the object on which the
642method operates, and \code{\var{m}.im_func} is the function
643implementing the method. Calling \code{\var{m}(\var{arg-1},
644\var{arg-2}, {\rm \ldots}, \var{arg-n})} is completely equivalent to
645calling \code{\var{m}.im_func(\var{m}.im_self, \var{arg-1},
646\var{arg-2}, {\rm \ldots}, \var{arg-n})}.
Fred Drake64e3b431998-07-24 13:56:11 +0000647
648See the \emph{Python Reference Manual} for more information.
649
Fred Drake7a2f0661998-09-10 18:25:58 +0000650
651\subsubsection{Code Objects \label{bltin-code-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000652\obindex{code}
653
654Code objects are used by the implementation to represent
655``pseudo-compiled'' executable Python code such as a function body.
656They differ from function objects because they don't contain a
657reference to their global execution environment. Code objects are
658returned by the built-in \code{compile()} function and can be
659extracted from function objects through their \code{func_code}
660attribute.
661\bifuncindex{compile}
Fred Drake7a2f0661998-09-10 18:25:58 +0000662\withsubitem{(code object attribute)}{\ttindex{func_code}}
Fred Drake64e3b431998-07-24 13:56:11 +0000663
664A code object can be executed or evaluated by passing it (instead of a
665source string) to the \code{exec} statement or the built-in
666\code{eval()} function.
667\stindex{exec}
668\bifuncindex{eval}
669
670See the \emph{Python Reference Manual} for more information.
671
Fred Drake7a2f0661998-09-10 18:25:58 +0000672
673\subsubsection{Type Objects \label{bltin-type-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000674
675Type objects represent the various object types. An object's type is
676accessed by the built-in function \code{type()}. There are no special
677operations on types. The standard module \code{types} defines names
678for all standard built-in types.
679\bifuncindex{type}
680\refstmodindex{types}
681
682Types are written like this: \code{<type 'int'>}.
683
Fred Drake7a2f0661998-09-10 18:25:58 +0000684
685\subsubsection{The Null Object \label{bltin-null-object}}
Fred Drake64e3b431998-07-24 13:56:11 +0000686
687This object is returned by functions that don't explicitly return a
688value. It supports no special operations. There is exactly one null
689object, named \code{None} (a built-in name).
690
691It is written as \code{None}.
692
Fred Drake7a2f0661998-09-10 18:25:58 +0000693
694\subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
Guido van Rossumb193c951998-07-24 15:02:02 +0000695
696This object is used by extended slice notation (see the \emph{Python
697Reference Manual}). It supports no special operations. There is
698exactly one ellipsis object, named \code{Ellipsis} (a built-in name).
699
700It is written as \code{Ellipsis}.
701
Fred Drake7a2f0661998-09-10 18:25:58 +0000702\subsubsection{File Objects \label{bltin-file-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +0000703
704File objects are implemented using \C{}'s \code{stdio} package and can be
705created with the built-in function \code{open()} described under
706Built-in Functions below. They are also returned by some other
Fred Drake7a2f0661998-09-10 18:25:58 +0000707built-in functions and methods, e.g.\ \function{posix.popen()} and
708\function{posix.fdopen()} and the \method{makefile()} method of socket
Fred Drake64e3b431998-07-24 13:56:11 +0000709objects.
710\bifuncindex{open}
711\refbimodindex{posix}
712\refbimodindex{socket}
713
714When a file operation fails for an I/O-related reason, the exception
715\code{IOError} is raised. This includes situations where the
716operation is not defined for some reason, like \code{seek()} on a tty
717device or writing a file opened for reading.
718
719Files have the following methods:
720
721
722\begin{methoddesc}[file]{close}{}
723 Close the file. A closed file cannot be read or written anymore.
724\end{methoddesc}
725
726\begin{methoddesc}[file]{flush}{}
727 Flush the internal buffer, like \code{stdio}'s \code{fflush()}.
728\end{methoddesc}
729
730\begin{methoddesc}[file]{isatty}{}
731 Return \code{1} if the file is connected to a tty(-like) device, else
732 \code{0}.
733\end{methoddesc}
734
735\begin{methoddesc}[file]{fileno}{}
736Return the integer ``file descriptor'' that is used by the underlying
737implementation to request I/O operations from the operating system.
738This can be useful for other, lower level interfaces that use file
739descriptors, e.g. module \code{fcntl} or \code{os.read()} and friends.
740\refbimodindex{fcntl}
741\end{methoddesc}
742
743\begin{methoddesc}[file]{read}{\optional{size}}
744 Read at most \var{size} bytes from the file (less if the read hits
745 \EOF{} or no more data is immediately available on a pipe, tty or
746 similar device). If the \var{size} argument is negative or omitted,
747 read all data until \EOF{} is reached. The bytes are returned as a string
748 object. An empty string is returned when \EOF{} is encountered
749 immediately. (For certain files, like ttys, it makes sense to
750 continue reading after an \EOF{} is hit.)
751\end{methoddesc}
752
753\begin{methoddesc}[file]{readline}{\optional{size}}
754 Read one entire line from the file. A trailing newline character is
755 kept in the string%
756\footnote{The advantage of leaving the newline on is that an empty string
757 can be returned to mean \EOF{} without being ambiguous. Another
758 advantage is that (in cases where it might matter, e.g. if you
759 want to make an exact copy of a file while scanning its lines)
760 you can tell whether the last line of a file ended in a newline
761 or not (yes this happens!).}
762 (but may be absent when a file ends with an
763 incomplete line). If the \var{size} argument is present and
764 non-negative, it is a maximum byte count (including the trailing
765 newline) and an incomplete line may be returned.
766 An empty string is returned when \EOF{} is hit
767 immediately. Note: unlike \code{stdio}'s \cfunction{fgets()}, the returned
768 string contains null characters (\code{'\e 0'}) if they occurred in the
769 input.
770\end{methoddesc}
771
772\begin{methoddesc}[file]{readlines}{\optional{sizehint}}
773 Read until \EOF{} using \method{readline()} and return a list containing
774 the lines thus read. If the optional \var{sizehint} argument is
775 present, instead of reading up to \EOF{}, whole lines totalling
776 approximately \var{sizehint} bytes (possibly after rounding up to an
777 internal buffer size) are read.
778\end{methoddesc}
779
780\begin{methoddesc}[file]{seek}{offset\optional{, whence}}
781 Set the file's current position, like \code{stdio}'s \cfunction{fseek()}.
782 The \var{whence} argument is optional and defaults to \code{0}
783 (absolute file positioning); other values are \code{1} (seek
784 relative to the current position) and \code{2} (seek relative to the
785 file's end). There is no return value.
786\end{methoddesc}
787
788\begin{methoddesc}[file]{tell}{}
789 Return the file's current position, like \code{stdio}'s
790 \cfunction{ftell()}.
791\end{methoddesc}
792
793\begin{methoddesc}[file]{truncate}{\optional{size}}
794Truncate the file's size. If the optional size argument present, the
795file is truncated to (at most) that size. The size defaults to the
796current position. Availability of this function depends on the
797operating system version (e.g., not all \UNIX{} versions support this
798operation).
799\end{methoddesc}
800
801\begin{methoddesc}[file]{write}{str}
802Write a string to the file. There is no return value. Note: due to
803buffering, the string may not actually show up in the file until
804the \method{flush()} or \method{close()} method is called.
805\end{methoddesc}
806
807\begin{methoddesc}[file]{writelines}{list}
808Write a list of strings to the file. There is no return value.
809(The name is intended to match \method{readlines()};
810\method{writelines()} does not add line separators.)
811\end{methoddesc}
812
813
814File objects also offer the following attributes:
815
816\begin{memberdesc}[file]{closed}
817Boolean indicating the current state of the file object. This is a
818read-only attribute; the \method{close()} method changes the value.
819\end{memberdesc}
820
821\begin{memberdesc}[file]{mode}
822The I/O mode for the file. If the file was created using the
823\function{open()} built-in function, this will be the value of the
824\var{mode} parameter. This is a read-only attribute.
825\end{memberdesc}
826
827\begin{memberdesc}[file]{name}
828If the file object was created using \function{open()}, the name of
829the file. Otherwise, some string that indicates the source of the
830file object, of the form \samp{<\mbox{\ldots}>}. This is a read-only
831attribute.
832\end{memberdesc}
833
834\begin{memberdesc}[file]{softspace}
835Boolean that indicates whether a space character needs to be printed
836before another value when using the \keyword{print} statement.
837Classes that are trying to simulate a file object should also have a
838writable \member{softspace} attribute, which should be initialized to
839zero. This will be automatic for classes implemented in Python; types
840implemented in \C{} will have to provide a writable \member{softspace}
841attribute.
842\end{memberdesc}
843
844\subsubsection{Internal Objects}
845
846See the \emph{Python Reference Manual} for this information. It
847describes code objects, stack frame objects, traceback objects, and
848slice objects.
849
850
Fred Drake7a2f0661998-09-10 18:25:58 +0000851\subsection{Special Attributes \label{specialattrs}}
Fred Drake64e3b431998-07-24 13:56:11 +0000852
853The implementation adds a few special read-only attributes to several
854object types, where they are relevant:
855
Fred Drake7a2f0661998-09-10 18:25:58 +0000856\begin{memberdescni}{__dict__}
857A dictionary of some sort used to store an
858object's (writable) attributes.
859\end{memberdescni}
Fred Drake64e3b431998-07-24 13:56:11 +0000860
Fred Drake7a2f0661998-09-10 18:25:58 +0000861\begin{memberdescni}{__methods__}
862List of the methods of many built-in object types,
Fred Drake64e3b431998-07-24 13:56:11 +0000863e.g., \code{[].__methods__} yields
Fred Drake7a2f0661998-09-10 18:25:58 +0000864\code{['append', 'count', 'index', 'insert', 'pop', 'remove',
865'reverse', 'sort']}.
866\end{memberdescni}
Fred Drake64e3b431998-07-24 13:56:11 +0000867
Fred Drake7a2f0661998-09-10 18:25:58 +0000868\begin{memberdescni}{__members__}
869Similar to \member{__methods__}, but lists data attributes.
870\end{memberdescni}
Fred Drake64e3b431998-07-24 13:56:11 +0000871
Fred Drake7a2f0661998-09-10 18:25:58 +0000872\begin{memberdescni}{__class__}
873The class to which a class instance belongs.
874\end{memberdescni}
Fred Drake64e3b431998-07-24 13:56:11 +0000875
Fred Drake7a2f0661998-09-10 18:25:58 +0000876\begin{memberdescni}{__bases__}
877The tuple of base classes of a class object.
878\end{memberdescni}