blob: a97a5195fa824bffc0e68b064622cb1c18c10391 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. XXX: reference/datamodel and this have quite a few overlaps!
2
3
4.. _bltin-types:
5
6**************
7Built-in Types
8**************
9
10The following sections describe the standard types that are built into the
11interpreter.
12
Georg Brandl116aa622007-08-15 14:28:22 +000013.. index:: pair: built-in; types
14
15The principal built-in types are numerics, sequences, mappings, files, classes,
16instances and exceptions.
17
Georg Brandl116aa622007-08-15 14:28:22 +000018Some operations are supported by several object types; in particular,
19practically all objects can be compared, tested for truth value, and converted
20to a string (with the :func:`repr` function or the slightly different
21:func:`str` function). The latter function is implicitly used when an object is
22written by the :func:`print` function.
23
24
25.. _truth:
26
27Truth Value Testing
28===================
29
30.. index::
31 statement: if
32 statement: while
33 pair: truth; value
34 pair: Boolean; operations
35 single: false
36
37Any object can be tested for truth value, for use in an :keyword:`if` or
38:keyword:`while` condition or as operand of the Boolean operations below. The
39following values are considered false:
40
41 .. index:: single: None (Built-in object)
42
43* ``None``
44
45 .. index:: single: False (Built-in object)
46
47* ``False``
48
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +000049* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51* any empty sequence, for example, ``''``, ``()``, ``[]``.
52
53* any empty mapping, for example, ``{}``.
54
55* instances of user-defined classes, if the class defines a :meth:`__bool__` or
56 :meth:`__len__` method, when that method returns the integer zero or
57 :class:`bool` value ``False``. [#]_
58
59.. index:: single: true
60
61All other values are considered true --- so objects of many types are always
62true.
63
64.. index::
65 operator: or
66 operator: and
67 single: False
68 single: True
69
70Operations and built-in functions that have a Boolean result always return ``0``
71or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
72(Important exception: the Boolean operations ``or`` and ``and`` always return
73one of their operands.)
74
75
76.. _boolean:
77
78Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
79====================================================================
80
81.. index:: pair: Boolean; operations
82
83These are the Boolean operations, ordered by ascending priority:
84
85+-------------+---------------------------------+-------+
86| Operation | Result | Notes |
87+=============+=================================+=======+
88| ``x or y`` | if *x* is false, then *y*, else | \(1) |
89| | *x* | |
90+-------------+---------------------------------+-------+
91| ``x and y`` | if *x* is false, then *x*, else | \(2) |
92| | *y* | |
93+-------------+---------------------------------+-------+
94| ``not x`` | if *x* is false, then ``True``, | \(3) |
95| | else ``False`` | |
96+-------------+---------------------------------+-------+
97
98.. index::
99 operator: and
100 operator: or
101 operator: not
102
103Notes:
104
105(1)
106 This is a short-circuit operator, so it only evaluates the second
107 argument if the first one is :const:`False`.
108
109(2)
110 This is a short-circuit operator, so it only evaluates the second
111 argument if the first one is :const:`True`.
112
113(3)
114 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
115 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
116
117
118.. _stdcomparisons:
119
120Comparisons
121===========
122
123.. index:: pair: chaining; comparisons
124
Georg Brandl905ec322007-09-28 13:39:25 +0000125There are eight comparison operations in Python. They all have the same
126priority (which is higher than that of the Boolean operations). Comparisons can
Georg Brandl116aa622007-08-15 14:28:22 +0000127be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
128y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
129evaluated at all when ``x < y`` is found to be false).
130
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000131.. index::
132 pair: operator; comparison
133 operator: ==
134 operator: <
135 operator: >
136 operator: <=
137 operator: >=
138 operator: !=
139 operator: is
140 operator: is not
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142This table summarizes the comparison operations:
143
Georg Brandlfd855162008-01-07 09:13:03 +0000144+------------+-------------------------+
145| Operation | Meaning |
146+============+=========================+
147| ``<`` | strictly less than |
148+------------+-------------------------+
149| ``<=`` | less than or equal |
150+------------+-------------------------+
151| ``>`` | strictly greater than |
152+------------+-------------------------+
153| ``>=`` | greater than or equal |
154+------------+-------------------------+
155| ``==`` | equal |
156+------------+-------------------------+
157| ``!=`` | not equal |
158+------------+-------------------------+
159| ``is`` | object identity |
160+------------+-------------------------+
161| ``is not`` | negated object identity |
162+------------+-------------------------+
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000163
164.. index::
Georg Brandl116aa622007-08-15 14:28:22 +0000165 pair: object; numeric
166 pair: objects; comparing
167
Georg Brandl905ec322007-09-28 13:39:25 +0000168Objects of different types, except different numeric types, never compare equal.
Georg Brandl116aa622007-08-15 14:28:22 +0000169Furthermore, some types (for example, file objects) support only a degenerate
Georg Brandl905ec322007-09-28 13:39:25 +0000170notion of comparison where any two objects of that type are unequal. The ``<``,
171``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when
172any operand is a complex number, the objects are of different types that cannot
173be compared, or other cases where there is no defined ordering.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Georg Brandl905ec322007-09-28 13:39:25 +0000175.. index::
176 single: __cmp__() (instance method)
177 single: __eq__() (instance method)
178 single: __ne__() (instance method)
179 single: __lt__() (instance method)
180 single: __le__() (instance method)
181 single: __gt__() (instance method)
182 single: __ge__() (instance method)
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184Instances of a class normally compare as non-equal unless the class defines the
Georg Brandl905ec322007-09-28 13:39:25 +0000185:meth:`__eq__` or :meth:`__cmp__` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Georg Brandl905ec322007-09-28 13:39:25 +0000187Instances of a class cannot be ordered with respect to other instances of the
188same class, or other types of object, unless the class defines enough of the
189methods :meth:`__cmp__`, :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and
190:meth:`__ge__` (in general, either :meth:`__cmp__` or both :meth:`__lt__` and
191:meth:`__eq__` are sufficient, if you want the conventional meanings of the
192comparison operators).
193
194The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
195customized; also they can be applied to any two objects and never raise an
196exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198.. index::
199 operator: in
200 operator: not in
201
202Two more operations with the same syntactic priority, ``in`` and ``not in``, are
203supported only by sequence types (below).
204
205
206.. _typesnumeric:
207
Georg Brandl905ec322007-09-28 13:39:25 +0000208Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
209================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211.. index::
212 object: numeric
213 object: Boolean
214 object: integer
Georg Brandl116aa622007-08-15 14:28:22 +0000215 object: floating point
216 object: complex number
217 pair: C; language
218
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000219There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
220point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
221subtype of integers. Integers have unlimited precision. Floating point
222numbers are implemented using :ctype:`double` in C---all bets on their
223precision are off unless you happen to know the machine you are working
224with. Complex numbers have a real and imaginary part, which are each
225implemented using :ctype:`double` in C. To extract these parts from a
226complex number *z*, use ``z.real`` and ``z.imag``. (The standard library
227includes additional numeric types, :mod:`fractions` that hold rationals,
228and :mod:`decimal` that hold floating-point numbers with user-definable
229precision.)
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231.. index::
232 pair: numeric; literals
233 pair: integer; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000234 pair: floating point; literals
235 pair: complex number; literals
236 pair: hexadecimal; literals
237 pair: octal; literals
Neal Norwitz1d2aef52007-10-02 07:26:14 +0000238 pair: binary; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240Numbers are created by numeric literals or as the result of built-in functions
Georg Brandl905ec322007-09-28 13:39:25 +0000241and operators. Unadorned integer literals (including hex, octal and binary
242numbers) yield integers. Numeric literals containing a decimal point or an
243exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a
244numeric literal yields an imaginary number (a complex number with a zero real
245part) which you can add to an integer or float to get a complex number with real
246and imaginary parts.
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. index::
249 single: arithmetic
250 builtin: int
Georg Brandl116aa622007-08-15 14:28:22 +0000251 builtin: float
252 builtin: complex
253
254Python fully supports mixed arithmetic: when a binary arithmetic operator has
255operands of different numeric types, the operand with the "narrower" type is
Georg Brandl905ec322007-09-28 13:39:25 +0000256widened to that of the other, where integer is narrower than floating point,
257which is narrower than complex. Comparisons between numbers of mixed type use
258the same rule. [#]_ The constructors :func:`int`, :func:`float`, and
259:func:`complex` can be used to produce numbers of a specific type.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261All numeric types (except complex) support the following operations, sorted by
262ascending priority (operations in the same box have the same priority; all
263numeric operations have a higher priority than comparison operations):
264
Georg Brandl905ec322007-09-28 13:39:25 +0000265+---------------------+---------------------------------+-------+--------------------+
266| Operation | Result | Notes | Full documentation |
Neal Norwitz1d2aef52007-10-02 07:26:14 +0000267+=====================+=================================+=======+====================+
Georg Brandl905ec322007-09-28 13:39:25 +0000268| ``x + y`` | sum of *x* and *y* | | |
269+---------------------+---------------------------------+-------+--------------------+
270| ``x - y`` | difference of *x* and *y* | | |
271+---------------------+---------------------------------+-------+--------------------+
272| ``x * y`` | product of *x* and *y* | | |
273+---------------------+---------------------------------+-------+--------------------+
274| ``x / y`` | quotient of *x* and *y* | | |
275+---------------------+---------------------------------+-------+--------------------+
276| ``x // y`` | floored quotient of *x* and | \(1) | |
277| | *y* | | |
278+---------------------+---------------------------------+-------+--------------------+
279| ``x % y`` | remainder of ``x / y`` | \(2) | |
280+---------------------+---------------------------------+-------+--------------------+
281| ``-x`` | *x* negated | | |
282+---------------------+---------------------------------+-------+--------------------+
283| ``+x`` | *x* unchanged | | |
284+---------------------+---------------------------------+-------+--------------------+
285| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
286| | *x* | | |
287+---------------------+---------------------------------+-------+--------------------+
288| ``int(x)`` | *x* converted to integer | \(3) | :func:`int` |
289+---------------------+---------------------------------+-------+--------------------+
Georg Brandl74f36692008-01-06 17:39:49 +0000290| ``float(x)`` | *x* converted to floating point | \(4) | :func:`float` |
Georg Brandl905ec322007-09-28 13:39:25 +0000291+---------------------+---------------------------------+-------+--------------------+
292| ``complex(re, im)`` | a complex number with real part | | :func:`complex` |
293| | *re*, imaginary part *im*. | | |
294| | *im* defaults to zero. | | |
295+---------------------+---------------------------------+-------+--------------------+
296| ``c.conjugate()`` | conjugate of the complex number | | |
297| | *c* | | |
298+---------------------+---------------------------------+-------+--------------------+
299| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
300+---------------------+---------------------------------+-------+--------------------+
Georg Brandl60fe2f12008-01-07 09:16:46 +0000301| ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
Georg Brandl905ec322007-09-28 13:39:25 +0000302+---------------------+---------------------------------+-------+--------------------+
Georg Brandl60fe2f12008-01-07 09:16:46 +0000303| ``x ** y`` | *x* to the power *y* | \(5) | |
Georg Brandl905ec322007-09-28 13:39:25 +0000304+---------------------+---------------------------------+-------+--------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306.. index::
307 triple: operations on; numeric; types
308 single: conjugate() (complex number method)
309
310Notes:
311
312(1)
Georg Brandl905ec322007-09-28 13:39:25 +0000313 Also referred to as integer division. The resultant value is a whole
314 integer, though the result's type is not necessarily int. The result is
315 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
316 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318(2)
Georg Brandl905ec322007-09-28 13:39:25 +0000319 Not for complex numbers. Instead convert to floats using :func:`abs` if
320 appropriate.
321
322(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000323 .. index::
324 module: math
325 single: floor() (in module math)
326 single: ceil() (in module math)
327 pair: numeric; conversions
328 pair: C; language
329
Georg Brandlba956ae2007-11-29 17:24:34 +0000330 Conversion from floating point to integer may round or truncate
Georg Brandl116aa622007-08-15 14:28:22 +0000331 as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
332 for well-defined conversions.
333
Georg Brandl74f36692008-01-06 17:39:49 +0000334(4)
Christian Heimes99170a52007-12-19 02:07:34 +0000335 float also accepts the strings "nan" and "inf" with an optional prefix "+"
336 or "-" for Not a Number (NaN) and positive or negative infinity.
Christian Heimes7f044312008-01-06 17:05:40 +0000337
Georg Brandl74f36692008-01-06 17:39:49 +0000338(5)
Christian Heimes7f044312008-01-06 17:05:40 +0000339 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
340 programming languages.
341
Christian Heimes99170a52007-12-19 02:07:34 +0000342
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000343
Christian Heimesfaf2f632008-01-06 16:59:19 +0000344All :class:`numbers.Real` types (:class:`int` and
345:class:`float`) also include the following operations:
346
347+--------------------+--------------------------------+--------+
348| Operation | Result | Notes |
349+====================+================================+========+
350| ``trunc(x)`` | *x* truncated to Integral | |
351+--------------------+--------------------------------+--------+
352| ``round(x[, n])`` | *x* rounded to n digits, | |
353| | rounding half to even. If n is | |
354| | omitted, it defaults to 0. | |
355+--------------------+--------------------------------+--------+
356| ``math.floor(x)`` | the greatest Integral <= *x* | |
357+--------------------+--------------------------------+--------+
358| ``math.ceil(x)`` | the least Integral >= *x* | |
359+--------------------+--------------------------------+--------+
360
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000361For additional numeric operations see the :mod:`math` and :mod:`cmath`
362modules.
363
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000364.. XXXJH exceptions: overflow (when? what operations?) zerodivision
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366
367.. _bitstring-ops:
368
369Bit-string Operations on Integer Types
370--------------------------------------
371
372.. _bit-string-operations:
373
Georg Brandl905ec322007-09-28 13:39:25 +0000374Integers support additional operations that make sense only for bit-strings.
375Negative numbers are treated as their 2's complement value (this assumes a
376sufficiently large number of bits that no overflow occurs during the operation).
Georg Brandl116aa622007-08-15 14:28:22 +0000377
Christian Heimesfaf2f632008-01-06 16:59:19 +0000378The priorities of the binary bitwise operations are all lower than the numeric
Georg Brandl116aa622007-08-15 14:28:22 +0000379operations and higher than the comparisons; the unary operation ``~`` has the
380same priority as the other unary numeric operations (``+`` and ``-``).
381
382This table lists the bit-string operations sorted in ascending priority
383(operations in the same box have the same priority):
384
385+------------+--------------------------------+----------+
386| Operation | Result | Notes |
387+============+================================+==========+
388| ``x | y`` | bitwise :dfn:`or` of *x* and | |
389| | *y* | |
390+------------+--------------------------------+----------+
391| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
392| | *x* and *y* | |
393+------------+--------------------------------+----------+
394| ``x & y`` | bitwise :dfn:`and` of *x* and | |
395| | *y* | |
396+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000397| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
Georg Brandl116aa622007-08-15 14:28:22 +0000398+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000399| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000400+------------+--------------------------------+----------+
401| ``~x`` | the bits of *x* inverted | |
402+------------+--------------------------------+----------+
403
404.. index::
405 triple: operations on; integer; types
406 pair: bit-string; operations
407 pair: shifting; operations
408 pair: masking; operations
409
410Notes:
411
412(1)
413 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
414
415(2)
416 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
417 without overflow check.
418
419(3)
420 A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
421 overflow check.
422
423
424.. _typeiter:
425
426Iterator Types
427==============
428
Georg Brandl116aa622007-08-15 14:28:22 +0000429.. index::
430 single: iterator protocol
431 single: protocol; iterator
432 single: sequence; iteration
433 single: container; iteration over
434
435Python supports a concept of iteration over containers. This is implemented
436using two distinct methods; these are used to allow user-defined classes to
437support iteration. Sequences, described below in more detail, always support
438the iteration methods.
439
440One method needs to be defined for container objects to provide iteration
441support:
442
Christian Heimes790c8232008-01-07 21:14:23 +0000443.. XXX duplicated in reference/datamodel!
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Christian Heimes790c8232008-01-07 21:14:23 +0000445.. method:: container.__iter__()
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447 Return an iterator object. The object is required to support the iterator
448 protocol described below. If a container supports different types of
449 iteration, additional methods can be provided to specifically request
450 iterators for those iteration types. (An example of an object supporting
451 multiple forms of iteration would be a tree structure which supports both
452 breadth-first and depth-first traversal.) This method corresponds to the
453 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
454 API.
455
456The iterator objects themselves are required to support the following two
457methods, which together form the :dfn:`iterator protocol`:
458
459
460.. method:: iterator.__iter__()
461
462 Return the iterator object itself. This is required to allow both containers
463 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
464 This method corresponds to the :attr:`tp_iter` slot of the type structure for
465 Python objects in the Python/C API.
466
467
Georg Brandl905ec322007-09-28 13:39:25 +0000468.. method:: iterator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470 Return the next item from the container. If there are no further items, raise
471 the :exc:`StopIteration` exception. This method corresponds to the
472 :attr:`tp_iternext` slot of the type structure for Python objects in the
473 Python/C API.
474
475Python defines several iterator objects to support iteration over general and
476specific sequence types, dictionaries, and other more specialized forms. The
477specific types are not important beyond their implementation of the iterator
478protocol.
479
Georg Brandl905ec322007-09-28 13:39:25 +0000480Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must
481continue to do so on subsequent calls. Implementations that do not obey this
482property are deemed broken.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Georg Brandl9afde1c2007-11-01 20:32:30 +0000484Python's :term:`generator`\s provide a convenient way to implement the iterator
485protocol. If a container object's :meth:`__iter__` method is implemented as a
486generator, it will automatically return an iterator object (technically, a
487generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489
490.. _typesseq:
491
Georg Brandl95414632007-11-22 11:00:28 +0000492Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`list`, :class:`tuple`, :class:`range`
493==================================================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandl95414632007-11-22 11:00:28 +0000495There are five sequence types: strings, byte sequences, byte arrays, lists,
496tuples, and range objects. (For other containers see the built-in
497:class:`dict`, :class:`list`, :class:`set`, and :class:`tuple` classes, and the
Georg Brandl4b491312007-08-31 09:22:56 +0000498:mod:`collections` module.)
Georg Brandl116aa622007-08-15 14:28:22 +0000499
500.. index::
501 object: sequence
502 object: string
Georg Brandl4b491312007-08-31 09:22:56 +0000503 object: bytes
Georg Brandl7c676132007-10-23 18:17:00 +0000504 object: buffer
Georg Brandl116aa622007-08-15 14:28:22 +0000505 object: tuple
506 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000507 object: range
508
Georg Brandl7c676132007-10-23 18:17:00 +0000509Strings contain Unicode characters. Their literals are written in single or
510double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about
511string literals. In addition to the functionality described here, there are
512also string-specific methods described in the :ref:`string-methods` section.
513
Georg Brandl95414632007-11-22 11:00:28 +0000514Bytes and bytearray objects contain single bytes -- the former is immutable
Georg Brandl18da8f02008-07-01 20:08:02 +0000515while the latter is a mutable sequence. Bytes objects can be constructed the
516constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal
517string syntax: ``b'xyzzy'``. To construct byte arrays, use the
518:func:`bytearray` function.
Georg Brandl4b491312007-08-31 09:22:56 +0000519
Georg Brandl226878c2007-08-31 10:15:37 +0000520.. warning::
Georg Brandl4b491312007-08-31 09:22:56 +0000521
522 While string objects are sequences of characters (represented by strings of
Georg Brandl95414632007-11-22 11:00:28 +0000523 length 1), bytes and bytearray objects are sequences of *integers* (between 0
Georg Brandl7c676132007-10-23 18:17:00 +0000524 and 255), representing the ASCII value of single bytes. That means that for
Georg Brandl18da8f02008-07-01 20:08:02 +0000525 a bytes or bytearray object *b*, ``b[0]`` will be an integer, while
526 ``b[0:1]`` will be a bytes or bytearray object of length 1. The
527 representation of bytes objects uses the literal format (``b'...'``) since it
528 is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always
529 convert a bytes object into a list of integers using ``list(b)``.
Georg Brandl4b491312007-08-31 09:22:56 +0000530
Georg Brandl2326a792007-09-01 12:08:51 +0000531 Also, while in previous Python versions, byte strings and Unicode strings
532 could be exchanged for each other rather freely (barring encoding issues),
Georg Brandl7c676132007-10-23 18:17:00 +0000533 strings and bytes are now completely separate concepts. There's no implicit
534 en-/decoding if you pass and object of the wrong type. A string always
Georg Brandl95414632007-11-22 11:00:28 +0000535 compares unequal to a bytes or bytearray object.
Georg Brandl2326a792007-09-01 12:08:51 +0000536
Georg Brandl4b491312007-08-31 09:22:56 +0000537Lists are constructed with square brackets, separating items with commas: ``[a,
538b, c]``. Tuples are constructed by the comma operator (not within square
539brackets), with or without enclosing parentheses, but an empty tuple must have
540the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple
541must have a trailing comma, such as ``(d,)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Georg Brandl95414632007-11-22 11:00:28 +0000543Objects of type range are created using the :func:`range` function. They don't
544support slicing, concatenation or repetition, and using ``in``, ``not in``,
545:func:`min` or :func:`max` on them is inefficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547Most sequence types support the following operations. The ``in`` and ``not in``
548operations have the same priorities as the comparison operations. The ``+`` and
549``*`` operations have the same priority as the corresponding numeric operations.
Christian Heimes043d6f62008-01-07 17:19:16 +0000550[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552This table lists the sequence operations sorted in ascending priority
553(operations in the same box have the same priority). In the table, *s* and *t*
554are sequences of the same type; *n*, *i* and *j* are integers:
555
556+------------------+--------------------------------+----------+
557| Operation | Result | Notes |
558+==================+================================+==========+
559| ``x in s`` | ``True`` if an item of *s* is | \(1) |
560| | equal to *x*, else ``False`` | |
561+------------------+--------------------------------+----------+
562| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
563| | equal to *x*, else ``True`` | |
564+------------------+--------------------------------+----------+
565| ``s + t`` | the concatenation of *s* and | \(6) |
566| | *t* | |
567+------------------+--------------------------------+----------+
568| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
569| | concatenated | |
570+------------------+--------------------------------+----------+
571| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
572+------------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000573| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000574+------------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000575| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
Georg Brandl116aa622007-08-15 14:28:22 +0000576| | with step *k* | |
577+------------------+--------------------------------+----------+
578| ``len(s)`` | length of *s* | |
579+------------------+--------------------------------+----------+
580| ``min(s)`` | smallest item of *s* | |
581+------------------+--------------------------------+----------+
582| ``max(s)`` | largest item of *s* | |
583+------------------+--------------------------------+----------+
584
Georg Brandl7c676132007-10-23 18:17:00 +0000585Sequence types also support comparisons. In particular, tuples and lists are
586compared lexicographically by comparing corresponding elements. This means that
Georg Brandl4b491312007-08-31 09:22:56 +0000587to compare equal, every element must compare equal and the two sequences must be
Georg Brandl7c676132007-10-23 18:17:00 +0000588of the same type and have the same length. (For full details see
Georg Brandl4b491312007-08-31 09:22:56 +0000589:ref:`comparisons` in the language reference.)
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591.. index::
592 triple: operations on; sequence; types
593 builtin: len
594 builtin: min
595 builtin: max
596 pair: concatenation; operation
597 pair: repetition; operation
598 pair: subscript; operation
599 pair: slice; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000600 operator: in
601 operator: not in
602
603Notes:
604
605(1)
Georg Brandl4b491312007-08-31 09:22:56 +0000606 When *s* is a string object, the ``in`` and ``not in`` operations act like a
607 substring test.
Georg Brandl116aa622007-08-15 14:28:22 +0000608
609(2)
610 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
611 sequence of the same type as *s*). Note also that the copies are shallow;
612 nested structures are not copied. This often haunts new Python programmers;
Christian Heimesfe337bf2008-03-23 21:54:12 +0000613 consider:
Georg Brandl116aa622007-08-15 14:28:22 +0000614
615 >>> lists = [[]] * 3
616 >>> lists
617 [[], [], []]
618 >>> lists[0].append(3)
619 >>> lists
620 [[3], [3], [3]]
621
622 What has happened is that ``[[]]`` is a one-element list containing an empty
Christian Heimesfe337bf2008-03-23 21:54:12 +0000623 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
624 list. Modifying any of the elements of ``lists`` modifies this single list.
625 You can create a list of different lists this way:
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627 >>> lists = [[] for i in range(3)]
628 >>> lists[0].append(3)
629 >>> lists[1].append(5)
630 >>> lists[2].append(7)
631 >>> lists
632 [[3], [5], [7]]
633
634(3)
635 If *i* or *j* is negative, the index is relative to the end of the string:
Georg Brandl7c676132007-10-23 18:17:00 +0000636 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
637 still ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639(4)
640 The slice of *s* from *i* to *j* is defined as the sequence of items with index
641 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
642 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
643 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
644 empty.
645
646(5)
647 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
Christian Heimes2c181612007-12-17 20:04:13 +0000648 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
Georg Brandl116aa622007-08-15 14:28:22 +0000649 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
650 *j* is reached (but never including *j*). If *i* or *j* is greater than
651 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
652 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
653 If *k* is ``None``, it is treated like ``1``.
654
655(6)
656 If *s* and *t* are both strings, some Python implementations such as CPython can
657 usually perform an in-place optimization for assignments of the form ``s=s+t``
658 or ``s+=t``. When applicable, this optimization makes quadratic run-time much
659 less likely. This optimization is both version and implementation dependent.
660 For performance sensitive code, it is preferable to use the :meth:`str.join`
661 method which assures consistent linear concatenation performance across versions
662 and implementations.
663
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665.. _string-methods:
666
667String Methods
668--------------
669
670.. index:: pair: string; methods
671
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000672String objects support the methods listed below. Note that none of these
673methods take keyword arguments.
674
675In addition, Python's strings support the sequence type methods described in
676the :ref:`typesseq` section. To output formatted strings, see the
677:ref:`string-formatting` section. Also, see the :mod:`re` module for string
678functions based on regular expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680.. method:: str.capitalize()
681
682 Return a copy of the string with only its first character capitalized.
683
Georg Brandl116aa622007-08-15 14:28:22 +0000684
685.. method:: str.center(width[, fillchar])
686
687 Return centered in a string of length *width*. Padding is done using the
688 specified *fillchar* (default is a space).
689
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691.. method:: str.count(sub[, start[, end]])
692
Georg Brandl9afde1c2007-11-01 20:32:30 +0000693 Return the number of occurrences of substring *sub* in the range [*start*,
694 *end*]. Optional arguments *start* and *end* are interpreted as in slice
695 notation.
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697
Georg Brandl226878c2007-08-31 10:15:37 +0000698.. method:: str.encode([encoding[, errors]])
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700 Return an encoded version of the string. Default encoding is the current
701 default string encoding. *errors* may be given to set a different error
702 handling scheme. The default for *errors* is ``'strict'``, meaning that
703 encoding errors raise a :exc:`UnicodeError`. Other possible values are
704 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
705 any other name registered via :func:`codecs.register_error`, see section
706 :ref:`codec-base-classes`. For a list of possible encodings, see section
707 :ref:`standard-encodings`.
708
Georg Brandl116aa622007-08-15 14:28:22 +0000709
710.. method:: str.endswith(suffix[, start[, end]])
711
712 Return ``True`` if the string ends with the specified *suffix*, otherwise return
713 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
714 *start*, test beginning at that position. With optional *end*, stop comparing
715 at that position.
716
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718.. method:: str.expandtabs([tabsize])
719
Georg Brandl9afde1c2007-11-01 20:32:30 +0000720 Return a copy of the string where all tab characters are replaced by one or
721 more spaces, depending on the current column and the given tab size. The
722 column number is reset to zero after each newline occurring in the string.
723 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
724 doesn't understand other non-printing characters or escape sequences.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726
727.. method:: str.find(sub[, start[, end]])
728
729 Return the lowest index in the string where substring *sub* is found, such that
730 *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
731 and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
732 found.
733
734
Georg Brandl1c502b52008-05-12 16:50:12 +0000735.. method:: str.format(format_string, *args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000736
737 Perform a string formatting operation. The *format_string* argument can
738 contain literal text or replacement fields delimited by braces ``{}``. Each
739 replacement field contains either the numeric index of a positional argument,
740 or the name of a keyword argument. Returns a copy of *format_string* where
741 each replacement field is replaced with the string value of the corresponding
742 argument.
743
744 >>> "The sum of 1 + 2 is {0}".format(1+2)
745 'The sum of 1 + 2 is 3'
746
747 See :ref:`formatstrings` for a description of the various formatting options
748 that can be specified in format strings.
749
Georg Brandl4b491312007-08-31 09:22:56 +0000750
Georg Brandl116aa622007-08-15 14:28:22 +0000751.. method:: str.index(sub[, start[, end]])
752
753 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
754
755
756.. method:: str.isalnum()
757
758 Return true if all characters in the string are alphanumeric and there is at
759 least one character, false otherwise.
760
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762.. method:: str.isalpha()
763
764 Return true if all characters in the string are alphabetic and there is at least
765 one character, false otherwise.
766
Georg Brandl116aa622007-08-15 14:28:22 +0000767
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000768.. method:: str.isdecimal()
769
770 Return true if all characters in the string are decimal
771 characters and there is at least one character, false
772 otherwise. Decimal characters include digit characters, and all characters
773 that that can be used to form decimal-radix numbers, e.g. U+0660,
774 ARABIC-INDIC DIGIT ZERO.
775
776
Georg Brandl116aa622007-08-15 14:28:22 +0000777.. method:: str.isdigit()
778
779 Return true if all characters in the string are digits and there is at least one
780 character, false otherwise.
781
Georg Brandl116aa622007-08-15 14:28:22 +0000782
783.. method:: str.isidentifier()
784
785 Return true if the string is a valid identifier according to the language
Georg Brandl4b491312007-08-31 09:22:56 +0000786 definition, section :ref:`identifiers`.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788
789.. method:: str.islower()
790
791 Return true if all cased characters in the string are lowercase and there is at
792 least one cased character, false otherwise.
793
Georg Brandl116aa622007-08-15 14:28:22 +0000794
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000795.. method:: str.isnumeric()
796
797 Return true if all characters in the string are numeric
798 characters, and there is at least one character, false
799 otherwise. Numeric characters include digit characters, and all characters
800 that have the Unicode numeric value property, e.g. U+2155,
801 VULGAR FRACTION ONE FIFTH.
802
803
Georg Brandl559e5d72008-06-11 18:37:52 +0000804.. method:: str.isprintable()
805
806 Return true if all characters in the string are printable or the string is
807 empty, false otherwise. Nonprintable characters are those characters defined
808 in the Unicode character database as "Other" or "Separator", excepting the
809 ASCII space (0x20) which is considered printable. (Note that printable
810 characters in this context are those which should not be escaped when
811 :func:`repr` is invoked on a string. It has no bearing on the handling of
812 strings written to :data:`sys.stdout` or :data:`sys.stderr`.)
813
814
Georg Brandl116aa622007-08-15 14:28:22 +0000815.. method:: str.isspace()
816
817 Return true if there are only whitespace characters in the string and there is
818 at least one character, false otherwise.
819
Georg Brandl116aa622007-08-15 14:28:22 +0000820
821.. method:: str.istitle()
822
823 Return true if the string is a titlecased string and there is at least one
824 character, for example uppercase characters may only follow uncased characters
825 and lowercase characters only cased ones. Return false otherwise.
826
Georg Brandl116aa622007-08-15 14:28:22 +0000827
828.. method:: str.isupper()
829
830 Return true if all cased characters in the string are uppercase and there is at
831 least one cased character, false otherwise.
832
Georg Brandl116aa622007-08-15 14:28:22 +0000833
834.. method:: str.join(seq)
835
Guido van Rossumf1044292007-09-27 18:01:22 +0000836 Return a string which is the concatenation of the values in the sequence
837 *seq*. Non-string values in *seq* will be converted to a string using their
Georg Brandl7c676132007-10-23 18:17:00 +0000838 respective ``str()`` value. If there are any :class:`bytes` objects in
839 *seq*, a :exc:`TypeError` will be raised. The separator between elements is
Guido van Rossumf1044292007-09-27 18:01:22 +0000840 the string providing this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842
843.. method:: str.ljust(width[, fillchar])
844
845 Return the string left justified in a string of length *width*. Padding is done
846 using the specified *fillchar* (default is a space). The original string is
847 returned if *width* is less than ``len(s)``.
848
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850.. method:: str.lower()
851
852 Return a copy of the string converted to lowercase.
853
Georg Brandl116aa622007-08-15 14:28:22 +0000854
855.. method:: str.lstrip([chars])
856
857 Return a copy of the string with leading characters removed. The *chars*
858 argument is a string specifying the set of characters to be removed. If omitted
859 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +0000860 argument is not a prefix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862 >>> ' spacious '.lstrip()
863 'spacious '
864 >>> 'www.example.com'.lstrip('cmowz.')
865 'example.com'
866
Georg Brandl116aa622007-08-15 14:28:22 +0000867
Georg Brandlceee0772007-11-27 23:48:05 +0000868.. method:: str.maketrans(x[, y[, z]])
869
870 This static method returns a translation table usable for :meth:`str.translate`.
871
872 If there is only one argument, it must be a dictionary mapping Unicode
873 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
874 strings (of arbitrary lengths) or None. Character keys will then be
875 converted to ordinals.
876
877 If there are two arguments, they must be strings of equal length, and in the
878 resulting dictionary, each character in x will be mapped to the character at
879 the same position in y. If there is a third argument, it must be a string,
880 whose characters will be mapped to None in the result.
881
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883.. method:: str.partition(sep)
884
885 Split the string at the first occurrence of *sep*, and return a 3-tuple
886 containing the part before the separator, the separator itself, and the part
887 after the separator. If the separator is not found, return a 3-tuple containing
888 the string itself, followed by two empty strings.
889
Georg Brandl116aa622007-08-15 14:28:22 +0000890
891.. method:: str.replace(old, new[, count])
892
893 Return a copy of the string with all occurrences of substring *old* replaced by
894 *new*. If the optional argument *count* is given, only the first *count*
895 occurrences are replaced.
896
897
Georg Brandl226878c2007-08-31 10:15:37 +0000898.. method:: str.rfind(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900 Return the highest index in the string where substring *sub* is found, such that
901 *sub* is contained within s[start,end]. Optional arguments *start* and *end*
902 are interpreted as in slice notation. Return ``-1`` on failure.
903
904
905.. method:: str.rindex(sub[, start[, end]])
906
907 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
908 found.
909
910
911.. method:: str.rjust(width[, fillchar])
912
913 Return the string right justified in a string of length *width*. Padding is done
914 using the specified *fillchar* (default is a space). The original string is
915 returned if *width* is less than ``len(s)``.
916
Georg Brandl116aa622007-08-15 14:28:22 +0000917
918.. method:: str.rpartition(sep)
919
920 Split the string at the last occurrence of *sep*, and return a 3-tuple
921 containing the part before the separator, the separator itself, and the part
922 after the separator. If the separator is not found, return a 3-tuple containing
923 two empty strings, followed by the string itself.
924
Georg Brandl116aa622007-08-15 14:28:22 +0000925
Georg Brandl226878c2007-08-31 10:15:37 +0000926.. method:: str.rsplit([sep[, maxsplit]])
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928 Return a list of the words in the string, using *sep* as the delimiter string.
929 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
930 ones. If *sep* is not specified or ``None``, any whitespace string is a
931 separator. Except for splitting from the right, :meth:`rsplit` behaves like
932 :meth:`split` which is described in detail below.
933
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935.. method:: str.rstrip([chars])
936
937 Return a copy of the string with trailing characters removed. The *chars*
938 argument is a string specifying the set of characters to be removed. If omitted
939 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +0000940 argument is not a suffix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942 >>> ' spacious '.rstrip()
943 ' spacious'
944 >>> 'mississippi'.rstrip('ipz')
945 'mississ'
946
Georg Brandl116aa622007-08-15 14:28:22 +0000947
Georg Brandl226878c2007-08-31 10:15:37 +0000948.. method:: str.split([sep[, maxsplit]])
Georg Brandl116aa622007-08-15 14:28:22 +0000949
Georg Brandl226878c2007-08-31 10:15:37 +0000950 Return a list of the words in the string, using *sep* as the delimiter
951 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
952 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
953 specified, then there is no limit on the number of splits (all possible
Georg Brandl9afde1c2007-11-01 20:32:30 +0000954 splits are made).
955
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000956 If *sep* is given, consecutive delimiters are not grouped together and are
Georg Brandl226878c2007-08-31 10:15:37 +0000957 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
958 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
Georg Brandl9afde1c2007-11-01 20:32:30 +0000959 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
Georg Brandl226878c2007-08-31 10:15:37 +0000960 Splitting an empty string with a specified separator returns ``['']``.
Georg Brandl116aa622007-08-15 14:28:22 +0000961
962 If *sep* is not specified or is ``None``, a different splitting algorithm is
Georg Brandl9afde1c2007-11-01 20:32:30 +0000963 applied: runs of consecutive whitespace are regarded as a single separator,
964 and the result will contain no empty strings at the start or end if the
965 string has leading or trailing whitespace. Consequently, splitting an empty
966 string or a string consisting of just whitespace with a ``None`` separator
967 returns ``[]``.
968
969 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
970 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972
973.. method:: str.splitlines([keepends])
974
975 Return a list of the lines in the string, breaking at line boundaries. Line
976 breaks are not included in the resulting list unless *keepends* is given and
977 true.
978
979
980.. method:: str.startswith(prefix[, start[, end]])
981
982 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
983 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
984 test string beginning at that position. With optional *end*, stop comparing
985 string at that position.
986
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988.. method:: str.strip([chars])
989
990 Return a copy of the string with the leading and trailing characters removed.
991 The *chars* argument is a string specifying the set of characters to be removed.
992 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
993 The *chars* argument is not a prefix or suffix; rather, all combinations of its
Christian Heimesfe337bf2008-03-23 21:54:12 +0000994 values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +0000995
996 >>> ' spacious '.strip()
997 'spacious'
998 >>> 'www.example.com'.strip('cmowz.')
999 'example'
1000
Georg Brandl116aa622007-08-15 14:28:22 +00001001
1002.. method:: str.swapcase()
1003
1004 Return a copy of the string with uppercase characters converted to lowercase and
1005 vice versa.
1006
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008.. method:: str.title()
1009
1010 Return a titlecased version of the string: words start with uppercase
1011 characters, all remaining cased characters are lowercase.
1012
Georg Brandl116aa622007-08-15 14:28:22 +00001013
Georg Brandl4b491312007-08-31 09:22:56 +00001014.. method:: str.translate(map)
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Georg Brandl226878c2007-08-31 10:15:37 +00001016 Return a copy of the *s* where all characters have been mapped through the
Georg Brandlceee0772007-11-27 23:48:05 +00001017 *map* which must be a dictionary of Unicode ordinals(integers) to Unicode
1018 ordinals, strings or ``None``. Unmapped characters are left untouched.
1019 Characters mapped to ``None`` are deleted.
1020
1021 A *map* for :meth:`translate` is usually best created by
1022 :meth:`str.maketrans`.
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Christian Heimesfe337bf2008-03-23 21:54:12 +00001024 You can use the :func:`maketrans` helper function in the :mod:`string` module to
1025 create a translation table. For string objects, set the *table* argument to
1026 ``None`` for translations that only delete characters:
1027
Georg Brandl4b491312007-08-31 09:22:56 +00001028 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001029
Georg Brandlceee0772007-11-27 23:48:05 +00001030 An even more flexible approach is to create a custom character mapping
1031 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
Georg Brandl4b491312007-08-31 09:22:56 +00001032 example).
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034
1035.. method:: str.upper()
1036
1037 Return a copy of the string converted to uppercase.
1038
Georg Brandl116aa622007-08-15 14:28:22 +00001039
1040.. method:: str.zfill(width)
1041
Georg Brandl9afde1c2007-11-01 20:32:30 +00001042 Return the numeric string left filled with zeros in a string of length
1043 *width*. A sign prefix is handled correctly. The original string is
1044 returned if *width* is less than ``len(s)``.
Christian Heimesb186d002008-03-18 15:15:01 +00001045
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandl4b491312007-08-31 09:22:56 +00001048.. _old-string-formatting:
Georg Brandl116aa622007-08-15 14:28:22 +00001049
Georg Brandl4b491312007-08-31 09:22:56 +00001050Old String Formatting Operations
1051--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001052
1053.. index::
1054 single: formatting, string (%)
1055 single: interpolation, string (%)
1056 single: string; formatting
1057 single: string; interpolation
1058 single: printf-style formatting
1059 single: sprintf-style formatting
1060 single: % formatting
1061 single: % interpolation
1062
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001063.. XXX is the note enough?
Georg Brandl4b491312007-08-31 09:22:56 +00001064
1065.. note::
1066
Georg Brandl226878c2007-08-31 10:15:37 +00001067 The formatting operations described here are obsolete and may go away in future
Georg Brandl4b491312007-08-31 09:22:56 +00001068 versions of Python. Use the new :ref:`string-formatting` in new code.
1069
1070String objects have one unique built-in operation: the ``%`` operator (modulo).
1071This is also known as the string *formatting* or *interpolation* operator.
1072Given ``format % values`` (where *format* is a string), ``%`` conversion
1073specifications in *format* are replaced with zero or more elements of *values*.
1074The effect is similar to the using :cfunc:`sprintf` in the C language.
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076If *format* requires a single argument, *values* may be a single non-tuple
1077object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1078items specified by the format string, or a single mapping object (for example, a
1079dictionary).
1080
1081A conversion specifier contains two or more characters and has the following
1082components, which must occur in this order:
1083
1084#. The ``'%'`` character, which marks the start of the specifier.
1085
1086#. Mapping key (optional), consisting of a parenthesised sequence of characters
1087 (for example, ``(somename)``).
1088
1089#. Conversion flags (optional), which affect the result of some conversion
1090 types.
1091
1092#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1093 actual width is read from the next element of the tuple in *values*, and the
1094 object to convert comes after the minimum field width and optional precision.
1095
1096#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1097 specified as ``'*'`` (an asterisk), the actual width is read from the next
1098 element of the tuple in *values*, and the value to convert comes after the
1099 precision.
1100
1101#. Length modifier (optional).
1102
1103#. Conversion type.
1104
1105When the right argument is a dictionary (or other mapping type), then the
1106formats in the string *must* include a parenthesised mapping key into that
1107dictionary inserted immediately after the ``'%'`` character. The mapping key
Christian Heimesfe337bf2008-03-23 21:54:12 +00001108selects the value to be formatted from the mapping. For example:
Georg Brandl116aa622007-08-15 14:28:22 +00001109
Christian Heimesfe337bf2008-03-23 21:54:12 +00001110
1111 >>> print('%(language)s has %(#)03d quote types.' % \
1112 ... {'language': "Python", "#": 2})
Georg Brandl116aa622007-08-15 14:28:22 +00001113 Python has 002 quote types.
1114
1115In this case no ``*`` specifiers may occur in a format (since they require a
1116sequential parameter list).
1117
1118The conversion flag characters are:
1119
1120+---------+---------------------------------------------------------------------+
1121| Flag | Meaning |
1122+=========+=====================================================================+
1123| ``'#'`` | The value conversion will use the "alternate form" (where defined |
1124| | below). |
1125+---------+---------------------------------------------------------------------+
1126| ``'0'`` | The conversion will be zero padded for numeric values. |
1127+---------+---------------------------------------------------------------------+
1128| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1129| | conversion if both are given). |
1130+---------+---------------------------------------------------------------------+
1131| ``' '`` | (a space) A blank should be left before a positive number (or empty |
1132| | string) produced by a signed conversion. |
1133+---------+---------------------------------------------------------------------+
1134| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1135| | (overrides a "space" flag). |
1136+---------+---------------------------------------------------------------------+
1137
1138A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001139is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141The conversion types are:
1142
1143+------------+-----------------------------------------------------+-------+
1144| Conversion | Meaning | Notes |
1145+============+=====================================================+=======+
1146| ``'d'`` | Signed integer decimal. | |
1147+------------+-----------------------------------------------------+-------+
1148| ``'i'`` | Signed integer decimal. | |
1149+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001150| ``'o'`` | Signed octal value. | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +00001151+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001152| ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
Georg Brandl116aa622007-08-15 14:28:22 +00001153+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001154| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001155+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001156| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001157+------------+-----------------------------------------------------+-------+
1158| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1159+------------+-----------------------------------------------------+-------+
1160| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1161+------------+-----------------------------------------------------+-------+
1162| ``'f'`` | Floating point decimal format. | \(3) |
1163+------------+-----------------------------------------------------+-------+
1164| ``'F'`` | Floating point decimal format. | \(3) |
1165+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001166| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1167| | format if exponent is less than -4 or not less than | |
1168| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001169+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001170| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1171| | format if exponent is less than -4 or not less than | |
1172| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001173+------------+-----------------------------------------------------+-------+
1174| ``'c'`` | Single character (accepts integer or single | |
1175| | character string). | |
1176+------------+-----------------------------------------------------+-------+
1177| ``'r'`` | String (converts any python object using | \(5) |
1178| | :func:`repr`). | |
1179+------------+-----------------------------------------------------+-------+
Georg Brandl4b491312007-08-31 09:22:56 +00001180| ``'s'`` | String (converts any python object using | |
Georg Brandl116aa622007-08-15 14:28:22 +00001181| | :func:`str`). | |
1182+------------+-----------------------------------------------------+-------+
1183| ``'%'`` | No argument is converted, results in a ``'%'`` | |
1184| | character in the result. | |
1185+------------+-----------------------------------------------------+-------+
1186
1187Notes:
1188
1189(1)
1190 The alternate form causes a leading zero (``'0'``) to be inserted between
1191 left-hand padding and the formatting of the number if the leading character
1192 of the result is not already a zero.
1193
1194(2)
1195 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1196 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1197 and the formatting of the number if the leading character of the result is not
1198 already a zero.
1199
1200(3)
1201 The alternate form causes the result to always contain a decimal point, even if
1202 no digits follow it.
1203
1204 The precision determines the number of digits after the decimal point and
1205 defaults to 6.
1206
1207(4)
1208 The alternate form causes the result to always contain a decimal point, and
1209 trailing zeroes are not removed as they would otherwise be.
1210
1211 The precision determines the number of significant digits before and after the
1212 decimal point and defaults to 6.
1213
1214(5)
Georg Brandl116aa622007-08-15 14:28:22 +00001215 The precision determines the maximal number of characters used.
1216
Georg Brandl116aa622007-08-15 14:28:22 +00001217
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001218(7)
1219 See :pep:`237`.
1220
Georg Brandl116aa622007-08-15 14:28:22 +00001221Since Python strings have an explicit length, ``%s`` conversions do not assume
1222that ``'\0'`` is the end of the string.
1223
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001224.. XXX Examples?
1225
Georg Brandl116aa622007-08-15 14:28:22 +00001226For safety reasons, floating point precisions are clipped to 50; ``%f``
1227conversions for numbers whose absolute value is over 1e25 are replaced by ``%g``
1228conversions. [#]_ All other errors raise exceptions.
1229
1230.. index::
1231 module: string
1232 module: re
1233
1234Additional string operations are defined in standard modules :mod:`string` and
1235:mod:`re`.
1236
1237
1238.. _typesseq-range:
1239
Georg Brandl905ec322007-09-28 13:39:25 +00001240Range Type
1241----------
Georg Brandl116aa622007-08-15 14:28:22 +00001242
1243.. index:: object: range
1244
1245The :class:`range` type is an immutable sequence which is commonly used for
1246looping. The advantage of the :class:`range` type is that an :class:`range`
1247object will always take the same amount of memory, no matter the size of the
1248range it represents. There are no consistent performance advantages.
1249
Georg Brandl905ec322007-09-28 13:39:25 +00001250Range objects have very little behavior: they only support indexing, iteration,
Georg Brandl116aa622007-08-15 14:28:22 +00001251and the :func:`len` function.
1252
1253
1254.. _typesseq-mutable:
1255
1256Mutable Sequence Types
1257----------------------
1258
1259.. index::
1260 triple: mutable; sequence; types
1261 object: list
Georg Brandl95414632007-11-22 11:00:28 +00001262 object: bytearray
Georg Brandl116aa622007-08-15 14:28:22 +00001263
Georg Brandl95414632007-11-22 11:00:28 +00001264List and bytearray objects support additional operations that allow in-place
Georg Brandl226878c2007-08-31 10:15:37 +00001265modification of the object. Other mutable sequence types (when added to the
1266language) should also support these operations. Strings and tuples are
1267immutable sequence types: such objects cannot be modified once created. The
1268following operations are defined on mutable sequence types (where *x* is an
1269arbitrary object).
1270
Georg Brandl95414632007-11-22 11:00:28 +00001271Note that while lists allow their items to be of any type, bytearray object
Georg Brandl226878c2007-08-31 10:15:37 +00001272"items" are all integers in the range 0 <= x < 256.
Georg Brandl116aa622007-08-15 14:28:22 +00001273
1274+------------------------------+--------------------------------+---------------------+
1275| Operation | Result | Notes |
1276+==============================+================================+=====================+
1277| ``s[i] = x`` | item *i* of *s* is replaced by | |
1278| | *x* | |
1279+------------------------------+--------------------------------+---------------------+
1280| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1281| | is replaced by the contents of | |
1282| | the iterable *t* | |
1283+------------------------------+--------------------------------+---------------------+
1284| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1285+------------------------------+--------------------------------+---------------------+
1286| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1287| | are replaced by those of *t* | |
1288+------------------------------+--------------------------------+---------------------+
1289| ``del s[i:j:k]`` | removes the elements of | |
1290| | ``s[i:j:k]`` from the list | |
1291+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001292| ``s.append(x)`` | same as ``s[len(s):len(s)] = | |
Georg Brandl116aa622007-08-15 14:28:22 +00001293| | [x]`` | |
1294+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001295| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001296| | x`` | |
1297+------------------------------+--------------------------------+---------------------+
1298| ``s.count(x)`` | return number of *i*'s for | |
1299| | which ``s[i] == x`` | |
1300+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001301| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001302| | ``s[k] == x`` and ``i <= k < | |
1303| | j`` | |
1304+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001305| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) |
Georg Brandl116aa622007-08-15 14:28:22 +00001306+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001307| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001308| | return x`` | |
1309+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001310| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001311+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001312| ``s.reverse()`` | reverses the items of *s* in | \(6) |
Georg Brandl116aa622007-08-15 14:28:22 +00001313| | place | |
1314+------------------------------+--------------------------------+---------------------+
Raymond Hettinger7f732952008-02-14 13:34:38 +00001315| ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) |
Georg Brandl116aa622007-08-15 14:28:22 +00001316+------------------------------+--------------------------------+---------------------+
1317
1318.. index::
1319 triple: operations on; sequence; types
1320 triple: operations on; list; type
1321 pair: subscript; assignment
1322 pair: slice; assignment
Georg Brandl116aa622007-08-15 14:28:22 +00001323 statement: del
Georg Brandl226878c2007-08-31 10:15:37 +00001324 single: append() (sequence method)
1325 single: extend() (sequence method)
1326 single: count() (sequence method)
1327 single: index() (sequence method)
1328 single: insert() (sequence method)
1329 single: pop() (sequence method)
1330 single: remove() (sequence method)
1331 single: reverse() (sequence method)
1332 single: sort() (sequence method)
Georg Brandl116aa622007-08-15 14:28:22 +00001333
1334Notes:
1335
1336(1)
Georg Brandl226878c2007-08-31 10:15:37 +00001337 *t* must have the same length as the slice it is replacing.
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339(2)
Georg Brandl116aa622007-08-15 14:28:22 +00001340 *x* can be any iterable object.
1341
Georg Brandl226878c2007-08-31 10:15:37 +00001342(3)
Georg Brandl116aa622007-08-15 14:28:22 +00001343 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
Georg Brandl226878c2007-08-31 10:15:37 +00001344 passed as the second or third parameter to the :meth:`index` method, the sequence
Georg Brandl116aa622007-08-15 14:28:22 +00001345 length is added, as for slice indices. If it is still negative, it is truncated
1346 to zero, as for slice indices.
1347
Georg Brandl226878c2007-08-31 10:15:37 +00001348(4)
Georg Brandl116aa622007-08-15 14:28:22 +00001349 When a negative index is passed as the first parameter to the :meth:`insert`
Georg Brandl226878c2007-08-31 10:15:37 +00001350 method, the sequence length is added, as for slice indices. If it is still
Georg Brandl116aa622007-08-15 14:28:22 +00001351 negative, it is truncated to zero, as for slice indices.
1352
Georg Brandl226878c2007-08-31 10:15:37 +00001353(5)
1354 The optional argument *i* defaults to ``-1``, so that by default the last
1355 item is removed and returned.
1356
Georg Brandl116aa622007-08-15 14:28:22 +00001357(6)
Georg Brandl226878c2007-08-31 10:15:37 +00001358 The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for
1359 economy of space when sorting or reversing a large sequence. To remind you
1360 that they operate by side effect, they don't return the sorted or reversed
1361 sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001362
1363(7)
Georg Brandl116aa622007-08-15 14:28:22 +00001364 The :meth:`sort` method takes optional arguments for controlling the
Raymond Hettinger7f732952008-02-14 13:34:38 +00001365 comparisons. Each must be specified as a keyword argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001366
Georg Brandl116aa622007-08-15 14:28:22 +00001367 *key* specifies a function of one argument that is used to extract a comparison
Christian Heimesfaf2f632008-01-06 16:59:19 +00001368 key from each list element: ``key=str.lower``. The default value is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001369
1370 *reverse* is a boolean value. If set to ``True``, then the list elements are
1371 sorted as if each comparison were reversed.
1372
Raymond Hettinger71161862008-02-14 13:32:18 +00001373 The :meth:`sort` method is guaranteed to be stable. A
Georg Brandl116aa622007-08-15 14:28:22 +00001374 sort is stable if it guarantees not to change the relative order of elements
1375 that compare equal --- this is helpful for sorting in multiple passes (for
1376 example, sort by department, then by salary grade).
1377
Georg Brandl116aa622007-08-15 14:28:22 +00001378 While a list is being sorted, the effect of attempting to mutate, or even
Raymond Hettinger71161862008-02-14 13:32:18 +00001379 inspect, the list is undefined. The C implementation
Georg Brandl116aa622007-08-15 14:28:22 +00001380 makes the list appear empty for the duration, and raises :exc:`ValueError` if it
1381 can detect that the list has been mutated during a sort.
1382
Raymond Hettinger7f732952008-02-14 13:34:38 +00001383(8)
1384 :meth:`sort` is not supported by :class:`bytearray` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001385
Georg Brandl226878c2007-08-31 10:15:37 +00001386.. _bytes-methods:
1387
Georg Brandl95414632007-11-22 11:00:28 +00001388Bytes and Byte Array Methods
1389----------------------------
Georg Brandl226878c2007-08-31 10:15:37 +00001390
1391.. index:: pair: bytes; methods
Georg Brandl95414632007-11-22 11:00:28 +00001392 pair: bytearray; methods
Georg Brandl226878c2007-08-31 10:15:37 +00001393
Georg Brandl95414632007-11-22 11:00:28 +00001394Bytes and bytearray objects, being "strings of bytes", have all methods found on
Georg Brandl7c676132007-10-23 18:17:00 +00001395strings, with the exception of :func:`encode`, :func:`format` and
Guido van Rossum98297ee2007-11-06 21:34:58 +00001396:func:`isidentifier`, which do not make sense with these types. For converting
1397the objects to strings, they have a :func:`decode` method.
1398
1399Wherever one of these methods needs to interpret the bytes as characters
1400(e.g. the :func:`is...` methods), the ASCII character set is assumed.
Georg Brandl226878c2007-08-31 10:15:37 +00001401
Georg Brandl7c676132007-10-23 18:17:00 +00001402.. note::
Georg Brandl226878c2007-08-31 10:15:37 +00001403
Georg Brandl95414632007-11-22 11:00:28 +00001404 The methods on bytes and bytearray objects don't accept strings as their
Georg Brandl7c676132007-10-23 18:17:00 +00001405 arguments, just as the methods on strings don't accept bytes as their
1406 arguments. For example, you have to write ::
Georg Brandl226878c2007-08-31 10:15:37 +00001407
Georg Brandl7c676132007-10-23 18:17:00 +00001408 a = "abc"
1409 b = a.replace("a", "f")
1410
1411 and ::
1412
1413 a = b"abc"
1414 b = a.replace(b"a", b"f")
Georg Brandl226878c2007-08-31 10:15:37 +00001415
1416
Georg Brandl95414632007-11-22 11:00:28 +00001417The bytes and bytearray types have an additional class method:
Georg Brandl226878c2007-08-31 10:15:37 +00001418
1419.. method:: bytes.fromhex(string)
Georg Brandl18da8f02008-07-01 20:08:02 +00001420 bytearray.fromhex(string)
Georg Brandl226878c2007-08-31 10:15:37 +00001421
Georg Brandl18da8f02008-07-01 20:08:02 +00001422 This :class:`bytes` class method returns a bytes or bytearray object,
1423 decoding the given string object. The string must contain two hexadecimal
1424 digits per byte, spaces are ignored.
Georg Brandl226878c2007-08-31 10:15:37 +00001425
Georg Brandl18da8f02008-07-01 20:08:02 +00001426 >>> bytes.fromhex('f0 f1f2 ')
1427 b'\xf0\xf1\xf2'
Georg Brandl226878c2007-08-31 10:15:37 +00001428
Georg Brandl7c676132007-10-23 18:17:00 +00001429.. XXX verify/document translate() semantics!
Georg Brandl226878c2007-08-31 10:15:37 +00001430
Georg Brandl7c676132007-10-23 18:17:00 +00001431 .. method:: bytes.translate(table[, delete])
Georg Brandl226878c2007-08-31 10:15:37 +00001432
1433 Return a copy of the bytes object where all bytes occurring in the optional
Georg Brandl7f13e6b2007-08-31 10:37:15 +00001434 argument *delete* are removed, and the remaining bytes have been mapped
Georg Brandl226878c2007-08-31 10:15:37 +00001435 through the given translation table, which must be a bytes object of length
1436 256.
1437
1438 You can use the :func:`maketrans` helper function in the :mod:`string` module to
1439 create a translation table.
1440
1441 .. XXX a None table doesn't seem to be supported
Georg Brandl7f13e6b2007-08-31 10:37:15 +00001442 Set the *table* argument to ``None`` for translations that only delete characters::
Georg Brandl226878c2007-08-31 10:15:37 +00001443
1444 >>> 'read this short text'.translate(None, 'aeiou')
1445 'rd ths shrt txt'
1446
1447
Georg Brandl116aa622007-08-15 14:28:22 +00001448.. _types-set:
1449
1450Set Types --- :class:`set`, :class:`frozenset`
1451==============================================
1452
1453.. index:: object: set
1454
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001455A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001456Common uses include membership testing, removing duplicates from a sequence, and
1457computing mathematical operations such as intersection, union, difference, and
1458symmetric difference.
1459(For other containers see the built in :class:`dict`, :class:`list`,
1460and :class:`tuple` classes, and the :mod:`collections` module.)
1461
Georg Brandl116aa622007-08-15 14:28:22 +00001462Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1463set``. Being an unordered collection, sets do not record element position or
1464order of insertion. Accordingly, sets do not support indexing, slicing, or
1465other sequence-like behavior.
1466
1467There are currently two builtin set types, :class:`set` and :class:`frozenset`.
1468The :class:`set` type is mutable --- the contents can be changed using methods
1469like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1470and cannot be used as either a dictionary key or as an element of another set.
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001471The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
Georg Brandl116aa622007-08-15 14:28:22 +00001472altered after it is created; it can therefore be used as a dictionary key or as
1473an element of another set.
1474
1475The constructors for both classes work the same:
1476
1477.. class:: set([iterable])
1478 frozenset([iterable])
1479
1480 Return a new set or frozenset object whose elements are taken from
1481 *iterable*. The elements of a set must be hashable. To represent sets of
1482 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1483 not specified, a new empty set is returned.
1484
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001485 Instances of :class:`set` and :class:`frozenset` provide the following
1486 operations:
Georg Brandl116aa622007-08-15 14:28:22 +00001487
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001488 .. describe:: len(s)
Georg Brandl116aa622007-08-15 14:28:22 +00001489
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001490 Return the cardinality of set *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001491
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001492 .. describe:: x in s
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001494 Test *x* for membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001495
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001496 .. describe:: x not in s
Georg Brandl116aa622007-08-15 14:28:22 +00001497
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001498 Test *x* for non-membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001499
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001500 .. method:: isdisjoint(other)
Guido van Rossum58da9312007-11-10 23:39:45 +00001501
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001502 Return True if the set has no elements in common with *other*. Sets are
1503 disjoint if and only if their interesection is the empty set.
Guido van Rossum58da9312007-11-10 23:39:45 +00001504
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001505 .. method:: issubset(other)
1506 set <= other
Georg Brandl116aa622007-08-15 14:28:22 +00001507
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001508 Test whether every element in the set is in *other*.
Georg Brandl116aa622007-08-15 14:28:22 +00001509
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001510 .. method:: set < other
Georg Brandla6f52782007-09-01 15:49:30 +00001511
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001512 Test whether the set is a true subset of *other*, that is,
1513 ``set <= other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00001514
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001515 .. method:: issuperset(other)
1516 set >= other
Georg Brandl116aa622007-08-15 14:28:22 +00001517
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001518 Test whether every element in *other* is in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001519
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001520 .. method:: set > other
Georg Brandla6f52782007-09-01 15:49:30 +00001521
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001522 Test whether the set is a true superset of *other*, that is, ``set >=
1523 other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00001524
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001525 .. method:: union(other, ...)
1526 set | other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001527
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001528 Return a new set with elements from both sets.
Georg Brandl116aa622007-08-15 14:28:22 +00001529
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001530 .. method:: intersection(other, ...)
1531 set & other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00001532
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001533 Return a new set with elements common to both sets.
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001535 .. method:: difference(other, ...)
1536 set - other - ...
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001537
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001538 Return a new set with elements in the set that are not in the others.
Georg Brandl116aa622007-08-15 14:28:22 +00001539
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001540 .. method:: symmetric_difference(other)
1541 set ^ other
Georg Brandl116aa622007-08-15 14:28:22 +00001542
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001543 Return a new set with elements in either the set or *other* but not both.
Georg Brandl116aa622007-08-15 14:28:22 +00001544
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001545 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00001546
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001547 Return a new set with a shallow copy of *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001548
1549
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001550 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1551 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1552 :meth:`issuperset` methods will accept any iterable as an argument. In
1553 contrast, their operator based counterparts require their arguments to be
1554 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1555 in favor of the more readable ``set('abc').intersection('cbs')``.
Georg Brandl116aa622007-08-15 14:28:22 +00001556
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001557 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1558 sets are equal if and only if every element of each set is contained in the
1559 other (each is a subset of the other). A set is less than another set if and
1560 only if the first set is a proper subset of the second set (is a subset, but
1561 is not equal). A set is greater than another set if and only if the first set
1562 is a proper superset of the second set (is a superset, but is not equal).
Georg Brandl116aa622007-08-15 14:28:22 +00001563
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001564 Instances of :class:`set` are compared to instances of :class:`frozenset`
1565 based on their members. For example, ``set('abc') == frozenset('abc')``
1566 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
Georg Brandl116aa622007-08-15 14:28:22 +00001567
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001568 The subset and equality comparisons do not generalize to a complete ordering
1569 function. For example, any two disjoint sets are not equal and are not
1570 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1571 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1572 method.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001574 Since sets only define partial ordering (subset relationships), the output of
1575 the :meth:`list.sort` method is undefined for lists of sets.
Georg Brandl116aa622007-08-15 14:28:22 +00001576
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001577 Set elements, like dictionary keys, must be :term:`hashable`.
Georg Brandl116aa622007-08-15 14:28:22 +00001578
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001579 Binary operations that mix :class:`set` instances with :class:`frozenset`
1580 return the type of the first operand. For example: ``frozenset('ab') |
1581 set('bc')`` returns an instance of :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00001582
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001583 The following table lists operations available for :class:`set` that do not
1584 apply to immutable instances of :class:`frozenset`:
Georg Brandl116aa622007-08-15 14:28:22 +00001585
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001586 .. method:: update(other, ...)
1587 set |= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001588
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001589 Update the set, adding elements from *other*.
Georg Brandl116aa622007-08-15 14:28:22 +00001590
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001591 .. versionchanged:: 2.6
1592 Accepts multiple input iterables.
1593
1594 .. method:: intersection_update(other, ...)
1595 set &= other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00001596
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001597 Update the set, keeping only elements found in it and *other*.
Georg Brandl116aa622007-08-15 14:28:22 +00001598
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001599 .. versionchanged:: 2.6
1600 Accepts multiple input iterables.
1601
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001602 .. method:: difference_update(other, ...)
1603 set -= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001604
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001605 Update the set, removing elements found in others.
1606
1607 .. versionchanged:: 2.6
1608 Accepts multiple input iterables.
Georg Brandl116aa622007-08-15 14:28:22 +00001609
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001610 .. method:: symmetric_difference_update(other)
1611 set ^= other
Georg Brandl116aa622007-08-15 14:28:22 +00001612
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001613 Update the set, keeping only elements found in either set, but not in both.
Georg Brandl116aa622007-08-15 14:28:22 +00001614
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001615 .. method:: add(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00001616
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001617 Add element *elem* to the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001618
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001619 .. method:: remove(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00001620
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001621 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1622 not contained in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001623
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001624 .. method:: discard(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00001625
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001626 Remove element *elem* from the set if it is present.
Georg Brandl116aa622007-08-15 14:28:22 +00001627
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001628 .. method:: pop()
Georg Brandl116aa622007-08-15 14:28:22 +00001629
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001630 Remove and return an arbitrary element from the set. Raises
1631 :exc:`KeyError` if the set is empty.
Georg Brandl116aa622007-08-15 14:28:22 +00001632
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001633 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00001634
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001635 Remove all elements from the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001636
1637
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001638 Note, the non-operator versions of the :meth:`update`,
1639 :meth:`intersection_update`, :meth:`difference_update`, and
1640 :meth:`symmetric_difference_update` methods will accept any iterable as an
1641 argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001642
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001643 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1644 :meth:`discard` methods may be a set. To support searching for an equivalent
1645 frozenset, the *elem* set is temporarily mutated during the search and then
1646 restored. During the search, the *elem* set should not be read or mutated
1647 since it does not have a meaningful value.
Benjamin Peterson699adb92008-05-08 22:27:58 +00001648
Georg Brandl116aa622007-08-15 14:28:22 +00001649
1650.. _typesmapping:
1651
1652Mapping Types --- :class:`dict`
1653===============================
1654
1655.. index::
1656 object: mapping
1657 object: dictionary
1658 triple: operations on; mapping; types
1659 triple: operations on; dictionary; type
1660 statement: del
1661 builtin: len
1662
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001663A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1664Mappings are mutable objects. There is currently only one standard mapping
1665type, the :dfn:`dictionary`. (For other containers see the built in
1666:class:`list`, :class:`set`, and :class:`tuple` classes, and the
1667:mod:`collections` module.)
Georg Brandl116aa622007-08-15 14:28:22 +00001668
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001669A dictionary's keys are *almost* arbitrary values. Values that are not
1670:term:`hashable`, that is, values containing lists, dictionaries or other
1671mutable types (that are compared by value rather than by object identity) may
1672not be used as keys. Numeric types used for keys obey the normal rules for
1673numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1674then they can be used interchangeably to index the same dictionary entry. (Note
1675however, that since computers store floating-point numbers as approximations it
1676is usually unwise to use them as dictionary keys.)
Georg Brandl116aa622007-08-15 14:28:22 +00001677
1678Dictionaries can be created by placing a comma-separated list of ``key: value``
1679pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1680'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1681
1682.. class:: dict([arg])
1683
Georg Brandld22a8152007-09-04 17:43:37 +00001684 Return a new dictionary initialized from an optional positional argument or
1685 from a set of keyword arguments. If no arguments are given, return a new
1686 empty dictionary. If the positional argument *arg* is a mapping object,
1687 return a dictionary mapping the same keys to the same values as does the
1688 mapping object. Otherwise the positional argument must be a sequence, a
1689 container that supports iteration, or an iterator object. The elements of
1690 the argument must each also be of one of those kinds, and each must in turn
1691 contain exactly two objects. The first is used as a key in the new
1692 dictionary, and the second as the key's value. If a given key is seen more
1693 than once, the last value associated with it is retained in the new
1694 dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001695
1696 If keyword arguments are given, the keywords themselves with their associated
Georg Brandld22a8152007-09-04 17:43:37 +00001697 values are added as items to the dictionary. If a key is specified both in
1698 the positional argument and as a keyword argument, the value associated with
1699 the keyword is retained in the dictionary. For example, these all return a
Georg Brandl116aa622007-08-15 14:28:22 +00001700 dictionary equal to ``{"one": 2, "two": 3}``:
1701
1702 * ``dict(one=2, two=3)``
Georg Brandl116aa622007-08-15 14:28:22 +00001703 * ``dict({'one': 2, 'two': 3})``
Georg Brandl116aa622007-08-15 14:28:22 +00001704 * ``dict(zip(('one', 'two'), (2, 3)))``
Georg Brandl116aa622007-08-15 14:28:22 +00001705 * ``dict([['two', 3], ['one', 2]])``
1706
Georg Brandld22a8152007-09-04 17:43:37 +00001707 The first example only works for keys that are valid Python identifiers; the
1708 others work with any valid keys.
Georg Brandl116aa622007-08-15 14:28:22 +00001709
Georg Brandl116aa622007-08-15 14:28:22 +00001710
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001711 These are the operations that dictionaries support (and therefore, custom
1712 mapping types should support too):
Georg Brandl116aa622007-08-15 14:28:22 +00001713
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001714 .. describe:: len(d)
Georg Brandl116aa622007-08-15 14:28:22 +00001715
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001716 Return the number of items in the dictionary *d*.
Georg Brandl116aa622007-08-15 14:28:22 +00001717
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001718 .. describe:: d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00001719
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001720 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
1721 not in the map.
1722
1723 If a subclass of dict defines a method :meth:`__missing__`, if the key *key*
1724 is not present, the ``d[key]`` operation calls that method with the key *key*
1725 as argument. The ``d[key]`` operation then returns or raises whatever is
1726 returned or raised by the ``__missing__(key)`` call if the key is not
1727 present. No other operations or methods invoke :meth:`__missing__`. If
1728 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
1729 :meth:`__missing__` must be a method; it cannot be an instance variable. For
1730 an example, see :class:`collections.defaultdict`.
Georg Brandl116aa622007-08-15 14:28:22 +00001731
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001732 .. describe:: d[key] = value
Georg Brandl116aa622007-08-15 14:28:22 +00001733
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001734 Set ``d[key]`` to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00001735
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001736 .. describe:: del d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00001737
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001738 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1739 map.
Georg Brandl116aa622007-08-15 14:28:22 +00001740
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001741 .. describe:: key in d
Georg Brandl116aa622007-08-15 14:28:22 +00001742
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001743 Return ``True`` if *d* has a key *key*, else ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +00001744
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001745 .. describe:: key not in d
Georg Brandl116aa622007-08-15 14:28:22 +00001746
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001747 Equivalent to ``not key in d``.
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001749 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00001750
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001751 Remove all items from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001752
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001753 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00001754
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001755 Return a shallow copy of the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001756
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001757 .. method:: fromkeys(seq[, value])
Georg Brandl116aa622007-08-15 14:28:22 +00001758
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001759 Create a new dictionary with keys from *seq* and values set to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00001760
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001761 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
1762 defaults to ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001763
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001764 .. method:: get(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00001765
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001766 Return the value for *key* if *key* is in the dictionary, else *default*.
1767 If *default* is not given, it defaults to ``None``, so that this method
1768 never raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001769
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001770 .. method:: items()
Georg Brandl116aa622007-08-15 14:28:22 +00001771
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001772 Return a new view of the dictionary's items (``(key, value)`` pairs). See
1773 below for documentation of view objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001774
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001775 .. method:: keys()
Georg Brandl116aa622007-08-15 14:28:22 +00001776
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001777 Return a new view of the dictionary's keys. See below for documentation of
1778 view objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001779
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001780 .. method:: pop(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00001781
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001782 If *key* is in the dictionary, remove it and return its value, else return
1783 *default*. If *default* is not given and *key* is not in the dictionary,
1784 a :exc:`KeyError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001785
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001786 .. method:: popitem()
Georg Brandl116aa622007-08-15 14:28:22 +00001787
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001788 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001789
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001790 :meth:`popitem` is useful to destructively iterate over a dictionary, as
1791 often used in set algorithms. If the dictionary is empty, calling
1792 :meth:`popitem` raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001793
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001794 .. method:: setdefault(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00001795
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001796 If *key* is in the dictionary, return its value. If not, insert *key*
1797 with a value of *default* and return *default*. *default* defaults to
1798 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001799
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001800 .. method:: update([other])
Georg Brandl116aa622007-08-15 14:28:22 +00001801
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001802 Update the dictionary with the key/value pairs from *other*, overwriting
1803 existing keys. Return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001804
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001805 :meth:`update` accepts either another dictionary object or an iterable of
1806 key/value pairs (as a tuple or other iterable of length two). If keyword
1807 arguments are specified, the dictionary is then is updated with those
1808 key/value pairs: ``d.update(red=1, blue=2)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001809
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001810 .. method:: values()
Georg Brandl116aa622007-08-15 14:28:22 +00001811
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001812 Return a new view of the dictionary's values. See below for documentation of
1813 view objects.
Georg Brandld22a8152007-09-04 17:43:37 +00001814
1815
1816Dictionary view objects
1817-----------------------
1818
1819The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
1820:meth:`dict.items` are *view objects*. They provide a dynamic view on the
1821dictionary's entries, which means that when the dictionary changes, the view
1822reflects these changes. The keys and items views have a set-like character
1823since their entries
1824
1825Dictionary views can be iterated over to yield their respective data, and
1826support membership tests:
1827
1828.. describe:: len(dictview)
1829
1830 Return the number of entries in the dictionary.
1831
1832.. describe:: iter(dictview)
1833
1834 Return an iterator over the keys, values or items (represented as tuples of
1835 ``(key, value)``) in the dictionary.
1836
1837 Keys and values are iterated over in an arbitrary order which is non-random,
1838 varies across Python implementations, and depends on the dictionary's history
1839 of insertions and deletions. If keys, values and items views are iterated
1840 over with no intervening modifications to the dictionary, the order of items
1841 will directly correspond. This allows the creation of ``(value, key)`` pairs
1842 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
1843 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
1844
1845.. describe:: x in dictview
1846
1847 Return ``True`` if *x* is in the underlying dictionary's keys, values or
1848 items (in the latter case, *x* should be a ``(key, value)`` tuple).
1849
1850
1851The keys and items views also provide set-like operations ("other" here refers
1852to another dictionary view or a set):
1853
1854.. describe:: dictview & other
1855
1856 Return the intersection of the dictview and the other object as a new set.
1857
1858.. describe:: dictview | other
1859
1860 Return the union of the dictview and the other object as a new set.
1861
1862.. describe:: dictview - other
1863
1864 Return the difference between the dictview and the other object (all elements
1865 in *dictview* that aren't in *other*) as a new set.
1866
1867.. describe:: dictview ^ other
1868
1869 Return the symmetric difference (all elements either in *dictview* or
1870 *other*, but not in both) of the dictview and the other object as a new set.
1871
1872.. warning::
1873
1874 Since a dictionary's values are not required to be hashable, any of these
1875 four operations will fail if an involved dictionary contains such a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001876
1877
Georg Brandlc53c9662007-09-04 17:58:02 +00001878An example of dictionary view usage::
1879
1880 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
1881 >>> keys = dishes.keys()
1882 >>> values = dishes.values()
1883
1884 >>> # iteration
1885 >>> n = 0
1886 >>> for val in values:
1887 ... n += val
1888 >>> print(n)
1889 504
1890
1891 >>> # keys and values are iterated over in the same order
1892 >>> list(keys)
1893 ['eggs', 'bacon', 'sausage', 'spam']
1894 >>> list(values)
1895 [2, 1, 1, 500]
1896
1897 >>> # view objects are dynamic and reflect dict changes
1898 >>> del dishes['eggs']
1899 >>> del dishes['sausage']
1900 >>> list(keys)
1901 ['spam', 'bacon']
1902
1903 >>> # set operations
1904 >>> keys & {'eggs', 'bacon', 'salad'}
1905 {'eggs', 'bacon'}
1906
1907
Georg Brandl116aa622007-08-15 14:28:22 +00001908.. _bltin-file-objects:
1909
1910File Objects
1911============
1912
1913.. index::
1914 object: file
1915 builtin: file
1916 module: os
1917 module: socket
1918
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001919.. XXX this is quite out of date, must be updated with "io" module
1920
Georg Brandl116aa622007-08-15 14:28:22 +00001921File objects are implemented using C's ``stdio`` package and can be
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001922created with the built-in :func:`open` function. File
Georg Brandl116aa622007-08-15 14:28:22 +00001923objects are also returned by some other built-in functions and methods,
1924such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001925method of socket objects. Temporary files can be created using the
1926:mod:`tempfile` module, and high-level file operations such as copying,
1927moving, and deleting files and directories can be achieved with the
1928:mod:`shutil` module.
Georg Brandl116aa622007-08-15 14:28:22 +00001929
1930When a file operation fails for an I/O-related reason, the exception
1931:exc:`IOError` is raised. This includes situations where the operation is not
1932defined for some reason, like :meth:`seek` on a tty device or writing a file
1933opened for reading.
1934
1935Files have the following methods:
1936
1937
1938.. method:: file.close()
1939
1940 Close the file. A closed file cannot be read or written any more. Any operation
1941 which requires that the file be open will raise a :exc:`ValueError` after the
1942 file has been closed. Calling :meth:`close` more than once is allowed.
1943
Georg Brandle6bcc912008-05-12 18:05:20 +00001944 You can avoid having to call this method explicitly if you use
Georg Brandl116aa622007-08-15 14:28:22 +00001945 the :keyword:`with` statement. For example, the following code will
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001946 automatically close *f* when the :keyword:`with` block is exited::
Georg Brandl116aa622007-08-15 14:28:22 +00001947
1948 from __future__ import with_statement
1949
1950 with open("hello.txt") as f:
1951 for line in f:
Collin Winterc79461b2007-09-01 23:34:30 +00001952 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +00001953
1954 In older versions of Python, you would have needed to do this to get the same
1955 effect::
1956
1957 f = open("hello.txt")
1958 try:
1959 for line in f:
Collin Winterc79461b2007-09-01 23:34:30 +00001960 print(line)
Georg Brandl116aa622007-08-15 14:28:22 +00001961 finally:
1962 f.close()
1963
1964 .. note::
1965
1966 Not all "file-like" types in Python support use as a context manager for the
1967 :keyword:`with` statement. If your code is intended to work with any file-like
1968 object, you can use the function :func:`contextlib.closing` instead of using
1969 the object directly.
1970
1971
1972.. method:: file.flush()
1973
1974 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
1975 no-op on some file-like objects.
1976
1977
1978.. method:: file.fileno()
1979
1980 .. index::
Georg Brandl9afde1c2007-11-01 20:32:30 +00001981 pair: file; descriptor
Georg Brandl116aa622007-08-15 14:28:22 +00001982 module: fcntl
1983
1984 Return the integer "file descriptor" that is used by the underlying
1985 implementation to request I/O operations from the operating system. This can be
1986 useful for other, lower level interfaces that use file descriptors, such as the
1987 :mod:`fcntl` module or :func:`os.read` and friends.
1988
1989 .. note::
1990
1991 File-like objects which do not have a real file descriptor should *not* provide
1992 this method!
1993
1994
1995.. method:: file.isatty()
1996
1997 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
1998
1999 .. note::
2000
2001 If a file-like object is not associated with a real file, this method should
2002 *not* be implemented.
2003
2004
2005.. method:: file.__next__()
2006
2007 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2008 *f* is closed). When a file is used as an iterator, typically in a
Georg Brandl6911e3c2007-09-04 07:15:32 +00002009 :keyword:`for` loop (for example, ``for line in f: print(line)``), the
Georg Brandl116aa622007-08-15 14:28:22 +00002010 :meth:`__next__` method is called repeatedly. This method returns the next
2011 input line, or raises :exc:`StopIteration` when EOF is hit when the file is open
2012 for reading (behavior is undefined when the file is open for writing). In order
2013 to make a :keyword:`for` loop the most efficient way of looping over the lines
2014 of a file (a very common operation), the :meth:`__next__` method uses a hidden
2015 read-ahead buffer. As a consequence of using a read-ahead buffer, combining
2016 :meth:`__next__` with other file methods (like :meth:`readline`) does not work
2017 right. However, using :meth:`seek` to reposition the file to an absolute
2018 position will flush the read-ahead buffer.
2019
Georg Brandl116aa622007-08-15 14:28:22 +00002020
2021.. method:: file.read([size])
2022
2023 Read at most *size* bytes from the file (less if the read hits EOF before
2024 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2025 all data until EOF is reached. The bytes are returned as a string object. An
2026 empty string is returned when EOF is encountered immediately. (For certain
2027 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2028 that this method may call the underlying C function :cfunc:`fread` more than
2029 once in an effort to acquire as close to *size* bytes as possible. Also note
Georg Brandl86b2fb92008-07-16 03:43:04 +00002030 that when in non-blocking mode, less data than was requested may be
Georg Brandl116aa622007-08-15 14:28:22 +00002031 returned, even if no *size* parameter was given.
2032
2033
2034.. method:: file.readline([size])
2035
2036 Read one entire line from the file. A trailing newline character is kept in the
2037 string (but may be absent when a file ends with an incomplete line). [#]_ If
2038 the *size* argument is present and non-negative, it is a maximum byte count
2039 (including the trailing newline) and an incomplete line may be returned. An
2040 empty string is returned *only* when EOF is encountered immediately.
2041
2042 .. note::
2043
2044 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
2045 (``'\0'``) if they occurred in the input.
2046
2047
2048.. method:: file.readlines([sizehint])
2049
2050 Read until EOF using :meth:`readline` and return a list containing the lines
2051 thus read. If the optional *sizehint* argument is present, instead of
2052 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2053 (possibly after rounding up to an internal buffer size) are read. Objects
2054 implementing a file-like interface may choose to ignore *sizehint* if it
2055 cannot be implemented, or cannot be implemented efficiently.
2056
2057
2058.. method:: file.seek(offset[, whence])
2059
2060 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
2061 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2062 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2063 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
Christian Heimesfaf2f632008-01-06 16:59:19 +00002064 end). There is no return value.
2065
2066 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2067 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2068
2069 Note that if the file is opened for appending
Georg Brandl116aa622007-08-15 14:28:22 +00002070 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2071 next write. If the file is only opened for writing in append mode (mode
2072 ``'a'``), this method is essentially a no-op, but it remains useful for files
2073 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2074 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2075 legal. Use of other offsets causes undefined behavior.
2076
2077 Note that not all file objects are seekable.
2078
Georg Brandl116aa622007-08-15 14:28:22 +00002079
2080.. method:: file.tell()
2081
2082 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2083
2084 .. note::
2085
2086 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
2087 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2088 circumvent this problem.
2089
2090
2091.. method:: file.truncate([size])
2092
2093 Truncate the file's size. If the optional *size* argument is present, the file
2094 is truncated to (at most) that size. The size defaults to the current position.
2095 The current file position is not changed. Note that if a specified size exceeds
2096 the file's current size, the result is platform-dependent: possibilities
2097 include that the file may remain unchanged, increase to the specified size as if
2098 zero-filled, or increase to the specified size with undefined new content.
2099 Availability: Windows, many Unix variants.
2100
2101
2102.. method:: file.write(str)
2103
Georg Brandl38889802008-03-21 19:42:31 +00002104 Write a string to the file. Due to buffering, the string may not actually
2105 show up in the file until the :meth:`flush` or :meth:`close` method is
2106 called.
2107
2108 The meaning of the return value is not defined for every file-like object.
2109 Some (mostly low-level) file-like objects may return the number of bytes
2110 actually written, others return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002111
2112
2113.. method:: file.writelines(sequence)
2114
2115 Write a sequence of strings to the file. The sequence can be any iterable
2116 object producing strings, typically a list of strings. There is no return value.
2117 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2118 add line separators.)
2119
2120Files support the iterator protocol. Each iteration returns the same result as
2121``file.readline()``, and iteration ends when the :meth:`readline` method returns
2122an empty string.
2123
2124File objects also offer a number of other interesting attributes. These are not
2125required for file-like objects, but should be implemented if they make sense for
2126the particular object.
2127
2128
2129.. attribute:: file.closed
2130
2131 bool indicating the current state of the file object. This is a read-only
2132 attribute; the :meth:`close` method changes the value. It may not be available
2133 on all file-like objects.
2134
2135
Georg Brandl4b491312007-08-31 09:22:56 +00002136.. XXX does this still apply?
Georg Brandl116aa622007-08-15 14:28:22 +00002137.. attribute:: file.encoding
2138
Georg Brandlf6945182008-02-01 11:56:49 +00002139 The encoding that this file uses. When strings are written to a file,
Georg Brandl116aa622007-08-15 14:28:22 +00002140 they will be converted to byte strings using this encoding. In addition, when
2141 the file is connected to a terminal, the attribute gives the encoding that the
2142 terminal is likely to use (that information might be incorrect if the user has
2143 misconfigured the terminal). The attribute is read-only and may not be present
2144 on all file-like objects. It may also be ``None``, in which case the file uses
Georg Brandlf6945182008-02-01 11:56:49 +00002145 the system default encoding for converting strings.
Georg Brandl116aa622007-08-15 14:28:22 +00002146
Georg Brandl116aa622007-08-15 14:28:22 +00002147
Benjamin Petersondcf97b92008-07-02 17:30:14 +00002148.. attribute:: file.errors
2149
2150 The Unicode error handler used along with the encoding.
2151
2152
Georg Brandl116aa622007-08-15 14:28:22 +00002153.. attribute:: file.mode
2154
2155 The I/O mode for the file. If the file was created using the :func:`open`
2156 built-in function, this will be the value of the *mode* parameter. This is a
2157 read-only attribute and may not be present on all file-like objects.
2158
2159
2160.. attribute:: file.name
2161
2162 If the file object was created using :func:`open`, the name of the file.
2163 Otherwise, some string that indicates the source of the file object, of the
2164 form ``<...>``. This is a read-only attribute and may not be present on all
2165 file-like objects.
2166
2167
2168.. attribute:: file.newlines
2169
2170 If Python was built with the :option:`--with-universal-newlines` option to
2171 :program:`configure` (the default) this read-only attribute exists, and for
2172 files opened in universal newline read mode it keeps track of the types of
2173 newlines encountered while reading the file. The values it can take are
2174 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2175 tuple containing all the newline types seen, to indicate that multiple newline
2176 conventions were encountered. For files not opened in universal newline read
2177 mode the value of this attribute will be ``None``.
2178
2179
Georg Brandl116aa622007-08-15 14:28:22 +00002180.. _typecontextmanager:
2181
2182Context Manager Types
2183=====================
2184
Georg Brandl116aa622007-08-15 14:28:22 +00002185.. index::
2186 single: context manager
2187 single: context management protocol
2188 single: protocol; context management
2189
2190Python's :keyword:`with` statement supports the concept of a runtime context
2191defined by a context manager. This is implemented using two separate methods
2192that allow user-defined classes to define a runtime context that is entered
2193before the statement body is executed and exited when the statement ends.
2194
2195The :dfn:`context management protocol` consists of a pair of methods that need
2196to be provided for a context manager object to define a runtime context:
2197
2198
2199.. method:: contextmanager.__enter__()
2200
2201 Enter the runtime context and return either this object or another object
2202 related to the runtime context. The value returned by this method is bound to
2203 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2204 this context manager.
2205
2206 An example of a context manager that returns itself is a file object. File
2207 objects return themselves from __enter__() to allow :func:`open` to be used as
2208 the context expression in a :keyword:`with` statement.
2209
2210 An example of a context manager that returns a related object is the one
Christian Heimesfaf2f632008-01-06 16:59:19 +00002211 returned by :func:`decimal.localcontext`. These managers set the active
Georg Brandl116aa622007-08-15 14:28:22 +00002212 decimal context to a copy of the original decimal context and then return the
2213 copy. This allows changes to be made to the current decimal context in the body
2214 of the :keyword:`with` statement without affecting code outside the
2215 :keyword:`with` statement.
2216
2217
2218.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2219
Georg Brandl9afde1c2007-11-01 20:32:30 +00002220 Exit the runtime context and return a Boolean flag indicating if any exception
Georg Brandl116aa622007-08-15 14:28:22 +00002221 that occurred should be suppressed. If an exception occurred while executing the
2222 body of the :keyword:`with` statement, the arguments contain the exception type,
2223 value and traceback information. Otherwise, all three arguments are ``None``.
2224
2225 Returning a true value from this method will cause the :keyword:`with` statement
2226 to suppress the exception and continue execution with the statement immediately
2227 following the :keyword:`with` statement. Otherwise the exception continues
2228 propagating after this method has finished executing. Exceptions that occur
2229 during execution of this method will replace any exception that occurred in the
2230 body of the :keyword:`with` statement.
2231
2232 The exception passed in should never be reraised explicitly - instead, this
2233 method should return a false value to indicate that the method completed
2234 successfully and does not want to suppress the raised exception. This allows
2235 context management code (such as ``contextlib.nested``) to easily detect whether
2236 or not an :meth:`__exit__` method has actually failed.
2237
2238Python defines several context managers to support easy thread synchronisation,
2239prompt closure of files or other objects, and simpler manipulation of the active
2240decimal arithmetic context. The specific types are not treated specially beyond
2241their implementation of the context management protocol. See the
2242:mod:`contextlib` module for some examples.
2243
Christian Heimesd8654cf2007-12-02 15:22:16 +00002244Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
2245provide a convenient way to implement these protocols. If a generator function is
Georg Brandl116aa622007-08-15 14:28:22 +00002246decorated with the ``contextlib.contextfactory`` decorator, it will return a
2247context manager implementing the necessary :meth:`__enter__` and
2248:meth:`__exit__` methods, rather than the iterator produced by an undecorated
2249generator function.
2250
2251Note that there is no specific slot for any of these methods in the type
2252structure for Python objects in the Python/C API. Extension types wanting to
2253define these methods must provide them as a normal Python accessible method.
2254Compared to the overhead of setting up the runtime context, the overhead of a
2255single class dictionary lookup is negligible.
2256
2257
2258.. _typesother:
2259
2260Other Built-in Types
2261====================
2262
2263The interpreter supports several other kinds of objects. Most of these support
2264only one or two operations.
2265
2266
2267.. _typesmodules:
2268
2269Modules
2270-------
2271
2272The only special operation on a module is attribute access: ``m.name``, where
2273*m* is a module and *name* accesses a name defined in *m*'s symbol table.
2274Module attributes can be assigned to. (Note that the :keyword:`import`
2275statement is not, strictly speaking, an operation on a module object; ``import
2276foo`` does not require a module object named *foo* to exist, rather it requires
2277an (external) *definition* for a module named *foo* somewhere.)
2278
2279A special member of every module is :attr:`__dict__`. This is the dictionary
2280containing the module's symbol table. Modifying this dictionary will actually
2281change the module's symbol table, but direct assignment to the :attr:`__dict__`
2282attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2283``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2284:attr:`__dict__` directly is not recommended.
2285
2286Modules built into the interpreter are written like this: ``<module 'sys'
2287(built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2288'/usr/local/lib/pythonX.Y/os.pyc'>``.
2289
2290
2291.. _typesobjects:
2292
2293Classes and Class Instances
2294---------------------------
2295
2296See :ref:`objects` and :ref:`class` for these.
2297
2298
2299.. _typesfunctions:
2300
2301Functions
2302---------
2303
2304Function objects are created by function definitions. The only operation on a
2305function object is to call it: ``func(argument-list)``.
2306
2307There are really two flavors of function objects: built-in functions and
2308user-defined functions. Both support the same operation (to call the function),
2309but the implementation is different, hence the different object types.
2310
2311See :ref:`function` for more information.
2312
2313
2314.. _typesmethods:
2315
2316Methods
2317-------
2318
2319.. index:: object: method
2320
2321Methods are functions that are called using the attribute notation. There are
2322two flavors: built-in methods (such as :meth:`append` on lists) and class
2323instance methods. Built-in methods are described with the types that support
2324them.
2325
Georg Brandl2e0b7552007-11-27 12:43:08 +00002326If you access a method (a function defined in a class namespace) through an
2327instance, you get a special object: a :dfn:`bound method` (also called
2328:dfn:`instance method`) object. When called, it will add the ``self`` argument
2329to the argument list. Bound methods have two special read-only attributes:
2330``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
2331the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
2332is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
2333arg-n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002334
Georg Brandl2e0b7552007-11-27 12:43:08 +00002335Like function objects, bound method objects support getting arbitrary
2336attributes. However, since method attributes are actually stored on the
2337underlying function object (``meth.__func__``), setting method attributes on
2338bound methods is disallowed. Attempting to set a method attribute results in a
Georg Brandl116aa622007-08-15 14:28:22 +00002339:exc:`TypeError` being raised. In order to set a method attribute, you need to
2340explicitly set it on the underlying function object::
2341
2342 class C:
2343 def method(self):
2344 pass
2345
2346 c = C()
Christian Heimesff737952007-11-27 10:40:20 +00002347 c.method.__func__.whoami = 'my name is c'
Georg Brandl116aa622007-08-15 14:28:22 +00002348
2349See :ref:`types` for more information.
2350
2351
2352.. _bltin-code-objects:
2353
2354Code Objects
2355------------
2356
2357.. index:: object: code
2358
2359.. index::
2360 builtin: compile
2361 single: __code__ (function object attribute)
2362
2363Code objects are used by the implementation to represent "pseudo-compiled"
2364executable Python code such as a function body. They differ from function
2365objects because they don't contain a reference to their global execution
2366environment. Code objects are returned by the built-in :func:`compile` function
2367and can be extracted from function objects through their :attr:`__code__`
2368attribute. See also the :mod:`code` module.
2369
2370.. index::
2371 builtin: exec
2372 builtin: eval
2373
2374A code object can be executed or evaluated by passing it (instead of a source
2375string) to the :func:`exec` or :func:`eval` built-in functions.
2376
2377See :ref:`types` for more information.
2378
2379
2380.. _bltin-type-objects:
2381
2382Type Objects
2383------------
2384
2385.. index::
2386 builtin: type
2387 module: types
2388
2389Type objects represent the various object types. An object's type is accessed
2390by the built-in function :func:`type`. There are no special operations on
2391types. The standard module :mod:`types` defines names for all standard built-in
2392types.
2393
Martin v. Löwis250ad612008-04-07 05:43:42 +00002394Types are written like this: ``<class 'int'>``.
Georg Brandl116aa622007-08-15 14:28:22 +00002395
2396
2397.. _bltin-null-object:
2398
2399The Null Object
2400---------------
2401
2402This object is returned by functions that don't explicitly return a value. It
2403supports no special operations. There is exactly one null object, named
2404``None`` (a built-in name).
2405
2406It is written as ``None``.
2407
2408
2409.. _bltin-ellipsis-object:
2410
2411The Ellipsis Object
2412-------------------
2413
Georg Brandlcb8ecb12007-09-04 06:35:14 +00002414This object is commonly used by slicing (see :ref:`slicings`). It supports no
2415special operations. There is exactly one ellipsis object, named
Georg Brandl116aa622007-08-15 14:28:22 +00002416:const:`Ellipsis` (a built-in name).
2417
2418It is written as ``Ellipsis`` or ``...``.
2419
2420
2421Boolean Values
2422--------------
2423
2424Boolean values are the two constant objects ``False`` and ``True``. They are
2425used to represent truth values (although other values can also be considered
2426false or true). In numeric contexts (for example when used as the argument to
2427an arithmetic operator), they behave like the integers 0 and 1, respectively.
2428The built-in function :func:`bool` can be used to cast any value to a Boolean,
2429if the value can be interpreted as a truth value (see section Truth Value
2430Testing above).
2431
2432.. index::
2433 single: False
2434 single: True
2435 pair: Boolean; values
2436
2437They are written as ``False`` and ``True``, respectively.
2438
2439
2440.. _typesinternal:
2441
2442Internal Objects
2443----------------
2444
2445See :ref:`types` for this information. It describes stack frame objects,
2446traceback objects, and slice objects.
2447
2448
2449.. _specialattrs:
2450
2451Special Attributes
2452==================
2453
2454The implementation adds a few special read-only attributes to several object
2455types, where they are relevant. Some of these are not reported by the
2456:func:`dir` built-in function.
2457
2458
2459.. attribute:: object.__dict__
2460
2461 A dictionary or other mapping object used to store an object's (writable)
2462 attributes.
2463
2464
2465.. attribute:: instance.__class__
2466
2467 The class to which a class instance belongs.
2468
2469
2470.. attribute:: class.__bases__
2471
2472 The tuple of base classes of a class object. If there are no base classes, this
2473 will be an empty tuple.
2474
2475
2476.. attribute:: class.__name__
2477
2478 The name of the class or type.
2479
2480.. rubric:: Footnotes
2481
2482.. [#] Additional information on these special methods may be found in the Python
2483 Reference Manual (:ref:`customization`).
2484
2485.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2486 similarly for tuples.
2487
2488.. [#] They must have since the parser can't tell the type of the operands.
2489
2490.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2491 element is the tuple to be formatted.
2492
2493.. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
2494 strings of meaningless digits without hampering correct use and without having
2495 to know the exact precision of floating point values on a particular machine.
2496
Georg Brandl116aa622007-08-15 14:28:22 +00002497.. [#] The advantage of leaving the newline on is that returning an empty string is
2498 then an unambiguous EOF indication. It is also possible (in cases where it
2499 might matter, for example, if you want to make an exact copy of a file while
2500 scanning its lines) to tell whether the last line of a file ended in a newline
2501 or not (yes this happens!).