Jeremy Kloth avatar Jeremy Kloth committed 8073225 Merge

merge default

Comments (0)

Files changed (435)

 4972a8f1b2aa3d7cdd64dc96aa7fa112fe1ea343 v3.3.0b2
 8bb5c7bc46ba43804480f3e328e1fa956672c885 v3.3.0rc1
 88a0792e8ba3e4916b24c7e7a522c277d326d66e v3.3.0rc2
+c191d21cefafb3832c45570e84854e309aa62eaa v3.3.0rc3
+bd8afb90ebf28ba4edc901d4a235f75e7bbc79fd v3.3.0
 	fi
 	@if [ ! -d tools/pygments ]; then \
 	  echo "Checking out Pygments..."; \
-	  svn checkout $(SVNROOT)/external/Pygments-1.3.1/pygments tools/pygments; \
+	  svn checkout $(SVNROOT)/external/Pygments-1.5dev-20120930/pygments tools/pygments; \
 	fi
 
 update: clean checkout

Doc/c-api/import.rst

    UTF-8 encoded string instead of a Unicode object.
 
    .. versionchanged:: 3.3
-         Negative values for **level** are no longer accepted.
+         Negative values for *level* are no longer accepted.
 
 .. c:function:: PyObject* PyImport_Import(PyObject *name)
 

Doc/c-api/object.rst

    returned.  This is the equivalent to the Python expression ``len(o)``.
 
 
+.. c:function:: Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t default)
+
+   Return an estimated length for the object *o*. First trying to return its
+   actual length, then an estimate using ``__length_hint__``, and finally
+   returning the default value. On error ``-1`` is returned. This is the
+   equivalent to the Python expression ``operator.length_hint(o, default)``.
+
+   .. versionadded:: 3.4
+
 .. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key)
 
    Return element of *o* corresponding to the object *key* or *NULL* on failure.

Doc/c-api/unicode.rst

    After completion, *\*byteorder* is set to the current byte order at the end
    of input data.
 
-   In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
-
    If *byteorder* is *NULL*, the codec starts in native order mode.
 
    Return *NULL* if an exception was raised by the codec.

Doc/extending/newtypes.rst

 bit does not indicate that the slot values are non-*NULL*. The flag may be set
 to indicate the presence of a slot, but a slot may still be unfilled.) ::
 
-   PyNumberMethods   tp_as_number;
-   PySequenceMethods tp_as_sequence;
-   PyMappingMethods  tp_as_mapping;
+   PyNumberMethods   *tp_as_number;
+   PySequenceMethods *tp_as_sequence;
+   PyMappingMethods  *tp_as_mapping;
 
 If you wish your object to be able to act like a number, a sequence, or a
 mapping object, then you place the address of a structure that implements the C

Doc/faq/windows.rst

 Why does os.path.isdir() fail on NT shared directories?
 -------------------------------------------------------
 
-The solution appears to be always append the "\\" on the end of shared
-drives.
+In order to work correctly, :func:`os.path.isdir` requires a ``"\\"`` at the
+end of the shared drive::
 
    >>> import os
-   >>> os.path.isdir( '\\\\rorschach\\public')
+   >>> os.path.isdir('\\\\rorschach\\public')
    0
-   >>> os.path.isdir( '\\\\rorschach\\public\\')
+   >>> os.path.isdir('\\\\rorschach\\public\\')
    1
 
 It helps to think of share points as being like drive letters.  Example::
    k:\media is a directory
    k:\media\ is not a directory
 
-The same rules apply if you substitute "k:" with "\\conky\foo"::
+The same rules apply if you substitute ``"k:"`` with ``"\\conky\foo"``::
 
    \\conky\foo  is not a directory
    \\conky\foo\ is a directory
 
    iterator
       An object representing a stream of data.  Repeated calls to the iterator's
