Issue #23921: Standardized documentation whitespace formatting.
Original patch by James Edwards.
diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst
index 3f4a04b..1e523d4 100644
--- a/Doc/faq/design.rst
+++ b/Doc/faq/design.rst
@@ -169,7 +169,7 @@
        line = f.readline()
        if not line:
            break
-       ... # do something with line
+       ...  # do something with line
 
 The reason for not allowing assignment in Python expressions is a common,
 hard-to-find bug in those other languages, caused by this construct:
@@ -201,7 +201,7 @@
 
    line = f.readline()
    while line:
-       ... # do something with line...
+       ...  # do something with line...
        line = f.readline()
 
 The problem with this is that if you change your mind about exactly how you get
@@ -214,7 +214,7 @@
 Python file objects support the iterator protocol, so you can now write simply::
 
    for line in f:
-       ... # do something with line...
+       ...  # do something with line...
 
 
 
@@ -625,8 +625,10 @@
    class ListWrapper:
        def __init__(self, the_list):
            self.the_list = the_list
+
        def __eq__(self, other):
            return self.the_list == other.the_list
+
        def __hash__(self):
            l = self.the_list
            result = 98767 - len(l)*555
@@ -667,7 +669,7 @@
 order::
 
    for key in sorted(mydict):
-       ... # do whatever with mydict[key]...
+       ...  # do whatever with mydict[key]...
 
 
 How do you specify and enforce an interface spec in Python?
@@ -723,11 +725,11 @@
    class label: pass  # declare a label
 
    try:
-        ...
-        if condition: raise label()  # goto label
-        ...
+       ...
+       if condition: raise label()  # goto label
+       ...
    except label:  # where to goto
-        pass
+       pass
    ...
 
 This doesn't allow you to jump into the middle of a loop, but that's usually
diff --git a/Doc/faq/library.rst b/Doc/faq/library.rst
index c5fa4c2..d1b3efb 100644
--- a/Doc/faq/library.rst
+++ b/Doc/faq/library.rst
@@ -658,20 +658,20 @@
 
    import httplib, sys, time
 
-   ### build the query string
+   # build the query string
    qs = "First=Josephine&MI=Q&Last=Public"
 
-   ### connect and send the server a path
+   # connect and send the server a path
    httpobj = httplib.HTTP('www.some-server.out-there', 80)
    httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
-   ### now generate the rest of the HTTP headers...
+   # now generate the rest of the HTTP headers...
    httpobj.putheader('Accept', '*/*')
    httpobj.putheader('Connection', 'Keep-Alive')
    httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
    httpobj.putheader('Content-length', '%d' % len(qs))
    httpobj.endheaders()
    httpobj.send(qs)
-   ### find out what the server said in response...
+   # find out what the server said in response...
    reply, msg, hdrs = httpobj.getreply()
    if reply != 200:
        sys.stdout.write(httpobj.getfile().read())
@@ -724,8 +724,9 @@
 ``/usr/sbin/sendmail``.  The sendmail manual page will help you out.  Here's
 some sample code::
 
-   SENDMAIL = "/usr/sbin/sendmail" # sendmail location
    import os
+
+   SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
    p = os.popen("%s -t -i" % SENDMAIL, "w")
    p.write("To: receiver@example.com\n")
    p.write("Subject: test\n")
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index 4578280..d83833d 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -353,7 +353,7 @@
 
    >>> squares = []
    >>> for x in range(5):
-   ...    squares.append(lambda: x**2)
+   ...     squares.append(lambda: x**2)
 
 This gives you a list that contains 5 lambdas that calculate ``x**2``.  You
 might expect that, when called, they would return, respectively, ``0``, ``1``,
@@ -380,7 +380,7 @@
 
    >>> squares = []
    >>> for x in range(5):
-   ...    squares.append(lambda n=x: n**2)
+   ...     squares.append(lambda n=x: n**2)
 
 Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
 when the lambda is defined so that it has the same value that ``x`` had at
@@ -699,7 +699,7 @@
           args['a'] = 'new-value'     # args is a mutable dictionary
           args['b'] = args['b'] + 1   # change it in-place
 
-      args = {'a':' old-value', 'b': 99}
+      args = {'a': 'old-value', 'b': 99}
       func3(args)
       print args['a'], args['b']
 
@@ -815,16 +815,15 @@
 ``def`` and ``class`` statements, but in that case the value is a
 callable. Consider the following code::
 
-   class A:
-       pass
-
-   B = A
-
-   a = B()
-   b = a
-   print b
+   >>> class A:
+   ...     pass
+   ...
+   >>> B = A
+   >>> a = B()
+   >>> b = a
+   >>> print b
    <__main__.A instance at 0x16D07CC>
-   print a
+   >>> print a
    <__main__.A instance at 0x16D07CC>
 
 Arguably the class has a name: even though it is bound to two names and invoked
@@ -1209,7 +1208,7 @@
 Use the :func:`reversed` built-in function, which is new in Python 2.4::
 
    for x in reversed(sequence):
-       ... # do something with x...
+       ...  # do something with x ...
 
 This won't touch your original sequence, but build a new copy with reversed
 order to iterate over.
@@ -1217,7 +1216,7 @@
 With Python 2.3, you can use an extended slice syntax::
 
    for x in sequence[::-1]:
-       ... # do something with x...
+       ...  # do something with x ...
 
 
 How do you remove duplicates from a list?
@@ -1552,7 +1551,7 @@
 definition::
 
    class C:
-       def meth (self, arg):
+       def meth(self, arg):
            return arg * 2 + self.attribute
 
 
@@ -1585,9 +1584,9 @@
 
    def search(obj):
        if isinstance(obj, Mailbox):
-           # ... code to search a mailbox
+           ...  # code to search a mailbox
        elif isinstance(obj, Document):
-           # ... code to search a document
+           ...  # code to search a document
        elif ...
 
 A better approach is to define a ``search()`` method on all the classes and just
@@ -1595,11 +1594,11 @@
 
    class Mailbox:
        def search(self):
-           # ... code to search a mailbox
+           ...  # code to search a mailbox
 
    class Document:
        def search(self):
-           # ... code to search a document
+           ...  # code to search a document
 
    obj.search()
 
@@ -1656,7 +1655,7 @@
 If you're using new-style classes, use the built-in :func:`super` function::
 
    class Derived(Base):
-       def meth (self):
+       def meth(self):
            super(Derived, self).meth()
 
 If you're using classic classes: For a class definition such as ``class
