blob: 2b871597394c8c731cbc657096a1a1442e891760 [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}
Fred Drake8c071d42001-01-26 20:48:35 +000065 \lineiii{\var{x} or \var{y}}
66 {if \var{x} is false, then \var{y}, else \var{x}}{(1)}
67 \lineiii{\var{x} and \var{y}}
68 {if \var{x} is false, then \var{x}, else \var{y}}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +000069 \hline
Fred Drake8c071d42001-01-26 20:48:35 +000070 \lineiii{not \var{x}}
71 {if \var{x} is false, then \code{1}, else \code{0}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +000072\end{tableiii}
73\opindex{and}
74\opindex{or}
75\opindex{not}
76
77\noindent
78Notes:
79
80\begin{description}
81
82\item[(1)]
83These only evaluate their second argument if needed for their outcome.
84
85\item[(2)]
Fred Drake38e5d272000-04-03 20:13:55 +000086\samp{not} has a lower priority than non-Boolean operators, so
87\code{not \var{a} == \var{b}} is interpreted as \code{not (\var{a} ==
88\var{b})}, and \code{\var{a} == not \var{b}} is a syntax error.
Fred Drake64e3b431998-07-24 13:56:11 +000089
90\end{description}
91
92
Fred Drake7a2f0661998-09-10 18:25:58 +000093\subsection{Comparisons \label{comparisons}}
Fred Drake64e3b431998-07-24 13:56:11 +000094
95Comparison operations are supported by all objects. They all have the
96same priority (which is higher than that of the Boolean operations).
Fred Drake38e5d272000-04-03 20:13:55 +000097Comparisons can be chained arbitrarily; for example, \code{\var{x} <
98\var{y} <= \var{z}} is equivalent to \code{\var{x} < \var{y} and
99\var{y} <= \var{z}}, except that \var{y} is evaluated only once (but
100in both cases \var{z} is not evaluated at all when \code{\var{x} <
101\var{y}} is found to be false).
Fred Drake64e3b431998-07-24 13:56:11 +0000102\indexii{chaining}{comparisons}
103
104This table summarizes the comparison operations:
105
106\begin{tableiii}{c|l|c}{code}{Operation}{Meaning}{Notes}
107 \lineiii{<}{strictly less than}{}
108 \lineiii{<=}{less than or equal}{}
109 \lineiii{>}{strictly greater than}{}
110 \lineiii{>=}{greater than or equal}{}
111 \lineiii{==}{equal}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000112 \lineiii{!=}{not equal}{(1)}
Fred Drake512bb722000-08-18 03:12:38 +0000113 \lineiii{<>}{not equal}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000114 \lineiii{is}{object identity}{}
115 \lineiii{is not}{negated object identity}{}
116\end{tableiii}
117\indexii{operator}{comparison}
118\opindex{==} % XXX *All* others have funny characters < ! >
119\opindex{is}
120\opindex{is not}
121
122\noindent
123Notes:
124
125\begin{description}
126
127\item[(1)]
128\code{<>} and \code{!=} are alternate spellings for the same operator.
Fred Drake4de96c22000-08-12 03:36:23 +0000129(I couldn't choose between \ABC{} and C! :-)
Fred Drake64e3b431998-07-24 13:56:11 +0000130\index{ABC language@\ABC{} language}
Fred Drakec37b65e2001-11-28 07:26:15 +0000131\index{language!ABC@\ABC}
Fred Drake4de96c22000-08-12 03:36:23 +0000132\indexii{C}{language}
Fred Drake38e5d272000-04-03 20:13:55 +0000133\code{!=} is the preferred spelling; \code{<>} is obsolescent.
Fred Drake64e3b431998-07-24 13:56:11 +0000134
135\end{description}
136
137Objects of different types, except different numeric types, never
138compare equal; such objects are ordered consistently but arbitrarily
139(so that sorting a heterogeneous array yields a consistent result).
Fred Drake38e5d272000-04-03 20:13:55 +0000140Furthermore, some types (for example, file objects) support only a
141degenerate notion of comparison where any two objects of that type are
142unequal. Again, such objects are ordered arbitrarily but
143consistently.
144\indexii{object}{numeric}
Fred Drake64e3b431998-07-24 13:56:11 +0000145\indexii{objects}{comparing}
146
Fred Drake38e5d272000-04-03 20:13:55 +0000147Instances of a class normally compare as non-equal unless the class
148\withsubitem{(instance method)}{\ttindex{__cmp__()}}
Fred Drake66571cc2000-09-09 03:30:34 +0000149defines the \method{__cmp__()} method. Refer to the
150\citetitle[../ref/customization.html]{Python Reference Manual} for
151information on the use of this method to effect object comparisons.
Fred Drake64e3b431998-07-24 13:56:11 +0000152
Fred Drake38e5d272000-04-03 20:13:55 +0000153\strong{Implementation note:} Objects of different types except
154numbers are ordered by their type names; objects of the same types
155that don't support proper comparison are ordered by their address.
156
157Two more operations with the same syntactic priority,
158\samp{in}\opindex{in} and \samp{not in}\opindex{not in}, are supported
159only by sequence types (below).
Fred Drake64e3b431998-07-24 13:56:11 +0000160
161
Fred Drake7a2f0661998-09-10 18:25:58 +0000162\subsection{Numeric Types \label{typesnumeric}}
Fred Drake64e3b431998-07-24 13:56:11 +0000163
164There are four numeric types: \dfn{plain integers}, \dfn{long integers},
165\dfn{floating point numbers}, and \dfn{complex numbers}.
166Plain integers (also just called \dfn{integers})
Fred Drake38e5d272000-04-03 20:13:55 +0000167are implemented using \ctype{long} in C, which gives them at least 32
Fred Drake64e3b431998-07-24 13:56:11 +0000168bits of precision. Long integers have unlimited precision. Floating
Fred Drake38e5d272000-04-03 20:13:55 +0000169point numbers are implemented using \ctype{double} in C. All bets on
Fred Drake64e3b431998-07-24 13:56:11 +0000170their precision are off unless you happen to know the machine you are
171working with.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000172\obindex{numeric}
173\obindex{integer}
174\obindex{long integer}
175\obindex{floating point}
176\obindex{complex number}
Fred Drake38e5d272000-04-03 20:13:55 +0000177\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000178
179Complex numbers have a real and imaginary part, which are both
Fred Drake38e5d272000-04-03 20:13:55 +0000180implemented using \ctype{double} in C. To extract these parts from
Fred Drake64e3b431998-07-24 13:56:11 +0000181a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
182
183Numbers are created by numeric literals or as the result of built-in
184functions and operators. Unadorned integer literals (including hex
Fred Drake38e5d272000-04-03 20:13:55 +0000185and octal numbers) yield plain integers. Integer literals with an
186\character{L} or \character{l} suffix yield long integers
187(\character{L} is preferred because \samp{1l} looks too much like
188eleven!). Numeric literals containing a decimal point or an exponent
189sign yield floating point numbers. Appending \character{j} or
190\character{J} to a numeric literal yields a complex number.
Fred Drake64e3b431998-07-24 13:56:11 +0000191\indexii{numeric}{literals}
192\indexii{integer}{literals}
193\indexiii{long}{integer}{literals}
194\indexii{floating point}{literals}
195\indexii{complex number}{literals}
196\indexii{hexadecimal}{literals}
197\indexii{octal}{literals}
198
199Python fully supports mixed arithmetic: when a binary arithmetic
200operator has operands of different numeric types, the operand with the
201``smaller'' type is converted to that of the other, where plain
202integer is smaller than long integer is smaller than floating point is
203smaller than complex.
Fred Drakeea003fc1999-04-05 21:59:15 +0000204Comparisons between numbers of mixed type use the same rule.\footnote{
205 As a consequence, the list \code{[1, 2]} is considered equal
Fred Drake82ac24f1999-07-02 14:29:14 +0000206 to \code{[1.0, 2.0]}, and similar for tuples.
207} The functions \function{int()}, \function{long()}, \function{float()},
Fred Drake84538cd1998-11-30 21:51:25 +0000208and \function{complex()} can be used
Fred Drake64e3b431998-07-24 13:56:11 +0000209to coerce numbers to a specific type.
210\index{arithmetic}
211\bifuncindex{int}
212\bifuncindex{long}
213\bifuncindex{float}
214\bifuncindex{complex}
215
216All numeric types support the following operations, sorted by
217ascending priority (operations in the same box have the same
218priority; all numeric operations have a higher priority than
219comparison operations):
220
221\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
222 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
223 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
224 \hline
225 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
226 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
227 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
228 \hline
229 \lineiii{-\var{x}}{\var{x} negated}{}
230 \lineiii{+\var{x}}{\var{x} unchanged}{}
231 \hline
232 \lineiii{abs(\var{x})}{absolute value or magnitude of \var{x}}{}
233 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
234 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
235 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
236 \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 +0000237 \lineiii{\var{c}.conjugate()}{conjugate of the complex number \var{c}}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000238 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
239 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
240 \lineiii{\var{x} ** \var{y}}{\var{x} to the power \var{y}}{}
241\end{tableiii}
242\indexiii{operations on}{numeric}{types}
Fred Drake26b698f1999-02-12 18:27:31 +0000243\withsubitem{(complex number method)}{\ttindex{conjugate()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000244
245\noindent
246Notes:
247\begin{description}
248
249\item[(1)]
250For (plain or long) integer division, the result is an integer.
251The result is always rounded towards minus infinity: 1/2 is 0,
Fred Drake38e5d272000-04-03 20:13:55 +0000252(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
253is a long integer if either operand is a long integer, regardless of
254the numeric value.
Fred Drake64e3b431998-07-24 13:56:11 +0000255\indexii{integer}{division}
256\indexiii{long}{integer}{division}
257
258\item[(2)]
259Conversion from floating point to (long or plain) integer may round or
Fred Drake4de96c22000-08-12 03:36:23 +0000260truncate as in C; see functions \function{floor()} and
261\function{ceil()} in the \refmodule{math}\refbimodindex{math} module
262for well-defined conversions.
Fred Drake9474d861999-02-12 22:05:33 +0000263\withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000264\indexii{numeric}{conversions}
Fred Drake4de96c22000-08-12 03:36:23 +0000265\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000266
267\item[(3)]
Fred Drake38e5d272000-04-03 20:13:55 +0000268See section \ref{built-in-funcs}, ``Built-in Functions,'' for a full
269description.
Fred Drake64e3b431998-07-24 13:56:11 +0000270
271\end{description}
272% XXXJH exceptions: overflow (when? what operations?) zerodivision
273
Fred Drake4e7c2051999-02-19 15:30:25 +0000274\subsubsection{Bit-string Operations on Integer Types \label{bitstring-ops}}
Fred Drake64e3b431998-07-24 13:56:11 +0000275\nodename{Bit-string Operations}
276
277Plain and long integer types support additional operations that make
278sense only for bit-strings. Negative numbers are treated as their 2's
279complement value (for long integers, this assumes a sufficiently large
280number of bits that no overflow occurs during the operation).
281
282The priorities of the binary bit-wise operations are all lower than
283the numeric operations and higher than the comparisons; the unary
284operation \samp{\~} has the same priority as the other unary numeric
285operations (\samp{+} and \samp{-}).
286
287This table lists the bit-string operations sorted in ascending
288priority (operations in the same box have the same priority):
289
290\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
291 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
292 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
293 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
294 \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
295 \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
296 \hline
297 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
298\end{tableiii}
299\indexiii{operations on}{integer}{types}
300\indexii{bit-string}{operations}
301\indexii{shifting}{operations}
302\indexii{masking}{operations}
303
304\noindent
305Notes:
306\begin{description}
307\item[(1)] Negative shift counts are illegal and cause a
308\exception{ValueError} to be raised.
309\item[(2)] A left shift by \var{n} bits is equivalent to
310multiplication by \code{pow(2, \var{n})} without overflow check.
311\item[(3)] A right shift by \var{n} bits is equivalent to
312division by \code{pow(2, \var{n})} without overflow check.
313\end{description}
314
315
Fred Drake93656e72001-05-02 20:18:03 +0000316\subsection{Iterator Types \label{typeiter}}
317
Fred Drakef42cc452001-05-03 04:39:10 +0000318\versionadded{2.2}
Fred Drake93656e72001-05-02 20:18:03 +0000319\index{iterator protocol}
320\index{protocol!iterator}
321\index{sequence!iteration}
322\index{container!iteration over}
323
324Python supports a concept of iteration over containers. This is
325implemented using two distinct methods; these are used to allow
326user-defined classes to support iteration. Sequences, described below
327in more detail, always support the iteration methods.
328
329One method needs to be defined for container objects to provide
330iteration support:
331
332\begin{methoddesc}[container]{__iter__}{}
Greg Ward54f65092001-07-26 21:01:21 +0000333 Return an iterator object. The object is required to support the
Fred Drake93656e72001-05-02 20:18:03 +0000334 iterator protocol described below. If a container supports
335 different types of iteration, additional methods can be provided to
336 specifically request iterators for those iteration types. (An
337 example of an object supporting multiple forms of iteration would be
338 a tree structure which supports both breadth-first and depth-first
339 traversal.) This method corresponds to the \member{tp_iter} slot of
340 the type structure for Python objects in the Python/C API.
341\end{methoddesc}
342
343The iterator objects themselves are required to support the following
344two methods, which together form the \dfn{iterator protocol}:
345
346\begin{methoddesc}[iterator]{__iter__}{}
347 Return the iterator object itself. This is required to allow both
348 containers and iterators to be used with the \keyword{for} and
349 \keyword{in} statements. This method corresponds to the
350 \member{tp_iter} slot of the type structure for Python objects in
351 the Python/C API.
352\end{methoddesc}
353
Fred Drakef42cc452001-05-03 04:39:10 +0000354\begin{methoddesc}[iterator]{next}{}
Fred Drake93656e72001-05-02 20:18:03 +0000355 Return the next item from the container. If there are no further
356 items, raise the \exception{StopIteration} exception. This method
357 corresponds to the \member{tp_iternext} slot of the type structure
358 for Python objects in the Python/C API.
359\end{methoddesc}
360
361Python defines several iterator objects to support iteration over
362general and specific sequence types, dictionaries, and other more
363specialized forms. The specific types are not important beyond their
364implementation of the iterator protocol.
365
366
Fred Drake7a2f0661998-09-10 18:25:58 +0000367\subsection{Sequence Types \label{typesseq}}
Fred Drake64e3b431998-07-24 13:56:11 +0000368
Fred Drake107b9672000-08-14 15:37:59 +0000369There are six sequence types: strings, Unicode strings, lists,
Fred Drake512bb722000-08-18 03:12:38 +0000370tuples, buffers, and xrange objects.
Fred Drake64e3b431998-07-24 13:56:11 +0000371
372Strings literals are written in single or double quotes:
Fred Drake38e5d272000-04-03 20:13:55 +0000373\code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
Fred Drake4de96c22000-08-12 03:36:23 +0000374\citetitle[../ref/strings.html]{Python Reference Manual} for more about
375string literals. Unicode strings are much like strings, but are
376specified in the syntax using a preceeding \character{u} character:
377\code{u'abc'}, \code{u"def"}. Lists are constructed with square brackets,
Fred Drake37f15741999-11-10 16:21:37 +0000378separating items with commas: \code{[a, b, c]}. Tuples are
379constructed by the comma operator (not within square brackets), with
380or without enclosing parentheses, but an empty tuple must have the
381enclosing parentheses, e.g., \code{a, b, c} or \code{()}. A single
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000382item tuple must have a trailing comma, e.g., \code{(d,)}.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000383\obindex{sequence}
384\obindex{string}
385\obindex{Unicode}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000386\obindex{tuple}
387\obindex{list}
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000388
389Buffer objects are not directly supported by Python syntax, but can be
390created by calling the builtin function
391\function{buffer()}.\bifuncindex{buffer}. They don't support
392concatenation or repetition.
393\obindex{buffer}
394
395Xrange objects are similar to buffers in that there is no specific
396syntax to create them, but they are created using the \function{xrange()}
397function.\bifuncindex{xrange} They don't support slicing,
398concatenation or repetition, and using \code{in}, \code{not in},
399\function{min()} or \function{max()} on them is inefficient.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000400\obindex{xrange}
Fred Drake64e3b431998-07-24 13:56:11 +0000401
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000402Most sequence types support the following operations. The \samp{in} and
Fred Drake64e3b431998-07-24 13:56:11 +0000403\samp{not in} operations have the same priorities as the comparison
404operations. The \samp{+} and \samp{*} operations have the same
405priority as the corresponding numeric operations.\footnote{They must
406have since the parser can't tell the type of the operands.}
407
408This table lists the sequence operations sorted in ascending priority
409(operations in the same box have the same priority). In the table,
410\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
411and \var{j} are integers:
412
413\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
414 \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
415 \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is
416equal to \var{x}, else \code{1}}{}
417 \hline
418 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
Fred Draked800cff2001-08-28 14:56:05 +0000419 \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} shallow copies of \var{s} concatenated}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000420 \hline
Fred Drake38e5d272000-04-03 20:13:55 +0000421 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(2)}
422 \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 +0000423 \hline
424 \lineiii{len(\var{s})}{length of \var{s}}{}
425 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
426 \lineiii{max(\var{s})}{largest item of \var{s}}{}
427\end{tableiii}
428\indexiii{operations on}{sequence}{types}
429\bifuncindex{len}
430\bifuncindex{min}
431\bifuncindex{max}
432\indexii{concatenation}{operation}
433\indexii{repetition}{operation}
434\indexii{subscript}{operation}
435\indexii{slice}{operation}
436\opindex{in}
437\opindex{not in}
438
439\noindent
440Notes:
441
442\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000443\item[(1)] Values of \var{n} less than \code{0} are treated as
444 \code{0} (which yields an empty sequence of the same type as
Fred Draked800cff2001-08-28 14:56:05 +0000445 \var{s}). Note also that the copies are shallow; nested structures
446 are not copied. This often haunts new Python programmers; consider:
447
448\begin{verbatim}
449>>> lists = [[]] * 3
450>>> lists
451[[], [], []]
452>>> lists[0].append(3)
453>>> lists
454[[3], [3], [3]]
455\end{verbatim}
456
457 What has happened is that \code{lists} is a list containing three
458 copies of the list \code{[[]]} (a one-element list containing an
459 empty list), but the contained list is shared by each copy. You can
460 create a list of different lists this way:
461
462\begin{verbatim}
463>>> lists = [[] for i in range(3)]
464>>> lists[0].append(3)
465>>> lists[1].append(5)
466>>> lists[2].append(7)
467>>> lists
468[[3], [5], [7]]
469\end{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000470
471\item[(2)] If \var{i} or \var{j} is negative, the index is relative to
Fred Drake907e76b2001-07-06 20:30:11 +0000472 the end of the string: \code{len(\var{s}) + \var{i}} or
Fred Drake64e3b431998-07-24 13:56:11 +0000473 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
474 still \code{0}.
475
Fred Drake38e5d272000-04-03 20:13:55 +0000476\item[(3)] The slice of \var{s} from \var{i} to \var{j} is defined as
Fred Drake64e3b431998-07-24 13:56:11 +0000477 the sequence of items with index \var{k} such that \code{\var{i} <=
478 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
479 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
480 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
481 \var{i} is greater than or equal to \var{j}, the slice is empty.
Fred Drake64e3b431998-07-24 13:56:11 +0000482\end{description}
483
Fred Drake9474d861999-02-12 22:05:33 +0000484
Fred Drake4de96c22000-08-12 03:36:23 +0000485\subsubsection{String Methods \label{string-methods}}
486
487These are the string methods which both 8-bit strings and Unicode
488objects support:
489
490\begin{methoddesc}[string]{capitalize}{}
491Return a copy of the string with only its first character capitalized.
492\end{methoddesc}
493
494\begin{methoddesc}[string]{center}{width}
495Return centered in a string of length \var{width}. Padding is done
496using spaces.
497\end{methoddesc}
498
499\begin{methoddesc}[string]{count}{sub\optional{, start\optional{, end}}}
500Return the number of occurrences of substring \var{sub} in string
501S\code{[\var{start}:\var{end}]}. Optional arguments \var{start} and
502\var{end} are interpreted as in slice notation.
503\end{methoddesc}
504
505\begin{methoddesc}[string]{encode}{\optional{encoding\optional{,errors}}}
506Return an encoded version of the string. Default encoding is the current
507default string encoding. \var{errors} may be given to set a different
508error handling scheme. The default for \var{errors} is
509\code{'strict'}, meaning that encoding errors raise a
510\exception{ValueError}. Other possible values are \code{'ignore'} and
511\code{'replace'}.
Fred Drake1dba66c2000-10-25 21:03:55 +0000512\versionadded{2.0}
Fred Drake4de96c22000-08-12 03:36:23 +0000513\end{methoddesc}
514
515\begin{methoddesc}[string]{endswith}{suffix\optional{, start\optional{, end}}}
516Return true if the string ends with the specified \var{suffix},
517otherwise return false. With optional \var{start}, test beginning at
518that position. With optional \var{end}, stop comparing at that position.
519\end{methoddesc}
520
521\begin{methoddesc}[string]{expandtabs}{\optional{tabsize}}
522Return a copy of the string where all tab characters are expanded
523using spaces. If \var{tabsize} is not given, a tab size of \code{8}
524characters is assumed.
525\end{methoddesc}
526
527\begin{methoddesc}[string]{find}{sub\optional{, start\optional{, end}}}
528Return the lowest index in the string where substring \var{sub} is
529found, such that \var{sub} is contained in the range [\var{start},
530\var{end}). Optional arguments \var{start} and \var{end} are
531interpreted as in slice notation. Return \code{-1} if \var{sub} is
532not found.
533\end{methoddesc}
534
535\begin{methoddesc}[string]{index}{sub\optional{, start\optional{, end}}}
536Like \method{find()}, but raise \exception{ValueError} when the
537substring is not found.
538\end{methoddesc}
539
540\begin{methoddesc}[string]{isalnum}{}
541Return true if all characters in the string are alphanumeric and there
542is at least one character, false otherwise.
543\end{methoddesc}
544
545\begin{methoddesc}[string]{isalpha}{}
546Return true if all characters in the string are alphabetic and there
547is at least one character, false otherwise.
548\end{methoddesc}
549
550\begin{methoddesc}[string]{isdigit}{}
551Return true if there are only digit characters, false otherwise.
552\end{methoddesc}
553
554\begin{methoddesc}[string]{islower}{}
555Return true if all cased characters in the string are lowercase and
556there is at least one cased character, false otherwise.
557\end{methoddesc}
558
559\begin{methoddesc}[string]{isspace}{}
560Return true if there are only whitespace characters in the string and
561the string is not empty, false otherwise.
562\end{methoddesc}
563
564\begin{methoddesc}[string]{istitle}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000565Return true if the string is a titlecased string: uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000566characters may only follow uncased characters and lowercase characters
567only cased ones. Return false otherwise.
568\end{methoddesc}
569
570\begin{methoddesc}[string]{isupper}{}
571Return true if all cased characters in the string are uppercase and
572there is at least one cased character, false otherwise.
573\end{methoddesc}
574
575\begin{methoddesc}[string]{join}{seq}
576Return a string which is the concatenation of the strings in the
577sequence \var{seq}. The separator between elements is the string
578providing this method.
579\end{methoddesc}
580
581\begin{methoddesc}[string]{ljust}{width}
582Return the string left justified in a string of length \var{width}.
583Padding is done using spaces. The original string is returned if
584\var{width} is less than \code{len(\var{s})}.
585\end{methoddesc}
586
587\begin{methoddesc}[string]{lower}{}
588Return a copy of the string converted to lowercase.
589\end{methoddesc}
590
591\begin{methoddesc}[string]{lstrip}{}
592Return a copy of the string with leading whitespace removed.
593\end{methoddesc}
594
595\begin{methoddesc}[string]{replace}{old, new\optional{, maxsplit}}
596Return a copy of the string with all occurrences of substring
597\var{old} replaced by \var{new}. If the optional argument
598\var{maxsplit} is given, only the first \var{maxsplit} occurrences are
599replaced.
600\end{methoddesc}
601
602\begin{methoddesc}[string]{rfind}{sub \optional{,start \optional{,end}}}
603Return the highest index in the string where substring \var{sub} is
604found, such that \var{sub} is contained within s[start,end]. Optional
605arguments \var{start} and \var{end} are interpreted as in slice
606notation. Return \code{-1} on failure.
607\end{methoddesc}
608
609\begin{methoddesc}[string]{rindex}{sub\optional{, start\optional{, end}}}
610Like \method{rfind()} but raises \exception{ValueError} when the
611substring \var{sub} is not found.
612\end{methoddesc}
613
614\begin{methoddesc}[string]{rjust}{width}
615Return the string right justified in a string of length \var{width}.
616Padding is done using spaces. The original string is returned if
617\var{width} is less than \code{len(\var{s})}.
618\end{methoddesc}
619
620\begin{methoddesc}[string]{rstrip}{}
621Return a copy of the string with trailing whitespace removed.
622\end{methoddesc}
623
624\begin{methoddesc}[string]{split}{\optional{sep \optional{,maxsplit}}}
625Return a list of the words in the string, using \var{sep} as the
626delimiter string. If \var{maxsplit} is given, at most \var{maxsplit}
627splits are done. If \var{sep} is not specified or \code{None}, any
628whitespace string is a separator.
629\end{methoddesc}
630
631\begin{methoddesc}[string]{splitlines}{\optional{keepends}}
632Return a list of the lines in the string, breaking at line
633boundaries. Line breaks are not included in the resulting list unless
634\var{keepends} is given and true.
635\end{methoddesc}
636
637\begin{methoddesc}[string]{startswith}{prefix\optional{, start\optional{, end}}}
638Return true if string starts with the \var{prefix}, otherwise
639return false. With optional \var{start}, test string beginning at
640that position. With optional \var{end}, stop comparing string at that
641position.
642\end{methoddesc}
643
644\begin{methoddesc}[string]{strip}{}
645Return a copy of the string with leading and trailing whitespace
646removed.
647\end{methoddesc}
648
649\begin{methoddesc}[string]{swapcase}{}
650Return a copy of the string with uppercase characters converted to
651lowercase and vice versa.
652\end{methoddesc}
653
654\begin{methoddesc}[string]{title}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000655Return a titlecased version of the string: words start with uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000656characters, all remaining cased characters are lowercase.
657\end{methoddesc}
658
659\begin{methoddesc}[string]{translate}{table\optional{, deletechars}}
660Return a copy of the string where all characters occurring in the
661optional argument \var{deletechars} are removed, and the remaining
662characters have been mapped through the given translation table, which
663must be a string of length 256.
664\end{methoddesc}
665
666\begin{methoddesc}[string]{upper}{}
667Return a copy of the string converted to uppercase.
668\end{methoddesc}
669
670
671\subsubsection{String Formatting Operations \label{typesseq-strings}}
Fred Drake64e3b431998-07-24 13:56:11 +0000672
Fred Drake66d32b12000-09-14 17:57:42 +0000673\index{formatting, string}
674\index{string!formatting}
675\index{printf-style formatting}
676\index{sprintf-style formatting}
677
Fred Drake8c071d42001-01-26 20:48:35 +0000678String and Unicode objects have one unique built-in operation: the
679\code{\%} operator (modulo). Given \code{\var{format} \%
680\var{values}} (where \var{format} is a string or Unicode object),
681\code{\%} conversion specifications in \var{format} are replaced with
682zero or more elements of \var{values}. The effect is similar to the
683using \cfunction{sprintf()} in the C language. If \var{format} is a
684Unicode object, or if any of the objects being converted using the
685\code{\%s} conversion are Unicode objects, the result will be a
686Unicode object as well.
Fred Drake64e3b431998-07-24 13:56:11 +0000687
Fred Drake8c071d42001-01-26 20:48:35 +0000688If \var{format} requires a single argument, \var{values} may be a
689single non-tuple object. \footnote{A tuple object in this case should
690 be a singleton.} Otherwise, \var{values} must be a tuple with
691exactly the number of items specified by the format string, or a
692single mapping object (for example, a dictionary).
Fred Drake64e3b431998-07-24 13:56:11 +0000693
Fred Drake8c071d42001-01-26 20:48:35 +0000694A conversion specifier contains two or more characters and has the
695following components, which must occur in this order:
696
697\begin{enumerate}
698 \item The \character{\%} character, which marks the start of the
699 specifier.
700 \item Mapping key value (optional), consisting of an identifier in
701 parentheses (for example, \code{(somename)}).
702 \item Conversion flags (optional), which affect the result of some
703 conversion types.
704 \item Minimum field width (optional). If specified as an
705 \character{*} (asterisk), the actual width is read from the
706 next element of the tuple in \var{values}, and the object to
707 convert comes after the minimum field width and optional
708 precision.
709 \item Precision (optional), given as a \character{.} (dot) followed
710 by the precision. If specified as \character{*} (an
711 asterisk), the actual width is read from the next element of
712 the tuple in \var{values}, and the value to convert comes after
713 the precision.
714 \item Length modifier (optional).
715 \item Conversion type.
716\end{enumerate}
Fred Drake64e3b431998-07-24 13:56:11 +0000717
718If the right argument is a dictionary (or any kind of mapping), then
Fred Drake8c071d42001-01-26 20:48:35 +0000719the formats in the string \emph{must} have a parenthesized key into
720that dictionary inserted immediately after the \character{\%}
721character, and each format formats the corresponding entry from the
722mapping. For example:
Fred Drake64e3b431998-07-24 13:56:11 +0000723
724\begin{verbatim}
725>>> count = 2
726>>> language = 'Python'
727>>> print '%(language)s has %(count)03d quote types.' % vars()
728Python has 002 quote types.
729\end{verbatim}
730
731In this case no \code{*} specifiers may occur in a format (since they
732require a sequential parameter list).
733
Fred Drake8c071d42001-01-26 20:48:35 +0000734The conversion flag characters are:
735
736\begin{tableii}{c|l}{character}{Flag}{Meaning}
737 \lineii{\#}{The value conversion will use the ``alternate form''
738 (where defined below).}
739 \lineii{0}{The conversion will be zero padded.}
740 \lineii{-}{The converted value is left adjusted (overrides
741 \character{-}).}
742 \lineii{{~}}{(a space) A blank should be left before a positive number
743 (or empty string) produced by a signed conversion.}
744 \lineii{+}{A sign character (\character{+} or \character{-}) will
745 precede the conversion (overrides a "space" flag).}
746\end{tableii}
747
748The length modifier may be \code{h}, \code{l}, and \code{L} may be
749present, but are ignored as they are not necessary for Python.
750
751The conversion types are:
752
753\begin{tableii}{c|l}{character}{Conversion}{Meaning}
754 \lineii{d}{Signed integer decimal.}
755 \lineii{i}{Signed integer decimal.}
756 \lineii{o}{Unsigned octal.}
757 \lineii{u}{Unsigned decimal.}
758 \lineii{x}{Unsigned hexidecimal (lowercase).}
759 \lineii{X}{Unsigned hexidecimal (uppercase).}
760 \lineii{e}{Floating point exponential format (lowercase).}
761 \lineii{E}{Floating point exponential format (uppercase).}
762 \lineii{f}{Floating point decimal format.}
763 \lineii{F}{Floating point decimal format.}
764 \lineii{g}{Same as \character{e} if exponent is greater than -4 or
765 less than precision, \character{f} otherwise.}
766 \lineii{G}{Same as \character{E} if exponent is greater than -4 or
767 less than precision, \character{F} otherwise.}
768 \lineii{c}{Single character (accepts integer or single character
769 string).}
770 \lineii{r}{String (converts any python object using
771 \function{repr()}).}
772 \lineii{s}{String (converts any python object using
773 \function{str()}).}
774 \lineii{\%}{No argument is converted, results in a \character{\%}
775 character in the result. (The complete specification is
776 \code{\%\%}.)}
777\end{tableii}
778
779% XXX Examples?
780
781
782Since Python strings have an explicit length, \code{\%s} conversions
783do not assume that \code{'\e0'} is the end of the string.
784
785For safety reasons, floating point precisions are clipped to 50;
786\code{\%f} conversions for numbers whose absolute value is over 1e25
787are replaced by \code{\%g} conversions.\footnote{
788 These numbers are fairly arbitrary. They are intended to
789 avoid printing endless strings of meaningless digits without hampering
790 correct use and without having to know the exact precision of floating
791 point values on a particular machine.
792} All other errors raise exceptions.
793
Fred Drake14f5c5f2001-12-03 18:33:13 +0000794Additional string operations are defined in standard modules
795\refmodule{string}\refstmodindex{string} and
796\refmodule{re}.\refstmodindex{re}
Fred Drake64e3b431998-07-24 13:56:11 +0000797
Fred Drake107b9672000-08-14 15:37:59 +0000798
Fred Drake512bb722000-08-18 03:12:38 +0000799\subsubsection{XRange Type \label{typesseq-xrange}}
Fred Drake107b9672000-08-14 15:37:59 +0000800
Fred Drake0b4e25d2000-10-04 04:21:19 +0000801The xrange\obindex{xrange} type is an immutable sequence which is
Fred Drake512bb722000-08-18 03:12:38 +0000802commonly used for looping. The advantage of the xrange type is that an
803xrange object will always take the same amount of memory, no matter the
Fred Drake107b9672000-08-14 15:37:59 +0000804size of the range it represents. There are no consistent performance
805advantages.
806
Guido van Rossum3f561662001-07-05 13:27:48 +0000807XRange objects have very little behavior: they only support indexing
808and the \function{len()} function.
Fred Drake107b9672000-08-14 15:37:59 +0000809
810
Fred Drake9474d861999-02-12 22:05:33 +0000811\subsubsection{Mutable Sequence Types \label{typesseq-mutable}}
Fred Drake64e3b431998-07-24 13:56:11 +0000812
813List objects support additional operations that allow in-place
814modification of the object.
815These operations would be supported by other mutable sequence types
816(when added to the language) as well.
817Strings and tuples are immutable sequence types and such objects cannot
818be modified once created.
819The following operations are defined on mutable sequence types (where
820\var{x} is an arbitrary object):
821\indexiii{mutable}{sequence}{types}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000822\obindex{list}
Fred Drake64e3b431998-07-24 13:56:11 +0000823
824\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
825 \lineiii{\var{s}[\var{i}] = \var{x}}
826 {item \var{i} of \var{s} is replaced by \var{x}}{}
827 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
828 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
829 \lineiii{del \var{s}[\var{i}:\var{j}]}
830 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
831 \lineiii{\var{s}.append(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000832 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{(1)}
Barry Warsawafd974c1998-10-09 16:39:58 +0000833 \lineiii{\var{s}.extend(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000834 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +0000835 \lineiii{\var{s}.count(\var{x})}
836 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
837 \lineiii{\var{s}.index(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000838 {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000839 \lineiii{\var{s}.insert(\var{i}, \var{x})}
840 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
Fred Drakeef428a22001-10-26 18:57:14 +0000841 if \code{\var{i} >= 0}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000842 \lineiii{\var{s}.pop(\optional{\var{i}})}
Fred Drakeef428a22001-10-26 18:57:14 +0000843 {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(5)}
Fred Drake64e3b431998-07-24 13:56:11 +0000844 \lineiii{\var{s}.remove(\var{x})}
Fred Drake38e5d272000-04-03 20:13:55 +0000845 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000846 \lineiii{\var{s}.reverse()}
Fred Drakeef428a22001-10-26 18:57:14 +0000847 {reverses the items of \var{s} in place}{(6)}
Fred Drake64e3b431998-07-24 13:56:11 +0000848 \lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
Fred Drakeef428a22001-10-26 18:57:14 +0000849 {sort the items of \var{s} in place}{(6), (7)}
Fred Drake64e3b431998-07-24 13:56:11 +0000850\end{tableiii}
851\indexiv{operations on}{mutable}{sequence}{types}
852\indexiii{operations on}{sequence}{types}
853\indexiii{operations on}{list}{type}
854\indexii{subscript}{assignment}
855\indexii{slice}{assignment}
856\stindex{del}
Fred Drake9474d861999-02-12 22:05:33 +0000857\withsubitem{(list method)}{
Fred Drake68921df1999-08-09 17:05:12 +0000858 \ttindex{append()}\ttindex{extend()}\ttindex{count()}\ttindex{index()}
859 \ttindex{insert()}\ttindex{pop()}\ttindex{remove()}\ttindex{reverse()}
Fred Drakee8391991998-11-25 17:09:19 +0000860 \ttindex{sort()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000861\noindent
862Notes:
863\begin{description}
Fred Drake38e5d272000-04-03 20:13:55 +0000864\item[(1)] The C implementation of Python has historically accepted
865 multiple parameters and implicitly joined them into a tuple; this
Fred Drake30f76ff2000-06-30 16:06:19 +0000866 no longer works in Python 2.0. Use of this misfeature has been
Fred Drake38e5d272000-04-03 20:13:55 +0000867 deprecated since Python 1.4.
868
869\item[(2)] Raises an exception when \var{x} is not a list object. The
870 \method{extend()} method is experimental and not supported by
871 mutable sequence types other than lists.
872
873\item[(3)] Raises \exception{ValueError} when \var{x} is not found in
Fred Drake68921df1999-08-09 17:05:12 +0000874 \var{s}.
875
Fred Drakeef428a22001-10-26 18:57:14 +0000876\item[(4)] When a negative index is passed as the first parameter to
877 the \method{insert()} method, the new element is prepended to the
878 sequence.
879
880\item[(5)] The \method{pop()} method is only supported by the list and
Fred Drakefbd3b452000-07-31 23:42:23 +0000881 array types. The optional argument \var{i} defaults to \code{-1},
882 so that by default the last item is removed and returned.
Fred Drake38e5d272000-04-03 20:13:55 +0000883
Fred Drakeef428a22001-10-26 18:57:14 +0000884\item[(6)] The \method{sort()} and \method{reverse()} methods modify the
Fred Drake38e5d272000-04-03 20:13:55 +0000885 list in place for economy of space when sorting or reversing a large
Skip Montanaro41d7d582001-07-25 16:18:19 +0000886 list. To remind you that they operate by side effect, they don't return
887 the sorted or reversed list.
Fred Drake38e5d272000-04-03 20:13:55 +0000888
Fred Drakeef428a22001-10-26 18:57:14 +0000889\item[(7)] The \method{sort()} method takes an optional argument
Fred Drake64e3b431998-07-24 13:56:11 +0000890 specifying a comparison function of two arguments (list items) which
Tim Peters599db7d2001-09-29 01:08:19 +0000891 should return a negative, zero or positive number depending on whether
Fred Drake68921df1999-08-09 17:05:12 +0000892 the first argument is considered smaller than, equal to, or larger
893 than the second argument. Note that this slows the sorting process
894 down considerably; e.g. to sort a list in reverse order it is much
895 faster to use calls to the methods \method{sort()} and
896 \method{reverse()} than to use the built-in function
897 \function{sort()} with a comparison function that reverses the
898 ordering of the elements.
Fred Drake64e3b431998-07-24 13:56:11 +0000899\end{description}
900
901
Fred Drake7a2f0661998-09-10 18:25:58 +0000902\subsection{Mapping Types \label{typesmapping}}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000903\obindex{mapping}
904\obindex{dictionary}
Fred Drake64e3b431998-07-24 13:56:11 +0000905
906A \dfn{mapping} object maps values of one type (the key type) to
907arbitrary objects. Mappings are mutable objects. There is currently
908only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
909almost arbitrary values. The only types of values not acceptable as
910keys are values containing lists or dictionaries or other mutable
911types that are compared by value rather than by object identity.
912Numeric types used for keys obey the normal rules for numeric
913comparison: if two numbers compare equal (e.g. \code{1} and
914\code{1.0}) then they can be used interchangeably to index the same
915dictionary entry.
916
Fred Drake64e3b431998-07-24 13:56:11 +0000917Dictionaries are created by placing a comma-separated list of
918\code{\var{key}: \var{value}} pairs within braces, for example:
919\code{\{'jack': 4098, 'sjoerd': 4127\}} or
920\code{\{4098: 'jack', 4127: 'sjoerd'\}}.
921
Fred Drake9c5cc141999-06-10 22:37:34 +0000922The following operations are defined on mappings (where \var{a} and
923\var{b} are mappings, \var{k} is a key, and \var{v} and \var{x} are
924arbitrary objects):
Fred Drake64e3b431998-07-24 13:56:11 +0000925\indexiii{operations on}{mapping}{types}
926\indexiii{operations on}{dictionary}{type}
927\stindex{del}
928\bifuncindex{len}
Fred Drake9474d861999-02-12 22:05:33 +0000929\withsubitem{(dictionary method)}{
930 \ttindex{clear()}
931 \ttindex{copy()}
932 \ttindex{has_key()}
933 \ttindex{items()}
934 \ttindex{keys()}
935 \ttindex{update()}
936 \ttindex{values()}
Fred Drakee8391991998-11-25 17:09:19 +0000937 \ttindex{get()}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000938
939\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
940 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
941 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
Fred Drake1e75e172000-07-31 16:34:46 +0000942 \lineiii{\var{a}[\var{k}] = \var{v}}
943 {set \code{\var{a}[\var{k}]} to \var{v}}
Fred Drake9c5cc141999-06-10 22:37:34 +0000944 {}
945 \lineiii{del \var{a}[\var{k}]}
946 {remove \code{\var{a}[\var{k}]} from \var{a}}
947 {(1)}
948 \lineiii{\var{a}.clear()}{remove all items from \code{a}}{}
949 \lineiii{\var{a}.copy()}{a (shallow) copy of \code{a}}{}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +0000950 \lineiii{\var{a}.has_key(\var{k})}
Fred Drake9c5cc141999-06-10 22:37:34 +0000951 {\code{1} if \var{a} has a key \var{k}, else \code{0}}
952 {}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +0000953 \lineiii{\var{k} \code{in} \var{a}}
954 {Equivalent to \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000955 {(2)}
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000956 \lineiii{\var{k} not in \var{a}}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +0000957 {Equivalent to \code{not} \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000958 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000959 \lineiii{\var{a}.items()}
960 {a copy of \var{a}'s list of (\var{key}, \var{value}) pairs}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000961 {(3)}
Fred Drake4a6c5c52001-06-12 03:31:56 +0000962 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000963 \lineiii{\var{a}.update(\var{b})}
Fred Drake1e75e172000-07-31 16:34:46 +0000964 {\code{for k in \var{b}.keys(): \var{a}[k] = \var{b}[k]}}
Barry Warsawe9218a12001-06-26 20:32:59 +0000965 {}
Fred Drake4a6c5c52001-06-12 03:31:56 +0000966 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000967 \lineiii{\var{a}.get(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +0000968 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Fred Drake9c5cc141999-06-10 22:37:34 +0000969 else \var{x}}
Barry Warsawe9218a12001-06-26 20:32:59 +0000970 {(4)}
Guido van Rossum8141cf52000-08-08 16:15:49 +0000971 \lineiii{\var{a}.setdefault(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +0000972 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Guido van Rossum8141cf52000-08-08 16:15:49 +0000973 else \var{x} (also setting it)}
Barry Warsawe9218a12001-06-26 20:32:59 +0000974 {(5)}
Guido van Rossumff63f202000-12-12 22:03:47 +0000975 \lineiii{\var{a}.popitem()}
976 {remove and return an arbitrary (\var{key}, \var{value}) pair}
Barry Warsawe9218a12001-06-26 20:32:59 +0000977 {(6)}
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000978 \lineiii{\var{a}.iteritems()}
979 {return an iterator over (\var{key}, \var{value}) pairs}
980 {(2)}
981 \lineiii{\var{a}.iterkeys()}
982 {return an iterator over the mapping's keys}
983 {(2)}
984 \lineiii{\var{a}.itervalues()}
985 {return an iterator over the mapping's values}
986 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +0000987\end{tableiii}
988
Fred Drake64e3b431998-07-24 13:56:11 +0000989\noindent
990Notes:
991\begin{description}
Fred Drake9c5cc141999-06-10 22:37:34 +0000992\item[(1)] Raises a \exception{KeyError} exception if \var{k} is not
993in the map.
Fred Drake64e3b431998-07-24 13:56:11 +0000994
Fred Drakec6d8f8d2001-05-25 04:24:37 +0000995\item[(2)] \versionadded{2.2}
996
997\item[(3)] Keys and values are listed in random order. If
Fred Drake38e5d272000-04-03 20:13:55 +0000998\method{keys()} and \method{values()} are called with no intervening
999modifications to the dictionary, the two lists will directly
1000correspond. This allows the creation of \code{(\var{value},
Fred Drake4a6c5c52001-06-12 03:31:56 +00001001\var{key})} pairs using \function{zip()}: \samp{pairs =
1002zip(\var{a}.values(), \var{a}.keys())}.
Fred Drake64e3b431998-07-24 13:56:11 +00001003
Barry Warsawe9218a12001-06-26 20:32:59 +00001004\item[(4)] Never raises an exception if \var{k} is not in the map,
Fred Drake38e5d272000-04-03 20:13:55 +00001005instead it returns \var{x}. \var{x} is optional; when \var{x} is not
Fred Drake9c5cc141999-06-10 22:37:34 +00001006provided and \var{k} is not in the map, \code{None} is returned.
Guido van Rossum8141cf52000-08-08 16:15:49 +00001007
Barry Warsawe9218a12001-06-26 20:32:59 +00001008\item[(5)] \function{setdefault()} is like \function{get()}, except
Guido van Rossum8141cf52000-08-08 16:15:49 +00001009that if \var{k} is missing, \var{x} is both returned and inserted into
1010the dictionary as the value of \var{k}.
Guido van Rossumff63f202000-12-12 22:03:47 +00001011
Barry Warsawe9218a12001-06-26 20:32:59 +00001012\item[(6)] \function{popitem()} is useful to destructively iterate
Guido van Rossumff63f202000-12-12 22:03:47 +00001013over a dictionary, as often used in set algorithms.
Fred Drake64e3b431998-07-24 13:56:11 +00001014\end{description}
1015
1016
Fred Drake99de2182001-10-30 06:23:14 +00001017\subsection{File Objects
1018 \label{bltin-file-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +00001019
Fred Drake99de2182001-10-30 06:23:14 +00001020File objects\obindex{file} are implemented using C's \code{stdio}
1021package and can be created with the built-in constructor
Tim Peters003047a2001-10-30 05:54:04 +00001022\function{file()}\bifuncindex{file} described in section
1023\ref{built-in-funcs}, ``Built-in Functions.''\footnote{\function{file()}
1024is new in Python 2.2. The older built-in \function{open()} is an
1025alias for \function{file()}.}
1026They are also returned
Fred Drake907e76b2001-07-06 20:30:11 +00001027by some other built-in functions and methods, such as
Fred Drake4de96c22000-08-12 03:36:23 +00001028\function{os.popen()} and \function{os.fdopen()} and the
Fred Drake130072d1998-10-28 20:08:35 +00001029\method{makefile()} method of socket objects.
Fred Drake4de96c22000-08-12 03:36:23 +00001030\refstmodindex{os}
Fred Drake64e3b431998-07-24 13:56:11 +00001031\refbimodindex{socket}
1032
1033When a file operation fails for an I/O-related reason, the exception
Fred Drake84538cd1998-11-30 21:51:25 +00001034\exception{IOError} is raised. This includes situations where the
1035operation is not defined for some reason, like \method{seek()} on a tty
Fred Drake64e3b431998-07-24 13:56:11 +00001036device or writing a file opened for reading.
1037
1038Files have the following methods:
1039
1040
1041\begin{methoddesc}[file]{close}{}
1042 Close the file. A closed file cannot be read or written anymore.
Fred Drakea776cea2000-11-06 20:17:37 +00001043 Any operation which requires that the file be open will raise a
1044 \exception{ValueError} after the file has been closed. Calling
Fred Drake752ba392000-09-19 15:18:51 +00001045 \method{close()} more than once is allowed.
Fred Drake64e3b431998-07-24 13:56:11 +00001046\end{methoddesc}
1047
1048\begin{methoddesc}[file]{flush}{}
Fred Drake752ba392000-09-19 15:18:51 +00001049 Flush the internal buffer, like \code{stdio}'s
1050 \cfunction{fflush()}. This may be a no-op on some file-like
1051 objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001052\end{methoddesc}
1053
1054\begin{methoddesc}[file]{isatty}{}
Fred Drake752ba392000-09-19 15:18:51 +00001055 Return true if the file is connected to a tty(-like) device, else
Fred Drake0aa811c2001-10-20 04:24:09 +00001056 false. \note{If a file-like object is not associated
1057 with a real file, this method should \emph{not} be implemented.}
Fred Drake64e3b431998-07-24 13:56:11 +00001058\end{methoddesc}
1059
1060\begin{methoddesc}[file]{fileno}{}
Fred Drake752ba392000-09-19 15:18:51 +00001061 \index{file descriptor}
1062 \index{descriptor, file}
1063 Return the integer ``file descriptor'' that is used by the
1064 underlying implementation to request I/O operations from the
1065 operating system. This can be useful for other, lower level
Fred Drake907e76b2001-07-06 20:30:11 +00001066 interfaces that use file descriptors, such as the
1067 \refmodule{fcntl}\refbimodindex{fcntl} module or
Fred Drake0aa811c2001-10-20 04:24:09 +00001068 \function{os.read()} and friends. \note{File-like objects
Fred Drake907e76b2001-07-06 20:30:11 +00001069 which do not have a real file descriptor should \emph{not} provide
Fred Drake0aa811c2001-10-20 04:24:09 +00001070 this method!}
Fred Drake64e3b431998-07-24 13:56:11 +00001071\end{methoddesc}
1072
1073\begin{methoddesc}[file]{read}{\optional{size}}
1074 Read at most \var{size} bytes from the file (less if the read hits
Fred Drakef4cbada1999-04-14 14:31:53 +00001075 \EOF{} before obtaining \var{size} bytes). If the \var{size}
1076 argument is negative or omitted, read all data until \EOF{} is
1077 reached. The bytes are returned as a string object. An empty
1078 string is returned when \EOF{} is encountered immediately. (For
1079 certain files, like ttys, it makes sense to continue reading after
1080 an \EOF{} is hit.) Note that this method may call the underlying
1081 C function \cfunction{fread()} more than once in an effort to
1082 acquire as close to \var{size} bytes as possible.
Fred Drake64e3b431998-07-24 13:56:11 +00001083\end{methoddesc}
1084
1085\begin{methoddesc}[file]{readline}{\optional{size}}
1086 Read one entire line from the file. A trailing newline character is
Fred Drakeea003fc1999-04-05 21:59:15 +00001087 kept in the string\footnote{
1088 The advantage of leaving the newline on is that an empty string
Fred Drake64e3b431998-07-24 13:56:11 +00001089 can be returned to mean \EOF{} without being ambiguous. Another
Fred Drake907e76b2001-07-06 20:30:11 +00001090 advantage is that (in cases where it might matter, for example. if you
Fred Drake64e3b431998-07-24 13:56:11 +00001091 want to make an exact copy of a file while scanning its lines)
1092 you can tell whether the last line of a file ended in a newline
Fred Drake4de96c22000-08-12 03:36:23 +00001093 or not (yes this happens!).
1094 } (but may be absent when a file ends with an
Fred Drake64e3b431998-07-24 13:56:11 +00001095 incomplete line). If the \var{size} argument is present and
1096 non-negative, it is a maximum byte count (including the trailing
1097 newline) and an incomplete line may be returned.
1098 An empty string is returned when \EOF{} is hit
Fred Drake0aa811c2001-10-20 04:24:09 +00001099 immediately. \note{Unlike \code{stdio}'s \cfunction{fgets()}, the
Fred Drake752ba392000-09-19 15:18:51 +00001100 returned string contains null characters (\code{'\e 0'}) if they
Fred Drake0aa811c2001-10-20 04:24:09 +00001101 occurred in the input.}
Fred Drake64e3b431998-07-24 13:56:11 +00001102\end{methoddesc}
1103
1104\begin{methoddesc}[file]{readlines}{\optional{sizehint}}
1105 Read until \EOF{} using \method{readline()} and return a list containing
1106 the lines thus read. If the optional \var{sizehint} argument is
Fred Drakec37b65e2001-11-28 07:26:15 +00001107 present, instead of reading up to \EOF, whole lines totalling
Fred Drake64e3b431998-07-24 13:56:11 +00001108 approximately \var{sizehint} bytes (possibly after rounding up to an
Fred Drake752ba392000-09-19 15:18:51 +00001109 internal buffer size) are read. Objects implementing a file-like
1110 interface may choose to ignore \var{sizehint} if it cannot be
1111 implemented, or cannot be implemented efficiently.
Fred Drake64e3b431998-07-24 13:56:11 +00001112\end{methoddesc}
1113
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001114\begin{methoddesc}[file]{xreadlines}{}
Fred Drake82f93c62001-04-22 01:56:51 +00001115 Equivalent to
1116 \function{xreadlines.xreadlines(\var{file})}.\refstmodindex{xreadlines}
1117 (See the \refmodule{xreadlines} module for more information.)
1118 \versionadded{2.1}
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001119\end{methoddesc}
1120
Fred Drake64e3b431998-07-24 13:56:11 +00001121\begin{methoddesc}[file]{seek}{offset\optional{, whence}}
1122 Set the file's current position, like \code{stdio}'s \cfunction{fseek()}.
1123 The \var{whence} argument is optional and defaults to \code{0}
1124 (absolute file positioning); other values are \code{1} (seek
1125 relative to the current position) and \code{2} (seek relative to the
Fred Drake19ae7832001-01-04 05:16:39 +00001126 file's end). There is no return value. Note that if the file is
1127 opened for appending (mode \code{'a'} or \code{'a+'}), any
1128 \method{seek()} operations will be undone at the next write. If the
1129 file is only opened for writing in append mode (mode \code{'a'}),
1130 this method is essentially a no-op, but it remains useful for files
1131 opened in append mode with reading enabled (mode \code{'a+'}).
Fred Drake64e3b431998-07-24 13:56:11 +00001132\end{methoddesc}
1133
1134\begin{methoddesc}[file]{tell}{}
1135 Return the file's current position, like \code{stdio}'s
1136 \cfunction{ftell()}.
1137\end{methoddesc}
1138
1139\begin{methoddesc}[file]{truncate}{\optional{size}}
Fred Drake752ba392000-09-19 15:18:51 +00001140 Truncate the file's size. If the optional \var{size} argument
1141 present, the file is truncated to (at most) that size. The size
1142 defaults to the current position. Availability of this function
1143 depends on the operating system version (for example, not all
1144 \UNIX{} versions support this operation).
Fred Drake64e3b431998-07-24 13:56:11 +00001145\end{methoddesc}
1146
1147\begin{methoddesc}[file]{write}{str}
Fred Drake0aa811c2001-10-20 04:24:09 +00001148 Write a string to the file. There is no return value. Due to
Fred Drake3c48ef72001-01-09 22:47:46 +00001149 buffering, the string may not actually show up in the file until
1150 the \method{flush()} or \method{close()} method is called.
Fred Drake64e3b431998-07-24 13:56:11 +00001151\end{methoddesc}
1152
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001153\begin{methoddesc}[file]{writelines}{sequence}
1154 Write a sequence of strings to the file. The sequence can be any
1155 iterable object producing strings, typically a list of strings.
1156 There is no return value.
Fred Drake3c48ef72001-01-09 22:47:46 +00001157 (The name is intended to match \method{readlines()};
1158 \method{writelines()} does not add line separators.)
1159\end{methoddesc}
1160
Fred Drake64e3b431998-07-24 13:56:11 +00001161
Fred Drake038d2642001-09-22 04:34:48 +00001162Files support the iterator protocol. Each iteration returns the same
1163result as \code{\var{file}.readline()}, and iteration ends when the
1164\method{readline()} method returns an empty string.
1165
1166
Fred Drake752ba392000-09-19 15:18:51 +00001167File objects also offer a number of other interesting attributes.
1168These are not required for file-like objects, but should be
1169implemented if they make sense for the particular object.
Fred Drake64e3b431998-07-24 13:56:11 +00001170
1171\begin{memberdesc}[file]{closed}
1172Boolean indicating the current state of the file object. This is a
1173read-only attribute; the \method{close()} method changes the value.
Fred Drake752ba392000-09-19 15:18:51 +00001174It may not be available on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001175\end{memberdesc}
1176
1177\begin{memberdesc}[file]{mode}
1178The I/O mode for the file. If the file was created using the
1179\function{open()} built-in function, this will be the value of the
Fred Drake752ba392000-09-19 15:18:51 +00001180\var{mode} parameter. This is a read-only attribute and may not be
1181present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001182\end{memberdesc}
1183
1184\begin{memberdesc}[file]{name}
1185If the file object was created using \function{open()}, the name of
1186the file. Otherwise, some string that indicates the source of the
1187file object, of the form \samp{<\mbox{\ldots}>}. This is a read-only
Fred Drake752ba392000-09-19 15:18:51 +00001188attribute and may not be present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001189\end{memberdesc}
1190
1191\begin{memberdesc}[file]{softspace}
1192Boolean that indicates whether a space character needs to be printed
1193before another value when using the \keyword{print} statement.
1194Classes that are trying to simulate a file object should also have a
1195writable \member{softspace} attribute, which should be initialized to
Fred Drake66571cc2000-09-09 03:30:34 +00001196zero. This will be automatic for most classes implemented in Python
1197(care may be needed for objects that override attribute access); types
1198implemented in C will have to provide a writable
1199\member{softspace} attribute.
Fred Drake0aa811c2001-10-20 04:24:09 +00001200\note{This attribute is not used to control the
Fred Drake51f53df2000-09-20 04:48:20 +00001201\keyword{print} statement, but to allow the implementation of
Fred Drake0aa811c2001-10-20 04:24:09 +00001202\keyword{print} to keep track of its internal state.}
Fred Drake64e3b431998-07-24 13:56:11 +00001203\end{memberdesc}
1204
Fred Drakea776cea2000-11-06 20:17:37 +00001205
Fred Drake99de2182001-10-30 06:23:14 +00001206\subsection{Other Built-in Types \label{typesother}}
1207
1208The interpreter supports several other kinds of objects.
1209Most of these support only one or two operations.
1210
1211
1212\subsubsection{Modules \label{typesmodules}}
1213
1214The only special operation on a module is attribute access:
1215\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name}
1216accesses a name defined in \var{m}'s symbol table. Module attributes
1217can be assigned to. (Note that the \keyword{import} statement is not,
1218strictly speaking, an operation on a module object; \code{import
1219\var{foo}} does not require a module object named \var{foo} to exist,
1220rather it requires an (external) \emph{definition} for a module named
1221\var{foo} somewhere.)
1222
1223A special member of every module is \member{__dict__}.
1224This is the dictionary containing the module's symbol table.
1225Modifying this dictionary will actually change the module's symbol
1226table, but direct assignment to the \member{__dict__} attribute is not
1227possible (you can write \code{\var{m}.__dict__['a'] = 1}, which
1228defines \code{\var{m}.a} to be \code{1}, but you can't write
1229\code{\var{m}.__dict__ = \{\}}.
1230
1231Modules built into the interpreter are written like this:
1232\code{<module 'sys' (built-in)>}. If loaded from a file, they are
1233written as \code{<module 'os' from
1234'/usr/local/lib/python\shortversion/os.pyc'>}.
1235
1236
1237\subsubsection{Classes and Class Instances \label{typesobjects}}
1238\nodename{Classes and Instances}
1239
1240See chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python
1241Reference Manual} for these.
1242
1243
1244\subsubsection{Functions \label{typesfunctions}}
1245
1246Function objects are created by function definitions. The only
1247operation on a function object is to call it:
1248\code{\var{func}(\var{argument-list})}.
1249
1250There are really two flavors of function objects: built-in functions
1251and user-defined functions. Both support the same operation (to call
1252the function), but the implementation is different, hence the
1253different object types.
1254
1255The implementation adds two special read-only attributes:
1256\code{\var{f}.func_code} is a function's \dfn{code
1257object}\obindex{code} (see below) and \code{\var{f}.func_globals} is
1258the dictionary used as the function's global namespace (this is the
1259same as \code{\var{m}.__dict__} where \var{m} is the module in which
1260the function \var{f} was defined).
1261
1262Function objects also support getting and setting arbitrary
1263attributes, which can be used to, e.g. attach metadata to functions.
1264Regular attribute dot-notation is used to get and set such
1265attributes. \emph{Note that the current implementation only supports
1266function attributes on user-defined functions. Function attributes on
1267built-in functions may be supported in the future.}
1268
1269Functions have another special attribute \code{\var{f}.__dict__}
1270(a.k.a. \code{\var{f}.func_dict}) which contains the namespace used to
1271support function attributes. \code{__dict__} and \code{func_dict} can
1272be accessed directly or set to a dictionary object. A function's
1273dictionary cannot be deleted.
1274
1275\subsubsection{Methods \label{typesmethods}}
1276\obindex{method}
1277
1278Methods are functions that are called using the attribute notation.
1279There are two flavors: built-in methods (such as \method{append()} on
1280lists) and class instance methods. Built-in methods are described
1281with the types that support them.
1282
1283The implementation adds two special read-only attributes to class
1284instance methods: \code{\var{m}.im_self} is the object on which the
1285method operates, and \code{\var{m}.im_func} is the function
1286implementing the method. Calling \code{\var{m}(\var{arg-1},
1287\var{arg-2}, \textrm{\ldots}, \var{arg-n})} is completely equivalent to
1288calling \code{\var{m}.im_func(\var{m}.im_self, \var{arg-1},
1289\var{arg-2}, \textrm{\ldots}, \var{arg-n})}.
1290
1291Class instance methods are either \emph{bound} or \emph{unbound},
1292referring to whether the method was accessed through an instance or a
1293class, respectively. When a method is unbound, its \code{im_self}
1294attribute will be \code{None} and if called, an explicit \code{self}
1295object must be passed as the first argument. In this case,
1296\code{self} must be an instance of the unbound method's class (or a
1297subclass of that class), otherwise a \code{TypeError} is raised.
1298
1299Like function objects, methods objects support getting
1300arbitrary attributes. However, since method attributes are actually
1301stored on the underlying function object (\code{meth.im_func}),
1302setting method attributes on either bound or unbound methods is
1303disallowed. Attempting to set a method attribute results in a
1304\code{TypeError} being raised. In order to set a method attribute,
1305you need to explicitly set it on the underlying function object:
1306
1307\begin{verbatim}
1308class C:
1309 def method(self):
1310 pass
1311
1312c = C()
1313c.method.im_func.whoami = 'my name is c'
1314\end{verbatim}
1315
1316See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1317information.
1318
1319
1320\subsubsection{Code Objects \label{bltin-code-objects}}
1321\obindex{code}
1322
1323Code objects are used by the implementation to represent
1324``pseudo-compiled'' executable Python code such as a function body.
1325They differ from function objects because they don't contain a
1326reference to their global execution environment. Code objects are
1327returned by the built-in \function{compile()} function and can be
1328extracted from function objects through their \member{func_code}
1329attribute.
1330\bifuncindex{compile}
1331\withsubitem{(function object attribute)}{\ttindex{func_code}}
1332
1333A code object can be executed or evaluated by passing it (instead of a
1334source string) to the \keyword{exec} statement or the built-in
1335\function{eval()} function.
1336\stindex{exec}
1337\bifuncindex{eval}
1338
1339See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1340information.
1341
1342
1343\subsubsection{Type Objects \label{bltin-type-objects}}
1344
1345Type objects represent the various object types. An object's type is
1346accessed by the built-in function \function{type()}. There are no special
1347operations on types. The standard module \module{types} defines names
1348for all standard built-in types.
1349\bifuncindex{type}
1350\refstmodindex{types}
1351
1352Types are written like this: \code{<type 'int'>}.
1353
1354
1355\subsubsection{The Null Object \label{bltin-null-object}}
1356
1357This object is returned by functions that don't explicitly return a
1358value. It supports no special operations. There is exactly one null
1359object, named \code{None} (a built-in name).
1360
1361It is written as \code{None}.
1362
1363
1364\subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
1365
1366This object is used by extended slice notation (see the
1367\citetitle[../ref/ref.html]{Python Reference Manual}). It supports no
1368special operations. There is exactly one ellipsis object, named
1369\constant{Ellipsis} (a built-in name).
1370
1371It is written as \code{Ellipsis}.
1372
1373
Fred Drake9474d861999-02-12 22:05:33 +00001374\subsubsection{Internal Objects \label{typesinternal}}
Fred Drake64e3b431998-07-24 13:56:11 +00001375
Fred Drake37f15741999-11-10 16:21:37 +00001376See the \citetitle[../ref/ref.html]{Python Reference Manual} for this
Fred Drake512bb722000-08-18 03:12:38 +00001377information. It describes stack frame objects, traceback objects, and
1378slice objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001379
1380
Fred Drake7a2f0661998-09-10 18:25:58 +00001381\subsection{Special Attributes \label{specialattrs}}
Fred Drake64e3b431998-07-24 13:56:11 +00001382
1383The implementation adds a few special read-only attributes to several
1384object types, where they are relevant:
1385
Fred Drakea776cea2000-11-06 20:17:37 +00001386\begin{memberdesc}[object]{__dict__}
1387A dictionary or other mapping object used to store an
Fred Drake7a2f0661998-09-10 18:25:58 +00001388object's (writable) attributes.
Fred Drakea776cea2000-11-06 20:17:37 +00001389\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001390
Fred Drakea776cea2000-11-06 20:17:37 +00001391\begin{memberdesc}[object]{__methods__}
Fred Drake35705512001-12-03 17:32:27 +00001392\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1393list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001394\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001395
Fred Drakea776cea2000-11-06 20:17:37 +00001396\begin{memberdesc}[object]{__members__}
Fred Drake35705512001-12-03 17:32:27 +00001397\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1398list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001399\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001400
Fred Drakea776cea2000-11-06 20:17:37 +00001401\begin{memberdesc}[instance]{__class__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001402The class to which a class instance belongs.
Fred Drakea776cea2000-11-06 20:17:37 +00001403\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001404
Fred Drakea776cea2000-11-06 20:17:37 +00001405\begin{memberdesc}[class]{__bases__}
Fred Drake907e76b2001-07-06 20:30:11 +00001406The tuple of base classes of a class object. If there are no base
1407classes, this will be an empty tuple.
Fred Drakea776cea2000-11-06 20:17:37 +00001408\end{memberdesc}