blob: c2a7c88aa69a22d5d50c7ec457395ef88755d959 [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
Steve Holden1e4519f2002-06-14 09:16:40 +00004the interpreter. Historically, Python's built-in types have differed
5from user-defined types because it was not possible to use the built-in
6types as the basis for object-oriented inheritance. With the 2.2
7release this situation has started to change, although the intended
8unification of user-defined and built-in types is as yet far from
9complete.
10
11The principal built-in types are numerics, sequences, mappings, files
12classes, instances and exceptions.
Fred Drake64e3b431998-07-24 13:56:11 +000013\indexii{built-in}{types}
Fred Drake64e3b431998-07-24 13:56:11 +000014
15Some operations are supported by several object types; in particular,
Guido van Rossum50e7a112003-12-31 06:32:38 +000016practically all objects can be compared, tested for truth value,
17and converted to a string (with the \code{`\textrm{\ldots}`} notation,
18the equivalent \function{repr()} function, or the slightly different
19\function{str()} function). The latter
20function is implicitly used when an object is written by the
Fred Drake84538cd1998-11-30 21:51:25 +000021\keyword{print}\stindex{print} statement.
Fred Drake90fc0b32003-04-30 16:44:36 +000022(Information on \ulink{\keyword{print} statement}{../ref/print.html}
23and other language statements can be found in the
24\citetitle[../ref/ref.html]{Python Reference Manual} and the
25\citetitle[../tut/tut.html]{Python Tutorial}.)
Fred Drake64e3b431998-07-24 13:56:11 +000026
27
Fred Drake90fc0b32003-04-30 16:44:36 +000028\subsection{Truth Value Testing\label{truth}}
Fred Drake64e3b431998-07-24 13:56:11 +000029
Fred Drake84538cd1998-11-30 21:51:25 +000030Any object can be tested for truth value, for use in an \keyword{if} or
31\keyword{while} condition or as operand of the Boolean operations below.
Fred Drake64e3b431998-07-24 13:56:11 +000032The following values are considered false:
33\stindex{if}
34\stindex{while}
35\indexii{truth}{value}
36\indexii{Boolean}{operations}
37\index{false}
38
Fred Drake64e3b431998-07-24 13:56:11 +000039\begin{itemize}
40
41\item \code{None}
Fred Drake442c7c72002-08-07 15:40:15 +000042 \withsubitem{(Built-in object)}{\ttindex{None}}
Fred Drake64e3b431998-07-24 13:56:11 +000043
Guido van Rossum77f6a652002-04-03 22:41:51 +000044\item \code{False}
Fred Drake442c7c72002-08-07 15:40:15 +000045 \withsubitem{(Built-in object)}{\ttindex{False}}
Guido van Rossum77f6a652002-04-03 22:41:51 +000046
Fred Drake38e5d272000-04-03 20:13:55 +000047\item zero of any numeric type, for example, \code{0}, \code{0L},
48 \code{0.0}, \code{0j}.
Fred Drake64e3b431998-07-24 13:56:11 +000049
Fred Drake38e5d272000-04-03 20:13:55 +000050\item any empty sequence, for example, \code{''}, \code{()}, \code{[]}.
Fred Drake64e3b431998-07-24 13:56:11 +000051
Fred Drake38e5d272000-04-03 20:13:55 +000052\item any empty mapping, for example, \code{\{\}}.
Fred Drake64e3b431998-07-24 13:56:11 +000053
54\item instances of user-defined classes, if the class defines a
Fred Drake442c7c72002-08-07 15:40:15 +000055 \method{__nonzero__()} or \method{__len__()} method, when that
56 method returns the integer zero or \class{bool} value
57 \code{False}.\footnote{Additional
Fred Drake3e59f722002-07-12 17:15:10 +000058information on these special methods may be found in the
59\citetitle[../ref/ref.html]{Python Reference Manual}.}
Fred Drake64e3b431998-07-24 13:56:11 +000060
61\end{itemize}
62
63All other values are considered true --- so objects of many types are
64always true.
65\index{true}
66
67Operations and built-in functions that have a Boolean result always
Guido van Rossum77f6a652002-04-03 22:41:51 +000068return \code{0} or \code{False} for false and \code{1} or \code{True}
69for true, unless otherwise stated. (Important exception: the Boolean
70operations \samp{or}\opindex{or} and \samp{and}\opindex{and} always
71return one of their operands.)
72\index{False}
73\index{True}
Fred Drake64e3b431998-07-24 13:56:11 +000074
Raymond Hettinger24d75212005-06-14 08:45:43 +000075\subsection{Boolean Operations ---
76 \keyword{and}, \keyword{or}, \keyword{not}
77 \label{boolean}}
Fred Drake64e3b431998-07-24 13:56:11 +000078
79These are the Boolean operations, ordered by ascending priority:
80\indexii{Boolean}{operations}
81
82\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
Fred Drake8c071d42001-01-26 20:48:35 +000083 \lineiii{\var{x} or \var{y}}
84 {if \var{x} is false, then \var{y}, else \var{x}}{(1)}
85 \lineiii{\var{x} and \var{y}}
86 {if \var{x} is false, then \var{x}, else \var{y}}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +000087 \hline
Fred Drake8c071d42001-01-26 20:48:35 +000088 \lineiii{not \var{x}}
Guido van Rossum77f6a652002-04-03 22:41:51 +000089 {if \var{x} is false, then \code{True}, else \code{False}}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +000090\end{tableiii}
91\opindex{and}
92\opindex{or}
93\opindex{not}
94
95\noindent
96Notes:
97
98\begin{description}
99
100\item[(1)]
101These only evaluate their second argument if needed for their outcome.
102
103\item[(2)]
Fred Drake38e5d272000-04-03 20:13:55 +0000104\samp{not} has a lower priority than non-Boolean operators, so
105\code{not \var{a} == \var{b}} is interpreted as \code{not (\var{a} ==
106\var{b})}, and \code{\var{a} == not \var{b}} is a syntax error.
Fred Drake64e3b431998-07-24 13:56:11 +0000107
108\end{description}
109
110
Fred Drake7a2f0661998-09-10 18:25:58 +0000111\subsection{Comparisons \label{comparisons}}
Fred Drake64e3b431998-07-24 13:56:11 +0000112
113Comparison operations are supported by all objects. They all have the
114same priority (which is higher than that of the Boolean operations).
Fred Drake38e5d272000-04-03 20:13:55 +0000115Comparisons can be chained arbitrarily; for example, \code{\var{x} <
116\var{y} <= \var{z}} is equivalent to \code{\var{x} < \var{y} and
117\var{y} <= \var{z}}, except that \var{y} is evaluated only once (but
118in both cases \var{z} is not evaluated at all when \code{\var{x} <
119\var{y}} is found to be false).
Fred Drake64e3b431998-07-24 13:56:11 +0000120\indexii{chaining}{comparisons}
121
122This table summarizes the comparison operations:
123
124\begin{tableiii}{c|l|c}{code}{Operation}{Meaning}{Notes}
125 \lineiii{<}{strictly less than}{}
126 \lineiii{<=}{less than or equal}{}
127 \lineiii{>}{strictly greater than}{}
128 \lineiii{>=}{greater than or equal}{}
129 \lineiii{==}{equal}{}
Fred Drake64e3b431998-07-24 13:56:11 +0000130 \lineiii{!=}{not equal}{(1)}
Fred Drake512bb722000-08-18 03:12:38 +0000131 \lineiii{<>}{not equal}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000132 \lineiii{is}{object identity}{}
133 \lineiii{is not}{negated object identity}{}
134\end{tableiii}
135\indexii{operator}{comparison}
136\opindex{==} % XXX *All* others have funny characters < ! >
137\opindex{is}
138\opindex{is not}
139
140\noindent
141Notes:
142
143\begin{description}
144
145\item[(1)]
146\code{<>} and \code{!=} are alternate spellings for the same operator.
Fred Drake38e5d272000-04-03 20:13:55 +0000147\code{!=} is the preferred spelling; \code{<>} is obsolescent.
Fred Drake64e3b431998-07-24 13:56:11 +0000148
149\end{description}
150
Martin v. Löwis19a5a712003-05-31 08:05:49 +0000151Objects of different types, except different numeric types and different string types, never
Fred Drake64e3b431998-07-24 13:56:11 +0000152compare equal; such objects are ordered consistently but arbitrarily
153(so that sorting a heterogeneous array yields a consistent result).
Fred Drake38e5d272000-04-03 20:13:55 +0000154Furthermore, some types (for example, file objects) support only a
155degenerate notion of comparison where any two objects of that type are
156unequal. Again, such objects are ordered arbitrarily but
Steve Holden1e4519f2002-06-14 09:16:40 +0000157consistently. The \code{<}, \code{<=}, \code{>} and \code{>=}
158operators will raise a \exception{TypeError} exception when any operand
159is a complex number.
Fred Drake38e5d272000-04-03 20:13:55 +0000160\indexii{object}{numeric}
Fred Drake64e3b431998-07-24 13:56:11 +0000161\indexii{objects}{comparing}
162
Fred Drake38e5d272000-04-03 20:13:55 +0000163Instances of a class normally compare as non-equal unless the class
164\withsubitem{(instance method)}{\ttindex{__cmp__()}}
Fred Drake66571cc2000-09-09 03:30:34 +0000165defines the \method{__cmp__()} method. Refer to the
166\citetitle[../ref/customization.html]{Python Reference Manual} for
167information on the use of this method to effect object comparisons.
Fred Drake64e3b431998-07-24 13:56:11 +0000168
Fred Drake38e5d272000-04-03 20:13:55 +0000169\strong{Implementation note:} Objects of different types except
170numbers are ordered by their type names; objects of the same types
171that don't support proper comparison are ordered by their address.
172
173Two more operations with the same syntactic priority,
174\samp{in}\opindex{in} and \samp{not in}\opindex{not in}, are supported
175only by sequence types (below).
Fred Drake64e3b431998-07-24 13:56:11 +0000176
177
Raymond Hettinger24d75212005-06-14 08:45:43 +0000178\subsection{Numeric Types ---
179 \class{int}, \class{float}, \class{long}, \class{complex}
180 \label{typesnumeric}}
Fred Drake64e3b431998-07-24 13:56:11 +0000181
Guido van Rossum77f6a652002-04-03 22:41:51 +0000182There are four distinct numeric types: \dfn{plain integers},
183\dfn{long integers},
Fred Drake64e3b431998-07-24 13:56:11 +0000184\dfn{floating point numbers}, and \dfn{complex numbers}.
Guido van Rossum77f6a652002-04-03 22:41:51 +0000185In addition, Booleans are a subtype of plain integers.
Fred Drake64e3b431998-07-24 13:56:11 +0000186Plain integers (also just called \dfn{integers})
Fred Drake38e5d272000-04-03 20:13:55 +0000187are implemented using \ctype{long} in C, which gives them at least 32
Fred Drake64e3b431998-07-24 13:56:11 +0000188bits of precision. Long integers have unlimited precision. Floating
Fred Drake38e5d272000-04-03 20:13:55 +0000189point numbers are implemented using \ctype{double} in C. All bets on
Fred Drake64e3b431998-07-24 13:56:11 +0000190their precision are off unless you happen to know the machine you are
191working with.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000192\obindex{numeric}
Guido van Rossum77f6a652002-04-03 22:41:51 +0000193\obindex{Boolean}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000194\obindex{integer}
195\obindex{long integer}
196\obindex{floating point}
197\obindex{complex number}
Fred Drake38e5d272000-04-03 20:13:55 +0000198\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000199
Steve Holden1e4519f2002-06-14 09:16:40 +0000200Complex numbers have a real and imaginary part, which are each
Fred Drake38e5d272000-04-03 20:13:55 +0000201implemented using \ctype{double} in C. To extract these parts from
Tim Peters8f01b682002-03-12 03:04:44 +0000202a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Fred Drake64e3b431998-07-24 13:56:11 +0000203
204Numbers are created by numeric literals or as the result of built-in
205functions and operators. Unadorned integer literals (including hex
Steve Holden1e4519f2002-06-14 09:16:40 +0000206and octal numbers) yield plain integers unless the value they denote
207is too large to be represented as a plain integer, in which case
208they yield a long integer. Integer literals with an
Fred Drake38e5d272000-04-03 20:13:55 +0000209\character{L} or \character{l} suffix yield long integers
210(\character{L} is preferred because \samp{1l} looks too much like
211eleven!). Numeric literals containing a decimal point or an exponent
212sign yield floating point numbers. Appending \character{j} or
Steve Holden1e4519f2002-06-14 09:16:40 +0000213\character{J} to a numeric literal yields a complex number with a
214zero real part. A complex numeric literal is the sum of a real and
215an imaginary part.
Fred Drake64e3b431998-07-24 13:56:11 +0000216\indexii{numeric}{literals}
217\indexii{integer}{literals}
218\indexiii{long}{integer}{literals}
219\indexii{floating point}{literals}
220\indexii{complex number}{literals}
221\indexii{hexadecimal}{literals}
222\indexii{octal}{literals}
223
224Python fully supports mixed arithmetic: when a binary arithmetic
225operator has operands of different numeric types, the operand with the
Steve Holden1e4519f2002-06-14 09:16:40 +0000226``narrower'' type is widened to that of the other, where plain
227integer is narrower than long integer is narrower than floating point is
228narrower than complex.
Fred Drakeea003fc1999-04-05 21:59:15 +0000229Comparisons between numbers of mixed type use the same rule.\footnote{
230 As a consequence, the list \code{[1, 2]} is considered equal
Steve Holden1e4519f2002-06-14 09:16:40 +0000231 to \code{[1.0, 2.0]}, and similarly for tuples.
232} The constructors \function{int()}, \function{long()}, \function{float()},
Fred Drake84538cd1998-11-30 21:51:25 +0000233and \function{complex()} can be used
Steve Holden1e4519f2002-06-14 09:16:40 +0000234to produce numbers of a specific type.
Fred Drake64e3b431998-07-24 13:56:11 +0000235\index{arithmetic}
236\bifuncindex{int}
237\bifuncindex{long}
238\bifuncindex{float}
239\bifuncindex{complex}
240
Michael W. Hudson9c206152003-03-05 14:42:09 +0000241All numeric types (except complex) support the following operations,
242sorted by ascending priority (operations in the same box have the same
Fred Drake64e3b431998-07-24 13:56:11 +0000243priority; all numeric operations have a higher priority than
244comparison operations):
245
246\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
247 \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
248 \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
249 \hline
250 \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
251 \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)}
Michael W. Hudson9c206152003-03-05 14:42:09 +0000252 \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000253 \hline
254 \lineiii{-\var{x}}{\var{x} negated}{}
255 \lineiii{+\var{x}}{\var{x} unchanged}{}
256 \hline
257 \lineiii{abs(\var{x})}{absolute value or magnitude of \var{x}}{}
258 \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)}
259 \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)}
260 \lineiii{float(\var{x})}{\var{x} converted to floating point}{}
261 \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 +0000262 \lineiii{\var{c}.conjugate()}{conjugate of the complex number \var{c}}{}
Raymond Hettingerdede3bd2005-05-31 11:04:00 +0000263 \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} // \var{y}, \var{x} \%{} \var{y})}}{(3)(4)}
Fred Drake64e3b431998-07-24 13:56:11 +0000264 \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
265 \lineiii{\var{x} ** \var{y}}{\var{x} to the power \var{y}}{}
266\end{tableiii}
267\indexiii{operations on}{numeric}{types}
Fred Drake26b698f1999-02-12 18:27:31 +0000268\withsubitem{(complex number method)}{\ttindex{conjugate()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000269
270\noindent
271Notes:
272\begin{description}
273
274\item[(1)]
275For (plain or long) integer division, the result is an integer.
Tim Peters8f01b682002-03-12 03:04:44 +0000276The result is always rounded towards minus infinity: 1/2 is 0,
Fred Drake38e5d272000-04-03 20:13:55 +0000277(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
278is a long integer if either operand is a long integer, regardless of
279the numeric value.
Fred Drake64e3b431998-07-24 13:56:11 +0000280\indexii{integer}{division}
281\indexiii{long}{integer}{division}
282
283\item[(2)]
284Conversion from floating point to (long or plain) integer may round or
Fred Drake4de96c22000-08-12 03:36:23 +0000285truncate as in C; see functions \function{floor()} and
286\function{ceil()} in the \refmodule{math}\refbimodindex{math} module
287for well-defined conversions.
Fred Drake9474d861999-02-12 22:05:33 +0000288\withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}}
Fred Drake64e3b431998-07-24 13:56:11 +0000289\indexii{numeric}{conversions}
Fred Drake4de96c22000-08-12 03:36:23 +0000290\indexii{C}{language}
Fred Drake64e3b431998-07-24 13:56:11 +0000291
292\item[(3)]
Fred Drake38e5d272000-04-03 20:13:55 +0000293See section \ref{built-in-funcs}, ``Built-in Functions,'' for a full
294description.
Fred Drake64e3b431998-07-24 13:56:11 +0000295
Michael W. Hudson9c206152003-03-05 14:42:09 +0000296\item[(4)]
297Complex floor division operator, modulo operator, and \function{divmod()}.
298
299\deprecated{2.3}{Instead convert to float using \function{abs()}
300if appropriate.}
301
Fred Drake64e3b431998-07-24 13:56:11 +0000302\end{description}
303% XXXJH exceptions: overflow (when? what operations?) zerodivision
304
Fred Drake4e7c2051999-02-19 15:30:25 +0000305\subsubsection{Bit-string Operations on Integer Types \label{bitstring-ops}}
Fred Drake64e3b431998-07-24 13:56:11 +0000306\nodename{Bit-string Operations}
307
308Plain and long integer types support additional operations that make
309sense only for bit-strings. Negative numbers are treated as their 2's
310complement value (for long integers, this assumes a sufficiently large
311number of bits that no overflow occurs during the operation).
312
313The priorities of the binary bit-wise operations are all lower than
314the numeric operations and higher than the comparisons; the unary
315operation \samp{\~} has the same priority as the other unary numeric
316operations (\samp{+} and \samp{-}).
317
318This table lists the bit-string operations sorted in ascending
319priority (operations in the same box have the same priority):
320
321\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
322 \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
323 \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
324 \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
Fred Drake2269d862004-11-11 06:14:05 +0000325 % The empty groups below prevent conversion to guillemets.
326 \lineiii{\var{x} <{}< \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)}
327 \lineiii{\var{x} >{}> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)}
Fred Drake64e3b431998-07-24 13:56:11 +0000328 \hline
329 \lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
330\end{tableiii}
331\indexiii{operations on}{integer}{types}
332\indexii{bit-string}{operations}
333\indexii{shifting}{operations}
334\indexii{masking}{operations}
335
336\noindent
337Notes:
338\begin{description}
339\item[(1)] Negative shift counts are illegal and cause a
340\exception{ValueError} to be raised.
341\item[(2)] A left shift by \var{n} bits is equivalent to
342multiplication by \code{pow(2, \var{n})} without overflow check.
343\item[(3)] A right shift by \var{n} bits is equivalent to
344division by \code{pow(2, \var{n})} without overflow check.
345\end{description}
346
347
Fred Drake93656e72001-05-02 20:18:03 +0000348\subsection{Iterator Types \label{typeiter}}
349
Fred Drakef42cc452001-05-03 04:39:10 +0000350\versionadded{2.2}
Fred Drake93656e72001-05-02 20:18:03 +0000351\index{iterator protocol}
352\index{protocol!iterator}
353\index{sequence!iteration}
354\index{container!iteration over}
355
356Python supports a concept of iteration over containers. This is
357implemented using two distinct methods; these are used to allow
358user-defined classes to support iteration. Sequences, described below
359in more detail, always support the iteration methods.
360
361One method needs to be defined for container objects to provide
362iteration support:
363
364\begin{methoddesc}[container]{__iter__}{}
Greg Ward54f65092001-07-26 21:01:21 +0000365 Return an iterator object. The object is required to support the
Fred Drake93656e72001-05-02 20:18:03 +0000366 iterator protocol described below. If a container supports
367 different types of iteration, additional methods can be provided to
368 specifically request iterators for those iteration types. (An
369 example of an object supporting multiple forms of iteration would be
370 a tree structure which supports both breadth-first and depth-first
371 traversal.) This method corresponds to the \member{tp_iter} slot of
372 the type structure for Python objects in the Python/C API.
373\end{methoddesc}
374
375The iterator objects themselves are required to support the following
376two methods, which together form the \dfn{iterator protocol}:
377
378\begin{methoddesc}[iterator]{__iter__}{}
379 Return the iterator object itself. This is required to allow both
380 containers and iterators to be used with the \keyword{for} and
381 \keyword{in} statements. This method corresponds to the
382 \member{tp_iter} slot of the type structure for Python objects in
383 the Python/C API.
384\end{methoddesc}
385
Fred Drakef42cc452001-05-03 04:39:10 +0000386\begin{methoddesc}[iterator]{next}{}
Fred Drake93656e72001-05-02 20:18:03 +0000387 Return the next item from the container. If there are no further
388 items, raise the \exception{StopIteration} exception. This method
389 corresponds to the \member{tp_iternext} slot of the type structure
390 for Python objects in the Python/C API.
391\end{methoddesc}
392
393Python defines several iterator objects to support iteration over
394general and specific sequence types, dictionaries, and other more
395specialized forms. The specific types are not important beyond their
396implementation of the iterator protocol.
397
Guido van Rossum9534e142002-07-16 19:53:39 +0000398The intention of the protocol is that once an iterator's
399\method{next()} method raises \exception{StopIteration}, it will
400continue to do so on subsequent calls. Implementations that
401do not obey this property are deemed broken. (This constraint
402was added in Python 2.3; in Python 2.2, various iterators are
403broken according to this rule.)
404
Raymond Hettinger2dd8c422003-06-25 19:03:22 +0000405Python's generators provide a convenient way to implement the
406iterator protocol. If a container object's \method{__iter__()}
407method is implemented as a generator, it will automatically
408return an iterator object (technically, a generator object)
409supplying the \method{__iter__()} and \method{next()} methods.
410
Fred Drake93656e72001-05-02 20:18:03 +0000411
Raymond Hettinger24d75212005-06-14 08:45:43 +0000412\subsection{Sequence Types ---
413 \class{str}, \class{unicode}, \class{list},
414 \class{tuple}, \class{buffer}, \class{xrange}
415 \label{typesseq}}
Fred Drake64e3b431998-07-24 13:56:11 +0000416
Fred Drake107b9672000-08-14 15:37:59 +0000417There are six sequence types: strings, Unicode strings, lists,
Fred Drake512bb722000-08-18 03:12:38 +0000418tuples, buffers, and xrange objects.
Fred Drake64e3b431998-07-24 13:56:11 +0000419
Steve Holden1e4519f2002-06-14 09:16:40 +0000420String literals are written in single or double quotes:
Fred Drake38e5d272000-04-03 20:13:55 +0000421\code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
Fred Drake4de96c22000-08-12 03:36:23 +0000422\citetitle[../ref/strings.html]{Python Reference Manual} for more about
423string literals. Unicode strings are much like strings, but are
Raymond Hettinger68804312005-01-01 00:28:46 +0000424specified in the syntax using a preceding \character{u} character:
Fred Drake4de96c22000-08-12 03:36:23 +0000425\code{u'abc'}, \code{u"def"}. Lists are constructed with square brackets,
Fred Drake37f15741999-11-10 16:21:37 +0000426separating items with commas: \code{[a, b, c]}. Tuples are
427constructed by the comma operator (not within square brackets), with
428or without enclosing parentheses, but an empty tuple must have the
Raymond Hettingerb67449d2003-09-08 18:52:18 +0000429enclosing parentheses, such as \code{a, b, c} or \code{()}. A single
430item tuple must have a trailing comma, such as \code{(d,)}.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000431\obindex{sequence}
432\obindex{string}
433\obindex{Unicode}
Fred Drake0b4e25d2000-10-04 04:21:19 +0000434\obindex{tuple}
435\obindex{list}
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000436
437Buffer objects are not directly supported by Python syntax, but can be
438created by calling the builtin function
Fred Drake36c2bd82002-09-24 15:32:04 +0000439\function{buffer()}.\bifuncindex{buffer} They don't support
Steve Holden1e4519f2002-06-14 09:16:40 +0000440concatenation or repetition.
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000441\obindex{buffer}
442
443Xrange objects are similar to buffers in that there is no specific
Steve Holden1e4519f2002-06-14 09:16:40 +0000444syntax to create them, but they are created using the \function{xrange()}
445function.\bifuncindex{xrange} They don't support slicing,
446concatenation or repetition, and using \code{in}, \code{not in},
447\function{min()} or \function{max()} on them is inefficient.
Fred Drake0b4e25d2000-10-04 04:21:19 +0000448\obindex{xrange}
Fred Drake64e3b431998-07-24 13:56:11 +0000449
Guido van Rossum5fe2c132001-07-05 15:27:19 +0000450Most sequence types support the following operations. The \samp{in} and
Fred Drake64e3b431998-07-24 13:56:11 +0000451\samp{not in} operations have the same priorities as the comparison
452operations. The \samp{+} and \samp{*} operations have the same
453priority as the corresponding numeric operations.\footnote{They must
454have since the parser can't tell the type of the operands.}
455
456This table lists the sequence operations sorted in ascending priority
457(operations in the same box have the same priority). In the table,
458\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i}
459and \var{j} are integers:
460
461\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
Raymond Hettinger77d110d2004-10-08 01:52:15 +0000462 \lineiii{\var{x} in \var{s}}{\code{True} if an item of \var{s} is equal to \var{x}, else \code{False}}{(1)}
463 \lineiii{\var{x} not in \var{s}}{\code{False} if an item of \var{s} is
464equal to \var{x}, else \code{True}}{(1)}
Fred Drake64e3b431998-07-24 13:56:11 +0000465 \hline
Raymond Hettinger52a21b82004-08-06 18:43:09 +0000466 \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{(6)}
Barry Warsaw817918c2002-08-06 16:58:21 +0000467 \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} shallow copies of \var{s} concatenated}{(2)}
Fred Drake64e3b431998-07-24 13:56:11 +0000468 \hline
Barry Warsaw817918c2002-08-06 16:58:21 +0000469 \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(3)}
470 \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(3), (4)}
Michael W. Hudson9c206152003-03-05 14:42:09 +0000471 \lineiii{\var{s}[\var{i}:\var{j}:\var{k}]}{slice of \var{s} from \var{i} to \var{j} with step \var{k}}{(3), (5)}
Fred Drake64e3b431998-07-24 13:56:11 +0000472 \hline
473 \lineiii{len(\var{s})}{length of \var{s}}{}
474 \lineiii{min(\var{s})}{smallest item of \var{s}}{}
475 \lineiii{max(\var{s})}{largest item of \var{s}}{}
476\end{tableiii}
477\indexiii{operations on}{sequence}{types}
478\bifuncindex{len}
479\bifuncindex{min}
480\bifuncindex{max}
481\indexii{concatenation}{operation}
482\indexii{repetition}{operation}
483\indexii{subscript}{operation}
484\indexii{slice}{operation}
Michael W. Hudson9c206152003-03-05 14:42:09 +0000485\indexii{extended slice}{operation}
Fred Drake64e3b431998-07-24 13:56:11 +0000486\opindex{in}
487\opindex{not in}
488
489\noindent
490Notes:
491
492\begin{description}
Barry Warsaw817918c2002-08-06 16:58:21 +0000493\item[(1)] When \var{s} is a string or Unicode string object the
494\code{in} and \code{not in} operations act like a substring test. In
495Python versions before 2.3, \var{x} had to be a string of length 1.
496In Python 2.3 and beyond, \var{x} may be a string of any length.
497
498\item[(2)] Values of \var{n} less than \code{0} are treated as
Fred Drake38e5d272000-04-03 20:13:55 +0000499 \code{0} (which yields an empty sequence of the same type as
Fred Draked800cff2001-08-28 14:56:05 +0000500 \var{s}). Note also that the copies are shallow; nested structures
501 are not copied. This often haunts new Python programmers; consider:
502
503\begin{verbatim}
504>>> lists = [[]] * 3
505>>> lists
506[[], [], []]
507>>> lists[0].append(3)
508>>> lists
509[[3], [3], [3]]
510\end{verbatim}
511
Armin Rigo80adba62004-11-04 11:29:09 +0000512 What has happened is that \code{[[]]} is a one-element list containing
513 an empty list, so all three elements of \code{[[]] * 3} are (pointers to)
514 this single empty list. Modifying any of the elements of \code{lists}
515 modifies this single list. You can create a list of different lists this
516 way:
Fred Draked800cff2001-08-28 14:56:05 +0000517
518\begin{verbatim}
519>>> lists = [[] for i in range(3)]
520>>> lists[0].append(3)
521>>> lists[1].append(5)
522>>> lists[2].append(7)
523>>> lists
524[[3], [5], [7]]
525\end{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000526
Barry Warsaw817918c2002-08-06 16:58:21 +0000527\item[(3)] If \var{i} or \var{j} is negative, the index is relative to
Fred Drake907e76b2001-07-06 20:30:11 +0000528 the end of the string: \code{len(\var{s}) + \var{i}} or
Fred Drake64e3b431998-07-24 13:56:11 +0000529 \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
530 still \code{0}.
Tim Peters8f01b682002-03-12 03:04:44 +0000531
Barry Warsaw817918c2002-08-06 16:58:21 +0000532\item[(4)] The slice of \var{s} from \var{i} to \var{j} is defined as
Fred Drake64e3b431998-07-24 13:56:11 +0000533 the sequence of items with index \var{k} such that \code{\var{i} <=
534 \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
535 \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
536 use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
537 \var{i} is greater than or equal to \var{j}, the slice is empty.
Michael W. Hudson9c206152003-03-05 14:42:09 +0000538
539\item[(5)] The slice of \var{s} from \var{i} to \var{j} with step
540 \var{k} is defined as the sequence of items with index
Armin Rigo80adba62004-11-04 11:29:09 +0000541 \code{\var{x} = \var{i} + \var{n}*\var{k}} such that
542 $0 \leq n < \frac{j-i}{k}$. In other words, the indices
543 are \code{i}, \code{i+k}, \code{i+2*k}, \code{i+3*k} and so on, stopping when
544 \var{j} is reached (but never including \var{j}). If \var{i} or \var{j}
Michael W. Hudson9c206152003-03-05 14:42:09 +0000545 is greater than \code{len(\var{s})}, use \code{len(\var{s})}. If
Raymond Hettinger81702002003-08-30 23:31:31 +0000546 \var{i} or \var{j} are omitted then they become ``end'' values
547 (which end depends on the sign of \var{k}). Note, \var{k} cannot
548 be zero.
Michael W. Hudson9c206152003-03-05 14:42:09 +0000549
Raymond Hettinger52a21b82004-08-06 18:43:09 +0000550\item[(6)] If \var{s} and \var{t} are both strings, some Python
Andrew M. Kuchling34ed2b02004-08-06 18:55:09 +0000551implementations such as CPython can usually perform an in-place optimization
Raymond Hettinger52a21b82004-08-06 18:43:09 +0000552for assignments of the form \code{\var{s}=\var{s}+\var{t}} or
553\code{\var{s}+=\var{t}}. When applicable, this optimization makes
554quadratic run-time much less likely. This optimization is both version
555and implementation dependent. For performance sensitive code, it is
Raymond Hettinger68804312005-01-01 00:28:46 +0000556preferable to use the \method{str.join()} method which assures consistent
Raymond Hettinger52a21b82004-08-06 18:43:09 +0000557linear concatenation performance across versions and implementations.
Andrew M. Kuchling34ed2b02004-08-06 18:55:09 +0000558\versionchanged[Formerly, string concatenation never occurred in-place]{2.4}
Raymond Hettinger52a21b82004-08-06 18:43:09 +0000559
Fred Drake64e3b431998-07-24 13:56:11 +0000560\end{description}
561
Fred Drake9474d861999-02-12 22:05:33 +0000562
Fred Drake4de96c22000-08-12 03:36:23 +0000563\subsubsection{String Methods \label{string-methods}}
564
565These are the string methods which both 8-bit strings and Unicode
566objects support:
567
568\begin{methoddesc}[string]{capitalize}{}
569Return a copy of the string with only its first character capitalized.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000570
571For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000572\end{methoddesc}
573
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000574\begin{methoddesc}[string]{center}{width\optional{, fillchar}}
Fred Drake4de96c22000-08-12 03:36:23 +0000575Return centered in a string of length \var{width}. Padding is done
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000576using the specified \var{fillchar} (default is a space).
Neal Norwitz72452652003-11-26 14:54:56 +0000577\versionchanged[Support for the \var{fillchar} argument]{2.4}
Fred Drake4de96c22000-08-12 03:36:23 +0000578\end{methoddesc}
579
580\begin{methoddesc}[string]{count}{sub\optional{, start\optional{, end}}}
581Return the number of occurrences of substring \var{sub} in string
582S\code{[\var{start}:\var{end}]}. Optional arguments \var{start} and
583\var{end} are interpreted as in slice notation.
584\end{methoddesc}
585
Fred Drake6048ce92001-12-10 16:43:08 +0000586\begin{methoddesc}[string]{decode}{\optional{encoding\optional{, errors}}}
587Decodes the string using the codec registered for \var{encoding}.
588\var{encoding} defaults to the default string encoding. \var{errors}
589may be given to set a different error handling scheme. The default is
590\code{'strict'}, meaning that encoding errors raise
Walter Dörwaldac1075a2004-07-01 19:58:47 +0000591\exception{UnicodeError}. Other possible values are \code{'ignore'},
592\code{'replace'} and any other name registered via
Walter Dörwaldd4bfe2c2005-11-25 17:17:12 +0000593\function{codecs.register_error}, see section~\ref{codec-base-classes}.
Fred Drake6048ce92001-12-10 16:43:08 +0000594\versionadded{2.2}
Walter Dörwaldac1075a2004-07-01 19:58:47 +0000595\versionchanged[Support for other error handling schemes added]{2.3}
Fred Drake6048ce92001-12-10 16:43:08 +0000596\end{methoddesc}
597
Fred Drake4de96c22000-08-12 03:36:23 +0000598\begin{methoddesc}[string]{encode}{\optional{encoding\optional{,errors}}}
599Return an encoded version of the string. Default encoding is the current
600default string encoding. \var{errors} may be given to set a different
601error handling scheme. The default for \var{errors} is
602\code{'strict'}, meaning that encoding errors raise a
Walter Dörwaldac1075a2004-07-01 19:58:47 +0000603\exception{UnicodeError}. Other possible values are \code{'ignore'},
604\code{'replace'}, \code{'xmlcharrefreplace'}, \code{'backslashreplace'}
Walter Dörwaldd4bfe2c2005-11-25 17:17:12 +0000605and any other name registered via \function{codecs.register_error},
606see section~\ref{codec-base-classes}.
Walter Dörwaldac1075a2004-07-01 19:58:47 +0000607For a list of possible encodings, see section~\ref{standard-encodings}.
Fred Drake1dba66c2000-10-25 21:03:55 +0000608\versionadded{2.0}
Walter Dörwaldac1075a2004-07-01 19:58:47 +0000609\versionchanged[Support for \code{'xmlcharrefreplace'} and
610\code{'backslashreplace'} and other error handling schemes added]{2.3}
Fred Drake4de96c22000-08-12 03:36:23 +0000611\end{methoddesc}
612
613\begin{methoddesc}[string]{endswith}{suffix\optional{, start\optional{, end}}}
Michael W. Hudson9c206152003-03-05 14:42:09 +0000614Return \code{True} if the string ends with the specified \var{suffix},
615otherwise return \code{False}. With optional \var{start}, test beginning at
Fred Drake4de96c22000-08-12 03:36:23 +0000616that position. With optional \var{end}, stop comparing at that position.
617\end{methoddesc}
618
619\begin{methoddesc}[string]{expandtabs}{\optional{tabsize}}
620Return a copy of the string where all tab characters are expanded
621using spaces. If \var{tabsize} is not given, a tab size of \code{8}
622characters is assumed.
623\end{methoddesc}
624
625\begin{methoddesc}[string]{find}{sub\optional{, start\optional{, end}}}
626Return the lowest index in the string where substring \var{sub} is
627found, such that \var{sub} is contained in the range [\var{start},
Georg Brandla3a93ae2006-01-20 09:14:36 +0000628\var{end}]. Optional arguments \var{start} and \var{end} are
Fred Drake4de96c22000-08-12 03:36:23 +0000629interpreted as in slice notation. Return \code{-1} if \var{sub} is
630not found.
631\end{methoddesc}
632
633\begin{methoddesc}[string]{index}{sub\optional{, start\optional{, end}}}
634Like \method{find()}, but raise \exception{ValueError} when the
635substring is not found.
636\end{methoddesc}
637
638\begin{methoddesc}[string]{isalnum}{}
639Return true if all characters in the string are alphanumeric and there
640is at least one character, false otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000641
642For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000643\end{methoddesc}
644
645\begin{methoddesc}[string]{isalpha}{}
646Return true if all characters in the string are alphabetic and there
647is at least one character, false otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000648
649For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000650\end{methoddesc}
651
652\begin{methoddesc}[string]{isdigit}{}
Martin v. Löwis6828e182003-10-18 09:55:08 +0000653Return true if all characters in the string are digits and there
654is at least one character, false otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000655
656For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000657\end{methoddesc}
658
659\begin{methoddesc}[string]{islower}{}
660Return true if all cased characters in the string are lowercase and
661there is at least one cased character, false otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000662
663For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000664\end{methoddesc}
665
666\begin{methoddesc}[string]{isspace}{}
667Return true if there are only whitespace characters in the string and
Martin v. Löwis6828e182003-10-18 09:55:08 +0000668there is at least one character, false otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000669
670For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000671\end{methoddesc}
672
673\begin{methoddesc}[string]{istitle}{}
Martin v. Löwis6828e182003-10-18 09:55:08 +0000674Return true if the string is a titlecased string and there is at least one
Raymond Hettinger0a9b9da2003-10-29 06:54:43 +0000675character, for example uppercase characters may only follow uncased
Martin v. Löwis6828e182003-10-18 09:55:08 +0000676characters and lowercase characters only cased ones. Return false
677otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000678
679For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000680\end{methoddesc}
681
682\begin{methoddesc}[string]{isupper}{}
683Return true if all cased characters in the string are uppercase and
684there is at least one cased character, false otherwise.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000685
686For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000687\end{methoddesc}
688
689\begin{methoddesc}[string]{join}{seq}
690Return a string which is the concatenation of the strings in the
691sequence \var{seq}. The separator between elements is the string
692providing this method.
693\end{methoddesc}
694
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000695\begin{methoddesc}[string]{ljust}{width\optional{, fillchar}}
Fred Drake4de96c22000-08-12 03:36:23 +0000696Return the string left justified in a string of length \var{width}.
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000697Padding is done using the specified \var{fillchar} (default is a
698space). The original string is returned if
Fred Drake4de96c22000-08-12 03:36:23 +0000699\var{width} is less than \code{len(\var{s})}.
Neal Norwitz72452652003-11-26 14:54:56 +0000700\versionchanged[Support for the \var{fillchar} argument]{2.4}
Fred Drake4de96c22000-08-12 03:36:23 +0000701\end{methoddesc}
702
703\begin{methoddesc}[string]{lower}{}
704Return a copy of the string converted to lowercase.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000705
706For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000707\end{methoddesc}
708
Fred Drake8b1c47b2002-04-13 02:43:39 +0000709\begin{methoddesc}[string]{lstrip}{\optional{chars}}
Raymond Hettinger7bebbe72005-05-31 10:26:28 +0000710Return a copy of the string with leading characters removed. The
711\var{chars} argument is a string specifying the set of characters
712to be removed. If omitted or \code{None}, the \var{chars} argument
713defaults to removing whitespace. The \var{chars} argument is not
714a prefix; rather, all combinations of its values are stripped:
715\begin{verbatim}
716 >>> ' spacious '.lstrip()
717 'spacious '
718 >>> 'www.example.com'.lstrip('cmowz.')
719 'example.com'
720\end{verbatim}
Fred Drake91718012002-11-16 00:41:55 +0000721\versionchanged[Support for the \var{chars} argument]{2.2.2}
Fred Drake4de96c22000-08-12 03:36:23 +0000722\end{methoddesc}
723
Fred Draked22bb652003-10-22 02:56:40 +0000724\begin{methoddesc}[string]{replace}{old, new\optional{, count}}
Fred Drake4de96c22000-08-12 03:36:23 +0000725Return a copy of the string with all occurrences of substring
726\var{old} replaced by \var{new}. If the optional argument
Fred Draked22bb652003-10-22 02:56:40 +0000727\var{count} is given, only the first \var{count} occurrences are
Fred Drake4de96c22000-08-12 03:36:23 +0000728replaced.
729\end{methoddesc}
730
731\begin{methoddesc}[string]{rfind}{sub \optional{,start \optional{,end}}}
732Return the highest index in the string where substring \var{sub} is
733found, such that \var{sub} is contained within s[start,end]. Optional
734arguments \var{start} and \var{end} are interpreted as in slice
735notation. Return \code{-1} on failure.
736\end{methoddesc}
737
738\begin{methoddesc}[string]{rindex}{sub\optional{, start\optional{, end}}}
739Like \method{rfind()} but raises \exception{ValueError} when the
740substring \var{sub} is not found.
741\end{methoddesc}
742
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000743\begin{methoddesc}[string]{rjust}{width\optional{, fillchar}}
Fred Drake4de96c22000-08-12 03:36:23 +0000744Return the string right justified in a string of length \var{width}.
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000745Padding is done using the specified \var{fillchar} (default is a space).
746The original string is returned if
Fred Drake4de96c22000-08-12 03:36:23 +0000747\var{width} is less than \code{len(\var{s})}.
Neal Norwitz72452652003-11-26 14:54:56 +0000748\versionchanged[Support for the \var{fillchar} argument]{2.4}
Fred Drake4de96c22000-08-12 03:36:23 +0000749\end{methoddesc}
750
Hye-Shik Changc6f066f2003-12-17 02:49:03 +0000751\begin{methoddesc}[string]{rsplit}{\optional{sep \optional{,maxsplit}}}
752Return a list of the words in the string, using \var{sep} as the
753delimiter string. If \var{maxsplit} is given, at most \var{maxsplit}
Fred Drake401d1e32003-12-30 22:21:18 +0000754splits are done, the \emph{rightmost} ones. If \var{sep} is not specified
Raymond Hettinger770184b2005-01-25 10:21:19 +0000755or \code{None}, any whitespace string is a separator. Except for splitting
756from the right, \method{rsplit()} behaves like \method{split()} which
757is described in detail below.
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000758\versionadded{2.4}
759\end{methoddesc}
760
Fred Drake8b1c47b2002-04-13 02:43:39 +0000761\begin{methoddesc}[string]{rstrip}{\optional{chars}}
Raymond Hettinger7bebbe72005-05-31 10:26:28 +0000762Return a copy of the string with trailing characters removed. The
763\var{chars} argument is a string specifying the set of characters
764to be removed. If omitted or \code{None}, the \var{chars} argument
765defaults to removing whitespace. The \var{chars} argument is not
766a suffix; rather, all combinations of its values are stripped:
767\begin{verbatim}
768 >>> ' spacious '.rstrip()
769 ' spacious'
770 >>> 'mississippi'.rstrip('ipz')
771 'mississ'
772\end{verbatim}
Fred Drake91718012002-11-16 00:41:55 +0000773\versionchanged[Support for the \var{chars} argument]{2.2.2}
Fred Drake4de96c22000-08-12 03:36:23 +0000774\end{methoddesc}
775
776\begin{methoddesc}[string]{split}{\optional{sep \optional{,maxsplit}}}
777Return a list of the words in the string, using \var{sep} as the
778delimiter string. If \var{maxsplit} is given, at most \var{maxsplit}
Raymond Hettinger18c69602004-09-06 00:12:04 +0000779splits are done. (thus, the list will have at most \code{\var{maxsplit}+1}
Raymond Hettingerbc029af2005-01-26 22:40:08 +0000780elements). If \var{maxsplit} is not specified, then there
Raymond Hettinger18c69602004-09-06 00:12:04 +0000781is no limit on the number of splits (all possible splits are made).
782Consecutive delimiters are not grouped together and are
783deemed to delimit empty strings (for example, \samp{'1,,2'.split(',')}
Raymond Hettingerbb30af42004-09-06 00:42:14 +0000784returns \samp{['1', '', '2']}). The \var{sep} argument may consist of
Raymond Hettinger18c69602004-09-06 00:12:04 +0000785multiple characters (for example, \samp{'1, 2, 3'.split(', ')} returns
Raymond Hettingerbb30af42004-09-06 00:42:14 +0000786\samp{['1', '2', '3']}). Splitting an empty string with a specified
Raymond Hettinger87bd3fe2005-04-19 04:29:44 +0000787separator returns \samp{['']}.
Raymond Hettinger18c69602004-09-06 00:12:04 +0000788
789If \var{sep} is not specified or is \code{None}, a different splitting
Raymond Hettinger770184b2005-01-25 10:21:19 +0000790algorithm is applied. First, whitespace characters (spaces, tabs,
791newlines, returns, and formfeeds) are stripped from both ends. Then,
792words are separated by arbitrary length strings of whitespace
793characters. Consecutive whitespace delimiters are treated as a single
794delimiter (\samp{'1 2 3'.split()} returns \samp{['1', '2', '3']}).
795Splitting an empty string or a string consisting of just whitespace
Raymond Hettinger87bd3fe2005-04-19 04:29:44 +0000796returns an empty list.
Fred Drake4de96c22000-08-12 03:36:23 +0000797\end{methoddesc}
798
799\begin{methoddesc}[string]{splitlines}{\optional{keepends}}
800Return a list of the lines in the string, breaking at line
801boundaries. Line breaks are not included in the resulting list unless
802\var{keepends} is given and true.
803\end{methoddesc}
804
Fred Drake8b1c47b2002-04-13 02:43:39 +0000805\begin{methoddesc}[string]{startswith}{prefix\optional{,
806 start\optional{, end}}}
Michael W. Hudson9c206152003-03-05 14:42:09 +0000807Return \code{True} if string starts with the \var{prefix}, otherwise
808return \code{False}. With optional \var{start}, test string beginning at
Fred Drake4de96c22000-08-12 03:36:23 +0000809that position. With optional \var{end}, stop comparing string at that
810position.
811\end{methoddesc}
812
Fred Drake8b1c47b2002-04-13 02:43:39 +0000813\begin{methoddesc}[string]{strip}{\optional{chars}}
Raymond Hettinger7bebbe72005-05-31 10:26:28 +0000814Return a copy of the string with the leading and trailing characters
815removed. The \var{chars} argument is a string specifying the set of
816characters to be removed. If omitted or \code{None}, the \var{chars}
817argument defaults to removing whitespace. The \var{chars} argument is not
818a prefix or suffix; rather, all combinations of its values are stripped:
819\begin{verbatim}
820 >>> ' spacious '.strip()
821 'spacious'
822 >>> 'www.example.com'.strip('cmowz.')
823 'example'
824\end{verbatim}
Fred Drake91718012002-11-16 00:41:55 +0000825\versionchanged[Support for the \var{chars} argument]{2.2.2}
Fred Drake4de96c22000-08-12 03:36:23 +0000826\end{methoddesc}
827
828\begin{methoddesc}[string]{swapcase}{}
829Return a copy of the string with uppercase characters converted to
830lowercase and vice versa.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000831
832For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000833\end{methoddesc}
834
835\begin{methoddesc}[string]{title}{}
Fred Drake907e76b2001-07-06 20:30:11 +0000836Return a titlecased version of the string: words start with uppercase
Fred Drake4de96c22000-08-12 03:36:23 +0000837characters, all remaining cased characters are lowercase.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000838
839For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000840\end{methoddesc}
841
842\begin{methoddesc}[string]{translate}{table\optional{, deletechars}}
843Return a copy of the string where all characters occurring in the
844optional argument \var{deletechars} are removed, and the remaining
845characters have been mapped through the given translation table, which
846must be a string of length 256.
Raymond Hettinger46f681c2003-07-16 05:11:27 +0000847
848For Unicode objects, the \method{translate()} method does not
849accept the optional \var{deletechars} argument. Instead, it
850returns a copy of the \var{s} where all characters have been mapped
851through the given translation table which must be a mapping of
852Unicode ordinals to Unicode ordinals, Unicode strings or \code{None}.
853Unmapped characters are left untouched. Characters mapped to \code{None}
854are deleted. Note, a more flexible approach is to create a custom
855character mapping codec using the \refmodule{codecs} module (see
856\module{encodings.cp1251} for an example).
Fred Drake4de96c22000-08-12 03:36:23 +0000857\end{methoddesc}
858
859\begin{methoddesc}[string]{upper}{}
860Return a copy of the string converted to uppercase.
Martin v. Löwis4a9b8062004-06-03 09:47:01 +0000861
862For 8-bit strings, this method is locale-dependent.
Fred Drake4de96c22000-08-12 03:36:23 +0000863\end{methoddesc}
864
Walter Dörwald068325e2002-04-15 13:36:47 +0000865\begin{methoddesc}[string]{zfill}{width}
866Return the numeric string left filled with zeros in a string
867of length \var{width}. The original string is returned if
868\var{width} is less than \code{len(\var{s})}.
Fred Drakee55bec22002-11-16 00:44:00 +0000869\versionadded{2.2.2}
Walter Dörwald068325e2002-04-15 13:36:47 +0000870\end{methoddesc}
871
Fred Drake4de96c22000-08-12 03:36:23 +0000872
873\subsubsection{String Formatting Operations \label{typesseq-strings}}
Fred Drake64e3b431998-07-24 13:56:11 +0000874
Fred Drakeb38784e2001-12-03 22:15:56 +0000875\index{formatting, string (\%{})}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000876\index{interpolation, string (\%{})}
Fred Drake66d32b12000-09-14 17:57:42 +0000877\index{string!formatting}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000878\index{string!interpolation}
Fred Drake66d32b12000-09-14 17:57:42 +0000879\index{printf-style formatting}
880\index{sprintf-style formatting}
Fred Drakeb38784e2001-12-03 22:15:56 +0000881\index{\protect\%{} formatting}
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000882\index{\protect\%{} interpolation}
Fred Drake66d32b12000-09-14 17:57:42 +0000883
Fred Drake8c071d42001-01-26 20:48:35 +0000884String and Unicode objects have one unique built-in operation: the
Fred Drakeab2dc1d2001-12-26 20:06:40 +0000885\code{\%} operator (modulo). This is also known as the string
886\emph{formatting} or \emph{interpolation} operator. Given
887\code{\var{format} \% \var{values}} (where \var{format} is a string or
888Unicode object), \code{\%} conversion specifications in \var{format}
889are replaced with zero or more elements of \var{values}. The effect
890is similar to the using \cfunction{sprintf()} in the C language. If
891\var{format} is a Unicode object, or if any of the objects being
892converted using the \code{\%s} conversion are Unicode objects, the
Steve Holden1e4519f2002-06-14 09:16:40 +0000893result will also be a Unicode object.
Fred Drake64e3b431998-07-24 13:56:11 +0000894
Fred Drake8c071d42001-01-26 20:48:35 +0000895If \var{format} requires a single argument, \var{values} may be a
Fred Drake401d1e32003-12-30 22:21:18 +0000896single non-tuple object.\footnote{To format only a tuple you
Steve Holden1e4519f2002-06-14 09:16:40 +0000897should therefore provide a singleton tuple whose only element
898is the tuple to be formatted.} Otherwise, \var{values} must be a tuple with
Fred Drake8c071d42001-01-26 20:48:35 +0000899exactly the number of items specified by the format string, or a
900single mapping object (for example, a dictionary).
Fred Drake64e3b431998-07-24 13:56:11 +0000901
Fred Drake8c071d42001-01-26 20:48:35 +0000902A conversion specifier contains two or more characters and has the
903following components, which must occur in this order:
904
905\begin{enumerate}
906 \item The \character{\%} character, which marks the start of the
907 specifier.
Steve Holden1e4519f2002-06-14 09:16:40 +0000908 \item Mapping key (optional), consisting of a parenthesised sequence
909 of characters (for example, \code{(somename)}).
Fred Drake8c071d42001-01-26 20:48:35 +0000910 \item Conversion flags (optional), which affect the result of some
911 conversion types.
912 \item Minimum field width (optional). If specified as an
913 \character{*} (asterisk), the actual width is read from the
914 next element of the tuple in \var{values}, and the object to
915 convert comes after the minimum field width and optional
916 precision.
917 \item Precision (optional), given as a \character{.} (dot) followed
918 by the precision. If specified as \character{*} (an
919 asterisk), the actual width is read from the next element of
920 the tuple in \var{values}, and the value to convert comes after
921 the precision.
922 \item Length modifier (optional).
923 \item Conversion type.
924\end{enumerate}
Fred Drake64e3b431998-07-24 13:56:11 +0000925
Steve Holden1e4519f2002-06-14 09:16:40 +0000926When the right argument is a dictionary (or other mapping type), then
927the formats in the string \emph{must} include a parenthesised mapping key into
Fred Drake8c071d42001-01-26 20:48:35 +0000928that dictionary inserted immediately after the \character{\%}
Steve Holden1e4519f2002-06-14 09:16:40 +0000929character. The mapping key selects the value to be formatted from the
Fred Drake8c071d42001-01-26 20:48:35 +0000930mapping. For example:
Fred Drake64e3b431998-07-24 13:56:11 +0000931
932\begin{verbatim}
Steve Holden1e4519f2002-06-14 09:16:40 +0000933>>> print '%(language)s has %(#)03d quote types.' % \
934 {'language': "Python", "#": 2}
Fred Drake64e3b431998-07-24 13:56:11 +0000935Python has 002 quote types.
936\end{verbatim}
937
938In this case no \code{*} specifiers may occur in a format (since they
939require a sequential parameter list).
940
Fred Drake8c071d42001-01-26 20:48:35 +0000941The conversion flag characters are:
942
943\begin{tableii}{c|l}{character}{Flag}{Meaning}
944 \lineii{\#}{The value conversion will use the ``alternate form''
945 (where defined below).}
Neal Norwitzf927f142003-02-17 18:57:06 +0000946 \lineii{0}{The conversion will be zero padded for numeric values.}
Fred Drake8c071d42001-01-26 20:48:35 +0000947 \lineii{-}{The converted value is left adjusted (overrides
Fred Drakef5968262002-10-25 16:55:51 +0000948 the \character{0} conversion if both are given).}
Fred Drake8c071d42001-01-26 20:48:35 +0000949 \lineii{{~}}{(a space) A blank should be left before a positive number
950 (or empty string) produced by a signed conversion.}
951 \lineii{+}{A sign character (\character{+} or \character{-}) will
952 precede the conversion (overrides a "space" flag).}
953\end{tableii}
954
Georg Brandl0f194232006-01-01 21:35:20 +0000955A length modifier (\code{h}, \code{l}, or \code{L}) may be
956present, but is ignored as it is not necessary for Python.
Fred Drake8c071d42001-01-26 20:48:35 +0000957
958The conversion types are:
959
Fred Drakef5968262002-10-25 16:55:51 +0000960\begin{tableiii}{c|l|c}{character}{Conversion}{Meaning}{Notes}
961 \lineiii{d}{Signed integer decimal.}{}
962 \lineiii{i}{Signed integer decimal.}{}
963 \lineiii{o}{Unsigned octal.}{(1)}
964 \lineiii{u}{Unsigned decimal.}{}
Raymond Hettinger68804312005-01-01 00:28:46 +0000965 \lineiii{x}{Unsigned hexadecimal (lowercase).}{(2)}
966 \lineiii{X}{Unsigned hexadecimal (uppercase).}{(2)}
Fred Drakef5968262002-10-25 16:55:51 +0000967 \lineiii{e}{Floating point exponential format (lowercase).}{}
968 \lineiii{E}{Floating point exponential format (uppercase).}{}
969 \lineiii{f}{Floating point decimal format.}{}
970 \lineiii{F}{Floating point decimal format.}{}
971 \lineiii{g}{Same as \character{e} if exponent is greater than -4 or
972 less than precision, \character{f} otherwise.}{}
973 \lineiii{G}{Same as \character{E} if exponent is greater than -4 or
974 less than precision, \character{F} otherwise.}{}
975 \lineiii{c}{Single character (accepts integer or single character
976 string).}{}
977 \lineiii{r}{String (converts any python object using
978 \function{repr()}).}{(3)}
979 \lineiii{s}{String (converts any python object using
Raymond Hettinger2bd15682003-01-13 04:29:19 +0000980 \function{str()}).}{(4)}
Fred Drakef5968262002-10-25 16:55:51 +0000981 \lineiii{\%}{No argument is converted, results in a \character{\%}
982 character in the result.}{}
983\end{tableiii}
984
985\noindent
986Notes:
987\begin{description}
988 \item[(1)]
989 The alternate form causes a leading zero (\character{0}) to be
990 inserted between left-hand padding and the formatting of the
991 number if the leading character of the result is not already a
992 zero.
993 \item[(2)]
994 The alternate form causes a leading \code{'0x'} or \code{'0X'}
995 (depending on whether the \character{x} or \character{X} format
996 was used) to be inserted between left-hand padding and the
997 formatting of the number if the leading character of the result is
998 not already a zero.
999 \item[(3)]
1000 The \code{\%r} conversion was added in Python 2.0.
Raymond Hettinger2bd15682003-01-13 04:29:19 +00001001 \item[(4)]
1002 If the object or format provided is a \class{unicode} string,
1003 the resulting string will also be \class{unicode}.
Fred Drakef5968262002-10-25 16:55:51 +00001004\end{description}
Fred Drake8c071d42001-01-26 20:48:35 +00001005
1006% XXX Examples?
1007
Fred Drake8c071d42001-01-26 20:48:35 +00001008Since Python strings have an explicit length, \code{\%s} conversions
1009do not assume that \code{'\e0'} is the end of the string.
1010
1011For safety reasons, floating point precisions are clipped to 50;
1012\code{\%f} conversions for numbers whose absolute value is over 1e25
1013are replaced by \code{\%g} conversions.\footnote{
1014 These numbers are fairly arbitrary. They are intended to
1015 avoid printing endless strings of meaningless digits without hampering
1016 correct use and without having to know the exact precision of floating
1017 point values on a particular machine.
1018} All other errors raise exceptions.
1019
Fred Drake14f5c5f2001-12-03 18:33:13 +00001020Additional string operations are defined in standard modules
Fred Drake401d1e32003-12-30 22:21:18 +00001021\refmodule{string}\refstmodindex{string}\ and
Tim Peters8f01b682002-03-12 03:04:44 +00001022\refmodule{re}.\refstmodindex{re}
Fred Drake64e3b431998-07-24 13:56:11 +00001023
Fred Drake107b9672000-08-14 15:37:59 +00001024
Fred Drake512bb722000-08-18 03:12:38 +00001025\subsubsection{XRange Type \label{typesseq-xrange}}
Fred Drake107b9672000-08-14 15:37:59 +00001026
Fred Drake401d1e32003-12-30 22:21:18 +00001027The \class{xrange}\obindex{xrange} type is an immutable sequence which
1028is commonly used for looping. The advantage of the \class{xrange}
1029type is that an \class{xrange} object will always take the same amount
1030of memory, no matter the size of the range it represents. There are
1031no consistent performance advantages.
Fred Drake107b9672000-08-14 15:37:59 +00001032
Raymond Hettingerd2bef822002-12-11 07:14:03 +00001033XRange objects have very little behavior: they only support indexing,
1034iteration, and the \function{len()} function.
Fred Drake107b9672000-08-14 15:37:59 +00001035
1036
Fred Drake9474d861999-02-12 22:05:33 +00001037\subsubsection{Mutable Sequence Types \label{typesseq-mutable}}
Fred Drake64e3b431998-07-24 13:56:11 +00001038
1039List objects support additional operations that allow in-place
1040modification of the object.
Steve Holden1e4519f2002-06-14 09:16:40 +00001041Other mutable sequence types (when added to the language) should
1042also support these operations.
1043Strings and tuples are immutable sequence types: such objects cannot
Fred Drake64e3b431998-07-24 13:56:11 +00001044be modified once created.
1045The following operations are defined on mutable sequence types (where
1046\var{x} is an arbitrary object):
1047\indexiii{mutable}{sequence}{types}
Fred Drake0b4e25d2000-10-04 04:21:19 +00001048\obindex{list}
Fred Drake64e3b431998-07-24 13:56:11 +00001049
1050\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
1051 \lineiii{\var{s}[\var{i}] = \var{x}}
1052 {item \var{i} of \var{s} is replaced by \var{x}}{}
1053 \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
1054 {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
1055 \lineiii{del \var{s}[\var{i}:\var{j}]}
1056 {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001057 \lineiii{\var{s}[\var{i}:\var{j}:\var{k}] = \var{t}}
1058 {the elements of \code{\var{s}[\var{i}:\var{j}:\var{k}]} are replaced by those of \var{t}}{(1)}
1059 \lineiii{del \var{s}[\var{i}:\var{j}:\var{k}]}
1060 {removes the elements of \code{\var{s}[\var{i}:\var{j}:\var{k}]} from the list}{}
Fred Drake64e3b431998-07-24 13:56:11 +00001061 \lineiii{\var{s}.append(\var{x})}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001062 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{(2)}
Barry Warsawafd974c1998-10-09 16:39:58 +00001063 \lineiii{\var{s}.extend(\var{x})}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001064 {same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(3)}
Fred Drake64e3b431998-07-24 13:56:11 +00001065 \lineiii{\var{s}.count(\var{x})}
1066 {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
Walter Dörwald93719b52003-06-17 16:19:56 +00001067 \lineiii{\var{s}.index(\var{x}\optional{, \var{i}\optional{, \var{j}}})}
1068 {return smallest \var{k} such that \code{\var{s}[\var{k}] == \var{x}} and
1069 \code{\var{i} <= \var{k} < \var{j}}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +00001070 \lineiii{\var{s}.insert(\var{i}, \var{x})}
Guido van Rossum3a3cca52003-04-14 20:58:14 +00001071 {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}}{(5)}
Fred Drake64e3b431998-07-24 13:56:11 +00001072 \lineiii{\var{s}.pop(\optional{\var{i}})}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001073 {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(6)}
Fred Drake64e3b431998-07-24 13:56:11 +00001074 \lineiii{\var{s}.remove(\var{x})}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001075 {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(4)}
Fred Drake64e3b431998-07-24 13:56:11 +00001076 \lineiii{\var{s}.reverse()}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001077 {reverses the items of \var{s} in place}{(7)}
Fred Drake401d1e32003-12-30 22:21:18 +00001078 \lineiii{\var{s}.sort(\optional{\var{cmp}\optional{,
1079 \var{key}\optional{, \var{reverse}}}})}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001080 {sort the items of \var{s} in place}{(7), (8), (9), (10)}
Fred Drake64e3b431998-07-24 13:56:11 +00001081\end{tableiii}
1082\indexiv{operations on}{mutable}{sequence}{types}
1083\indexiii{operations on}{sequence}{types}
1084\indexiii{operations on}{list}{type}
1085\indexii{subscript}{assignment}
1086\indexii{slice}{assignment}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001087\indexii{extended slice}{assignment}
Fred Drake64e3b431998-07-24 13:56:11 +00001088\stindex{del}
Fred Drake9474d861999-02-12 22:05:33 +00001089\withsubitem{(list method)}{
Fred Drake68921df1999-08-09 17:05:12 +00001090 \ttindex{append()}\ttindex{extend()}\ttindex{count()}\ttindex{index()}
1091 \ttindex{insert()}\ttindex{pop()}\ttindex{remove()}\ttindex{reverse()}
Fred Drakee8391991998-11-25 17:09:19 +00001092 \ttindex{sort()}}
Fred Drake64e3b431998-07-24 13:56:11 +00001093\noindent
1094Notes:
1095\begin{description}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001096\item[(1)] \var{t} must have the same length as the slice it is
1097 replacing.
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001098
Michael W. Hudson9c206152003-03-05 14:42:09 +00001099\item[(2)] The C implementation of Python has historically accepted
1100 multiple parameters and implicitly joined them into a tuple; this
1101 no longer works in Python 2.0. Use of this misfeature has been
1102 deprecated since Python 1.4.
Fred Drake38e5d272000-04-03 20:13:55 +00001103
Raymond Hettinger4e9907c2005-02-09 23:19:25 +00001104\item[(3)] \var{x} can be any iterable object.
Michael W. Hudson9c206152003-03-05 14:42:09 +00001105
1106\item[(4)] Raises \exception{ValueError} when \var{x} is not found in
Walter Dörwald93719b52003-06-17 16:19:56 +00001107 \var{s}. When a negative index is passed as the second or third parameter
1108 to the \method{index()} method, the list length is added, as for slice
1109 indices. If it is still negative, it is truncated to zero, as for
1110 slice indices. \versionchanged[Previously, \method{index()} didn't
1111 have arguments for specifying start and stop positions]{2.3}
Fred Drake68921df1999-08-09 17:05:12 +00001112
Michael W. Hudson9c206152003-03-05 14:42:09 +00001113\item[(5)] When a negative index is passed as the first parameter to
Guido van Rossum3a3cca52003-04-14 20:58:14 +00001114 the \method{insert()} method, the list length is added, as for slice
1115 indices. If it is still negative, it is truncated to zero, as for
1116 slice indices. \versionchanged[Previously, all negative indices
1117 were truncated to zero]{2.3}
Fred Drakeef428a22001-10-26 18:57:14 +00001118
Michael W. Hudson9c206152003-03-05 14:42:09 +00001119\item[(6)] The \method{pop()} method is only supported by the list and
Fred Drakefbd3b452000-07-31 23:42:23 +00001120 array types. The optional argument \var{i} defaults to \code{-1},
1121 so that by default the last item is removed and returned.
Fred Drake38e5d272000-04-03 20:13:55 +00001122
Michael W. Hudson9c206152003-03-05 14:42:09 +00001123\item[(7)] The \method{sort()} and \method{reverse()} methods modify the
Fred Drake38e5d272000-04-03 20:13:55 +00001124 list in place for economy of space when sorting or reversing a large
Skip Montanaro41d7d582001-07-25 16:18:19 +00001125 list. To remind you that they operate by side effect, they don't return
1126 the sorted or reversed list.
Fred Drake38e5d272000-04-03 20:13:55 +00001127
Raymond Hettinger64958a12003-12-17 20:43:33 +00001128\item[(8)] The \method{sort()} method takes optional arguments for
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001129 controlling the comparisons.
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001130
1131 \var{cmp} specifies a custom comparison function of two arguments
1132 (list items) which should return a negative, zero or positive number
1133 depending on whether the first argument is considered smaller than,
1134 equal to, or larger than the second argument:
1135 \samp{\var{cmp}=\keyword{lambda} \var{x},\var{y}:
1136 \function{cmp}(x.lower(), y.lower())}
1137
1138 \var{key} specifies a function of one argument that is used to
1139 extract a comparison key from each list element:
Raymond Hettinger5d6057f2004-12-02 08:31:41 +00001140 \samp{\var{key}=\function{str.lower}}
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001141
1142 \var{reverse} is a boolean value. If set to \code{True}, then the
1143 list elements are sorted as if each comparison were reversed.
1144
1145 In general, the \var{key} and \var{reverse} conversion processes are
1146 much faster than specifying an equivalent \var{cmp} function. This is
1147 because \var{cmp} is called multiple times for each list element while
Fred Drake5b6150e2003-10-21 17:04:21 +00001148 \var{key} and \var{reverse} touch each element only once.
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001149
Fred Drake4cee2202003-03-20 22:17:59 +00001150 \versionchanged[Support for \code{None} as an equivalent to omitting
Fred Drake401d1e32003-12-30 22:21:18 +00001151 \var{cmp} was added]{2.3}
Fred Drake4cee2202003-03-20 22:17:59 +00001152
Fred Drake5b6150e2003-10-21 17:04:21 +00001153 \versionchanged[Support for \var{key} and \var{reverse} was added]{2.4}
Fred Drake4cee2202003-03-20 22:17:59 +00001154
Fred Drake401d1e32003-12-30 22:21:18 +00001155\item[(9)] Starting with Python 2.3, the \method{sort()} method is
Raymond Hettinger64958a12003-12-17 20:43:33 +00001156 guaranteed to be stable. A sort is stable if it guarantees not to
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001157 change the relative order of elements that compare equal --- this is
1158 helpful for sorting in multiple passes (for example, sort by
1159 department, then by salary grade).
Tim Petersb9099c32002-11-12 22:08:10 +00001160
Michael W. Hudson9c206152003-03-05 14:42:09 +00001161\item[(10)] While a list is being sorted, the effect of attempting to
Fred Drake401d1e32003-12-30 22:21:18 +00001162 mutate, or even inspect, the list is undefined. The C
1163 implementation of Python 2.3 and newer makes the list appear empty
1164 for the duration, and raises \exception{ValueError} if it can detect
1165 that the list has been mutated during a sort.
Fred Drake64e3b431998-07-24 13:56:11 +00001166\end{description}
1167
Raymond Hettinger24d75212005-06-14 08:45:43 +00001168\subsection{Set Types ---
1169 \class{set}, \class{frozenset}
1170 \label{types-set}}
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001171\obindex{set}
1172
1173A \dfn{set} object is an unordered collection of immutable values.
1174Common uses include membership testing, removing duplicates from a sequence,
1175and computing mathematical operations such as intersection, union, difference,
1176and symmetric difference.
1177\versionadded{2.4}
1178
1179Like other collections, sets support \code{\var{x} in \var{set}},
1180\code{len(\var{set})}, and \code{for \var{x} in \var{set}}. Being an
1181unordered collection, sets do not record element position or order of
1182insertion. Accordingly, sets do not support indexing, slicing, or
1183other sequence-like behavior.
1184
1185There are currently two builtin set types, \class{set} and \class{frozenset}.
1186The \class{set} type is mutable --- the contents can be changed using methods
1187like \method{add()} and \method{remove()}. Since it is mutable, it has no
1188hash value and cannot be used as either a dictionary key or as an element of
1189another set. The \class{frozenset} type is immutable and hashable --- its
1190contents cannot be altered after is created; however, it can be used as
1191a dictionary key or as an element of another set.
1192
1193Instances of \class{set} and \class{frozenset} provide the following operations:
1194
1195\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
1196 \lineiii{len(\var{s})}{}{cardinality of set \var{s}}
1197
1198 \hline
1199 \lineiii{\var{x} in \var{s}}{}
1200 {test \var{x} for membership in \var{s}}
1201 \lineiii{\var{x} not in \var{s}}{}
1202 {test \var{x} for non-membership in \var{s}}
1203 \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}}
1204 {test whether every element in \var{s} is in \var{t}}
1205 \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}}
1206 {test whether every element in \var{t} is in \var{s}}
1207
1208 \hline
1209 \lineiii{\var{s}.union(\var{t})}{\var{s} | \var{t}}
1210 {new set with elements from both \var{s} and \var{t}}
1211 \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}}
1212 {new set with elements common to \var{s} and \var{t}}
1213 \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}}
1214 {new set with elements in \var{s} but not in \var{t}}
1215 \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}}
1216 {new set with elements in either \var{s} or \var{t} but not both}
1217 \lineiii{\var{s}.copy()}{}
1218 {new set with a shallow copy of \var{s}}
1219\end{tableiii}
1220
1221Note, the non-operator versions of \method{union()}, \method{intersection()},
1222\method{difference()}, and \method{symmetric_difference()},
1223\method{issubset()}, and \method{issuperset()} methods will accept any
1224iterable as an argument. In contrast, their operator based counterparts
1225require their arguments to be sets. This precludes error-prone constructions
1226like \code{set('abc') \&\ 'cbs'} in favor of the more readable
1227\code{set('abc').intersection('cbs')}.
1228
1229Both \class{set} and \class{frozenset} support set to set comparisons.
1230Two sets are equal if and only if every element of each set is contained in
1231the other (each is a subset of the other).
1232A set is less than another set if and only if the first set is a proper
1233subset of the second set (is a subset, but is not equal).
1234A set is greater than another set if and only if the first set is a proper
1235superset of the second set (is a superset, but is not equal).
1236
Raymond Hettinger68804312005-01-01 00:28:46 +00001237Instances of \class{set} are compared to instances of \class{frozenset} based
Raymond Hettingercab5b942004-07-22 19:33:53 +00001238on their members. For example, \samp{set('abc') == frozenset('abc')} returns
1239\code{True}.
1240
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001241The subset and equality comparisons do not generalize to a complete
1242ordering function. For example, any two disjoint sets are not equal and
1243are not subsets of each other, so \emph{all} of the following return
1244\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or
1245\code{\var{a}>\var{b}}.
1246Accordingly, sets do not implement the \method{__cmp__} method.
1247
1248Since sets only define partial ordering (subset relationships), the output
1249of the \method{list.sort()} method is undefined for lists of sets.
1250
Raymond Hettingere4905022005-04-10 17:32:35 +00001251Set elements are like dictionary keys; they need to define both
1252\method{__hash__} and \method{__eq__} methods.
1253
Raymond Hettingercab5b942004-07-22 19:33:53 +00001254Binary operations that mix \class{set} instances with \class{frozenset}
1255return the type of the first operand. For example:
1256\samp{frozenset('ab') | set('bc')} returns an instance of \class{frozenset}.
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001257
1258The following table lists operations available for \class{set}
1259that do not apply to immutable instances of \class{frozenset}:
1260
1261\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
1262 \lineiii{\var{s}.update(\var{t})}
1263 {\var{s} |= \var{t}}
Georg Brandl75400db2005-12-26 23:55:56 +00001264 {update set \var{s}, adding elements from \var{t}}
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001265 \lineiii{\var{s}.intersection_update(\var{t})}
1266 {\var{s} \&= \var{t}}
Georg Brandl75400db2005-12-26 23:55:56 +00001267 {update set \var{s}, keeping only elements found in both \var{s} and \var{t}}
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001268 \lineiii{\var{s}.difference_update(\var{t})}
1269 {\var{s} -= \var{t}}
Georg Brandl75400db2005-12-26 23:55:56 +00001270 {update set \var{s}, removing elements found in \var{t}}
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001271 \lineiii{\var{s}.symmetric_difference_update(\var{t})}
1272 {\var{s} \textasciicircum= \var{t}}
Georg Brandl75400db2005-12-26 23:55:56 +00001273 {update set \var{s}, keeping only elements found in either \var{s} or \var{t}
1274 but not in both}
Raymond Hettingerf5f41bf2003-11-24 02:57:33 +00001275
1276 \hline
1277 \lineiii{\var{s}.add(\var{x})}{}
1278 {add element \var{x} to set \var{s}}
1279 \lineiii{\var{s}.remove(\var{x})}{}
1280 {remove \var{x} from set \var{s}; raises KeyError if not present}
1281 \lineiii{\var{s}.discard(\var{x})}{}
1282 {removes \var{x} from set \var{s} if present}
1283 \lineiii{\var{s}.pop()}{}
1284 {remove and return an arbitrary element from \var{s}; raises
1285 \exception{KeyError} if empty}
1286 \lineiii{\var{s}.clear()}{}
1287 {remove all elements from set \var{s}}
1288\end{tableiii}
1289
1290Note, the non-operator versions of the \method{update()},
1291\method{intersection_update()}, \method{difference_update()}, and
1292\method{symmetric_difference_update()} methods will accept any iterable
1293as an argument.
1294
Raymond Hettinger452b6832005-07-01 23:18:36 +00001295The design of the set types was based on lessons learned from the
1296\module{sets} module.
1297
1298\begin{seealso}
Fred Drake4094d042005-10-03 14:25:40 +00001299 \seelink{comparison-to-builtin-set.html}
1300 {Comparison to the built-in set types}
1301 {Differences between the \module{sets} module and the
1302 built-in set types.}
Raymond Hettinger452b6832005-07-01 23:18:36 +00001303\end{seealso}
1304
Fred Drake64e3b431998-07-24 13:56:11 +00001305
Raymond Hettinger1a663912005-08-18 21:27:11 +00001306\subsection{Mapping Types --- \class{dict} \label{typesmapping}}
Fred Drake0b4e25d2000-10-04 04:21:19 +00001307\obindex{mapping}
1308\obindex{dictionary}
Fred Drake64e3b431998-07-24 13:56:11 +00001309
Steve Holden1e4519f2002-06-14 09:16:40 +00001310A \dfn{mapping} object maps immutable values to
Fred Drake64e3b431998-07-24 13:56:11 +00001311arbitrary objects. Mappings are mutable objects. There is currently
1312only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
Steve Holden1e4519f2002-06-14 09:16:40 +00001313almost arbitrary values. Only values containing lists, dictionaries
1314or other mutable types (that are compared by value rather than by
1315object identity) may not be used as keys.
Fred Drake64e3b431998-07-24 13:56:11 +00001316Numeric types used for keys obey the normal rules for numeric
Raymond Hettinger74c8e552003-09-12 00:02:37 +00001317comparison: if two numbers compare equal (such as \code{1} and
Fred Drake64e3b431998-07-24 13:56:11 +00001318\code{1.0}) then they can be used interchangeably to index the same
1319dictionary entry.
1320
Fred Drake64e3b431998-07-24 13:56:11 +00001321Dictionaries are created by placing a comma-separated list of
1322\code{\var{key}: \var{value}} pairs within braces, for example:
1323\code{\{'jack': 4098, 'sjoerd': 4127\}} or
1324\code{\{4098: 'jack', 4127: 'sjoerd'\}}.
1325
Fred Drake9c5cc141999-06-10 22:37:34 +00001326The following operations are defined on mappings (where \var{a} and
1327\var{b} are mappings, \var{k} is a key, and \var{v} and \var{x} are
1328arbitrary objects):
Fred Drake64e3b431998-07-24 13:56:11 +00001329\indexiii{operations on}{mapping}{types}
1330\indexiii{operations on}{dictionary}{type}
1331\stindex{del}
1332\bifuncindex{len}
Fred Drake9474d861999-02-12 22:05:33 +00001333\withsubitem{(dictionary method)}{
1334 \ttindex{clear()}
1335 \ttindex{copy()}
1336 \ttindex{has_key()}
Raymond Hettinger74c8e552003-09-12 00:02:37 +00001337 \ttindex{fromkeys()}
Fred Drake9474d861999-02-12 22:05:33 +00001338 \ttindex{items()}
1339 \ttindex{keys()}
1340 \ttindex{update()}
1341 \ttindex{values()}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001342 \ttindex{get()}
1343 \ttindex{setdefault()}
1344 \ttindex{pop()}
1345 \ttindex{popitem()}
1346 \ttindex{iteritems()}
Raymond Hettinger0dfd7a92003-05-10 07:40:56 +00001347 \ttindex{iterkeys()}
Michael W. Hudson9c206152003-03-05 14:42:09 +00001348 \ttindex{itervalues()}}
Fred Drake9c5cc141999-06-10 22:37:34 +00001349
1350\begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes}
1351 \lineiii{len(\var{a})}{the number of items in \var{a}}{}
1352 \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
Fred Drake1e75e172000-07-31 16:34:46 +00001353 \lineiii{\var{a}[\var{k}] = \var{v}}
1354 {set \code{\var{a}[\var{k}]} to \var{v}}
Fred Drake9c5cc141999-06-10 22:37:34 +00001355 {}
1356 \lineiii{del \var{a}[\var{k}]}
1357 {remove \code{\var{a}[\var{k}]} from \var{a}}
1358 {(1)}
1359 \lineiii{\var{a}.clear()}{remove all items from \code{a}}{}
1360 \lineiii{\var{a}.copy()}{a (shallow) copy of \code{a}}{}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +00001361 \lineiii{\var{a}.has_key(\var{k})}
Raymond Hettinger6e13bcc2003-08-08 11:07:59 +00001362 {\code{True} if \var{a} has a key \var{k}, else \code{False}}
Fred Drake9c5cc141999-06-10 22:37:34 +00001363 {}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +00001364 \lineiii{\var{k} \code{in} \var{a}}
1365 {Equivalent to \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001366 {(2)}
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001367 \lineiii{\var{k} not in \var{a}}
Guido van Rossum8b3d6ca2001-04-23 13:22:59 +00001368 {Equivalent to \code{not} \var{a}.has_key(\var{k})}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001369 {(2)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001370 \lineiii{\var{a}.items()}
1371 {a copy of \var{a}'s list of (\var{key}, \var{value}) pairs}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001372 {(3)}
Fred Drake4a6c5c52001-06-12 03:31:56 +00001373 \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(3)}
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001374 \lineiii{\var{a}.update(\optional{\var{b}})}
1375 {updates (and overwrites) key/value pairs from \var{b}}
1376 {(9)}
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001377 \lineiii{\var{a}.fromkeys(\var{seq}\optional{, \var{value}})}
1378 {Creates a new dictionary with keys from \var{seq} and values set to \var{value}}
1379 {(7)}
Fred Drake4a6c5c52001-06-12 03:31:56 +00001380 \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(3)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001381 \lineiii{\var{a}.get(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +00001382 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Fred Drake9c5cc141999-06-10 22:37:34 +00001383 else \var{x}}
Barry Warsawe9218a12001-06-26 20:32:59 +00001384 {(4)}
Guido van Rossum8141cf52000-08-08 16:15:49 +00001385 \lineiii{\var{a}.setdefault(\var{k}\optional{, \var{x}})}
Fred Drake4cacec52001-04-21 05:56:06 +00001386 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
Guido van Rossum8141cf52000-08-08 16:15:49 +00001387 else \var{x} (also setting it)}
Barry Warsawe9218a12001-06-26 20:32:59 +00001388 {(5)}
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001389 \lineiii{\var{a}.pop(\var{k}\optional{, \var{x}})}
1390 {\code{\var{a}[\var{k}]} if \code{\var{k} in \var{a}},
1391 else \var{x} (and remove k)}
1392 {(8)}
Guido van Rossumff63f202000-12-12 22:03:47 +00001393 \lineiii{\var{a}.popitem()}
1394 {remove and return an arbitrary (\var{key}, \var{value}) pair}
Barry Warsawe9218a12001-06-26 20:32:59 +00001395 {(6)}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001396 \lineiii{\var{a}.iteritems()}
1397 {return an iterator over (\var{key}, \var{value}) pairs}
Fred Drake01777832002-08-19 21:58:58 +00001398 {(2), (3)}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001399 \lineiii{\var{a}.iterkeys()}
1400 {return an iterator over the mapping's keys}
Fred Drake01777832002-08-19 21:58:58 +00001401 {(2), (3)}
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001402 \lineiii{\var{a}.itervalues()}
1403 {return an iterator over the mapping's values}
Fred Drake01777832002-08-19 21:58:58 +00001404 {(2), (3)}
Fred Drake9c5cc141999-06-10 22:37:34 +00001405\end{tableiii}
1406
Fred Drake64e3b431998-07-24 13:56:11 +00001407\noindent
1408Notes:
1409\begin{description}
Fred Drake9c5cc141999-06-10 22:37:34 +00001410\item[(1)] Raises a \exception{KeyError} exception if \var{k} is not
1411in the map.
Fred Drake64e3b431998-07-24 13:56:11 +00001412
Fred Drakec6d8f8d2001-05-25 04:24:37 +00001413\item[(2)] \versionadded{2.2}
1414
Raymond Hettinger23ce5842004-11-25 05:16:19 +00001415\item[(3)] Keys and values are listed in an arbitrary order which is
1416non-random, varies across Python implementations, and depends on the
1417dictionary's history of insertions and deletions.
1418If \method{items()}, \method{keys()}, \method{values()},
Fred Drake01777832002-08-19 21:58:58 +00001419\method{iteritems()}, \method{iterkeys()}, and \method{itervalues()}
1420are called with no intervening modifications to the dictionary, the
1421lists will directly correspond. This allows the creation of
1422\code{(\var{value}, \var{key})} pairs using \function{zip()}:
1423\samp{pairs = zip(\var{a}.values(), \var{a}.keys())}. The same
1424relationship holds for the \method{iterkeys()} and
1425\method{itervalues()} methods: \samp{pairs = zip(\var{a}.itervalues(),
1426\var{a}.iterkeys())} provides the same value for \code{pairs}.
1427Another way to create the same list is \samp{pairs = [(v, k) for (k,
1428v) in \var{a}.iteritems()]}.
Fred Drake64e3b431998-07-24 13:56:11 +00001429
Barry Warsawe9218a12001-06-26 20:32:59 +00001430\item[(4)] Never raises an exception if \var{k} is not in the map,
Fred Drake38e5d272000-04-03 20:13:55 +00001431instead it returns \var{x}. \var{x} is optional; when \var{x} is not
Fred Drake9c5cc141999-06-10 22:37:34 +00001432provided and \var{k} is not in the map, \code{None} is returned.
Guido van Rossum8141cf52000-08-08 16:15:49 +00001433
Barry Warsawe9218a12001-06-26 20:32:59 +00001434\item[(5)] \function{setdefault()} is like \function{get()}, except
Guido van Rossum8141cf52000-08-08 16:15:49 +00001435that if \var{k} is missing, \var{x} is both returned and inserted into
Michael W. Hudson049e7aa2004-08-07 16:41:34 +00001436the dictionary as the value of \var{k}. \var{x} defaults to \var{None}.
Guido van Rossumff63f202000-12-12 22:03:47 +00001437
Barry Warsawe9218a12001-06-26 20:32:59 +00001438\item[(6)] \function{popitem()} is useful to destructively iterate
Raymond Hettinger631bfe62005-05-27 10:43:55 +00001439over a dictionary, as often used in set algorithms. If the dictionary
1440is empty, calling \function{popitem()} raises a \exception{KeyError}.
Fred Drake64e3b431998-07-24 13:56:11 +00001441
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001442\item[(7)] \function{fromkeys()} is a class method that returns a
1443new dictionary. \var{value} defaults to \code{None}. \versionadded{2.3}
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001444
1445\item[(8)] \function{pop()} raises a \exception{KeyError} when no default
1446value is given and the key is not found. \versionadded{2.3}
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001447
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001448\item[(9)] \function{update()} accepts either another mapping object
1449or an iterable of key/value pairs (as a tuple or other iterable of
1450length two). If keyword arguments are specified, the mapping is
1451then is updated with those key/value pairs:
1452\samp{d.update(red=1, blue=2)}.
1453\versionchanged[Allowed the argument to be an iterable of key/value
1454 pairs and allowed keyword arguments]{2.4}
Fred Drake64e3b431998-07-24 13:56:11 +00001455
Hye-Shik Chang9168c702004-03-09 05:53:15 +00001456\end{description}
1457
Fred Drake99de2182001-10-30 06:23:14 +00001458\subsection{File Objects
1459 \label{bltin-file-objects}}
Fred Drake64e3b431998-07-24 13:56:11 +00001460
Fred Drake99de2182001-10-30 06:23:14 +00001461File objects\obindex{file} are implemented using C's \code{stdio}
1462package and can be created with the built-in constructor
Tim Peters8f01b682002-03-12 03:04:44 +00001463\function{file()}\bifuncindex{file} described in section
Tim Peters003047a2001-10-30 05:54:04 +00001464\ref{built-in-funcs}, ``Built-in Functions.''\footnote{\function{file()}
1465is new in Python 2.2. The older built-in \function{open()} is an
Fred Drake401d1e32003-12-30 22:21:18 +00001466alias for \function{file()}.} File objects are also returned
Fred Drake907e76b2001-07-06 20:30:11 +00001467by some other built-in functions and methods, such as
Fred Drake4de96c22000-08-12 03:36:23 +00001468\function{os.popen()} and \function{os.fdopen()} and the
Fred Drake130072d1998-10-28 20:08:35 +00001469\method{makefile()} method of socket objects.
Fred Drake4de96c22000-08-12 03:36:23 +00001470\refstmodindex{os}
Fred Drake64e3b431998-07-24 13:56:11 +00001471\refbimodindex{socket}
1472
1473When a file operation fails for an I/O-related reason, the exception
Fred Drake84538cd1998-11-30 21:51:25 +00001474\exception{IOError} is raised. This includes situations where the
1475operation is not defined for some reason, like \method{seek()} on a tty
Fred Drake64e3b431998-07-24 13:56:11 +00001476device or writing a file opened for reading.
1477
1478Files have the following methods:
1479
1480
1481\begin{methoddesc}[file]{close}{}
Steve Holden1e4519f2002-06-14 09:16:40 +00001482 Close the file. A closed file cannot be read or written any more.
Fred Drakea776cea2000-11-06 20:17:37 +00001483 Any operation which requires that the file be open will raise a
1484 \exception{ValueError} after the file has been closed. Calling
Fred Drake752ba392000-09-19 15:18:51 +00001485 \method{close()} more than once is allowed.
Fred Drake64e3b431998-07-24 13:56:11 +00001486\end{methoddesc}
1487
1488\begin{methoddesc}[file]{flush}{}
Fred Drake752ba392000-09-19 15:18:51 +00001489 Flush the internal buffer, like \code{stdio}'s
1490 \cfunction{fflush()}. This may be a no-op on some file-like
1491 objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001492\end{methoddesc}
1493
Fred Drake64e3b431998-07-24 13:56:11 +00001494\begin{methoddesc}[file]{fileno}{}
Fred Drake752ba392000-09-19 15:18:51 +00001495 \index{file descriptor}
1496 \index{descriptor, file}
1497 Return the integer ``file descriptor'' that is used by the
1498 underlying implementation to request I/O operations from the
1499 operating system. This can be useful for other, lower level
Fred Drake907e76b2001-07-06 20:30:11 +00001500 interfaces that use file descriptors, such as the
1501 \refmodule{fcntl}\refbimodindex{fcntl} module or
Fred Drake0aa811c2001-10-20 04:24:09 +00001502 \function{os.read()} and friends. \note{File-like objects
Fred Drake907e76b2001-07-06 20:30:11 +00001503 which do not have a real file descriptor should \emph{not} provide
Fred Drake0aa811c2001-10-20 04:24:09 +00001504 this method!}
Fred Drake64e3b431998-07-24 13:56:11 +00001505\end{methoddesc}
1506
Guido van Rossum0fc01862002-08-06 17:01:28 +00001507\begin{methoddesc}[file]{isatty}{}
1508 Return \code{True} if the file is connected to a tty(-like) device, else
1509 \code{False}. \note{If a file-like object is not associated
1510 with a real file, this method should \emph{not} be implemented.}
1511\end{methoddesc}
1512
1513\begin{methoddesc}[file]{next}{}
Raymond Hettinger74c8e552003-09-12 00:02:37 +00001514A file object is its own iterator, for example \code{iter(\var{f})} returns
Guido van Rossum0fc01862002-08-06 17:01:28 +00001515\var{f} (unless \var{f} is closed). When a file is used as an
1516iterator, typically in a \keyword{for} loop (for example,
1517\code{for line in f: print line}), the \method{next()} method is
1518called repeatedly. This method returns the next input line, or raises
1519\exception{StopIteration} when \EOF{} is hit. In order to make a
1520\keyword{for} loop the most efficient way of looping over the lines of
1521a file (a very common operation), the \method{next()} method uses a
1522hidden read-ahead buffer. As a consequence of using a read-ahead
1523buffer, combining \method{next()} with other file methods (like
1524\method{readline()}) does not work right. However, using
1525\method{seek()} to reposition the file to an absolute position will
1526flush the read-ahead buffer.
1527\versionadded{2.3}
1528\end{methoddesc}
1529
Fred Drake64e3b431998-07-24 13:56:11 +00001530\begin{methoddesc}[file]{read}{\optional{size}}
1531 Read at most \var{size} bytes from the file (less if the read hits
Fred Drakef4cbada1999-04-14 14:31:53 +00001532 \EOF{} before obtaining \var{size} bytes). If the \var{size}
1533 argument is negative or omitted, read all data until \EOF{} is
1534 reached. The bytes are returned as a string object. An empty
1535 string is returned when \EOF{} is encountered immediately. (For
1536 certain files, like ttys, it makes sense to continue reading after
1537 an \EOF{} is hit.) Note that this method may call the underlying
1538 C function \cfunction{fread()} more than once in an effort to
Gustavo Niemeyer786ddb22002-12-16 18:12:53 +00001539 acquire as close to \var{size} bytes as possible. Also note that
1540 when in non-blocking mode, less data than what was requested may
1541 be returned, even if no \var{size} parameter was given.
Fred Drake64e3b431998-07-24 13:56:11 +00001542\end{methoddesc}
1543
1544\begin{methoddesc}[file]{readline}{\optional{size}}
1545 Read one entire line from the file. A trailing newline character is
Fred Drake401d1e32003-12-30 22:21:18 +00001546 kept in the string (but may be absent when a file ends with an
1547 incomplete line).\footnote{
Steve Holden1e4519f2002-06-14 09:16:40 +00001548 The advantage of leaving the newline on is that
1549 returning an empty string is then an unambiguous \EOF{}
1550 indication. It is also possible (in cases where it might
1551 matter, for example, if you
Tim Peters8f01b682002-03-12 03:04:44 +00001552 want to make an exact copy of a file while scanning its lines)
Steve Holden1e4519f2002-06-14 09:16:40 +00001553 to tell whether the last line of a file ended in a newline
Fred Drake4de96c22000-08-12 03:36:23 +00001554 or not (yes this happens!).
Fred Drake401d1e32003-12-30 22:21:18 +00001555 } If the \var{size} argument is present and
Fred Drake64e3b431998-07-24 13:56:11 +00001556 non-negative, it is a maximum byte count (including the trailing
1557 newline) and an incomplete line may be returned.
Steve Holden1e4519f2002-06-14 09:16:40 +00001558 An empty string is returned \emph{only} when \EOF{} is encountered
Fred Drake0aa811c2001-10-20 04:24:09 +00001559 immediately. \note{Unlike \code{stdio}'s \cfunction{fgets()}, the
Fred Drake752ba392000-09-19 15:18:51 +00001560 returned string contains null characters (\code{'\e 0'}) if they
Fred Drake0aa811c2001-10-20 04:24:09 +00001561 occurred in the input.}
Fred Drake64e3b431998-07-24 13:56:11 +00001562\end{methoddesc}
1563
1564\begin{methoddesc}[file]{readlines}{\optional{sizehint}}
1565 Read until \EOF{} using \method{readline()} and return a list containing
1566 the lines thus read. If the optional \var{sizehint} argument is
Fred Drakec37b65e2001-11-28 07:26:15 +00001567 present, instead of reading up to \EOF, whole lines totalling
Fred Drake64e3b431998-07-24 13:56:11 +00001568 approximately \var{sizehint} bytes (possibly after rounding up to an
Fred Drake752ba392000-09-19 15:18:51 +00001569 internal buffer size) are read. Objects implementing a file-like
1570 interface may choose to ignore \var{sizehint} if it cannot be
1571 implemented, or cannot be implemented efficiently.
Fred Drake64e3b431998-07-24 13:56:11 +00001572\end{methoddesc}
1573
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001574\begin{methoddesc}[file]{xreadlines}{}
Guido van Rossum0fc01862002-08-06 17:01:28 +00001575 This method returns the same thing as \code{iter(f)}.
Fred Drake82f93c62001-04-22 01:56:51 +00001576 \versionadded{2.1}
Fred Drake401d1e32003-12-30 22:21:18 +00001577 \deprecated{2.3}{Use \samp{for \var{line} in \var{file}} instead.}
Guido van Rossum20ab9e92001-01-17 01:18:00 +00001578\end{methoddesc}
1579
Fred Drake64e3b431998-07-24 13:56:11 +00001580\begin{methoddesc}[file]{seek}{offset\optional{, whence}}
1581 Set the file's current position, like \code{stdio}'s \cfunction{fseek()}.
1582 The \var{whence} argument is optional and defaults to \code{0}
1583 (absolute file positioning); other values are \code{1} (seek
1584 relative to the current position) and \code{2} (seek relative to the
Fred Drake19ae7832001-01-04 05:16:39 +00001585 file's end). There is no return value. Note that if the file is
1586 opened for appending (mode \code{'a'} or \code{'a+'}), any
1587 \method{seek()} operations will be undone at the next write. If the
1588 file is only opened for writing in append mode (mode \code{'a'}),
1589 this method is essentially a no-op, but it remains useful for files
Martin v. Löwis849a9722003-10-18 09:38:01 +00001590 opened in append mode with reading enabled (mode \code{'a+'}). If the
Georg Brandl6ee33912005-12-15 21:34:29 +00001591 file is opened in text mode (without \code{'b'}), only offsets returned
Martin v. Löwis849a9722003-10-18 09:38:01 +00001592 by \method{tell()} are legal. Use of other offsets causes undefined
1593 behavior.
1594
1595 Note that not all file objects are seekable.
Fred Drake64e3b431998-07-24 13:56:11 +00001596\end{methoddesc}
1597
1598\begin{methoddesc}[file]{tell}{}
1599 Return the file's current position, like \code{stdio}'s
1600 \cfunction{ftell()}.
Georg Brandla3a93ae2006-01-20 09:14:36 +00001601
1602 \note{On Windows, \method{tell()} can return illegal values (after an
1603 \cfunction{fgets()}) when reading files with \UNIX{}-style line-endings.
1604 Use binary mode (\code{'rb'}) to circumvent this problem.}
Fred Drake64e3b431998-07-24 13:56:11 +00001605\end{methoddesc}
1606
1607\begin{methoddesc}[file]{truncate}{\optional{size}}
Tim Peters8f01b682002-03-12 03:04:44 +00001608 Truncate the file's size. If the optional \var{size} argument is
Fred Drake752ba392000-09-19 15:18:51 +00001609 present, the file is truncated to (at most) that size. The size
Tim Peters8f01b682002-03-12 03:04:44 +00001610 defaults to the current position. The current file position is
1611 not changed. Note that if a specified size exceeds the file's
1612 current size, the result is platform-dependent: possibilities
Georg Brandl0f194232006-01-01 21:35:20 +00001613 include that the file may remain unchanged, increase to the specified
Tim Peters8f01b682002-03-12 03:04:44 +00001614 size as if zero-filled, or increase to the specified size with
1615 undefined new content.
Raymond Hettingerb67449d2003-09-08 18:52:18 +00001616 Availability: Windows, many \UNIX{} variants.
Fred Drake64e3b431998-07-24 13:56:11 +00001617\end{methoddesc}
1618
1619\begin{methoddesc}[file]{write}{str}
Fred Drake0aa811c2001-10-20 04:24:09 +00001620 Write a string to the file. There is no return value. Due to
Fred Drake3c48ef72001-01-09 22:47:46 +00001621 buffering, the string may not actually show up in the file until
1622 the \method{flush()} or \method{close()} method is called.
Fred Drake64e3b431998-07-24 13:56:11 +00001623\end{methoddesc}
1624
Tim Peters2c9aa5e2001-09-23 04:06:05 +00001625\begin{methoddesc}[file]{writelines}{sequence}
1626 Write a sequence of strings to the file. The sequence can be any
1627 iterable object producing strings, typically a list of strings.
1628 There is no return value.
Fred Drake3c48ef72001-01-09 22:47:46 +00001629 (The name is intended to match \method{readlines()};
1630 \method{writelines()} does not add line separators.)
1631\end{methoddesc}
1632
Fred Drake64e3b431998-07-24 13:56:11 +00001633
Fred Drake038d2642001-09-22 04:34:48 +00001634Files support the iterator protocol. Each iteration returns the same
1635result as \code{\var{file}.readline()}, and iteration ends when the
1636\method{readline()} method returns an empty string.
1637
1638
Fred Drake752ba392000-09-19 15:18:51 +00001639File objects also offer a number of other interesting attributes.
1640These are not required for file-like objects, but should be
1641implemented if they make sense for the particular object.
Fred Drake64e3b431998-07-24 13:56:11 +00001642
1643\begin{memberdesc}[file]{closed}
Neal Norwitz6b353702002-04-09 18:15:00 +00001644bool indicating the current state of the file object. This is a
Fred Drake64e3b431998-07-24 13:56:11 +00001645read-only attribute; the \method{close()} method changes the value.
Fred Drake752ba392000-09-19 15:18:51 +00001646It may not be available on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001647\end{memberdesc}
1648
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001649\begin{memberdesc}[file]{encoding}
1650The encoding that this file uses. When Unicode strings are written
1651to a file, they will be converted to byte strings using this encoding.
1652In addition, when the file is connected to a terminal, the attribute
1653gives the encoding that the terminal is likely to use (that
1654information might be incorrect if the user has misconfigured the
1655terminal). The attribute is read-only and may not be present on
1656all file-like objects. It may also be \code{None}, in which case
1657the file uses the system default encoding for converting Unicode
1658strings.
1659
1660\versionadded{2.3}
1661\end{memberdesc}
1662
Fred Drake64e3b431998-07-24 13:56:11 +00001663\begin{memberdesc}[file]{mode}
1664The I/O mode for the file. If the file was created using the
1665\function{open()} built-in function, this will be the value of the
Fred Drake752ba392000-09-19 15:18:51 +00001666\var{mode} parameter. This is a read-only attribute and may not be
1667present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001668\end{memberdesc}
1669
1670\begin{memberdesc}[file]{name}
1671If the file object was created using \function{open()}, the name of
1672the file. Otherwise, some string that indicates the source of the
1673file object, of the form \samp{<\mbox{\ldots}>}. This is a read-only
Fred Drake752ba392000-09-19 15:18:51 +00001674attribute and may not be present on all file-like objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001675\end{memberdesc}
1676
Michael W. Hudson9c206152003-03-05 14:42:09 +00001677\begin{memberdesc}[file]{newlines}
Fred Drake7c67cb82003-12-30 17:17:17 +00001678If Python was built with the \longprogramopt{with-universal-newlines}
1679option to \program{configure} (the default) this read-only attribute
1680exists, and for files opened in
Michael W. Hudson9c206152003-03-05 14:42:09 +00001681universal newline read mode it keeps track of the types of newlines
1682encountered while reading the file. The values it can take are
1683\code{'\e r'}, \code{'\e n'}, \code{'\e r\e n'}, \code{None} (unknown,
1684no newlines read yet) or a tuple containing all the newline
1685types seen, to indicate that multiple
1686newline conventions were encountered. For files not opened in universal
1687newline read mode the value of this attribute will be \code{None}.
1688\end{memberdesc}
1689
Fred Drake64e3b431998-07-24 13:56:11 +00001690\begin{memberdesc}[file]{softspace}
1691Boolean that indicates whether a space character needs to be printed
1692before another value when using the \keyword{print} statement.
1693Classes that are trying to simulate a file object should also have a
1694writable \member{softspace} attribute, which should be initialized to
Fred Drake66571cc2000-09-09 03:30:34 +00001695zero. This will be automatic for most classes implemented in Python
1696(care may be needed for objects that override attribute access); types
1697implemented in C will have to provide a writable
1698\member{softspace} attribute.
Fred Drake0aa811c2001-10-20 04:24:09 +00001699\note{This attribute is not used to control the
Fred Drake51f53df2000-09-20 04:48:20 +00001700\keyword{print} statement, but to allow the implementation of
Fred Drake0aa811c2001-10-20 04:24:09 +00001701\keyword{print} to keep track of its internal state.}
Fred Drake64e3b431998-07-24 13:56:11 +00001702\end{memberdesc}
1703
Fred Drakea776cea2000-11-06 20:17:37 +00001704
Fred Drake99de2182001-10-30 06:23:14 +00001705\subsection{Other Built-in Types \label{typesother}}
1706
1707The interpreter supports several other kinds of objects.
1708Most of these support only one or two operations.
1709
1710
1711\subsubsection{Modules \label{typesmodules}}
1712
1713The only special operation on a module is attribute access:
1714\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name}
1715accesses a name defined in \var{m}'s symbol table. Module attributes
1716can be assigned to. (Note that the \keyword{import} statement is not,
1717strictly speaking, an operation on a module object; \code{import
1718\var{foo}} does not require a module object named \var{foo} to exist,
1719rather it requires an (external) \emph{definition} for a module named
1720\var{foo} somewhere.)
1721
1722A special member of every module is \member{__dict__}.
1723This is the dictionary containing the module's symbol table.
1724Modifying this dictionary will actually change the module's symbol
1725table, but direct assignment to the \member{__dict__} attribute is not
1726possible (you can write \code{\var{m}.__dict__['a'] = 1}, which
1727defines \code{\var{m}.a} to be \code{1}, but you can't write
Fred Drake401d1e32003-12-30 22:21:18 +00001728\code{\var{m}.__dict__ = \{\}}). Modifying \member{__dict__} directly
1729is not recommended.
Fred Drake99de2182001-10-30 06:23:14 +00001730
1731Modules built into the interpreter are written like this:
1732\code{<module 'sys' (built-in)>}. If loaded from a file, they are
1733written as \code{<module 'os' from
1734'/usr/local/lib/python\shortversion/os.pyc'>}.
1735
1736
1737\subsubsection{Classes and Class Instances \label{typesobjects}}
1738\nodename{Classes and Instances}
1739
1740See chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python
1741Reference Manual} for these.
1742
1743
1744\subsubsection{Functions \label{typesfunctions}}
1745
1746Function objects are created by function definitions. The only
1747operation on a function object is to call it:
1748\code{\var{func}(\var{argument-list})}.
1749
1750There are really two flavors of function objects: built-in functions
1751and user-defined functions. Both support the same operation (to call
1752the function), but the implementation is different, hence the
1753different object types.
1754
Michael W. Hudson5e897952004-08-12 18:12:44 +00001755See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1756information.
Fred Drake99de2182001-10-30 06:23:14 +00001757
1758\subsubsection{Methods \label{typesmethods}}
1759\obindex{method}
1760
1761Methods are functions that are called using the attribute notation.
1762There are two flavors: built-in methods (such as \method{append()} on
1763lists) and class instance methods. Built-in methods are described
1764with the types that support them.
1765
1766The implementation adds two special read-only attributes to class
1767instance methods: \code{\var{m}.im_self} is the object on which the
1768method operates, and \code{\var{m}.im_func} is the function
1769implementing the method. Calling \code{\var{m}(\var{arg-1},
1770\var{arg-2}, \textrm{\ldots}, \var{arg-n})} is completely equivalent to
1771calling \code{\var{m}.im_func(\var{m}.im_self, \var{arg-1},
1772\var{arg-2}, \textrm{\ldots}, \var{arg-n})}.
1773
1774Class instance methods are either \emph{bound} or \emph{unbound},
1775referring to whether the method was accessed through an instance or a
1776class, respectively. When a method is unbound, its \code{im_self}
1777attribute will be \code{None} and if called, an explicit \code{self}
1778object must be passed as the first argument. In this case,
1779\code{self} must be an instance of the unbound method's class (or a
1780subclass of that class), otherwise a \code{TypeError} is raised.
1781
1782Like function objects, methods objects support getting
1783arbitrary attributes. However, since method attributes are actually
1784stored on the underlying function object (\code{meth.im_func}),
1785setting method attributes on either bound or unbound methods is
1786disallowed. Attempting to set a method attribute results in a
1787\code{TypeError} being raised. In order to set a method attribute,
1788you need to explicitly set it on the underlying function object:
1789
1790\begin{verbatim}
1791class C:
1792 def method(self):
1793 pass
1794
1795c = C()
1796c.method.im_func.whoami = 'my name is c'
1797\end{verbatim}
1798
1799See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1800information.
1801
1802
1803\subsubsection{Code Objects \label{bltin-code-objects}}
1804\obindex{code}
1805
1806Code objects are used by the implementation to represent
1807``pseudo-compiled'' executable Python code such as a function body.
1808They differ from function objects because they don't contain a
1809reference to their global execution environment. Code objects are
1810returned by the built-in \function{compile()} function and can be
1811extracted from function objects through their \member{func_code}
1812attribute.
1813\bifuncindex{compile}
1814\withsubitem{(function object attribute)}{\ttindex{func_code}}
1815
1816A code object can be executed or evaluated by passing it (instead of a
1817source string) to the \keyword{exec} statement or the built-in
1818\function{eval()} function.
1819\stindex{exec}
1820\bifuncindex{eval}
1821
1822See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
1823information.
1824
1825
1826\subsubsection{Type Objects \label{bltin-type-objects}}
1827
1828Type objects represent the various object types. An object's type is
1829accessed by the built-in function \function{type()}. There are no special
Fred Drake401d1e32003-12-30 22:21:18 +00001830operations on types. The standard module \refmodule{types} defines names
Fred Drake99de2182001-10-30 06:23:14 +00001831for all standard built-in types.
1832\bifuncindex{type}
1833\refstmodindex{types}
1834
1835Types are written like this: \code{<type 'int'>}.
1836
1837
1838\subsubsection{The Null Object \label{bltin-null-object}}
1839
1840This object is returned by functions that don't explicitly return a
1841value. It supports no special operations. There is exactly one null
1842object, named \code{None} (a built-in name).
1843
1844It is written as \code{None}.
1845
1846
1847\subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
1848
1849This object is used by extended slice notation (see the
1850\citetitle[../ref/ref.html]{Python Reference Manual}). It supports no
1851special operations. There is exactly one ellipsis object, named
1852\constant{Ellipsis} (a built-in name).
1853
1854It is written as \code{Ellipsis}.
1855
Guido van Rossum77f6a652002-04-03 22:41:51 +00001856\subsubsection{Boolean Values}
1857
1858Boolean values are the two constant objects \code{False} and
1859\code{True}. They are used to represent truth values (although other
1860values can also be considered false or true). In numeric contexts
1861(for example when used as the argument to an arithmetic operator),
1862they behave like the integers 0 and 1, respectively. The built-in
1863function \function{bool()} can be used to cast any value to a Boolean,
1864if the value can be interpreted as a truth value (see section Truth
1865Value Testing above).
1866
1867They are written as \code{False} and \code{True}, respectively.
1868\index{False}
1869\index{True}
1870\indexii{Boolean}{values}
1871
Fred Drake99de2182001-10-30 06:23:14 +00001872
Fred Drake9474d861999-02-12 22:05:33 +00001873\subsubsection{Internal Objects \label{typesinternal}}
Fred Drake64e3b431998-07-24 13:56:11 +00001874
Fred Drake37f15741999-11-10 16:21:37 +00001875See the \citetitle[../ref/ref.html]{Python Reference Manual} for this
Fred Drake512bb722000-08-18 03:12:38 +00001876information. It describes stack frame objects, traceback objects, and
1877slice objects.
Fred Drake64e3b431998-07-24 13:56:11 +00001878
1879
Fred Drake7a2f0661998-09-10 18:25:58 +00001880\subsection{Special Attributes \label{specialattrs}}
Fred Drake64e3b431998-07-24 13:56:11 +00001881
1882The implementation adds a few special read-only attributes to several
Fred Drakef72de0f2004-05-12 02:48:29 +00001883object types, where they are relevant. Some of these are not reported
1884by the \function{dir()} built-in function.
Fred Drake64e3b431998-07-24 13:56:11 +00001885
Fred Drakea776cea2000-11-06 20:17:37 +00001886\begin{memberdesc}[object]{__dict__}
1887A dictionary or other mapping object used to store an
Fred Drake7a2f0661998-09-10 18:25:58 +00001888object's (writable) attributes.
Fred Drakea776cea2000-11-06 20:17:37 +00001889\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001890
Fred Drakea776cea2000-11-06 20:17:37 +00001891\begin{memberdesc}[object]{__methods__}
Fred Drake35705512001-12-03 17:32:27 +00001892\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1893list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001894\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001895
Fred Drakea776cea2000-11-06 20:17:37 +00001896\begin{memberdesc}[object]{__members__}
Fred Drake35705512001-12-03 17:32:27 +00001897\deprecated{2.2}{Use the built-in function \function{dir()} to get a
1898list of an object's attributes. This attribute is no longer available.}
Fred Drakea776cea2000-11-06 20:17:37 +00001899\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001900
Fred Drakea776cea2000-11-06 20:17:37 +00001901\begin{memberdesc}[instance]{__class__}
Fred Drake7a2f0661998-09-10 18:25:58 +00001902The class to which a class instance belongs.
Fred Drakea776cea2000-11-06 20:17:37 +00001903\end{memberdesc}
Fred Drake64e3b431998-07-24 13:56:11 +00001904
Fred Drakea776cea2000-11-06 20:17:37 +00001905\begin{memberdesc}[class]{__bases__}
Fred Drake907e76b2001-07-06 20:30:11 +00001906The tuple of base classes of a class object. If there are no base
1907classes, this will be an empty tuple.
Fred Drakea776cea2000-11-06 20:17:37 +00001908\end{memberdesc}
Fred Drakef72de0f2004-05-12 02:48:29 +00001909
1910\begin{memberdesc}[class]{__name__}
1911The name of the class or type.
1912\end{memberdesc}