diff --git a/Doc/howto/descriptor.rst b/Doc/howto/descriptor.rst
index e2359d9..8f98c42 100644
--- a/Doc/howto/descriptor.rst
+++ b/Doc/howto/descriptor.rst
@@ -108,7 +108,7 @@
         "Emulate type_getattro() in Objects/typeobject.c"
         v = object.__getattribute__(self, key)
         if hasattr(v, '__get__'):
-           return v.__get__(None, self)
+            return v.__get__(None, self)
         return v
 
 The important points to remember are:
@@ -169,9 +169,9 @@
             self.val = val
 
     >>> class MyClass(object):
-        x = RevealAccess(10, 'var "x"')
-        y = 5
-
+    ...     x = RevealAccess(10, 'var "x"')
+    ...     y = 5
+    ...
     >>> m = MyClass()
     >>> m.x
     Retrieving var "x"
@@ -293,15 +293,15 @@
 Running the interpreter shows how the function descriptor works in practice::
 
     >>> class D(object):
-         def f(self, x):
-              return x
-
+    ...     def f(self, x):
+    ...         return x
+    ...
     >>> d = D()
-    >>> D.__dict__['f'] # Stored internally as a function
+    >>> D.__dict__['f']  # Stored internally as a function
     <function f at 0x00C45070>
-    >>> D.f             # Get from a class becomes an unbound method
+    >>> D.f              # Get from a class becomes an unbound method
     <unbound method D.f>
-    >>> d.f             # Get from an instance becomes a bound method
+    >>> d.f              # Get from an instance becomes a bound method
     <bound method D.f of <__main__.D object at 0x00B18C90>>
 
 The output suggests that bound and unbound methods are two different types.
@@ -364,10 +364,10 @@
 calls are unexciting::
 
     >>> class E(object):
-         def f(x):
-              print x
-         f = staticmethod(f)
-
+    ...     def f(x):
+    ...         print x
+    ...     f = staticmethod(f)
+    ...
     >>> print E.f(3)
     3
     >>> print E().f(3)
@@ -377,23 +377,23 @@
 :func:`staticmethod` would look like this::
 
     class StaticMethod(object):
-     "Emulate PyStaticMethod_Type() in Objects/funcobject.c"
+        "Emulate PyStaticMethod_Type() in Objects/funcobject.c"
 
-     def __init__(self, f):
-          self.f = f
+        def __init__(self, f):
+            self.f = f
 
-     def __get__(self, obj, objtype=None):
-          return self.f
+        def __get__(self, obj, objtype=None):
+            return self.f
 
 Unlike static methods, class methods prepend the class reference to the
 argument list before calling the function.  This format is the same
 for whether the caller is an object or a class::
 
     >>> class E(object):
-         def f(klass, x):
-              return klass.__name__, x
-         f = classmethod(f)
-
+    ...     def f(klass, x):
+    ...          return klass.__name__, x
+    ...     f = classmethod(f)
+    ...
     >>> print E.f(3)
     ('E', 3)
     >>> print E().f(3)
@@ -425,15 +425,15 @@
 :func:`classmethod` would look like this::
 
     class ClassMethod(object):
-         "Emulate PyClassMethod_Type() in Objects/funcobject.c"
+        "Emulate PyClassMethod_Type() in Objects/funcobject.c"
 
-         def __init__(self, f):
-              self.f = f
+        def __init__(self, f):
+            self.f = f
 
-         def __get__(self, obj, klass=None):
-              if klass is None:
-                   klass = type(obj)
-              def newfunc(*args):
-                   return self.f(klass, *args)
-              return newfunc
+        def __get__(self, obj, klass=None):
+            if klass is None:
+                klass = type(obj)
+            def newfunc(*args):
+                return self.f(klass, *args)
+            return newfunc
 
diff --git a/Doc/howto/functional.rst b/Doc/howto/functional.rst
index 62792b8..ee9a5f6d 100644
--- a/Doc/howto/functional.rst
+++ b/Doc/howto/functional.rst
@@ -394,14 +394,14 @@
             continue   # Skip this element
         for expr2 in sequence2:
             if not (condition2):
-                continue    # Skip this element
+                continue   # Skip this element
             ...
             for exprN in sequenceN:
-                 if not (conditionN):
-                     continue   # Skip this element
+                if not (conditionN):
+                    continue   # Skip this element
 
-                 # Output the value of
-                 # the expression.
+                # Output the value of
+                # the expression.
 
 This means that when there are multiple ``for...in`` clauses but no ``if``
 clauses, the length of the resulting output will be equal to the product of the
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst
index 4b8765a..074c396 100644
--- a/Doc/howto/logging-cookbook.rst
+++ b/Doc/howto/logging-cookbook.rst
@@ -63,6 +63,7 @@
         def __init__(self):
             self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
             self.logger.info('creating an instance of Auxiliary')
+
         def do_something(self):
             self.logger.info('doing something')
             a = 1 + 1
@@ -585,21 +586,21 @@
             return True
 
     if __name__ == '__main__':
