rest25/library/stdtypes.rst => rest262/library/stdtypes.rst
n1+.. XXX: reference/datamodel and this have quite a few overlaps!
1
n3+ 
2-.. _types:
4+.. _bltin-types:
3
4**************
5Built-in Types
6**************
7
8The following sections describe the standard types that are built into the
9interpreter.
10
11.. note::
12
13   Historically (until release 2.2), Python's built-in types have differed from
14   user-defined types because it was not possible to use the built-in types as the
n15-   basis for object-oriented inheritance. This limitation does noexist any
n17+   basis for object-oriented inheritance. This limitation no longer
16-   longer.
18+   exists.
17
18.. index:: pair: built-in; types
19
20The principal built-in types are numerics, sequences, mappings, files, classes,
21instances and exceptions.
22
23.. index:: statement: print
24
25Some operations are supported by several object types; in particular,
26practically all objects can be compared, tested for truth value, and converted
27to a string (with the :func:`repr` function or the slightly different
28:func:`str` function).  The latter function is implicitly used when an object is
n29-written by the :keyword:`print` statement. (Information on the :keyword:`print`
n31+written by the :func:`print` function.
30-statement (XXX reference: ../ref/print.html) and other language statements can
31-be found in the Python Reference Manual (XXX reference: ../ref/ref.html) and the
32-Python Tutorial (XXX reference: ../tut/tut.html).)
33
34
35.. _truth:
36
37Truth Value Testing
38===================
39
40.. index::
93These are the Boolean operations, ordered by ascending priority:
94
95+-------------+---------------------------------+-------+
96| Operation   | Result                          | Notes |
97+=============+=================================+=======+
98| ``x or y``  | if *x* is false, then *y*, else | \(1)  |
99|             | *x*                             |       |
100+-------------+---------------------------------+-------+
n101-| ``x and y`` | if *x* is false, then *x*, else | \(1)  |
n100+| ``x and y`` | if *x* is false, then *x*, else | \(2)  |
102|             | *y*                             |       |
103+-------------+---------------------------------+-------+
n104-| ``not x``   | if *x* is false, then ``True``, | \(2)  |
n103+| ``not x``   | if *x* is false, then ``True``, | \(3)  |
105|             | else ``False``                  |       |
106+-------------+---------------------------------+-------+
107
108.. index::
109   operator: and
110   operator: or
111   operator: not
112
113Notes:
114
115(1)
n116-   These only evaluate their second argument if needed for their outcome.
n115+   This is a short-circuit operator, so it only evaluates the second
116+   argument if the first one is :const:`False`.
117
118(2)
n119+   This is a short-circuit operator, so it only evaluates the second
120+   argument if the first one is :const:`True`.
121+ 
122+(3)
119   ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
120   interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
121
122
n123-.. _comparisons:
n127+.. _stdcomparisons:
124
125Comparisons
126===========
127
128.. index:: pair: chaining; comparisons
129
130Comparison operations are supported by all objects.  They all have the same
131priority (which is higher than that of the Boolean operations). Comparisons can
145| ``>``      | strictly greater than   |       |
146+------------+-------------------------+-------+
147| ``>=``     | greater than or equal   |       |
148+------------+-------------------------+-------+
149| ``==``     | equal                   |       |
150+------------+-------------------------+-------+
151| ``!=``     | not equal               | \(1)  |
152+------------+-------------------------+-------+
n153-| ``<>``     | not equal               | \(1)  |
154-+------------+-------------------------+-------+
155| ``is``     | object identity         |       |
156+------------+-------------------------+-------+
157| ``is not`` | negated object identity |       |
158+------------+-------------------------+-------+
159
160.. index::
161   pair: operator; comparison
162   operator: ==
n165+   operator: <
166+   operator: <=
167+   operator: >
168+   operator: >=
169+   operator: !=
163   operator: is
164   operator: is not
165
n166-.. % XXX *All* others have funny characters < ! >
167- 
168Notes:
169
170(1)
n171-   ``<>`` and ``!=`` are alternate spellings for the same operator. ``!=`` is the
n176+    ``!=`` can also be written ``<>``, but this is an obsolete usage
172-   preferred spelling; ``<>`` is obsolescent.
177+    kept for backwards compatibility only. New code should always use
178+    ``!=``.
173
174.. index::
175   pair: object; numeric
176   pair: objects; comparing
177
178Objects of different types, except different numeric types and different string
179types, never compare equal; such objects are ordered consistently but
180arbitrarily (so that sorting a heterogeneous array yields a consistent result).
181Furthermore, some types (for example, file objects) support only a degenerate
182notion of comparison where any two objects of that type are unequal.  Again,
183such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
184and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
185a complex number.
186
187.. index:: single: __cmp__() (instance method)
188
n189-Instances of a class normally compare as non-equal unless the class  defines the
n195+Instances of a class normally compare as non-equal unless the class defines the
190-:meth:`__cmp__` method.  Refer to the Python Reference Manual (XXX reference:
196+:meth:`__cmp__` method.  Refer to :ref:`customization`) for information on the
191-../ref/customization.html) for information on the use of this method to effect
197+use of this method to effect object comparisons.
192-object comparisons.
193
194**Implementation note:** Objects of different types except numbers are ordered
195by their type names; objects of the same types that don't support proper
196comparison are ordered by their address.
197
198.. index::
199   operator: in
200   operator: not in
236   pair: integer; literals
237   triple: long; integer; literals
238   pair: floating point; literals
239   pair: complex number; literals
240   pair: hexadecimal; literals
241   pair: octal; literals
242
243Numbers are created by numeric literals or as the result of built-in functions
n244-and operators.  Unadorned integer literals (including hex and octal numbers)
n249+and operators.  Unadorned integer literals (including binary, hex, and octal
245-yield plain integers unless the value they denote is too large to be represented
250+numbers) yield plain integers unless the value they denote is too large to be
246-as a plain integer, in which case they yield a long integer.  Integer literals
251+represented as a plain integer, in which case they yield a long integer.
247-with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` is preferred
252+Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
248-because ``1l`` looks too much like eleven!).  Numeric literals containing a
253+is preferred because ``1l`` looks too much like eleven!).  Numeric literals
249-decimal point or an exponent sign yield floating point numbers.  Appending
254+containing a decimal point or an exponent sign yield floating point numbers.
250-``'j'`` or ``'J'`` to a numeric literal yields a complex number with a zero real
255+Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
251-part. A complex numeric literal is the sum of a real and an imaginary part.
256+zero real part. A complex numeric literal is the sum of a real and an imaginary
257+part.
252
253.. index::
254   single: arithmetic
255   builtin: int
256   builtin: long
257   builtin: float
258   builtin: complex
259
260Python fully supports mixed arithmetic: when a binary arithmetic operator has
261operands of different numeric types, the operand with the "narrower" type is
262widened to that of the other, where plain integer is narrower than long integer
263is narrower than floating point is narrower than complex. Comparisons between
264numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
265:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
266of a specific type.
267
n268-All numeric types (except complex) support the following operations, sorted by
n274+All builtin numeric types support the following operations. See
269-ascending priority (operations in the same box have the same priority; all
275+:ref:`power` and later sections for the operators' priorities.
270-numeric operations have a higher priority than comparison operations):
271
272+--------------------+---------------------------------+--------+
273| Operation          | Result                          | Notes  |
274+====================+=================================+========+
275| ``x + y``          | sum of *x* and *y*              |        |
276+--------------------+---------------------------------+--------+
277| ``x - y``          | difference of *x* and *y*       |        |
278+--------------------+---------------------------------+--------+
279| ``x * y``          | product of *x* and *y*          |        |
280+--------------------+---------------------------------+--------+
281| ``x / y``          | quotient of *x* and *y*         | \(1)   |
282+--------------------+---------------------------------+--------+
n283-| ``x // y``         | (floored) quotient of *x* and   | \(5)   |
n288+| ``x // y``         | (floored) quotient of *x* and   | (4)(5) |
284|                    | *y*                             |        |
285+--------------------+---------------------------------+--------+
286| ``x % y``          | remainder of ``x / y``          | \(4)   |
287+--------------------+---------------------------------+--------+
288| ``-x``             | *x* negated                     |        |
289+--------------------+---------------------------------+--------+
290| ``+x``             | *x* unchanged                   |        |
291+--------------------+---------------------------------+--------+
n292-| ``abs(x)``         | absolute value or magnitude of  |        |
n297+| ``abs(x)``         | absolute value or magnitude of  | \(3)   |
293|                    | *x*                             |        |
294+--------------------+---------------------------------+--------+
295| ``int(x)``         | *x* converted to integer        | \(2)   |
296+--------------------+---------------------------------+--------+
297| ``long(x)``        | *x* converted to long integer   | \(2)   |
298+--------------------+---------------------------------+--------+
n299-| ``float(x)``       | *x* converted to floating point |        |
n304+| ``float(x)``       | *x* converted to floating point | \(6)   |
300+--------------------+---------------------------------+--------+
301| ``complex(re,im)`` | a complex number with real part |        |
302|                    | *re*, imaginary part *im*.      |        |
303|                    | *im* defaults to zero.          |        |
304+--------------------+---------------------------------+--------+
305| ``c.conjugate()``  | conjugate of the complex number |        |
n306-|                    | *c*                             |        |
n311+|                    | *c*. (Identity on real numbers) |        |
307+--------------------+---------------------------------+--------+
308| ``divmod(x, y)``   | the pair ``(x // y, x % y)``    | (3)(4) |
309+--------------------+---------------------------------+--------+
n310-| ``pow(x, y)``      | *x* to the power *y*            |        |
n315+| ``pow(x, y)``      | *x* to the power *y*            | (3)(7) |
311+--------------------+---------------------------------+--------+
n312-| ``x ** y``         | *x* to the power *y*            |        |
n317+| ``x ** y``         | *x* to the power *y*            | \(7)   |
313+--------------------+---------------------------------+--------+
314
315.. index::
316   triple: operations on; numeric; types
317   single: conjugate() (complex number method)
318
319Notes:
320
328   (-1)/(-2) is 0.  Note that the result is a long integer if either operand is a
329   long integer, regardless of the numeric value.
330
331(2)
332   .. index::
333      module: math
334      single: floor() (in module math)
335      single: ceil() (in module math)
n341+      single: trunc() (in module math)
336      pair: numeric; conversions
n337-      pair: C; language
338
n339-   Conversion from floating point to (long or plain) integer may round or truncate
n344+   Conversion from floats using :func:`int` or :func:`long` truncates toward
340-   as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
345+   zero like the related function, :func:`math.trunc`.  Use the function
341-   for well-defined conversions.
346+   :func:`math.floor` to round downward and :func:`math.ceil` to round
347+   upward.
342
343(3)
n344-   See section :ref:`built-in-funcs`, "Built-in Functions," for a full description.
n350+   See :ref:`built-in-funcs` for a full description.
345
346(4)
347   Complex floor division operator, modulo operator, and :func:`divmod`.
348
349   .. deprecated:: 2.3
350      Instead convert to float using :func:`abs` if appropriate.
351
352(5)
353   Also referred to as integer division.  The resultant value is a whole integer,
354   though the result's type is not necessarily int.
355
n362+(6)
363+   float also accepts the strings "nan" and "inf" with an optional prefix "+"
364+   or "-" for Not a Number (NaN) and positive or negative infinity.
365+ 
366+   .. versionadded:: 2.6
367+ 
368+(7)
369+   Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
370+   programming languages.
371+ 
372+All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
373+:class:`float`) also include the following operations:
374+ 
375++--------------------+------------------------------------+--------+
376+| Operation          | Result                             | Notes  |
377++====================+====================================+========+
378+| ``math.trunc(x)``  | *x* truncated to Integral          |        |
379++--------------------+------------------------------------+--------+
380+| ``round(x[, n])``  | *x* rounded to n digits,           |        |
381+|                    | rounding half to even. If n is     |        |
382+|                    | omitted, it defaults to 0.         |        |
383++--------------------+------------------------------------+--------+
384+| ``math.floor(x)``  | the greatest integral float <= *x* |        |
385++--------------------+------------------------------------+--------+
386+| ``math.ceil(x)``   | the least integral float >= *x*    |        |
387++--------------------+------------------------------------+--------+
388+ 
356-.. % XXXJH exceptions: overflow (when? what operations?) zerodivision
389+.. XXXJH exceptions: overflow (when? what operations?) zerodivision
357
358
359.. _bitstring-ops:
360
361Bit-string Operations on Integer Types
362--------------------------------------
363
n364-.. _bit-string operations:
n397+.. _bit-string-operations:
365
366Plain and long integer types support additional operations that make sense only
367for bit-strings.  Negative numbers are treated as their 2's complement value
368(for long integers, this assumes a sufficiently large number of bits that no
369overflow occurs during the operation).
370
n371-The priorities of the binary bit-wise operations are all lower than the numeric
n404+The priorities of the binary bitwise operations are all lower than the numeric
372operations and higher than the comparisons; the unary operation ``~`` has the
373same priority as the other unary numeric operations (``+`` and ``-``).
374
n375-This table lists the bit-string operations sorted in ascending priority
n408+This table lists the bit-string operations sorted in ascending priority:
376-(operations in the same box have the same priority):
377
378+------------+--------------------------------+----------+
379| Operation  | Result                         | Notes    |
380+============+================================+==========+
381| ``x | y``  | bitwise :dfn:`or` of *x* and   |          |
382|            | *y*                            |          |
383+------------+--------------------------------+----------+
384| ``x ^ y``  | bitwise :dfn:`exclusive or` of |          |
385|            | *x* and *y*                    |          |
386+------------+--------------------------------+----------+
387| ``x & y``  | bitwise :dfn:`and` of *x* and  |          |
388|            | *y*                            |          |
389+------------+--------------------------------+----------+
n390-| ``x << n`` | *x* shifted left by *n* bits   | (1)(2) |
n422+| ``x << n`` | *x* shifted left by *n* bits   | (1)(2)   |
391+------------+--------------------------------+----------+
n392-| ``x >> n`` | *x* shifted right by *n* bits  | (1)(3) |
n424+| ``x >> n`` | *x* shifted right by *n* bits  | (1)(3)   |
393+------------+--------------------------------+----------+
394| ``~x``     | the bits of *x* inverted       |          |
395+------------+--------------------------------+----------+
396
397.. index::
398   triple: operations on; integer; types
399   pair: bit-string; operations
400   pair: shifting; operations
401   pair: masking; operations
402
403Notes:
404
405(1)
406   Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
407
408(2)
n409-   A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
n441+   A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``.  A
410-   without overflow check.
442+   long integer is returned if the result exceeds the range of plain integers.
411
412(3)
n413-   A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
n445+   A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
414-   overflow check.
446+ 
447+ 
448+Additional Methods on Float
449+---------------------------
450+ 
451+The float type has some additional methods.
452+ 
453+.. method:: float.as_integer_ratio()
454+ 
455+    Return a pair of integers whose ratio is exactly equal to the
456+    original float and with a positive denominator.  Raises
457+    :exc:`OverflowError` on infinities and a :exc:`ValueError` on
458+    NaNs.
459+ 
460+    .. versionadded:: 2.6
461+ 
462+Two methods support conversion to
463+and from hexadecimal strings.  Since Python's floats are stored
464+internally as binary numbers, converting a float to or from a
465+*decimal* string usually involves a small rounding error.  In
466+contrast, hexadecimal strings allow exact representation and
467+specification of floating-point numbers.  This can be useful when
468+debugging, and in numerical work.
469+ 
470+ 
471+.. method:: float.hex()
472+ 
473+   Return a representation of a floating-point number as a hexadecimal
474+   string.  For finite floating-point numbers, this representation
475+   will always include a leading ``0x`` and a trailing ``p`` and
476+   exponent.
477+ 
478+   .. versionadded:: 2.6
479+ 
480+ 
481+.. method:: float.fromhex(s)
482+ 
483+   Class method to return the float represented by a hexadecimal
484+   string *s*.  The string *s* may have leading and trailing
485+   whitespace.
486+ 
487+   .. versionadded:: 2.6
488+ 
489+ 
490+Note that :meth:`float.hex` is an instance method, while
491+:meth:`float.fromhex` is a class method.
492+ 
493+A hexadecimal string takes the form::
494+ 
495+   [sign] ['0x'] integer ['.' fraction] ['p' exponent]
496+ 
497+where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
498+and ``fraction`` are strings of hexadecimal digits, and ``exponent``
499+is a decimal integer with an optional leading sign.  Case is not
500+significant, and there must be at least one hexadecimal digit in
501+either the integer or the fraction.  This syntax is similar to the
502+syntax specified in section 6.4.4.2 of the C99 standard, and also to
503+the syntax used in Java 1.5 onwards.  In particular, the output of
504+:meth:`float.hex` is usable as a hexadecimal floating-point literal in
505+C or Java code, and hexadecimal strings produced by C's ``%a`` format
506+character or Java's ``Double.toHexString`` are accepted by
507+:meth:`float.fromhex`.
508+ 
509+ 
510+Note that the exponent is written in decimal rather than hexadecimal,
511+and that it gives the power of 2 by which to multiply the coefficient.
512+For example, the hexadecimal string ``0x3.a7p10`` represents the
513+floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
514+``3740.0``::
515+ 
516+   >>> float.fromhex('0x3.a7p10')
517+   3740.0
518+ 
519+ 
520+Applying the reverse conversion to ``3740.0`` gives a different
521+hexadecimal string representing the same number::
522+ 
523+   >>> float.hex(3740.0)
524+   '0x1.d380000000000p+11'
415
416
417.. _typeiter:
418
419Iterator Types
420==============
421
422.. versionadded:: 2.2
430Python supports a concept of iteration over containers.  This is implemented
431using two distinct methods; these are used to allow user-defined classes to
432support iteration.  Sequences, described below in more detail, always support
433the iteration methods.
434
435One method needs to be defined for container objects to provide iteration
436support:
437
n548+.. XXX duplicated in reference/datamodel!
438
439.. method:: container.__iter__()
440
441   Return an iterator object.  The object is required to support the iterator
n442-   protocol described below.  If a container supports different types of iteration,
n553+   protocol described below.  If a container supports different types of
443-   additional methods can be provided to specifically request iterators for those
554+   iteration, additional methods can be provided to specifically request
444-   iteration types.  (An example of an object supporting multiple forms of
555+   iterators for those iteration types.  (An example of an object supporting
445-   iteration would be a tree structure which supports both breadth-first and depth-
556+   multiple forms of iteration would be a tree structure which supports both
446-   first traversal.)  This method corresponds to the :attr:`tp_iter` slot of the
557+   breadth-first and depth-first traversal.)  This method corresponds to the
447-   type structure for Python objects in the Python/C API.
558+   :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
559+   API.
448
449The iterator objects themselves are required to support the following two
450methods, which together form the :dfn:`iterator protocol`:
451
452
453.. method:: iterator.__iter__()
454
455   Return the iterator object itself.  This is required to allow both containers
471protocol.
472
473The intention of the protocol is that once an iterator's :meth:`next` method
474raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
475Implementations that do not obey this property are deemed broken.  (This
476constraint was added in Python 2.3; in Python 2.2, various iterators are broken
477according to this rule.)
478
n479-Python's generators provide a convenient way to implement the iterator protocol.
n591+Python's :term:`generator`\s provide a convenient way to implement the iterator
480-If a container object's :meth:`__iter__` method is implemented as a generator,
592+protocol.  If a container object's :meth:`__iter__` method is implemented as a
481-it will automatically return an iterator object (technically, a generator
593+generator, it will automatically return an iterator object (technically, a
482-object) supplying the :meth:`__iter__` and :meth:`next` methods.
594+generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
483
484
485.. _typesseq:
486
487Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
488==================================================================================================================
489
490There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
491and xrange objects.
n604+ 
605+For other containers see the built in :class:`dict` and :class:`set` classes,
606+and the :mod:`collections` module.
607+ 
492
493.. index::
494   object: sequence
495   object: string
496   object: Unicode
497   object: tuple
498   object: list
n615+   object: buffer
616+   object: xrange
499
500String literals are written in single or double quotes: ``'xyzzy'``,
n501-``"frobozz"``.  See chapter 2 of the Python Reference Manual (XXX reference:
n619+``"frobozz"``.  See :ref:`strings` for more about string literals.
502-../ref/strings.html) for more about string literals.  Unicode strings are much
620+Unicode strings are much like strings, but are specified in the syntax
503-like strings, but are specified in the syntax using a preceding ``'u'``
621+using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
504-character: ``u'abc'``, ``u"def"``.  Lists are constructed with square brackets,
622+to the functionality described here, there are also string-specific
505-separating items with commas: ``[a, b, c]``.  Tuples are constructed by the
623+methods described in the :ref:`string-methods` section. Lists are
506-comma operator (not within square brackets), with or without enclosing
624+constructed with square brackets, separating items with commas: ``[a, b, c]``.
507-parentheses, but an empty tuple must have the enclosing parentheses, such as
625+Tuples are constructed by the comma operator (not within square
508-``a, b, c`` or ``()``.  A single item tuple must have a trailing comma, such as
626+brackets), with or without enclosing parentheses, but an empty tuple
509-``(d,)``.
627+must have the enclosing parentheses, such as ``a, b, c`` or ``()``.  A
510- 
628+single item tuple must have a trailing comma, such as ``(d,)``.
511-.. index::
512-   builtin: buffer
513-   object: buffer
514
515Buffer objects are not directly supported by Python syntax, but can be created
516by calling the builtin function :func:`buffer`.  They don't support
517concatenation or repetition.
518
n519-.. index::
520-   builtin: xrange
521-   object: xrange
522- 
523-Xrange objects are similar to buffers in that there is no specific syntax to
634+Objects of type xrange are similar to buffers in that there is no specific syntax to
524create them, but they are created using the :func:`xrange` function.  They don't
525support slicing, concatenation or repetition, and using ``in``, ``not in``,
526:func:`min` or :func:`max` on them is inefficient.
527
528Most sequence types support the following operations.  The ``in`` and ``not in``
529operations have the same priorities as the comparison operations.  The ``+`` and
530``*`` operations have the same priority as the corresponding numeric operations.
n531-[#]_
n642+[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
532
533This table lists the sequence operations sorted in ascending priority
534(operations in the same box have the same priority).  In the table, *s* and *t*
535are sequences of the same type; *n*, *i* and *j* are integers:
536
537+------------------+--------------------------------+----------+
538| Operation        | Result                         | Notes    |
539+==================+================================+==========+
546| ``s + t``        | the concatenation of *s* and   | \(6)     |
547|                  | *t*                            |          |
548+------------------+--------------------------------+----------+
549| ``s * n, n * s`` | *n* shallow copies of *s*      | \(2)     |
550|                  | concatenated                   |          |
551+------------------+--------------------------------+----------+
552| ``s[i]``         | *i*'th item of *s*, origin 0   | \(3)     |
553+------------------+--------------------------------+----------+
n554-| ``s[i:j]``       | slice of *s* from *i* to *j*   | (3)(4) |
n665+| ``s[i:j]``       | slice of *s* from *i* to *j*   | (3)(4)   |
555+------------------+--------------------------------+----------+
n556-| ``s[i:j:k]``     | slice of *s* from *i* to *j*   | (3)(5) |
n667+| ``s[i:j:k]``     | slice of *s* from *i* to *j*   | (3)(5)   |
557|                  | with step *k*                  |          |
558+------------------+--------------------------------+----------+
559| ``len(s)``       | length of *s*                  |          |
560+------------------+--------------------------------+----------+
561| ``min(s)``       | smallest item of *s*           |          |
562+------------------+--------------------------------+----------+
563| ``max(s)``       | largest item of *s*            |          |
564+------------------+--------------------------------+----------+
n676+ 
677+Sequence types also support comparisons. In particular, tuples and lists
678+are compared lexicographically by comparing corresponding
679+elements. This means that to compare equal, every element must compare
680+equal and the two sequences must be of the same type and have the same
681+length. (For full details see :ref:`comparisons` in the language
682+reference.)
565
566.. index::
567   triple: operations on; sequence; types
568   builtin: len
569   builtin: min
570   builtin: max
571   pair: concatenation; operation
572   pair: repetition; operation
583   operations act like a substring test.  In Python versions before 2.3, *x* had to
584   be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
585   length.
586
587(2)
588   Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
589   sequence of the same type as *s*).  Note also that the copies are shallow;
590   nested structures are not copied.  This often haunts new Python programmers;
n591-   consider::
n709+   consider:
592
593      >>> lists = [[]] * 3
594      >>> lists
595      [[], [], []]
596      >>> lists[0].append(3)
597      >>> lists
598      [[3], [3], [3]]
599
600   What has happened is that ``[[]]`` is a one-element list containing an empty
601   list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
602   list.  Modifying any of the elements of ``lists`` modifies this single list.
n603-   You can create a list of different lists this way::
n721+   You can create a list of different lists this way:
604
605      >>> lists = [[] for i in range(3)]
606      >>> lists[0].append(3)
607      >>> lists[1].append(5)
608      >>> lists[2].append(7)
609      >>> lists
610      [[3], [5], [7]]
611
618   The slice of *s* from *i* to *j* is defined as the sequence of items with index
619   *k* such that ``i <= k < j``.  If *i* or *j* is greater than ``len(s)``, use
620   ``len(s)``.  If *i* is omitted or ``None``, use ``0``.  If *j* is omitted or
621   ``None``, use ``len(s)``.  If *i* is greater than or equal to *j*, the slice is
622   empty.
623
624(5)
625   The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
n626-   items with index  ``x = i + n*k`` such that 0 â‰¤n < (j-i)/(k).  In other words,
n744+   items with index  ``x = i + n*k`` such that ``<= n < (j-i)/k``.  In other words,
627   the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
628   *j* is reached (but never including *j*).  If *i* or *j* is greater than
629   ``len(s)``, use ``len(s)``.  If *i* or *j* are omitted or ``None``, they become
630   "end" values (which end depends on the sign of *k*).  Note, *k* cannot be zero.
631   If *k* is ``None``, it is treated like ``1``.
632
633(6)
634   If *s* and *t* are both strings, some Python implementations such as CPython can
645
646.. _string-methods:
647
648String Methods
649--------------
650
651.. index:: pair: string; methods
652
n653-These are the string methods which both 8-bit strings and Unicode objects
n771+Below are listed the string methods which both 8-bit strings and Unicode objects
654-support:
772+support. Note that none of these methods take keyword arguments.
655
n774+In addition, Python's strings support the sequence type methods
775+described in the :ref:`typesseq` section. To output formatted strings
776+use template strings or the ``%`` operator described in the
777+:ref:`string-formatting` section. Also, see the :mod:`re` module for
778+string functions based on regular expressions.
656
n657-.. method:: string.capitalize()
n780+.. method:: str.capitalize()
658
659   Return a copy of the string with only its first character capitalized.
660
661   For 8-bit strings, this method is locale-dependent.
662
663
n664-.. method:: string.center(width[, fillchar])
n787+.. method:: str.center(width[, fillchar])
665
666   Return centered in a string of length *width*. Padding is done using the
667   specified *fillchar* (default is a space).
668
669   .. versionchanged:: 2.4
670      Support for the *fillchar* argument.
671
672
n673-.. method:: string.count(sub[, start[, end]])
n796+.. method:: str.count(sub[, start[, end]])
674
n675-   Return the number of occurrences of substring *sub* in string S\
n798+   Return the number of non-overlapping occurrences of substring *sub* in the
676-   ``[start:end]``.  Optional arguments *start* and *end* are interpreted as in
799+   range [*start*, *end*].  Optional arguments *start* and *end* are
677-   slice notation.
800+   interpreted as in slice notation.
678
679
n680-.. method:: string.decode([encoding[, errors]])
n803+.. method:: str.decode([encoding[, errors]])
681
682   Decodes the string using the codec registered for *encoding*. *encoding*
683   defaults to the default string encoding.  *errors* may be given to set a
684   different error handling scheme.  The default is ``'strict'``, meaning that
685   encoding errors raise :exc:`UnicodeError`.  Other possible values are
686   ``'ignore'``, ``'replace'`` and any other name registered via
687   :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
688
689   .. versionadded:: 2.2
690
691   .. versionchanged:: 2.3
692      Support for other error handling schemes added.
693
694
n695-.. method:: string.encode([encoding[,errors]])
n818+.. method:: str.encode([encoding[,errors]])
696
697   Return an encoded version of the string.  Default encoding is the current
698   default string encoding.  *errors* may be given to set a different error
699   handling scheme.  The default for *errors* is ``'strict'``, meaning that
700   encoding errors raise a :exc:`UnicodeError`.  Other possible values are
701   ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
702   any other name registered via :func:`codecs.register_error`, see section
703   :ref:`codec-base-classes`. For a list of possible encodings, see section
705
706   .. versionadded:: 2.0
707
708   .. versionchanged:: 2.3
709      Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
710      handling schemes added.
711
712
n713-.. method:: string.endswith(suffix[, start[, end]])
n836+.. method:: str.endswith(suffix[, start[, end]])
714
715   Return ``True`` if the string ends with the specified *suffix*, otherwise return
716   ``False``.  *suffix* can also be a tuple of suffixes to look for.  With optional
717   *start*, test beginning at that position.  With optional *end*, stop comparing
718   at that position.
719
720   .. versionchanged:: 2.5
721      Accept tuples as *suffix*.
722
723
n724-.. method:: string.expandtabs([tabsize])
n847+.. method:: str.expandtabs([tabsize])
725
n726-   Return a copy of the string where all tab characters are expanded using spaces.
n849+   Return a copy of the string where all tab characters are replaced by one or
850+   more spaces, depending on the current column and the given tab size.  The
851+   column number is reset to zero after each newline occurring in the string.
727-   If *tabsize* is not given, a tab size of ``8`` characters is assumed.
852+   If *tabsize* is not given, a tab size of ``8`` characters is assumed.  This
853+   doesn't understand other non-printing characters or escape sequences.
728
729
n730-.. method:: string.find(sub[, start[, end]])
n856+.. method:: str.find(sub[, start[, end]])
731
732   Return the lowest index in the string where substring *sub* is found, such that
733   *sub* is contained in the range [*start*, *end*].  Optional arguments *start*
734   and *end* are interpreted as in slice notation.  Return ``-1`` if *sub* is not
735   found.
736
737
n864+.. method:: str.format(format_string, *args, **kwargs)
865+ 
866+   Perform a string formatting operation.  The *format_string* argument can
867+   contain literal text or replacement fields delimited by braces ``{}``.  Each
868+   replacement field contains either the numeric index of a positional argument,
869+   or the name of a keyword argument.  Returns a copy of *format_string* where
870+   each replacement field is replaced with the string value of the corresponding
871+   argument.
872+ 
873+      >>> "The sum of 1 + 2 is {0}".format(1+2)
874+      'The sum of 1 + 2 is 3'
875+ 
876+   See :ref:`formatstrings` for a description of the various formatting options
877+   that can be specified in format strings.
878+ 
879+   This method of string formatting is the new standard in Python 3.0, and
880+   should be preferred to the ``%`` formatting described in
881+   :ref:`string-formatting` in new code.
882+ 
883+   .. versionadded:: 2.6
884+ 
885+ 
738-.. method:: string.index(sub[, start[, end]])
886+.. method:: str.index(sub[, start[, end]])
739
740   Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
741
742
n743-.. method:: string.isalnum()
n891+.. method:: str.isalnum()
744
745   Return true if all characters in the string are alphanumeric and there is at
746   least one character, false otherwise.
747
748   For 8-bit strings, this method is locale-dependent.
749
750
n751-.. method:: string.isalpha()
n899+.. method:: str.isalpha()
752
753   Return true if all characters in the string are alphabetic and there is at least
754   one character, false otherwise.
755
756   For 8-bit strings, this method is locale-dependent.
757
758
n759-.. method:: string.isdigit()
n907+.. method:: str.isdigit()
760
761   Return true if all characters in the string are digits and there is at least one
762   character, false otherwise.
763
764   For 8-bit strings, this method is locale-dependent.
765
766
n767-.. method:: string.islower()
n915+.. method:: str.islower()
768
769   Return true if all cased characters in the string are lowercase and there is at
770   least one cased character, false otherwise.
771
772   For 8-bit strings, this method is locale-dependent.
773
774
n775-.. method:: string.isspace()
n923+.. method:: str.isspace()
776
777   Return true if there are only whitespace characters in the string and there is
778   at least one character, false otherwise.
779
780   For 8-bit strings, this method is locale-dependent.
781
782
n783-.. method:: string.istitle()
n931+.. method:: str.istitle()
784
785   Return true if the string is a titlecased string and there is at least one
786   character, for example uppercase characters may only follow uncased characters
787   and lowercase characters only cased ones.  Return false otherwise.
788
789   For 8-bit strings, this method is locale-dependent.
790
791
n792-.. method:: string.isupper()
n940+.. method:: str.isupper()
793
794   Return true if all cased characters in the string are uppercase and there is at
795   least one cased character, false otherwise.
796
797   For 8-bit strings, this method is locale-dependent.
798
799
n800-.. method:: string.join(seq)
n948+.. method:: str.join(seq)
801
802   Return a string which is the concatenation of the strings in the sequence *seq*.
803   The separator between elements is the string providing this method.
804
805
n806-.. method:: string.ljust(width[, fillchar])
n954+.. method:: str.ljust(width[, fillchar])
807
808   Return the string left justified in a string of length *width*. Padding is done
809   using the specified *fillchar* (default is a space).  The original string is
810   returned if *width* is less than ``len(s)``.
811
812   .. versionchanged:: 2.4
813      Support for the *fillchar* argument.
814
815
n816-.. method:: string.lower()
n964+.. method:: str.lower()
817
818   Return a copy of the string converted to lowercase.
819
820   For 8-bit strings, this method is locale-dependent.
821
822
n823-.. method:: string.lstrip([chars])
n971+.. method:: str.lstrip([chars])
824
825   Return a copy of the string with leading characters removed.  The *chars*
826   argument is a string specifying the set of characters to be removed.  If omitted
827   or ``None``, the *chars* argument defaults to removing whitespace.  The *chars*
n828-   argument is not a prefix; rather, all combinations of its values are stripped::
n976+   argument is not a prefix; rather, all combinations of its values are stripped:
829
830      >>> '   spacious   '.lstrip()
831      'spacious   '
832      >>> 'www.example.com'.lstrip('cmowz.')
833      'example.com'
834
835   .. versionchanged:: 2.2.2
836      Support for the *chars* argument.
837
838
n839-.. method:: string.partition(sep)
n987+.. method:: str.partition(sep)
840
841   Split the string at the first occurrence of *sep*, and return a 3-tuple
842   containing the part before the separator, the separator itself, and the part
843   after the separator.  If the separator is not found, return a 3-tuple containing
844   the string itself, followed by two empty strings.
845
846   .. versionadded:: 2.5
847
848
n849-.. method:: string.replace(old, new[, count])
n997+.. method:: str.replace(old, new[, count])
850
851   Return a copy of the string with all occurrences of substring *old* replaced by
852   *new*.  If the optional argument *count* is given, only the first *count*
853   occurrences are replaced.
854
855
n856-.. method:: string.rfind(sub [,start [,end]])
n1004+.. method:: str.rfind(sub [,start [,end]])
857
858   Return the highest index in the string where substring *sub* is found, such that
859   *sub* is contained within s[start,end].  Optional arguments *start* and *end*
860   are interpreted as in slice notation.  Return ``-1`` on failure.
861
862
n863-.. method:: string.rindex(sub[, start[, end]])
n1011+.. method:: str.rindex(sub[, start[, end]])
864
865   Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
866   found.
867
868
n869-.. method:: string.rjust(width[, fillchar])
n1017+.. method:: str.rjust(width[, fillchar])
870
871   Return the string right justified in a string of length *width*. Padding is done
872   using the specified *fillchar* (default is a space). The original string is
873   returned if *width* is less than ``len(s)``.
874
875   .. versionchanged:: 2.4
876      Support for the *fillchar* argument.
877
878
n879-.. method:: string.rpartition(sep)
n1027+.. method:: str.rpartition(sep)
880
881   Split the string at the last occurrence of *sep*, and return a 3-tuple
882   containing the part before the separator, the separator itself, and the part
883   after the separator.  If the separator is not found, return a 3-tuple containing
884   two empty strings, followed by the string itself.
885
886   .. versionadded:: 2.5
887
888
n889-.. method:: string.rsplit([sep [,maxsplit]])
n1037+.. method:: str.rsplit([sep [,maxsplit]])
890
891   Return a list of the words in the string, using *sep* as the delimiter string.
892   If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
893   ones.  If *sep* is not specified or ``None``, any whitespace string is a
894   separator.  Except for splitting from the right, :meth:`rsplit` behaves like
895   :meth:`split` which is described in detail below.
896
897   .. versionadded:: 2.4
898
899
n900-.. method:: string.rstrip([chars])
n1048+.. method:: str.rstrip([chars])
901
902   Return a copy of the string with trailing characters removed.  The *chars*
903   argument is a string specifying the set of characters to be removed.  If omitted
904   or ``None``, the *chars* argument defaults to removing whitespace.  The *chars*
n905-   argument is not a suffix; rather, all combinations of its values are stripped::
n1053+   argument is not a suffix; rather, all combinations of its values are stripped:
906
907      >>> '   spacious   '.rstrip()
908      '   spacious'
909      >>> 'mississippi'.rstrip('ipz')
910      'mississ'
911
912   .. versionchanged:: 2.2.2
913      Support for the *chars* argument.
914
915
n916-.. method:: string.split([sep [,maxsplit]])
n1064+.. method:: str.split([sep[, maxsplit]])
917
n918-   Return a list of the words in the string, using *sep* as the delimiter string.
n1066+   Return a list of the words in the string, using *sep* as the delimiter
919-   If *maxsplit* is given, at most *maxsplit* splits are done. (thus, the list will
1067+   string.  If *maxsplit* is given, at most *maxsplit* splits are done (thus,
920-   have at most ``maxsplit+1`` elements).  If *maxsplit* is not specified, then
1068+   the list will have at most ``maxsplit+1`` elements).  If *maxsplit* is not
921-   there is no limit on the number of splits (all possible splits are made).
1069+   specified, then there is no limit on the number of splits (all possible
922-   Consecutive delimiters are not grouped together and are deemed to delimit empty
1070+   splits are made).
1071+ 
1072+   If *sep* is given, consecutive delimiters are not grouped together and are
1073+   deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1074+   ``['1', '', '2']``).  The *sep* argument may consist of multiple characters
923-   strings (for example, ``'1,,2'.split(',')`` returns ``['1', '', '2']``).  The
1075+   (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
924-   *sep* argument may consist of multiple characters (for example, ``'1, 2,
1076+   Splitting an empty string with a specified separator returns ``['']``.
925-   3'.split(', ')`` returns ``['1', '2', '3']``).  Splitting an empty string with a
926-   specified separator returns ``['']``.
927
928   If *sep* is not specified or is ``None``, a different splitting algorithm is
n929-   applied.  First, whitespace characters (spaces, tabs, newlines, returns, and
n1079+   applied: runs of consecutive whitespace are regarded as a single separator,
930-   formfeeds) are stripped from both ends.  Then, words are separated by arbitrary
1080+   and the result will contain no empty strings at the start or end if the
931-   length strings of whitespace characters. Consecutive whitespace delimiters are
1081+   string has leading or trailing whitespace.  Consequently, splitting an empty
932-   treated as a single delimiter (``'1  2  3'.split()`` returns ``['1', '2',
1082+   string or a string consisting of just whitespace with a ``None`` separator
933-   '3']``). Splitting an empty string or a string consisting of just whitespace
1083+   returns ``[]``.
934-   returns an empty list.
935
n1085+   For example, ``' 1  2   3  '.split()`` returns ``['1', '2', '3']``, and
1086+   ``'  1  2   3  '.split(None, 1)`` returns ``['1', '2   3  ']``.
936
n1088+ 
937-.. method:: string.splitlines([keepends])
1089+.. method:: str.splitlines([keepends])
938
939   Return a list of the lines in the string, breaking at line boundaries.  Line
940   breaks are not included in the resulting list unless *keepends* is given and
941   true.
942
943
n944-.. method:: string.startswith(prefix[, start[, end]])
n1096+.. method:: str.startswith(prefix[, start[, end]])
945
946   Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
n947-   *prefix* can also be a tuple of suffixes to look for.  With optional *start*,
n1099+   *prefix* can also be a tuple of prefixes to look for.  With optional *start*,
948   test string beginning at that position.  With optional *end*, stop comparing
949   string at that position.
950
951   .. versionchanged:: 2.5
952      Accept tuples as *prefix*.
953
954
n955-.. method:: string.strip([chars])
n1107+.. method:: str.strip([chars])
956
957   Return a copy of the string with the leading and trailing characters removed.
958   The *chars* argument is a string specifying the set of characters to be removed.
959   If omitted or ``None``, the *chars* argument defaults to removing whitespace.
960   The *chars* argument is not a prefix or suffix; rather, all combinations of its
n961-   values are stripped::
n1113+   values are stripped:
962
963      >>> '   spacious   '.strip()
964      'spacious'
965      >>> 'www.example.com'.strip('cmowz.')
966      'example'
967
968   .. versionchanged:: 2.2.2
969      Support for the *chars* argument.
970
971
n972-.. method:: string.swapcase()
n1124+.. method:: str.swapcase()
973
974   Return a copy of the string with uppercase characters converted to lowercase and
975   vice versa.
976
977   For 8-bit strings, this method is locale-dependent.
978
979
n980-.. method:: string.title()
n1132+.. method:: str.title()
981
982   Return a titlecased version of the string: words start with uppercase
983   characters, all remaining cased characters are lowercase.
984
985   For 8-bit strings, this method is locale-dependent.
986
987
n988-.. method:: string.translate(table[, deletechars])
n1140+.. method:: str.translate(table[, deletechars])
989
990   Return a copy of the string where all characters occurring in the optional
991   argument *deletechars* are removed, and the remaining characters have been
992   mapped through the given translation table, which must be a string of length
993   256.
n1146+ 
1147+   You can use the :func:`maketrans` helper function in the :mod:`string` module to
1148+   create a translation table. For string objects, set the *table* argument to
1149+   ``None`` for translations that only delete characters:
1150+ 
1151+      >>> 'read this short text'.translate(None, 'aeiou')
1152+      'rd ths shrt txt'
1153+ 
1154+   .. versionadded:: 2.6
1155+      Support for a ``None`` *table* argument.
994
995   For Unicode objects, the :meth:`translate` method does not accept the optional
996   *deletechars* argument.  Instead, it returns a copy of the *s* where all
997   characters have been mapped through the given translation table which must be a
998   mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
999   Unmapped characters are left untouched. Characters mapped to ``None`` are
1000   deleted.  Note, a more flexible approach is to create a custom character mapping
1001   codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1002   example).
1003
1004
n1005-.. method:: string.upper()
n1167+.. method:: str.upper()
1006
1007   Return a copy of the string converted to uppercase.
1008
1009   For 8-bit strings, this method is locale-dependent.
1010
1011
n1012-.. method:: string.zfill(width)
n1174+.. method:: str.zfill(width)
1013
n1014-   Return the numeric string left filled with zeros in a string of length *width*.
n1176+   Return the numeric string left filled with zeros in a string of length
1177+   *width*.  A sign prefix is handled correctly.  The original string is
1015-   The original string is returned if *width* is less than ``len(s)``.
1178+   returned if *width* is less than ``len(s)``.
1179+ 
1016
1017   .. versionadded:: 2.2.2
1018
n1183+The following methods are present only on unicode objects:
1019
n1020-.. _typesseq-strings:
n1185+.. method:: unicode.isnumeric()
1186+ 
1187+   Return ``True`` if there are only numeric characters in S, ``False``
1188+   otherwise. Numeric characters include digit characters, and all characters
1189+   that have the Unicode numeric value property, e.g. U+2155,
1190+   VULGAR FRACTION ONE FIFTH.
1191+ 
1192+.. method:: unicode.isdecimal()
1193+ 
1194+   Return ``True`` if there are only decimal characters in S, ``False``
1195+   otherwise. Decimal characters include digit characters, and all characters
1196+   that that can be used to form decimal-radix numbers, e.g. U+0660,
1197+   ARABIC-INDIC DIGIT ZERO.
1198+ 
1199+ 
1200+.. _string-formatting:
1021
1022String Formatting Operations
1023----------------------------
1024
1025.. index::
1026   single: formatting, string (%)
1027   single: interpolation, string (%)
1028   single: string; formatting
1068
1069#. Length modifier (optional).
1070
1071#. Conversion type.
1072
1073When the right argument is a dictionary (or other mapping type), then the
1074formats in the string *must* include a parenthesised mapping key into that
1075dictionary inserted immediately after the ``'%'`` character. The mapping key
n1076-selects the value to be formatted from the mapping.  For example::
n1256+selects the value to be formatted from the mapping.  For example:
1077
1078   >>> print '%(language)s has %(#)03d quote types.' % \
n1079-             {'language': "Python", "#": 2}
n1259+   ...       {'language': "Python", "#": 2}
1080   Python has 002 quote types.
1081
1082In this case no ``*`` specifiers may occur in a format (since they require a
1083sequential parameter list).
1084
1085The conversion flag characters are:
1086
n1087-+---------+-----------------------------------------------+
n1267++---------+---------------------------------------------------------------------+
1088-| Flag    | Meaning                                       |
1268+| Flag    | Meaning                                                             |
1089-+=========+===============================================+
1269++=========+=====================================================================+
1090-| ``'#'`` | The value conversion will use the "alternate  |
1270+| ``'#'`` | The value conversion will use the "alternate form" (where defined   |
1091-|         | form" (where defined below).                  |
1271+|         | below).                                                             |
1092-+---------+-----------------------------------------------+
1272++---------+---------------------------------------------------------------------+
1093-| ``'0'`` | The conversion will be zero padded for        |
1273+| ``'0'`` | The conversion will be zero padded for numeric values.              |
1094-|         | numeric values.                               |
1095-+---------+-----------------------------------------------+
1274++---------+---------------------------------------------------------------------+
1096-| ``'-'`` | The converted value is left adjusted          |
1275+| ``'-'`` | The converted value is left adjusted (overrides the ``'0'``         |
1097-|         | (overrides the ``'0'`` conversion if both are |
1098-|         | given).                                       |
1276+|         | conversion if both are given).                                      |
1099-+---------+-----------------------------------------------+
1277++---------+---------------------------------------------------------------------+
1100-| ``' '`` | (a space) A blank should be left before a     |
1278+| ``' '`` | (a space) A blank should be left before a positive number (or empty |
1101-|         | positive number (or empty string) produced by |
1102-|         | a signed conversion.                          |
1279+|         | string) produced by a signed conversion.                            |
1103-+---------+-----------------------------------------------+
1280++---------+---------------------------------------------------------------------+
1104-| ``'+'`` | A sign character (``'+'`` or ``'-'``) will    |
1281+| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion   |
1105-|         | precede the conversion (overrides a "space"   |
1106-|         | flag).                                        |
1282+|         | (overrides a "space" flag).                                         |
1107-+---------+-----------------------------------------------+
1283++---------+---------------------------------------------------------------------+
1108
1109A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
n1110-is not necessary for Python.
n1286+is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1111
1112The conversion types are:
1113
n1114-+------------+---------------------------------+-------+
n1290++------------+-----------------------------------------------------+-------+
1115-| Conversion | Meaning                         | Notes |
1291+| Conversion | Meaning                                             | Notes |
1116-+============+=================================+=======+
1292++============+=====================================================+=======+
1117-| ``'d'``    | Signed integer decimal.         |       |
1293+| ``'d'``    | Signed integer decimal.                             |       |
1118-+------------+---------------------------------+-------+
1294++------------+-----------------------------------------------------+-------+
1119-| ``'i'``    | Signed integer decimal.         |       |
1295+| ``'i'``    | Signed integer decimal.                             |       |
1120-+------------+---------------------------------+-------+
1296++------------+-----------------------------------------------------+-------+
1121-| ``'o'``    | Unsigned octal.                 | \(1)  |
1297+| ``'o'``    | Signed octal value.                                 | \(1)  |
1122-+------------+---------------------------------+-------+
1298++------------+-----------------------------------------------------+-------+
1123-| ``'u'``    | Unsigned decimal.               |       |
1299+| ``'u'``    | Obsolete type -- it is identical to ``'d'``.        | \(7)  |
1124-+------------+---------------------------------+-------+
1300++------------+-----------------------------------------------------+-------+
1125-| ``'x'``    | Unsigned hexadecimal            | \(2)  |
1301+| ``'x'``    | Signed hexadecimal (lowercase).                     | \(2)  |
1126-|            | (lowercase).                    |       |
1127-+------------+---------------------------------+-------+
1302++------------+-----------------------------------------------------+-------+
1128-| ``'X'``    | Unsigned hexadecimal            | \(2)  |
1303+| ``'X'``    | Signed hexadecimal (uppercase).                     | \(2)  |
1129-|            | (uppercase).                    |       |
1130-+------------+---------------------------------+-------+
1304++------------+-----------------------------------------------------+-------+
1131-| ``'e'``    | Floating point exponential      | \(3)  |
1305+| ``'e'``    | Floating point exponential format (lowercase).      | \(3)  |
1132-|            | format (lowercase).             |       |
1133-+------------+---------------------------------+-------+
1306++------------+-----------------------------------------------------+-------+
1134-| ``'E'``    | Floating point exponential      | \(3)  |
1307+| ``'E'``    | Floating point exponential format (uppercase).      | \(3)  |
1135-|            | format (uppercase).             |       |
1136-+------------+---------------------------------+-------+
1308++------------+-----------------------------------------------------+-------+
1137-| ``'f'``    | Floating point decimal format.  | \(3)  |
1309+| ``'f'``    | Floating point decimal format.                      | \(3)  |
1138-+------------+---------------------------------+-------+
1310++------------+-----------------------------------------------------+-------+
1139-| ``'F'``    | Floating point decimal format.  | \(3)  |
1311+| ``'F'``    | Floating point decimal format.                      | \(3)  |
1140-+------------+---------------------------------+-------+
1312++------------+-----------------------------------------------------+-------+
1141-| ``'g'``    | Floating point format. Uses     | \(4)  |
1313+| ``'g'``    | Floating point format. Uses lowercase exponential   | \(4)  |
1142-|            | exponential format if exponent  |       |
1143-|            | is greater than -4 or less than |       |
1314+|            | format if exponent is less than -4 or not less than |       |
1144-|            | precision, decimal format       |       |
1315+|            | precision, decimal format otherwise.                |       |
1145-|            | otherwise.                      |       |
1146-+------------+---------------------------------+-------+
1316++------------+-----------------------------------------------------+-------+
1147-| ``'G'``    | Floating point format. Uses     | \(4)  |
1317+| ``'G'``    | Floating point format. Uses uppercase exponential   | \(4)  |
1148-|            | exponential format if exponent  |       |
1149-|            | is greater than -4 or less than |       |
1318+|            | format if exponent is less than -4 or not less than |       |
1150-|            | precision, decimal format       |       |
1319+|            | precision, decimal format otherwise.                |       |
1151-|            | otherwise.                      |       |
1152-+------------+---------------------------------+-------+
1320++------------+-----------------------------------------------------+-------+
1153-| ``'c'``    | Single character (accepts       |       |
1321+| ``'c'``    | Single character (accepts integer or single         |       |
1154-|            | integer or single character     |       |
1155-|            | string).                        |       |
1322+|            | character string).                                  |       |
1156-+------------+---------------------------------+-------+
1323++------------+-----------------------------------------------------+-------+
1157-| ``'r'``    | String (converts any python     | \(5)  |
1324+| ``'r'``    | String (converts any python object using            | \(5)  |
1158-|            | object using :func:`repr`).     |       |
1325+|            | :func:`repr`).                                      |       |
1159-+------------+---------------------------------+-------+
1326++------------+-----------------------------------------------------+-------+
1160-| ``'s'``    | String (converts any python     | \(6)  |
1327+| ``'s'``    | String (converts any python object using            | \(6)  |
1161-|            | object using :func:`str`).      |       |
1328+|            | :func:`str`).                                       |       |
1162-+------------+---------------------------------+-------+
1329++------------+-----------------------------------------------------+-------+
1163-| ``'%'``    | No argument is converted,       |       |
1330+| ``'%'``    | No argument is converted, results in a ``'%'``      |       |
1164-|            | results in a ``'%'`` character  |       |
1165-|            | in the result.                  |       |
1331+|            | character in the result.                            |       |
1166-+------------+---------------------------------+-------+
1332++------------+-----------------------------------------------------+-------+
1167
1168Notes:
1169
1170(1)
n1171-   The alternate form causes a leading zero (``'0'``) to be inserted between left-
n1337+   The alternate form causes a leading zero (``'0'``) to be inserted between
1172-   hand padding and the formatting of the number if the leading character of the
1338+   left-hand padding and the formatting of the number if the leading character
1173-   result is not already a zero.
1339+   of the result is not already a zero.
1174
1175(2)
1176   The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1177   the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1178   and the formatting of the number if the leading character of the result is not
1179   already a zero.
1180
1181(3)
1198   The precision determines the maximal number of characters used.
1199
1200(6)
1201   If the object or format provided is a :class:`unicode` string, the resulting
1202   string will also be :class:`unicode`.
1203
1204   The precision determines the maximal number of characters used.
1205
n1372+(7)
1373+   See :pep:`237`.
1374+ 
1206Since Python strings have an explicit length, ``%s`` conversions do not assume
1207that ``'\0'`` is the end of the string.
1208
n1209-.. % XXX Examples?
n1378+.. XXX Examples?
1210
1211For safety reasons, floating point precisions are clipped to 50; ``%f``
n1212-conversions for numbers whose absolute value is over 1e25 are replaced by ``%g``
n1381+conversions for numbers whose absolute value is over 1e50 are replaced by ``%g``
1213conversions. [#]_  All other errors raise exceptions.
1214
1215.. index::
1216   module: string
1217   module: re
1218
1219Additional string operations are defined in standard modules :mod:`string` and
1220:mod:`re`.
1273|                              | [x]``                          |                     |
1274+------------------------------+--------------------------------+---------------------+
1275| ``s.extend(x)``              | same as ``s[len(s):len(s)] =   | \(3)                |
1276|                              | x``                            |                     |
1277+------------------------------+--------------------------------+---------------------+
1278| ``s.count(x)``               | return number of *i*'s for     |                     |
1279|                              | which ``s[i] == x``            |                     |
1280+------------------------------+--------------------------------+---------------------+
n1281-| ``s.index(x[, *i*[, *j*]])`` | return smallest *k* such that  | \(4)                |
n1450+| ``s.index(x[, i[, j]])``     | return smallest *k* such that  | \(4)                |
1282|                              | ``s[k] == x`` and ``i <= k <   |                     |
1283|                              | j``                            |                     |
1284+------------------------------+--------------------------------+---------------------+
1285| ``s.insert(i, x)``           | same as ``s[i:i] = [x]``       | \(5)                |
1286+------------------------------+--------------------------------+---------------------+
n1287-| ``s.pop([*i*])``             | same as ``x = s[i]; del s[i];  | \(6)                |
n1456+| ``s.pop([i])``               | same as ``x = s[i]; del s[i];  | \(6)                |
1288|                              | return x``                     |                     |
1289+------------------------------+--------------------------------+---------------------+
1290| ``s.remove(x)``              | same as ``del s[s.index(x)]``  | \(4)                |
1291+------------------------------+--------------------------------+---------------------+
1292| ``s.reverse()``              | reverses the items of *s* in   | \(7)                |
1293|                              | place                          |                     |
1294+------------------------------+--------------------------------+---------------------+
n1295-| ``s.sort([*cmp*[, *key*[,    | sort the items of *s* in place | (7)(8)(9)(10) |
n1464+| ``s.sort([cmp[, key[,        | sort the items of *s* in place | (7)(8)(9)(10)       |
1296-*reverse*]]])``              |                                |                     |
1465+| reverse]]])``                |                                |                     |
1297+------------------------------+--------------------------------+---------------------+
1298
1299.. index::
n1300-   quadruple: operations on; mutable; sequence; types
1301   triple: operations on; sequence; types
1302   triple: operations on; list; type
1303   pair: subscript; assignment
1304   pair: slice; assignment
1305   pair: extended slice; assignment
1306   statement: del
1307   single: append() (list method)
1308   single: extend() (list method)
1357
1358(8)
1359   The :meth:`sort` method takes optional arguments for controlling the
1360   comparisons.
1361
1362   *cmp* specifies a custom comparison function of two arguments (list items) which
1363   should return a negative, zero or positive number depending on whether the first
1364   argument is considered smaller than, equal to, or larger than the second
n1365-   argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``
n1533+   argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.  The default value
1534+   is ``None``.
1366
1367   *key* specifies a function of one argument that is used to extract a comparison
n1368-   key from each list element: ``key=str.lower``
n1537+   key from each list element: ``key=str.lower``.  The default value is ``None``.
1369
1370   *reverse* is a boolean value.  If set to ``True``, then the list elements are
1371   sorted as if each comparison were reversed.
1372
1373   In general, the *key* and *reverse* conversion processes are much faster than
1374   specifying an equivalent *cmp* function.  This is because *cmp* is called
1375   multiple times for each list element while *key* and *reverse* touch each
1376   element only once.
1396
1397.. _types-set:
1398
1399Set Types --- :class:`set`, :class:`frozenset`
1400==============================================
1401
1402.. index:: object: set
1403
n1404-A :dfn:`set` object is an unordered collection of immutable values. Common uses
n1573+A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1405-include membership testing, removing duplicates from a sequence, and computing
1574+Common uses include membership testing, removing duplicates from a sequence, and
1406-mathematical operations such as intersection, union, difference, and symmetric
1575+computing mathematical operations such as intersection, union, difference, and
1407-difference.
1576+symmetric difference.
1577+(For other containers see the built in :class:`dict`, :class:`list`,
1578+and :class:`tuple` classes, and the :mod:`collections` module.)
1579+ 
1408
1409.. versionadded:: 2.4
1410
1411Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1412set``.  Being an unordered collection, sets do not record element position or
1413order of insertion.  Accordingly, sets do not support indexing, slicing, or
1414other sequence-like behavior.
1415
1416There are currently two builtin set types, :class:`set` and :class:`frozenset`.
1417The :class:`set` type is mutable --- the contents can be changed using methods
1418like :meth:`add` and :meth:`remove`.  Since it is mutable, it has no hash value
1419and cannot be used as either a dictionary key or as an element of another set.
n1420-The :class:`frozenset` type is immutable and hashable --- its contents cannot be
n1592+The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
1421-altered after is created; however, it can be used as a dictionary key or as an
1593+altered after it is created; it can therefore be used as a dictionary key or as
1422-element of another set.
1594+an element of another set.
1423
n1596+The constructors for both classes work the same:
1597+ 
1598+.. class:: set([iterable])
1599+           frozenset([iterable])
1600+ 
1601+   Return a new set or frozenset object whose elements are taken from
1602+   *iterable*.  The elements of a set must be hashable.  To represent sets of
1603+   sets, the inner sets must be :class:`frozenset` objects.  If *iterable* is
1604+   not specified, a new empty set is returned.
1605+ 
1424-Instances of :class:`set` and :class:`frozenset` provide the following
1606+   Instances of :class:`set` and :class:`frozenset` provide the following
1425-operations:
1607+   operations:
1426
n1427-+-------------------------------+------------+---------------------------------+
n1609+   .. describe:: len(s)
1428-| Operation                     | Equivalent | Result                          |
1429-+===============================+============+=================================+
1430-| ``len(s)``                    |            | cardinality of set *s*          |
1431-+-------------------------------+------------+---------------------------------+
1432-| ``x in s``                    |            | test *x* for membership in *s*  |
1433-+-------------------------------+------------+---------------------------------+
1434-| ``x not in s``                |            | test *x* for non-membership in  |
1435-|                               |            | *s*                             |
1436-+-------------------------------+------------+---------------------------------+
1437-| ``s.issubset(t)``             | ``s <= t`` | test whether every element in   |
1438-|                               |            | *s* is in *t*                   |
1439-+-------------------------------+------------+---------------------------------+
1440-| ``s.issuperset(t)``           | ``s >= t`` | test whether every element in   |
1441-|                               |            | *t* is in *s*                   |
1442-+-------------------------------+------------+---------------------------------+
1443-| ``s.union(t)``                | *s* \| *t* | new set with elements from both |
1444-|                               |            | *s* and *t*                     |
1445-+-------------------------------+------------+---------------------------------+
1446-| ``s.intersection(t)``         | *s* & *t*  | new set with elements common to |
1447-|                               |            | *s* and *t*                     |
1448-+-------------------------------+------------+---------------------------------+
1449-| ``s.difference(t)``           | *s* - *t*  | new set with elements in *s*    |
1450-|                               |            | but not in *t*                  |
1451-+-------------------------------+------------+---------------------------------+
1452-| ``s.symmetric_difference(t)`` | *s* ^ *t*  | new set with elements in either |
1453-|                               |            | *s* or *t* but not both         |
1454-+-------------------------------+------------+---------------------------------+
1455-| ``s.copy()``                  |            | new set with a shallow copy of  |
1456-|                               |            | *s*                             |
1457-+-------------------------------+------------+---------------------------------+
1458
n1611+      Return the cardinality of set *s*.
1612+ 
1613+   .. describe:: x in s
1614+ 
1615+      Test *x* for membership in *s*.
1616+ 
1617+   .. describe:: x not in s
1618+ 
1619+      Test *x* for non-membership in *s*.
1620+ 
1621+   .. method:: isdisjoint(other)
1622+ 
1623+      Return True if the set has no elements in common with *other*.  Sets are
1624+      disjoint if and only if their intersection is the empty set.
1625+ 
1626+      .. versionadded:: 2.6
1627+ 
1628+   .. method:: issubset(other)
1629+               set <= other
1630+ 
1631+      Test whether every element in the set is in *other*.
1632+ 
1633+   .. method:: set < other
1634+ 
1635+      Test whether the set is a true subset of *other*, that is,
1636+      ``set <= other and set != other``.
1637+ 
1638+   .. method:: issuperset(other)
1639+               set >= other
1640+ 
1641+      Test whether every element in *other* is in the set.
1642+ 
1643+   .. method:: set > other
1644+ 
1645+      Test whether the set is a true superset of *other*, that is, ``set >=
1646+      other and set != other``.
1647+ 
1648+   .. method:: union(other, ...)
1649+               set | other | ...
1650+ 
1651+      Return a new set with elements from the set and all others.
1652+ 
1653+      .. versionchanged:: 2.6
1654+         Accepts multiple input iterables.
1655+ 
1656+   .. method:: intersection(other, ...)
1657+               set & other & ...
1658+ 
1659+      Return a new set with elements common to the set and all others.
1660+ 
1661+      .. versionchanged:: 2.6
1662+         Accepts multiple input iterables.
1663+ 
1664+   .. method:: difference(other, ...)
1665+               set - other - ...
1666+ 
1667+      Return a new set with elements in the set that are not in the others.
1668+ 
1669+      .. versionchanged:: 2.6
1670+         Accepts multiple input iterables.
1671+ 
1672+   .. method:: symmetric_difference(other)
1673+               set ^ other
1674+ 
1675+      Return a new set with elements in either the set or *other* but not both.
1676+ 
1677+   .. method:: copy()
1678+ 
1679+      Return a new set with a shallow copy of *s*.
1680+ 
1681+ 
1459-Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1682+   Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1460-:meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1683+   :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1461-:meth:`issuperset` methods will accept any iterable as an argument.  In
1684+   :meth:`issuperset` methods will accept any iterable as an argument.  In
1462-contrast, their operator based counterparts require their arguments to be sets.
1685+   contrast, their operator based counterparts require their arguments to be
1463-This precludes error-prone constructions like ``set('abc') & 'cbs'`` in favor of
1686+   sets.  This precludes error-prone constructions like ``set('abc') & 'cbs'``
1464-the more readable ``set('abc').intersection('cbs')``.
1687+   in favor of the more readable ``set('abc').intersection('cbs')``.
1465
n1466-Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
n1689+   Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1467-sets are equal if and only if every element of each set is contained in the
1690+   sets are equal if and only if every element of each set is contained in the
1468-other (each is a subset of the other). A set is less than another set if and
1691+   other (each is a subset of the other). A set is less than another set if and
1469-only if the first set is a proper subset of the second set (is a subset, but is
1692+   only if the first set is a proper subset of the second set (is a subset, but
1470-not equal). A set is greater than another set if and only if the first set is a
1693+   is not equal). A set is greater than another set if and only if the first set
1471-proper superset of the second set (is a superset, but is not equal).
1694+   is a proper superset of the second set (is a superset, but is not equal).
1472
n1473-Instances of :class:`set` are compared to instances of :class:`frozenset` based
n1696+   Instances of :class:`set` are compared to instances of :class:`frozenset`
1474-on their members.  For example, ``set('abc') == frozenset('abc')`` returns
1697+   based on their members.  For example, ``set('abc') == frozenset('abc')``
1475-``True``.
1698+   returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1476
n1477-The subset and equality comparisons do not generalize to a complete ordering
n1700+   The subset and equality comparisons do not generalize to a complete ordering
1478-function.  For example, any two disjoint sets are not equal and are not subsets
1701+   function.  For example, any two disjoint sets are not equal and are not
1479-of each other, so *all* of the following return ``False``:  ``a<b``, ``a==b``,
1702+   subsets of each other, so *all* of the following return ``False``: ``a<b``,
1480-or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__` method.
1703+   ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1704+   method.
1481
n1482-Since sets only define partial ordering (subset relationships), the output of
n1706+   Since sets only define partial ordering (subset relationships), the output of
1483-the :meth:`list.sort` method is undefined for lists of sets.
1707+   the :meth:`list.sort` method is undefined for lists of sets.
1484
n1485-Set elements are like dictionary keys; they need to define both :meth:`__hash__`
n1709+   Set elements, like dictionary keys, must be :term:`hashable`.
1486-and :meth:`__eq__` methods.
1487
n1488-Binary operations that mix :class:`set` instances with :class:`frozenset` return
n1711+   Binary operations that mix :class:`set` instances with :class:`frozenset`
1489-the type of the first operand.  For example: ``frozenset('ab') | set('bc')``
1712+   return the type of the first operand.  For example: ``frozenset('ab') |
1490-returns an instance of :class:`frozenset`.
1713+   set('bc')`` returns an instance of :class:`frozenset`.
1491
n1492-The following table lists operations available for :class:`set` that do not
n1715+   The following table lists operations available for :class:`set` that do not
1493-apply to immutable instances of :class:`frozenset`:
1716+   apply to immutable instances of :class:`frozenset`:
1494
n1495-+--------------------------------------+-------------+---------------------------------+
n1718+   .. method:: update(other, ...)
1496-| Operation                            | Equivalent  | Result                          |
1719+               set |= other | ...
1497-+======================================+=============+=================================+
1498-| ``s.update(t)``                      | *s* \|= *t* | update set *s*, adding elements |
1499-|                                      |             | from *t*                        |
1500-+--------------------------------------+-------------+---------------------------------+
1501-| ``s.intersection_update(t)``         | *s* &= *t*  | update set *s*, keeping only    |
1502-|                                      |             | elements found in both *s* and  |
1503-|                                      |             | *t*                             |
1504-+--------------------------------------+-------------+---------------------------------+
1505-| ``s.difference_update(t)``           | *s* -= *t*  | update set *s*, removing        |
1506-|                                      |             | elements found in *t*           |
1507-+--------------------------------------+-------------+---------------------------------+
1508-| ``s.symmetric_difference_update(t)`` | *s* ^= *t*  | update set *s*, keeping only    |
1509-|                                      |             | elements found in either *s* or |
1510-|                                      |             | *t* but not in both             |
1511-+--------------------------------------+-------------+---------------------------------+
1512-| ``s.add(x)``                         |             | add element *x* to set *s*      |
1513-+--------------------------------------+-------------+---------------------------------+
1514-| ``s.remove(x)``                      |             | remove *x* from set *s*; raises |
1515-|                                      |             | :exc:`KeyError` if not present  |
1516-+--------------------------------------+-------------+---------------------------------+
1517-| ``s.discard(x)``                     |             | removes *x* from set *s* if     |
1518-|                                      |             | present                         |
1519-+--------------------------------------+-------------+---------------------------------+
1520-| ``s.pop()``                          |             | remove and return an arbitrary  |
1521-|                                      |             | element from *s*; raises        |
1522-|                                      |             | :exc:`KeyError` if empty        |
1523-+--------------------------------------+-------------+---------------------------------+
1524-| ``s.clear()``                        |             | remove all elements from set    |
1525-|                                      |             | *s*                             |
1526-+--------------------------------------+-------------+---------------------------------+
1527
n1721+      Update the set, adding elements from *other*.
1722+ 
1723+      .. versionchanged:: 2.6
1724+         Accepts multiple input iterables.
1725+ 
1726+   .. method:: intersection_update(other, ...)
1727+               set &= other & ...
1728+ 
1729+      Update the set, keeping only elements found in it and *other*.
1730+ 
1731+      .. versionchanged:: 2.6
1732+         Accepts multiple input iterables.
1733+ 
1734+   .. method:: difference_update(other, ...)
1735+               set -= other | ...
1736+ 
1737+      Update the set, removing elements found in others.
1738+ 
1739+      .. versionchanged:: 2.6
1740+         Accepts multiple input iterables.
1741+ 
1742+   .. method:: symmetric_difference_update(other)
1743+               set ^= other
1744+ 
1745+      Update the set, keeping only elements found in either set, but not in both.
1746+ 
1747+   .. method:: add(elem)
1748+ 
1749+      Add element *elem* to the set.
1750+ 
1751+   .. method:: remove(elem)
1752+ 
1753+      Remove element *elem* from the set.  Raises :exc:`KeyError` if *elem* is
1754+      not contained in the set.
1755+ 
1756+   .. method:: discard(elem)
1757+ 
1758+      Remove element *elem* from the set if it is present.
1759+ 
1760+   .. method:: pop()
1761+ 
1762+      Remove and return an arbitrary element from the set.  Raises
1763+      :exc:`KeyError` if the set is empty.
1764+ 
1765+   .. method:: clear()
1766+ 
1767+      Remove all elements from the set.
1768+ 
1769+ 
1528-Note, the non-operator versions of the :meth:`update`,
1770+   Note, the non-operator versions of the :meth:`update`,
1529-:meth:`intersection_update`, :meth:`difference_update`, and
1771+   :meth:`intersection_update`, :meth:`difference_update`, and
1530-:meth:`symmetric_difference_update` methods will accept any iterable as an
1772+   :meth:`symmetric_difference_update` methods will accept any iterable as an
1531-argument.
1773+   argument.
1532
n1533-The design of the set types was based on lessons learned from the :mod:`sets`
n1775+   Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1534-module.
1776+   :meth:`discard` methods may be a set.  To support searching for an equivalent
1777+   frozenset, the *elem* set is temporarily mutated during the search and then
1778+   restored.  During the search, the *elem* set should not be read or mutated
1779+   since it does not have a meaningful value.
1535
1536
1537.. seealso::
1538
n1539-   `Comparison to the built-in set types <comparison-to-builtin-set.html>`_
n1784+   :ref:`comparison-to-builtin-set`
1540      Differences between the :mod:`sets` module and the built-in set types.
1541
1542
1543.. _typesmapping:
1544
1545Mapping Types --- :class:`dict`
1546===============================
1547
1548.. index::
1549   object: mapping
1550   object: dictionary
n1551- 
1552-A :dfn:`mapping` object maps  immutable values to arbitrary objects.  Mappings
1553-are mutable objects.  There is currently only one standard mapping type, the
1554-:dfn:`dictionary`.  A dictionary's keys are almost arbitrary values.  Only
1555-values containing lists, dictionaries or other mutable types (that are compared
1556-by value rather than by object identity) may not be used as keys. Numeric types
1557-used for keys obey the normal rules for numeric comparison: if two numbers
1558-compare equal (such as ``1`` and ``1.0``) then they can be used interchangeably
1559-to index the same dictionary entry.
1560- 
1561-Dictionaries are created by placing a comma-separated list of ``key: value``
1562-pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1563-'jack', 4127: 'sjoerd'}``.
1564- 
1565-.. index::
1566   triple: operations on; mapping; types
1567   triple: operations on; dictionary; type
1568   statement: del
1569   builtin: len
n1570-   single: clear() (dictionary method)
1571-   single: copy() (dictionary method)
1572-   single: has_key() (dictionary method)
1573-   single: fromkeys() (dictionary method)
1574-   single: items() (dictionary method)
1575-   single: keys() (dictionary method)
1576-   single: update() (dictionary method)
1577-   single: values() (dictionary method)
1578-   single: get() (dictionary method)
1579-   single: setdefault() (dictionary method)
1580-   single: pop() (dictionary method)
1581-   single: popitem() (dictionary method)
1582-   single: iteritems() (dictionary method)
1583-   single: iterkeys() (dictionary method)
1584-   single: itervalues() (dictionary method)
1585
n1586-The following operations are defined on mappings (where *a* and *b* are
n1801+A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1587-mappings, *k* is a key, and *v* and *x* are arbitrary objects):
1802+Mappings are mutable objects.  There is currently only one standard mapping
1803+type, the :dfn:`dictionary`.  (For other containers see the built in
1804+:class:`list`, :class:`set`, and :class:`tuple` classes, and the
1805+:mod:`collections` module.)
1588
n1589-+--------------------------------+---------------------------------+-----------+
n1807+A dictionary's keys are *almost* arbitrary values.  Values that are not
1590-| Operation                      | Result                          | Notes     |
1808+:term:`hashable`, that is, values containing lists, dictionaries or other
1591-+================================+=================================+===========+
1809+mutable types (that are compared by value rather than by object identity) may
1592-| ``len(a)``                     | the number of items in *a*      |           |
1810+not be used as keys.  Numeric types used for keys obey the normal rules for
1593-+--------------------------------+---------------------------------+-----------+
1811+numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1594-| ``a[k]``                       | the item of *a* with key *k*    | (1), (10) |
1812+then they can be used interchangeably to index the same dictionary entry.  (Note
1595-+--------------------------------+---------------------------------+-----------+
1813+however, that since computers store floating-point numbers as approximations it
1596-| ``a[k] = v``                   | set ``a[k]`` to *v*             |           |
1814+is usually unwise to use them as dictionary keys.)
1597-+--------------------------------+---------------------------------+-----------+
1598-| ``del a[k]``                   | remove ``a[k]`` from *a*        | \(1)      |
1599-+--------------------------------+---------------------------------+-----------+
1600-| ``a.clear()``                  | remove all items from ``a``     |           |
1601-+--------------------------------+---------------------------------+-----------+
1602-| ``a.copy()``                   | a (shallow) copy of ``a``       |           |
1603-+--------------------------------+---------------------------------+-----------+
1604-| ``k in a``                     | ``True`` if *a* has a key *k*,  | \(2)      |
1605-|                                | else ``False``                  |           |
1606-+--------------------------------+---------------------------------+-----------+
1607-| ``k not in a``                 | Equivalent to ``not`` *k* in    | \(2)      |
1608-|                                | *a*                             |           |
1609-+--------------------------------+---------------------------------+-----------+
1610-| ``a.has_key(k)``               | Equivalent to *k* ``in`` *a*,   |           |
1611-|                                | use that form in new code       |           |
1612-+--------------------------------+---------------------------------+-----------+
1613-| ``a.items()``                  | a copy of *a*'s list of (*key*, | \(3)      |
1614-|                                | *value*) pairs                  |           |
1615-+--------------------------------+---------------------------------+-----------+
1616-| ``a.keys()``                   | a copy of *a*'s list of keys    | \(3)      |
1617-+--------------------------------+---------------------------------+-----------+
1618-| ``a.update([*b*])``            | updates (and overwrites)        | \(9)      |
1619-|                                | key/value pairs from *b*        |           |
1620-+--------------------------------+---------------------------------+-----------+
1621-| ``a.fromkeys(seq[, *value*])`` | Creates a new dictionary with   | \(7)      |
1622-|                                | keys from *seq* and values set  |           |
1623-|                                | to *value*                      |           |
1624-+--------------------------------+---------------------------------+-----------+
1625-| ``a.values()``                 | a copy of *a*'s list of values  | \(3)      |
1626-+--------------------------------+---------------------------------+-----------+
1627-| ``a.get(k[, *x*])``            | ``a[k]`` if ``k in a``, else    | \(4)      |
1628-|                                | *x*                             |           |
1629-+--------------------------------+---------------------------------+-----------+
1630-| ``a.setdefault(k[, *x*])``     | ``a[k]`` if ``k in a``, else    | \(5)      |
1631-|                                | *x* (also setting it)           |           |
1632-+--------------------------------+---------------------------------+-----------+
1633-| ``a.pop(k[, *x*])``            | ``a[k]`` if ``k in a``, else    | \(8)      |
1634-|                                | *x* (and remove k)              |           |
1635-+--------------------------------+---------------------------------+-----------+
1636-| ``a.popitem()``                | remove and return an arbitrary  | \(6)      |
1637-|                                | (*key*, *value*) pair           |           |
1638-+--------------------------------+---------------------------------+-----------+
1639-| ``a.iteritems()``              | return an iterator over (*key*, | (2), (3)  |
1640-|                                | *value*) pairs                  |           |
1641-+--------------------------------+---------------------------------+-----------+
1642-| ``a.iterkeys()``               | return an iterator over the     | (2), (3)  |
1643-|                                | mapping's keys                  |           |
1644-+--------------------------------+---------------------------------+-----------+
1645-| ``a.itervalues()``             | return an iterator over the     | (2), (3)  |
1646-|                                | mapping's values                |           |
1647-+--------------------------------+---------------------------------+-----------+
1648
n1649-Notes:
n1816+Dictionaries can be created by placing a comma-separated list of ``key: value``
1817+pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1818+'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1650
n1651-(1)
n1820+.. class:: dict([arg])
1652-   Raises a :exc:`KeyError` exception if *k* is not in the map.
1653
n1654-(2)
n1822+   Return a new dictionary initialized from an optional positional argument or from
1823+   a set of keyword arguments. If no arguments are given, return a new empty
1824+   dictionary. If the positional argument *arg* is a mapping object, return a
1825+   dictionary mapping the same keys to the same values as does the mapping object.
1826+   Otherwise the positional argument must be a sequence, a container that supports
1827+   iteration, or an iterator object.  The elements of the argument must each also
1828+   be of one of those kinds, and each must in turn contain exactly two objects.
1829+   The first is used as a key in the new dictionary, and the second as the key's
1830+   value.  If a given key is seen more than once, the last value associated with it
1831+   is retained in the new dictionary.
1832+ 
1833+   If keyword arguments are given, the keywords themselves with their associated
1834+   values are added as items to the dictionary. If a key is specified both in the
1835+   positional argument and as a keyword argument, the value associated with the
1836+   keyword is retained in the dictionary. For example, these all return a
1837+   dictionary equal to ``{"one": 2, "two": 3}``:
1838+ 
1839+   * ``dict(one=2, two=3)``
1840+ 
1841+   * ``dict({'one': 2, 'two': 3})``
1842+ 
1843+   * ``dict(zip(('one', 'two'), (2, 3)))``
1844+ 
1845+   * ``dict([['two', 3], ['one', 2]])``
1846+ 
1847+   The first example only works for keys that are valid Python
1848+   identifiers; the others work with any valid keys.
1849+ 
1655   .. versionadded:: 2.2
1656
n1657-(3)
n1852+   .. versionchanged:: 2.3
1658-   Keys and values are listed in an arbitrary order which is non-random, varies
1853+      Support for building a dictionary from keyword arguments added.
1659-   across Python implementations, and depends on the dictionary's history of
1660-   insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`,
1661-   :meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no
1662-   intervening modifications to the dictionary, the lists will directly correspond.
1663-   This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
1664-   zip(a.values(), a.keys())``.  The same relationship holds for the
1665-   :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(a.itervalues(),
1666-   a.iterkeys())`` provides the same value for ``pairs``. Another way to create the
1667-   same list is ``pairs = [(v, k) for (k, v) in a.iteritems()]``.
1668
n1669-(4)
1670-   Never raises an exception if *k* is not in the map, instead it returns *x*.  *x*
1671-   is optional; when *x* is not provided and *k* is not in the map, ``None`` is
1672-   returned.
1673
n1674-(5)
n1856+   These are the operations that dictionaries support (and therefore, custom
1675-   :func:`setdefault` is like :func:`get`, except that if *k* is missing, *x* is
1857+   mapping types should support too):
1676-   both returned and inserted into the dictionary as the value of *k*. *x* defaults
1677-   to *None*.
1678
n1679-(6)
n1859+   .. describe:: len(d)
1680-   :func:`popitem` is useful to destructively iterate over a dictionary, as often
1681-   used in set algorithms.  If the dictionary is empty, calling :func:`popitem`
1682-   raises a :exc:`KeyError`.
1683
n1684-(7)
n1861+      Return the number of items in the dictionary *d*.
1862+ 
1863+   .. describe:: d[key]
1864+ 
1865+      Return the item of *d* with key *key*.  Raises a :exc:`KeyError` if *key*
1866+      is not in the map.
1867+ 
1868+      .. versionadded:: 2.5
1869+         If a subclass of dict defines a method :meth:`__missing__`, if the key
1870+         *key* is not present, the ``d[key]`` operation calls that method with
1871+         the key *key* as argument.  The ``d[key]`` operation then returns or
1872+         raises whatever is returned or raised by the ``__missing__(key)`` call
1873+         if the key is not present. No other operations or methods invoke
1874+         :meth:`__missing__`. If :meth:`__missing__` is not defined,
1875+         :exc:`KeyError` is raised.  :meth:`__missing__` must be a method; it
1876+         cannot be an instance variable. For an example, see
1877+         :class:`collections.defaultdict`.
1878+ 
1879+   .. describe:: d[key] = value
1880+ 
1881+      Set ``d[key]`` to *value*.
1882+ 
1883+   .. describe:: del d[key]
1884+ 
1885+      Remove ``d[key]`` from *d*.  Raises a :exc:`KeyError` if *key* is not in the
1886+      map.
1887+ 
1888+   .. describe:: key in d
1889+ 
1890+      Return ``True`` if *d* has a key *key*, else ``False``.
1891+ 
1892+      .. versionadded:: 2.2
1893+ 
1894+   .. describe:: key not in d
1895+ 
1896+      Equivalent to ``not key in d``.
1897+ 
1898+      .. versionadded:: 2.2
1899+ 
1900+   .. describe:: iter(d)
1901+ 
1902+      Return an iterator over the keys of the dictionary.  This is a shortcut
1903+      for :meth:`iterkeys`.
1904+ 
1905+   .. method:: clear()
1906+ 
1907+      Remove all items from the dictionary.
1908+ 
1909+   .. method:: copy()
1910+ 
1911+      Return a shallow copy of the dictionary.
1912+ 
1913+   .. method:: fromkeys(seq[, value])
1914+ 
1915+      Create a new dictionary with keys from *seq* and values set to *value*.
1916+ 
1685-   :func:`fromkeys` is a class method that returns a new dictionary. *value*
1917+      :func:`fromkeys` is a class method that returns a new dictionary. *value*
1686-   defaults to ``None``.
1918+      defaults to ``None``.
1687
n1688-   .. versionadded:: 2.3
n1920+      .. versionadded:: 2.3
1689
n1690-(8)
n1922+   .. method:: get(key[, default])
1691-   :func:`pop` raises a :exc:`KeyError` when no default value is given and the key
1692-   is not found.
1693
n1924+      Return the value for *key* if *key* is in the dictionary, else *default*.
1925+      If *default* is not given, it defaults to ``None``, so that this method
1926+      never raises a :exc:`KeyError`.
1927+ 
1928+   .. method:: has_key(key)
1929+ 
1930+      Test for the presence of *key* in the dictionary.  :meth:`has_key` is
1931+      deprecated in favor of ``key in d``.
1932+ 
1933+   .. method:: items()
1934+ 
1935+      Return a copy of the dictionary's list of ``(key, value)`` pairs.
1936+ 
1937+      .. note::
1938+ 
1939+         Keys and values are listed in an arbitrary order which is non-random,
1940+         varies across Python implementations, and depends on the dictionary's
1941+         history of insertions and deletions. If :meth:`items`, :meth:`keys`,
1942+         :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
1943+         :meth:`itervalues` are called with no intervening modifications to the
1944+         dictionary, the lists will directly correspond.  This allows the
1945+         creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
1946+         zip(d.values(), d.keys())``.  The same relationship holds for the
1947+         :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
1948+         zip(d.itervalues(), d.iterkeys())`` provides the same value for
1949+         ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
1950+         (k, v) in d.iteritems()]``.
1951+ 
1952+   .. method:: iteritems()
1953+ 
1954+      Return an iterator over the dictionary's ``(key, value)`` pairs.  See the
1955+      note for :meth:`dict.items`.
1956+ 
1957+      Using :meth:`iteritems` while adding or deleting entries in the dictionary
1958+      will raise a :exc:`RuntimeError`.
1959+ 
1960+      .. versionadded:: 2.2
1961+ 
1962+   .. method:: iterkeys()
1963+ 
1964+      Return an iterator over the dictionary's keys.  See the note for
1965+      :meth:`dict.items`.
1966+ 
1967+      Using :meth:`iterkeys` while adding or deleting entries in the dictionary
1968+      will raise a :exc:`RuntimeError`.
1969+ 
1970+      .. versionadded:: 2.2
1971+ 
1972+   .. method:: itervalues()
1973+ 
1974+      Return an iterator over the dictionary's values.  See the note for
1975+      :meth:`dict.items`.
1976+ 
1977+      Using :meth:`itervalues` while adding or deleting entries in the
1978+      dictionary will raise a :exc:`RuntimeError`.
1979+ 
1980+      .. versionadded:: 2.2
1981+ 
1982+   .. method:: keys()
1983+ 
1984+      Return a copy of the dictionary's list of keys.  See the note for
1985+      :meth:`dict.items`.
1986+ 
1987+   .. method:: pop(key[, default])
1988+ 
1989+      If *key* is in the dictionary, remove it and return its value, else return
1990+      *default*.  If *default* is not given and *key* is not in the dictionary,
1991+      a :exc:`KeyError` is raised.
1992+ 
1694-   .. versionadded:: 2.3
1993+      .. versionadded:: 2.3
1695
n1696-(9)
n1995+   .. method:: popitem()
1996+ 
1997+      Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
1998+ 
1999+      :func:`popitem` is useful to destructively iterate over a dictionary, as
2000+      often used in set algorithms.  If the dictionary is empty, calling
2001+      :func:`popitem` raises a :exc:`KeyError`.
2002+ 
2003+   .. method:: setdefault(key[, default])
2004+ 
2005+      If *key* is in the dictionary, return its value.  If not, insert *key*
2006+      with a value of *default* and return *default*.  *default* defaults to
2007+      ``None``.
2008+ 
2009+   .. method:: update([other])
2010+ 
2011+      Update the dictionary with the key/value pairs from *other*, overwriting
2012+      existing keys.  Return ``None``.
2013+ 
1697-   :func:`update` accepts either another mapping object or an iterable of key/value
2014+      :func:`update` accepts either another dictionary object or an iterable of
1698-   pairs (as a tuple or other iterable of length two).  If keyword arguments are
2015+      key/value pairs (as a tuple or other iterable of length two).  If keyword
1699-   specified, the mapping is then is updated with those key/value pairs:
2016+      arguments are specified, the dictionary is then is updated with those
1700-   ``d.update(red=1, blue=2)``.
2017+      key/value pairs: ``d.update(red=1, blue=2)``.
1701
n1702-   .. versionchanged:: 2.4
n2019+      .. versionchanged:: 2.4
1703-      Allowed the argument to be an iterable of key/value pairs and allowed keyword
2020+          Allowed the argument to be an iterable of key/value pairs and allowed
1704-      arguments.
2021+          keyword arguments.
1705
n1706-(10)
n2023+   .. method:: values()
1707-   If a subclass of dict defines a method :meth:`__missing__`, if the key *k* is
1708-   not present, the *a*[*k*] operation calls that method with the key *k* as
1709-   argument.  The *a*[*k*] operation then returns or raises whatever is returned or
1710-   raised by the :func:`__missing__`\ (*k*) call if the key is not present. No
1711-   other operations or methods invoke :meth:`__missing__`\ (). If
1712-   :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
1713-   :meth:`__missing__` must be a method; it cannot be an instance variable. For an
1714-   example, see :mod:`collections`.\ :class:`defaultdict`.
1715
n1716-   .. versionadded:: 2.5
n2025+      Return a copy of the dictionary's list of values.  See the note for
2026+      :meth:`dict.items`.
1717
1718
1719.. _bltin-file-objects:
1720
1721File Objects
1722============
1723
1724.. index::
1725   object: file
1726   builtin: file
1727   module: os
1728   module: socket
1729
n1730-File objects are implemented using C's ``stdio`` package and can be created with
n2040+File objects are implemented using C's ``stdio`` package and can be
1731-the built-in constructor :func:`file` described in section
2041+created with the built-in :func:`open` function.  File
1732-:ref:`built-in-funcs`, "Built-in Functions." [#]_  File objects are also
2042+objects are also returned by some other built-in functions and methods,
1733-returned by some other built-in functions and methods, such as :func:`os.popen`
2043+such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
1734-and :func:`os.fdopen` and the :meth:`makefile` method of socket objects.
2044+method of socket objects. Temporary files can be created using the
2045+:mod:`tempfile` module, and high-level file operations such as copying,
2046+moving, and deleting files and directories can be achieved with the
2047+:mod:`shutil` module.
1735
1736When a file operation fails for an I/O-related reason, the exception
1737:exc:`IOError` is raised.  This includes situations where the operation is not
1738defined for some reason, like :meth:`seek` on a tty device or writing a file
1739opened for reading.
1740
1741Files have the following methods:
1742
1744.. method:: file.close()
1745
1746   Close the file.  A closed file cannot be read or written any more. Any operation
1747   which requires that the file be open will raise a :exc:`ValueError` after the
1748   file has been closed.  Calling :meth:`close` more than once is allowed.
1749
1750   As of Python 2.5, you can avoid having to call this method explicitly if you use
1751   the :keyword:`with` statement.  For example, the following code will
n1752-   automatically close ``f`` when the :keyword:`with` block is exited::
n2065+   automatically close *f* when the :keyword:`with` block is exited::
1753
n1754-      from __future__ import with_statement
n2067+      from __future__ import with_statement # This isn't required in Python 2.6
1755
1756      with open("hello.txt") as f:
1757          for line in f:
1758              print line
1759
1760   In older versions of Python, you would have needed to do this to get the same
1761   effect::
1762
1766              print line
1767      finally:
1768          f.close()
1769
1770   .. note::
1771
1772      Not all "file-like" types in Python support use as a context manager for the
1773      :keyword:`with` statement.  If your code is intended to work with any file-like
n1774-      object, you can use the :func:`closing` function in the :mod:`contextlib` module
n2087+      object, you can use the function :func:`contextlib.closing` instead of using
1775-      instead of using the object directly.  See section :ref:`context-closing` for
2088+      the object directly.
1776-      details.
1777
1778
1779.. method:: file.flush()
1780
n1781-   Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`.  This may be a no-
n2093+   Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`.  This may be a
1782-   op on some file-like objects.
2094+   no-op on some file-like objects.
1783
1784
1785.. method:: file.fileno()
1786
1787   .. index::
n1788-      single: file descriptor
n2100+      pair: file; descriptor
1789-      single: descriptor, file
1790      module: fcntl
1791
1792   Return the integer "file descriptor" that is used by the underlying
1793   implementation to request I/O operations from the operating system.  This can be
1794   useful for other, lower level interfaces that use file descriptors, such as the
1795   :mod:`fcntl` module or :func:`os.read` and friends.
1796
1797   .. note::
1811
1812
1813.. method:: file.next()
1814
1815   A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
1816   *f* is closed).  When a file is used as an iterator, typically in a
1817   :keyword:`for` loop (for example, ``for line in f: print line``), the
1818   :meth:`next` method is called repeatedly.  This method returns the next input
n1819-   line, or raises :exc:`StopIteration` when EOF is hit.  In order to make a
n2130+   line, or raises :exc:`StopIteration` when EOF is hit whethe file is open for
2131+   reading (behavior is undefined when the file is open for writing).  In order to
1820-   :keyword:`for` loop the most efficient way of looping over the lines of a file
2132+   make a :keyword:`for` loop the most efficient way of looping over the lines of a
1821-   (a very common operation), the :meth:`next` method uses a hidden read-ahead
2133+   file (a very common operation), the :meth:`next` method uses a hidden read-ahead
1822   buffer.  As a consequence of using a read-ahead buffer, combining :meth:`next`
1823   with other file methods (like :meth:`readline`) does not work right.  However,
1824   using :meth:`seek` to reposition the file to an absolute position will flush the
1825   read-ahead buffer.
1826
1827   .. versionadded:: 2.3
1828
1829
1831
1832   Read at most *size* bytes from the file (less if the read hits EOF before
1833   obtaining *size* bytes).  If the *size* argument is negative or omitted, read
1834   all data until EOF is reached.  The bytes are returned as a string object.  An
1835   empty string is returned when EOF is encountered immediately.  (For certain
1836   files, like ttys, it makes sense to continue reading after an EOF is hit.)  Note
1837   that this method may call the underlying C function :cfunc:`fread` more than
1838   once in an effort to acquire as close to *size* bytes as possible. Also note
n1839-   that when in non-blocking mode, less data than what was requested may be
n2151+   that when in non-blocking mode, less data than was requested may be
1840   returned, even if no *size* parameter was given.
n2153+ 
2154+   .. note::
2155+      This function is simply a wrapper for the underlying
2156+      :cfunc:`fread` C function, and will behave the same in corner cases,
2157+      such as whether the EOF value is cached.
1841
1842
1843.. method:: file.readline([size])
1844
1845   Read one entire line from the file.  A trailing newline character is kept in the
1846   string (but may be absent when a file ends with an incomplete line). [#]_  If
1847   the *size* argument is present and non-negative, it is a maximum byte count
1848   (including the trailing newline) and an incomplete line may be returned. An
1852
1853      Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
1854      (``'\0'``) if they occurred in the input.
1855
1856
1857.. method:: file.readlines([sizehint])
1858
1859   Read until EOF using :meth:`readline` and return a list containing the lines
n1860-   thus read.  If the optional *sizehint* argument is present, instead of reading
n2177+   thus read.  If the optional *sizehint* argument is present, instead of
1861-   up to EOF, whole lines totalling approximately *sizehint* bytes (possibly after
2178+   reading up to EOF, whole lines totalling approximately *sizehint* bytes
1862-   rounding up to an internal buffer size) are read.  Objects implementing a file-
2179+   (possibly after rounding up to an internal buffer size) are read.  Objects
1863-   like interface may choose to ignore *sizehint* if it cannot be implemented, or
2180+   implementing a file-like interface may choose to ignore *sizehint* if it
1864-   cannot be implemented efficiently.
2181+   cannot be implemented, or cannot be implemented efficiently.
1865
1866
1867.. method:: file.xreadlines()
1868
1869   This method returns the same thing as ``iter(f)``.
1870
1871   .. versionadded:: 2.1
1872
1873   .. deprecated:: 2.3
1874      Use ``for line in file`` instead.
1875
1876
1877.. method:: file.seek(offset[, whence])
1878
1879   Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
n1880-   argument is optional and defaults to ``0`` (absolute file positioning); other
n2197+   argument is optional and defaults to  ``os.SEEK_SET`` or ``0`` (absolute file
1881-   values are ``1`` (seek relative to the current position) and ``2`` (seek
2198+   positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
1882-   relative to the file's end).  There is no return value.  Note that if the file
2199+   current position) and ``os.SEEK_END`` or ``2``  (seek relative to the file's
1883-   is opened for appending (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations
2200+   end).  There is no return value.
1884-   will be undone at the next write.  If the file is only opened for writing in
2201+ 
2202+   For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2203+   ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2204+ 
2205+   Note that if the file is opened for appending
2206+   (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2207+   next write.  If the file is only opened for writing in append mode (mode
1885-   append mode (mode ``'a'``), this method is essentially a no-op, but it remains
2208+   ``'a'``), this method is essentially a no-op, but it remains useful for files
1886-   useful for files opened in append mode with reading enabled (mode ``'a+'``).  If
2209+   opened in append mode with reading enabled (mode ``'a+'``).  If the file is
1887-   the file is opened in text mode (without ``'b'``), only offsets returned by
2210+   opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
1888-   :meth:`tell` are legal.  Use of other offsets causes undefined behavior.
2211+   legal.  Use of other offsets causes undefined behavior.
1889
1890   Note that not all file objects are seekable.
n2214+ 
2215+   .. versionchanged:: 2.6
2216+      Passing float values as offset has been deprecated.
1891
1892
1893.. method:: file.tell()
1894
1895   Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
1896
1897   .. note::
1898
1950   terminal is likely to use (that  information might be incorrect if the user has
1951   misconfigured the  terminal). The attribute is read-only and may not be present
1952   on all file-like objects. It may also be ``None``, in which case the file uses
1953   the system default encoding for converting Unicode strings.
1954
1955   .. versionadded:: 2.3
1956
1957
n2284+.. attribute:: file.errors
2285+ 
2286+   The Unicode error handler used along with the encoding.
2287+ 
2288+   .. versionadded:: 2.6
2289+ 
2290+ 
1958.. attribute:: file.mode
1959
1960   The I/O mode for the file.  If the file was created using the :func:`open`
1961   built-in function, this will be the value of the *mode* parameter.  This is a
1962   read-only attribute and may not be present on all file-like objects.
1963
1964
1965.. attribute:: file.name
1966
1967   If the file object was created using :func:`open`, the name of the file.
n1968-   Otherwise, some string that indicates the source of the file object, of the form
n2301+   Otherwise, some string that indicates the source of the file object, of the
1969-   ``<...>``.  This is a read-only attribute and may not be present on all file-
2302+   form ``<...>``.  This is a read-only attribute and may not be present on all
1970-   like objects.
2303+   file-like objects.
1971
1972
1973.. attribute:: file.newlines
1974
1975   If Python was built with the :option:`--with-universal-newlines` option to
1976   :program:`configure` (the default) this read-only attribute exists, and for
1977   files opened in universal newline read mode it keeps track of the types of
1978   newlines encountered while reading the file. The values it can take are
2015defined by a context manager.  This is implemented using two separate methods
2016that allow user-defined classes to define a runtime context that is entered
2017before the statement body is executed and exited when the statement ends.
2018
2019The :dfn:`context management protocol` consists of a pair of methods that need
2020to be provided for a context manager object to define a runtime context:
2021
2022
n2023-.. method:: context manager.__enter__()
n2356+.. method:: contextmanager.__enter__()
2024
2025   Enter the runtime context and return either this object or another object
2026   related to the runtime context. The value returned by this method is bound to
2027   the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2028   this context manager.
2029
2030   An example of a context manager that returns itself is a file object. File
2031   objects return themselves from __enter__() to allow :func:`open` to be used as
2032   the context expression in a :keyword:`with` statement.
2033
2034   An example of a context manager that returns a related object is the one
n2035-   returned by ``decimal.Context.get_manager()``. These managers set the active
n2368+   returned by :func:`decimal.localcontext`. These managers set the active
2036   decimal context to a copy of the original decimal context and then return the
2037   copy. This allows changes to be made to the current decimal context in the body
2038   of the :keyword:`with` statement without affecting code outside the
2039   :keyword:`with` statement.
2040
2041
n2042-.. method:: context manager.__exit__(exc_type, exc_val, exc_tb)
n2375+.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2043
n2044-   Exit the runtime context and return a Boolean flag indicating if any expection
n2377+   Exit the runtime context and return a Boolean flag indicating if any exception
2045   that occurred should be suppressed. If an exception occurred while executing the
2046   body of the :keyword:`with` statement, the arguments contain the exception type,
n2047-   value and traceback information. Otherwise, all three arguments are *None*.
n2380+   value and traceback information. Otherwise, all three arguments are ``None``.
2048
2049   Returning a true value from this method will cause the :keyword:`with` statement
2050   to suppress the exception and continue execution with the statement immediately
2051   following the :keyword:`with` statement. Otherwise the exception continues
2052   propagating after this method has finished executing. Exceptions that occur
2053   during execution of this method will replace any exception that occurred in the
2054   body of the :keyword:`with` statement.
2055
2057   method should return a false value to indicate that the method completed
2058   successfully and does not want to suppress the raised exception. This allows
2059   context management code (such as ``contextlib.nested``) to easily detect whether
2060   or not an :meth:`__exit__` method has actually failed.
2061
2062Python defines several context managers to support easy thread synchronisation,
2063prompt closure of files or other objects, and simpler manipulation of the active
2064decimal arithmetic context. The specific types are not treated specially beyond
n2065-their implementation of the context management protocol.
n2398+their implementation of the context management protocol. See the
2399+:mod:`contextlib` module for some examples.
2066
n2067-Python's generators and the ``contextlib.contextfactory`` decorator provide a
n2401+Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
2068-convenient way to implement these protocols.  If a generator function is
2402+provide a convenient way to implement these protocols.  If a generator function is
2069decorated with the ``contextlib.contextfactory`` decorator, it will return a
2070context manager implementing the necessary :meth:`__enter__` and
2071:meth:`__exit__` methods, rather than the iterator produced by an undecorated
2072generator function.
2073
2074Note that there is no specific slot for any of these methods in the type
2075structure for Python objects in the Python/C API. Extension types wanting to
2076define these methods must provide them as a normal Python accessible method.
2103containing the module's symbol table. Modifying this dictionary will actually
2104change the module's symbol table, but direct assignment to the :attr:`__dict__`
2105attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2106``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``).  Modifying
2107:attr:`__dict__` directly is not recommended.
2108
2109Modules built into the interpreter are written like this: ``<module 'sys'
2110(built-in)>``.  If loaded from a file, they are written as ``<module 'os' from
n2111-'/usr/local/lib/python|version|/os.pyc'>``.
n2445+'/usr/local/lib/pythonX.Y/os.pyc'>``.
2112
2113
2114.. _typesobjects:
2115
2116Classes and Class Instances
2117---------------------------
2118
n2119-.. _classes and instances:
n2453+See :ref:`objects` and :ref:`class` for these.
2120- 
2121-See chapters 3 and 7 of the Python Reference Manual (XXX reference:
2122-../ref/ref.html) for these.
2123
2124
2125.. _typesfunctions:
2126
2127Functions
2128---------
2129
2130Function objects are created by function definitions.  The only operation on a
2131function object is to call it: ``func(argument-list)``.
2132
n2133-There are really two flavors of function objects: built-in functions and user-
n2464+There are really two flavors of function objects: built-in functions and
2134-defined functions.  Both support the same operation (to call the function), but
2465+user-defined functions.  Both support the same operation (to call the function),
2135-the implementation is different, hence the different object types.
2466+but the implementation is different, hence the different object types.
2136
n2137-See the Python Reference Manual (XXX reference: ../ref/ref.html) for more
n2468+See :ref:`function` for more information.
2138-information.
2139
2140
2141.. _typesmethods:
2142
2143Methods
2144-------
2145
2146.. index:: object: method
2172
2173   class C:
2174       def method(self):
2175           pass
2176
2177   c = C()
2178   c.method.im_func.whoami = 'my name is c'
2179
n2180-See the Python Reference Manual (XXX reference: ../ref/ref.html) for more
n2510+See :ref:`types` for more information.
2181-information.
2182
2183
2184.. _bltin-code-objects:
2185
2186Code Objects
2187------------
2188
2189.. index:: object: code
2192   builtin: compile
2193   single: func_code (function object attribute)
2194
2195Code objects are used by the implementation to represent "pseudo-compiled"
2196executable Python code such as a function body. They differ from function
2197objects because they don't contain a reference to their global execution
2198environment.  Code objects are returned by the built-in :func:`compile` function
2199and can be extracted from function objects through their :attr:`func_code`
n2200-attribute.
n2529+attribute. See also the :mod:`code` module.
2201
2202.. index::
2203   statement: exec
2204   builtin: eval
2205
2206A code object can be executed or evaluated by passing it (instead of a source
2207string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
2208
n2209-See the Python Reference Manual (XXX reference: ../ref/ref.html) for more
n2538+See :ref:`types` for more information.
2210-information.
2211
2212
2213.. _bltin-type-objects:
2214
2215Type Objects
2216------------
2217
2218.. index::
2239It is written as ``None``.
2240
2241
2242.. _bltin-ellipsis-object:
2243
2244The Ellipsis Object
2245-------------------
2246
n2247-This object is used by extended slice notation (see the Python Reference Manual
n2575+This object is used by extended slice notation (see :ref:`slicings`).  It
2248-(XXX reference: ../ref/ref.html)).  It supports no special operations.  There is
2576+supports no special operations.  There is exactly one ellipsis object, named
2249-exactly one ellipsis object, named :const:`Ellipsis` (a built-in name).
2577+:const:`Ellipsis` (a built-in name).
2250
2251It is written as ``Ellipsis``.
2252
2253
2254Boolean Values
2255--------------
2256
2257Boolean values are the two constant objects ``False`` and ``True``.  They are
2270They are written as ``False`` and ``True``, respectively.
2271
2272
2273.. _typesinternal:
2274
2275Internal Objects
2276----------------
2277
n2278-See the Python Reference Manual (XXX reference: ../ref/ref.html) for this
n2606+See :ref:`types` for this information.  It describes stack frame objects,
2279-information.  It describes stack frame objects, traceback objects, and slice
2607+traceback objects, and slice objects.
2280-objects.
2281
2282
2283.. _specialattrs:
2284
2285Special Attributes
2286==================
2287
2288The implementation adds a few special read-only attributes to several object
2320   The tuple of base classes of a class object.  If there are no base classes, this
2321   will be an empty tuple.
2322
2323
2324.. attribute:: class.__name__
2325
2326   The name of the class or type.
2327
n2655+ 
2656+The following attributes are only supported by :term:`new-style class`\ es.
2657+ 
2658+.. attribute:: class.__mro__
2659+ 
2660+   This attribute is a tuple of classes that are considered when looking for
2661+   base classes during method resolution.
2662+ 
2663+ 
2664+.. method:: class.mro()
2665+ 
2666+   This method can be overridden by a metaclass to customize the method
2667+   resolution order for its instances.  It is called at class instantiation, and
2668+   its result is stored in :attr:`__mro__`.
2669+ 
2670+ 
2671+.. method:: class.__subclasses__
2672+ 
2673+   Each new-style class keeps a list of weak references to its immediate
2674+   subclasses.  This method returns a list of all those references still alive.
2675+   Example::
2676+ 
2677+      >>> int.__subclasses__()
2678+      [<type 'bool'>]
2679+ 
2680+ 
2328.. rubric:: Footnotes
2329
n2330-.. [#] Additional  information on these special methods may be found in the Python
n2683+.. [#] Additional information on these special methods may be found in the Python
2331-   Reference Manual (XXX reference: ../ref/ref.html).
2684+   Reference Manual (:ref:`customization`).
2332
2333.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2334   similarly for tuples.
2335
2336.. [#] They must have since the parser can't tell the type of the operands.
2337
2338.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2339   element is the tuple to be formatted.
2340
2341.. [#] These numbers are fairly arbitrary.  They are intended to avoid printing endless
2342   strings of meaningless digits without hampering correct use and without having
2343   to know the exact precision of floating point values on a particular machine.
n2344- 
2345-.. [#] :func:`file` is new in Python 2.2.  The older built-in :func:`open` is an alias
2346-   for :func:`file`.
2347
2348.. [#] The advantage of leaving the newline on is that returning an empty string is
2349   then an unambiguous EOF indication.  It is also possible (in cases where it
2350   might matter, for example, if you want to make an exact copy of a file while
2351   scanning its lines) to tell whether the last line of a file ended in a newline
2352   or not (yes this happens!).
t2353- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op