(original) (raw)
changeset: 101288:2b492ea961c1 branch: 3.5 parent: 101284:bfc4c57a0986 user: Serhiy Storchaka storchaka@gmail.com date: Tue May 10 12:01:23 2016 +0300 files: Doc/distutils/apiref.rst Doc/faq/design.rst Doc/faq/library.rst Doc/faq/programming.rst Doc/howto/descriptor.rst Doc/howto/functional.rst Doc/howto/logging-cookbook.rst Doc/howto/logging.rst Doc/howto/regex.rst Doc/howto/unicode.rst Doc/howto/urllib2.rst Doc/library/argparse.rst Doc/library/asynchat.rst Doc/library/asyncio-sync.rst Doc/library/asyncore.rst Doc/library/audioop.rst Doc/library/collections.abc.rst Doc/library/collections.rst Doc/library/concurrent.futures.rst Doc/library/configparser.rst Doc/library/contextlib.rst Doc/library/crypt.rst Doc/library/ctypes.rst Doc/library/email.headerregistry.rst Doc/library/getopt.rst Doc/library/html.parser.rst Doc/library/http.client.rst Doc/library/inspect.rst Doc/library/ipaddress.rst Doc/library/locale.rst Doc/library/mailcap.rst Doc/library/mmap.rst Doc/library/multiprocessing.rst Doc/library/optparse.rst Doc/library/re.rst Doc/library/shelve.rst Doc/library/ssl.rst Doc/library/string.rst Doc/library/threading.rst Doc/library/tkinter.rst Doc/library/tokenize.rst Doc/library/types.rst Doc/library/unittest.rst Doc/library/urllib.request.rst Doc/library/wsgiref.rst Doc/library/xml.dom.minidom.rst Doc/library/xml.etree.elementtree.rst Doc/library/xmlrpc.client.rst Doc/reference/datamodel.rst Doc/reference/expressions.rst Doc/reference/simple_stmts.rst Doc/tutorial/appendix.rst Doc/tutorial/classes.rst Doc/tutorial/controlflow.rst Doc/tutorial/errors.rst Doc/tutorial/inputoutput.rst Doc/tutorial/introduction.rst Doc/tutorial/modules.rst Doc/tutorial/stdlib.rst Doc/tutorial/stdlib2.rst Doc/whatsnew/3.2.rst Doc/whatsnew/3.3.rst Doc/whatsnew/3.4.rst description: Issue #23921: Standardized documentation whitespace formatting. Original patch by James Edwards. diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/distutils/apiref.rst --- a/Doc/distutils/apiref.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/distutils/apiref.rst Tue May 10 12:01:23 2016 +0300 @@ -1907,9 +1907,9 @@ that is designed to run with both Python 2.x and 3.x, add:: try: - from distutils.command.build_py import build_py_2to3 as build_py + from distutils.command.build_py import build_py_2to3 as build_py except ImportError: - from distutils.command.build_py import build_py + from distutils.command.build_py import build_py to your setup.py, and later:: diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/faq/design.rst --- a/Doc/faq/design.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/faq/design.rst Tue May 10 12:01:23 2016 +0300 @@ -158,7 +158,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: @@ -190,7 +190,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 @@ -203,7 +203,7 @@` support the iterator protocol, so you can write simply:: for line in f: - ... # do something with line... + ... # do something with line... @@ -577,8 +577,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 @@ -619,7 +621,7 @@ dictionary in sorted 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? @@ -675,11 +677,11 @@ class label(Exception): 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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/faq/library.rst --- a/Doc/faq/library.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/faq/library.rst Tue May 10 12:01:23 2016 +0300 @@ -257,7 +257,8 @@ import threading, time def thread_task(name, n): - for i in range(n): print(name, i) + for i in range(n): + print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) @@ -273,7 +274,8 @@ def thread_task(name, n): time.sleep(0.001) # <--------------------! - for i in range(n): print(name, i) + for i in range(n): + print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) @@ -502,8 +504,8 @@ import struct with open(filename, "rb") as f: - s = f.read(8) - x, y, z = struct.unpack(">hhl", s) + s = f.read(8) + x, y, z = struct.unpack(">hhl", s) The '>' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the @@ -681,10 +683,10 @@ import urllib.request - ### 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 req = urllib.request.urlopen('http://www.some-server.out-there' '/cgi-bin/some-cgi-script', data=qs) with req: @@ -740,8 +742,9 @@ ``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's some sample code:: + import os + SENDMAIL = "/usr/sbin/sendmail" # sendmail location - import os p = os.popen("%s -t -i" % SENDMAIL, "w") p.write("To: receiver@example.com\n") p.write("Subject: test\n") diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/faq/programming.rst --- a/Doc/faq/programming.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/faq/programming.rst Tue May 10 12:01:23 2016 +0300 @@ -207,7 +207,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``, @@ -234,7 +234,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 @@ -539,7 +539,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']) @@ -655,16 +655,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 object at 0x16D07CC> - print(a) + >>> print(a) <__main__.A object at 0x16D07CC> Arguably the class has a name: even though it is bound to two names and invoked @@ -1099,7 +1098,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. @@ -1107,7 +1106,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? @@ -1405,7 +1404,7 @@ definition:: class C: - def meth (self, arg): + def meth(self, arg): return arg * 2 + self.attribute @@ -1438,9 +1437,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 @@ -1448,11 +1447,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() @@ -1509,7 +1508,7 @@ Use the built-in :func:`super` function:: class Derived(Base): - def meth (self): + def meth(self): super(Derived, self).meth() For version prior to 3.0, you may be using classic classes: For a class diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/descriptor.rst --- a/Doc/howto/descriptor.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/descriptor.rst Tue May 10 12:01:23 2016 +0300 @@ -104,7 +104,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: @@ -163,9 +163,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" @@ -287,15 +287,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- >>> D.f # Get from a class becomes an unbound method + >>> D.f # Get from a class becomes an unbound method- >>> d.f # Get from an instance becomes a bound method + >>> d.f # Get from an instance becomes a bound method> The output suggests that bound and unbound methods are two different types. @@ -358,10 +358,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)) @@ -371,23 +371,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)) @@ -419,15 +419,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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/functional.rst --- a/Doc/howto/functional.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/functional.rst Tue May 10 12:01:23 2016 +0300 @@ -395,14 +395,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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/logging-cookbook.rst --- a/Doc/howto/logging-cookbook.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/logging-cookbook.rst Tue May 10 12:01:23 2016 +0300 @@ -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 @@ -360,7 +361,7 @@ An example of using these two classes follows (imports omitted):: - que = queue.Queue(-1) # no limit on size + que = queue.Queue(-1) # no limit on size queue_handler = QueueHandler(que) handler = logging.StreamHandler() listener = QueueListener(que, handler) @@ -656,21 +657,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') - - 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') + 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') which, when run, produces something like:: @@ -764,10 +765,10 @@ while True: try: record = queue.get() - if record is None: # We send this as a sentinel to tell the listener to quit. + if record is None: # We send this as a sentinel to tell the listener to quit. break logger = logging.getLogger(record.name) - logger.handle(record) # No level or filter logic applied - just do it! + logger.handle(record) # No level or filter logic applied - just do it! except Exception: import sys, traceback print('Whoops! Problem:', file=sys.stderr) @@ -790,10 +791,11 @@ # Note that on Windows you can't rely on fork semantics, so each process # will run the logging configuration code when it starts. def worker_configurer(queue): - h = logging.handlers.QueueHandler(queue) # Just the one handler needed + h = logging.handlers.QueueHandler(queue) # Just the one handler needed root = logging.getLogger() root.addHandler(h) - root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied. + # send all messages, for demo; no other level or filter logic applied. + root.setLevel(logging.DEBUG) # This is the worker process top-level loop, which just logs ten events with # random intervening delays before terminating. @@ -821,7 +823,7 @@ workers = [] for i in range(10): worker = multiprocessing.Process(target=worker_process, - args=(queue, worker_configurer)) + args=(queue, worker_configurer)) workers.append(worker) worker.start() for w in workers: @@ -1245,12 +1247,12 @@ of queues, for example a ZeroMQ 'publish' socket. In the example below,the socket is created separately and passed to the handler (as its 'queue'):: - import zmq # using pyzmq, the Python binding for ZeroMQ - import json # for serializing records portably + import zmq # using pyzmq, the Python binding for ZeroMQ + import json # for serializing records portably ctx = zmq.Context() - sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value - sock.bind('tcp://*:5556') # or wherever + sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value + sock.bind('tcp://*:5556') # or wherever class ZeroMQSocketHandler(QueueHandler): def enqueue(self, record): @@ -1288,7 +1290,7 @@ def __init__(self, uri, *handlers, **kwargs): self.ctx = kwargs.get('ctx') or zmq.Context() socket = zmq.Socket(self.ctx, zmq.SUB) - socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything + socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything socket.connect(uri) def dequeue(self): @@ -2116,7 +2118,7 @@ Format an exception so that it prints on a single line. """ result = super(OneLineExceptionFormatter, self).formatException(exc_info) - return repr(result) # or format into one line however you want to + return repr(result) # or format into one line however you want to def format(self, record): s = super(OneLineExceptionFormatter, self).format(record) diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/logging.rst --- a/Doc/howto/logging.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/logging.rst Tue May 10 12:01:23 2016 +0300 @@ -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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/regex.rst --- a/Doc/howto/regex.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/regex.rst Tue May 10 12:01:23 2016 +0300 @@ -1115,19 +1115,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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/unicode.rst --- a/Doc/howto/unicode.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/unicode.rst Tue May 10 12:01:23 2016 +0300 @@ -687,7 +687,7 @@ # make changes to the string 'data' with open(fname + '.new', 'w', - encoding="ascii", errors="surrogateescape") as f: + encoding="ascii", errors="surrogateescape") as f: f.write(data) The ``surrogateescape`` error handler will decode any non-ASCII bytes diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/howto/urllib2.rst --- a/Doc/howto/urllib2.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/howto/urllib2.rst Tue May 10 12:01:23 2016 +0300 @@ -175,10 +175,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.parse.urlencode(values) data = data.encode('ascii') @@ -215,7 +215,7 @@ >>> req = urllib.request.Request('http://www.pretend\_server.org') >>> try: urllib.request.urlopen(req) ... except urllib.error.URLError as e: - ... print(e.reason) #doctest: +SKIP + ... print(e.reason) #doctest: +SKIP ... (4, 'getaddrinfo failed') @@ -372,7 +372,7 @@ :: from urllib.request import Request, urlopen - from urllib.error import URLError + from urllib.error import URLError req = Request(someurl) try: response = urlopen(req) diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/argparse.rst --- a/Doc/library/argparse.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/argparse.rst Tue May 10 12:01:23 2016 +0300 @@ -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)) @@ -488,7 +488,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']) @@ -1109,9 +1109,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 ...] @@ -1129,7 +1129,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] @@ -1468,10 +1468,10 @@ >>> parser = argparse.ArgumentParser() >>> parser.add_argument( ... 'integers', metavar='int', type=int, choices=range(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=, integers=[1, 2, 3, 4]) >>> parser.parse_args(['1', '2', '3', '4', '--sum']) diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/asynchat.rst --- a/Doc/library/asynchat.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/asynchat.rst Tue May 10 12:01:23 2016 +0300 @@ -202,7 +202,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, b"".join(self.ibuffer)) self.handling = True self.ibuffer = [] diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/asyncio-sync.rst --- a/Doc/library/asyncio-sync.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/asyncio-sync.rst Tue May 10 12:01:23 2016 +0300 @@ -71,14 +71,14 @@ lock = Lock() ... with (yield from lock): - ... + ... Lock objects can be tested for locking state:: if not lock.locked(): - yield from lock + yield from lock else: - # lock is acquired + # lock is acquired ... .. method:: locked() diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/asyncore.rst --- a/Doc/library/asyncore.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/asyncore.rst Tue May 10 12:01:23 2016 +0300 @@ -315,8 +315,8 @@ self.buffer = self.buffer[sent:] - client = HTTPClient('www.python.org', '/') - asyncore.loop() + client = HTTPClient('www.python.org', '/') + asyncore.loop() .. _asyncore-example-2: diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/audioop.rst --- a/Doc/library/audioop.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/audioop.rst Tue May 10 12:01:23 2016 +0300 @@ -276,6 +276,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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/collections.abc.rst --- a/Doc/library/collections.abc.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/collections.abc.rst Tue May 10 12:01:23 2016 +0300 @@ -218,19 +218,22 @@ :meth:`isdisjoint`:: class ListBasedSet(collections.abc.Set): - ''' Alternate set implementation favoring space over speed - and not requiring the set elements to be hashable. ''' - def __init__(self, iterable): - self.elements = lst = [] - 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) + ''' Alternate set implementation favoring space over speed + and not requiring the set elements to be hashable. ''' + def __init__(self, iterable): + self.elements = lst = [] + 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) s1 = ListBasedSet('abcdef') s2 = ListBasedSet('defghi') diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/collections.rst --- a/Doc/library/collections.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/collections.rst Tue May 10 12:01:23 2016 +0300 @@ -1029,7 +1029,7 @@ in conjunction 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])) diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/concurrent.futures.rst --- a/Doc/library/concurrent.futures.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/concurrent.futures.rst Tue May 10 12:01:23 2016 +0300 @@ -99,12 +99,12 @@ import time def wait_on_b(): time.sleep(5) - print(b.result()) # b will never complete because it is waiting on a. + print(b.result()) # b will never complete because it is waiting on a. return 5 def wait_on_a(): time.sleep(5) - print(a.result()) # a will never complete because it is waiting on b. + print(a.result()) # a will never complete because it is waiting on b. return 6 diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/configparser.rst --- a/Doc/library/configparser.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/configparser.rst Tue May 10 12:01:23 2016 +0300 @@ -833,13 +833,13 @@ # Set the optional *raw* argument of get() to True if you wish to disable # interpolation in a single get operation. - print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" - print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" + print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" + print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" # The optional *vars* argument is a dict with members that will take # precedence in interpolation. print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation', - 'baz': 'evil'})) + 'baz': 'evil'})) # The optional *fallback* argument can be used to provide a fallback value print(cfg.get('Section1', 'foo')) @@ -866,10 +866,10 @@ config = configparser.ConfigParser({'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!" .. _configparser-objects: diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/contextlib.rst --- a/Doc/library/contextlib.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/contextlib.rst Tue May 10 12:01:23 2016 +0300 @@ -644,7 +644,7 @@ Before After >>> with cm: - ... pass + ... pass ... Traceback (most recent call last): ... diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/crypt.rst --- a/Doc/library/crypt.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/crypt.rst Tue May 10 12:01:23 2016 +0300 @@ -149,4 +149,4 @@ hashed = crypt.crypt(plaintext) if not compare_hash(hashed, crypt.crypt(plaintext, hashed)): - raise ValueError("hashed version doesn't validate against original") + raise ValueError("hashed version doesn't validate against original") diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/ctypes.rst --- a/Doc/library/ctypes.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/ctypes.rst Tue May 10 12:01:23 2016 +0300 @@ -52,11 +52,11 @@ convention:: >>> from ctypes import * - >>> print(windll.kernel32) # doctest: +WINDOWS + >>> print(windll.kernel32) # doctest: +WINDOWS- >>> print(cdll.msvcrt) # doctest: +WINDOWS + >>> print(cdll.msvcrt) # doctest: +WINDOWS- >>> libc = cdll.msvcrt # doctest: +WINDOWS + >>> libc = cdll.msvcrt # doctest: +WINDOWS >>> Windows appends the usual ``.dll`` file suffix automatically. @@ -72,10 +72,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- >>> libc = CDLL("libc.so.6") # doctest: +LINUX - >>> libc # doctest: +LINUX + >>> libc = CDLL("libc.so.6") # doctest: +LINUX + >>> libc # doctest: +LINUX >>> @@ -92,9 +92,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 "", line 1, in ? File "ctypes.py", line 239, in __getattr__ @@ -123,16 +123,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 "", line 1, in ? File "ctypes.py", line 310, in __getitem__ @@ -154,9 +154,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 >>> @@ -165,11 +165,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 "", 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 "", line 1, in ? ValueError: Procedure probably called with too many arguments (4 bytes in excess) @@ -178,13 +178,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 "", line 1, in ? ValueError: Procedure probably called with not enough arguments (4 bytes missing) >>> - >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS + >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS Traceback (most recent call last): File "", line 1, in ? ValueError: Procedure probably called with too many arguments (4 bytes in excess) @@ -197,7 +197,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 "", line 1, in ? OSError: exception: access violation reading 0x00000020 @@ -462,9 +462,9 @@ a string pointer and a char, and returns a pointer to a string:: >>> strchr = libc.strchr - >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP + >>> strchr(b"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(b"abcdef", ord("d")) b'def' >>> print(strchr(b"abcdef", ord("x"))) @@ -495,17 +495,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 "", line 1, in ? File "", line 3, in ValidHandle @@ -676,12 +676,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 @@ -998,7 +998,7 @@ The result:: - >>> 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 @@ -1100,9 +1100,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 -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/email.headerregistry.rst --- a/Doc/library/email.headerregistry.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/email.headerregistry.rst Tue May 10 12:01:23 2016 +0300 @@ -171,7 +171,7 @@ :class:`~datetime.datetime` instance. This means, for example, that the following code is valid and does what one would expect:: - msg['Date'] = datetime(2011, 7, 15, 21) + msg['Date'] = datetime(2011, 7, 15, 21) Because this is a naive ``datetime`` it will be interpreted as a UTC timestamp, and the resulting value will have a timezone of ``-0000``. Much diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/getopt.rst --- a/Doc/library/getopt.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/getopt.rst Tue May 10 12:01:23 2016 +0300 @@ -124,7 +124,7 @@ opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError as err: # print help information and exit: - print(err) # will print something like "option -a not recognized" + print(err) # will print something like "option -a not recognized" usage() sys.exit(2) output = None diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/html.parser.rst --- a/Doc/library/html.parser.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/html.parser.rst Tue May 10 12:01:23 2016 +0300 @@ -51,8 +51,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) @@ -237,21 +239,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 = chr(name2codepoint[name]) print("Named ent:", c) + def handle_charref(self, name): if name.startswith('x'): c = chr(int(name[1:], 16)) else: c = chr(int(name)) print("Num ent :", c) + def handle_decl(self, data): print("Decl :", data) @@ -283,7 +291,7 @@ attr: ('type', 'text/css') Data : #python { color: green } End tag : style - >>> + >>> parser.feed('') Start tag: script diff -r bfc4c57a0986 -r 2b492ea961c1 Doc/library/http.client.rst --- a/Doc/library/http.client.rst Mon May 09 23:43:53 2016 -0700 +++ b/Doc/library/http.client.rst Tue May 10 12:01:23 2016 +0300 @@ -441,7 +441,7 @@ >>> conn.request("GET", "/") >>> r1 = conn.getresponse() >>> while not r1.closed: - ... print(r1.read(200)) # 200 bytes + ... print(r1.read(200)) # 200 bytes b'\n/storchaka@gmail.com