-       levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
-       logging.basicConfig(level=logging.DEBUG,
-                           format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
-       a1 = logging.getLogger('a.b.c')
-       a2 = logging.getLogger('d.e.f')
+        levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
+        logging.basicConfig(level=logging.DEBUG,
+                            format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
+        a1 = logging.getLogger('a.b.c')
+        a2 = logging.getLogger('d.e.f')
 
-       f = ContextFilter()
-       a1.addFilter(f)
-       a2.addFilter(f)
-       a1.debug('A debug message')
-       a1.info('An info message with %s', 'some parameters')
-       for x in range(10):
-           lvl = choice(levels)
-           lvlname = logging.getLevelName(lvl)
-           a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
+        f = ContextFilter()
+        a1.addFilter(f)
+        a2.addFilter(f)
+        a1.debug('A debug message')
+        a1.info('An info message with %s', 'some parameters')
+        for x in range(10):
+            lvl = choice(levels)
+            lvlname = logging.getLevelName(lvl)
+            a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
 
 which, when run, produces something like::
 
diff --git a/Doc/howto/logging.rst b/Doc/howto/logging.rst
index dd8ec63..5b431f0 100644
--- a/Doc/howto/logging.rst
+++ b/Doc/howto/logging.rst
@@ -103,8 +103,8 @@
 A very simple example is::
 
    import logging
-   logging.warning('Watch out!') # will print a message to the console
-   logging.info('I told you so') # will not print anything
+   logging.warning('Watch out!')  # will print a message to the console
+   logging.info('I told you so')  # will not print anything
 
 If you type these lines into a script and run it, you'll see::
 
diff --git a/Doc/howto/regex.rst b/Doc/howto/regex.rst
index 9fe2128..2c95fb4 100644
--- a/Doc/howto/regex.rst
+++ b/Doc/howto/regex.rst
@@ -1127,19 +1127,19 @@
 Here's a simple example of using the :meth:`sub` method.  It replaces colour
 names with the word ``colour``::
 
-   >>> p = re.compile( '(blue|white|red)')
-   >>> p.sub( 'colour', 'blue socks and red shoes')
+   >>> p = re.compile('(blue|white|red)')
+   >>> p.sub('colour', 'blue socks and red shoes')
    'colour socks and colour shoes'
-   >>> p.sub( 'colour', 'blue socks and red shoes', count=1)
+   >>> p.sub('colour', 'blue socks and red shoes', count=1)
    'colour socks and red shoes'
 
 The :meth:`subn` method does the same work, but returns a 2-tuple containing the
 new string value and the number of replacements  that were performed::
 
-   >>> p = re.compile( '(blue|white|red)')
-   >>> p.subn( 'colour', 'blue socks and red shoes')
+   >>> p = re.compile('(blue|white|red)')
+   >>> p.subn('colour', 'blue socks and red shoes')
    ('colour socks and colour shoes', 2)
-   >>> p.subn( 'colour', 'no colours at all')
+   >>> p.subn('colour', 'no colours at all')
    ('no colours at all', 0)
 
 Empty matches are replaced only when they're not adjacent to a previous match.
diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst
index 3550112..ff2e7a8 100644
--- a/Doc/howto/urllib2.rst
+++ b/Doc/howto/urllib2.rst
@@ -165,10 +165,10 @@
 
     url = 'http://www.someserver.com/cgi-bin/register.cgi'
     user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
-    values = {'name' : 'Michael Foord',
-              'location' : 'Northampton',
-              'language' : 'Python' }
-    headers = { 'User-Agent' : user_agent }
+    values = {'name': 'Michael Foord',
+              'location': 'Northampton',
+              'language': 'Python' }
+    headers = {'User-Agent': user_agent}
 
     data = urllib.urlencode(values)
     req = urllib2.Request(url, data, headers)
diff --git a/Doc/howto/webservers.rst b/Doc/howto/webservers.rst
index 54dac23..5d401e8 100644
--- a/Doc/howto/webservers.rst
+++ b/Doc/howto/webservers.rst
@@ -295,7 +295,7 @@
         yield '<h1>FastCGI Environment</h1>'
         yield '<table>'
         for k, v in sorted(environ.items()):
-             yield '<tr><th>%s</th><td>%s</td></tr>' % (escape(k), escape(v))
+            yield '<tr><th>%s</th><td>%s</td></tr>' % (escape(k), escape(v))
         yield '</table>'
 
     WSGIServer(app).run()
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst
index d0527d6..fd9312b 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -35,10 +35,10 @@
 
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
-                      help='an integer for the accumulator')
+                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
-                      const=sum, default=max,
-                      help='sum the integers (default: find the max)')
+                       const=sum, default=max,
+                       help='sum the integers (default: find the max)')
 
    args = parser.parse_args()
    print args.accumulate(args.integers)
@@ -463,7 +463,7 @@
 arguments they contain.  For example::
 
    >>> with open('args.txt', 'w') as fp:
-   ...    fp.write('-f\nbar')
+   ...     fp.write('-f\nbar')
    >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
    >>> parser.add_argument('-f')
    >>> parser.parse_args(['-f', 'foo', '@args.txt'])
@@ -1064,9 +1064,9 @@
 
    >>> parser = argparse.ArgumentParser(prog='frobble')
    >>> parser.add_argument('--foo', action='store_true',
-   ...         help='foo the bars before frobbling')
+   ...                     help='foo the bars before frobbling')
    >>> parser.add_argument('bar', nargs='+',
-   ...         help='one of the bars to be frobbled')
+   ...                     help='one of the bars to be frobbled')
    >>> parser.parse_args(['-h'])
    usage: frobble [-h] [--foo] bar [bar ...]
 
@@ -1084,7 +1084,7 @@
 
    >>> parser = argparse.ArgumentParser(prog='frobble')
    >>> parser.add_argument('bar', nargs='?', type=int, default=42,
-   ...         help='the bar to %(prog)s (default: %(default)s)')
+   ...                     help='the bar to %(prog)s (default: %(default)s)')
    >>> parser.print_help()
    usage: frobble [-h] [bar]
 
@@ -1417,10 +1417,10 @@
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument(
    ...     'integers', metavar='int', type=int, choices=xrange(10),
-   ...  nargs='+', help='an integer in the range 0..9')
+   ...     nargs='+', help='an integer in the range 0..9')
    >>> parser.add_argument(
    ...     '--sum', dest='accumulate', action='store_const', const=sum,
-   ...   default=max, help='sum the integers (default: find the max)')
+   ...     default=max, help='sum the integers (default: find the max)')
    >>> parser.parse_args(['1', '2', '3', '4'])
    Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
    >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
diff --git a/Doc/library/asynchat.rst b/Doc/library/asynchat.rst
index 37d001b..1ad02ec 100644
--- a/Doc/library/asynchat.rst
+++ b/Doc/library/asynchat.rst
@@ -228,7 +228,7 @@
                    self.set_terminator(None)
                    self.handle_request()
            elif not self.handling:
-               self.set_terminator(None) # browsers sometimes over-send
+               self.set_terminator(None)  # browsers sometimes over-send
                self.cgi_data = parse(self.headers, "".join(self.ibuffer))
                self.handling = True
                self.ibuffer = []
diff --git a/Doc/library/audioop.rst b/Doc/library/audioop.rst
index e747ba1..8261117 100644
--- a/Doc/library/audioop.rst
+++ b/Doc/library/audioop.rst
@@ -269,6 +269,6 @@
        #              out_test)
        prefill = '\0'*(pos+ipos)*2
        postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
-       outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
+       outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
        return audioop.add(inputdata, outputdata, 2)
 
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index cdf4a43..9ac2c02 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -838,7 +838,7 @@
 in conjuction with sorting to make a sorted dictionary::
 
     >>> # regular unsorted dictionary
-    >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
+    >>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
 
     >>> # dictionary sorted by key
     >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
@@ -1002,10 +1002,13 @@
              for value in iterable:
                  if value not in lst:
                      lst.append(value)
+
          def __iter__(self):
              return iter(self.elements)
+
          def __contains__(self, value):
              return value in self.elements
+
          def __len__(self):
              return len(self.elements)
 