-      :meth:`__next__` method (or passing it to the built-in function
+      :meth:`~iterator.__next__` method (or passing it to the built-in function
       :func:`next`) return successive items in the stream.  When no more data
       are available a :exc:`StopIteration` exception is raised instead.  At this
       point, the iterator object is exhausted and any further calls to its
    sequence
       An :term:`iterable` which supports efficient element access using integer
       indices via the :meth:`__getitem__` special method and defines a
-      :meth:`len` method that returns the length of the sequence.
+      :meth:`__len__` method that returns the length of the sequence.
       Some built-in sequence types are :class:`list`, :class:`str`,
       :class:`tuple`, and :class:`bytes`. Note that :class:`dict` also
       supports :meth:`__getitem__` and :meth:`__len__`, but is considered a

Doc/howto/functional.rst

 
 An iterator is an object representing a stream of data; this object returns the
 data one element at a time.  A Python iterator must support a method called
-``__next__()`` that takes no arguments and always returns the next element of
-the stream.  If there are no more elements in the stream, ``__next__()`` must
-raise the ``StopIteration`` exception.  Iterators don't have to be finite,
-though; it's perfectly reasonable to write an iterator that produces an infinite
-stream of data.
+:meth:`~iterator.__next__` that takes no arguments and always returns the next
+element of the stream.  If there are no more elements in the stream,
+:meth:`~iterator.__next__` must raise the :exc:`StopIteration` exception.
+Iterators don't have to be finite, though; it's perfectly reasonable to write
+an iterator that produces an infinite stream of data.
 
 The built-in :func:`iter` function takes an arbitrary object and tries to return
 an iterator that will return the object's contents or elements, raising
 :exc:`TypeError` if the object doesn't support iteration.  Several of Python's
 built-in data types support iteration, the most common being lists and
-dictionaries.  An object is called an **iterable** object if you can get an
-iterator for it.
+dictionaries.  An object is called :term:`iterable` if you can get an iterator
+for it.
 
 You can experiment with the iteration interface manually:
 
     >>> L = [1,2,3]
     >>> it = iter(L)
-    >>> it
+    >>> it  #doctest: +ELLIPSIS
     <...iterator object at ...>
-    >>> it.__next__()
+    >>> it.__next__()  # same as next(it)
     1
     >>> next(it)
     2
     >>>
 
 Python expects iterable objects in several different contexts, the most
-important being the ``for`` statement.  In the statement ``for X in Y``, Y must
-be an iterator or some object for which ``iter()`` can create an iterator.
-These two statements are equivalent::
+important being the :keyword:`for` statement.  In the statement ``for X in Y``,
+Y must be an iterator or some object for which :func:`iter` can create an
+iterator.  These two statements are equivalent::
 
 
     for i in iter(obj):
 iterator argument and will return the largest or smallest element.  The ``"in"``
 and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
 X is found in the stream returned by the iterator.  You'll run into obvious
-problems if the iterator is infinite; ``max()``, ``min()``
+problems if the iterator is infinite; :func:`max`, :func:`min`
 will never return, and if the element X never appears in the stream, the
 ``"in"`` and ``"not in"`` operators won't return either.
 
 Note that you can only go forward in an iterator; there's no way to get the
 previous element, reset the iterator, or make a copy of it.  Iterator objects
 can optionally provide these additional capabilities, but the iterator protocol
-only specifies the ``next()`` method.  Functions may therefore consume all of
-the iterator's output, and if you need to do something different with the same
-stream, you'll have to create a new iterator.
+only specifies the :meth:`~iterator.__next__` method.  Functions may therefore
+consume all of the iterator's output, and if you need to do something different
+with the same stream, you'll have to create a new iterator.
 
 
 
 iterator.
 
 Calling :func:`iter` on a dictionary returns an iterator that will loop over the
-dictionary's keys:
-
-.. not a doctest since dict ordering varies across Pythons
-
-::
+dictionary's keys::
 
     >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
     ...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
-    >>> for key in m:
+    >>> for key in m:  #doctest: +SKIP
     ...     print(key, m[key])
     Mar 3
     Feb 2
 Applying :func:`iter` to a dictionary always loops over the keys, but
 dictionaries have methods that return other iterators.  If you want to iterate
 over values or key/value pairs, you can explicitly call the
-:meth:`values` or :meth:`items` methods to get an appropriate iterator.
+:meth:`~dict.values` or :meth:`~dict.items` methods to get an appropriate
+iterator.
 
 The :func:`dict` constructor can accept an iterator that returns a finite stream
 of ``(key, value)`` tuples:
 
     >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
-    >>> dict(iter(L))
+    >>> dict(iter(L))  #doctest: +SKIP
     {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
 
-Files also support iteration by calling the ``readline()`` method until there
-are no more lines in the file.  This means you can read each line of a file like
-this::
+Files also support iteration by calling the :meth:`~io.TextIOBase.readline`
+method until there are no more lines in the file.  This means you can read each
+line of a file like this::
 
     for line in file:
         # do something for each line
 lengths of all the sequences.  If you have two lists of length 3, the output
 list is 9 elements long:
 
-.. doctest::
-    :options: +NORMALIZE_WHITESPACE
-
     >>> seq1 = 'abc'
     >>> seq2 = (1,2,3)
-    >>> [(x,y) for x in seq1 for y in seq2]
+    >>> [(x, y) for x in seq1 for y in seq2]  #doctest: +NORMALIZE_WHITESPACE
     [('a', 1), ('a', 2), ('a', 3),
      ('b', 1), ('b', 2), ('b', 3),
      ('c', 1), ('c', 2), ('c', 3)]
 comprehension below is a syntax error, while the second one is correct::
 
     # Syntax error
-    [ x,y for x in seq1 for y in seq2]
+    [x, y for x in seq1 for y in seq2]
     # Correct
-    [ (x,y) for x in seq1 for y in seq2]
+    [(x, y) for x in seq1 for y in seq2]
 
 
 Generators
 
 Here's the simplest example of a generator function:
 
-.. testcode::
+    >>> def generate_ints(N):
+    ...    for i in range(N):
+    ...        yield i
 
-    def generate_ints(N):
-        for i in range(N):
-            yield i
-
-Any function containing a ``yield`` keyword is a generator function; this is
-detected by Python's :term:`bytecode` compiler which compiles the function
-specially as a result.
+Any function containing a :keyword:`yield` keyword is a generator function;
+this is detected by Python's :term:`bytecode` compiler which compiles the
+function specially as a result.
 
 When you call a generator function, it doesn't return a single value; instead it
 returns a generator object that supports the iterator protocol.  On executing
 ``return`` statement.  The big difference between ``yield`` and a ``return``
 statement is that on reaching a ``yield`` the generator's state of execution is
 suspended and local variables are preserved.  On the next call to the
-generator's ``.__next__()`` method, the function will resume executing.
+generator's :meth:`~generator.__next__` method, the function will resume
+executing.
 
 Here's a sample usage of the ``generate_ints()`` generator:
 
     >>> gen = generate_ints(3)
-    >>> gen
+    >>> gen  #doctest: +ELLIPSIS
     <generator object generate_ints at ...>
     >>> next(gen)
     0
 ``return`` the generator cannot return any further values.  ``return`` with a
 value, such as ``return 5``, is a syntax error inside a generator function.  The
 end of the generator's results can also be indicated by raising
-``StopIteration`` manually, or by just letting the flow of execution fall off
+:exc:`StopIteration` manually, or by just letting the flow of execution fall off
 the bottom of the function.
 
 You could achieve the effect of generators manually by writing your own class
 and storing all the local variables of the generator as instance variables.  For
 example, returning a list of integers could be done by setting ``self.count`` to
-0, and having the ``__next__()`` method increment ``self.count`` and return it.
+0, and having the :meth:`~iterator.__next__` method increment ``self.count`` and
+return it.
 However, for a moderately complicated generator, writing a corresponding class
 can be much messier.
 
-The test suite included with Python's library, ``test_generators.py``, contains
+The test suite included with Python's library,
+:source:`Lib/test/test_generators.py`, contains
 a number of more interesting examples.  Here's one generator that implements an
 in-order traversal of a tree using generators recursively. ::
 
 The parentheses aren't always necessary, but it's easier to always add them
 instead of having to remember when they're needed.
 
-(PEP 342 explains the exact rules, which are that a ``yield``-expression must
+(:pep:`342` explains the exact rules, which are that a ``yield``-expression must
 always be parenthesized except when it occurs at the top-level expression on the
 right-hand side of an assignment.  This means you can write ``val = yield i``
 but have to use parentheses when there's an operation, as in ``val = (yield i)
 + 12``.)
 
-Values are sent into a generator by calling its ``send(value)`` method.  This
-method resumes the generator's code and the ``yield`` expression returns the
-specified value.  If the regular ``__next__()`` method is called, the ``yield``
-returns ``None``.
+Values are sent into a generator by calling its :meth:`send(value)
+<generator.send>` method.  This method resumes the generator's code and the
+``yield`` expression returns the specified value.  If the regular
+:meth:`~generator.__next__` method is called, the ``yield`` returns ``None``.
 
 Here's a simple counter that increments by 1 and allows changing the value of
 the internal counter.
 
 .. testcode::
 
-    def counter (maximum):
+    def counter(maximum):
         i = 0
         while i < maximum:
             val = (yield i)
 
 And here's an example of changing the counter:
 
-    >>> it = counter(10)
-    >>> next(it)
+    >>> it = counter(10)  #doctest: +SKIP
+    >>> next(it)  #doctest: +SKIP
     0
-    >>> next(it)
+    >>> next(it)  #doctest: +SKIP
     1
-    >>> it.send(8)
+    >>> it.send(8)  #doctest: +SKIP
     8
-    >>> next(it)
+    >>> next(it)  #doctest: +SKIP
     9
-    >>> next(it)
+    >>> next(it)  #doctest: +SKIP
     Traceback (most recent call last):
       File "t.py", line 15, in ?
         it.next()
 
 Because ``yield`` will often be returning ``None``, you should always check for
 this case.  Don't just use its value in expressions unless you're sure that the
-``send()`` method will be the only method used resume your generator function.
+:meth:`~generator.send` method will be the only method used resume your
+generator function.
 
-In addition to ``send()``, there are two other new methods on generators:
+In addition to :meth:`~generator.send`, there are two other methods on
+generators:
 
-* ``throw(type, value=None, traceback=None)`` is used to raise an exception
-  inside the generator; the exception is raised by the ``yield`` expression
-  where the generator's execution is paused.
+* :meth:`throw(type, value=None, traceback=None) <generator.throw>` is used to
+  raise an exception inside the generator; the exception is raised by the
+  ``yield`` expression where the generator's execution is paused.
 
-* ``close()`` raises a :exc:`GeneratorExit` exception inside the generator to
-  terminate the iteration.  On receiving this exception, the generator's code
-  must either raise :exc:`GeneratorExit` or :exc:`StopIteration`; catching the
-  exception and doing anything else is illegal and will trigger a
-  :exc:`RuntimeError`.  ``close()`` will also be called by Python's garbage
-  collector when the generator is garbage-collected.
+* :meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the
+  generator to terminate the iteration.  On receiving this exception, the
+  generator's code must either raise :exc:`GeneratorExit` or
+  :exc:`StopIteration`; catching the exception and doing anything else is
+  illegal and will trigger a :exc:`RuntimeError`.  :meth:`~generator.close`
+  will also be called by Python's garbage collector when the generator is
+  garbage-collected.
 
   If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
   using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
 Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
 features of generator expressions:
 
-``map(f, iterA, iterB, ...)`` returns an iterator over the sequence
+:func:`map(f, iterA, iterB, ...) <map>` returns an iterator over the sequence
  ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
 
     >>> def upper(s):
     ...     return s.upper()
 
-
     >>> list(map(upper, ['sentence', 'fragment']))
     ['SENTENCE', 'FRAGMENT']
     >>> [upper(s) for s in ['sentence', 'fragment']]
 
 You can of course achieve the same effect with a list comprehension.
 
-``filter(predicate, iter)`` returns an iterator over all the sequence elements
-that meet a certain condition, and is similarly duplicated by list
-comprehensions.  A **predicate** is a function that returns the truth value of
-some condition; for use with :func:`filter`, the predicate must take a single
-value.
+:func:`filter(predicate, iter) <filter>` returns an iterator over all the
+sequence elements that meet a certain condition, and is similarly duplicated by
+list comprehensions.  A **predicate** is a function that returns the truth
+value of some condition; for use with :func:`filter`, the predicate must take a
+single value.
 
     >>> def is_even(x):
     ...     return (x % 2) == 0
     [0, 2, 4, 6, 8]
 
 
-``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples
-containing the count and each element. ::
+:func:`enumerate(iter) <enumerate>` counts off the elements in the iterable,
+returning 2-tuples containing the count and each element. ::
 
     >>> for item in enumerate(['subject', 'verb', 'object']):
     ...     print(item)
         if line.strip() == '':
             print('Blank line at line #%i' % i)
 
-``sorted(iterable, [key=None], [reverse=False])`` collects all the elements of
-the iterable into a list, sorts the list, and returns the sorted result.  The
-``key``, and ``reverse`` arguments are passed through to the constructed list's
-``.sort()`` method. ::
+:func:`sorted(iterable, key=None, reverse=False) <sorted>` collects all the
+elements of the iterable into a list, sorts the list, and returns the sorted
+result.  The *key*, and *reverse* arguments are passed through to the
+constructed list's :meth:`~list.sort` method. ::
 
     >>> import random
     >>> # Generate 8 random numbers between [0, 10000)
     >>> rand_list = random.sample(range(10000), 8)
-    >>> rand_list
+    >>> rand_list  #doctest: +SKIP
     [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
-    >>> sorted(rand_list)
+    >>> sorted(rand_list)  #doctest: +SKIP
     [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
-    >>> sorted(rand_list, reverse=True)
+    >>> sorted(rand_list, reverse=True)  #doctest: +SKIP
     [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
 
-(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
-Python wiki at http://wiki.python.org/moin/HowTo/Sorting.)
+(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)
 
 
-The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an
-iterable's contents.  :func:`any` returns True if any element in the iterable is
-a true value, and :func:`all` returns True if all of the elements are true
-values:
+The :func:`any(iter) <any>` and :func:`all(iter) <all>` built-ins look at the
+truth values of an iterable's contents.  :func:`any` returns True if any element
+in the iterable is a true value, and :func:`all` returns True if all of the
+elements are true values:
 
     >>> any([0,1,0])
     True
     True
 
 
-``zip(iterA, iterB, ...)`` takes one element from each iterable and
+:func:`zip(iterA, iterB, ...) <zip>` takes one element from each iterable and
 returns them in a tuple::
 
     zip(['a', 'b', 'c'], (1, 2, 3)) =>
 Creating new iterators
 ----------------------
 
-``itertools.count(n)`` returns an infinite stream of integers, increasing by 1
-each time.  You can optionally supply the starting number, which defaults to 0::
+:func:`itertools.count(n) <itertools.count>` returns an infinite stream of
+integers, increasing by 1 each time.  You can optionally supply the starting
+number, which defaults to 0::
 
     itertools.count() =>
       0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
     itertools.count(10) =>
       10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
 
-``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable
-and returns a new iterator that returns its elements from first to last.  The
-new iterator will repeat these elements infinitely. ::
+:func:`itertools.cycle(iter) <itertools.cycle>` saves a copy of the contents of
+a provided iterable and returns a new iterator that returns its elements from
+first to last.  The new iterator will repeat these elements infinitely. ::
 
     itertools.cycle([1,2,3,4,5]) =>
       1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
 
-``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or
-returns the element endlessly if ``n`` is not provided. ::
+:func:`itertools.repeat(elem, [n]) <itertools.repeat>` returns the provided
+element *n* times, or returns the element endlessly if *n* is not provided. ::
 
     itertools.repeat('abc') =>
       abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
     itertools.repeat('abc', 5) =>
       abc, abc, abc, abc, abc
 
-``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as
-input, and returns all the elements of the first iterator, then all the elements
-of the second, and so on, until all of the iterables have been exhausted. ::
+:func:`itertools.chain(iterA, iterB, ...) <itertools.chain>` takes an arbitrary
+number of iterables as input, and returns all the elements of the first
+iterator, then all the elements of the second, and so on, until all of the
+iterables have been exhausted. ::
 
     itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
       a, b, c, 1, 2, 3
 
-``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a
-slice of the iterator.  With a single ``stop`` argument, it will return the
-first ``stop`` elements.  If you supply a starting index, you'll get
-``stop-start`` elements, and if you supply a value for ``step``, elements will
-be skipped accordingly.  Unlike Python's string and list slicing, you can't use
-negative values for ``start``, ``stop``, or ``step``. ::
+:func:`itertools.islice(iter, [start], stop, [step]) <itertools.islice>` returns
+a stream that's a slice of the iterator.  With a single *stop* argument, it
+will return the first *stop* elements.  If you supply a starting index, you'll
+get *stop-start* elements, and if you supply a value for *step*, elements
+will be skipped accordingly.  Unlike Python's string and list slicing, you can't
+use negative values for *start*, *stop*, or *step*. ::
 
     itertools.islice(range(10), 8) =>
       0, 1, 2, 3, 4, 5, 6, 7
     itertools.islice(range(10), 2, 8, 2) =>
       2, 4, 6
 
-``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n``
-independent iterators that will all return the contents of the source iterator.
-If you don't supply a value for ``n``, the default is 2.  Replicating iterators
+:func:`itertools.tee(iter, [n]) <itertools.tee>` replicates an iterator; it
+returns *n* independent iterators that will all return the contents of the
+source iterator.
+If you don't supply a value for *n*, the default is 2.  Replicating iterators
 requires saving some of the contents of the source iterator, so this can consume
 significant memory if the iterator is large and one of the new iterators is
 consumed more than the others. ::
 Calling functions on elements
 -----------------------------
 
-The ``operator`` module contains a set of functions corresponding to Python's
-operators.  Some examples are ``operator.add(a, b)`` (adds two values),
-``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')``
-(returns a callable that fetches the ``"id"`` attribute).
+The :mod:`operator` module contains a set of functions corresponding to Python's
+operators.  Some examples are :func:`operator.add(a, b) <operator.add>` (adds
+two values), :func:`operator.ne(a, b)  <operator.ne>` (same as ``a != b``), and
+:func:`operator.attrgetter('id') <operator.attrgetter>`
+(returns a callable that fetches the ``.id`` attribute).
 
-``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
-of tuples, and calls ``f()`` using these tuples as the arguments::
+:func:`itertools.starmap(func, iter) <itertools.starmap>` assumes that the
+iterable will return a stream of tuples, and calls *func* using these tuples as
+the arguments::
 
     itertools.starmap(os.path.join,
-                      [('/usr', 'bin', 'java'), ('/bin', 'python'),
-                       ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
+                      [('/bin', 'python'), ('/usr', 'bin', 'java'),
+                       ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
     =>
-      /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby
+      /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
 
 
 Selecting elements
 Another group of functions chooses a subset of an iterator's elements based on a
 predicate.
 
-``itertools.filterfalse(predicate, iter)`` is the opposite, returning all
-elements for which the predicate returns false::
+:func:`itertools.filterfalse(predicate, iter) <itertools.filterfalse>` is the
+opposite, returning all elements for which the predicate returns false::
 
     itertools.filterfalse(is_even, itertools.count()) =>
       1, 3, 5, 7, 9, 11, 13, 15, ...
 
-``itertools.takewhile(predicate, iter)`` returns elements for as long as the
-predicate returns true.  Once the predicate returns false, the iterator will
-signal the end of its results.
-
-::
+:func:`itertools.takewhile(predicate, iter) <itertools.takewhile>` returns
+elements for as long as the predicate returns true.  Once the predicate returns
+false, the iterator will signal the end of its results. ::
 
     def less_than_10(x):
-        return (x < 10)
+        return x < 10
 
     itertools.takewhile(less_than_10, itertools.count()) =>
       0, 1, 2, 3, 4, 5, 6, 7, 8, 9
     itertools.takewhile(is_even, itertools.count()) =>
       0
 
-``itertools.dropwhile(predicate, iter)`` discards elements while the predicate
-returns true, and then returns the rest of the iterable's results.
-
-::
+:func:`itertools.dropwhile(predicate, iter) <itertools.dropwhile>` discards
+elements while the predicate returns true, and then returns the rest of the
+iterable's results. ::
 
     itertools.dropwhile(less_than_10, itertools.count()) =>
       10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
 Grouping elements
 -----------------
 
-The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is
-the most complicated.  ``key_func(elem)`` is a function that can compute a key
-value for each element returned by the iterable.  If you don't supply a key
-function, the key is simply each element itself.
+The last function I'll discuss, :func:`itertools.groupby(iter, key_func=None)
+<itertools.groupby>`, is the most complicated.  ``key_func(elem)`` is a function
+that can compute a key value for each element returned by the iterable.  If you
+don't supply a key function, the key is simply each element itself.
 
-``groupby()`` collects all the consecutive elements from the underlying iterable
-that have the same key value, and returns a stream of 2-tuples containing a key
-value and an iterator for the elements with that key.
+:func:`~itertools.groupby` collects all the consecutive elements from the
+underlying iterable that have the same key value, and returns a stream of
+2-tuples containing a key value and an iterator for the elements with that key.
 
 ::
 
                  ...
                 ]
 
-    def get_state (city_state):
+    def get_state(city_state):
         return city_state[1]
 
     itertools.groupby(city_list, get_state) =>
     iterator-3 =>
       ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
 
-``groupby()`` assumes that the underlying iterable's contents will already be
-sorted based on the key.  Note that the returned iterators also use the
-underlying iterable, so you have to consume the results of iterator-1 before
+:func:`~itertools.groupby` assumes that the underlying iterable's contents will
+already be sorted based on the key.  Note that the returned iterators also use
+the underlying iterable, so you have to consume the results of iterator-1 before
 requesting iterator-2 and its corresponding key.
 
 
 ``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
 one of ``f()``'s parameters.  This is called "partial function application".
 
-The constructor for ``partial`` takes the arguments ``(function, arg1, arg2,
-... kwarg1=value1, kwarg2=value2)``.  The resulting object is callable, so you
-can just call it to invoke ``function`` with the filled-in arguments.
+The constructor for :func:`~functools.partial` takes the arguments
+``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``.  The resulting
+object is callable, so you can just call it to invoke ``function`` with the
+filled-in arguments.
 
 Here's a small but realistic example::
 
     import functools
 
-    def log (message, subsystem):
-        "Write the contents of 'message' to the specified subsystem."
+    def log(message, subsystem):
+        """Write the contents of 'message' to the specified subsystem."""
         print('%s: %s' % (subsystem, message))
         ...
 
     server_log = functools.partial(log, subsystem='server')
     server_log('Unable to open socket')
 
-``functools.reduce(func, iter, [initial_value])`` cumulatively performs an
-operation on all the iterable's elements and, therefore, can't be applied to
-infinite iterables.  (Note it is not in :mod:`builtins`, but in the
-:mod:`functools` module.)  ``func`` must be a function that takes two elements
-and returns a single value.  :func:`functools.reduce` takes the first two
-elements A and B returned by the iterator and calculates ``func(A, B)``.  It
-then requests the third element, C, calculates ``func(func(A, B), C)``, combines
-this result with the fourth element returned, and continues until the iterable
-is exhausted.  If the iterable returns no values at all, a :exc:`TypeError`
-exception is raised.  If the initial value is supplied, it's used as a starting
-point and ``func(initial_value, A)`` is the first calculation. ::
+:func:`functools.reduce(func, iter, [initial_value]) <functools.reduce>`
+cumulatively performs an operation on all the iterable's elements and,
+therefore, can't be applied to infinite iterables. *func* must be a function
+that takes two elements and returns a single value.  :func:`functools.reduce`
+takes the first two elements A and B returned by the iterator and calculates
+``func(A, B)``.  It then requests the third element, C, calculates
+``func(func(A, B), C)``, combines this result with the fourth element returned,
+and continues until the iterable is exhausted.  If the iterable returns no
+values at all, a :exc:`TypeError` exception is raised.  If the initial value is
+supplied, it's used as a starting point and ``func(initial_value, A)`` is the
+first calculation. ::
 
     >>> import operator, functools
     >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
     >>> sum([])
     0
 
-For many uses of :func:`functools.reduce`, though, it can be clearer to just write the
-obvious :keyword:`for` loop::
+For many uses of :func:`functools.reduce`, though, it can be clearer to just
+write the obvious :keyword:`for` loop::
 
    import functools
    # Instead of:
     existing_files = filter(os.path.exists, file_list)
 
 If the function you need doesn't exist, you need to write it.  One way to write
-small functions is to use the ``lambda`` statement.  ``lambda`` takes a number
-of parameters and an expression combining these parameters, and creates a small
-function that returns the value of the expression::
+small functions is to use the :keyword:`lambda` statement.  ``lambda`` takes a
+number of parameters and an expression combining these parameters, and creates
+an anonymous function that returns the value of the expression::
 
-    lowercase = lambda x: x.lower()
+    adder = lambda x, y: x+y
 
     print_assign = lambda name, value: name + '=' + str(value)
 
-    adder = lambda x, y: x+y
-
 An alternative is to just use the ``def`` statement and define a function in the
 usual way::
 
-    def lowercase(x):
-        return x.lower()
+    def adder(x, y):
+        return x + y
 
     def print_assign(name, value):
         return name + '=' + str(value)
 
-    def adder(x,y):
-        return x + y
-
 Which alternative is preferable?  That's a style question; my usual course is to
 avoid using ``lambda``.
 
 expression, which means you can't have multiway ``if... elif... else``
 comparisons or ``try... except`` statements.  If you try to do too much in a
 ``lambda`` statement, you'll end up with an overly complicated expression that's
-hard to read.  Quick, what's the following code doing?
-
-::
+hard to read.  Quick, what's the following code doing? ::
 
     import functools
     total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
 little bit better::
 
     import functools
-    def combine (a, b):
+    def combine(a, b):
         return 0, a[1] + b[1]
 
     total = functools.reduce(combine, items)[1]
 Fredrik Lundh once suggested the following set of rules for refactoring uses of
 ``lambda``:
 
-1) Write a lambda function.
-2) Write a comment explaining what the heck that lambda does.
-3) Study the comment for a while, and think of a name that captures the essence
+1. Write a lambda function.
+2. Write a comment explaining what the heck that lambda does.
+3. Study the comment for a while, and think of a name that captures the essence
    of the comment.
-4) Convert the lambda to a def statement, using that name.
-5) Remove the comment.
+4. Convert the lambda to a def statement, using that name.
+5. Remove the comment.
 
 I really like these rules, but you're free to disagree
 about whether this lambda-free style is better.

Doc/howto/ipaddress.rst

 .. _ipaddress-howto:
 
 ***************************************
-An Introduction to the ipaddress module
+An introduction to the ipaddress module
 ***************************************
 
 :author: Peter Moody
 when working with IP addressing. The simplest way to create addresses is
 to use the :func:`ipaddress.ip_address` factory function, which automatically
 determines whether to create an IPv4 or IPv6 address based on the passed in
-value::
+value:
+
+.. testsetup::
+   >>> import ipaddress
+
+::
 
    >>> ipaddress.ip_address('192.0.2.1')
    IPv4Address('192.0.2.1')
 
    >>> ipaddress.ip_interface('192.0.2.1/24')
    IPv4Interface('192.0.2.1/24')
-   >>> ipaddress.ip_network('2001:db8::1/96')
+   >>> ipaddress.ip_interface('2001:db8::1/96')
    IPv6Interface('2001:db8::1/96')
 
 Integer inputs are accepted (as with networks), and use of a particular IP
 Finding out how many individual addresses are in a network::
 
    >>> net4 = ipaddress.ip_network('192.0.2.0/24')
-   >>> net4.numhosts
+   >>> net4.num_addresses
    256
    >>> net6 = ipaddress.ip_network('2001:db8::0/96')
-   >>> net6.numhosts
+   >>> net6.num_addresses
    4294967296
 
 Iterating through the "usable" addresses on a network::
 
    >>> net4 = ipaddress.ip_network('192.0.2.0/24')
    >>> for x in net4.hosts():
-          print(x)
+   ...     print(x)  # doctest: +ELLIPSIS
    192.0.2.1
    192.0.2.2
    192.0.2.3
    192.0.2.4
-   <snip>
+   ...
    192.0.2.252
    192.0.2.253
    192.0.2.254
 Exploding or compressing the address::
 
    >>> addr6.exploded
-   '2001:0db8:0000:0000:0000:0000:0000:0000'
+   '2001:0db8:0000:0000:0000:0000:0000:0001'
    >>> addr6.compressed
-   '2001:db8::'
+   '2001:db8::1'
    >>> net6.exploded
    '2001:0db8:0000:0000:0000:0000:0000:0000/96'
    >>> net6.compressed
    >>> net4[-1]
    IPv4Address('192.0.2.255')
    >>> net6[1]
-   IPv6Address('2001::1')
+   IPv6Address('2001:db8::1')
    >>> net6[-1]
-   IPv6Address('2001::ffff:ffff')
+   IPv6Address('2001:db8::ffff:ffff')
 
 
 It also means that network objects lend themselves to using the list

Doc/howto/unicode.rst

     UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
       invalid start byte
     >>> b'\x80abc'.decode("utf-8", "replace")
-    'abc'
+    '\ufffdabc'
     >>> b'\x80abc'.decode("utf-8", "ignore")
     'abc'
 
 ----------
 
 The ``str`` type is described in the Python library reference at
-:ref:`typesseq`.
+:ref:`textseq`.
 
 The documentation for the :mod:`unicodedata` module.
 

Doc/howto/urllib2.rst

     >>> data['location'] = 'Northampton'
     >>> data['language'] = 'Python'
     >>> url_values = urllib.parse.urlencode(data)
-    >>> print(url_values)
+    >>> print(url_values)  # The order may differ from below.  #doctest: +SKIP
     name=Somebody+Here&language=Python&location=Northampton
     >>> url = 'http://www.example.com/example.cgi'
     >>> full_url = url + '?' + url_values
 
     >>> req = urllib.request.Request('http://www.pretend_server.org')
     >>> try: urllib.request.urlopen(req)
-    >>> except urllib.error.URLError as e:
-    >>>    print(e.reason)
-    >>>
+    ... except urllib.error.URLError as e:
+    ...    print(e.reason)      #doctest: +SKIP
+    ...
     (4, 'getaddrinfo failed')
 
 
 
     >>> req = urllib.request.Request('http://www.python.org/fish.html')
     >>> try:
-    >>>     urllib.request.urlopen(req)
-    >>> except urllib.error.HTTPError as e:
-    >>>     print(e.code)
-    >>>     print(e.read())
-    >>>
+    ...     urllib.request.urlopen(req)
+    ... except urllib.error.HTTPError as e:
+    ...     print(e.code)
+    ...     print(e.read())  #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+    ...
     404
-    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
-        "http://www.w3.org/TR/html4/loose.dtd">
-    <?xml-stylesheet href="./css/ht2html.css"
-        type="text/css"?>
-    <html><head><title>Error 404: File Not Found</title>
-    ...... etc...
+    b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
+      ...
+      <title>Page Not Found</title>\n
+      ...
 
 Wrapping it Up
 --------------

Doc/library/2to3.rst

 also located in the :file:`Tools/scripts` directory of the Python root.
 
 2to3's basic arguments are a list of files or directories to transform.  The
-directories are to recursively traversed for Python sources.
+directories are recursively traversed for Python sources.
 
 Here is a sample Python 2.x source file, :file:`example.py`::
 

Doc/library/argparse.rst

    >>> parser.parse_args(''.split())
    Namespace(foo=42)
 
+If the ``default`` value is a string, the parser parses the value as if it
+were a command-line argument.  In particular, the parser applies any type_
+conversion argument, if provided, before setting the attribute on the
+:class:`Namespace` return value.  Otherwise, the parser uses the value as is::
+
+   >>> parser = argparse.ArgumentParser()
+   >>> parser.add_argument('--length', default='10', type=int)
+   >>> parser.add_argument('--width', default=10.5, type=int)
+   >>> parser.parse_args()
+   Namespace(length=10, width=10.5)
+
 For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
 is used when no command-line argument was present::
 
    >>> parser.parse_args('2 temp.txt'.split())
    Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
 
+See the section on the default_ keyword argument for information on when the
+``type`` argument is applied to default arguments.
+
 To ease the use of various types of files, the argparse module provides the
 factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
 :func:`open` function.  For example, ``FileType('w')`` can be used to create a

Doc/library/collections.rst

 
         d['x']                # Get first key in the chain of contexts
         d['x'] = 1            # Set value in current context
-        del['x']              # Delete from current context
+        del d['x']            # Delete from current context
         list(d)               # All nested values
         k in d                # Check all nested values
         len(d)                # Number of nested values
     this section documents the minimum range and type restrictions.
 
     * The :class:`Counter` class itself is a dictionary subclass with no
-        restrictions on its keys and values.  The values are intended to be numbers
-        representing counts, but you *could* store anything in the value field.
+      restrictions on its keys and values.  The values are intended to be numbers
+      representing counts, but you *could* store anything in the value field.
 
     * The :meth:`most_common` method requires only that the values be orderable.
 
     * For in-place operations such as ``c[key] += 1``, the value type need only
-        support addition and subtraction.  So fractions, floats, and decimals would
-        work and negative values are supported.  The same is also true for
-        :meth:`update` and :meth:`subtract` which allow negative and zero values
-        for both inputs and outputs.
+      support addition and subtraction.  So fractions, floats, and decimals would
+      work and negative values are supported.  The same is also true for
+      :meth:`update` and :meth:`subtract` which allow negative and zero values
+      for both inputs and outputs.
 
     * The multiset methods are designed only for use cases with positive values.
-        The inputs may be negative or zero, but only outputs with positive values
-        are created.  There are no type restrictions, but the value type needs to
-        support addition, subtraction, and comparison.
+      The inputs may be negative or zero, but only outputs with positive values
+      are created.  There are no type restrictions, but the value type needs to
+      support addition, subtraction, and comparison.
 
     * The :meth:`elements` method requires integer counts.  It ignores zero and
-        negative counts.
+      negative counts.
 
 .. seealso::
 

Doc/library/concurrency.rst

 
    threading.rst
    multiprocessing.rst
+   concurrent.rst
    concurrent.futures.rst
    subprocess.rst
    sched.rst

Doc/library/concurrent.futures.rst

 
        Equivalent to ``map(func, *iterables)`` except *func* is executed
        asynchronously and several calls to *func* may be made concurrently.  The
-       returned iterator raises a :exc:`TimeoutError` if :meth:`__next__()` is
-       called and the result isn't available after *timeout* seconds from the
-       original call to :meth:`Executor.map`. *timeout* can be an int or a
-       float.  If *timeout* is not specified or ``None``, there is no limit to
-       the wait time.  If a call raises an exception, then that exception will
-       be raised when its value is retrieved from the iterator.
+       returned iterator raises a :exc:`TimeoutError` if
+       :meth:`~iterator.__next__` is called and the result isn't available
+       after *timeout* seconds from the original call to :meth:`Executor.map`.
+       *timeout* can be an int or a float.  If *timeout* is not specified or
+       ``None``, there is no limit to the wait time.  If a call raises an
+       exception, then that exception will be raised when its value is
+       retrieved from the iterator.
 
     .. method:: shutdown(wait=True)
 
            'http://www.bbc.co.uk/',
            'http://some-made-up-domain.com/']
 
+   # Retrieve a single page and report the url and contents
    def load_url(url, timeout):
-       return urllib.request.urlopen(url, timeout=timeout).read()
+       conn = urllib.request.urlopen(url, timeout=timeout)
+       return conn.readall()
 
+   # We can use a with statement to ensure threads are cleaned up promptly
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
-       future_to_url = dict((executor.submit(load_url, url, 60), url)
-                            for url in URLS)
-
+       # Start the load operations and mark each future with its URL
+       future_to_url = {executor.submit(load_url, url, 60):url for url in URLS}
        for future in concurrent.futures.as_completed(future_to_url):
            url = future_to_url[future]
-           if future.exception() is not None:
-               print('%r generated an exception: %s' % (url,
-                                                        future.exception()))
+           try:
+               data = future.result()
+           except Exception as exc:
+               print('%r generated an exception: %s' % (url, exc))
            else:
-               print('%r page is %d bytes' % (url, len(future.result())))
+               print('%r page is %d bytes' % (url, len(data)))
 
 
 ProcessPoolExecutor
    different :class:`Executor` instances) given by *fs* that yields futures as
    they complete (finished or were cancelled).  Any futures that completed
    before :func:`as_completed` is called will be yielded first.  The returned
-   iterator raises a :exc:`TimeoutError` if :meth:`__next__` is called and the
-   result isn't available after *timeout* seconds from the original call to
-   :func:`as_completed`.  *timeout* can be an int or float.  If *timeout* is not
-   specified or ``None``, there is no limit to the wait time.
+   iterator raises a :exc:`TimeoutError` if :meth:`~iterator.__next__` is
+   called and the result isn't available after *timeout* seconds from the
+   original call to :func:`as_completed`.  *timeout* can be an int or float.
+   If *timeout* is not specified or ``None``, there is no limit to the wait
+   time.
 
 
 .. seealso::

Doc/library/concurrent.rst

+The :mod:`concurrent` package
+=============================
+
+Currently, there is only one module in this package:
+
+* :mod:`concurrent.futures` -- Launching parallel tasks

Doc/library/configparser.rst

    # values using the mapping protocol or ConfigParser's set() does not allow
    # such assignments to take place.
    config.add_section('Section1')
-   config.set('Section1', 'int', '15')
-   config.set('Section1', 'bool', 'true')
-   config.set('Section1', 'float', '3.1415')
+   config.set('Section1', 'an_int', '15')
+   config.set('Section1', 'a_bool', 'true')
+   config.set('Section1', 'a_float', '3.1415')
    config.set('Section1', 'baz', 'fun')
    config.set('Section1', 'bar', 'Python')
    config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
 
    # getfloat() raises an exception if the value is not a float
    # getint() and getboolean() also do this for their respective types
-   float = config.getfloat('Section1', 'float')
-   int = config.getint('Section1', 'int')
-   print(float + int)
+   a_float = config.getfloat('Section1', 'a_float')
+   an_int = config.getint('Section1', 'an_int')
+   print(a_float + an_int)
 
    # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
    # This is because we are using a RawConfigParser().
-   if config.getboolean('Section1', 'bool'):
+   if config.getboolean('Section1', 'a_bool'):
        print(config.get('Section1', 'foo'))
 
 To get interpolation, use :class:`ConfigParser`::

Doc/library/crypt.rst

 Examples
 --------
 
-A simple example illustrating typical use::
+A simple example illustrating typical use (a constant-time comparison
+operation is needed to limit exposure to timing attacks.
+:func:`hmac.compare_digest` is suitable for this purpose)::
 
    import pwd
    import crypt
    import getpass
+   from hmac import compare_digest as compare_hash
 
    def login():
        username = input('Python login: ')
            if cryptedpasswd == 'x' or cryptedpasswd == '*':
                raise ValueError('no support for shadow passwords')
            cleartext = getpass.getpass()
-           return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd
+           return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
        else:
            return True
 
 check it against the original::
 
    import crypt
+   from hmac import compare_digest as compare_hash
 
    hashed = crypt.crypt(plaintext)
-   if hashed != crypt.crypt(plaintext, hashed):
+   if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
       raise ValueError("hashed version doesn't validate against original")

Doc/library/crypto.rst

 
 The modules described in this chapter implement various algorithms of a
 cryptographic nature.  They are available at the discretion of the installation.
+On Unix systems, the :mod:`crypt` module may also be available.
 Here's an overview:
 
 

Doc/library/dis.rst

 
 .. opcode:: FOR_ITER (delta)
 
-   ``TOS`` is an :term:`iterator`.  Call its :meth:`__next__` method.  If this
-   yields a new value, push it on the stack (leaving the iterator below it).  If
-   the iterator indicates it is exhausted ``TOS`` is popped, and the byte code
-   counter is incremented by *delta*.
+   ``TOS`` is an :term:`iterator`.  Call its :meth:`~iterator.__next__` method.
+   If this yields a new value, push it on the stack (leaving the iterator below
+   it).  If the iterator indicates it is exhausted ``TOS`` is popped, and the
+   byte code counter is incremented by *delta*.
 
 
 .. opcode:: LOAD_GLOBAL (namei)

Doc/library/doctest.rst

+:keepdoctest:
+
 :mod:`doctest` --- Test interactive Python examples
 ===================================================
 
   Tabs in output generated by the tested code are not modified.  Because any
   hard tabs in the sample output *are* expanded, this means that if the code
   output includes hard tabs, the only way the doctest can pass is if the
-  :const:`NORMALIZE_WHITESPACE` option or directive is in effect.
+  :const:`NORMALIZE_WHITESPACE` option or :ref:`directive <doctest-directives>`
+  is in effect.
   Alternatively, the test can be rewritten to capture the output and compare it
   to an expected value as part of the test.  This handling of tabs in the
   source was arrived at through trial and error, and has proven to be the least
      Backslashes in a raw docstring: m\n
 
   Otherwise, the backslash will be interpreted as part of the string. For example,
-  the "\\" above would be interpreted as a newline character.  Alternatively, you
+  the ``\n`` above would be interpreted as a newline character.  Alternatively, you
   can double each backslash in the doctest version (and not use a raw string)::
 
      >>> def f(x):
      SyntaxError: invalid syntax
 
 
+.. _option-flags-and-directives:
 .. _doctest-options:
 
-Option Flags and Directives
-^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Option Flags
+^^^^^^^^^^^^
 
 A number of option flags control various aspects of doctest's behavior.
 Symbolic names for the flags are supplied as module constants, which can be
 or'ed together and passed to various functions.  The names can also be used in
-doctest directives (see below).
+:ref:`doctest directives <doctest-directives>`.
 
 The first group of options define test semantics, controlling aspects of how
 doctest decides whether actual output matches an example's expected output:
    :exc:`TypeError` is raised.
 
    It will also ignore the module name used in Python 3 doctest reports. Hence
-   both these variations will work regardless of whether the test is run under
-   Python 2.7 or Python 3.2 (or later versions):
+   both of these variations will work with the flag specified, regardless of
+   whether the test is run under Python 2.7 or Python 3.2 (or later versions)::
 
-      >>> raise CustomError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
+      >>> raise CustomError('message')
       Traceback (most recent call last):
       CustomError: message
 
-      >>> raise CustomError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
+      >>> raise CustomError('message')
       Traceback (most recent call last):
       my_module.CustomError: message
 
    exception name. Using :const:`IGNORE_EXCEPTION_DETAIL` and the details
    from Python 2.3 is also the only clear way to write a doctest that doesn't
    care about the exception detail yet continues to pass under Python 2.3 or
-   earlier (those releases do not support doctest directives and ignore them
-   as irrelevant comments). For example, ::
+   earlier (those releases do not support :ref:`doctest directives
+   <doctest-directives>` and ignore them as irrelevant comments). For example::
 
-      >>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
+      >>> (1, 2)[3] = 'moo'
       Traceback (most recent call last):
         File "<stdin>", line 1, in ?
       TypeError: object doesn't support item assignment
 
-   passes under Python 2.3 and later Python versions, even though the detail
+   passes under Python 2.3 and later Python versions with the flag specified,
+   even though the detail
    changed in Python 2.4 to say "does not" instead of "doesn't".
 
    .. versionchanged:: 3.2
 
    A bitmask or'ing together all the reporting flags above.
 
-"Doctest directives" may be used to modify the option flags for individual
-examples.  Doctest directives are expressed as a special Python comment
-following an example's source code:
+
+There is also a way to register new option flag names, though this isn't
+useful unless you intend to extend :mod:`doctest` internals via subclassing:
+
+
+.. function:: register_optionflag(name)
+
+   Create a new option flag with a given name, and return the new flag's integer
+   value.  :func:`register_optionflag` can be used when subclassing
+   :class:`OutputChecker` or :class:`DocTestRunner` to create new options that are
+   supported by your subclasses.  :func:`register_optionflag` should always be
+   called using the following idiom::
+
+      MY_FLAG = register_optionflag('MY_FLAG')
+
+
+.. _doctest-directives:
+
+Directives
+^^^^^^^^^^
+
+Doctest directives may be used to modify the :ref:`option flags
+<doctest-options>` for an individual example.  Doctest directives are
+special Python comments following an example's source code:
 
 .. productionlist:: doctest
    directive: "#" "doctest:" `directive_options`
 
 For example, this test passes::
 
-   >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
+   >>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE
    [0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
    10,  11, 12, 13, 14, 15, 16, 17, 18, 19]
 
    >>> print(list(range(20))) # doctest: +ELLIPSIS
    [0, 1, ..., 18, 19]
 
-Multiple directives can be used on a single physical line, separated by commas::
+Multiple directives can be used on a single physical line, separated by
+commas::
 
    >>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    [0,    1, ...,   18,    19]
 functions that run doctests, establishing different defaults.  In such cases,
 disabling an option via ``-`` in a directive can be useful.
 
-There's also a way to register new option flag names, although this isn't useful
-unless you intend to extend :mod:`doctest` internals via subclassing:
-
-
-.. function:: register_optionflag(name)
-
-   Create a new option flag with a given name, and return the new flag's integer
-   value.  :func:`register_optionflag` can be used when subclassing
-   :class:`OutputChecker` or :class:`DocTestRunner` to create new options that are
-   supported by your subclasses.  :func:`register_optionflag` should always be
-   called using the following idiom::
-
-      MY_FLAG = register_optionflag('MY_FLAG')
-
 
 .. _doctest-warnings:
 

Doc/library/dummy_threading.rst

    try:
        import threading
    except ImportError:
-       import dummy_threading
+       import dummy_threading as threading
 
 Be careful to not use this module where deadlock might occur from a thread being
 created that blocks waiting for another thread to be created.  This often occurs

Doc/library/exceptions.rst

 .. exception:: StopIteration
 
    Raised by built-in function :func:`next` and an :term:`iterator`\'s
-   :meth:`__next__` method to signal that there are no further items to be
-   produced by the iterator.
+   :meth:`~iterator.__next__` method to signal that there are no further
+   items produced by the iterator.
 
    The exception object has a single attribute :attr:`value`, which is
    given as an argument when constructing the exception, and defaults
 
 .. exception:: ConnectionError
 
-   A base class for connection-related issues.  Subclasses are
-   :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
+   A base class for connection-related issues.
+
+   Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
    :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
 
-   .. exception:: BrokenPipeError
+.. exception:: BrokenPipeError
 
-      A subclass of :exc:`ConnectionError`, raised when trying to write on a
-      pipe while the other end has been closed, or trying to write on a socket
-      which has been shutdown for writing.
-      Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
+   A subclass of :exc:`ConnectionError`, raised when trying to write on a
+   pipe while the other end has been closed, or trying to write on a socket
+   which has been shutdown for writing.
+   Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
 
-   .. exception:: ConnectionAbortedError
+.. exception:: ConnectionAbortedError
 
-      A subclass of :exc:`ConnectionError`, raised when a connection attempt
-      is aborted by the peer.
-      Corresponds to :c:data:`errno` ``ECONNABORTED``.
+   A subclass of :exc:`ConnectionError`, raised when a connection attempt
+   is aborted by the peer.
+   Corresponds to :c:data:`errno` ``ECONNABORTED``.
 
-   .. exception:: ConnectionRefusedError
+.. exception:: ConnectionRefusedError
 
-      A subclass of :exc:`ConnectionError`, raised when a connection attempt
-      is refused by the peer.
-      Corresponds to :c:data:`errno` ``ECONNREFUSED``.
+   A subclass of :exc:`ConnectionError`, raised when a connection attempt
+   is refused by the peer.
+   Corresponds to :c:data:`errno` ``ECONNREFUSED``.
 
-   .. exception:: ConnectionResetError
+.. exception:: ConnectionResetError
 
-      A subclass of :exc:`ConnectionError`, raised when a connection is
-      reset by the peer.
-      Corresponds to :c:data:`errno` ``ECONNRESET``.
+   A subclass of :exc:`ConnectionError`, raised when a connection is
+   reset by the peer.
+   Corresponds to :c:data:`errno` ``ECONNRESET``.
 
 .. exception:: FileExistsError
 

Doc/library/faulthandler.rst

 Dump the tracebacks after a timeout
 -----------------------------------
 
-.. function:: dump_tracebacks_later(timeout, repeat=False, file=sys.stderr, exit=False)
+.. function:: dump_traceback_later(timeout, repeat=False, file=sys.stderr, exit=False)
 
    Dump the tracebacks of all threads, after a timeout of *timeout* seconds, or
    every *timeout* seconds if *repeat* is ``True``.  If *exit* is ``True``, call
    This function is implemented using a watchdog thread and therefore is not
    available if Python is compiled with threads disabled.
 
-.. function:: cancel_dump_tracebacks_later()
+.. function:: cancel_dump_traceback_later()
 
-   Cancel the last call to :func:`dump_tracebacks_later`.
+   Cancel the last call to :func:`dump_traceback_later`.
 
 
 Dump the traceback on a user signal
 File descriptor issue
 ---------------------
 
-:func:`enable`, :func:`dump_tracebacks_later` and :func:`register` keep the
+:func:`enable`, :func:`dump_traceback_later` and :func:`register` keep the
 file descriptor of their *file* argument. If the file is closed and its file
 descriptor is reused by a new file, or if :func:`os.dup2` is used to replace</