diff --git a/Doc/library/configparser.rst b/Doc/library/configparser.rst
index 515074a..16bd07a 100644
--- a/Doc/library/configparser.rst
+++ b/Doc/library/configparser.rst
@@ -489,8 +489,8 @@
    config.read('example.cfg')
 
    # Set the third, optional argument of get to 1 if you wish to use raw mode.
-   print config.get('Section1', 'foo', 0) # -> "Python is fun!"
-   print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
+   print config.get('Section1', 'foo', 0)  # -> "Python is fun!"
+   print config.get('Section1', 'foo', 1)  # -> "%(bar)s is %(baz)s!"
 
    # The optional fourth argument is a dict with members that will take
    # precedence in interpolation.
@@ -506,10 +506,10 @@
    config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
    config.read('example.cfg')
 
-   print config.get('Section1', 'foo') # -> "Python is fun!"
+   print config.get('Section1', 'foo')  # -> "Python is fun!"
    config.remove_option('Section1', 'bar')
    config.remove_option('Section1', 'baz')
-   print config.get('Section1', 'foo') # -> "Life is hard!"
+   print config.get('Section1', 'foo')  # -> "Life is hard!"
 
 The function ``opt_move`` below can be used to move options between sections::
 
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index 8e3020f..e30b006 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -49,11 +49,11 @@
 convention::
 
    >>> from ctypes import *
-   >>> print windll.kernel32 # doctest: +WINDOWS
+   >>> print windll.kernel32  # doctest: +WINDOWS
    <WinDLL 'kernel32', handle ... at ...>
-   >>> print cdll.msvcrt # doctest: +WINDOWS
+   >>> print cdll.msvcrt      # doctest: +WINDOWS
    <CDLL 'msvcrt', handle ... at ...>
-   >>> libc = cdll.msvcrt # doctest: +WINDOWS
+   >>> libc = cdll.msvcrt     # doctest: +WINDOWS
    >>>
 
 Windows appends the usual ``.dll`` file suffix automatically.
@@ -63,10 +63,10 @@
 :meth:`LoadLibrary` method of the dll loaders should be used, or you should load
 the library by creating an instance of CDLL by calling the constructor::
 
-   >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
+   >>> cdll.LoadLibrary("libc.so.6")  # doctest: +LINUX
    <CDLL 'libc.so.6', handle ... at ...>
-   >>> libc = CDLL("libc.so.6")     # doctest: +LINUX
-   >>> libc                         # doctest: +LINUX
+   >>> libc = CDLL("libc.so.6")       # doctest: +LINUX
+   >>> libc                           # doctest: +LINUX
    <CDLL 'libc.so.6', handle ... at ...>
    >>>
 
@@ -83,9 +83,9 @@
    >>> from ctypes import *
    >>> libc.printf
    <_FuncPtr object at 0x...>
-   >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
+   >>> print windll.kernel32.GetModuleHandleA  # doctest: +WINDOWS
    <_FuncPtr object at 0x...>
-   >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
+   >>> print windll.kernel32.MyOwnFunction     # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "ctypes.py", line 239, in __getattr__
@@ -115,16 +115,16 @@
 identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
 :func:`getattr` to retrieve the function::
 
-   >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
+   >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  # doctest: +WINDOWS
    <_FuncPtr object at 0x...>
    >>>
 
 On Windows, some dlls export functions not by name but by ordinal. These
 functions can be accessed by indexing the dll object with the ordinal number::
 
-   >>> cdll.kernel32[1] # doctest: +WINDOWS
+   >>> cdll.kernel32[1]  # doctest: +WINDOWS
    <_FuncPtr object at 0x...>
-   >>> cdll.kernel32[0] # doctest: +WINDOWS
+   >>> cdll.kernel32[0]  # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "ctypes.py", line 310, in __getitem__
@@ -146,9 +146,9 @@
 This example calls both functions with a NULL pointer (``None`` should be used
 as the NULL pointer)::
 
-   >>> print libc.time(None) # doctest: +SKIP
+   >>> print libc.time(None)  # doctest: +SKIP
    1150640792
-   >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
+   >>> print hex(windll.kernel32.GetModuleHandleA(None))  # doctest: +WINDOWS
    0x1d000000
    >>>
 
@@ -157,11 +157,11 @@
 Windows.  It does this by examining the stack after the function returns, so
 although an error is raised the function *has* been called::
 
-   >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
+   >>> windll.kernel32.GetModuleHandleA()      # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: Procedure probably called with not enough arguments (4 bytes missing)
-   >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
+   >>> windll.kernel32.GetModuleHandleA(0, 0)  # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: Procedure probably called with too many arguments (4 bytes in excess)
@@ -170,13 +170,13 @@
 The same exception is raised when you call an ``stdcall`` function with the
 ``cdecl`` calling convention, or vice versa::
 
-   >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
+   >>> cdll.kernel32.GetModuleHandleA(None)  # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: Procedure probably called with not enough arguments (4 bytes missing)
    >>>
 
-   >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
+   >>> windll.msvcrt.printf("spam")  # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: Procedure probably called with too many arguments (4 bytes in excess)
@@ -189,7 +189,7 @@
 crashes from general protection faults when functions are called with invalid
 argument values::
 
-   >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
+   >>> windll.kernel32.GetModuleHandleA(32)  # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    WindowsError: exception: access violation reading 0x00000020
@@ -448,9 +448,9 @@
 a string pointer and a char, and returns a pointer to a string::
 
    >>> strchr = libc.strchr
-   >>> strchr("abcdef", ord("d")) # doctest: +SKIP
+   >>> strchr("abcdef", ord("d"))  # doctest: +SKIP
    8059983
-   >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
+   >>> strchr.restype = c_char_p   # c_char_p is a pointer to a string
    >>> strchr("abcdef", ord("d"))
    'def'
    >>> print strchr("abcdef", ord("x"))
@@ -481,17 +481,17 @@
 result of this call will be used as the result of your function call. This is
 useful to check for error return values and automatically raise an exception::
 
-   >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
+   >>> GetModuleHandle = windll.kernel32.GetModuleHandleA  # doctest: +WINDOWS
    >>> def ValidHandle(value):
    ...     if value == 0:
    ...         raise WinError()
    ...     return value
    ...
    >>>
-   >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
-   >>> GetModuleHandle(None) # doctest: +WINDOWS
+   >>> GetModuleHandle.restype = ValidHandle  # doctest: +WINDOWS
+   >>> GetModuleHandle(None)  # doctest: +WINDOWS
    486539264
-   >>> GetModuleHandle("something silly") # doctest: +WINDOWS
+   >>> GetModuleHandle("something silly")  # doctest: +WINDOWS
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 3, in ValidHandle
@@ -662,12 +662,12 @@
 
    >>> from ctypes import *
    >>> class POINT(Structure):
-   ...    _fields_ = ("x", c_int), ("y", c_int)
+   ...     _fields_ = ("x", c_int), ("y", c_int)
    ...
    >>> class MyStruct(Structure):
-   ...    _fields_ = [("a", c_int),
-   ...                ("b", c_float),
-   ...                ("point_array", POINT * 4)]
+   ...     _fields_ = [("a", c_int),
+   ...                 ("b", c_float),
+   ...                 ("point_array", POINT * 4)]
    >>>
    >>> print len(MyStruct().point_array)
    4
@@ -1028,7 +1028,7 @@
 It is funny to see that on linux the sort function seems to work much more
 efficiently, it is doing less comparisons::
 
-   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
+   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func)  # doctest: +LINUX
    py_cmp_func 5 1
    py_cmp_func 33 99
    py_cmp_func 7 33
@@ -1151,9 +1151,9 @@
 hit the NULL entry::
 
    >>> for item in table:
-   ...    print item.name, item.size
-   ...    if item.name is None:
-   ...        break
+   ...     print item.name, item.size
+   ...     if item.name is None:
+   ...         break
    ...
    __hello__ 104
    __phello__ -104
diff --git a/Doc/library/getopt.rst b/Doc/library/getopt.rst
index 2dfb102..2d81e5a 100644
--- a/Doc/library/getopt.rst
+++ b/Doc/library/getopt.rst
@@ -129,7 +129,7 @@
            opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
        except getopt.GetoptError as err:
            # print help information and exit:
-           print str(err) # will print something like "option -a not recognized"
+           print str(err)  # will print something like "option -a not recognized"
            usage()
            sys.exit(2)
        output = None
diff --git a/Doc/library/htmlparser.rst b/Doc/library/htmlparser.rst
index 2af4d0c..e73ce07 100644
--- a/Doc/library/htmlparser.rst
+++ b/Doc/library/htmlparser.rst
@@ -66,8 +66,10 @@
    class MyHTMLParser(HTMLParser):
        def handle_starttag(self, tag, attrs):
            print "Encountered a start tag:", tag
+
        def handle_endtag(self, tag):
            print "Encountered an end tag :", tag
+
        def handle_data(self, data):
            print "Encountered some data  :", data
 
@@ -252,21 +254,27 @@
            print "Start tag:", tag
            for attr in attrs:
                print "     attr:", attr
+
        def handle_endtag(self, tag):
            print "End tag  :", tag
+
        def handle_data(self, data):
            print "Data     :", data
+
        def handle_comment(self, data):
            print "Comment  :", data
+
        def handle_entityref(self, name):
            c = unichr(name2codepoint[name])
            print "Named ent:", c
+
        def handle_charref(self, name):
            if name.startswith('x'):
                c = unichr(int(name[1:], 16))
            else:
                c = unichr(int(name))
            print "Num ent  :", c
+
        def handle_decl(self, data):
            print "Decl     :", data
 
@@ -298,7 +306,7 @@
         attr: ('type', 'text/css')
    Data     : #python { color: green }
    End tag  : style
-   >>>
+
    >>> parser.feed('<script type="text/javascript">'
    ...             'alert("<strong>hello!</strong>");</script>')
    Start tag: script
diff --git a/Doc/library/locale.rst b/Doc/library/locale.rst
index 8fa1a1b..0b02685 100644
--- a/Doc/library/locale.rst
+++ b/Doc/library/locale.rst
@@ -481,13 +481,13 @@
 Example::
 
    >>> import locale
-   >>> loc = locale.getlocale() # get current locale
+   >>> loc = locale.getlocale()  # get current locale
    # use German locale; name might vary with platform
    >>> locale.setlocale(locale.LC_ALL, 'de_DE')
-   >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
-   >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
-   >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
-   >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
+   >>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
+   >>> locale.setlocale(locale.LC_ALL, '')   # use user's preferred locale
+   >>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
+   >>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale
 
 
 Background, details, hints, tips and caveats
diff --git a/Doc/library/mailcap.rst b/Doc/library/mailcap.rst
index b359509..750d085 100644
--- a/Doc/library/mailcap.rst
+++ b/Doc/library/mailcap.rst
@@ -70,7 +70,7 @@
 An example usage::
 
    >>> import mailcap
-   >>> d=mailcap.getcaps()
+   >>> d = mailcap.getcaps()
    >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
    ('xmpeg tmp1223', {'view': 'xmpeg %s'})
 
diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst
index ac1963f..0860cac 100644
--- a/Doc/library/mmap.rst
+++ b/Doc/library/mmap.rst
@@ -140,7 +140,7 @@
 
       pid = os.fork()
 
-      if pid == 0: # In a child process
+      if pid == 0:  # In a child process
           mm.seek(0)
           print mm.readline()
 
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index 9413222..82a0201 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -2352,8 +2352,8 @@
             ... do something using "lock" ...
 
         if __name__ == '__main__':
-           lock = Lock()
-           for i in range(10):
+            lock = Lock()
+            for i in range(10):
                 Process(target=f).start()
 
     should be rewritten as ::
@@ -2364,8 +2364,8 @@
             ... do something using "l" ...
 
         if __name__ == '__main__':
-           lock = Lock()
-           for i in range(10):
+            lock = Lock()
+            for i in range(10):
                 Process(target=f, args=(lock,)).start()
 
 Beware of replacing :data:`sys.stdin` with a "file like object"
diff --git a/Doc/library/optparse.rst b/Doc/library/optparse.rst
index 417b3bb..dfb43a1 100644
--- a/Doc/library/optparse.rst
+++ b/Doc/library/optparse.rst
@@ -27,7 +27,7 @@
 Here's an example of using :mod:`optparse` in a simple script::
 
    from optparse import OptionParser
-   [...]
+   ...
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename",
                      help="write report to FILE", metavar="FILE")
@@ -254,7 +254,7 @@
 program, create an OptionParser instance::
 
    from optparse import OptionParser
-   [...]
+   ...
    parser = OptionParser()
 
 Then you can start defining options.  The basic syntax is::
@@ -721,7 +721,7 @@
 condition::
 
    (options, args) = parser.parse_args()
-   [...]
+   ...
    if options.a and options.b:
        parser.error("options -a and -b are mutually exclusive")
 
@@ -761,7 +761,7 @@
 Here's what :mod:`optparse`\ -based scripts usually look like::
 
    from optparse import OptionParser
-   [...]
+   ...
    def main():
        usage = "usage: %prog [options] arg"
        parser = OptionParser(usage)
@@ -771,13 +771,13 @@
                          action="store_true", dest="verbose")
        parser.add_option("-q", "--quiet",
                          action="store_false", dest="verbose")
-       [...]
+       ...
        (options, args) = parser.parse_args()
        if len(args) != 1:
            parser.error("incorrect number of arguments")
        if options.verbose:
            print "reading %s..." % options.filename
-       [...]
+       ...
 
    if __name__ == "__main__":
        main()
@@ -1412,7 +1412,7 @@
 strings::
 
    parser.add_option("-n", "--dry-run", ...)
-   [...]
+   ...
    parser.add_option("-n", "--noisy", ...)
 
 (This is particularly true if you've defined your own OptionParser subclass with
@@ -1453,7 +1453,7 @@
 
    Options:
      --dry-run     do no harm
-     [...]
+     ...
      -n, --noisy   be noisy
 
 It's possible to whittle away the option strings for a previously-added option
@@ -1468,7 +1468,7 @@
 accessible, so :mod:`optparse` removes it, leaving this help text::
 
    Options:
-     [...]
+     ...
      -n, --noisy   be noisy
      --dry-run     new dry-run option
 
@@ -1704,7 +1704,7 @@
        if parser.values.b:
            raise OptionValueError("can't use -a after -b")
        parser.values.a = 1
-   [...]
+   ...
    parser.add_option("-a", action="callback", callback=check_order)
    parser.add_option("-b", action="store_true", dest="b")
 
@@ -1722,7 +1722,7 @@
        if parser.values.b:
            raise OptionValueError("can't use %s after -b" % opt_str)
        setattr(parser.values, option.dest, 1)
-   [...]
+   ...
    parser.add_option("-a", action="callback", callback=check_order, dest='a')
    parser.add_option("-b", action="store_true", dest="b")
    parser.add_option("-c", action="callback", callback=check_order, dest='c')
@@ -1742,7 +1742,7 @@
            raise OptionValueError("%s option invalid when moon is full"
                                   % opt_str)
        setattr(parser.values, option.dest, 1)
-   [...]
+   ...
    parser.add_option("--foo",
                      action="callback", callback=check_moon, dest="foo")
 
@@ -1765,7 +1765,7 @@
 
    def store_value(option, opt_str, value, parser):
        setattr(parser.values, option.dest, value)
-   [...]
+   ...
    parser.add_option("--foo",
                      action="callback", callback=store_value,
                      type="int", nargs=3, dest="foo")
@@ -1827,9 +1827,9 @@
         del parser.rargs[:len(value)]
         setattr(parser.values, option.dest, value)
 
-   [...]
-   parser.add_option("-c", "--callback", dest="vararg_attr",
-                     action="callback", callback=vararg_callback)
+    ...
+    parser.add_option("-c", "--callback", dest="vararg_attr",
+                      action="callback", callback=vararg_callback)
 
 
 .. _optparse-extending-optparse:
diff --git a/Doc/library/re.rst b/Doc/library/re.rst
index 55663ec..1239434 100644
--- a/Doc/library/re.rst
+++ b/Doc/library/re.rst
@@ -1120,15 +1120,15 @@
 
 For example::
 
-   >>> re.match("c", "abcdef")  # No match
-   >>> re.search("c", "abcdef") # Match
+   >>> re.match("c", "abcdef")    # No match
+   >>> re.search("c", "abcdef")   # Match
    <_sre.SRE_Match object at ...>
 
 Regular expressions beginning with ``'^'`` can be used with :func:`search` to
 restrict the match at the beginning of the string::
 
-   >>> re.match("c", "abcdef")  # No match
-   >>> re.search("^c", "abcdef") # No match
+   >>> re.match("c", "abcdef")    # No match
+   >>> re.search("^c", "abcdef")  # No match
    >>> re.search("^a", "abcdef")  # Match
    <_sre.SRE_Match object at ...>
 
@@ -1209,9 +1209,9 @@
 in each word of a sentence except for the first and last characters::
 
    >>> def repl(m):
-   ...   inner_word = list(m.group(2))
-   ...   random.shuffle(inner_word)
-   ...   return m.group(1) + "".join(inner_word) + m.group(3)
+   ...     inner_word = list(m.group(2))
+   ...     random.shuffle(inner_word)
+   ...     return m.group(1) + "".join(inner_word) + m.group(3)
    >>> text = "Professor Abdolmalek, please report your absences promptly."
    >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
    'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index fe2325e..9d8d080 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -1452,7 +1452,7 @@
    except ImportError:
        pass
    else:
-       ... # do something that requires SSL support
+       ...  # do something that requires SSL support
 
 Client-side operation
 ^^^^^^^^^^^^^^^^^^^^^
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index 260cd0a..55733b9 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -262,12 +262,12 @@
 
 Some simple format string examples::
 
-   "First, thou shalt count to {0}" # References first positional argument
-   "Bring me a {}"                  # Implicitly references the first positional argument
-   "From {} to {}"                  # Same as "From {0} to {1}"
-   "My quest is {name}"             # References keyword argument 'name'
-   "Weight in tons {0.weight}"      # 'weight' attribute of first positional arg
-   "Units destroyed: {players[0]}"  # First element of keyword argument 'players'.
+   "First, thou shalt count to {0}"  # References first positional argument
+   "Bring me a {}"                   # Implicitly references the first positional argument
+   "From {} to {}"                   # Same as "From {0} to {1}"
+   "My quest is {name}"              # References keyword argument 'name'
+   "Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
+   "Units destroyed: {players[0]}"   # First element of keyword argument 'players'.
 
 The *conversion* field causes a type coercion before formatting.  Normally, the
 job of formatting a value is done by the :meth:`__format__` method of the value
diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst
index ccb922b..e16f78c 100644
--- a/Doc/library/threading.rst
+++ b/Doc/library/threading.rst
@@ -778,7 +778,7 @@
        print "hello, world"
 
    t = Timer(30.0, hello)
-   t.start() # after 30 seconds, "hello, world" will be printed
+   t.start()  # after 30 seconds, "hello, world" will be printed
 
 
 .. class:: Timer(interval, function, args=[], kwargs={})
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
index cacbb3c..64a1834 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -115,19 +115,19 @@
 
   class TestStringMethods(unittest.TestCase):
 
-    def test_upper(self):
-        self.assertEqual('foo'.upper(), 'FOO')
+      def test_upper(self):
+          self.assertEqual('foo'.upper(), 'FOO')
 
-    def test_isupper(self):
-        self.assertTrue('FOO'.isupper())
-        self.assertFalse('Foo'.isupper())
+      def test_isupper(self):
+          self.assertTrue('FOO'.isupper())
+          self.assertFalse('Foo'.isupper())
 
-    def test_split(self):
-        s = 'hello world'
-        self.assertEqual(s.split(), ['hello', 'world'])
-        # check that s.split fails when the separator is not a string
-        with self.assertRaises(TypeError):
-            s.split(2)
+      def test_split(self):
+          s = 'hello world'
+          self.assertEqual(s.split(), ['hello', 'world'])
+          # check that s.split fails when the separator is not a string
+          with self.assertRaises(TypeError):
+              s.split(2)
 
   if __name__ == '__main__':
       unittest.main()
diff --git a/Doc/library/wsgiref.rst b/Doc/library/wsgiref.rst
index ea33c94..e755d18 100644
--- a/Doc/library/wsgiref.rst
+++ b/Doc/library/wsgiref.rst
@@ -418,8 +418,8 @@
       # Our callable object which is intentionally not compliant to the
       # standard, so the validator is going to break
       def simple_app(environ, start_response):
-          status = '200 OK' # HTTP Status
-          headers = [('Content-type', 'text/plain')] # HTTP Headers
+          status = '200 OK'  # HTTP Status
+          headers = [('Content-type', 'text/plain')]  # HTTP Headers
           start_response(status, headers)
 
           # This is going to break because we need to return a list, and
@@ -714,8 +714,8 @@
    # is a dictionary containing CGI-style envrironment variables and the
    # second variable is the callable object (see PEP 333).
    def hello_world_app(environ, start_response):
-       status = '200 OK' # HTTP Status
-       headers = [('Content-type', 'text/plain')] # HTTP Headers
+       status = '200 OK'  # HTTP Status
+       headers = [('Content-type', 'text/plain')]  # HTTP Headers
        start_response(status, headers)
 
        # The returned object is going to be printed
diff --git a/Doc/library/xml.dom.minidom.rst b/Doc/library/xml.dom.minidom.rst
index afff1c6..b6d46fc 100644
--- a/Doc/library/xml.dom.minidom.rst
+++ b/Doc/library/xml.dom.minidom.rst
@@ -33,10 +33,10 @@
 
    from xml.dom.minidom import parse, parseString
 
-   dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name
+   dom1 = parse('c:\\temp\\mydata.xml')  # parse an XML file by name
 
    datasource = open('c:\\temp\\mydata.xml')
-   dom2 = parse(datasource)   # parse an open file
+   dom2 = parse(datasource)  # parse an open file
 
    dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
 
diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst
index 15325c2..20cfc4c 100644
--- a/Doc/library/xml.etree.elementtree.rst
+++ b/Doc/library/xml.etree.elementtree.rst
@@ -129,7 +129,7 @@
 It also has children nodes over which we can iterate::
 
    >>> for child in root:
-   ...   print child.tag, child.attrib
+   ...     print child.tag, child.attrib
    ...
    country {'name': 'Liechtenstein'}
    country {'name': 'Singapore'}
@@ -148,7 +148,7 @@
 :meth:`Element.iter`::
 
    >>> for neighbor in root.iter('neighbor'):
-   ...   print neighbor.attrib
+   ...     print neighbor.attrib
    ...
    {'name': 'Austria', 'direction': 'E'}
    {'name': 'Switzerland', 'direction': 'W'}
@@ -162,9 +162,9 @@
 content.  :meth:`Element.get` accesses the element's attributes::
 
    >>> for country in root.findall('country'):
-   ...   rank = country.find('rank').text
-   ...   name = country.get('name')
-   ...   print name, rank
+   ...     rank = country.find('rank').text
+   ...     name = country.get('name')
+   ...     print name, rank
    ...
    Liechtenstein 1
    Singapore 4
@@ -188,9 +188,9 @@
 attribute to the rank element::
 
    >>> for rank in root.iter('rank'):
-   ...   new_rank = int(rank.text) + 1
-   ...   rank.text = str(new_rank)
-   ...   rank.set('updated', 'yes')
+   ...     new_rank = int(rank.text) + 1
+   ...     rank.text = str(new_rank)
+   ...     rank.set('updated', 'yes')
    ...
    >>> tree.write('output.xml')
 
@@ -226,9 +226,9 @@
 remove all countries with a rank higher than 50::
 
    >>> for country in root.findall('country'):
-   ...   rank = int(country.find('rank').text)
-   ...   if rank > 50:
-   ...     root.remove(country)
+   ...     rank = int(country.find('rank').text)
+   ...     if rank > 50:
+   ...         root.remove(country)
    ...
    >>> tree.write('output.xml')
 
@@ -887,6 +887,7 @@
     [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
     >>> for i in links:             # Iterates through all found links
     ...     i.attrib["target"] = "blank"
+    ...
     >>> tree.write("output.xhtml")
 
 .. _elementtree-qname-objects:
diff --git a/Doc/library/xmlrpclib.rst b/Doc/library/xmlrpclib.rst
index 4603f8b..07ed124 100644
--- a/Doc/library/xmlrpclib.rst
+++ b/Doc/library/xmlrpclib.rst
@@ -235,7 +235,7 @@
    from SimpleXMLRPCServer import SimpleXMLRPCServer
 
    def is_even(n):
-       return n%2 == 0
+       return n % 2 == 0
 
    server = SimpleXMLRPCServer(("localhost", 8000))
    print "Listening on port 8000..."
@@ -392,7 +392,7 @@
 
    # A marshalling error is going to occur because we're returning a
    # complex number
-   def add(x,y):
+   def add(x, y):
        return x+y+0j
 
    server = SimpleXMLRPCServer(("localhost", 8000))
@@ -590,12 +590,15 @@
    class ProxiedTransport(xmlrpclib.Transport):
        def set_proxy(self, proxy):
            self.proxy = proxy
+
        def make_connection(self, host):
            self.realhost = host
            h = httplib.HTTPConnection(self.proxy)
            return h
+
        def send_request(self, connection, handler, request_body):
            connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
+
        def send_host(self, connection, host):
            connection.putheader('Host', self.realhost)
 
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index c46ab64..f18984b 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -761,7 +761,7 @@
 (and the ``**expression`` argument, if any -- see below).  So::
 
    >>> def f(a, b):
-   ...  print a, b
+   ...     print a, b
    ...
    >>> f(b=1, *(2,))
    2 1
diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst
index 1aa1fc1..2c0b8db 100644
--- a/Doc/reference/simple_stmts.rst
+++ b/Doc/reference/simple_stmts.rst
@@ -306,12 +306,12 @@
 The simple form, ``assert expression``, is equivalent to ::
 
    if __debug__:
-      if not expression: raise AssertionError
+       if not expression: raise AssertionError
 
 The extended form, ``assert expression1, expression2``, is equivalent to ::
 
    if __debug__:
-      if not expression1: raise AssertionError(expression2)
+       if not expression1: raise AssertionError(expression2)
 
 .. index::
    single: __debug__
diff --git a/Doc/tutorial/appendix.rst b/Doc/tutorial/appendix.rst
index 7ab588b..73b7d1b 100644
--- a/Doc/tutorial/appendix.rst
+++ b/Doc/tutorial/appendix.rst
@@ -92,7 +92,7 @@
    filename = os.environ.get('PYTHONSTARTUP')
    if filename and os.path.isfile(filename):
        with open(filename) as fobj:
-          startup_file = fobj.read()
+           startup_file = fobj.read()
        exec(startup_file)
 
 
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
index d82adf6..b1f3f00 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -210,6 +210,7 @@
    class MyClass:
        """A simple example class"""
        i = 12345
+
        def f(self):
            return 'hello world'
 
@@ -458,8 +459,10 @@
 
    class C:
        f = f1
+
        def g(self):
            return 'hello world'
+
        h = g
 
 Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
@@ -473,8 +476,10 @@
    class Bag:
        def __init__(self):
            self.data = []
+
        def add(self, x):
            self.data.append(x)
+
        def addtwice(self, x):
            self.add(x)
            self.add(x)
@@ -670,7 +675,7 @@
    class Employee:
        pass
 
-   john = Employee() # Create an empty employee record
+   john = Employee()  # Create an empty employee record
 
    # Fill the fields of the record
    john.name = 'John Doe'
@@ -796,8 +801,10 @@
        def __init__(self, data):
            self.data = data
            self.index = len(data)
+
        def __iter__(self):
            return self
+
        def next(self):
            if self.index == 0:
                raise StopIteration
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
index 8ffaf3f..2af60d0 100644
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -284,7 +284,7 @@
 It is simple to write a function that returns a list of the numbers of the
 Fibonacci series, instead of printing it::
 
-   >>> def fib2(n): # return Fibonacci series up to n
+   >>> def fib2(n):  # return Fibonacci series up to n
    ...     """Return a list containing the Fibonacci series up to n."""
    ...     result = []
    ...     a, b = 0, 1
diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst
index 6f77def..f93a544 100644
--- a/Doc/tutorial/errors.rst
+++ b/Doc/tutorial/errors.rst
@@ -180,14 +180,14 @@
 attributes to it as desired. ::
 
    >>> try:
-   ...    raise Exception('spam', 'eggs')
+   ...     raise Exception('spam', 'eggs')
    ... except Exception as inst:
-   ...    print type(inst)     # the exception instance
-   ...    print inst.args      # arguments stored in .args
-   ...    print inst           # __str__ allows args to be printed directly
-   ...    x, y = inst.args
-   ...    print 'x =', x
-   ...    print 'y =', y
+   ...     print type(inst)     # the exception instance
+   ...     print inst.args      # arguments stored in .args
+   ...     print inst           # __str__ allows args to be printed directly
+   ...     x, y = inst.args
+   ...     print 'x =', x
+   ...     print 'y =', y
    ...
    <type 'exceptions.Exception'>
    ('spam', 'eggs')
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst
index 6fdc5f0..3e32af2 100644
--- a/Doc/tutorial/inputoutput.rst
+++ b/Doc/tutorial/inputoutput.rst
@@ -326,10 +326,10 @@
 
    >>> f = open('workfile', 'r+')
    >>> f.write('0123456789abcdef')
-   >>> f.seek(5)     # Go to the 6th byte in the file
+   >>> f.seek(5)      # Go to the 6th byte in the file
    >>> f.read(1)
    '5'
-   >>> f.seek(-3, 2) # Go to the 3rd byte before the end
+   >>> f.seek(-3, 2)  # Go to the 3rd byte before the end
    >>> f.read(1)
    'd'
 
diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst
index a4fb70c..b7be00e 100644
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -236,7 +236,7 @@
 This feature is particularly useful when you want to break long strings::
 
    >>> text = ('Put several strings within parentheses '
-               'to have them joined together.')
+   ...         'to have them joined together.')
    >>> text
    'Put several strings within parentheses to have them joined together.'
 
@@ -280,11 +280,11 @@
 Slice indices have useful defaults; an omitted first index defaults to zero, an
 omitted second index defaults to the size of the string being sliced. ::
 
-   >>> word[:2]  # character from the beginning to position 2 (excluded)
+   >>> word[:2]   # character from the beginning to position 2 (excluded)
    'Py'
-   >>> word[4:]  # characters from position 4 (included) to the end
+   >>> word[4:]   # characters from position 4 (included) to the end
    'on'
-   >>> word[-2:] # characters from the second-last (included) to the end
+   >>> word[-2:]  # characters from the second-last (included) to the end
    'on'
 
 One way to remember how slices work is to think of the indices as pointing
diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst
index f5b8114..7b6fd9c 100644
--- a/Doc/tutorial/modules.rst
+++ b/Doc/tutorial/modules.rst
@@ -33,7 +33,7 @@
            print b,
            a, b = b, a+b
 
-   def fib2(n): # return Fibonacci series up to n
+   def fib2(n):   # return Fibonacci series up to n
        result = []
        a, b = 0, 1
        while b < n:
diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst
index f6239d6..4dab074 100644
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -283,7 +283,7 @@
            with self.assertRaises(TypeError):
                average(20, 30, 70)
 
-   unittest.main() # Calling from the command line invokes all tests
+   unittest.main()  # Calling from the command line invokes all tests
 
 
 .. _tut-batteries-included:
diff --git a/Doc/tutorial/stdlib2.rst b/Doc/tutorial/stdlib2.rst
index 65fb093..50b74d1 100644
--- a/Doc/tutorial/stdlib2.rst
+++ b/Doc/tutorial/stdlib2.rst
@@ -178,6 +178,7 @@
            threading.Thread.__init__(self)
            self.infile = infile
            self.outfile = outfile
+
        def run(self):
            f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
            f.write(self.infile)