Imported Upstream version 2.7.12 50/138350/1 upstream/2.7.12
authorDongHun Kwak <dh0128.kwak@samsung.com>
Wed, 12 Jul 2017 02:05:55 +0000 (11:05 +0900)
committerDongHun Kwak <dh0128.kwak@samsung.com>
Wed, 12 Jul 2017 02:06:03 +0000 (11:06 +0900)
Change-Id: Id086dcc8e315c8ad61502768ef9b92372461e560
Signed-off-by: DongHun Kwak <dh0128.kwak@samsung.com>
605 files changed:
Demo/metaclasses/index.html
Demo/tix/samples/Balloon.py
Demo/tix/samples/CmpImg.py
Demo/tkinter/guido/canvasevents.py
Demo/tkinter/matt/canvas-with-scrollbars.py
Demo/tkinter/ttk/ttkcalendar.py
Doc/README.txt
Doc/bugs.rst
Doc/c-api/allocation.rst
Doc/c-api/arg.rst
Doc/c-api/code.rst
Doc/c-api/exceptions.rst
Doc/c-api/gcsupport.rst
Doc/c-api/init.rst
Doc/c-api/intro.rst
Doc/c-api/object.rst
Doc/c-api/set.rst
Doc/c-api/string.rst
Doc/c-api/structures.rst
Doc/c-api/unicode.rst
Doc/conf.py
Doc/copyright.rst
Doc/distributing/index.rst
Doc/distutils/apiref.rst
Doc/distutils/builtdist.rst
Doc/distutils/configfile.rst
Doc/distutils/index.rst
Doc/extending/extending.rst
Doc/faq/design.rst
Doc/faq/extending.rst
Doc/faq/general.rst
Doc/faq/gui.rst
Doc/faq/library.rst
Doc/faq/programming.rst
Doc/faq/windows.rst
Doc/glossary.rst
Doc/howto/argparse.rst
Doc/howto/cporting.rst
Doc/howto/curses.rst
Doc/howto/descriptor.rst
Doc/howto/functional.rst
Doc/howto/logging-cookbook.rst
Doc/howto/logging.rst
Doc/howto/pyporting.rst
Doc/howto/regex.rst
Doc/howto/sockets.rst
Doc/howto/sorting.rst
Doc/howto/unicode.rst
Doc/howto/urllib2.rst
Doc/howto/webservers.rst
Doc/install/index.rst
Doc/installing/index.rst
Doc/library/2to3.rst
Doc/library/_winreg.rst
Doc/library/argparse.rst
Doc/library/array.rst
Doc/library/asynchat.rst
Doc/library/audioop.rst
Doc/library/base64.rst
Doc/library/basehttpserver.rst
Doc/library/binascii.rst
Doc/library/bisect.rst
Doc/library/cgi.rst
Doc/library/codecs.rst
Doc/library/collections.rst
Doc/library/colorsys.rst
Doc/library/configparser.rst
Doc/library/contextlib.rst
Doc/library/cookie.rst
Doc/library/cookielib.rst
Doc/library/crypto.rst
Doc/library/csv.rst
Doc/library/ctypes.rst
Doc/library/curses.rst
Doc/library/datetime.rst
Doc/library/decimal.rst
Doc/library/difflib.rst
Doc/library/distutils.rst
Doc/library/email.generator.rst
Doc/library/fcntl.rst
Doc/library/fileinput.rst
Doc/library/fl.rst
Doc/library/ftplib.rst
Doc/library/functions.rst
Doc/library/getopt.rst
Doc/library/getpass.rst
Doc/library/heapq.rst
Doc/library/htmllib.rst
Doc/library/htmlparser.rst
Doc/library/httplib.rst
Doc/library/ic.rst
Doc/library/idle.rst
Doc/library/imageop.rst
Doc/library/imaplib.rst
Doc/library/inspect.rst
Doc/library/io.rst
Doc/library/ipc.rst
Doc/library/itertools.rst
Doc/library/json.rst
Doc/library/locale.rst
Doc/library/logging.handlers.rst
Doc/library/logging.rst
Doc/library/mailbox.rst
Doc/library/mailcap.rst
Doc/library/marshal.rst
Doc/library/math.rst
Doc/library/mimetypes.rst
Doc/library/mmap.rst
Doc/library/msilib.rst
Doc/library/multiprocessing.rst
Doc/library/nis.rst
Doc/library/optparse.rst
Doc/library/os.path.rst
Doc/library/os.rst
Doc/library/othergui.rst
Doc/library/pprint.rst
Doc/library/pyexpat.rst
Doc/library/random.rst
Doc/library/re.rst
Doc/library/readline.rst
Doc/library/resource.rst
Doc/library/restricted.rst
Doc/library/select.rst
Doc/library/sets.rst
Doc/library/sgmllib.rst
Doc/library/shelve.rst
Doc/library/shlex.rst
Doc/library/socket.rst
Doc/library/socketserver.rst
Doc/library/sqlite3.rst
Doc/library/ssl.rst
Doc/library/stdtypes.rst
Doc/library/string.rst
Doc/library/subprocess.rst
Doc/library/sunaudio.rst
Doc/library/tarfile.rst
Doc/library/tempfile.rst
Doc/library/termios.rst
Doc/library/test.rst
Doc/library/threading.rst
Doc/library/time.rst
Doc/library/timeit.rst
Doc/library/tix.rst
Doc/library/tkinter.rst
Doc/library/tokenize.rst
Doc/library/traceback.rst
Doc/library/ttk.rst
Doc/library/types.rst
Doc/library/unittest.rst
Doc/library/urllib.rst
Doc/library/urllib2.rst
Doc/library/urlparse.rst
Doc/library/warnings.rst
Doc/library/weakref.rst
Doc/library/webbrowser.rst
Doc/library/wsgiref.rst
Doc/library/xml.dom.minidom.rst
Doc/library/xml.dom.rst
Doc/library/xml.etree.elementtree.rst
Doc/library/xml.rst
Doc/library/xml.sax.reader.rst
Doc/library/xmlrpclib.rst
Doc/library/zipfile.rst
Doc/library/zipimport.rst
Doc/library/zlib.rst
Doc/license.rst
Doc/reference/compound_stmts.rst
Doc/reference/datamodel.rst
Doc/reference/expressions.rst
Doc/reference/introduction.rst
Doc/reference/simple_stmts.rst
Doc/tools/extensions/pyspecific.py
Doc/tools/rstlint.py
Doc/tools/static/basic.css
Doc/tools/static/copybutton.js
Doc/tools/susp-ignored.csv
Doc/tools/templates/download.html
Doc/tools/templates/indexcontent.html
Doc/tools/templates/indexsidebar.html
Doc/tools/templates/layout.html
Doc/tutorial/appendix.rst
Doc/tutorial/classes.rst
Doc/tutorial/controlflow.rst
Doc/tutorial/datastructures.rst
Doc/tutorial/errors.rst
Doc/tutorial/inputoutput.rst
Doc/tutorial/interactive.rst
Doc/tutorial/introduction.rst
Doc/tutorial/modules.rst
Doc/tutorial/stdlib.rst
Doc/tutorial/stdlib2.rst
Doc/tutorial/whatnow.rst
Doc/using/cmdline.rst
Doc/using/mac.rst
Doc/using/unix.rst
Doc/using/windows.rst
Doc/whatsnew/2.0.rst
Doc/whatsnew/2.1.rst
Doc/whatsnew/2.2.rst
Doc/whatsnew/2.3.rst
Doc/whatsnew/2.4.rst
Doc/whatsnew/2.5.rst
Doc/whatsnew/2.6.rst
Doc/whatsnew/2.7.rst
Include/code.h
Include/dictobject.h
Include/listobject.h
Include/memoryobject.h
Include/object.h
Include/patchlevel.h
Include/pyerrors.h
Include/pymacconfig.h
Include/pythonrun.h
Include/stringobject.h
Include/unicodeobject.h
LICENSE
Lib/BaseHTTPServer.py
Lib/Cookie.py
Lib/SimpleHTTPServer.py
Lib/SocketServer.py
Lib/_LWPCookieJar.py
Lib/_osx_support.py
Lib/_pyio.py
Lib/_strptime.py
Lib/base64.py
Lib/bsddb/test/test_all.py
Lib/bsddb/test/test_lock.py
Lib/calendar.py
Lib/cgi.py
Lib/collections.py
Lib/copy.py
Lib/ctypes/__init__.py
Lib/ctypes/_endian.py
Lib/ctypes/macholib/README.ctypes
Lib/ctypes/macholib/__init__.py
Lib/ctypes/macholib/dyld.py
Lib/ctypes/macholib/dylib.py
Lib/ctypes/macholib/framework.py
Lib/ctypes/test/test_arrays.py
Lib/ctypes/test/test_pointers.py
Lib/ctypes/test/test_structures.py
Lib/ctypes/test/test_values.py
Lib/ctypes/util.py
Lib/ctypes/wintypes.py
Lib/decimal.py
Lib/difflib.py
Lib/distutils/ccompiler.py
Lib/distutils/cygwinccompiler.py
Lib/distutils/msvc9compiler.py
Lib/distutils/tests/test_build_ext.py
Lib/distutils/tests/test_unixccompiler.py
Lib/distutils/unixccompiler.py
Lib/email/message.py
Lib/email/parser.py
Lib/encodings/utf_32.py
Lib/ensurepip/__init__.py
Lib/ensurepip/_bundled/pip-7.1.2-py2.py3-none-any.whl [deleted file]
Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl [new file with mode: 0644]
Lib/ensurepip/_bundled/setuptools-20.10.1-py2.py3-none-any.whl [moved from Lib/ensurepip/_bundled/setuptools-18.2-py2.py3-none-any.whl with 60% similarity]
Lib/fileinput.py
Lib/getopt.py
Lib/gzip.py
Lib/heapq.py
Lib/hotshot/__init__.py
Lib/idlelib/AutoComplete.py
Lib/idlelib/CREDITS.txt
Lib/idlelib/ChangeLog
Lib/idlelib/Debugger.py
Lib/idlelib/IOBinding.py
Lib/idlelib/MultiCall.py
Lib/idlelib/NEWS.txt
Lib/idlelib/PyShell.py
Lib/idlelib/README.txt
Lib/idlelib/WidgetRedirector.py
Lib/idlelib/aboutDialog.py
Lib/idlelib/configDialog.py
Lib/idlelib/configHandler.py
Lib/idlelib/help.html
Lib/idlelib/help.py
Lib/idlelib/idle_test/README.txt
Lib/idlelib/idle_test/__init__.py
Lib/idlelib/idle_test/htest.py
Lib/idlelib/idle_test/test_autocomplete.py
Lib/idlelib/idle_test/test_autoexpand.py
Lib/idlelib/idle_test/test_configdialog.py
Lib/idlelib/idle_test/test_editmenu.py [new file with mode: 0644]
Lib/idlelib/idle_test/test_formatparagraph.py
Lib/idlelib/idle_test/test_helpabout.py [new file with mode: 0644]
Lib/idlelib/idle_test/test_textview.py
Lib/idlelib/idle_test/test_warning.py
Lib/idlelib/idle_test/test_widgetredir.py
Lib/idlelib/rpc.py
Lib/idlelib/textView.py
Lib/lib-tk/Tix.py
Lib/lib-tk/Tkdnd.py
Lib/lib-tk/Tkinter.py
Lib/lib-tk/test/test_tkinter/test_geometry_managers.py
Lib/lib-tk/test/test_tkinter/test_widgets.py
Lib/lib-tk/test/test_ttk/test_functions.py
Lib/lib-tk/test/test_ttk/test_widgets.py
Lib/lib-tk/test/widget_tests.py
Lib/lib-tk/ttk.py
Lib/lib2to3/btm_utils.py
Lib/lib2to3/fixer_base.py
Lib/lib2to3/fixes/fix_metaclass.py
Lib/lib2to3/patcomp.py
Lib/lib2to3/pgen2/tokenize.py
Lib/lib2to3/refactor.py
Lib/locale.py
Lib/logging/__init__.py
Lib/mailbox.py
Lib/mimetypes.py
Lib/modulefinder.py
Lib/msilib/__init__.py
Lib/msilib/schema.py
Lib/multiprocessing/managers.py
Lib/mutex.py
Lib/ntpath.py
Lib/optparse.py
Lib/os2emxpath.py
Lib/pdb.doc
Lib/plat-irix5/flp.py
Lib/plat-irix6/flp.py
Lib/plat-mac/bgenlocations.py
Lib/plat-mac/lib-scriptpackages/Finder/Files.py
Lib/plat-mac/lib-scriptpackages/SystemEvents/Processes_Suite.py
Lib/platform.py
Lib/posixpath.py
Lib/pstats.py
Lib/pydoc_data/topics.py
Lib/rfc822.py
Lib/rlcompleter.py
Lib/robotparser.py
Lib/runpy.py
Lib/smtplib.py
Lib/socket.py
Lib/sqlite3/test/factory.py
Lib/sqlite3/test/regression.py
Lib/sre_parse.py
Lib/ssl.py
Lib/subprocess.py
Lib/tarfile.py
Lib/tempfile.py
Lib/test/buffer_tests.py [deleted file]
Lib/test/capath/0e4015b9.0 [new file with mode: 0644]
Lib/test/capath/ce7b8643.0 [new file with mode: 0644]
Lib/test/https_svn_python_org_root.pem [deleted file]
Lib/test/list_tests.py
Lib/test/pickletester.py
Lib/test/regrtest.py
Lib/test/script_helper.py
Lib/test/selfsigned_pythontestdotnet.pem
Lib/test/seq_tests.py
Lib/test/string_tests.py
Lib/test/test__locale.py
Lib/test/test_argparse.py
Lib/test/test_base64.py
Lib/test/test_binop.py
Lib/test/test_buffer.py
Lib/test/test_builtin.py
Lib/test/test_bytes.py
Lib/test/test_capi.py
Lib/test/test_cmd.py
Lib/test/test_cmd_line_script.py
Lib/test/test_codecs.py
Lib/test/test_coding.py [deleted file]
Lib/test/test_collections.py
Lib/test/test_compile.py
Lib/test/test_cookielib.py
Lib/test/test_copy.py
Lib/test/test_cpickle.py
Lib/test/test_csv.py
Lib/test/test_curses.py
Lib/test/test_datetime.py
Lib/test/test_deque.py
Lib/test/test_descr.py
Lib/test/test_dict.py
Lib/test/test_dictviews.py
Lib/test/test_dis.py
Lib/test/test_doctest.py
Lib/test/test_dummy_thread.py
Lib/test/test_exceptions.py
Lib/test/test_extcall.py
Lib/test/test_fileinput.py
Lib/test/test_float.py
Lib/test/test_format.py
Lib/test/test_functools.py
Lib/test/test_gdb.py
Lib/test/test_generators.py
Lib/test/test_getargs2.py
Lib/test/test_hashlib.py
Lib/test/test_httplib.py
Lib/test/test_httpservers.py
Lib/test/test_imageop.py
Lib/test/test_int.py
Lib/test/test_io.py
Lib/test/test_iter.py
Lib/test/test_itertools.py
Lib/test/test_locale.py
Lib/test/test_long.py
Lib/test/test_memoryio.py
Lib/test/test_memoryview.py
Lib/test/test_minidom.py
Lib/test/test_modulefinder.py
Lib/test/test_mutants.py
Lib/test/test_operator.py
Lib/test/test_ordered_dict.py [new file with mode: 0644]
Lib/test/test_pep263.py [deleted file]
Lib/test/test_pep292.py [deleted file]
Lib/test/test_pickle.py
Lib/test/test_platform.py
Lib/test/test_posixpath.py
Lib/test/test_print.py
Lib/test/test_rlcompleter.py
Lib/test/test_runpy.py
Lib/test/test_set.py
Lib/test/test_site.py
Lib/test/test_slice.py
Lib/test/test_socket.py
Lib/test/test_socketserver.py
Lib/test/test_source_encoding.py [new file with mode: 0644]
Lib/test/test_ssl.py
Lib/test/test_startfile.py
Lib/test/test_str.py
Lib/test/test_string.py
Lib/test/test_strptime.py
Lib/test/test_subprocess.py
Lib/test/test_support.py
Lib/test/test_sys.py
Lib/test/test_sys_setprofile.py
Lib/test/test_sys_settrace.py
Lib/test/test_tarfile.py
Lib/test/test_telnetlib.py
Lib/test/test_tempfile.py
Lib/test/test_thread.py
Lib/test/test_threading.py
Lib/test/test_threading_local.py
Lib/test/test_turtle.py [new file with mode: 0644]
Lib/test/test_unicode.py
Lib/test/test_urllib.py
Lib/test/test_urllib2.py
Lib/test/test_urllibnet.py
Lib/test/test_urlparse.py
Lib/test/test_warnings.py
Lib/test/test_weakref.py
Lib/test/test_winsound.py
Lib/test/test_xml_etree_c.py
Lib/test/test_xmlrpc.py
Lib/test/test_zipfile.py
Lib/test/test_zipfile64.py
Lib/test/test_zlib.py
Lib/unittest/case.py
Lib/unittest/result.py
Lib/urllib.py
Lib/urllib2.py
Lib/wsgiref/headers.py
Lib/xml/dom/minicompat.py
Lib/xml/etree/ElementTree.py
Lib/xmlrpclib.py
Mac/BuildScript/build-installer.py
Mac/BuildScript/openssl_sdk_makedepend.patch
Mac/BuildScript/resources/License.rtf
Mac/BuildScript/scripts/postflight.patch-profile
Mac/Demo/applescript/Disk_Copy/Special_Events.py
Mac/IDLE/Info.plist.in
Mac/IDLE/Makefile.in
Mac/IDLE/config-extensions.def [deleted file]
Mac/IDLE/config-main.def [deleted file]
Mac/Modules/icgluemodule.c
Mac/PythonLauncher/Info.plist.in
Mac/README
Mac/Resources/app/Info.plist.in
Mac/Resources/framework/Info.plist.in
Makefile.pre.in
Misc/ACKS
Misc/HISTORY
Misc/NEWS
Misc/cheatsheet
Misc/python.man
Modules/_bsddb.c
Modules/_collectionsmodule.c
Modules/_csv.c
Modules/_ctypes/_ctypes.c
Modules/_ctypes/_ctypes_test.c
Modules/_ctypes/callbacks.c
Modules/_ctypes/callproc.c
Modules/_ctypes/cfield.c
Modules/_ctypes/ctypes.h
Modules/_ctypes/ctypes_dlfcn.h
Modules/_ctypes/libffi/m4/libtool.m4
Modules/_ctypes/malloc_closure.c
Modules/_ctypes/stgdict.c
Modules/_curses_panel.c
Modules/_elementtree.c
Modules/_functoolsmodule.c
Modules/_heapqmodule.c
Modules/_io/bufferedio.c
Modules/_io/bytesio.c
Modules/_io/fileio.c
Modules/_io/iobase.c
Modules/_io/stringio.c
Modules/_io/textio.c
Modules/_json.c
Modules/_multiprocessing/semaphore.c
Modules/_sqlite/connection.c
Modules/_sqlite/cursor.c
Modules/_sre.c
Modules/_ssl.c
Modules/_struct.c
Modules/_testcapimodule.c
Modules/arraymodule.c
Modules/audioop.c
Modules/bz2module.c
Modules/cPickle.c
Modules/cdmodule.c
Modules/cjkcodecs/cjkcodecs.h
Modules/datetimemodule.c
Modules/expat/expat.h
Modules/expat/xmlparse.c
Modules/expat/xmltok.c
Modules/getaddrinfo.c
Modules/getpath.c
Modules/itertoolsmodule.c
Modules/ld_so_aix.in
Modules/mathmodule.c
Modules/mmapmodule.c
Modules/operator.c
Modules/parsermodule.c
Modules/python.c
Modules/readline.c
Modules/sha256module.c
Modules/sha512module.c
Modules/signalmodule.c
Modules/socketmodule.c
Modules/zipimport.c
Modules/zlibmodule.c
Objects/bytearrayobject.c
Objects/cellobject.c
Objects/codeobject.c
Objects/descrobject.c
Objects/dictobject.c
Objects/exceptions.c
Objects/fileobject.c
Objects/floatobject.c
Objects/frameobject.c
Objects/funcobject.c
Objects/iterobject.c
Objects/listobject.c
Objects/longobject.c
Objects/object.c
Objects/setobject.c
Objects/sliceobject.c
Objects/stringlib/formatter.h
Objects/stringlib/string_format.h
Objects/stringobject.c
Objects/tupleobject.c
Objects/typeobject.c
Objects/unicodeobject.c
Objects/weakrefobject.c
PC/VS9.0/pyproject.vsprops
PC/VS9.0/readme.txt
PC/_winreg.c
PC/icons/baselogo.svg [deleted file]
PC/icons/source.xar [deleted file]
PC/pyconfig.h
PC/python_nt.rc
PCbuild/_hashlib.vcxproj
PCbuild/_ssl.vcxproj
PCbuild/build.bat
PCbuild/build_pgo.bat
PCbuild/env.bat
PCbuild/get_externals.bat
PCbuild/openssl.props
PCbuild/pyproject.props
PCbuild/python.props
PCbuild/readme.txt
Python/_warnings.c
Python/bltinmodule.c
Python/ceval.c
Python/codecs.c
Python/compile.c
Python/errors.c
Python/getargs.c
Python/getcopyright.c
Python/import.c
Python/modsupport.c
Python/peephole.c
Python/pythonrun.c
Python/random.c
Python/symtable.c
Python/thread_nt.h
Python/thread_wince.h
Python/traceback.c
README
Tools/bgen/bgen/bgenVariable.py
Tools/compiler/astgen.py
Tools/gdb/libpython.py
Tools/msi/msi.py
Tools/msi/schema.py
Tools/msi/uisample.py
Tools/scripts/findnocoding.py
configure
configure.ac
pyconfig.h.in
setup.py

index eee473a..1675c63 100644 (file)
@@ -222,7 +222,7 @@ then used as a (normal, non-meta) class; instantiation of the class
 means calling the metainstance, and this will return a real instance.
 And what class is that an instance of?  Conceptually, it is of course
 an instance of our metainstance; but in most cases the Python runtime
-system will see it as an instance of a helper class used by the
+system will see it as an instance of a helper class used by the
 metaclass to implement its (non-meta) instances...
 
 <P>Hopefully an example will make things clearer.  Let's presume we
index 2295905..576b4ed 100644 (file)
@@ -11,7 +11,7 @@
 # program.
 
 # This file demonstrates the use of the tixBalloon widget, which provides
-# a interesting way to give help tips about elements in your user interface.
+# an interesting way to give help tips about elements in your user interface.
 # Your can display the help message in a "balloon" and a status bar widget.
 #
 
index 4720a10..8b33579 100644 (file)
@@ -155,7 +155,7 @@ def RunSample(w):
     net = Tix.Button(w, padx=4, pady=1, width=120)
 
     # Create the first image: we create a line, then put a string,
-    # a space and a image into this line, from left to right.
+    # a space and an image into this line, from left to right.
     # The result: we have a one-line image that consists of three
     # individual items
     #
index 74ed76f..1982a50 100755 (executable)
@@ -24,7 +24,7 @@ class Object:
     depends on the object; for simple objects, it may be their center.
 
     Objects have mouse sensitivity.  They can be clicked, dragged and
-    double-clicked.  The behavior may actually determined by the pile
+    double-clicked.  The behavior may actually be determined by the pile
     they are in.
 
     All instance attributes are public since the derived class may
index 81ef25a..8f81cad 100644 (file)
@@ -1,7 +1,7 @@
 from Tkinter import *
 
-# This example program creates a scroling canvas, and demonstrates
-# how to tie scrollbars and canvses together. The mechanism
+# This example program creates a scrolling canvas, and demonstrates
+# how to tie scrollbars and canvases together. The mechanism
 # is analogus for listboxes and other widgets with
 # "xscroll" and "yscroll" configuration options.
 
index faa45c5..f163170 100644 (file)
@@ -191,7 +191,7 @@ class Calendar(ttk.Frame):
 
         self._date = self._date - self.timedelta(days=1)
         self._date = self.datetime(self._date.year, self._date.month, 1)
-        self._build_calendar() # reconstuct calendar
+        self._build_calendar() # reconstruct calendar
 
     def _next_month(self):
         """Update calendar to show the next month."""
index 004c6e1..4f8e9f8 100644 (file)
@@ -119,27 +119,3 @@ and we will process your request as soon as possible.
 
 If you want to help the Documentation Team, you are always welcome.  Just send
 a mail to docs@python.org.
-
-
-Copyright notice
-================
-
-The Python source is copyrighted, but you can freely use and copy it
-as long as you don't change or remove the copyright notice:
-
-----------------------------------------------------------------------
-Copyright (c) 2000-2014 Python Software Foundation.
-All rights reserved.
-
-Copyright (c) 2000 BeOpen.com.
-All rights reserved.
-
-Copyright (c) 1995-2000 Corporation for National Research Initiatives.
-All rights reserved.
-
-Copyright (c) 1991-1995 Stichting Mathematisch Centrum.
-All rights reserved.
-
-See the file "license.rst" for information on usage and redistribution
-of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-----------------------------------------------------------------------
index f01ae0e..25ce3ca 100644 (file)
@@ -16,7 +16,8 @@ If you find a bug in this documentation or would like to propose an improvement,
 please submit a bug report on the :ref:`tracker <using-the-tracker>`.  If you
 have a suggestion how to fix it, include that as well.
 
-If you're short on time, you can also email your bug report to docs@python.org.
+If you're short on time, you can also email documentation bug reports to
+docs@python.org (behavioral bugs can be sent to python-list@python.org).
 'docs@' is a mailing list run by volunteers; your request will be noticed,
 though it may take a while to be processed.
 
index 32a414b..7f7435f 100644 (file)
@@ -98,7 +98,7 @@ Allocating Objects on the Heap
    Create a new module object based on a name and table of functions,
    returning the new module object.  If *doc* is non-*NULL*, it will be used
    to define the docstring for the module.  If *self* is non-*NULL*, it will
-   passed to the functions of the module as their (otherwise *NULL*) first
+   be passed to the functions of the module as their (otherwise *NULL*) first
    parameter.  (This was added as an experimental feature, and there are no
    known uses in the current version of Python.)  For *apiver*, the only value
    which should be passed is defined by the constant
index 8fbdc50..71e1fa3 100644 (file)
@@ -24,7 +24,7 @@ the format unit; the entry in (round) parentheses is the Python object type
 that matches the format unit; and the entry in [square] brackets is the type
 of the C variable(s) whose address should be passed.
 
-These formats allow to access an object as a contiguous chunk of memory.
+These formats allow accessing an object as a contiguous chunk of memory.
 You don't have to provide raw storage for the returned unicode or bytes
 area.  Also, you won't have to release any memory yourself, except with the
 ``es``, ``es#``, ``et`` and ``et#`` formats.
@@ -136,7 +136,8 @@ area.  Also, you won't have to release any memory yourself, except with the
    :c:func:`PyArg_ParseTuple` will use this location as the buffer and
    interpret the initial value of *\*buffer_length* as the buffer size.  It
    will then copy the encoded data into the buffer and NUL-terminate it.  If
-   the buffer is not large enough, a :exc:`ValueError` will be set.
+   the buffer is not large enough, a :exc:`TypeError` will be set.
+   Note: starting from Python 3.6 a :exc:`ValueError` will be set.
 
    In both cases, *\*buffer_length* is set to the length of the encoded data
    without the trailing NUL byte.
index 0412138..946ad6e 100644 (file)
@@ -2,15 +2,13 @@
 
 .. _codeobjects:
 
+.. index:: object; code, code object
+
 Code Objects
 ------------
 
 .. sectionauthor:: Jeffrey Yasskin <jyasskin@gmail.com>
 
-
-.. index::
-   object: code
-
 Code objects are a low-level detail of the CPython implementation.
 Each one represents a chunk of executable code that hasn't yet been
 bound into a function.
index 65249e1..10e2c4c 100644 (file)
@@ -404,8 +404,8 @@ is a separate error indicator for each thread.
    :meth:`__del__` method.
 
    The function is called with a single argument *obj* that identifies the context
-   in which the unraisable exception occurred. The repr of *obj* will be printed in
-   the warning message.
+   in which the unraisable exception occurred. If possible,
+   the repr of *obj* will be printed in the warning message.
 
 
 .. _unicodeexceptions:
index b0a2d5c..9438fea 100644 (file)
@@ -137,9 +137,10 @@ must name its arguments exactly *visit* and *arg*:
 
 .. c:function:: void Py_VISIT(PyObject *o)
 
-   Call the *visit* callback, with arguments *o* and *arg*. If *visit* returns
-   a non-zero value, then return it.  Using this macro, :c:member:`~PyTypeObject.tp_traverse`
-   handlers look like::
+   If *o* is not *NULL*, call the *visit* callback, with arguments *o*
+   and *arg*.  If *visit* returns a non-zero value, then return it.
+   Using this macro, :c:member:`~PyTypeObject.tp_traverse` handlers
+   look like::
 
       static int
       my_traverse(Noddy *self, visitproc visit, void *arg)
index d78b43d..6663551 100644 (file)
@@ -297,7 +297,7 @@ Process-wide parameters
       It is recommended that applications embedding the Python interpreter
       for purposes other than executing a single script pass 0 as *updatepath*,
       and update :data:`sys.path` themselves if desired.
-      See `CVE-2008-5983 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
+      See `CVE-2008-5983 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
 
       On versions before 2.6.6, you can achieve the same effect by manually
       popping the first :data:`sys.path` element after having called
index 6414277..fa2d9f0 100644 (file)
@@ -258,7 +258,7 @@ sets all items of a list (actually, any mutable sequence) to a given item::
            if (PyObject_SetItem(target, index, item) < 0) {
                Py_DECREF(index);
                return -1;
-       }
+           }
            Py_DECREF(index);
        }
        return 0;
index 50b83e9..1f0bd17 100644 (file)
@@ -157,7 +157,7 @@ Object Protocol
 
    .. index:: builtin: bytes
 
-   Compute a bytes representation of object *o*.  In 2.x, this is just a alias
+   Compute a bytes representation of object *o*.  In 2.x, this is just an alias
    for :c:func:`PyObject_Str`.
 
 
index 258530b..f6ebcf3 100644 (file)
@@ -140,7 +140,7 @@ or :class:`frozenset` or instances of their subtypes.
    Add *key* to a :class:`set` instance.  Does not apply to :class:`frozenset`
    instances.  Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if
    the *key* is unhashable. Raise a :exc:`MemoryError` if there is no room to grow.
-   Raise a :exc:`SystemError` if *set* is an not an instance of :class:`set` or its
+   Raise a :exc:`SystemError` if *set* is not an instance of :class:`set` or its
    subtype.
 
    .. versionchanged:: 2.6
@@ -158,7 +158,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes.
    error is encountered.  Does not raise :exc:`KeyError` for missing keys.  Raise a
    :exc:`TypeError` if the *key* is unhashable.  Unlike the Python :meth:`~set.discard`
    method, this function does not automatically convert unhashable sets into
-   temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is an not an
+   temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is not an
    instance of :class:`set` or its subtype.
 
 
@@ -166,7 +166,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes.
 
    Return a new reference to an arbitrary object in the *set*, and removes the
    object from the *set*.  Return *NULL* on failure.  Raise :exc:`KeyError` if the
-   set is empty. Raise a :exc:`SystemError` if *set* is an not an instance of
+   set is empty. Raise a :exc:`SystemError` if *set* is not an instance of
    :class:`set` or its subtype.
 
 
index 32dc274..a8baf29 100644 (file)
@@ -88,7 +88,7 @@ called with a non-string parameter.
    | :attr:`%%`        | *n/a*         | The literal % character.       |
    +-------------------+---------------+--------------------------------+
    | :attr:`%c`        | int           | A single character,            |
-   |                   |               | represented as an C int.       |
+   |                   |               | represented as a C int.        |
    +-------------------+---------------+--------------------------------+
    | :attr:`%d`        | int           | Exactly equivalent to          |
    |                   |               | ``printf("%d")``.              |
index c193510..c6ec685 100644 (file)
@@ -69,6 +69,37 @@ These macros are used in the definition of :c:type:`PyObject` and
    expansion varies depending on the definition of :c:macro:`Py_TRACE_REFS`.
 
 
+.. c:macro:: Py_TYPE(o)
+
+   This macro is used to access the :attr:`ob_type` member of a Python object.
+   It expands to::
+
+      (((PyObject*)(o))->ob_type)
+
+   .. versionadded:: 2.6
+
+
+.. c:macro:: Py_REFCNT(o)
+
+   This macro is used to access the :attr:`ob_refcnt` member of a Python
+   object.
+   It expands to::
+
+      (((PyObject*)(o))->ob_refcnt)
+
+   .. versionadded:: 2.6
+
+
+.. c:macro:: Py_SIZE(o)
+
+   This macro is used to access the :attr:`ob_size` member of a Python object.
+   It expands to::
+
+      (((PyVarObject*)(o))->ob_size)
+
+   .. versionadded:: 2.6
+
+
 .. c:macro:: PyObject_HEAD_INIT(type)
 
    This is a macro which expands to initialization values for a new
index 13a2807..85800c5 100644 (file)
@@ -234,7 +234,7 @@ APIs:
 
 .. c:function:: PyObject *PyUnicode_FromString(const char *u)
 
-   Create a Unicode object from an UTF-8 encoded null-terminated char buffer
+   Create a Unicode object from a UTF-8 encoded null-terminated char buffer
    *u*.
 
    .. versionadded:: 2.6
@@ -260,7 +260,7 @@ APIs:
    | :attr:`%%`        | *n/a*               | The literal % character.       |
    +-------------------+---------------------+--------------------------------+
    | :attr:`%c`        | int                 | A single character,            |
-   |                   |                     | represented as an C int.       |
+   |                   |                     | represented as a C int.        |
    +-------------------+---------------------+--------------------------------+
    | :attr:`%d`        | int                 | Exactly equivalent to          |
    |                   |                     | ``printf("%d")``.              |
@@ -347,7 +347,7 @@ APIs:
 
 .. c:function:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
 
-   Coerce an encoded object *obj* to an Unicode object and return a reference with
+   Coerce an encoded object *obj* to a Unicode object and return a reference with
    incremented refcount.
 
    String and other char buffer compatible objects are decoded according to the
@@ -663,7 +663,7 @@ These are the UTF-16 codec APIs:
 
    If *Py_UNICODE_WIDE* is defined, a single :c:type:`Py_UNICODE` value may get
    represented as a surrogate pair. If it is not defined, each :c:type:`Py_UNICODE`
-   values is interpreted as an UCS-2 character.
+   values is interpreted as a UCS-2 character.
 
    Return *NULL* if an exception was raised by the codec.
 
index ffead05..2c271e8 100644 (file)
@@ -135,6 +135,14 @@ latex_appendices = ['glossary', 'about', 'license', 'copyright']
 # Get LaTeX to handle Unicode correctly
 latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''}
 
+
+# Options for Epub output
+# -----------------------
+
+epub_author = 'Python Documentation Authors'
+epub_publisher = 'Python Software Foundation'
+
+
 # Options for the coverage checker
 # --------------------------------
 
index 2b2f887..22d7705 100644 (file)
@@ -4,7 +4,7 @@ Copyright
 
 Python and this documentation is:
 
-Copyright © 2001-2015 Python Software Foundation. All rights reserved.
+Copyright © 2001-2016 Python Software Foundation. All rights reserved.
 
 Copyright © 2000 BeOpen.com. All rights reserved.
 
index 1774d23..82ecd2c 100644 (file)
@@ -35,7 +35,7 @@ Key terms
   repository of open source licensed packages made available for use by
   other Python users
 * the `Python Packaging Authority
-  <https://packaging.python.org/en/latest/future.html>`__ are the group of
+  <https://www.pypa.io/>`__ are the group of
   developers and documentation authors responsible for the maintenance and
   evolution of the standard packaging tools and the associated metadata and
   file format standards. They maintain a variety of tools, documentation
@@ -61,8 +61,8 @@ Key terms
   extensions, to be installed on a system without needing to be built
   locally.
 
-.. _setuptools: https://setuptools.pypa.io/en/latest/setuptools.html
-.. _wheel: http://wheel.readthedocs.org
+.. _setuptools: https://setuptools.readthedocs.io/en/latest/
+.. _wheel: https://wheel.readthedocs.org
 
 Open source licensing and collaboration
 =======================================
@@ -111,7 +111,7 @@ by invoking the ``pip`` module at the command line::
 The Python Packaging User Guide includes more details on the `currently
 recommended tools`_.
 
-.. _currently recommended tools: https://packaging.python.org/en/latest/current.html#packaging-tool-recommendations
+.. _currently recommended tools: https://packaging.python.org/en/latest/current/#packaging-tool-recommendations
 
 Reading the guide
 =================
@@ -124,11 +124,11 @@ involved in creating a project:
 * `Uploading the project to the Python Packaging Index`_
 
 .. _Project structure: \
-   https://packaging.python.org/en/latest/distributing.html#creating-your-own-project
+   https://packaging.python.org/en/latest/distributing/
 .. _Building and packaging the project: \
-   https://packaging.python.org/en/latest/distributing.html#packaging-your-project
+   https://packaging.python.org/en/latest/distributing/#packaging-your-project
 .. _Uploading the project to the Python Packaging Index: \
-   https://packaging.python.org/en/latest/distributing.html#uploading-your-project-to-pypi
+   https://packaging.python.org/en/latest/distributing/#uploading-your-project-to-pypi
 
 
 How do I...?
@@ -160,11 +160,11 @@ Python Packaging User Guide for more information and recommendations.
 .. seealso::
 
    `Python Packaging User Guide: Binary Extensions
-   <https://packaging.python.org/en/latest/extensions.html>`__
+   <https://packaging.python.org/en/latest/extensions>`__
 
 .. other topics:
 
    Once the Development & Deployment part of PPUG is fleshed out, some of
    those sections should be linked from new questions here (most notably,
    we should have a question about avoiding depending on PyPI that links to
-   https://packaging.python.org/en/latest/deployment.html#pypi-mirrors-and-caches)
+   https://packaging.python.org/en/latest/mirrors/)
index c7d399f..67ad3be 100644 (file)
@@ -314,12 +314,12 @@ This module provides the following functions.
 
 .. function:: gen_preprocess_options(macros, include_dirs)
 
-   Generate C pre-processor options (:option:`-D`, :option:`-U`, :option:`-I`) as
+   Generate C pre-processor options (:option:`-D`, :option:`!-U`, :option:`!-I`) as
    used by at least two types of compilers: the typical Unix compiler and Visual
    C++. *macros* is the usual thing, a list of 1- or 2-tuples, where ``(name,)``
-   means undefine (:option:`-U`) macro *name*, and ``(name, value)`` means define
+   means undefine (:option:`!-U`) macro *name*, and ``(name, value)`` means define
    (:option:`-D`) macro *name* to *value*.  *include_dirs* is just a list of
-   directory names to be added to the header file search path (:option:`-I`).
+   directory names to be added to the header file search path (:option:`!-I`).
    Returns a list of command-line options suitable for either Unix compilers or
    Visual C++.
 
@@ -794,7 +794,7 @@ This module provides the :class:`UnixCCompiler` class, a subclass of
 
 * library search directories specified with :option:`-Ldir`
 
-* compile handled by :program:`cc` (or similar) executable with :option:`-c`
+* compile handled by :program:`cc` (or similar) executable with :option:`!-c`
   option: compiles :file:`.c` to :file:`.o`
 
 * link static library handled by :program:`ar` command (possibly with
@@ -832,7 +832,7 @@ selection by :class:`MSVCCompiler`.
 .. module:: distutils.bcppcompiler
 
 
-This module provides :class:`BorlandCCompiler`, an subclass of the abstract
+This module provides :class:`BorlandCCompiler`, a subclass of the abstract
 :class:`CCompiler` class for the Borland C++ compiler.
 
 
@@ -1106,13 +1106,13 @@ other utility module.
    during the build of Python), not the OS version of the current system.
 
    For universal binary builds on Mac OS X the architecture value reflects
-   the univeral binary status instead of the architecture of the current
+   the universal binary status instead of the architecture of the current
    processor. For 32-bit universal binaries the architecture is ``fat``,
    for 64-bit universal binaries the architecture is ``fat64``, and
    for 4-way universal binaries the architecture is ``universal``. Starting
    from Python 2.7 and Python 3.2 the architecture ``fat3`` is used for
    a 3-way universal build (ppc, i386, x86_64) and ``intel`` is used for
-   a univeral build with the i386 and x86_64 architectures
+   a universal build with the i386 and x86_64 architectures
 
    Examples of returned values on Mac OS X:
 
@@ -1816,7 +1816,7 @@ Subclasses of :class:`Command` must define the following methods.
 
    Builds a `Windows Installer`_ (.msi) binary package.
 
-   .. _Windows Installer: http://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx
+   .. _Windows Installer: https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx
 
    In most cases, the ``bdist_msi`` installer is a better choice than the
    ``bdist_wininst`` installer, because it provides better support for
index 7f6eb5d..5e70cba 100644 (file)
@@ -355,7 +355,7 @@ support this option, so the command::
 would create a 64bit installation executable on your 32bit version of Windows.
 
 To cross-compile, you must download the Python source code and cross-compile
-Python itself for the platform you are targetting - it is not possible from a
+Python itself for the platform you are targeting - it is not possible from a
 binary installation of Python (as the .lib etc file for other platforms are
 not included.)  In practice, this means the user of a 32 bit operating
 system will need to use Visual Studio 2008 to open the
index 8faffe6..51d8897 100644 (file)
@@ -51,7 +51,7 @@ option values can be split across multiple lines simply by indenting the
 continuation lines.
 
 You can find out the list of options supported by a particular command with the
-universal :option:`--help` option, e.g. ::
+universal :option:`!--help` option, e.g. ::
 
    > python setup.py --help build_ext
    [...]
index 1f21e14..a697f50 100644 (file)
@@ -1,12 +1,17 @@
 .. _distutils-index:
 
-###############################
-  Distributing Python Modules
-###############################
+##############################################
+  Distributing Python Modules (Legacy version)
+##############################################
 
 :Authors: Greg Ward, Anthony Baxter
 :Email: distutils-sig@python.org
 
+.. seealso::
+
+   :ref:`distributing-index`
+      The up to date module distribution documentations
+
 This document describes the Python Distribution Utilities ("Distutils") from
 the module developer's point of view, describing how to use the Distutils to
 make Python modules and extensions easily available to a wider audience with
index 4b23463..36de32a 100644 (file)
@@ -27,7 +27,7 @@ your system setup; details are given in later chapters.
    avoid writing C extensions and preserve portability to other implementations.
    For example, if your use case is calling C library functions or system calls,
    you should consider using the :mod:`ctypes` module or the `cffi
-   <http://cffi.readthedocs.org>`_ library rather than writing custom C code.
+   <https://cffi.readthedocs.org>`_ library rather than writing custom C code.
    These modules let you write Python code to interface with C code and are more
    portable between implementations of Python than writing and compiling a C
    extension module.
index eb87634..1e523d4 100644 (file)
@@ -169,7 +169,7 @@ where in Python you're forced to write this::
        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 @@ generally less robust than the "while True" solution::
 
    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 @@ objects using the ``for`` statement.  For example, in the current version of
 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...
 
 
 
@@ -431,10 +431,10 @@ much speed.
 There are also several programs which make it easier to intermingle Python and C
 code in various ways to increase performance.  See, for example, `Cython <http://cython.org/>`_ , `Psyco
 <http://psyco.sourceforge.net/>`_, `Pyrex
-<http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_, `PyInline
+<https://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_, `PyInline
 <http://pyinline.sourceforge.net/>`_, `Py2Cmod
 <http://sourceforge.net/projects/py2cmod/>`_, and
-`Weave <http://docs.scipy.org/doc/scipy-dev/reference/tutorial/weave.html>`_.
+`Weave <https://docs.scipy.org/doc/scipy-dev/reference/tutorial/weave.html>`_.
 
 
 How does Python manage memory?
@@ -625,8 +625,10 @@ other structure). ::
    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 @@ it.  For example, here's how to iterate over the keys of a 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?
@@ -723,11 +725,11 @@ languages.  For example::
    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
index 6e9e154..e78da55 100644 (file)
@@ -45,7 +45,7 @@ very little effort, as long as you're running on a machine with an
 x86-compatible processor.
 
 `Cython <http://cython.org>`_ and its relative `Pyrex
-<http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/>`_ are compilers
+<https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/>`_ are compilers
 that accept a slightly modified form of Python and generate the corresponding
 C code.  Pyrex makes it possible to write an extension without having to learn
 Python's C API.
@@ -53,10 +53,10 @@ Python's C API.
 If you need to interface to some C or C++ library for which no Python extension
 currently exists, you can try wrapping the library's data types and functions
 with a tool such as `SWIG <http://www.swig.org>`_.  `SIP
-<http://www.riverbankcomputing.co.uk/software/sip/intro>`__, `CXX
+<https://riverbankcomputing.com/software/sip/intro>`__, `CXX
 <http://cxx.sourceforge.net/>`_ `Boost
 <http://www.boost.org/libs/python/doc/index.html>`_, or `Weave
-<http://docs.scipy.org/doc/scipy-dev/reference/tutorial/weave.html>`_ are also
+<https://scipy.github.io/devdocs/tutorial/weave.html>`_ are also
 alternatives for wrapping C++ libraries.
 
 
index 8c7f538..f88f1de 100644 (file)
@@ -146,10 +146,9 @@ labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled
 2.0cN, and *those* precede 2.0.
 
 You may also find version numbers with a "+" suffix, e.g. "2.2+".  These are
-unreleased versions, built directly from the Subversion trunk.  In practice,
-after a final minor release is made, the Subversion trunk is incremented to the
-next minor version, which becomes the "a0" version,
-e.g. "2.4a0".
+unreleased versions, built directly from the CPython development repository.  In
+practice, after a final minor release is made, the version is incremented to the
+next minor version, which becomes the "a0" version, e.g. "2.4a0".
 
 See also the documentation for :data:`sys.version`, :data:`sys.hexversion`, and
 :data:`sys.version_info`.
@@ -159,7 +158,7 @@ How do I obtain a copy of the Python source?
 --------------------------------------------
 
 The latest Python source distribution is always available from python.org, at
-https://www.python.org/download/.  The latest development sources can be obtained
+https://www.python.org/downloads/.  The latest development sources can be obtained
 via anonymous Mercurial access at https://hg.python.org/cpython.
 
 The source distribution is a gzipped tar file containing the complete C source,
@@ -218,7 +217,7 @@ can be found at https://www.python.org/community/lists/.
 How do I get a beta test version of Python?
 -------------------------------------------
 
-Alpha and beta releases are available from https://www.python.org/download/.  All
+Alpha and beta releases are available from https://www.python.org/downloads/.  All
 releases are announced on the comp.lang.python and comp.lang.python.announce
 newsgroups and on the Python home page at https://www.python.org/; an RSS feed of
 news is available.
@@ -271,9 +270,9 @@ Where in the world is www.python.org located?
 
 The Python project's infrastructure is located all over the world.
 `www.python.org <https://www.python.org>`_ is graciously hosted by `Rackspace
-<http://www.rackspace.com>`_, with CDN caching provided by `Fastly
+<https://www.rackspace.com>`_, with CDN caching provided by `Fastly
 <https://www.fastly.com>`_.  `Upfront Systems
-<http://www.upfrontsystems.co.za>`_ hosts `bugs.python.org
+<http://www.upfrontsystems.co.za/>`_ hosts `bugs.python.org
 <https://bugs.python.org>`_.  Many other Python services like `the Wiki
 <https://wiki.python.org>`_ are hosted by `Oregon State
 University Open Source Lab <https://osuosl.org>`_.
@@ -284,7 +283,7 @@ Why is it called Python?
 
 When he began implementing Python, Guido van Rossum was also reading the
 published scripts from `"Monty Python's Flying Circus"
-<http://en.wikipedia.org/wiki/Monty_Python>`__, a BBC comedy series from the 1970s.  Van Rossum
+<https://en.wikipedia.org/wiki/Monty_Python>`__, a BBC comedy series from the 1970s.  Van Rossum
 thought he needed a name that was short, unique, and slightly mysterious, so he
 decided to call the language Python.
 
@@ -313,7 +312,7 @@ guaranteed that interfaces will remain the same throughout a series of bugfix
 releases.
 
 The latest stable releases can always be found on the `Python download page
-<https://www.python.org/download/>`_.  There are two recommended production-ready
+<https://www.python.org/downloads/>`_.  There are two recommended production-ready
 versions at this point in time, because at the moment there are two branches of
 stable releases: 2.x and 3.x.  Python 3.x may be less useful than 2.x, since
 currently there is more third party software available for Python 2 than for
@@ -345,7 +344,7 @@ different companies and organizations.
 High-profile Python projects include `the Mailman mailing list manager
 <http://www.list.org>`_ and `the Zope application server
 <http://www.zope.org>`_.  Several Linux distributions, most notably `Red Hat
-<http://www.redhat.com>`_, have written part or all of their installer and
+<https://www.redhat.com>`_, have written part or all of their installer and
 system administration software in Python.  Companies that use Python internally
 include Google, Yahoo, and Lucasfilm Ltd.
 
index 44e5908..832c1e0 100644 (file)
@@ -21,13 +21,13 @@ Tkinter
 Standard builds of Python include an object-oriented interface to the Tcl/Tk
 widget set, called Tkinter.  This is probably the easiest to install and use.
 For more info about Tk, including pointers to the source, see the Tcl/Tk home
-page at http://www.tcl.tk.  Tcl/Tk is fully portable to the Mac OS X, Windows,
+page at https://www.tcl.tk.  Tcl/Tk is fully portable to the Mac OS X, Windows,
 and Unix platforms.
 
 wxWidgets
 ---------
 
-wxWidgets (http://www.wxwidgets.org) is a free, portable GUI class
+wxWidgets (https://www.wxwidgets.org) is a free, portable GUI class
 library written in C++ that provides a native look and feel on a
 number of platforms, with Windows, Mac OS X, GTK, X11, all listed as
 current stable targets.  Language bindings are available for a number
@@ -48,14 +48,14 @@ Qt
 ---
 
 There are bindings available for the Qt toolkit (using either `PyQt
-<http://www.riverbankcomputing.co.uk/software/pyqt/intro>`_ or `PySide
-<http://www.pyside.org/>`_) and for KDE (`PyKDE <https://techbase.kde.org/Development/Languages/Python>`__).
+<https://riverbankcomputing.com/software/pyqt/intro>`_ or `PySide
+<https://wiki.qt.io/PySide>`_) and for KDE (`PyKDE4 <https://techbase.kde.org/Languages/Python/Using_PyKDE_4>`__).
 PyQt is currently more mature than PySide, but you must buy a PyQt license from
-`Riverbank Computing <http://www.riverbankcomputing.co.uk/software/pyqt/license>`_
+`Riverbank Computing <https://www.riverbankcomputing.com/commercial/license-faq>`_
 if you want to write proprietary applications.  PySide is free for all applications.
 
 Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses
-are available from `The Qt Company <http://www.qt.io/licensing/>`_.
+are available from `The Qt Company <https://www.qt.io/licensing/>`_.
 
 Gtk+
 ----
index 979df9e..d1b3efb 100644 (file)
@@ -597,7 +597,7 @@ For Win32, POSIX (Linux, BSD, etc.), Jython:
 
 For Unix, see a Usenet post by Mitch Chapman:
 
-   http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
+   https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
 
 
 Why doesn't closing sys.stdout (stdin, stderr) really close it?
@@ -658,20 +658,20 @@ Yes. Here's a simple example that uses httplib::
 
    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 @@ varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
 ``/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")
index 135ae52..9190e1a 100644 (file)
@@ -28,9 +28,9 @@ graphical debugger.
 PythonWin is a Python IDE that includes a GUI debugger based on pdb.  The
 Pythonwin debugger colors breakpoints and has quite a few cool features such as
 debugging non-Pythonwin programs.  Pythonwin is available as part of the `Python
-for Windows Extensions <http://sourceforge.net/projects/pywin32/>`__ project and
+for Windows Extensions <https://sourceforge.net/projects/pywin32/>`__ project and
 as a part of the ActivePython distribution (see
-http://www.activestate.com/activepython\ ).
+https://www.activestate.com/activepython\ ).
 
 `Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
 builder that uses wxWidgets.  It offers visual frame creation and manipulation,
@@ -44,13 +44,13 @@ and the Scintilla editing component.
 Pydb is a version of the standard Python debugger pdb, modified for use with DDD
 (Data Display Debugger), a popular graphical debugger front end.  Pydb can be
 found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
-http://www.gnu.org/software/ddd.
+https://www.gnu.org/software/ddd.
 
 There are a number of commercial Python IDEs that include graphical debuggers.
 They include:
 
-* Wing IDE (http://wingware.com/)
-* Komodo IDE (http://komodoide.com/)
+* Wing IDE (https://wingware.com/)
+* Komodo IDE (https://komodoide.com/)
 * PyCharm (https://www.jetbrains.com/pycharm/)
 
 
@@ -63,13 +63,13 @@ PyChecker is a static analysis tool that finds bugs in Python source code and
 warns about code complexity and style.  You can get PyChecker from
 http://pychecker.sourceforge.net/.
 
-`Pylint <http://www.logilab.org/projects/pylint>`_ is another tool that checks
+`Pylint <https://www.pylint.org/>`_ is another tool that checks
 if a module satisfies a coding standard, and also makes it possible to write
 plug-ins to add a custom feature.  In addition to the bug checking that
 PyChecker performs, Pylint offers some additional features such as checking line
 length, whether variable names are well-formed according to your coding
 standard, whether declared interfaces are fully implemented, and more.
-http://docs.pylint.org/ provides a full list of Pylint's features.
+https://docs.pylint.org/ provides a full list of Pylint's features.
 
 
 How can I create a stand-alone binary from a Python script?
@@ -353,7 +353,7 @@ functions), e.g.::
 
    >>> 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 @@ lambdas, so that they don't rely on the value of the global ``x``::
 
    >>> 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 @@ desired effect in a number of ways.
           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 @@ Essentially, assignment always binds a name to a value; The same is true of
 ``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 @@ How do I iterate over a sequence in reverse order?
 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 @@ order to iterate over.
 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?
@@ -1225,7 +1224,7 @@ How do you remove duplicates from a list?
 
 See the Python Cookbook for a long discussion of many ways to do this:
 
-   http://code.activestate.com/recipes/52560/
+   https://code.activestate.com/recipes/52560/
 
 If you don't mind reordering the list, sort it and then scan from the end of the
 list, deleting duplicates as you go::
@@ -1318,7 +1317,7 @@ use a list comprehension::
    w, h = 2, 3
    A = [[None] * w for i in range(h)]
 
-Or, you can use an extension that provides a matrix datatype; `Numeric Python
+Or, you can use an extension that provides a matrix datatype; `NumPy
 <http://www.numpy.org/>`_ is the best known.
 
 
@@ -1461,40 +1460,11 @@ I want to do a complicated sort: can you do a Schwartzian Transform in Python?
 
 The technique, attributed to Randal Schwartz of the Perl community, sorts the
 elements of a list by a metric which maps each element to its "sort value". In
-Python, just use the ``key`` argument for the ``sort()`` method::
+Python, use the ``key`` argument for the :func:`sort()` function::
 
    Isorted = L[:]
    Isorted.sort(key=lambda s: int(s[10:15]))
 
-The ``key`` argument is new in Python 2.4, for older versions this kind of
-sorting is quite simple to do with list comprehensions.  To sort a list of
-strings by their uppercase values::
-
-  tmp1 = [(x.upper(), x) for x in L]  # Schwartzian transform
-  tmp1.sort()
-  Usorted = [x[1] for x in tmp1]
-
-To sort by the integer value of a subfield extending from positions 10-15 in
-each string::
-
-  tmp2 = [(int(s[10:15]), s) for s in L]  # Schwartzian transform
-  tmp2.sort()
-  Isorted = [x[1] for x in tmp2]
-
-Note that Isorted may also be computed by ::
-
-   def intfield(s):
-       return int(s[10:15])
-
-   def Icmp(s1, s2):
-       return cmp(intfield(s1), intfield(s2))
-
-   Isorted = L[:]
-   Isorted.sort(Icmp)
-
-but since this method calls ``intfield()`` many times for each element of L, it
-is slower than the Schwartzian Transform.
-
 
 How can I sort one list by values from another list?
 ----------------------------------------------------
@@ -1552,7 +1522,7 @@ A method is a function on some object ``x`` that you normally call as
 definition::
 
    class C:
-       def meth (self, arg):
+       def meth(self, arg):
            return arg * 2 + self.attribute
 
 
@@ -1585,9 +1555,9 @@ that does something::
 
    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 +1565,11 @@ call it::
 
    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 +1626,7 @@ How do I call a method defined in a base class from a derived class that overrid
 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
index 27299c8..25c73b8 100644 (file)
@@ -334,5 +334,5 @@ This is a mistake; the extension should be .TGZ.
 
 Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
 able to handle it.  (If your copy of WinZip doesn't, get a newer one from
-http://www.winzip.com.)
+https://www.winzip.com.)
 
index 8b6dbac..cbd1237 100644 (file)
@@ -346,8 +346,8 @@ Glossary
       All of Python's immutable built-in objects are hashable, while no mutable
       containers (such as lists or dictionaries) are.  Objects which are
       instances of user-defined classes are hashable by default; they all
-      compare unequal (except with themselves), and their hash value is their
-      :func:`id`.
+      compare unequal (except with themselves), and their hash value is derived
+      from their :func:`id`.
 
    IDLE
       An Integrated Development Environment for Python.  IDLE is a basic editor
@@ -519,7 +519,8 @@ Glossary
    method resolution order
       Method Resolution Order is the order in which base classes are searched
       for a member during lookup. See `The Python 2.3 Method Resolution Order
-      <https://www.python.org/download/releases/2.3/mro/>`_.
+      <https://www.python.org/download/releases/2.3/mro/>`_ for details of the
+      algorithm used by the Python interpreter since the 2.3 release.
 
    module
       An object that serves as an organizational unit of Python code.  Modules
index f113c98..02bfc70 100644 (file)
@@ -513,7 +513,7 @@ to count the number of occurrences of a specific optional arguments:
 
 * Sadly, our help output isn't very informative on the new ability our script
   has acquired, but that can always be fixed by improving the documentation for
-  out script (e.g. via the ``help`` keyword argument).
+  our script (e.g. via the ``help`` keyword argument).
 
 * That last output exposes a bug in our program.
 
index d7a7086..27e7e6f 100644 (file)
@@ -161,7 +161,7 @@ simple example demonstrates how. ::
 
    #define INITERROR return NULL
 
-   PyObject *
+   PyMODINIT_FUNC
    PyInit_myextension(void)
 
    #else
index 74c1f2a..74f0da5 100644 (file)
@@ -122,13 +122,12 @@ raises an uncaught exception.  Keys are no longer echoed to the screen when
 you type them, for example, which makes using the shell difficult.
 
 In Python you can avoid these complications and make debugging much easier by
-importing the module :mod:`curses.wrapper`.  It supplies a :func:`wrapper`
-function that takes a callable.  It does the initializations described above,
-and also initializes colors if color support is present.  It then runs your
-provided callable and finally deinitializes appropriately.  The callable is
-called inside a try-catch clause which catches exceptions, performs curses
-deinitialization, and then passes the exception upwards.  Thus, your terminal
-won't be left in a funny state on exception.
+importing the :func:`curses.wrapper` function.  It takes a callable and does
+the initializations described above, also initializing colors if color support
+is present.  It then runs your provided callable and finally deinitializes
+appropriately.  The callable is called inside a try-catch clause which catches
+exceptions, performs curses deinitialization, and then passes the exception
+upwards.  Thus, your terminal won't be left in a funny state on exception.
 
 
 Windows and Pads
index e2359d9..8f98c42 100644 (file)
@@ -108,7 +108,7 @@ like::
         "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 @@ descriptor is useful for monitoring just a few chosen attributes::
             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 @@ this::
 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 @@ Since staticmethods return the underlying function with no changes, the example
 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 @@ Using the non-data descriptor protocol, a pure Python version of
 :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 @@ Using the non-data descriptor protocol, a pure Python version of
 :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
 
index e12e67b..ee9a5f6 100644 (file)
@@ -331,7 +331,7 @@ substring.
 
 List comprehensions and generator expressions (short form: "listcomps" and
 "genexps") are a concise notation for such operations, borrowed from the
-functional programming language Haskell (http://www.haskell.org/).  You can strip
+functional programming language Haskell (https://www.haskell.org/).  You can strip
 all the whitespace from a stream of strings with the following code::
 
     line_list = ['  line 1\n', 'line 2  \n', ...]
@@ -394,14 +394,14 @@ equivalent to the following Python code::
             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
@@ -1144,7 +1144,7 @@ General
 
 **Structure and Interpretation of Computer Programs**, by Harold Abelson and
 Gerald Jay Sussman with Julie Sussman.  Full text at
-http://mitpress.mit.edu/sicp/.  In this classic textbook of computer science,
+https://mitpress.mit.edu/sicp/.  In this classic textbook of computer science,
 chapters 2 and 3 discuss the use of sequences and streams to organize the data
 flow inside a program.  The book uses Scheme for its examples, but many of the
 design approaches described in these chapters are applicable to functional-style
@@ -1153,12 +1153,12 @@ Python code.
 http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
 programming that uses Java examples and has a lengthy historical introduction.
 
-http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
+https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
 describing functional programming.
 
-http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
+https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
 
-http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
+https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
 
 Python-specific
 ---------------
@@ -1171,9 +1171,9 @@ Text Processing".
 Mertz also wrote a 3-part series of articles on functional programming
 for IBM's DeveloperWorks site; see
 
-`part 1 <http://www.ibm.com/developerworks/linux/library/l-prog/index.html>`__,
-`part 2 <http://www.ibm.com/developerworks/linux/library/l-prog2/index.html>`__, and
-`part 3 <http://www.ibm.com/developerworks/linux/library/l-prog3/index.html>`__,
+`part 1 <https://www.ibm.com/developerworks/linux/library/l-prog/index.html>`__,
+`part 2 <https://www.ibm.com/developerworks/linux/library/l-prog2/index.html>`__, and
+`part 3 <https://www.ibm.com/developerworks/linux/library/l-prog3/index.html>`__,
 
 
 Python documentation
index 45fd779..074c396 100644 (file)
@@ -63,6 +63,7 @@ Here is the auxiliary module::
         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
@@ -94,6 +95,61 @@ The output looks like this::
     2005-03-23 23:47:11,673 - spam_application - INFO -
        done with auxiliary_module.some_function()
 
+Logging from multiple threads
+-----------------------------
+
+Logging from multiple threads requires no special effort. The following example
+shows logging from the main (initIal) thread and another thread::
+
+    import logging
+    import threading
+    import time
+
+    def worker(arg):
+        while not arg['stop']:
+            logging.debug('Hi from myfunc')
+            time.sleep(0.5)
+
+    def main():
+        logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
+        info = {'stop': False}
+        thread = threading.Thread(target=worker, args=(info,))
+        thread.start()
+        while True:
+            try:
+                logging.debug('Hello from main')
+                time.sleep(0.75)
+            except KeyboardInterrupt:
+                info['stop'] = True
+                break
+        thread.join()
+
+    if __name__ == '__main__':
+        main()
+
+When run, the script should print something like the following::
+
+     0 Thread-1 Hi from myfunc
+     3 MainThread Hello from main
+   505 Thread-1 Hi from myfunc
+   755 MainThread Hello from main
+  1007 Thread-1 Hi from myfunc
+  1507 MainThread Hello from main
+  1508 Thread-1 Hi from myfunc
+  2010 Thread-1 Hi from myfunc
+  2258 MainThread Hello from main
+  2512 Thread-1 Hi from myfunc
+  3009 MainThread Hello from main
+  3013 Thread-1 Hi from myfunc
+  3515 Thread-1 Hi from myfunc
+  3761 MainThread Hello from main
+  4017 Thread-1 Hi from myfunc
+  4513 MainThread Hello from main
+  4518 Thread-1 Hi from myfunc
+
+This shows the logging output interspersed as one might expect. This approach
+works for more threads than shown here, of course.
+
 Multiple handlers and formatters
 --------------------------------
 
@@ -530,21 +586,21 @@ script::
             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::
 
@@ -650,7 +706,7 @@ An example dictionary-based configuration
 -----------------------------------------
 
 Below is an example of a logging configuration dictionary - it's taken from
-the `documentation on the Django project <https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging>`_.
+the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_.
 This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::
 
     LOGGING = {
@@ -706,17 +762,17 @@ This dictionary is passed to :func:`~config.dictConfig` to put the configuration
     }
 
 For more information about this configuration, you can see the `relevant
-section <https://docs.djangoproject.com/en/1.6/topics/logging/#configuring-logging>`_
+section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_
 of the Django documentation.
 
 Inserting a BOM into messages sent to a SysLogHandler
 -----------------------------------------------------
 
-`RFC 5424 <http://tools.ietf.org/html/rfc5424>`_ requires that a
+`RFC 5424 <https://tools.ietf.org/html/rfc5424>`_ requires that a
 Unicode message be sent to a syslog daemon as a set of bytes which have the
 following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
 Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant
-section of the specification <http://tools.ietf.org/html/rfc5424#section-6>`_.)
+section of the specification <https://tools.ietf.org/html/rfc5424#section-6>`_.)
 
 In Python 2.6 and 2.7, code was added to
 :class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
@@ -1192,7 +1248,7 @@ flushing behavior.
 
 The example script has a simple function, ``foo``, which just cycles through
 all the logging levels, writing to ``sys.stderr`` to say what level it's about
-to log at, and then actually logging a message that that level. You can pass a
+to log at, and then actually logging a message at that level. You can pass a
 parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
 otherwise, it only logs at DEBUG, INFO and WARNING levels.
 
@@ -1370,3 +1426,105 @@ When this script is run, it should print something like::
 
 showing how the time is formatted both as local time and UTC, one for each
 handler.
+
+
+.. _context-manager:
+
+Using a context manager for selective logging
+---------------------------------------------
+
+There are times when it would be useful to temporarily change the logging
+configuration and revert it back after doing something. For this, a context
+manager is the most obvious way of saving and restoring the logging context.
+Here is a simple example of such a context manager, which allows you to
+optionally change the logging level and add a logging handler purely in the
+scope of the context manager::
+
+    import logging
+    import sys
+
+    class LoggingContext(object):
+        def __init__(self, logger, level=None, handler=None, close=True):
+            self.logger = logger
+            self.level = level
+            self.handler = handler
+            self.close = close
+
+        def __enter__(self):
+            if self.level is not None:
+                self.old_level = self.logger.level
+                self.logger.setLevel(self.level)
+            if self.handler:
+                self.logger.addHandler(self.handler)
+
+        def __exit__(self, et, ev, tb):
+            if self.level is not None:
+                self.logger.setLevel(self.old_level)
+            if self.handler:
+                self.logger.removeHandler(self.handler)
+            if self.handler and self.close:
+                self.handler.close()
+            # implicit return of None => don't swallow exceptions
+
+If you specify a level value, the logger's level is set to that value in the
+scope of the with block covered by the context manager. If you specify a
+handler, it is added to the logger on entry to the block and removed on exit
+from the block. You can also ask the manager to close the handler for you on
+block exit - you could do this if you don't need the handler any more.
+
+To illustrate how it works, we can add the following block of code to the
+above::
+
+    if __name__ == '__main__':
+        logger = logging.getLogger('foo')
+        logger.addHandler(logging.StreamHandler())
+        logger.setLevel(logging.INFO)
+        logger.info('1. This should appear just once on stderr.')
+        logger.debug('2. This should not appear.')
+        with LoggingContext(logger, level=logging.DEBUG):
+            logger.debug('3. This should appear once on stderr.')
+        logger.debug('4. This should not appear.')
+        h = logging.StreamHandler(sys.stdout)
+        with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
+            logger.debug('5. This should appear twice - once on stderr and once on stdout.')
+        logger.info('6. This should appear just once on stderr.')
+        logger.debug('7. This should not appear.')
+
+We initially set the logger's level to ``INFO``, so message #1 appears and
+message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the
+following ``with`` block, and so message #3 appears. After the block exits, the
+logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the
+next ``with`` block, we set the level to ``DEBUG`` again but also add a handler
+writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once
+via ``stderr`` and once via ``stdout``). After the ``with`` statement's
+completion, the status is as it was before so message #6 appears (like message
+#1) whereas message #7 doesn't (just like message #2).
+
+If we run the resulting script, the result is as follows::
+
+    $ python logctx.py
+    1. This should appear just once on stderr.
+    3. This should appear once on stderr.
+    5. This should appear twice - once on stderr and once on stdout.
+    5. This should appear twice - once on stderr and once on stdout.
+    6. This should appear just once on stderr.
+
+If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
+which is the only message written to ``stdout``::
+
+    $ python logctx.py 2>/dev/null
+    5. This should appear twice - once on stderr and once on stdout.
+
+Once again, but piping ``stdout`` to ``/dev/null``, we get::
+
+    $ python logctx.py >/dev/null
+    1. This should appear just once on stderr.
+    3. This should appear once on stderr.
+    5. This should appear twice - once on stderr and once on stdout.
+    6. This should appear just once on stderr.
+
+In this case, the message #5 printed to ``stdout`` doesn't appear, as expected.
+
+Of course, the approach described here can be generalised, for example to attach
+logging filters temporarily. Note that the above code works in Python 2 as well
+as Python 3.
index fdb6c53..5b431f0 100644 (file)
@@ -103,8 +103,8 @@ A simple example
 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::
 
@@ -310,7 +310,7 @@ favourite beverage and carry on.
 If your logging needs are simple, then use the above examples to incorporate
 logging into your own scripts, and if you run into problems or don't
 understand something, please post a question on the comp.lang.python Usenet
-group (available at http://groups.google.com/group/comp.lang.python) and you
+group (available at https://groups.google.com/group/comp.lang.python) and you
 should receive help before too long.
 
 Still here? You can carry on reading the next few sections, which provide a
index bd80dfd..59b283a 100644 (file)
@@ -243,8 +243,8 @@ bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for
 binary reading).  Under Python 3, binary files and text files are clearly
 distinct and mutually incompatible; see the :mod:`io` module for details.
 Therefore, you **must** make a decision of whether a file will be used for
-binary access (allowing to read and/or write binary data) or text access
-(allowing to read and/or write text data). You should also use :func:`io.open`
+binary access (allowing binary data to be read and/or written) or text access
+(allowing text data to be read and/or written). You should also use :func:`io.open`
 for opening files instead of the built-in :func:`open` function as the :mod:`io`
 module is consistent from Python 2 to 3 while the built-in :func:`open` function
 is not (in Python 3 it's actually :func:`io.open`).
@@ -346,7 +346,7 @@ your tests under multiple Python interpreters is tox_. You can then integrate
 tox with your continuous integration system so that you never accidentally break
 Python 2 or 3 support.
 
-You may also want to use use the ``-bb`` flag with the Python 3 interpreter to
+You may also want to use the ``-bb`` flag with the Python 3 interpreter to
 trigger an exception when you are comparing bytes to strings. Usually it's
 simply ``False``, but if you made a mistake in your separation of text/binary
 data handling you may be accidentally comparing text and binary data. This flag
@@ -379,10 +379,10 @@ supported by Python 2. You should also update the classifiers in your
 .. _cheat sheet: http://python-future.org/compatible_idioms.html
 .. _coverage.py: https://pypi.python.org/pypi/coverage
 .. _Futurize: http://python-future.org/automatic_conversion.html
-.. _Modernize: http://python-modernize.readthedocs.org/en/latest/
+.. _Modernize: https://python-modernize.readthedocs.org/en/latest/
 .. _Porting to Python 3: http://python3porting.com/
 .. _Pylint: https://pypi.python.org/pypi/pylint
-.. _Python 3 Q & A: http://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html
+.. _Python 3 Q & A: https://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html
 
 .. _python-future: http://python-future.org/
 .. _python-porting: https://mail.python.org/mailman/listinfo/python-porting
index 2f552e3..2c95fb4 100644 (file)
@@ -172,7 +172,7 @@ that limit.
 Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching
 engine will try to repeat it as many times as possible. If later portions of the
 pattern don't match, the matching engine will then back up and try again with
-few repetitions.
+fewer repetitions.
 
 A step-by-step example will make this more obvious.  Let's consider the
 expression ``a[bcd]*b``.  This matches the letter ``'a'``, zero or more letters
@@ -1015,17 +1015,18 @@ confusing.
 
 A negative lookahead cuts through all this confusion:
 
-``.*[.](?!bat$).*$``  The negative lookahead means: if the expression ``bat``
+``.*[.](?!bat$)[^.]*$``  The negative lookahead means: if the expression ``bat``
 doesn't match at this point, try the rest of the pattern; if ``bat$`` does
 match, the whole pattern will fail.  The trailing ``$`` is required to ensure
 that something like ``sample.batch``, where the extension only starts with
-``bat``, will be allowed.
+``bat``, will be allowed.  The ``[^.]*`` makes sure that the pattern works
+when there are multiple dots in the filename.
 
 Excluding another filename extension is now easy; simply add it as an
 alternative inside the assertion.  The following pattern excludes filenames that
 end in either ``bat`` or ``exe``:
 
-``.*[.](?!bat$|exe$).*$``
+``.*[.](?!bat$|exe$)[^.]*$``
 
 
 Modifying Strings
@@ -1126,19 +1127,19 @@ which can be either a string or a function, and the string to be processed.
 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.
index f8ac348..2b08141 100644 (file)
@@ -237,7 +237,7 @@ messages to be sent back to back (without some kind of reply), and you pass
 following message. You'll need to put that aside and hold onto it, until it's
 needed.
 
-Prefixing the message with it's length (say, as 5 numeric characters) gets more
+Prefixing the message with its length (say, as 5 numeric characters) gets more
 complex, because (believe it or not), you may not get all 5 characters in one
 ``recv``. In playing around, you'll get away with it; but in high network loads,
 your code will very quickly break unless you use two ``recv`` loops - the first
index 56b65b0..675ed97 100644 (file)
@@ -137,7 +137,7 @@ Sort Stability and Complex Sorts
 ================================
 
 Starting with Python 2.2, sorts are guaranteed to be `stable
-<http://en.wikipedia.org/wiki/Sorting_algorithm#Stability>`_\. That means that
+<https://en.wikipedia.org/wiki/Sorting_algorithm#Stability>`_\. That means that
 when multiple records have the same key, their original order is preserved.
 
     >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
@@ -155,7 +155,7 @@ ascending *age*, do the *age* sort first and then sort again using *grade*:
     >>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 
-The `Timsort <http://en.wikipedia.org/wiki/Timsort>`_ algorithm used in Python
+The `Timsort <https://en.wikipedia.org/wiki/Timsort>`_ algorithm used in Python
 does multiple sorts efficiently because it can take advantage of any ordering
 already present in a dataset.
 
@@ -194,7 +194,7 @@ decorated list, but including it gives two benefits:
   directly.
 
 Another name for this idiom is
-`Schwartzian transform <http://en.wikipedia.org/wiki/Schwartzian_transform>`_\,
+`Schwartzian transform <https://en.wikipedia.org/wiki/Schwartzian_transform>`_\,
 after Randal L. Schwartz, who popularized it among Perl programmers.
 
 For large lists and lists where the comparison information is expensive to
@@ -274,7 +274,11 @@ Odd and Ends
   twice:
 
     >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
-    >>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))
+    >>> standard_way = sorted(data, key=itemgetter(0), reverse=True)
+    >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0))))
+    >>> assert standard_way == double_reversed
+    >>> standard_way
+    [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]
 
 * To create a standard sort order for a class, just add the appropriate rich
   comparison methods:
index 8138a09..afd89c7 100644 (file)
@@ -211,7 +211,7 @@ origin and development of Unicode.
 
 To help understand the standard, Jukka Korpela has written an introductory guide
 to reading the Unicode character tables, available at
-<http://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
+<https://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
 
 Another good introductory article was written by Joel Spolsky
 <http://www.joelonsoftware.com/articles/Unicode.html>.
index cccbc54..6bb06d4 100644 (file)
@@ -1,3 +1,5 @@
+.. _urllib-howto:
+
 ************************************************
   HOWTO Fetch Internet Resources Using urllib2
 ************************************************
@@ -6,7 +8,7 @@
 
 .. note::
 
-    There is an French translation of an earlier revision of this
+    There is a French translation of an earlier revision of this
     HOWTO, available at `urllib2 - Le Manuel manquant
     <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_.
 
@@ -55,7 +57,7 @@ The simplest way to use urllib2 is as follows::
     html = response.read()
 
 Many uses of urllib2 will be that simple (note that instead of an 'http:' URL we
-could have used an URL starting with 'ftp:', 'file:', etc.).  However, it's the
+could have used a URL starting with 'ftp:', 'file:', etc.).  However, it's the
 purpose of this tutorial to explain the more complicated cases, concentrating on
 HTTP.
 
@@ -112,7 +114,7 @@ argument. The encoding is done using a function from the ``urllib`` library
 
 Note that other encodings are sometimes required (e.g. for file upload from HTML
 forms - see `HTML Specification, Form Submission
-<http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
+<https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
 details).
 
 If you do not pass the ``data`` argument, urllib2 uses a **GET** request. One
@@ -165,10 +167,10 @@ Explorer [#]_. ::
 
     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)
@@ -388,7 +390,7 @@ fetched, particularly the headers sent by the server. It is currently an
 ``httplib.HTTPMessage`` instance.
 
 Typical headers include 'Content-length', 'Content-type', and so on. See the
-`Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_
+`Quick Reference to HTTP Headers <https://www.cs.tut.fi/~jkorpela/http.html>`_
 for a useful listing of HTTP headers with brief explanations of their meaning
 and use.
 
@@ -499,7 +501,7 @@ component and the hostname and optionally the port number)
 e.g. "http://example.com/" *or* an "authority" (i.e. the hostname,
 optionally including the port number) e.g. "example.com" or "example.com:8080"
 (the latter example includes a port number).  The authority, if present, must
-NOT contain the "userinfo" component - for example "joe@password:example.com" is
+NOT contain the "userinfo" component - for example "joe:password@example.com" is
 not correct.
 
 
@@ -573,5 +575,5 @@ This document was reviewed and revised by John Lee.
        scripts with a localhost server, I have to prevent urllib2 from using
        the proxy.
 .. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
-       <http://code.activestate.com/recipes/456195/>`_.
+       <https://code.activestate.com/recipes/456195/>`_.
 
index d8a0562..5d401e8 100644 (file)
@@ -267,7 +267,7 @@ Setting up FastCGI
 Each web server requires a specific module.
 
 * Apache has both `mod_fastcgi <http://www.fastcgi.com/drupal/>`_ and `mod_fcgid
-  <http://httpd.apache.org/mod_fcgid/>`_.  ``mod_fastcgi`` is the original one, but it
+  <https://httpd.apache.org/mod_fcgid/>`_.  ``mod_fastcgi`` is the original one, but it
   has some licensing issues, which is why it is sometimes considered non-free.
   ``mod_fcgid`` is a smaller, compatible alternative.  One of these modules needs
   to be loaded by Apache.
@@ -277,7 +277,7 @@ Each web server requires a specific module.
   `SCGI module <http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModSCGI>`_.
 
 * `nginx <http://nginx.org/>`_ also supports `FastCGI
-  <http://wiki.nginx.org/NginxSimplePythonFCGI>`_.
+  <https://www.nginx.com/resources/wiki/start/topics/examples/simplepythonfcgi/>`_.
 
 Once you have installed and configured the module, you can test it with the
 following WSGI-application::
@@ -295,7 +295,7 @@ following WSGI-application::
         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()
@@ -306,8 +306,8 @@ FastCGI access.
 
 .. seealso::
 
-   There is some documentation on `setting up Django with FastCGI
-   <https://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/>`_, most of
+   There is some documentation on `setting up Django with WSGI
+   <https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/>`_, most of
    which can be reused for other WSGI-compliant frameworks and libraries.
    Only the ``manage.py`` part has to be changed, the example used here can be
    used instead.  Django does more or less the exact same thing.
@@ -357,7 +357,7 @@ testing.
 
 A really great WSGI feature is middleware.  Middleware is a layer around your
 program which can add various functionality to it.  There is quite a bit of
-`middleware <http://www.wsgi.org/en/latest/libraries.html>`_ already
+`middleware <https://wsgi.readthedocs.org/en/latest/libraries.html>`_ already
 available.  For example, instead of writing your own session management (HTTP
 is a stateless protocol, so to associate multiple HTTP requests with a single
 user your application must create and manage such state via a session), you can
@@ -378,7 +378,7 @@ WSGI Servers
 The code that is used to connect to various low level gateways like CGI or
 mod_python is called a *WSGI server*.  One of these servers is ``flup``, which
 supports FastCGI and SCGI, as well as `AJP
-<http://en.wikipedia.org/wiki/Apache_JServ_Protocol>`_.  Some of these servers
+<https://en.wikipedia.org/wiki/Apache_JServ_Protocol>`_.  Some of these servers
 are written in Python, as ``flup`` is, but there also exist others which are
 written in C and can be used as drop-in replacements.
 
@@ -389,8 +389,8 @@ compared with other web technologies.
 .. seealso::
 
    A good overview of WSGI-related code can be found in the `WSGI homepage
-   <http://www.wsgi.org/en/latest/index.html>`_, which contains an extensive list of `WSGI servers
-   <http://www.wsgi.org/en/latest/servers.html>`_ which can be used by *any* application
+   <https://wsgi.readthedocs.org/>`_, which contains an extensive list of `WSGI servers
+   <https://wsgi.readthedocs.org/en/latest/servers.html>`_ which can be used by *any* application
    supporting WSGI.
 
    You might be interested in some WSGI-supporting modules already contained in
@@ -407,7 +407,7 @@ an application that's been around for a while, which was written in
 Python without using WSGI.
 
 One of the most widely used wiki software packages is `MoinMoin
-<http://moinmo.in/>`_.  It was created in 2000, so it predates WSGI by about
+<https://moinmo.in/>`_.  It was created in 2000, so it predates WSGI by about
 three years.  Older versions needed separate code to run on CGI, mod_python,
 FastCGI and standalone.
 
@@ -459,7 +459,7 @@ maintainable web sites.
 .. seealso::
 
    The English Wikipedia has an article about the `Model-View-Controller pattern
-   <http://en.wikipedia.org/wiki/Model-view-controller>`_.  It includes a long
+   <https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller>`_.  It includes a long
    list of web frameworks for various programming languages.
 
 
@@ -547,10 +547,10 @@ module, and which uses only one file.  It has no other dependencies.  For
 smaller sites SQLite is just enough.
 
 Relational databases are *queried* using a language called `SQL
-<http://en.wikipedia.org/wiki/SQL>`_.  Python programmers in general do not
+<https://en.wikipedia.org/wiki/SQL>`_.  Python programmers in general do not
 like SQL too much, as they prefer to work with objects.  It is possible to save
 Python objects into a database using a technology called `ORM
-<http://en.wikipedia.org/wiki/Object-relational_mapping>`_ (Object Relational
+<https://en.wikipedia.org/wiki/Object-relational_mapping>`_ (Object Relational
 Mapping).  ORM translates all object-oriented access into SQL code under the
 hood, so the developer does not need to think about it.  Most `frameworks`_ use
 ORMs, and it works quite well.
@@ -583,13 +583,13 @@ alternate storage mechanism.
      helps with choosing a method for saving data
 
    * `SQLAlchemy <http://www.sqlalchemy.org/>`_, the most powerful OR-Mapper
-     for Python, and `Elixir <http://elixir.ematia.de/>`_, which makes
+     for Python, and `Elixir <https://pypi.python.org/pypi/Elixir>`_, which makes
      SQLAlchemy easier to use
 
    * `SQLObject <http://www.sqlobject.org/>`_, another popular OR-Mapper
 
    * `ZODB <https://launchpad.net/zodb>`_ and `Durus
-     <http://www.mems-exchange.org/software/durus/>`_, two object oriented
+     <https://www.mems-exchange.org/software/>`_, two object oriented
      databases
 
 
@@ -675,10 +675,10 @@ experience.  TurboGears gives the user flexibility in choosing components. For
 example the ORM and template engine can be changed to use packages different
 from those used by default.
 
-The documentation can be found in the `TurboGears wiki
-<http://docs.turbogears.org/>`_, where links to screencasts can be found.
+The documentation can be found in the `TurboGears documentation
+<https://turbogears.readthedocs.org/>`_, where links to screencasts can be found.
 TurboGears has also an active user community which can respond to most related
-questions.  There is also a `TurboGears book <http://turbogearsbook.com/>`_
+questions.  There is also a `TurboGears book <http://turbogears.org/1.0/docs/TGBooks.html>`_
 published, which is a good starting point.
 
 The newest version of TurboGears, version 2.0, moves even further in direction
index 7f3560a..029aff5 100644 (file)
@@ -2,14 +2,19 @@
 
 .. _install-index:
 
-*****************************
-  Installing Python Modules
-*****************************
+********************************************
+  Installing Python Modules (Legacy version)
+********************************************
 
 :Author: Greg Ward
 
 .. TODO: Fill in XXX comments
 
+.. seealso::
+
+   :ref:`installing-index`
+      The up to date module installation documentations
+
 .. The audience for this document includes people who don't know anything
    about Python and aren't about to learn the language just in order to
    install and maintain it for their users, i.e. system administrators.
@@ -862,12 +867,12 @@ config file will apply.  (Or if other commands that derive values from it are
 run, they will use the values in the config file.)
 
 You can find out the complete list of options for any command using the
-:option:`--help` option, e.g.::
+:option:`!--help` option, e.g.::
 
    python setup.py build --help
 
 and you can find out the complete list of global options by using
-:option:`--help` without a command::
+:option:`!--help` without a command::
 
    python setup.py --help
 
@@ -924,7 +929,7 @@ Let's examine each of the fields in turn.
   to be in Objective C.
 
 * *cpparg* is an argument for the C preprocessor,  and is anything starting with
-  :option:`-I`, :option:`-D`, :option:`-U` or :option:`-C`.
+  :option:`!-I`, :option:`-D`, :option:`!-U` or :option:`-C`.
 
 * *library* is anything ending in :file:`.a` or beginning with :option:`-l` or
   :option:`-L`.
@@ -1009,7 +1014,7 @@ section :ref:`inst-config-files`.)
 
 .. seealso::
 
-   `C++Builder Compiler <http://www.embarcadero.com/downloads>`_
+   `C++Builder Compiler <https://www.embarcadero.com/products>`_
       Information about the free C++ compiler from Borland, including links to the
       download pages.
 
@@ -1052,7 +1057,7 @@ These compilers require some special libraries.  This task is more complex than
 for Borland's C++, because there is no program to convert the library.  First
 you have to create a list of symbols which the Python DLL exports. (You can find
 a good program for this task at
-http://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/).
+https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/).
 
 .. I don't understand what the next line means. --amk
 .. (inclusive the references on data structures.)
@@ -1090,7 +1095,7 @@ normal libraries do.
 .. [#] This also means you could replace all existing COFF-libraries with OMF-libraries
    of the same name.
 
-.. [#] Check http://www.sourceware.org/cygwin/ and http://www.mingw.org/ for more
+.. [#] Check https://www.sourceware.org/cygwin/ and http://www.mingw.org/ for more
    information
 
 .. [#] Then you have no POSIX emulation available, but you also don't need
index f01b084..e5b3165 100644 (file)
@@ -43,7 +43,7 @@ Key terms
   repository of open source licensed packages made available for use by
   other Python users
 * the `Python Packaging Authority
-  <https://packaging.python.org/en/latest/future.html>`__ are the group of
+  <https://www.pypa.io/en/latest/>`__ are the group of
   developers and documentation authors responsible for the maintenance and
   evolution of the standard packaging tools and the associated metadata and
   file format standards. They maintain a variety of tools, documentation
@@ -82,10 +82,12 @@ dependencies from the Python Packaging Index::
    Python.
 
 It's also possible to specify an exact or minimum version directly on the
-command line::
+command line. When using comparator operators such as ``>``, ``<`` or some other
+special character which get interpreted by shell, the package name and the
+version should be enclosed within double quotes::
 
     python -m pip install SomePackage==1.0.4    # specific version
-    python -m pip install 'SomePackage>=1.0.4'  # minimum version
+    python -m pip install "SomePackage>=1.0.4"  # minimum version
 
 Normally, if a suitable module is already installed, attempting to install
 it again will have no effect. Upgrading existing modules must be requested
@@ -99,7 +101,7 @@ found in the `Python Packaging User Guide <https://packaging.python.org>`__.
 .. seealso::
 
     `Python Packaging User Guide: Installing Python Distribution Packages
-    <https://packaging.python.org/en/latest/installing.html#installing-python-distribution-packages>`__
+    <https://packaging.python.org/en/latest/installing/>`__
 
 
 How do I ...?
@@ -116,8 +118,8 @@ User Guide.
 
 .. seealso::
 
-   `Python Packaging User Guide: Setup for Installing Distribution Packages
-   <https://packaging.python.org/en/latest/installing.html#setup-for-installing-distribution-packages>`__
+   `Python Packaging User Guide: Requirements for Installing Packages
+   <https://packaging.python.org/en/latest/installing/#requirements-for-installing-packages>`__
 
 
 .. installing-per-user-installation:
@@ -136,13 +138,13 @@ A number of scientific Python packages have complex binary dependencies, and
 aren't currently easy to install using ``pip`` directly. At this point in
 time, it will often be easier for users to install these packages by
 `other means
-<https://packaging.python.org/en/latest/science.html>`__
+<https://packaging.python.org/en/latest/science/>`__
 rather than attempting to install them with ``pip``.
 
 .. seealso::
 
    `Python Packaging User Guide: Installing Scientific Packages
-   <https://packaging.python.org/en/latest/science.html>`__
+   <https://packaging.python.org/en/latest/science/>`__
 
 
 ... work with multiple versions of Python installed in parallel?
@@ -172,7 +174,7 @@ switch::
    Once the Development & Deployment part of PPUG is fleshed out, some of
    those sections should be linked from new questions here (most notably,
    we should have a question about avoiding depending on PyPI that links to
-   https://packaging.python.org/en/latest/deployment.html#pypi-mirrors-and-caches)
+   https://packaging.python.org/en/latest/mirrors/)
 
 
 Common installation issues
@@ -205,11 +207,11 @@ as users are more regularly able to install pre-built extensions rather
 than needing to build them themselves.
 
 Some of the solutions for installing `scientific software
-<https://packaging.python.org/en/latest/science.html>`__
+<https://packaging.python.org/en/latest/science/>`__
 that is not yet available as pre-built ``wheel`` files may also help with
 obtaining other binary extensions without needing to build them locally.
 
 .. seealso::
 
    `Python Packaging User Guide: Binary Extensions
-   <https://packaging.python.org/en/latest/extensions.html>`__
+   <https://packaging.python.org/en/latest/extensions/>`__
index 7ebc208..9f59dda 100644 (file)
@@ -56,7 +56,7 @@ Comments and exact indentation are preserved throughout the translation process.
 
 By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`.  The
 :option:`-l` flag lists all available fixers.  An explicit set of fixers to run
-can be given with :option:`-f`.  Likewise the :option:`-x` explicitly disables a
+can be given with :option:`-f`.  Likewise the :option:`!-x` explicitly disables a
 fixer.  The following example runs only the ``imports`` and ``has_key`` fixers::
 
    $ 2to3 -f imports -f has_key example.py
@@ -78,12 +78,12 @@ but 2to3 cannot fix automatically.  In this case, 2to3 will print a warning
 beneath the diff for a file.  You should address the warning in order to have
 compliant 3.x code.
 
-2to3 can also refactor doctests.  To enable this mode, use the :option:`-d`
+2to3 can also refactor doctests.  To enable this mode, use the :option:`!-d`
 flag.  Note that *only* doctests will be refactored.  This also doesn't require
 the module to be valid Python.  For example, doctest like examples in a reST
 document could also be refactored with this option.
 
-The :option:`-v` option enables output of more information on the translation
+The :option:`!-v` option enables output of more information on the translation
 process.
 
 Since some print statements can be parsed as function calls or statements, 2to3
@@ -102,14 +102,14 @@ when not overwriting the input files.
 .. versionadded:: 2.7.3
    The :option:`-o` option was added.
 
-The :option:`-W` or :option:`--write-unchanged-files` flag tells 2to3 to always
+The :option:`!-W` or :option:`--write-unchanged-files` flag tells 2to3 to always
 write output files even if no changes were required to the file.  This is most
 useful with :option:`-o` so that an entire Python source tree is copied with
 translation from one directory to another.
 This option implies the :option:`-w` flag as it would not make sense otherwise.
 
 .. versionadded:: 2.7.3
-   The :option:`-W` flag was added.
+   The :option:`!-W` flag was added.
 
 The :option:`--add-suffix` option specifies a string to append to all output
 filenames.  The :option:`-n` flag is required when specifying this as backups
index 804af8a..3d9042c 100644 (file)
@@ -577,7 +577,7 @@ For more information, see `Registry Key Security and Access
 64-bit Specific
 ***************
 
-For more information, see `Accesing an Alternate Registry View
+For more information, see `Accessing an Alternate Registry View
 <http://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx>`__.
 
 .. data:: KEY_WOW64_64KEY
index 181291f..1dfebc2 100644 (file)
@@ -35,10 +35,10 @@ produces either the sum or the max::
 
    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 @@ specified characters will be treated as files, and will be replaced by the
 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'])
@@ -675,13 +675,12 @@ how the command-line arguments should be handled. The supplied actions are:
     Namespace(foo='1')
 
 * ``'store_const'`` - This stores the value specified by the const_ keyword
-  argument.  (Note that the const_ keyword argument defaults to the rather
-  unhelpful ``None``.)  The ``'store_const'`` action is most commonly used with
+  argument.  The ``'store_const'`` action is most commonly used with
   optional arguments that specify some sort of flag.  For example::
 
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action='store_const', const=42)
-    >>> parser.parse_args('--foo'.split())
+    >>> parser.parse_args(['--foo'])
     Namespace(foo=42)
 
 * ``'store_true'`` and ``'store_false'`` - These are special cases of
@@ -722,7 +721,7 @@ how the command-line arguments should be handled. The supplied actions are:
 
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--verbose', '-v', action='count')
-    >>> parser.parse_args('-vvv'.split())
+    >>> parser.parse_args(['-vvv'])
     Namespace(verbose=3)
 
 * ``'help'`` - This prints a complete help message for all the options in the
@@ -797,11 +796,11 @@ values are:
      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
      >>> parser.add_argument('bar', nargs='?', default='d')
-     >>> parser.parse_args('XX --foo YY'.split())
+     >>> parser.parse_args(['XX', '--foo', 'YY'])
      Namespace(bar='XX', foo='YY')
-     >>> parser.parse_args('XX --foo'.split())
+     >>> parser.parse_args(['XX', '--foo'])
      Namespace(bar='XX', foo='c')
-     >>> parser.parse_args(''.split())
+     >>> parser.parse_args([])
      Namespace(bar='d', foo='d')
 
   One of the more common uses of ``nargs='?'`` is to allow optional input and
@@ -837,9 +836,9 @@ values are:
 
      >>> parser = argparse.ArgumentParser(prog='PROG')
      >>> parser.add_argument('foo', nargs='+')
-     >>> parser.parse_args('a b'.split())
+     >>> parser.parse_args(['a', 'b'])
      Namespace(foo=['a', 'b'])
-     >>> parser.parse_args(''.split())
+     >>> parser.parse_args([])
      usage: PROG [-h] foo [foo ...]
      PROG: error: too few arguments
 
@@ -878,7 +877,8 @@ the various :class:`ArgumentParser` actions.  The two most common uses of it are
   command-line argument following it, the value of ``const`` will be assumed instead.
   See the nargs_ description for examples.
 
-The ``const`` keyword argument defaults to ``None``.
+With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
+keyword argument must be given.  For other actions, it defaults to ``None``.
 
 
 default
@@ -893,9 +893,9 @@ was not present at the command line::
 
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', default=42)
-   >>> parser.parse_args('--foo 2'.split())
+   >>> parser.parse_args(['--foo', '2'])
    Namespace(foo='2')
-   >>> parser.parse_args(''.split())
+   >>> parser.parse_args([])
    Namespace(foo=42)
 
 If the ``default`` value is a string, the parser parses the value as if it
@@ -914,9 +914,9 @@ is used when no command-line argument was present::
 
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('foo', nargs='?', default=42)
-   >>> parser.parse_args('a'.split())
+   >>> parser.parse_args(['a'])
    Namespace(foo='a')
-   >>> parser.parse_args(''.split())
+   >>> parser.parse_args([])
    Namespace(foo=42)
 
 
@@ -973,9 +973,9 @@ the converted value::
    ...
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('foo', type=perfect_square)
-   >>> parser.parse_args('9'.split())
+   >>> parser.parse_args(['9'])
    Namespace(foo=9)
-   >>> parser.parse_args('7'.split())
+   >>> parser.parse_args(['7'])
    usage: PROG [-h] foo
    PROG: error: argument foo: '7' is not a perfect square
 
@@ -984,9 +984,9 @@ simply check against a range of values::
 
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
-   >>> parser.parse_args('7'.split())
+   >>> parser.parse_args(['7'])
    Namespace(foo=7)
-   >>> parser.parse_args('11'.split())
+   >>> parser.parse_args(['11'])
    usage: PROG [-h] {5,6,7,8,9}
    PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
 
@@ -1064,10 +1064,10 @@ argument::
 
    >>> 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')
-   >>> parser.parse_args('-h'.split())
+   ...                     help='one of the bars to be frobbled')
+   >>> parser.parse_args(['-h'])
    usage: frobble [-h] [--foo] bar [bar ...]
 
    positional arguments:
@@ -1084,7 +1084,7 @@ specifiers include the program name, ``%(prog)s`` and most keyword arguments to
 
    >>> 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]
 
@@ -1182,7 +1182,7 @@ attribute is determined by the ``dest`` keyword argument of
 
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('bar')
-   >>> parser.parse_args('XXX'.split())
+   >>> parser.parse_args(['XXX'])
    Namespace(bar='XXX')
 
 For optional argument actions, the value of ``dest`` is normally inferred from
@@ -1277,22 +1277,22 @@ option and its value are passed as two separate arguments::
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('-x')
    >>> parser.add_argument('--foo')
-   >>> parser.parse_args('-x X'.split())
+   >>> parser.parse_args(['-x', 'X'])
    Namespace(foo=None, x='X')
-   >>> parser.parse_args('--foo FOO'.split())
+   >>> parser.parse_args(['--foo', 'FOO'])
    Namespace(foo='FOO', x=None)
 
 For long options (options with names longer than a single character), the option
 and value can also be passed as a single command-line argument, using ``=`` to
 separate them::
 
-   >>> parser.parse_args('--foo=FOO'.split())
+   >>> parser.parse_args(['--foo=FOO'])
    Namespace(foo='FOO', x=None)
 
 For short options (options only one character long), the option and its value
 can be concatenated::
 
-   >>> parser.parse_args('-xX'.split())
+   >>> parser.parse_args(['-xX'])
    Namespace(foo=None, x='X')
 
 Several short options can be joined together, using only a single ``-`` prefix,
@@ -1302,7 +1302,7 @@ as long as only the last option (or none of them) requires a value::
    >>> parser.add_argument('-x', action='store_true')
    >>> parser.add_argument('-y', action='store_true')
    >>> parser.add_argument('-z')
-   >>> parser.parse_args('-xyzZ'.split())
+   >>> parser.parse_args(['-xyzZ'])
    Namespace(x=True, y=True, z='Z')
 
 
@@ -1417,13 +1417,13 @@ interactive prompt::
    >>> 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'.split())
+   >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
    Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
 
 
@@ -1873,7 +1873,7 @@ Customizing file parsing
 
    Arguments that are read from a file (see the *fromfile_prefix_chars*
    keyword argument to the :class:`ArgumentParser` constructor) are read one
-   argument per line. :meth:`convert_arg_line_to_args` can be overriden for
+   argument per line. :meth:`convert_arg_line_to_args` can be overridden for
    fancier reading.
 
    This method takes a single argument *arg_line* which is a string read from
index 1766d47..5b9f345 100644 (file)
@@ -268,7 +268,7 @@ Examples::
       Packing and unpacking of External Data Representation (XDR) data as used in some
       remote procedure call systems.
 
-   `The Numerical Python Documentation <http://docs.scipy.org/doc/>`_
+   `The Numerical Python Documentation <https://docs.scipy.org/doc/>`_
       The Numeric Python extension (NumPy) defines another array type; see
       http://www.numpy.org/ for further information about Numerical Python.
 
index 37d001b..1ad02ec 100644 (file)
@@ -228,7 +228,7 @@ any extraneous data sent by the web client are ignored. ::
                    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 = []
index e747ba1..8261117 100644 (file)
@@ -269,6 +269,6 @@ sample and subtract the whole output sample from the input sample::
        #              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)
 
index c9ce28b..7d1a6e0 100644 (file)
@@ -16,7 +16,8 @@ email, used as parts of URLs, or included as part of an HTTP POST request.  The
 encoding algorithm is not the same as the :program:`uuencode` program.
 
 There are two interfaces provided by this module.  The modern interface supports
-encoding and decoding string objects using all three alphabets.  The legacy
+encoding and decoding string objects using both base-64 alphabets defined
+in :rfc:`3548` (normal, and URL- and filesystem-safe).  The legacy
 interface provides for encoding and decoding to and from file-like objects as
 well as strings, but only using the Base64 standard alphabet.
 
@@ -25,7 +26,7 @@ The modern interface, which was introduced in Python 2.4, provides:
 
 .. function:: b64encode(s[, altchars])
 
-   Encode a string use Base64.
+   Encode a string using Base64.
 
    *s* is the string to encode.  Optional *altchars* must be a string of at least
    length 2 (additional characters are ignored) which specifies an alternative
@@ -44,9 +45,10 @@ The modern interface, which was introduced in Python 2.4, provides:
    length 2 (additional characters are ignored) which specifies the alternative
    alphabet used instead of the ``+`` and ``/`` characters.
 
-   The decoded string is returned.  A :exc:`TypeError` is raised if *s* were
-   incorrectly padded or if there are non-alphabet characters present in the
-   string.
+   The decoded string is returned.  A :exc:`TypeError` is raised if *s* is
+   incorrectly padded.  Characters that are neither
+   in the normal base-64 alphabet nor the alternative alphabet are
+   discarded prior to the padding check.
 
 
 .. function:: standard_b64encode(s)
@@ -61,14 +63,16 @@ The modern interface, which was introduced in Python 2.4, provides:
 
 .. function:: urlsafe_b64encode(s)
 
-   Encode string *s* using a URL-safe alphabet, which substitutes ``-`` instead of
+   Encode string *s* using the URL- and filesystem-safe
+   alphabet, which substitutes ``-`` instead of
    ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet.  The result
    can still contain ``=``.
 
 
 .. function:: urlsafe_b64decode(s)
 
-   Decode string *s* using a URL-safe alphabet, which substitutes ``-`` instead of
+   Decode string *s* using the URL- and filesystem-safe
+   alphabet, which substitutes ``-`` instead of
    ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet.
 
 
index 01776af..0c663fe 100644 (file)
@@ -197,7 +197,10 @@ to a handler.  Code to create and run the server looks like this::
       Sends and logs a complete error reply to the client. The numeric *code*
       specifies the HTTP error code, with *message* as optional, more specific text. A
       complete set of headers is sent, followed by text composed using the
-      :attr:`error_message_format` class variable.
+      :attr:`error_message_format` class variable. The body will be empty
+      if the method is HEAD or the response code is one of the following:
+      ``1xx``, ``204 No Content``, ``205 Reset Content``,
+      ``304 Not Modified``.
 
 
    .. method:: send_response(code[, message])
index 0f8a3de..5eb7c4b 100644 (file)
@@ -45,8 +45,10 @@ The :mod:`binascii` module defines the following functions:
 .. function:: b2a_base64(data)
 
    Convert binary data to a line of ASCII characters in base64 coding. The return
-   value is the converted line, including a newline char. The length of *data*
-   should be at most 57 to adhere to the base64 standard.
+   value is the converted line, including a newline char.  The newline is
+   added because the original use case for this function was to feed it a
+   series of 57 byte input lines to get output lines that conform to the
+   MIME-base64 standard.  Otherwise the output conforms to :rfc:`3548`.
 
 
 .. function:: a2b_qp(string[, header])
@@ -165,7 +167,7 @@ The :mod:`binascii` module defines the following functions:
 .. seealso::
 
    Module :mod:`base64`
-      Support for base64 encoding used in MIME email messages.
+      Support for RFC compliant base64-style encoding in base 16, 32, and 64.
 
    Module :mod:`binhex`
       Support for the binhex format used on the Macintosh.
index 64a362e..b6577e5 100644 (file)
@@ -62,7 +62,7 @@ The following functions are provided:
 .. seealso::
 
    `SortedCollection recipe
-   <http://code.activestate.com/recipes/577197-sortedcollection/>`_ that uses
+   <https://code.activestate.com/recipes/577197-sortedcollection/>`_ that uses
    bisect to build a full-featured collection class with straight-forward search
    methods and support for a key-function.  The keys are precomputed to save
    unnecessary calls to the key function during searches.
index 6f7c265..da15e00 100644 (file)
@@ -295,12 +295,12 @@ algorithms implemented in this module in other circumstances.
 .. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]])
 
    This function is deprecated in this module. Use :func:`urlparse.parse_qs`
-   instead. It is maintained here only for backward compatiblity.
+   instead. It is maintained here only for backward compatibility.
 
 .. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]])
 
    This function is deprecated in this module. Use :func:`urlparse.parse_qsl`
-   instead. It is maintained here only for backward compatiblity.
+   instead. It is maintained here only for backward compatibility.
 
 .. function:: parse_multipart(fp, pdict)
 
index 6f8b7af..9d52fe1 100644 (file)
@@ -909,7 +909,7 @@ particular, the following variants typically exist:
 
 * an ISO 8859 codeset
 
-* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
+* a Microsoft Windows code page, which is typically derived from an 8859 codeset,
   but replaces control characters with additional graphic characters
 
 * an IBM EBCDIC code page
@@ -1273,7 +1273,7 @@ parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
 (:mod:`httplib` then also transparently sends an IDNA hostname in the
 :mailheader:`Host` field if it sends that field at all).
 
-.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
+.. _section 3.1: https://tools.ietf.org/html/rfc3490#section-3.1
 
 When receiving host names from the wire (such as in reverse name lookup), no
 automatic conversion to Unicode is performed: Applications wishing to present
index 58278d1..4231e8c 100644 (file)
@@ -196,16 +196,15 @@ counts, but the output will exclude results with counts of zero or less.
 
 .. seealso::
 
-    * `Counter class <http://code.activestate.com/recipes/576611/>`_
+    * `Counter class <https://code.activestate.com/recipes/576611/>`_
       adapted for Python 2.5 and an early `Bag recipe
-      <http://code.activestate.com/recipes/259174/>`_ for Python 2.4.
+      <https://code.activestate.com/recipes/259174/>`_ for Python 2.4.
 
-    * `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
       in Smalltalk.
 
-    * Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_.
+    * Wikipedia entry for `Multisets <https://en.wikipedia.org/wiki/Multiset>`_.
 
-    * `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
+    * `C++ multisets <http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
       tutorial with examples.
 
     * For mathematical operations on multisets and their use cases, see
@@ -786,7 +785,7 @@ and more efficient to use a simple class declaration:
 
 .. seealso::
 
-   `Named tuple recipe <http://code.activestate.com/recipes/500261/>`_
+   `Named tuple recipe <https://code.activestate.com/recipes/500261/>`_
    adapted for Python 2.4.
 
 
@@ -829,17 +828,17 @@ semantics pass-in keyword arguments using a regular unordered dictionary.
 
 .. seealso::
 
-   `Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_
+   `Equivalent OrderedDict recipe <https://code.activestate.com/recipes/576693/>`_
    that runs on Python 2.4 or later.
 
 :class:`OrderedDict` Examples and Recipes
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Since an ordered dictionary remembers its insertion order, it can be used
-in conjuction with sorting to make a sorted dictionary::
+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]))
@@ -1003,10 +1002,13 @@ The ABC supplies the remaining methods such as :meth:`__and__` and
              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)
 
@@ -1035,13 +1037,13 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
 (3)
    The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
    for the set; however, :meth:`__hash__` is not defined because not all sets
-   are hashable or immutable.  To add set hashabilty using mixins,
+   are hashable or immutable.  To add set hashability using mixins,
    inherit from both :meth:`Set` and :meth:`Hashable`, then define
    ``__hash__ = Set._hash``.
 
 .. seealso::
 
-   * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
+   * `OrderedSet recipe <https://code.activestate.com/recipes/576694/>`_ for an
      example built on :class:`MutableSet`.
 
    * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.
index 225306c..f1447e8 100644 (file)
@@ -21,7 +21,7 @@ spaces, the coordinates are all between 0 and 1.
 
    More information about color spaces can be found at
    http://www.poynton.com/ColorFAQ.html and
-   http://www.cambridgeincolour.com/tutorials/color-spaces.htm.
+   https://www.cambridgeincolour.com/tutorials/color-spaces.htm.
 
 The :mod:`colorsys` module defines the following functions:
 
index 515074a..16bd07a 100644 (file)
@@ -489,8 +489,8 @@ To get interpolation, you will need to use a :class:`ConfigParser` or
    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 @@ interpolation if an option used is not defined elsewhere. ::
    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::
 
index 610c0b0..c88dd23 100644 (file)
@@ -135,7 +135,7 @@ Functions provided:
 
 .. seealso::
 
-   :pep:`0343` - The "with" statement
+   :pep:`343` - The "with" statement
       The specification, background, and examples for the Python :keyword:`with`
       statement.
 
index 8d64206..3e9ea5a 100644 (file)
@@ -173,7 +173,7 @@ Morsel Objects
    * ``version``
    * ``httponly``
 
-   The attribute :attr:`httponly` specifies that the cookie is only transfered
+   The attribute :attr:`httponly` specifies that the cookie is only transferred
    in HTTP requests, and is not accessible through JavaScript. This is intended
    to mitigate some forms of cross-site scripting.
 
index 7829f53..ceccc13 100644 (file)
@@ -122,7 +122,7 @@ The following classes are provided:
       HTTP cookie classes, principally useful for server-side code.  The
       :mod:`cookielib` and :mod:`Cookie` modules do not depend on each other.
 
-   http://curl.haxx.se/rfc/cookie_spec.html
+   https://curl.haxx.se/rfc/cookie_spec.html
       The specification of the original Netscape cookie protocol.  Though this is
       still the dominant protocol, the 'Netscape cookie protocol' implemented by all
       the major browsers (and :mod:`cookielib`) only bears a passing resemblance to
index 670cbf1..be3b5b9 100644 (file)
@@ -18,13 +18,3 @@ Here's an overview:
    hmac.rst
    md5.rst
    sha.rst
-.. index::
-   pair: AES; algorithm
-   single: cryptography
-   single: Kuchling, Andrew
-
-Hardcore cypherpunks will probably find the cryptographic modules written by
-A.M. Kuchling of further interest; the package contains modules for various
-encryption algorithms, most notably AES.  These modules are not distributed with
-Python but available separately.  See the URL http://www.pycrypto.org/ for more
-information.
index d3d505e..dbef60f 100644 (file)
@@ -112,6 +112,7 @@ The :mod:`csv` module defines the following functions:
    value :const:`None` is written as the empty string.  While this isn't a
    reversible transformation, it makes it easier to dump SQL NULL data values to
    CSV files without preprocessing the data returned from a ``cursor.fetch*`` call.
+   Floats are stringified with :func:`repr` before being written.
    All other non-string data are stringified with :func:`str` before being written.
 
    A short usage example::
index adb9595..e30b006 100644 (file)
@@ -49,11 +49,11 @@ library containing most standard C functions, and uses the cdecl calling
 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 @@ load a library, so attribute access can not be used to load libraries. Either th
 :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 @@ Functions are accessed as attributes of dll objects::
    >>> 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 @@ Sometimes, dlls export functions with names which aren't valid Python
 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 @@ handle.
 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 @@ of arguments or the wrong calling convention.  Unfortunately this only works on
 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 @@ although an error is raised the function *has* been called::
 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 @@ On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
 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 @@ Here is a more advanced example, it uses the ``strchr`` function, which expects
 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 @@ callable will be called with the *integer* the C function returns, and the
 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
@@ -657,17 +657,17 @@ positive integer::
 
    TenPointsArrayType = POINT * 10
 
-Here is an example of an somewhat artificial data type, a structure containing 4
+Here is an example of a somewhat artificial data type, a structure containing 4
 POINTs among other stuff::
 
    >>> 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
@@ -708,8 +708,8 @@ Pointer instances are created by calling the :func:`pointer` function on a
    >>> pi = pointer(i)
    >>>
 
-Pointer instances have a :attr:`contents` attribute which returns the object to
-which the pointer points, the ``i`` object above::
+Pointer instances have a :attr:`~_Pointer.contents` attribute which
+returns the object to which the pointer points, the ``i`` object above::
 
    >>> pi.contents
    c_long(42)
@@ -934,7 +934,7 @@ other, and finally follow the pointer chain a few times::
 Callback functions
 ^^^^^^^^^^^^^^^^^^
 
-:mod:`ctypes` allows to create C callable function pointers from Python callables.
+:mod:`ctypes` allows creating C callable function pointers from Python callables.
 These are sometimes called *callback functions*.
 
 First, you must create a class for the callback function, the class knows the
@@ -1028,7 +1028,7 @@ Here is what we get on Windows::
 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 @@ access violation or whatever, so it's better to break out of the loop when we
 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
@@ -1348,7 +1348,7 @@ module instead of using :func:`find_library` to locate the library at runtime.
 Loading shared libraries
 ^^^^^^^^^^^^^^^^^^^^^^^^
 
-There are several ways to loaded shared libraries into the Python process.  One
+There are several ways to load shared libraries into the Python process.  One
 way is to instantiate one of the following classes:
 
 
@@ -1404,7 +1404,7 @@ details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
 ignored.
 
 The *use_errno* parameter, when set to True, enables a ctypes mechanism that
-allows to access the system :data:`errno` error number in a safe way.
+allows accessing the system :data:`errno` error number in a safe way.
 :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
 variable; if you call foreign functions created with ``use_errno=True`` then the
 :data:`errno` value before the function call is swapped with the ctypes private
@@ -1478,7 +1478,7 @@ loader instance.
    Class which loads shared libraries.  *dlltype* should be one of the
    :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
 
-   :meth:`__getattr__` has special behavior: It allows to load a shared library by
+   :meth:`__getattr__` has special behavior: It allows loading a shared library by
    accessing it as attribute of a library loader instance.  The result is cached,
    so repeated attribute accesses return the same library each time.
 
@@ -1557,7 +1557,7 @@ They are instances of a private class:
 
       It is possible to assign a callable Python object that is not a ctypes
       type, in this case the function is assumed to return a C :c:type:`int`, and
-      the callable will be called with this integer, allowing to do further
+      the callable will be called with this integer, allowing further
       processing or error checking.  Using this is deprecated, for more flexible
       post processing or error checking use a ctypes data type as
       :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
@@ -1573,15 +1573,15 @@ They are instances of a private class:
 
       When a foreign function is called, each actual argument is passed to the
       :meth:`from_param` class method of the items in the :attr:`argtypes`
-      tuple, this method allows to adapt the actual argument to an object that
+      tuple, this method allows adapting the actual argument to an object that
       the foreign function accepts.  For example, a :class:`c_char_p` item in
       the :attr:`argtypes` tuple will convert a unicode string passed as
-      argument into an byte string using ctypes conversion rules.
+      argument into a byte string using ctypes conversion rules.
 
       New: It is now possible to put items in argtypes which are not ctypes
       types, but each item must have a :meth:`from_param` method which returns a
       value usable as argument (integer, string, ctypes instance).  This allows
-      to define adapters that can adapt custom objects as function parameters.
+      defining adapters that can adapt custom objects as function parameters.
 
 
    .. attribute:: errcheck
@@ -1595,12 +1595,12 @@ They are instances of a private class:
          *result* is what the foreign function returns, as specified by the
          :attr:`restype` attribute.
 
-         *func* is the foreign function object itself, this allows to reuse the
+         *func* is the foreign function object itself, this allows reusing the
          same callable object to check or post process the results of several
          functions.
 
          *arguments* is a tuple containing the parameters originally passed to
-         the function call, this allows to specialize the behavior on the
+         the function call, this allows specializing the behavior on the
          arguments used.
 
       The object that this function returns will be returned from the
@@ -1853,7 +1853,7 @@ Utility functions
    If a string is specified as first argument, the buffer is made one item larger
    than the length of the string so that the last element in the array is a NUL
    termination character. An integer can be passed as second argument which allows
-   to specify the size of the array if the length of the string should not be used.
+   specifying the size of the array if the length of the string should not be used.
 
    If the first parameter is a unicode string, it is converted into an 8-bit string
    according to ctypes conversion rules.
@@ -1870,23 +1870,23 @@ Utility functions
    If a unicode string is specified as first argument, the buffer is made one item
    larger than the length of the string so that the last element in the array is a
    NUL termination character. An integer can be passed as second argument which
-   allows to specify the size of the array if the length of the string should not
+   allows specifying the size of the array if the length of the string should not
    be used.
 
-   If the first parameter is a 8-bit string, it is converted into an unicode string
+   If the first parameter is an 8-bit string, it is converted into a unicode string
    according to ctypes conversion rules.
 
 
 .. function:: DllCanUnloadNow()
 
-   Windows only: This function is a hook which allows to implement in-process
+   Windows only: This function is a hook which allows implementing in-process
    COM servers with ctypes.  It is called from the DllCanUnloadNow function that
    the _ctypes extension dll exports.
 
 
 .. function:: DllGetClassObject()
 
-   Windows only: This function is a hook which allows to implement in-process
+   Windows only: This function is a hook which allows implementing in-process
    COM servers with ctypes.  It is called from the DllGetClassObject function
    that the ``_ctypes`` extension dll exports.
 
@@ -1964,7 +1964,7 @@ Utility functions
 .. function:: POINTER(type)
 
    This factory function creates and returns a new ctypes pointer type. Pointer
-   types are cached an reused internally, so calling this function repeatedly is
+   types are cached and reused internally, so calling this function repeatedly is
    cheap. *type* must be a ctypes type.
 
 
@@ -2432,7 +2432,7 @@ other data types containing pointer type fields.
       checked, only one field can be accessed when names are repeated.
 
       It is possible to define the :attr:`_fields_` class variable *after* the
-      class statement that defines the Structure subclass, this allows to create
+      class statement that defines the Structure subclass, this allows creating
       data types that directly or indirectly reference themselves::
 
          class List(Structure):
@@ -2453,7 +2453,7 @@ other data types containing pointer type fields.
 
    .. attribute:: _pack_
 
-      An optional small integer that allows to override the alignment of
+      An optional small integer that allows overriding the alignment of
       structure fields in the instance.  :attr:`_pack_` must already be defined
       when :attr:`_fields_` is assigned, otherwise it will have no effect.
 
@@ -2465,8 +2465,8 @@ other data types containing pointer type fields.
       assigned, otherwise it will have no effect.
 
       The fields listed in this variable must be structure or union type fields.
-      :mod:`ctypes` will create descriptors in the structure type that allows to
-      access the nested fields directly, without the need to create the
+      :mod:`ctypes` will create descriptors in the structure type that allow
+      accessing the nested fields directly, without the need to create the
       structure or union field.
 
       Here is an example type (Windows)::
@@ -2512,6 +2512,56 @@ other data types containing pointer type fields.
 Arrays and pointers
 ^^^^^^^^^^^^^^^^^^^
 
-Not yet written - please see the sections :ref:`ctypes-pointers` and section
-:ref:`ctypes-arrays` in the tutorial.
+.. class:: Array(\*args)
+
+   Abstract base class for arrays.
+
+   The recommended way to create concrete array types is by multiplying any
+   :mod:`ctypes` data type with a positive integer.  Alternatively, you can subclass
+   this type and define :attr:`_length_` and :attr:`_type_` class variables.
+   Array elements can be read and written using standard
+   subscript and slice accesses; for slice reads, the resulting object is
+   *not* itself an :class:`Array`.
+
+
+   .. attribute:: _length_
+
+        A positive integer specifying the number of elements in the array.
+        Out-of-range subscripts result in an :exc:`IndexError`. Will be
+        returned by :func:`len`.
+
+
+   .. attribute:: _type_
+
+        Specifies the type of each element in the array.
+
+
+   Array subclass constructors accept positional arguments, used to
+   initialize the elements in order.
+
+
+.. class:: _Pointer
+
+   Private, abstract base class for pointers.
+
+   Concrete pointer types are created by calling :func:`POINTER` with the
+   type that will be pointed to; this is done automatically by
+   :func:`pointer`.
+
+   If a pointer points to an array, its elements can be read and
+   written using standard subscript and slice accesses.  Pointer objects
+   have no size, so :func:`len` will raise :exc:`TypeError`.  Negative
+   subscripts will read from the memory *before* the pointer (as in C), and
+   out-of-range subscripts will probably crash with an access violation (if
+   you're lucky).
+
+
+   .. attribute:: _type_
+
+        Specifies the type pointed to.
+
+   .. attribute:: contents
+
+        Returns the object to which to pointer points.  Assigning to this
+        attribute changes the pointer to point to the assigned object.
 
index 642d25b..43941d9 100644 (file)
@@ -1474,9 +1474,9 @@ keys); also, the following keypad mappings are standard:
 +------------------+-----------+
 | :kbd:`End`       | KEY_END   |
 +------------------+-----------+
-| :kbd:`Page Up`   | KEY_NPAGE |
+| :kbd:`Page Up`   | KEY_PPAGE |
 +------------------+-----------+
-| :kbd:`Page Down` | KEY_PPAGE |
+| :kbd:`Page Down` | KEY_NPAGE |
 +------------------+-----------+
 
 The following table lists characters from the alternate character set. These are
index 0cc36e9..76c4f57 100644 (file)
@@ -33,7 +33,7 @@ number represents metres, miles, or mass.  Naive objects are easy to understand
 and to work with, at the cost of ignoring some aspects of reality.
 
 For applications requiring aware objects, :class:`.datetime` and :class:`.time`
-objects have an optional time zone information attribute, :attr:`tzinfo`, that
+objects have an optional time zone information attribute, :attr:`!tzinfo`, that
 can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
 These :class:`tzinfo` objects capture information about the offset from UTC
 time, the time zone name, and whether Daylight Saving Time is in effect.  Note
@@ -83,7 +83,7 @@ Available Types
    An idealized time, independent of any particular day, assuming that every day
    has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
    Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
-   and :attr:`tzinfo`.
+   and :attr:`.tzinfo`.
 
 
 .. class:: datetime
@@ -91,7 +91,7 @@ Available Types
 
    A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
    :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
-   and :attr:`tzinfo`.
+   and :attr:`.tzinfo`.
 
 
 .. class:: timedelta
@@ -102,6 +102,7 @@ Available Types
 
 
 .. class:: tzinfo
+   :noindex:
 
    An abstract base class for time zone information objects.  These are used by the
    :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
@@ -514,7 +515,7 @@ Instance methods:
    Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
 
    The ISO calendar is a widely used variant of the Gregorian calendar. See
-   http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
+   https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
    explanation.
 
    The ISO year consists of 52 or 53 full weeks, and where a week starts on a
@@ -558,7 +559,7 @@ Instance methods:
 
 .. method:: date.__format__(format)
 
-   Same as :meth:`.date.strftime`. This makes it possible to specify format
+   Same as :meth:`.date.strftime`. This makes it possible to specify format
    string for a :class:`.date` object when using :meth:`str.format`.
    See section :ref:`strftime-strptime-behavior`.
 
@@ -650,7 +651,7 @@ Other constructors, all class methods:
 
 .. classmethod:: datetime.today()
 
-   Return the current local datetime, with :attr:`tzinfo` ``None``. This is
+   Return the current local datetime, with :attr:`.tzinfo` ``None``. This is
    equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
    :meth:`fromtimestamp`.
 
@@ -663,15 +664,15 @@ Other constructors, all class methods:
    (for example, this may be possible on platforms supplying the C
    :c:func:`gettimeofday` function).
 
-   Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
-   current date and time are converted to *tz*'s time zone.  In this case the
+   If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
+   current date and time are converted to *tz*s time zone.  In this case the
    result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
    See also :meth:`today`, :meth:`utcnow`.
 
 
 .. classmethod:: datetime.utcnow()
 
-   Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
+   Return the current UTC date and time, with :attr:`.tzinfo` ``None``. This is like
    :meth:`now`, but returns the current UTC date and time, as a naive
    :class:`.datetime` object. See also :meth:`now`.
 
@@ -683,8 +684,8 @@ Other constructors, all class methods:
    specified, the timestamp is converted to the platform's local date and time, and
    the returned :class:`.datetime` object is naive.
 
-   Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the
-   timestamp is converted to *tz*'s time zone.  In this case the result is
+   If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
+   timestamp is converted to *tz*s time zone.  In this case the result is
    equivalent to
    ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
 
@@ -700,7 +701,7 @@ Other constructors, all class methods:
 .. classmethod:: datetime.utcfromtimestamp(timestamp)
 
    Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
-   :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
+   :attr:`.tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
    out of the range of values supported by the platform C :c:func:`gmtime` function.
    It's common for this to be restricted to years in 1970 through 2038. See also
    :meth:`fromtimestamp`.
@@ -711,17 +712,17 @@ Other constructors, all class methods:
    Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
    where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
    <= ordinal <= datetime.max.toordinal()``.  The hour, minute, second and
-   microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
+   microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.
 
 
 .. classmethod:: datetime.combine(date, time)
 
    Return a new :class:`.datetime` object whose date components are equal to the
-   given :class:`date` object's, and whose time components and :attr:`tzinfo`
+   given :class:`date` object's, and whose time components and :attr:`.tzinfo`
    attributes are equal to the given :class:`.time` object's. For any
    :class:`.datetime` object *d*,
    ``d == datetime.combine(d.date(), d.timetz())``.  If date is a
-   :class:`.datetime` object, its time components and :attr:`tzinfo` attributes
+   :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
    are ignored.
 
 
@@ -818,7 +819,7 @@ Supported operations:
 (1)
    datetime2 is a duration of timedelta removed from datetime1, moving forward in
    time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0.  The
-   result has the same :attr:`tzinfo` attribute as the input datetime, and
+   result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
    datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
    datetime2.year would be smaller than :const:`MINYEAR` or larger than
    :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
@@ -826,7 +827,7 @@ Supported operations:
 
 (2)
    Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
-   addition, the result has the same :attr:`tzinfo` attribute as the input
+   addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
    datetime, and no time zone adjustments are done even if the input is aware.
    This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
    in isolation can overflow in cases where datetime1 - timedelta does not.
@@ -836,12 +837,12 @@ Supported operations:
    both operands are naive, or if both are aware.  If one is aware and the other is
    naive, :exc:`TypeError` is raised.
 
-   If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
-   the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
+   If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
+   the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
    object *t* such that ``datetime2 + t == datetime1``.  No time zone adjustments
    are done in this case.
 
-   If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
+   If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
    as if *a* and *b* were first converted to naive UTC datetimes first.  The
    result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
    - b.utcoffset())`` except that the implementation never overflows.
@@ -851,9 +852,9 @@ Supported operations:
    *datetime2* in time.
 
    If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
-   If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
-   common :attr:`tzinfo` attribute is ignored and the base datetimes are
-   compared.  If both comparands are aware and have different :attr:`tzinfo`
+   If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
+   common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
+   compared.  If both comparands are aware and have different :attr:`~.datetime.tzinfo`
    attributes, the comparands are first adjusted by subtracting their UTC
    offsets (obtained from ``self.utcoffset()``).
 
@@ -882,7 +883,7 @@ Instance methods:
 .. method:: datetime.time()
 
    Return :class:`.time` object with same hour, minute, second and microsecond.
-   :attr:`tzinfo` is ``None``.  See also method :meth:`timetz`.
+   :attr:`.tzinfo` is ``None``.  See also method :meth:`timetz`.
 
 
 .. method:: datetime.timetz()
@@ -901,7 +902,7 @@ Instance methods:
 
 .. method:: datetime.astimezone(tz)
 
-   Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
+   Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
    adjusting the date and time data so the result is the same UTC time as
    *self*, but in *tz*'s local time.
 
@@ -939,7 +940,7 @@ Instance methods:
 
 .. method:: datetime.utcoffset()
 
-   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
+   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
    ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
    return ``None``, or a :class:`timedelta` object representing a whole number of
    minutes with magnitude less than one day.
@@ -947,7 +948,7 @@ Instance methods:
 
 .. method:: datetime.dst()
 
-   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
+   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
    ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
    ``None``, or a :class:`timedelta` object representing a whole number of minutes
    with magnitude less than one day.
@@ -955,7 +956,7 @@ Instance methods:
 
 .. method:: datetime.tzname()
 
-   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
+   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
    ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
    ``None`` or a string object,
 
@@ -967,7 +968,7 @@ Instance methods:
    d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
    d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
    the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
-   of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is
+   of the result is set according to the :meth:`dst` method: :attr:`.tzinfo` is
    ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
    else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
    else :attr:`tm_isdst` is set to ``0``.
@@ -1058,7 +1059,7 @@ Instance methods:
 
 .. method:: datetime.__format__(format)
 
-   Same as :meth:`.datetime.strftime`.  This makes it possible to specify format
+   Same as :meth:`.datetime.strftime`.  This makes it possible to specify format
    string for a :class:`.datetime` object when using :meth:`str.format`.
    See section :ref:`strftime-strptime-behavior`.
 
@@ -1242,9 +1243,9 @@ Supported operations:
 * comparison of :class:`.time` to :class:`.time`, where *a* is considered less
   than *b* when *a* precedes *b* in time.  If one comparand is naive and the other
   is aware, :exc:`TypeError` is raised.  If both comparands are aware, and have
-  the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
+  the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
   ignored and the base times are compared.  If both comparands are aware and
-  have different :attr:`tzinfo` attributes, the comparands are first adjusted by
+  have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
   subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
   to stop mixed-type comparisons from falling back to the default comparison by
   object address, when a :class:`.time` object is compared to an object of a
@@ -1292,14 +1293,14 @@ Instance methods:
 
 .. method:: time.__format__(format)
 
-   Same as :meth:`.time.strftime`. This makes it possible to specify format string
+   Same as :meth:`.time.strftime`. This makes it possible to specify format string
    for a :class:`.time` object when using :meth:`str.format`.
    See section :ref:`strftime-strptime-behavior`.
 
 
 .. method:: time.utcoffset()
 
-   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
+   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
    ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
    return ``None`` or a :class:`timedelta` object representing a whole number of
    minutes with magnitude less than one day.
@@ -1307,7 +1308,7 @@ Instance methods:
 
 .. method:: time.dst()
 
-   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
+   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
    ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
    ``None``, or a :class:`timedelta` object representing a whole number of minutes
    with magnitude less than one day.
@@ -1315,7 +1316,7 @@ Instance methods:
 
 .. method:: time.tzname()
 
-   If :attr:`tzinfo` is ``None``, returns ``None``, else returns
+   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
    ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
    return ``None`` or a string object.
 
@@ -1352,26 +1353,28 @@ Example:
 :class:`tzinfo` Objects
 -----------------------
 
-:class:`tzinfo` is an abstract base class, meaning that this class should not be
-instantiated directly.  You need to derive a concrete subclass, and (at least)
-supply implementations of the standard :class:`tzinfo` methods needed by the
-:class:`.datetime` methods you use.  The :mod:`datetime` module does not supply
-any concrete subclasses of :class:`tzinfo`.
+.. class:: tzinfo()
+
+   This is an abstract base class, meaning that this class should not be
+   instantiated directly.  You need to derive a concrete subclass, and (at least)
+   supply implementations of the standard :class:`tzinfo` methods needed by the
+   :class:`.datetime` methods you use.  The :mod:`datetime` module does not supply
+   any concrete subclasses of :class:`tzinfo`.
 
-An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
-constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
-view their attributes as being in local time, and the :class:`tzinfo` object
-supports methods revealing offset of local time from UTC, the name of the time
-zone, and DST offset, all relative to a date or time object passed to them.
+   An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
+   constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
+   view their attributes as being in local time, and the :class:`tzinfo` object
+   supports methods revealing offset of local time from UTC, the name of the time
+   zone, and DST offset, all relative to a date or time object passed to them.
 
-Special requirement for pickling:  A :class:`tzinfo` subclass must have an
-:meth:`__init__` method that can be called with no arguments, else it can be
-pickled but possibly not unpickled again.  This is a technical requirement that
-may be relaxed in the future.
+   Special requirement for pickling:  A :class:`tzinfo` subclass must have an
+   :meth:`__init__` method that can be called with no arguments, else it can be
+   pickled but possibly not unpickled again.  This is a technical requirement that
+   may be relaxed in the future.
 
-A concrete subclass of :class:`tzinfo` may need to implement the following
-methods.  Exactly which methods are needed depends on the uses made of aware
-:mod:`datetime` objects.  If in doubt, simply implement all of them.
+   A concrete subclass of :class:`tzinfo` may need to implement the following
+   methods.  Exactly which methods are needed depends on the uses made of aware
+   :mod:`datetime` objects.  If in doubt, simply implement all of them.
 
 
 .. method:: tzinfo.utcoffset(self, dt)
@@ -1404,7 +1407,7 @@ methods.  Exactly which methods are needed depends on the uses made of aware
    (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
    already been added to the UTC offset returned by :meth:`utcoffset`, so there's
    no need to consult :meth:`dst` unless you're interested in obtaining DST info
-   separately.  For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
+   separately.  For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
    attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
    should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
    DST changes when crossing time zones.
@@ -1570,7 +1573,7 @@ EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
 
       *pytz* contains up-to-date information and its usage is recommended.
 
-   `IANA timezone database <http://www.iana.org/time-zones>`_
+   `IANA timezone database <https://www.iana.org/time-zones>`_
       The Time Zone Database (often called tz or zoneinfo) contains code and
       data that represent the history of local time for many representative
       locations around the globe. It is updated periodically to reflect changes
index a203fbd..8d457e1 100644 (file)
@@ -111,9 +111,6 @@ reset them before monitoring a calculation.
    * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
      Specification <http://speleotrove.com/decimal/>`_.
 
-   * IEEE standard 854-1987, `Unofficial IEEE 854 Text
-     <http://754r.ucbtest.org/standards/854.pdf>`_.
-
 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
 
index 03e8cb8..ead6b7a 100644 (file)
@@ -594,7 +594,7 @@ If you want to know how to change the first sequence into the second, use
      work.
 
    * `Simple version control recipe
-     <http://code.activestate.com/recipes/576729/>`_ for a small application
+     <https://code.activestate.com/recipes/576729/>`_ for a small application
      built with :class:`SequenceMatcher`.
 
 
index 534faab..12ad8c0 100644 (file)
@@ -1,10 +1,9 @@
-
 :mod:`distutils` --- Building and installing Python modules
 ===========================================================
 
 .. module:: distutils
-   :synopsis: Support for building and installing Python modules into an existing Python
-              installation.
+   :synopsis: Support for building and installing Python modules into an
+              existing Python installation.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
 
@@ -13,18 +12,31 @@ additional modules into a Python installation.  The new modules may be either
 100%-pure Python, or may be extension modules written in C, or may be
 collections of Python packages which include modules coded in both Python and C.
 
-This package is discussed in two separate chapters:
-
-
-.. seealso::
-
-   :ref:`distutils-index`
-      The manual for developers and packagers of Python modules.  This describes how
-      to prepare :mod:`distutils`\ -based packages so that they may be easily
-      installed into an existing Python installation.
-
-   :ref:`install-index`
-      An "administrators" manual which includes information on installing modules into
-      an existing Python installation. You do not need to be a Python programmer to
-      read this manual.
-
+Most Python users will *not* want to use this module directly, but instead
+use the cross-version tools maintained by the Python Packaging Authority. In
+particular,
+`setuptools <https://setuptools.readthedocs.io/en/latest/>`__ is an
+enhanced alternative to :mod:`distutils` that provides:
+
+* support for declaring project dependencies
+* additional mechanisms for configuring which files to include in source
+  releases (including plugins for integration with version control systems)
+* the ability to declare project "entry points", which can be used as the
+  basis for application plugin systems
+* the ability to automatically generate Windows command line executables at
+  installation time rather than needing to prebuild them
+* consistent behaviour across all supported Python versions
+
+The recommended `pip <https://pip.pypa.io/>`__ installer runs all
+``setup.py`` scripts with ``setuptools``, even if the script itself only
+imports ``distutils``. Refer to the
+`Python Packaging User Guide <https://packaging.python.org>`_ for more
+information.
+
+For the benefits of packaging tool authors and users seeking a deeper
+understanding of the details of the current packaging and distribution
+system, the legacy :mod:`distutils` based user documentation and API
+reference remain available:
+
+* :ref:`install-index`
+* :ref:`distutils-index`
index 4ea7e6a..8fe70a7 100644 (file)
@@ -37,7 +37,7 @@ Here are the public methods of the :class:`Generator` class, imported from the
    followed by a space at the beginning of the line.  This is the only guaranteed
    portable way to avoid having such lines be mistaken for a Unix mailbox format
    envelope header separator (see `WHY THE CONTENT-LENGTH FORMAT IS BAD
-   <http://www.jwz.org/doc/content-length.html>`_ for details).  *mangle_from_*
+   <https://www.jwz.org/doc/content-length.html>`_ for details).  *mangle_from_*
    defaults to ``True``, but you might want to set this to ``False`` if you are not
    writing Unix mailbox format files.
 
index 478c450..ad72ab7 100644 (file)
@@ -12,7 +12,9 @@
    pair: UNIX; I/O control
 
 This module performs file control and I/O control on file descriptors. It is an
-interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines.
+interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines.  For a
+complete description of these calls, see :manpage:`fcntl(2)` and
+:manpage:`ioctl(2)` Unix manual pages.
 
 All functions in this module take a file descriptor *fd* as their first
 argument.  This can be an integer file descriptor, such as returned by
index 710bef3..307a36d 100644 (file)
@@ -60,6 +60,9 @@ The following function is the primary interface of this module:
    .. versionchanged:: 2.5
       Added the *mode* and *openhook* parameters.
 
+   .. versionchanged:: 2.7.12
+      The *bufsize* parameter is no longer used.
+
 The following functions use the global state created by :func:`fileinput.input`;
 if there is no active state, :exc:`RuntimeError` is raised.
 
@@ -143,6 +146,9 @@ available for subclassing as well:
    .. versionchanged:: 2.5
       Added the *mode* and *openhook* parameters.
 
+   .. versionchanged:: 2.7.12
+      The *bufsize* parameter is no longer used.
+
 **Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed
 to :func:`fileinput.input` or to the :class:`FileInput` constructor, the file is
 moved to a backup file and standard output is directed to the input file (if a
@@ -175,7 +181,7 @@ The two following opening hooks are provided by this module:
 
 .. function:: hook_encoded(encoding)
 
-   Returns a hook which opens each file with :func:`codecs.open`, using the given
+   Returns a hook which opens each file with :func:`io.open`, using the given
    *encoding* to read the file.
 
    Usage example: ``fi =
index c689372..c5928d5 100644 (file)
@@ -17,7 +17,7 @@
    single: Overmars, Mark
 
 This module provides an interface to the FORMS Library by Mark Overmars.  The
-source for the library can be retrieved by anonymous ftp from host
+source for the library can be retrieved by anonymous FTP from host
 ``ftp.cs.ruu.nl``, directory :file:`SGI/FORMS`.  It was last tested with version
 2.0b.
 
@@ -310,7 +310,7 @@ here.
 
 .. method:: form.add_input(type, x, y, w, h, name)
 
-   Add a input object to the form.  ---  Methods: :meth:`set_input`,
+   Add an input object to the form.  ---  Methods: :meth:`set_input`,
    :meth:`get_input`, :meth:`set_input_color`, :meth:`set_input_return`.
 
 
index 2d85de1..3ab7b3b 100644 (file)
@@ -16,7 +16,7 @@
 This module defines the class :class:`FTP` and a few related items. The
 :class:`FTP` class implements the client side of the FTP protocol.  You can use
 this to write Python programs that perform a variety of automated FTP jobs, such
-as mirroring other ftp servers.  It is also used by the module :mod:`urllib` to
+as mirroring other FTP servers.  It is also used by the module :mod:`urllib` to
 handle URLs that use FTP.  For more information on FTP (File Transfer Protocol),
 see Internet :rfc:`959`.
 
index 8b677ed..20372b3 100644 (file)
@@ -1447,7 +1447,7 @@ section.
 
    For practical suggestions on how to design cooperative classes using
    :func:`super`, see `guide to using super()
-   <http://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_.
+   <https://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_.
 
    .. versionadded:: 2.2
 
index 2dfb102..2d81e5a 100644 (file)
@@ -129,7 +129,7 @@ In a script, typical usage is something like this::
            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
index 02c3fd8..e735bfe 100644 (file)
@@ -22,8 +22,6 @@ The :mod:`getpass` module provides two functions:
    a warning message to *stream* and reading from ``sys.stdin`` and
    issuing a :exc:`GetPassWarning`.
 
-   Availability: Macintosh, Unix, Windows.
-
    .. versionchanged:: 2.5
       The *stream* parameter was added.
    .. versionchanged:: 2.6
@@ -41,7 +39,7 @@ The :mod:`getpass` module provides two functions:
 
 .. function:: getuser()
 
-   Return the "login name" of the user. Availability: Unix, Windows.
+   Return the "login name" of the user.
 
    This function checks the environment variables :envvar:`LOGNAME`,
    :envvar:`USER`, :envvar:`LNAME` and :envvar:`USERNAME`, in order, and returns
index a7d1f45..3dce037 100644 (file)
@@ -133,7 +133,7 @@ the iterable into an actual heap.
 Basic Examples
 --------------
 
-A `heapsort <http://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by
+A `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by
 pushing all values onto a heap and then popping off the smallest values one at a
 time::
 
@@ -164,7 +164,7 @@ Heap elements can be tuples.  This is useful for assigning comparison values
 Priority Queue Implementation Notes
 -----------------------------------
 
-A `priority queue <http://en.wikipedia.org/wiki/Priority_queue>`_ is common use
+A `priority queue <https://en.wikipedia.org/wiki/Priority_queue>`_ is common use
 for a heap, and it presents several implementation challenges:
 
 * Sort stability:  how do you get two tasks with equal priorities to be returned
@@ -244,7 +244,7 @@ for a tournament.  The numbers below are *k*, not ``a[k]``::
 
    15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30
 
-In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In an usual
+In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a usual
 binary tournament we see in sports, each cell is the winner over the two cells
 it tops, and we can trace the winner down the tree to see all opponents s/he
 had.  However, in many computer applications of such tournaments, we do not need
index e5045dd..08ac577 100644 (file)
@@ -64,7 +64,7 @@ The module defines a parser class and an exception:
 .. class:: HTMLParser(formatter)
 
    This is the basic HTML parser class.  It supports all entity names required by
-   the XHTML 1.0 Recommendation (http://www.w3.org/TR/xhtml1).   It also defines
+   the XHTML 1.0 Recommendation (https://www.w3.org/TR/xhtml1).   It also defines
    handlers for all HTML 2.0 and many HTML 3.0 and 3.2 elements.
 
 
index 81d5c53..e73ce07 100644 (file)
@@ -66,8 +66,10 @@ as they are encountered::
    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
 
@@ -148,8 +150,8 @@ implementations do nothing (except for :meth:`~HTMLParser.handle_startendtag`):
    and quotes in the *value* have been removed, and character and entity references
    have been replaced.
 
-   For instance, for the tag ``<A HREF="http://www.cwi.nl/">``, this method
-   would be called as ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
+   For instance, for the tag ``<A HREF="https://www.cwi.nl/">``, this method
+   would be called as ``handle_starttag('a', [('href', 'https://www.cwi.nl/')])``.
 
    .. versionchanged:: 2.6
       All entity references from :mod:`htmlentitydefs` are now replaced in the
@@ -252,21 +254,27 @@ examples::
            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 @@ further parsing::
         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
index 45d8295..4bf2006 100644 (file)
@@ -27,7 +27,7 @@ uses it to handle URLs that use HTTP and HTTPS.
 .. seealso::
 
     The `Requests package <http://requests.readthedocs.org/>`_
-    is recommended for a higher-level http client interface.
+    is recommended for a higher-level HTTP client interface.
 
 .. note::
 
index ab40e7a..5067084 100644 (file)
@@ -83,7 +83,7 @@ methods:
 
 .. method:: IC.parseurl(data[, start[, end[, hint]]])
 
-   Find an URL somewhere in *data* and return start position, end position and the
+   Find a URL somewhere in *data* and return start position, end position and the
    URL. The optional *start* and *end* can be used to limit the search, so for
    instance if a user clicks in a long text field you can pass the whole text field
    and the click-position in *start* and this routine will return the whole URL in
index 4384d56..84805ff 100644 (file)
@@ -128,7 +128,7 @@ Find Selection
    Search for the currently selected string, if there is one.
 
 Find in Files...
-   Open a file search dialog.  Put results in an new output window.
+   Open a file search dialog.  Put results in a new output window.
 
 Replace...
    Open a search-and-replace dialog.
@@ -550,14 +550,16 @@ IDLE-console differences
 
 As much as possible, the result of executing Python code with IDLE is the
 same as executing the same code in a console window.  However, the different
-interface and operation occasionally affects results.
-
-For instance, IDLE normally executes user code in a separate process from
-the IDLE GUI itself.  The IDLE versions of sys.stdin, .stdout, and .stderr in the
-execution process get input from and send output to the GUI process,
-which keeps control of the keyboard and screen.  This is normally transparent,
-but code that access these object will see different attribute values.
-Also, functions that directly access the keyboard and screen will not work.
+interface and operation occasionally affects visible results.  For instance,
+``sys.modules`` starts with more entries.
+
+IDLE also replaces ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` with
+objects that get input from and send output to the Shell window.
+When this window has the focus, it controls the keyboard and screen.
+This is normally transparent, but functions that directly access the keyboard
+and screen will not work.  If ``sys`` is reset with ``reload(sys)``,
+IDLE's changes are lost and things like ``input``, ``raw_input``, and
+``print`` will not work correctly.
 
 With IDLE's Shell, one enters, edits, and recalls complete statements.
 Some consoles only work with a single physical line at a time.
index e6cb669..674b029 100644 (file)
@@ -49,7 +49,7 @@ The module defines the following variables and functions:
 
 .. function:: grey2mono(image, width, height, threshold)
 
-   Convert a 8-bit deep greyscale image to a 1-bit deep image by thresholding all
+   Convert an 8-bit deep greyscale image to a 1-bit deep image by thresholding all
    the pixels.  The resulting image is tightly packed and is probably only useful
    as an argument to :func:`mono2grey`.
 
index ca18a9c..20e377f 100644 (file)
@@ -125,7 +125,7 @@ example of usage.
 
    Documents describing the protocol, and sources and binaries  for servers
    implementing it, can all be found at the University of Washington's *IMAP
-   Information Center* (http://www.washington.edu/imap/).
+   Information Center* (https://www.washington.edu/imap/).
 
 
 .. _imap4-objects:
index 2b41bec..1964f71 100644 (file)
@@ -272,7 +272,8 @@ Note:
 
 .. function:: ismethod(object)
 
-   Return true if the object is a bound method written in Python.
+   Return true if the object is a bound or unbound method written in Python.
+
 
 
 .. function:: isfunction(object)
@@ -442,8 +443,12 @@ Retrieving source code
 .. function:: cleandoc(doc)
 
    Clean up indentation from docstrings that are indented to line up with blocks
-   of code.  Any whitespace that can be uniformly removed from the second line
-   onwards is removed.  Also, all tabs are expanded to spaces.
+   of code.
+
+   All leading whitespace is removed from the first line.  Any leading whitespace
+   that can be uniformly removed from the second line onwards is removed.  Empty
+   lines at the beginning and end are subsequently removed.  Also, all tabs are
+   expanded to spaces.
 
    .. versionadded:: 2.6
 
index 6743b27..d3cdbf1 100644 (file)
@@ -225,10 +225,15 @@ I/O Base Classes
    support are called.
 
    The basic type used for binary data read from or written to a file is
-   :class:`bytes` (also known as :class:`str`).  :class:`bytearray`\s are
-   accepted too, and in some cases (such as :class:`readinto`) required.
+   :class:`bytes` (also known as :class:`str`).  Method arguments may
+   also be :class:`bytearray` or :class:`memoryview` of arrays of bytes.
+   In some cases, such as :meth:`~RawIOBase.readinto`, a writable object
+   such as :class:`bytearray` is required.
    Text I/O classes work with :class:`unicode` data.
 
+   .. versionchanged:: 2.7
+      Implementations should support :class:`memoryview` arguments.
+
    Note that calling any method (even inquiries) on a closed stream is
    undefined.  Implementations may raise :exc:`IOError` in this case.
 
@@ -383,18 +388,24 @@ I/O Base Classes
 
    .. method:: readinto(b)
 
-      Read up to len(b) bytes into bytearray *b* and return the number
-      of bytes read.  If the object is in non-blocking mode and no
+      Read up to len(b) bytes into *b*, and return the number
+      of bytes read.  The object *b* should be a pre-allocated, writable
+      array of bytes, either :class:`bytearray` or :class:`memoryview`.
+      If the object is in non-blocking mode and no
       bytes are available, ``None`` is returned.
 
    .. method:: write(b)
 
-      Write the given bytes or bytearray object, *b*, to the underlying raw
-      stream and return the number of bytes written.  This can be less than
+      Write *b* to the underlying raw stream, and return the
+      number of bytes written.  The object *b* should be an array
+      of bytes, either :class:`bytes`, :class:`bytearray`, or
+      :class:`memoryview`.  The return value can be less than
       ``len(b)``, depending on specifics of the underlying raw stream, and
       especially if it is in non-blocking mode.  ``None`` is returned if the
       raw stream is set not to block and no single byte could be readily
-      written to it.
+      written to it.  The caller may release or mutate *b* after
+      this method returns, so the implementation should only access *b*
+      during the method call.
 
 
 .. class:: BufferedIOBase
@@ -465,8 +476,9 @@ I/O Base Classes
 
    .. method:: readinto(b)
 
-      Read up to len(b) bytes into bytearray *b* and return the number of bytes
-      read.
+      Read up to len(b) bytes into *b*, and return the number of bytes read.
+      The object *b* should be a pre-allocated, writable array of bytes,
+      either :class:`bytearray` or :class:`memoryview`.
 
       Like :meth:`read`, multiple reads may be issued to the underlying raw
       stream, unless the latter is 'interactive'.
@@ -476,9 +488,11 @@ I/O Base Classes
 
    .. method:: write(b)
 
-      Write the given bytes or bytearray object, *b* and return the number
-      of bytes written (never less than ``len(b)``, since if the write fails
-      an :exc:`IOError` will be raised).  Depending on the actual
+      Write *b*, and return the number of bytes written
+      (always equal to ``len(b)``, since if the write fails
+      an :exc:`IOError` will be raised).  The object *b* should be
+      an array of bytes, either :class:`bytes`, :class:`bytearray`,
+      or :class:`memoryview`.  Depending on the actual
       implementation, these bytes may be readily written to the underlying
       stream, or held in a buffer for performance and latency reasons.
 
@@ -486,6 +500,9 @@ I/O Base Classes
       data needed to be written to the raw stream but it couldn't accept
       all the data without blocking.
 
+      The caller may release or mutate *b* after this method returns,
+      so the implementation should only access *b* during the method call.
+
 
 Raw File I/O
 ------------
@@ -535,7 +552,8 @@ than raw I/O does.
    A stream implementation using an in-memory bytes buffer.  It inherits
    :class:`BufferedIOBase`.
 
-   The argument *initial_bytes* is an optional initial :class:`bytes`.
+   The optional argument *initial_bytes* is a :class:`bytes` object that
+   contains initial data.
 
    :class:`BytesIO` provides or overrides these methods in addition to those
    from :class:`BufferedIOBase` and :class:`IOBase`:
@@ -611,8 +629,10 @@ than raw I/O does.
 
    .. method:: write(b)
 
-      Write the bytes or bytearray object, *b* and return the number of bytes
-      written.  When in non-blocking mode, a :exc:`BlockingIOError` is raised
+      Write *b*, and return the number of bytes written.
+      The object *b* should be an array of bytes, either
+      :class:`bytes`, :class:`bytearray`, or :class:`memoryview`.
+      When in non-blocking mode, a :exc:`BlockingIOError` is raised
       if the buffer needs to be written out but the raw stream blocks.
 
 
@@ -661,7 +681,7 @@ Text I/O
 
 .. class:: TextIOBase
 
-   Base class for text streams.  This class provides an unicode character
+   Base class for text streams.  This class provides a unicode character
    and line based interface to stream I/O.  There is no :meth:`readinto`
    method because Python's :class:`unicode` strings are immutable.
    It inherits :class:`IOBase`.  There is no public constructor.
index 10a6d6a..ff94d55 100644 (file)
@@ -10,7 +10,7 @@ to communicate.
 
 Some modules only work for two processes that are on the same machine, e.g.
 :mod:`signal` and :mod:`subprocess`.  Other modules support networking protocols
-that two or more processes can used to communicate across machines.
+that two or more processes can use to communicate across machines.
 
 The list of modules described in this chapter is:
 
index ea279b0..57ba4d4 100644 (file)
@@ -94,7 +94,7 @@ loops that truncate the stream.
    Make an iterator that returns elements from the first iterable until it is
    exhausted, then proceeds to the next iterable, until all of the iterables are
    exhausted.  Used for treating consecutive sequences as a single sequence.
-   Equivalent to::
+   Roughly equivalent to::
 
       def chain(*iterables):
           # chain('ABC', 'DEF') --> A B C D E F
@@ -129,7 +129,7 @@ loops that truncate the stream.
    value.  So if the input elements are unique, there will be no repeat
    values in each combination.
 
-   Equivalent to::
+   Roughly equivalent to::
 
         def combinations(iterable, r):
             # combinations('ABCD', 2) --> AB AC AD BC BD CD
@@ -180,7 +180,7 @@ loops that truncate the stream.
    value.  So if the input elements are unique, the generated combinations
    will also be unique.
 
-   Equivalent to::
+   Roughly equivalent to::
 
         def combinations_with_replacement(iterable, r):
             # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
@@ -219,7 +219,7 @@ loops that truncate the stream.
    Make an iterator that filters elements from *data* returning only those that
    have a corresponding element in *selectors* that evaluates to ``True``.
    Stops when either the *data* or *selectors* iterables has been exhausted.
-   Equivalent to::
+   Roughly equivalent to::
 
        def compress(data, selectors):
            # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
@@ -253,7 +253,7 @@ loops that truncate the stream.
 
    Make an iterator returning elements from the iterable and saving a copy of each.
    When the iterable is exhausted, return elements from the saved copy.  Repeats
-   indefinitely.  Equivalent to::
+   indefinitely.  Roughly equivalent to::
 
       def cycle(iterable):
           # cycle('ABCD') --> A B C D A B C D A B C D ...
@@ -274,7 +274,7 @@ loops that truncate the stream.
    Make an iterator that drops elements from the iterable as long as the predicate
    is true; afterwards, returns every element.  Note, the iterator does not produce
    *any* output until the predicate first becomes false, so it may have a lengthy
-   start-up time.  Equivalent to::
+   start-up time.  Roughly equivalent to::
 
       def dropwhile(predicate, iterable):
           # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
@@ -313,7 +313,7 @@ loops that truncate the stream.
           groups.append(list(g))      # Store group iterator as a list
           uniquekeys.append(k)
 
-   :func:`groupby` is equivalent to::
+   :func:`groupby` is roughly equivalent to::
 
       class groupby(object):
           # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
@@ -345,7 +345,7 @@ loops that truncate the stream.
 
    Make an iterator that filters elements from iterable returning only those for
    which the predicate is ``True``. If *predicate* is ``None``, return the items
-   that are true. Equivalent to::
+   that are true. Roughly equivalent to::
 
       def ifilter(predicate, iterable):
           # ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
@@ -360,7 +360,7 @@ loops that truncate the stream.
 
    Make an iterator that filters elements from iterable returning only those for
    which the predicate is ``False``. If *predicate* is ``None``, return the items
-   that are false. Equivalent to::
+   that are false. Roughly equivalent to::
 
       def ifilterfalse(predicate, iterable):
           # ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
@@ -379,7 +379,7 @@ loops that truncate the stream.
    exhausted instead of filling in ``None`` for shorter iterables.  The reason for
    the difference is that infinite iterator arguments are typically an error for
    :func:`map` (because the output is fully evaluated) but represent a common and
-   useful way of supplying arguments to :func:`imap`. Equivalent to::
+   useful way of supplying arguments to :func:`imap`. Roughly equivalent to::
 
       def imap(function, *iterables):
           # imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
@@ -403,7 +403,7 @@ loops that truncate the stream.
    specified position.  Unlike regular slicing, :func:`islice` does not support
    negative values for *start*, *stop*, or *step*.  Can be used to extract related
    fields from data where the internal structure has been flattened (for example, a
-   multi-line report may list a name field on every third line).  Equivalent to::
+   multi-line report may list a name field on every third line).  Roughly equivalent to::
 
       def islice(iterable, *args):
           # islice('ABCDEFG', 2) --> A B
@@ -429,7 +429,7 @@ loops that truncate the stream.
 
    Make an iterator that aggregates elements from each of the iterables. Like
    :func:`zip` except that it returns an iterator instead of a list.  Used for
-   lock-step iteration over several iterables at a time.  Equivalent to::
+   lock-step iteration over several iterables at a time.  Roughly equivalent to::
 
       def izip(*iterables):
           # izip('ABCD', 'xy') --> Ax By
@@ -454,7 +454,7 @@ loops that truncate the stream.
 
    Make an iterator that aggregates elements from each of the iterables. If the
    iterables are of uneven length, missing values are filled-in with *fillvalue*.
-   Iteration continues until the longest iterable is exhausted.  Equivalent to::
+   Iteration continues until the longest iterable is exhausted.  Roughly equivalent to::
 
       class ZipExhausted(Exception):
           pass
@@ -499,7 +499,7 @@ loops that truncate the stream.
    value.  So if the input elements are unique, there will be no repeat
    values in each permutation.
 
-   Equivalent to::
+   Roughly equivalent to::
 
         def permutations(iterable, r=None):
             # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
@@ -547,7 +547,7 @@ loops that truncate the stream.
 
    Cartesian product of input iterables.
 
-   Equivalent to nested for-loops in a generator expression. For example,
+   Roughly equivalent to nested for-loops in a generator expression. For example,
    ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
 
    The nested loops cycle like an odometer with the rightmost element advancing
@@ -559,7 +559,7 @@ loops that truncate the stream.
    repetitions with the optional *repeat* keyword argument.  For example,
    ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
 
-   This function is equivalent to the following code, except that the
+   This function is roughly equivalent to the following code, except that the
    actual implementation does not build up intermediate results in memory::
 
        def product(*args, **kwds):
@@ -579,7 +579,7 @@ loops that truncate the stream.
    Make an iterator that returns *object* over and over again. Runs indefinitely
    unless the *times* argument is specified. Used as argument to :func:`imap` for
    invariant function parameters.  Also used with :func:`izip` to create constant
-   fields in a tuple record.  Equivalent to::
+   fields in a tuple record.  Roughly equivalent to::
 
       def repeat(object, times=None):
           # repeat(10, 3) --> 10 10 10
@@ -602,7 +602,7 @@ loops that truncate the stream.
    the iterable.  Used instead of :func:`imap` when argument parameters are already
    grouped in tuples from a single iterable (the data has been "pre-zipped").  The
    difference between :func:`imap` and :func:`starmap` parallels the distinction
-   between ``function(a,b)`` and ``function(*c)``. Equivalent to::
+   between ``function(a,b)`` and ``function(*c)``. Roughly equivalent to::
 
       def starmap(function, iterable):
           # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
@@ -616,7 +616,7 @@ loops that truncate the stream.
 .. function:: takewhile(predicate, iterable)
 
    Make an iterator that returns elements from the iterable as long as the
-   predicate is true.  Equivalent to::
+   predicate is true.  Roughly equivalent to::
 
       def takewhile(predicate, iterable):
           # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
@@ -629,7 +629,7 @@ loops that truncate the stream.
 
 .. function:: tee(iterable[, n=2])
 
-   Return *n* independent iterators from a single iterable.  Equivalent to::
+   Return *n* independent iterators from a single iterable.  Roughly equivalent to::
 
         def tee(iterable, n=2):
             it = iter(iterable)
@@ -695,6 +695,11 @@ which incur interpreter overhead.
        "Returns the nth item or a default value"
        return next(islice(iterable, n, None), default)
 
+   def all_equal(iterable):
+       "Returns True if all the elements are equal to each other"
+       g = groupby(iterable)
+       return next(g, True) and not next(g, False)
+
    def quantify(iterable, pred=bool):
        "Count how many times the predicate is true"
        return sum(imap(pred, iterable))
index b501d65..8f66b6c 100644 (file)
@@ -11,7 +11,7 @@
 :rfc:`7159` (which obsoletes :rfc:`4627`) and by
 `ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_,
 is a lightweight data interchange format inspired by
-`JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
+`JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
 (although it is not a strict subset of JavaScript [#rfc-errata]_ ).
 
 :mod:`json` exposes an API familiar to users of the standard library
@@ -613,7 +613,7 @@ when serializing instances of "exotic" numerical types such as
 .. rubric:: Footnotes
 
 .. [#rfc-errata] As noted in `the errata for RFC 7159
-   <http://www.rfc-editor.org/errata_search.php?rfc=7159>`_,
+   <https://www.rfc-editor.org/errata_search.php?rfc=7159>`_,
    JSON permits literal U+2028 (LINE SEPARATOR) and
    U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript
    (as of ECMAScript Edition 5.1) does not.
index 8fa1a1b..0b02685 100644 (file)
@@ -481,13 +481,13 @@ The :mod:`locale` module defines the following exception and functions:
 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
index 6731abc..27167f0 100644 (file)
@@ -349,7 +349,7 @@ sends logging output to a network socket. The base class uses a TCP socket.
    .. method:: createSocket()
 
       Tries to create a socket; on failure, uses an exponential back-off
-      algorithm.  On intial failure, the handler will drop the message it was
+      algorithm.  On initial failure, the handler will drop the message it was
       trying to send.  When subsequent messages are handled by the same
       instance, it will not try connecting until some time has passed.  The
       default parameters are such that the initial delay is one second, and if
@@ -743,7 +743,7 @@ supports sending logging messages to a Web server, using either ``GET`` or
 
    .. method:: emit(record)
 
-      Sends the record to the Web server as an URL-encoded dictionary. The
+      Sends the record to the Web server as a URL-encoded dictionary. The
       :meth:`mapLogRecord` method is used to convert the record to the
       dictionary to be sent.
 
index 9f778f5..4f6e4e8 100644 (file)
@@ -622,7 +622,9 @@ format string.
 | Attribute name | Format                  | Description                                   |
 +================+=========================+===============================================+
 | args           | You shouldn't need to   | The tuple of arguments merged into ``msg`` to |
-|                | format this yourself.   | produce ``message``.                          |
+|                | format this yourself.   | produce ``message``, or a dict whose values   |
+|                |                         | are used for the merge (when there is only one|
+|                |                         | argument, and it is a dictionary).            |
 +----------------+-------------------------+-----------------------------------------------+
 | asctime        | ``%(asctime)s``         | Human-readable time when the                  |
 |                |                         | :class:`LogRecord` was created.  By default   |
@@ -1019,7 +1021,7 @@ with the :mod:`warnings` module.
       The proposal which described this feature for inclusion in the Python standard
       library.
 
-   `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
+   `Original Python logging package <https://www.red-dove.com/python_logging.html>`_
       This is the original source for the :mod:`logging` package.  The version of the
       package available from this site is suitable for use with Python 1.5.2, 2.1.x
       and 2.2.x, which do not include the :mod:`logging` package in the standard
index 3154aa4..9f894ca 100644 (file)
@@ -409,7 +409,7 @@ Maildir, mbox, MH, Babyl, and MMDF.
    `maildir man page from qmail <http://www.qmail.org/man/man5/maildir.html>`_
       The original specification of the format.
 
-   `Using maildir format <http://cr.yp.to/proto/maildir.html>`_
+   `Using maildir format <https://cr.yp.to/proto/maildir.html>`_
       Notes on Maildir by its inventor. Includes an updated name-creation scheme and
       details on "info" semantics.
 
@@ -471,7 +471,7 @@ Maildir, mbox, MH, Babyl, and MMDF.
    `mbox man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mbox>`_
       Another specification of the format, with details on locking.
 
-   `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <http://www.jwz.org/doc/content-length.html>`_
+   `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <https://www.jwz.org/doc/content-length.html>`_
       An argument for using the original mbox format rather than a variation.
 
    `"mbox" is a family of several mutually incompatible mailbox formats <http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/mail-mbox-formats.html>`_
@@ -677,10 +677,10 @@ Maildir, mbox, MH, Babyl, and MMDF.
 
 .. seealso::
 
-   `Format of Version 5 Babyl Files <http://quimby.gnus.org/notes/BABYL>`_
+   `Format of Version 5 Babyl Files <https://quimby.gnus.org/notes/BABYL>`_
       A specification of the Babyl format.
 
-   `Reading Mail with Rmail <http://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html>`_
+   `Reading Mail with Rmail <https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html>`_
       The Rmail manual, with some information on Babyl semantics.
 
 
@@ -731,7 +731,7 @@ Maildir, mbox, MH, Babyl, and MMDF.
    `mmdf man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mmdf>`_
       A specification of MMDF format from the documentation of tin, a newsreader.
 
-   `MMDF <http://en.wikipedia.org/wiki/MMDF>`_
+   `MMDF <https://en.wikipedia.org/wiki/MMDF>`_
       A Wikipedia article describing the Multichannel Memorandum Distribution
       Facility.
 
index b359509..750d085 100644 (file)
@@ -70,7 +70,7 @@ standard.  However, mailcap files are supported on most Unix systems.
 An example usage::
 
    >>> import mailcap
-   >>> d=mailcap.getcaps()
+   >>> d = mailcap.getcaps()
    >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
    ('xmpeg tmp1223', {'view': 'xmpeg %s'})
 
index f4dfc1f..1ce7326 100644 (file)
@@ -17,7 +17,6 @@ rarely does). [#]_
 .. index::
    module: pickle
    module: shelve
-   object: code
 
 This is not a general "persistence" module.  For general persistence and
 transfer of Python objects through RPC calls, see the modules :mod:`pickle` and
@@ -35,6 +34,8 @@ supports a substantially wider range of objects than marshal.
    maliciously constructed data.  Never unmarshal data received from an
    untrusted or unauthenticated source.
 
+.. index:: object; code, code object
+
 Not all Python object types are supported; in general, only objects whose value
 is independent from a particular invocation of Python can be written and read by
 this module.  The following types are supported: booleans, integers, long
@@ -66,7 +67,7 @@ The module defines these functions:
 .. function:: dump(value, file[, version])
 
    Write the value on the open file.  The value must be a supported type.  The
-   file must be a open file object such as ``sys.stdout`` or returned by
+   file must be an open file object such as ``sys.stdout`` or returned by
    :func:`open` or :func:`os.popen`.  It may not be a wrapper such as
    TemporaryFile on Windows. It must be opened in binary mode (``'wb'``
    or ``'w+b'``).
index 22d2316..ac34d58 100644 (file)
@@ -102,7 +102,7 @@ Number-theoretic and representation functions
 
    For further discussion and two alternative approaches, see the `ASPN cookbook
    recipes for accurate floating point summation
-   <http://code.activestate.com/recipes/393090/>`_\.
+   <https://code.activestate.com/recipes/393090/>`_\.
 
    .. versionadded:: 2.6
 
index 0b7fc92..43c4ea0 100644 (file)
@@ -44,7 +44,7 @@ the information :func:`init` sets up.
 
    The optional *strict* argument is a flag specifying whether the list of known MIME types
    is limited to only the official types `registered with IANA
-   <http://www.iana.org/assignments/media-types/media-types.xhtml>`_.
+   <https://www.iana.org/assignments/media-types/media-types.xhtml>`_.
    When *strict* is ``True`` (the default), only the IANA types are supported; when
    *strict* is ``False``, some additional non-standard but commonly used MIME types
    are also recognized.
index ac1963f..0860cac 100644 (file)
@@ -140,7 +140,7 @@ memory but does not update the underlying file.
 
       pid = os.fork()
 
-      if pid == 0: # In a child process
+      if pid == 0:  # In a child process
           mm.seek(0)
           print mm.readline()
 
index 4aca842..a4d382c 100644 (file)
@@ -123,9 +123,9 @@ structures.
 
 .. seealso::
 
-   `FCICreateFile <http://msdn.microsoft.com/library?url=/library/en-us/devnotes/winprog/fcicreate.asp>`_
-   `UuidCreate <http://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidcreate.asp>`_
-   `UuidToString <http://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidtostring.asp>`_
+   `FCICreateFile <https://msdn.microsoft.com/library?url=/library/en-us/devnotes/winprog/fcicreate.asp>`_
+   `UuidCreate <https://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidcreate.asp>`_
+   `UuidToString <https://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidtostring.asp>`_
 
 .. _database-objects:
 
@@ -154,9 +154,9 @@ Database Objects
 
 .. seealso::
 
-   `MSIDatabaseOpenView <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabaseopenview.asp>`_
-   `MSIDatabaseCommit <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabasecommit.asp>`_
-   `MSIGetSummaryInformation <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msigetsummaryinformation.asp>`_
+   `MSIDatabaseOpenView <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabaseopenview.asp>`_
+   `MSIDatabaseCommit <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabasecommit.asp>`_
+   `MSIGetSummaryInformation <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msigetsummaryinformation.asp>`_
 
 .. _view-objects:
 
@@ -202,11 +202,11 @@ View Objects
 
 .. seealso::
 
-   `MsiViewExecute <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewexecute.asp>`_
-   `MSIViewGetColumnInfo <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewgetcolumninfo.asp>`_
-   `MsiViewFetch <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewfetch.asp>`_
-   `MsiViewModify <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewmodify.asp>`_
-   `MsiViewClose <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewclose.asp>`_
+   `MsiViewExecute <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewexecute.asp>`_
+   `MSIViewGetColumnInfo <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewgetcolumninfo.asp>`_
+   `MsiViewFetch <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewfetch.asp>`_
+   `MsiViewModify <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewmodify.asp>`_
+   `MsiViewClose <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewclose.asp>`_
 
 .. _summary-objects:
 
@@ -246,10 +246,10 @@ Summary Information Objects
 
 .. seealso::
 
-   `MsiSummaryInfoGetProperty <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetproperty.asp>`_
-   `MsiSummaryInfoGetPropertyCount <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetpropertycount.asp>`_
-   `MsiSummaryInfoSetProperty <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfosetproperty.asp>`_
-   `MsiSummaryInfoPersist <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfopersist.asp>`_
+   `MsiSummaryInfoGetProperty <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetproperty.asp>`_
+   `MsiSummaryInfoGetPropertyCount <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetpropertycount.asp>`_
+   `MsiSummaryInfoSetProperty <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfosetproperty.asp>`_
+   `MsiSummaryInfoPersist <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfopersist.asp>`_
 
 .. _record-objects:
 
@@ -300,11 +300,11 @@ Record Objects
 
 .. seealso::
 
-   `MsiRecordGetFieldCount <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordgetfieldcount.asp>`_
-   `MsiRecordSetString <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstring.asp>`_
-   `MsiRecordSetStream <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstream.asp>`_
-   `MsiRecordSetInteger <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetinteger.asp>`_
-   `MsiRecordClear <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordclear.asp>`_
+   `MsiRecordGetFieldCount <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordgetfieldcount.asp>`_
+   `MsiRecordSetString <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstring.asp>`_
+   `MsiRecordSetStream <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstream.asp>`_
+   `MsiRecordSetInteger <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetinteger.asp>`_
+   `MsiRecordClear <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordclear.asp>`_
 
 .. _msi-errors:
 
@@ -396,10 +396,10 @@ Directory Objects
 
 .. seealso::
 
-   `Directory Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/directory_table.asp>`_
-   `File Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/file_table.asp>`_
-   `Component Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/component_table.asp>`_
-   `FeatureComponents Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/featurecomponents_table.asp>`_
+   `Directory Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/directory_table.asp>`_
+   `File Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/file_table.asp>`_
+   `Component Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/component_table.asp>`_
+   `FeatureComponents Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/featurecomponents_table.asp>`_
 
 .. _features:
 
@@ -424,7 +424,7 @@ Features
 
 .. seealso::
 
-   `Feature Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/feature_table.asp>`_
+   `Feature Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/feature_table.asp>`_
 
 .. _msi-gui:
 
@@ -519,13 +519,13 @@ for installing Python packages.
 
 .. seealso::
 
-   `Dialog Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/dialog_table.asp>`_
-   `Control Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/control_table.asp>`_
-   `Control Types <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controls.asp>`_
-   `ControlCondition Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlcondition_table.asp>`_
-   `ControlEvent Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlevent_table.asp>`_
-   `EventMapping Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/eventmapping_table.asp>`_
-   `RadioButton Table <http://msdn.microsoft.com/library?url=/library/en-us/msi/setup/radiobutton_table.asp>`_
+   `Dialog Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/dialog_table.asp>`_
+   `Control Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/control_table.asp>`_
+   `Control Types <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controls.asp>`_
+   `ControlCondition Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlcondition_table.asp>`_
+   `ControlEvent Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlevent_table.asp>`_
+   `EventMapping Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/eventmapping_table.asp>`_
+   `RadioButton Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/radiobutton_table.asp>`_
 
 .. _msi-tables:
 
index 2c765f5..e33f85f 100644 (file)
@@ -215,7 +215,7 @@ However, if you really do need to use some shared data then
    proxies.
 
    A manager returned by :func:`Manager` will support types :class:`list`,
-   :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`,
+   :class:`dict`, :class:`~managers.Namespace`, :class:`Lock`, :class:`RLock`,
    :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
    :class:`Event`, :class:`~multiprocessing.Queue`, :class:`Value` and :class:`Array`.  For
    example, ::
@@ -261,16 +261,41 @@ processes in a few different ways.
 
 For example::
 
-   from multiprocessing import Pool
+   from multiprocessing import Pool, TimeoutError
+   import time
+   import os
 
    def f(x):
        return x*x
 
    if __name__ == '__main__':
        pool = Pool(processes=4)              # start 4 worker processes
-       result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
-       print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
-       print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"
+
+       # print "[0, 1, 4,..., 81]"
+       print pool.map(f, range(10))
+
+       # print same numbers in arbitrary order
+       for i in pool.imap_unordered(f, range(10)):
+           print i
+
+       # evaluate "f(20)" asynchronously
+       res = pool.apply_async(f, (20,))      # runs in *only* one process
+       print res.get(timeout=1)              # prints "400"
+
+       # evaluate "os.getpid()" asynchronously
+       res = pool.apply_async(os.getpid, ()) # runs in *only* one process
+       print res.get(timeout=1)              # prints the PID of that process
+
+       # launching multiple evaluations asynchronously *may* use more processes
+       multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
+       print [res.get(timeout=1) for res in multiple_results]
+
+       # make a single worker sleep for 10 secs
+       res = pool.apply_async(time.sleep, (10,))
+       try:
+           print res.get(timeout=1)
+       except TimeoutError:
+           print "We lacked patience and got a multiprocessing.TimeoutError"
 
 Note that the methods of a pool should only ever be used by the
 process which created it.
@@ -751,8 +776,10 @@ Miscellaneous
    If the ``freeze_support()`` line is omitted then trying to run the frozen
    executable will raise :exc:`RuntimeError`.
 
-   If the module is being run normally by the Python interpreter then
-   :func:`freeze_support` has no effect.
+   Calling ``freeze_support()`` has no effect when invoked on any operating
+   system other than Windows.  In addition, if the module is being run
+   normally by the Python interpreter on Windows (the program has not been
+   frozen), then ``freeze_support()`` has no effect.
 
 .. function:: set_executable()
 
@@ -1510,24 +1537,25 @@ their parent process exits.  The manager classes are defined in the
          lproxy[0] = d
 
 
-Namespace objects
->>>>>>>>>>>>>>>>>
+.. class:: Namespace
 
-A namespace object has no public methods, but does have writable attributes.
-Its representation shows the values of its attributes.
+    A type that can register with :class:`SyncManager`.
 
-However, when using a proxy for a namespace object, an attribute beginning with
-``'_'`` will be an attribute of the proxy and not an attribute of the referent:
+    A namespace object has no public methods, but does have writable attributes.
+    Its representation shows the values of its attributes.
 
-.. doctest::
+    However, when using a proxy for a namespace object, an attribute beginning with
+    ``'_'`` will be an attribute of the proxy and not an attribute of the referent:
+
+    .. doctest::
 
-   >>> manager = multiprocessing.Manager()
-   >>> Global = manager.Namespace()
-   >>> Global.x = 10
-   >>> Global.y = 'hello'
-   >>> Global._z = 12.3    # this is an attribute of the proxy
-   >>> print Global
-   Namespace(x=10, y='hello')
+       >>> manager = multiprocessing.Manager()
+       >>> Global = manager.Namespace()
+       >>> Global.x = 10
+       >>> Global.y = 'hello'
+       >>> Global._z = 12.3    # this is an attribute of the proxy
+       >>> print Global
+       Namespace(x=10, y='hello')
 
 
 Customized managers
@@ -1884,6 +1912,7 @@ with the :class:`Pool` class.
 The following example demonstrates the use of a pool::
 
    from multiprocessing import Pool
+   import time
 
    def f(x):
        return x*x
@@ -1891,7 +1920,7 @@ The following example demonstrates the use of a pool::
    if __name__ == '__main__':
        pool = Pool(processes=4)              # start 4 worker processes
 
-       result = pool.apply_async(f, (10,))    # evaluate "f(10)" asynchronously
+       result = pool.apply_async(f, (10,))   # evaluate "f(10)" asynchronously in a single process
        print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
 
        print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"
@@ -1901,9 +1930,8 @@ The following example demonstrates the use of a pool::
        print it.next()                       # prints "1"
        print it.next(timeout=1)              # prints "4" unless your computer is *very* slow
 
-       import time
        result = pool.apply_async(time.sleep, (10,))
-       print result.get(timeout=1)           # raises TimeoutError
+       print result.get(timeout=1)           # raises multiprocessing.TimeoutError
 
 
 .. _multiprocessing-listeners-clients:
@@ -2109,9 +2137,9 @@ connection is established both ends will demand proof that the other knows the
 authentication key.  (Demonstrating that both ends are using the same key does
 **not** involve sending the key over the connection.)
 
-If authentication is requested but do authentication key is specified then the
+If authentication is requested but no authentication key is specified then the
 return value of ``current_process().authkey`` is used (see
-:class:`~multiprocessing.Process`).  This value will automatically inherited by
+:class:`~multiprocessing.Process`).  This value will be automatically inherited by
 any :class:`~multiprocessing.Process` object that the current process creates.
 This means that (by default) all processes of a multi-process program will share
 a single authentication key which can be used when setting up connections
@@ -2324,8 +2352,8 @@ Explicitly pass resources to child processes
             ... 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 ::
@@ -2336,8 +2364,8 @@ Explicitly pass resources to child processes
             ... 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"
index 77684bf..f9149af 100644 (file)
@@ -27,7 +27,7 @@ The :mod:`nis` module defines the following functions:
    Note that *mapname* is first checked if it is an alias to another name.
 
    .. versionchanged:: 2.5
-      The *domain* argument allows to override the NIS domain used for the lookup. If
+      The *domain* argument allows overriding the NIS domain used for the lookup. If
       unspecified, lookup is in the default NIS domain.
 
 
@@ -40,7 +40,7 @@ The :mod:`nis` module defines the following functions:
    Note that *mapname* is first checked if it is an alias to another name.
 
    .. versionchanged:: 2.5
-      The *domain* argument allows to override the NIS domain used for the lookup. If
+      The *domain* argument allows overriding the NIS domain used for the lookup. If
       unspecified, lookup is in the default NIS domain.
 
 
@@ -49,7 +49,7 @@ The :mod:`nis` module defines the following functions:
    Return a list of all valid maps.
 
    .. versionchanged:: 2.5
-      The *domain* argument allows to override the NIS domain used for the lookup. If
+      The *domain* argument allows overriding the NIS domain used for the lookup. If
       unspecified, lookup is in the default NIS domain.
 
 
index 417b3bb..dfb43a1 100644 (file)
@@ -27,7 +27,7 @@ GNU/POSIX syntax, and additionally generates usage and help messages for you.
 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 @@ First, you need to import the OptionParser class; then, early in the main
 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 @@ you can call :func:`OptionParser.error` to signal an application-defined error
 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 @@ Putting it all together
 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 @@ Here's what :mod:`optparse`\ -based scripts usually look like::
                          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 @@ If you're not careful, it's easy to define options with conflicting option
 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 @@ that option.  If the user asks for help, the help message will reflect that::
 
    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 @@ At this point, the original ``-n``/``--dry-run`` option is no longer
 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 @@ seen, but blow up if it comes after ``-b`` in the command-line.  ::
        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 @@ message and the flag that it sets must be generalized.  ::
        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 @@ should not be called when the moon is full, all you have to do is this::
            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 @@ Here's an example that just emulates the standard ``"store"`` action::
 
    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 @@ arguments::
         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:
index dc5d588..5d7edd1 100644 (file)
@@ -185,7 +185,7 @@ the :mod:`glob` module.)
 .. function:: islink(path)
 
    Return ``True`` if *path* refers to a directory entry that is a symbolic link.
-   Always ``False`` if symbolic links are not supported by the python runtime.
+   Always ``False`` if symbolic links are not supported by the Python runtime.
 
 
 .. function:: ismount(path)
index 77f02ab..d9a62dc 100644 (file)
@@ -1222,10 +1222,17 @@ Files and Directories
 .. function:: mkdir(path[, mode])
 
    Create a directory named *path* with numeric mode *mode*. The default *mode* is
-   ``0777`` (octal).  On some systems, *mode* is ignored.  Where it is used, the
-   current umask value is first masked out.  If the directory already exists,
+   ``0777`` (octal).  If the directory already exists,
    :exc:`OSError` is raised.
 
+   .. _mkdir_modebits:
+
+   On some systems, *mode* is ignored.  Where it is used, the current umask
+   value is first masked out.  If bits other than the last 9 (i.e. the last 3
+   digits of the octal representation of the *mode*) are set, their meaning is
+   platform-dependent.  On some platforms, they are ignored and you should call
+   :func:`chmod` explicitly to set them.
+
    It is also possible to create temporary directories; see the
    :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
 
@@ -1241,8 +1248,10 @@ Files and Directories
    Recursive directory creation function.  Like :func:`mkdir`, but makes all
    intermediate-level directories needed to contain the leaf directory.  Raises an
    :exc:`error` exception if the leaf directory already exists or cannot be
-   created.  The default *mode* is ``0777`` (octal).  On some systems, *mode* is
-   ignored. Where it is used, the current umask value is first masked out.
+   created.  The default *mode* is ``0777`` (octal).
+
+   The *mode* parameter is passed to :func:`mkdir`; see :ref:`the mkdir()
+   description <mkdir_modebits>` for how it is interpreted.
 
    .. note::
 
index 9ce9a16..413bad7 100644 (file)
@@ -13,24 +13,24 @@ available for Python:
       provides an object oriented interface that is slightly higher level than
       the C one. It comes with many more widgets than Tkinter provides, and has
       good Python-specific reference documentation. There are also bindings to
-      `GNOME <http://www.gnome.org>`_.  An online `tutorial
+      `GNOME <https://www.gnome.org/>`_.  An online `tutorial
       <http://www.pygtk.org/pygtk2tutorial/index.html>`_ is available.
 
-   `PyQt <http://www.riverbankcomputing.co.uk/software/pyqt/intro>`_
+   `PyQt <https://riverbankcomputing.com/software/pyqt/intro>`_
       PyQt is a :program:`sip`\ -wrapped binding to the Qt toolkit.  Qt is an
       extensive C++ GUI application development framework that is
       available for Unix, Windows and Mac OS X. :program:`sip` is a tool
       for generating bindings for C++ libraries as Python classes, and
       is specifically designed for Python. The *PyQt3* bindings have a
       book, `GUI Programming with Python: QT Edition
-      <http://www.commandprompt.com/community/pyqt/>`_ by Boudewijn
+      <https://www.commandprompt.com/community/pyqt/>`_ by Boudewijn
       Rempt. The *PyQt4* bindings also have a book, `Rapid GUI Programming
-      with Python and Qt <http://www.qtrac.eu/pyqtbook.html>`_, by Mark
+      with Python and Qt <https://www.qtrac.eu/pyqtbook.html>`_, by Mark
       Summerfield.
 
    `wxPython <http://www.wxpython.org>`_
       wxPython is a cross-platform GUI toolkit for Python that is built around
-      the popular `wxWidgets <http://www.wxwidgets.org/>`_ (formerly wxWindows)
+      the popular `wxWidgets <https://www.wxwidgets.org/>`_ (formerly wxWindows)
       C++ toolkit.  It provides a native look and feel for applications on
       Windows, Mac OS X, and Unix systems by using each platform's native
       widgets where ever possible, (GTK+ on Unix-like systems).  In addition to
@@ -39,7 +39,7 @@ available for Python:
       low-level device context drawing, drag and drop, system clipboard access,
       an XML-based resource format and more, including an ever growing library
       of user-contributed modules.  wxPython has a book, `wxPython in Action
-      <http://www.manning.com/rappin/>`_, by Noel Rappin and
+      <https://www.manning.com/books/wxpython-in-action>`_, by Noel Rappin and
       Robin Dunn.
 
 PyGTK, PyQt, and wxPython, all have a modern look and feel and more
index 8e7baf8..ffa27d4 100644 (file)
@@ -190,7 +190,7 @@ are converted to strings.  The default implementation uses the internals of the
    the current presentation context (direct and indirect containers for *object*
    that are affecting the presentation) as the keys; if an object needs to be
    presented which is already represented in *context*, the third return value
-   should be ``True``.  Recursive calls to the :meth:`format` method should add
+   should be ``True``.  Recursive calls to the :meth:`.format` method should add
    additional entries for containers to this dictionary.  The third argument,
    *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
    is no requested limit.  This argument should be passed unmodified to recursive
index 5876d1d..b580948 100644 (file)
@@ -595,9 +595,9 @@ Content Model Descriptions
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
 
-Content modules are described using nested tuples.  Each tuple contains four
+Content models are described using nested tuples.  Each tuple contains four
 values: the type, the quantifier, the name, and a tuple of children.  Children
-are simply additional content module descriptions.
+are simply additional content model descriptions.
 
 The values of the first two fields are constants defined in the ``model`` object
 of the :mod:`xml.parsers.expat` module.  These constants can be collected in two
@@ -788,7 +788,7 @@ The ``errors`` object has the following attributes:
 .. data:: XML_ERROR_UNDEFINED_ENTITY
    :noindex:
 
-   A reference was made to a entity which was not defined.
+   A reference was made to an entity which was not defined.
 
 
 .. data:: XML_ERROR_UNKNOWN_ENCODING
@@ -911,6 +911,6 @@ The ``errors`` object has the following attributes:
 
 .. [#] The encoding string included in XML output should conform to the
    appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
-   not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
-   and http://www.iana.org/assignments/character-sets/character-sets.xhtml.
+   not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
+   and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
 
index 1bc9989..1316d2d 100644 (file)
@@ -19,7 +19,7 @@ On the real line, there are functions to compute uniform, normal (Gaussian),
 lognormal, negative exponential, gamma, and beta distributions. For generating
 distributions of angles, the von Mises distribution is available.
 
-Almost all module functions depend on the basic function :func:`random`, which
+Almost all module functions depend on the basic function :func:`.random`, which
 generates a random float uniformly in the semi-open range [0.0, 1.0).  Python
 uses the Mersenne Twister as the core generator.  It produces 53-bit precision
 floats and has a period of 2\*\*19937-1.  The underlying implementation in C is
@@ -36,9 +36,10 @@ especially useful for multi-threaded programs, creating a different instance of
 it likely that the generated sequences seen by each thread don't overlap.
 
 Class :class:`Random` can also be subclassed if you want to use a different
-basic generator of your own devising: in that case, override the :meth:`random`,
-:meth:`seed`, :meth:`getstate`, :meth:`setstate` and :meth:`jumpahead` methods.
-Optionally, a new generator can supply a :meth:`getrandbits` method --- this
+basic generator of your own devising: in that case, override the :meth:`~Random.random`,
+:meth:`~Random.seed`, :meth:`~Random.getstate`, :meth:`~Random.setstate` and
+:meth:`~Random.jumpahead` methods.  Optionally, a new generator can supply a
+:meth:`~Random.getrandbits` method --- this
 allows :meth:`randrange` to produce selections over an arbitrarily large range.
 
 .. versionadded:: 2.4
@@ -158,7 +159,7 @@ Functions for sequences:
 
    Shuffle the sequence *x* in place. The optional argument *random* is a
    0-argument function returning a random float in [0.0, 1.0); by default, this is
-   the function :func:`random`.
+   the function :func:`.random`.
 
    Note that for even rather small ``len(x)``, the total number of permutations of
    *x* is larger than the period of most random number generators; this implies
index c4029c5..1239434 100644 (file)
@@ -108,11 +108,11 @@ The special characters are:
 ``*?``, ``+?``, ``??``
    The ``'*'``, ``'+'``, and ``'?'`` qualifiers are all :dfn:`greedy`; they match
    as much text as possible.  Sometimes this behaviour isn't desired; if the RE
-   ``<.*>`` is matched against ``'<H1>title</H1>'``, it will match the entire
-   string, and not just ``'<H1>'``.  Adding ``'?'`` after the qualifier makes it
+   ``<.*>`` is matched against ``<a> b <c>``, it will match the entire
+   string, and not just ``<a>``.  Adding ``?`` after the qualifier makes it
    perform the match in :dfn:`non-greedy` or :dfn:`minimal` fashion; as *few*
-   characters as possible will be matched.  Using ``.*?`` in the previous
-   expression will match only ``'<H1>'``.
+   characters as possible will be matched.  Using the RE ``<.*?>`` will match
+   only ``<a>``.
 
 ``{m}``
    Specifies that exactly *m* copies of the previous RE should be matched; fewer
@@ -1120,15 +1120,15 @@ does by default).
 
 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 @@ a function to "munge" text, or randomize the order of all the characters
 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.'
index 64c61a2..a0ed89e 100644 (file)
 
 The :mod:`readline` module defines a number of functions to facilitate
 completion and reading/writing of history files from the Python interpreter.
-This module can be used directly or via the :mod:`rlcompleter` module.  Settings
+This module can be used directly, or via the :mod:`rlcompleter` module, which
+supports completion of Python identifiers at the interactive prompt.  Settings
 made using  this module affect the behaviour of both the interpreter's
 interactive prompt  and the prompts offered by the :func:`raw_input` and
 :func:`input` built-in functions.
 
 .. note::
 
-  On MacOS X the :mod:`readline` module can be implemented using
+  The underlying Readline library API may be implemented by
   the ``libedit`` library instead of GNU readline.
+  On MacOS X the :mod:`readline` module detects which library is being used
+  at run time.
 
   The configuration file for ``libedit`` is different from that
   of GNU readline. If you programmatically load configuration strings
   you can check for the text "libedit" in :const:`readline.__doc__`
   to differentiate between GNU readline and libedit.
 
+Readline keybindings may be configured via an initialization file, typically
+``.inputrc`` in your home directory.  See `Readline Init File
+<https://cnswww.cns.cwru.edu/php/chet/readline/rluserman.html#SEC9>`_
+in the GNU Readline manual for information about the format and
+allowable constructs of that file, and the capabilities of the
+Readline library in general.
 
-The :mod:`readline` module defines the following functions:
+
+Init file
+---------
+
+The following functions relate to the init file and user configuration:
 
 
 .. function:: parse_and_bind(string)
 
-   Parse and execute single line of a readline init file.
+   Execute the init line provided in the *string* argument. This calls
+   :c:func:`rl_parse_and_bind` in the underlying library.
+
+
+.. function:: read_init_file([filename])
+
+   Execute a readline initialization file. The default filename is the last filename
+   used. This calls :c:func:`rl_read_init_file` in the underlying library.
+
+
+Line buffer
+-----------
+
+The following functions operate on the line buffer:
 
 
 .. function:: get_line_buffer()
 
-   Return the current contents of the line buffer.
+   Return the current contents of the line buffer (:c:data:`rl_line_buffer`
+   in the underlying library).
 
 
 .. function:: insert_text(string)
 
-   Insert text into the command line.
+   Insert text into the line buffer at the cursor position.  This calls
+   :c:func:`rl_insert_text` in the underlying library, but ignores
+   the return value.
 
 
-.. function:: read_init_file([filename])
+.. function:: redisplay()
 
-   Parse a readline initialization file. The default filename is the last filename
-   used.
+   Change what's displayed on the screen to reflect the current contents of the
+   line buffer.  This calls :c:func:`rl_redisplay` in the underlying library.
+
+
+History file
+------------
+
+The following functions operate on a history file:
 
 
 .. function:: read_history_file([filename])
 
-   Load a readline history file. The default filename is :file:`~/.history`.
+   Load a readline history file, and append it to the history list.
+   The default filename is :file:`~/.history`.  This calls
+   :c:func:`read_history` in the underlying library.
 
 
 .. function:: write_history_file([filename])
 
-   Save a readline history file. The default filename is :file:`~/.history`.
+   Save the history list to a readline history file, overwriting any
+   existing file.  The default filename is :file:`~/.history`.  This calls
+   :c:func:`write_history` in the underlying library.
 
 
-.. function:: clear_history()
+.. function:: get_history_length()
+              set_history_length(length)
 
-   Clear the current history.  (Note: this function is not available if the
-   installed version of GNU readline doesn't support it.)
+   Set or return the desired number of lines to save in the history file.
+   The :func:`write_history_file` function uses this value to truncate
+   the history file, by calling :c:func:`history_truncate_file` in
+   the underlying library.  Negative values imply
+   unlimited history file size.
 
-   .. versionadded:: 2.4
 
+History list
+------------
 
-.. function:: get_history_length()
+The following functions operate on a global history list:
 
-   Return the desired length of the history file.  Negative values imply unlimited
-   history file size.
 
+.. function:: clear_history()
 
-.. function:: set_history_length(length)
+   Clear the current history.  This calls :c:func:`clear_history` in the
+   underlying library.  The Python function only exists if Python was
+   compiled for a version of the library that supports it.
 
-   Set the number of lines to save in the history file. :func:`write_history_file`
-   uses this value to truncate the history file when saving.  Negative values imply
-   unlimited history file size.
+   .. versionadded:: 2.4
 
 
 .. function:: get_current_history_length()
 
-   Return the number of lines currently in the history.  (This is different from
+   Return the number of items currently in the history.  (This is different from
    :func:`get_history_length`, which returns the maximum number of lines that will
    be written to a history file.)
 
@@ -91,7 +134,8 @@ The :mod:`readline` module defines the following functions:
 
 .. function:: get_history_item(index)
 
-   Return the current contents of history item at *index*.
+   Return the current contents of history item at *index*.  The item index
+   is one-based.  This calls :c:func:`history_get` in the underlying library.
 
    .. versionadded:: 2.3
 
@@ -99,42 +143,63 @@ The :mod:`readline` module defines the following functions:
 .. function:: remove_history_item(pos)
 
    Remove history item specified by its position from the history.
+   The position is zero-based.  This calls :c:func:`remove_history` in
+   the underlying library.
 
    .. versionadded:: 2.4
 
 
 .. function:: replace_history_item(pos, line)
 
-   Replace history item specified by its position with the given line.
+   Replace history item specified by its position with *line*.
+   The position is zero-based.  This calls :c:func:`replace_history_entry`
+   in the underlying library.
 
    .. versionadded:: 2.4
 
 
-.. function:: redisplay()
+.. function:: add_history(line)
 
-   Change what's displayed on the screen to reflect the current contents of the
-   line buffer.
+   Append *line* to the history buffer, as if it was the last line typed.
+   This calls :c:func:`add_history` in the underlying library.
+
+
+Startup hooks
+-------------
 
    .. versionadded:: 2.3
 
 
 .. function:: set_startup_hook([function])
 
-   Set or remove the startup_hook function.  If *function* is specified, it will be
-   used as the new startup_hook function; if omitted or ``None``, any hook function
-   already installed is removed.  The startup_hook function is called with no
+   Set or remove the function invoked by the :c:data:`rl_startup_hook`
+   callback of the underlying library.  If *function* is specified, it will
+   be used as the new hook function; if omitted or ``None``, any function
+   already installed is removed.  The hook is called with no
    arguments just before readline prints the first prompt.
 
 
 .. function:: set_pre_input_hook([function])
 
-   Set or remove the pre_input_hook function.  If *function* is specified, it will
-   be used as the new pre_input_hook function; if omitted or ``None``, any hook
-   function already installed is removed.  The pre_input_hook function is called
+   Set or remove the function invoked by the :c:data:`rl_pre_input_hook`
+   callback of the underlying library.  If *function* is specified, it will
+   be used as the new hook function; if omitted or ``None``, any
+   function already installed is removed.  The hook is called
    with no arguments after the first prompt has been printed and just before
    readline starts reading input characters.
 
 
+Completion
+----------
+
+The following functions relate to implementing a custom word completion
+function.  This is typically operated by the Tab key, and can suggest and
+automatically complete a word being typed.  By default, Readline is set up
+to be used by :mod:`rlcompleter` to complete Python identifiers for
+the interactive interpreter.  If the :mod:`readline` module is to be used
+with a custom completer, a different set of word delimiters should be set.
+
+
 .. function:: set_completer([function])
 
    Set or remove the completer function.  If *function* is specified, it will be
@@ -144,6 +209,12 @@ The :mod:`readline` module defines the following functions:
    returns a non-string value.  It should return the next possible completion
    starting with *text*.
 
+   The installed completer function is invoked by the *entry_func* callback
+   passed to :c:func:`rl_completion_matches` in the underlying library.
+   The *text* string comes from the first parameter to the
+   :c:data:`rl_attempted_completion_function` callback of the
+   underlying library.
+
 
 .. function:: get_completer()
 
@@ -154,50 +225,42 @@ The :mod:`readline` module defines the following functions:
 
 .. function:: get_completion_type()
 
-   Get the type of completion being attempted.
+   Get the type of completion being attempted.  This returns the
+   :c:data:`rl_completion_type` variable in the underlying library as
+   an integer.
 
    .. versionadded:: 2.6
 
 .. function:: get_begidx()
+              get_endidx()
 
-   Get the beginning index of the readline tab-completion scope.
-
-
-.. function:: get_endidx()
-
-   Get the ending index of the readline tab-completion scope.
+   Get the beginning or ending index of the completion scope.
+   These indexes are the *start* and *end* arguments passed to the
+   :c:data:`rl_attempted_completion_function` callback of the
+   underlying library.
 
 
 .. function:: set_completer_delims(string)
+              get_completer_delims()
 
-   Set the readline word delimiters for tab-completion.
-
-
-.. function:: get_completer_delims()
-
-   Get the readline word delimiters for tab-completion.
+   Set or get the word delimiters for completion.  These determine the
+   start of the word to be considered for completion (the completion scope).
+   These functions access the :c:data:`rl_completer_word_break_characters`
+   variable in the underlying library.
 
 .. function:: set_completion_display_matches_hook([function])
 
    Set or remove the completion display function.  If *function* is
    specified, it will be used as the new completion display function;
    if omitted or ``None``, any completion display function already
-   installed is removed.  The completion display function is called as
+   installed is removed.  This sets or clears the
+   :c:data:`rl_completion_display_matches_hook` callback in the
+   underlying library.  The completion display function is called as
    ``function(substitution, [matches], longest_match_length)`` once
    each time matches need to be displayed.
 
    .. versionadded:: 2.6
 
-.. function:: add_history(line)
-
-   Append a line to the history buffer, as if it was the last line typed.
-
-.. seealso::
-
-   Module :mod:`rlcompleter`
-      Completion of Python identifiers at the interactive prompt.
-
-
 .. _readline-example:
 
 Example
@@ -214,6 +277,8 @@ normally be executed automatically during interactive sessions from the user's
    histfile = os.path.join(os.path.expanduser("~"), ".pyhist")
    try:
        readline.read_history_file(histfile)
+       # default history len is -1 (infinite), which may grow unruly
+       readline.set_history_length(1000)
    except IOError:
        pass
    import atexit
@@ -244,5 +309,6 @@ support history save/restore. ::
                atexit.register(self.save_history, histfile)
 
        def save_history(self, histfile):
+           readline.set_history_length(1000)
            readline.write_history_file(histfile)
 
index f6d6058..517a60b 100644 (file)
@@ -44,7 +44,7 @@ this module for those platforms.
 
 .. data:: RLIM_INFINITY
 
-   Constant used to represent the the limit for an unlimited resource.
+   Constant used to represent the limit for an unlimited resource.
 
 
 .. function:: getrlimit(resource)
index a40d1e9..80f6344 100644 (file)
@@ -34,7 +34,7 @@ the built-in :func:`open` function so that it raises an exception whenever the
 *mode* parameter is ``'w'``.  It might also perform a :c:func:`chroot`\ -like
 operation on the *filename* parameter, such that root is always relative to some
 safe "sandbox" area of the filesystem.  In this case, the untrusted code would
-still see an built-in :func:`open` function in its environment, with the same
+still see a built-in :func:`open` function in its environment, with the same
 calling interface.  The semantics would be identical too, with :exc:`IOError`\ s
 being raised when the supervisor determined that an unallowable parameter is
 being used.
index 24cb756..ad7deec 100644 (file)
@@ -305,7 +305,7 @@ Kqueue Objects
 Kevent Objects
 --------------
 
-http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
+https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
 
 .. attribute:: kevent.ident
 
index 7bd2931..6c5e183 100644 (file)
@@ -76,7 +76,8 @@ operations:
 +-------------------------------+------------+---------------------------------+
 | Operation                     | Equivalent | Result                          |
 +===============================+============+=================================+
-| ``len(s)``                    |            | cardinality of set *s*          |
+| ``len(s)``                    |            | number of elements in set *s*   |
+|                               |            | (cardinality)                   |
 +-------------------------------+------------+---------------------------------+
 | ``x in s``                    |            | test *x* for membership in *s*  |
 +-------------------------------+------------+---------------------------------+
index 84911fe..bffd535 100644 (file)
@@ -162,7 +162,7 @@ A single exception is defined as well:
 .. method:: SGMLParser.handle_entityref(ref)
 
    This method is called to process a general entity reference of the form
-   ``&ref;`` where *ref* is an general entity reference.  It converts *ref* by
+   ``&ref;`` where *ref* is a general entity reference.  It converts *ref* by
    passing it to :meth:`convert_entityref`.  If a translation is returned, it calls
    the method :meth:`handle_data` with the translation; otherwise, it calls the
    method ``unknown_entityref(ref)``. The default :attr:`entitydefs` defines
index b02f763..8c65790 100644 (file)
@@ -73,7 +73,7 @@ Two additional methods are supported:
 
 .. seealso::
 
-   `Persistent dictionary recipe <http://code.activestate.com/recipes/576642/>`_
+   `Persistent dictionary recipe <https://code.activestate.com/recipes/576642/>`_
    with widely supported storage formats and having the speed of native
    dictionaries.
 
index be08e01..fad6b76 100644 (file)
@@ -231,7 +231,8 @@ variables which either control lexical analysis or can be used for debugging:
    This attribute is ``None`` by default.  If you assign a string to it, that
    string will be recognized as a lexical-level inclusion request similar to the
    ``source`` keyword in various shells.  That is, the immediately following token
-   will opened as a filename and input taken from that stream until EOF, at which
+   will be opened as a filename and input will
+   be taken from that stream until EOF, at which
    point the :meth:`~io.IOBase.close` method of that stream will be called and
    the input source will again become the original input stream.  Source
    requests may be stacked any number of levels deep.
index d80ad57..f79eba6 100644 (file)
@@ -640,7 +640,7 @@ correspond to Unix system calls applicable to sockets.
 
    The :meth:`ioctl` method is a limited interface to the WSAIoctl system
    interface.  Please refer to the `Win32 documentation
-   <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
+   <https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
    information.
 
    On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
index bb933a6..a7c3e3e 100644 (file)
 
 The :mod:`SocketServer` module simplifies the task of writing network servers.
 
-There are four basic server classes: :class:`TCPServer` uses the Internet TCP
-protocol, which provides for continuous streams of data between the client and
-server.  :class:`UDPServer` uses datagrams, which are discrete packets of
-information that may arrive out of order or be lost while in transit.  The more
-infrequently used :class:`UnixStreamServer` and :class:`UnixDatagramServer`
-classes are similar, but use Unix domain sockets; they're not available on
-non-Unix platforms.  For more details on network programming, consult a book
-such as
-W. Richard Steven's UNIX Network Programming or Ralph Davis's Win32 Network
-Programming.
+There are four basic concrete server classes:
+
+
+.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
+
+   This uses the Internet TCP protocol, which provides for
+   continuous streams of data between the client and server.
+   If *bind_and_activate* is true, the constructor automatically attempts to
+   invoke :meth:`~BaseServer.server_bind` and
+   :meth:`~BaseServer.server_activate`.  The other parameters are passed to
+   the :class:`BaseServer` base class.
+
+
+.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
+
+   This uses datagrams, which are discrete packets of information that may
+   arrive out of order or be lost while in transit.  The parameters are
+   the same as for :class:`TCPServer`.
+
+
+.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
+           UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)
+
+   These more infrequently used classes are similar to the TCP and
+   UDP classes, but use Unix domain sockets; they're not available on
+   non-Unix platforms.  The parameters are the same as for
+   :class:`TCPServer`.
+
 
 These four classes process requests :dfn:`synchronously`; each request must be
 completed before the next request can be started.  This isn't suitable if each
@@ -37,10 +55,12 @@ support asynchronous behaviour.
 
 Creating a server requires several steps.  First, you must create a request
 handler class by subclassing the :class:`BaseRequestHandler` class and
-overriding its :meth:`handle` method; this method will process incoming
+overriding its :meth:`~BaseRequestHandler.handle` method;
+this method will process incoming
 requests.  Second, you must instantiate one of the server classes, passing it
 the server's address and the request handler class.  Then call the
-:meth:`handle_request` or :meth:`serve_forever` method of the server object to
+:meth:`~BaseServer.handle_request` or
+:meth:`~BaseServer.serve_forever` method of the server object to
 process one or many requests.  Finally, call :meth:`~BaseServer.server_close`
 to close the socket.
 
@@ -81,18 +101,36 @@ Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
 stream server is the address family, which is simply repeated in both Unix
 server classes.
 
-Forking and threading versions of each type of server can be created using the
-:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes.  For instance,
-a threading UDP server class is created as follows::
 
-   class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+.. class:: ForkingMixIn
+           ThreadingMixIn
+
+   Forking and threading versions of each type of server can be created
+   using these mix-in classes.  For instance, :class:`ThreadingUDPServer`
+   is created as follows::
+
+      class ThreadingUDPServer(ThreadingMixIn, UDPServer):
+          pass
+
+   The mix-in class comes first, since it overrides a method defined in
+   :class:`UDPServer`.  Setting the various attributes also changes the
+   behavior of the underlying server mechanism.
+
+   :class:`ForkingMixIn` and the Forking classes mentioned below are
+   only available on POSIX platforms that support :func:`~os.fork`.
+
+
+.. class:: ForkingTCPServer
+           ForkingUDPServer
+           ThreadingTCPServer
+           ThreadingUDPServer
+
+   These classes are pre-defined using the mix-in classes.
 
-The mix-in class must come first, since it overrides a method defined in
-:class:`UDPServer`.  Setting the various attributes also change the
-behavior of the underlying server mechanism.
 
 To implement a service, you must derive a class from :class:`BaseRequestHandler`
-and redefine its :meth:`handle` method.  You can then run various versions of
+and redefine its :meth:`~BaseRequestHandler.handle` method.
+You can then run various versions of
 the service by combining one of the server classes with your request handler
 class.  The request handler class must be different for datagram or stream
 services.  This can be hidden by using the handler subclasses
@@ -114,7 +152,7 @@ has requested.  Here a threading or forking server is appropriate.
 In some cases, it may be appropriate to process part of a request synchronously,
 but to finish processing in a forked child depending on the request data.  This
 can be implemented by using a synchronous server and doing an explicit fork in
-the request handler class :meth:`handle` method.
+the request handler class :meth:`~BaseRequestHandler.handle` method.
 
 Another approach to handling multiple simultaneous requests in an environment
 that supports neither threads nor :func:`~os.fork` (or where these are too
@@ -132,215 +170,230 @@ connected for a long time (if threads or subprocesses cannot be used). See
 Server Objects
 --------------
 
-.. class:: BaseServer
+.. class:: BaseServer(server_address, RequestHandlerClass)
 
    This is the superclass of all Server objects in the module.  It defines the
    interface, given below, but does not implement most of the methods, which is
-   done in subclasses.
+   done in subclasses.  The two parameters are stored in the respective
+   :attr:`server_address` and :attr:`RequestHandlerClass` attributes.
+
+
+   .. method:: fileno()
+
+      Return an integer file descriptor for the socket on which the server is
+      listening.  This function is most commonly passed to :func:`select.select`, to
+      allow monitoring multiple servers in the same process.
+
 
+   .. method:: handle_request()
 
-.. method:: BaseServer.fileno()
+      Process a single request.  This function calls the following methods in
+      order: :meth:`get_request`, :meth:`verify_request`, and
+      :meth:`process_request`.  If the user-provided
+      :meth:`~BaseRequestHandler.handle` method of the
+      handler class raises an exception, the server's :meth:`handle_error` method
+      will be called.  If no request is received within :attr:`timeout`
+      seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
+      will return.
 
-   Return an integer file descriptor for the socket on which the server is
-   listening.  This function is most commonly passed to :func:`select.select`, to
-   allow monitoring multiple servers in the same process.
 
+   .. method:: serve_forever(poll_interval=0.5)
 
-.. method:: BaseServer.handle_request()
+      Handle requests until an explicit :meth:`shutdown` request.  Poll for
+      shutdown every *poll_interval* seconds.
+      Ignores the :attr:`timeout` attribute.
+      If you need to do periodic tasks, do them in another thread.
 
-   Process a single request.  This function calls the following methods in
-   order: :meth:`get_request`, :meth:`verify_request`, and
-   :meth:`process_request`.  If the user-provided :meth:`handle` method of the
-   handler class raises an exception, the server's :meth:`handle_error` method
-   will be called.  If no request is received within :attr:`self.timeout`
-   seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
-   will return.
 
+   .. method:: shutdown()
 
-.. method:: BaseServer.serve_forever(poll_interval=0.5)
+      Tell the :meth:`serve_forever` loop to stop and wait until it does.
 
-   Handle requests until an explicit :meth:`shutdown` request.
-   Poll for shutdown every *poll_interval* seconds. Ignores :attr:`self.timeout`.
-   If you need to do periodic tasks, do them in another thread.
+      .. versionadded:: 2.6
 
 
-.. method:: BaseServer.shutdown()
+   .. method:: server_close()
 
-   Tell the :meth:`serve_forever` loop to stop and wait until it does.
+      Clean up the server. May be overridden.
 
-   .. versionadded:: 2.6
+      .. versionadded:: 2.6
 
 
-.. method:: BaseServer.server_close()
+   .. attribute:: address_family
 
-   Clean up the server. May be overridden.
+      The family of protocols to which the server's socket belongs.
+      Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
 
-   .. versionadded:: 2.6
 
+   .. attribute:: RequestHandlerClass
 
-.. attribute:: BaseServer.address_family
+      The user-provided request handler class; an instance of this class is created
+      for each request.
 
-   The family of protocols to which the server's socket belongs.
-   Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
 
+   .. attribute:: server_address
 
-.. attribute:: BaseServer.RequestHandlerClass
+      The address on which the server is listening.  The format of addresses varies
+      depending on the protocol family;
+      see the documentation for the :mod:`socket` module
+      for details.  For Internet protocols, this is a tuple containing a string giving
+      the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
 
-   The user-provided request handler class; an instance of this class is created
-   for each request.
 
+   .. attribute:: socket
 
-.. attribute:: BaseServer.server_address
+      The socket object on which the server will listen for incoming requests.
 
-   The address on which the server is listening.  The format of addresses varies
-   depending on the protocol family; see the documentation for the socket module
-   for details.  For Internet protocols, this is a tuple containing a string giving
-   the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
 
+   The server classes support the following class variables:
 
-.. attribute:: BaseServer.socket
+   .. XXX should class variables be covered before instance variables, or vice versa?
 
-   The socket object on which the server will listen for incoming requests.
+   .. attribute:: allow_reuse_address
 
+      Whether the server will allow the reuse of an address. This defaults to
+      :const:`False`, and can be set in subclasses to change the policy.
 
-The server classes support the following class variables:
 
-.. XXX should class variables be covered before instance variables, or vice versa?
+   .. attribute:: request_queue_size
 
-.. attribute:: BaseServer.allow_reuse_address
+      The size of the request queue.  If it takes a long time to process a single
+      request, any requests that arrive while the server is busy are placed into a
+      queue, up to :attr:`request_queue_size` requests.  Once the queue is full,
+      further requests from clients will get a "Connection denied" error.  The default
+      value is usually 5, but this can be overridden by subclasses.
 
-   Whether the server will allow the reuse of an address. This defaults to
-   :const:`False`, and can be set in subclasses to change the policy.
 
+   .. attribute:: socket_type
 
-.. attribute:: BaseServer.request_queue_size
+      The type of socket used by the server; :const:`socket.SOCK_STREAM` and
+      :const:`socket.SOCK_DGRAM` are two common values.
 
-   The size of the request queue.  If it takes a long time to process a single
-   request, any requests that arrive while the server is busy are placed into a
-   queue, up to :attr:`request_queue_size` requests.  Once the queue is full,
-   further requests from clients will get a "Connection denied" error.  The default
-   value is usually 5, but this can be overridden by subclasses.
 
+   .. attribute:: timeout
 
-.. attribute:: BaseServer.socket_type
+      Timeout duration, measured in seconds, or :const:`None` if no timeout is
+      desired.  If :meth:`handle_request` receives no incoming requests within the
+      timeout period, the :meth:`handle_timeout` method is called.
 
-   The type of socket used by the server; :const:`socket.SOCK_STREAM` and
-   :const:`socket.SOCK_DGRAM` are two common values.
 
+   There are various server methods that can be overridden by subclasses of base
+   server classes like :class:`TCPServer`; these methods aren't useful to external
+   users of the server object.
 
-.. attribute:: BaseServer.timeout
+   .. XXX should the default implementations of these be documented, or should
+      it be assumed that the user will look at SocketServer.py?
 
-   Timeout duration, measured in seconds, or :const:`None` if no timeout is
-   desired.  If :meth:`handle_request` receives no incoming requests within the
-   timeout period, the :meth:`handle_timeout` method is called.
+   .. method:: finish_request()
 
+      Actually processes the request by instantiating :attr:`RequestHandlerClass` and
+      calling its :meth:`~BaseRequestHandler.handle` method.
 
-There are various server methods that can be overridden by subclasses of base
-server classes like :class:`TCPServer`; these methods aren't useful to external
-users of the server object.
 
-.. XXX should the default implementations of these be documented, or should
-   it be assumed that the user will look at SocketServer.py?
+   .. method:: get_request()
 
-.. method:: BaseServer.finish_request()
+      Must accept a request from the socket, and return a 2-tuple containing the *new*
+      socket object to be used to communicate with the client, and the client's
+      address.
 
-   Actually processes the request by instantiating :attr:`RequestHandlerClass` and
-   calling its :meth:`handle` method.
 
+   .. method:: handle_error(request, client_address)
 
-.. method:: BaseServer.get_request()
+      This function is called if the :meth:`~BaseRequestHandler.handle`
+      method of a :attr:`RequestHandlerClass` instance raises
+      an exception.  The default action is to print the traceback to
+      standard output and continue handling further requests.
 
-   Must accept a request from the socket, and return a 2-tuple containing the *new*
-   socket object to be used to communicate with the client, and the client's
-   address.
 
+   .. method:: handle_timeout()
 
-.. method:: BaseServer.handle_error(request, client_address)
+      This function is called when the :attr:`timeout` attribute has been set to a
+      value other than :const:`None` and the timeout period has passed with no
+      requests being received.  The default action for forking servers is
+      to collect the status of any child processes that have exited, while
+      in threading servers this method does nothing.
 
-   This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle`
-   method raises an exception.  The default action is to print the traceback to
-   standard output and continue handling further requests.
 
+   .. method:: process_request(request, client_address)
 
-.. method:: BaseServer.handle_timeout()
+      Calls :meth:`finish_request` to create an instance of the
+      :attr:`RequestHandlerClass`.  If desired, this function can create a new process
+      or thread to handle the request; the :class:`ForkingMixIn` and
+      :class:`ThreadingMixIn` classes do this.
 
-   This function is called when the :attr:`timeout` attribute has been set to a
-   value other than :const:`None` and the timeout period has passed with no
-   requests being received.  The default action for forking servers is
-   to collect the status of any child processes that have exited, while
-   in threading servers this method does nothing.
 
+   .. Is there any point in documenting the following two functions?
+      What would the purpose of overriding them be: initializing server
+      instance variables, adding new network families?
 
-.. method:: BaseServer.process_request(request, client_address)
+   .. method:: server_activate()
 
-   Calls :meth:`finish_request` to create an instance of the
-   :attr:`RequestHandlerClass`.  If desired, this function can create a new process
-   or thread to handle the request; the :class:`ForkingMixIn` and
-   :class:`ThreadingMixIn` classes do this.
+      Called by the server's constructor to activate the server.  The default behavior
+      for a TCP server just invokes :meth:`~socket.socket.listen`
+      on the server's socket. May be overridden.
 
 
-.. Is there any point in documenting the following two functions?
-   What would the purpose of overriding them be: initializing server
-   instance variables, adding new network families?
+   .. method:: server_bind()
 
-.. method:: BaseServer.server_activate()
+      Called by the server's constructor to bind the socket to the desired address.
+      May be overridden.
 
-   Called by the server's constructor to activate the server.  The default behavior
-   just :meth:`listen`\ s to the server's socket. May be overridden.
 
+   .. method:: verify_request(request, client_address)
 
-.. method:: BaseServer.server_bind()
+      Must return a Boolean value; if the value is :const:`True`, the request will be
+      processed, and if it's :const:`False`, the request will be denied. This function
+      can be overridden to implement access controls for a server. The default
+      implementation always returns :const:`True`.
 
-   Called by the server's constructor to bind the socket to the desired address.
-   May be overridden.
 
+Request Handler Objects
+-----------------------
 
-.. method:: BaseServer.verify_request(request, client_address)
+.. class:: BaseRequestHandler
 
-   Must return a Boolean value; if the value is :const:`True`, the request will be
-   processed, and if it's :const:`False`, the request will be denied. This function
-   can be overridden to implement access controls for a server. The default
-   implementation always returns :const:`True`.
+   This is the superclass of all request handler objects.  It defines
+   the interface, given below.  A concrete request handler subclass must
+   define a new :meth:`handle` method, and can override any of
+   the other methods.  A new instance of the subclass is created for each
+   request.
 
 
-RequestHandler Objects
-----------------------
+   .. method:: setup()
 
-The request handler class must define a new :meth:`handle` method, and can
-override any of the following methods.  A new instance is created for each
-request.
+      Called before the :meth:`handle` method to perform any initialization actions
+      required.  The default implementation does nothing.
 
 
-.. method:: RequestHandler.finish()
+   .. method:: handle()
 
-   Called after the :meth:`handle` method to perform any clean-up actions
-   required.  The default implementation does nothing.  If :meth:`setup`
-   raises an exception, this function will not be called.
+      This function must do all the work required to service a request.  The
+      default implementation does nothing.  Several instance attributes are
+      available to it; the request is available as :attr:`self.request`; the client
+      address as :attr:`self.client_address`; and the server instance as
+      :attr:`self.server`, in case it needs access to per-server information.
 
+      The type of :attr:`self.request` is different for datagram or stream
+      services.  For stream services, :attr:`self.request` is a socket object; for
+      datagram services, :attr:`self.request` is a pair of string and socket.
 
-.. method:: RequestHandler.handle()
 
-   This function must do all the work required to service a request.  The
-   default implementation does nothing.  Several instance attributes are
-   available to it; the request is available as :attr:`self.request`; the client
-   address as :attr:`self.client_address`; and the server instance as
-   :attr:`self.server`, in case it needs access to per-server information.
+   .. method:: finish()
 
-   The type of :attr:`self.request` is different for datagram or stream
-   services.  For stream services, :attr:`self.request` is a socket object; for
-   datagram services, :attr:`self.request` is a pair of string and socket.
-   However, this can be hidden by using the request handler subclasses
-   :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
-   override the :meth:`setup` and :meth:`finish` methods, and provide
-   :attr:`self.rfile` and :attr:`self.wfile` attributes.  :attr:`self.rfile` and
-   :attr:`self.wfile` can be read or written, respectively, to get the request
-   data or return data to the client.
+      Called after the :meth:`handle` method to perform any clean-up actions
+      required.  The default implementation does nothing.  If :meth:`setup`
+      raises an exception, this function will not be called.
 
 
-.. method:: RequestHandler.setup()
+.. class:: StreamRequestHandler
+           DatagramRequestHandler
 
-   Called before the :meth:`handle` method to perform any initialization actions
-   required.  The default implementation does nothing.
+   These :class:`BaseRequestHandler` subclasses override the
+   :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
+   methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
+   The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
+   read or written, respectively, to get the request data or return data
+   to the client.
 
 
 Examples
@@ -355,7 +408,7 @@ This is the server side::
 
    class MyTCPHandler(SocketServer.BaseRequestHandler):
        """
-       The RequestHandler class for our server.
+       The request handler class for our server.
 
        It is instantiated once per connection to the server, and must
        override the handle() method to implement communication to the
@@ -562,3 +615,4 @@ The output of the example should look something like this::
 
 The :class:`ForkingMixIn` class is used in the same way, except that the server
 will spawn a new process for each request.
+Available only on POSIX platforms that support :func:`~os.fork`.
index ff634c0..f897234 100644 (file)
@@ -55,7 +55,7 @@ The data you've saved is persistent and is available in subsequent sessions::
 Usually your SQL operations will need to use values from Python variables.  You
 shouldn't assemble your query using Python's string operations because doing so
 is insecure; it makes your program vulnerable to an SQL injection attack
-(see http://xkcd.com/327/ for humorous example of what can go wrong).
+(see https://xkcd.com/327/ for humorous example of what can go wrong).
 
 Instead, use the DB-API's parameter substitution.  Put ``?`` as a placeholder
 wherever you want to use a value, and then provide a tuple of values as the
@@ -101,7 +101,7 @@ This example uses the iterator form::
       The pysqlite web page -- sqlite3 is developed externally under the name
       "pysqlite".
 
-   http://www.sqlite.org
+   https://www.sqlite.org
       The SQLite web page; the documentation describes the syntax and the
       available data types for the supported SQL dialect.
 
@@ -595,6 +595,18 @@ Cursor Objects
 
       It is set for ``SELECT`` statements without any matching rows as well.
 
+   .. attribute:: connection
+
+      This read-only attribute provides the SQLite database :class:`Connection`
+      used by the :class:`Cursor` object.  A :class:`Cursor` object created by
+      calling :meth:`con.cursor() <Connection.cursor>` will have a
+      :attr:`connection` attribute that refers to *con*::
+
+         >>> con = sqlite3.connect(":memory:")
+         >>> cur = con.cursor()
+         >>> cur.connection == con
+         True
+
 .. _sqlite3-row-objects:
 
 Row Objects
index c18d2a0..9d8d080 100644 (file)
@@ -206,7 +206,7 @@ instead.
 
    The *ciphers* parameter sets the available ciphers for this SSL object.
    It should be a string in the `OpenSSL cipher list format
-   <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
+   <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_.
 
    The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
    handshake automatically after doing a :meth:`socket.connect`, or whether the
@@ -280,6 +280,44 @@ purposes.
 
      RC4 was dropped from the default cipher string.
 
+.. function:: _https_verify_certificates(enable=True)
+
+   Specifies whether or not server certificates are verified when creating
+   client HTTPS connections without specifying a particular SSL context.
+
+   Starting with Python 2.7.9, :mod:`httplib` and modules which use it, such as
+   :mod:`urllib2` and :mod:`xmlrpclib`, default to verifying remote server
+   certificates received when establishing client HTTPS connections. This
+   default verification checks that the certificate is signed by a Certificate
+   Authority in the system trust store and that the Common Name (or Subject
+   Alternate Name) on the presented certificate matches the requested host.
+
+   Setting *enable* to :const:`True` ensures this default behaviour is in
+   effect.
+
+   Setting *enable* to :const:`False` reverts the default HTTPS certificate
+   handling to that of Python 2.7.8 and earlier, allowing connections to
+   servers using self-signed certificates, servers using certificates signed
+   by a Certicate Authority not present in the system trust store, and servers
+   where the hostname does not match the presented server certificate.
+
+   The leading underscore on this function denotes that it intentionally does
+   not exist in any implementation of Python 3 and may not be present in all
+   Python 2.7 implementations. The portable approach to bypassing certificate
+   checks or the system trust store when necessary is for tools to enable that
+   on a case-by-case basis by explicitly passing in a suitably configured SSL
+   context, rather than reverting the default behaviour of the standard library
+   client modules.
+
+   .. versionadded:: 2.7.12
+
+   .. seealso::
+
+      * `CVE-2014-9365 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9365>`_
+        -- HTTPS man-in-the-middle attack against Python clients using default settings
+      * :pep:`476` -- Enabling certificate verification by default for HTTPS
+      * :pep:`493` -- HTTPS verification migration tools for Python 2.7
+
 
 Random generation
 ^^^^^^^^^^^^^^^^^
@@ -675,7 +713,7 @@ Constants
 
    Whether the OpenSSL library has built-in support for *Next Protocol
    Negotiation* as described in the `NPN draft specification
-   <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
+   <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
    you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
    which protocols you want to support.
 
@@ -723,7 +761,7 @@ Constants
           ALERT_DESCRIPTION_*
 
    Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
-   <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
+   <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
    contains this list and references to the RFCs where their meaning is defined.
 
    Used as the return value of the callback function in
@@ -1024,7 +1062,7 @@ to speed up repeated connections from the same clients.
    The *capath* string, if present, is
    the path to a directory containing several CA certificates in PEM format,
    following an `OpenSSL specific layout
-   <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
+   <https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
 
    The *cadata* object, if present, is either an ASCII string of one or more
    PEM-encoded certificates or a bytes-like object of DER-encoded
@@ -1053,7 +1091,7 @@ to speed up repeated connections from the same clients.
 
    Set the available ciphers for sockets created with this context.
    It should be a string in the `OpenSSL cipher list format
-   <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
+   <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_.
    If no cipher can be selected (because compile-time options or other
    configuration forbids use of all the specified ciphers), an
    :class:`SSLError` will be raised.
@@ -1082,7 +1120,7 @@ to speed up repeated connections from the same clients.
    handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
    ordered by preference. The selection of a protocol will happen during the
    handshake, and will play out according to the `NPN draft specification
-   <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
+   <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
    successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
    return the agreed-upon protocol.
 
@@ -1192,7 +1230,7 @@ to speed up repeated connections from the same clients.
 
    Get statistics about the SSL sessions created or managed by this context.
    A dictionary is returned which maps the names of each `piece of information
-   <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
+   <https://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
    numeric values.  For example, here is the total number of hits and misses
    in the session cache since the context was created::
 
@@ -1414,7 +1452,7 @@ should use the following idiom::
    except ImportError:
        pass
    else:
-       ... # do something that requires SSL support
+       ...  # do something that requires SSL support
 
 Client-side operation
 ^^^^^^^^^^^^^^^^^^^^^
@@ -1684,7 +1722,7 @@ enabled when negotiating a SSL session is possible through the
 :meth:`SSLContext.set_ciphers` method.  Starting from Python 2.7.9, the
 ssl module disables certain weak ciphers by default, but you may want
 to further restrict the cipher choice. Be sure to read OpenSSL's documentation
-about the `cipher list format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
+about the `cipher list format <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_.
 If you want to check which ciphers are enabled by a given cipher list, use the
 ``openssl ciphers`` command on your system.
 
@@ -1705,26 +1743,26 @@ successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
    Class :class:`socket.socket`
        Documentation of underlying :mod:`socket` class
 
-   `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
+   `SSL/TLS Strong Encryption: An Introduction <https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
        Intro from the Apache webserver documentation
 
-   `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
+   `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <https://www.ietf.org/rfc/rfc1422>`_
        Steve Kent
 
-   `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
+   `RFC 1750: Randomness Recommendations for Security <https://www.ietf.org/rfc/rfc1750>`_
        D. Eastlake et. al.
 
-   `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
+   `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <https://www.ietf.org/rfc/rfc3280>`_
        Housley et. al.
 
-   `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
+   `RFC 4366: Transport Layer Security (TLS) Extensions <https://www.ietf.org/rfc/rfc4366>`_
        Blake-Wilson et. al.
 
-   `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <http://tools.ietf.org/html/rfc5246>`_
+   `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <https://tools.ietf.org/html/rfc5246>`_
        T. Dierks et. al.
 
-   `RFC 6066: Transport Layer Security (TLS) Extensions <http://tools.ietf.org/html/rfc6066>`_
+   `RFC 6066: Transport Layer Security (TLS) Extensions <https://tools.ietf.org/html/rfc6066>`_
        D. Eastlake
 
-   `IANA TLS: Transport Layer Security (TLS) Parameters <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
+   `IANA TLS: Transport Layer Security (TLS) Parameters <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
        IANA
index 94bfac1..5d8ebbc 100644 (file)
@@ -393,19 +393,22 @@ Notes:
 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
 :class:`float`) also include the following operations:
 
-+--------------------+------------------------------------+--------+
-| Operation          | Result                             | Notes  |
-+====================+====================================+========+
-| ``math.trunc(x)``  | *x* truncated to Integral          |        |
-+--------------------+------------------------------------+--------+
-| ``round(x[, n])``  | *x* rounded to n digits,           |        |
-|                    | rounding ties away from zero. If n |        |
-|                    | is omitted, it defaults to 0.      |        |
-+--------------------+------------------------------------+--------+
-| ``math.floor(x)``  | the greatest integral float <= *x* |        |
-+--------------------+------------------------------------+--------+
-| ``math.ceil(x)``   | the least integral float >= *x*    |        |
-+--------------------+------------------------------------+--------+
++--------------------+---------------------------------------------+
+| Operation          | Result                                      |
++====================+=============================================+
+| :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` |
+| x) <math.trunc>`   |                                             |
++--------------------+---------------------------------------------+
+| :func:`round(x[,   | *x* rounded to *n* digits,                  |
+| n]) <round>`       | rounding ties away from zero. If *n*        |
+|                    | is omitted, it defaults to 0.               |
++--------------------+---------------------------------------------+
+| :func:`math.floor(\| the greatest integer as a float <= *x*      |
+| x) <math.floor>`   |                                             |
++--------------------+---------------------------------------------+
+| :func:`math.ceil(x)| the least integer as a float >= *x*         |
+| <math.ceil>`       |                                             |
++--------------------+---------------------------------------------+
 
 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
 
@@ -963,10 +966,9 @@ string functions based on regular expressions.
 
 .. method:: str.find(sub[, start[, end]])
 
-   Return the lowest index in the string where substring *sub* is found, such
-   that *sub* is contained in the slice ``s[start:end]``.  Optional arguments
-   *start* and *end* are interpreted as in slice notation.  Return ``-1`` if
-   *sub* is not found.
+   Return the lowest index in the string where substring *sub* is found within
+   the slice ``s[start:end]``.  Optional arguments *start* and *end* are
+   interpreted as in slice notation.  Return ``-1`` if *sub* is not found.
 
    .. note::
 
@@ -1780,7 +1782,7 @@ The constructors for both classes work the same:
 
    .. describe:: len(s)
 
-      Return the cardinality of set *s*.
+      Return the number of elements in set *s* (cardinality of *s*).
 
    .. describe:: x in s
 
@@ -2747,7 +2749,7 @@ is generally interpreted as simple bytes.
    .. attribute:: shape
 
       A tuple of integers the length of :attr:`ndim` giving the shape of the
-      memory as a N-dimensional array.
+      memory as an N-dimensional array.
 
    .. attribute:: ndim
 
@@ -2951,13 +2953,13 @@ need to explicitly set it on the underlying function object::
 See :ref:`types` for more information.
 
 
+.. index:: object; code, code object
+
 .. _bltin-code-objects:
 
 Code Objects
 ------------
 
-.. index:: object: code
-
 .. index::
    builtin: compile
    single: func_code (function object attribute)
index b0ffb6a..55733b9 100644 (file)
@@ -105,8 +105,8 @@ The constants defined in this module are:
 
 .. _new-string-formatting:
 
-String Formatting
------------------
+Custom String Formatting
+------------------------
 
 .. versionadded:: 2.6
 
@@ -115,7 +115,7 @@ to do complex variable substitutions and value formatting via the
 :meth:`str.format` method described in :pep:`3101`.  The :class:`Formatter`
 class in the :mod:`string` module allows you to create and customize your own
 string formatting behaviors using the same implementation as the built-in
-:meth:`format` method.
+:meth:`~str.format` method.
 
 .. class:: Formatter
 
@@ -123,9 +123,9 @@ string formatting behaviors using the same implementation as the built-in
 
    .. method:: format(format_string, *args, **kwargs)
 
-      :meth:`format` is the primary API method.  It takes a format string and
+      The primary API method.  It takes a format string and
       an arbitrary set of positional and keyword arguments.
-      :meth:`format` is just a wrapper that calls :meth:`vformat`.
+      It is just a wrapper that calls :meth:`vformat`.
 
    .. method:: vformat(format_string, args, kwargs)
 
@@ -262,12 +262,12 @@ does an index lookup using :func:`__getitem__`.
 
 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
@@ -293,8 +293,9 @@ Most built-in types support a common formatting mini-language, which is
 described in the next section.
 
 A *format_spec* field can also include nested replacement fields within it.
-These nested replacement fields can contain only a field name; conversion flags
-and format specifications are not allowed.  The replacement fields within the
+These nested replacement fields may contain a field name, conversion flag
+and format specification, but deeper nesting is
+not allowed.  The replacement fields within the
 format_spec are substituted before the *format_spec* string is interpreted.
 This allows the formatting of a value to be dynamically specified.
 
@@ -332,8 +333,10 @@ The general form of a *standard format specifier* is:
 
 If a valid *align* value is specified, it can be preceded by a *fill*
 character that can be any character and defaults to a space if omitted.
-Note that it is not possible to use ``{`` and ``}`` as *fill* char while
-using the :meth:`str.format` method; this limitation however doesn't
+It is not possible to use a literal curly brace ("``{``" or "``}``") as
+the *fill* character when using the :meth:`str.format`
+method.  However, it is possible to insert a curly brace
+with a nested replacement field.  This limitation doesn't
 affect the :func:`format` function.
 
 The meaning of the various alignment options is as follows:
@@ -350,7 +353,8 @@ The meaning of the various alignment options is as follows:
    | ``'='`` | Forces the padding to be placed after the sign (if any)  |
    |         | but before the digits.  This is used for printing fields |
    |         | in the form '+000000120'. This alignment option is only  |
-   |         | valid for numeric types.                                 |
+   |         | valid for numeric types.  It becomes the default when '0'|
+   |         | immediately precedes the field width.                    |
    +---------+----------------------------------------------------------+
    | ``'^'`` | Forces the field to be centered within the available     |
    |         | space.                                                   |
@@ -390,7 +394,8 @@ instead.
 *width* is a decimal integer defining the minimum field width.  If not
 specified, then the field width will be determined by the content.
 
-Preceding the *width* field by a zero (``'0'``) character enables
+When no explicit alignment is given, preceding the *width* field by a zero
+(``'0'``) character enables
 sign-aware zero-padding for numeric types.  This is equivalent to a *fill*
 character of ``'0'`` with an *alignment* type of ``'='``.
 
@@ -508,8 +513,8 @@ The available presentation types for floating point and decimal values are:
 Format examples
 ^^^^^^^^^^^^^^^
 
-This section contains examples of the new format syntax and comparison with
-the old ``%``-formatting.
+This section contains examples of the :meth:`str.format` syntax and
+comparison with the old ``%``-formatting.
 
 In most of the cases the syntax is similar to the old ``%``-formatting, with the
 addition of the ``{}`` and with ``:`` used instead of ``%``.
index 01a791c..86a42ae 100644 (file)
@@ -404,7 +404,7 @@ functions.
       `side-by-side assembly`_ the specified *env* **must** include a valid
       :envvar:`SystemRoot`.
 
-   .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
+   .. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly
 
    If *universal_newlines* is ``True``, the file objects *stdout* and *stderr*
    are opened as text files in :term:`universal newlines` mode.  Lines may be
@@ -586,7 +586,7 @@ on Windows.
 .. class:: STARTUPINFO()
 
    Partial support of the Windows
-   `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
+   `STARTUPINFO <https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
    structure is used for :class:`Popen` creation.
 
    .. attribute:: dwFlags
@@ -622,7 +622,7 @@ on Windows.
       If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
       can be any of the values that can be specified in the ``nCmdShow``
       parameter for the
-      `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
+      `ShowWindow <https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
       function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
       ignored.
 
index 187204e..f09a4d6 100644 (file)
@@ -123,7 +123,7 @@ methods (except ``control`` objects which only provide :meth:`getinfo`,
 .. method:: audio device.setinfo(status)
 
    This method sets the audio device status parameters. The *status* parameter is
-   an device status object as returned by :func:`getinfo` and possibly modified by
+   a device status object as returned by :func:`getinfo` and possibly modified by
    the program.
 
 
index 75bde66..c819bf5 100644 (file)
@@ -79,8 +79,8 @@ Some facts and figures:
    for *name*. It is supposed to be at position 0.
 
    For modes ``'w:gz'``, ``'r:gz'``, ``'w:bz2'``, ``'r:bz2'``, :func:`tarfile.open`
-   accepts the keyword argument *compresslevel* to specify the compression level of
-   the file.
+   accepts the keyword argument *compresslevel* (default ``9``) to
+   specify the compression level of the file.
 
    For special purposes, there is a second format for *mode*:
    ``'filemode|[compression]'``.  :func:`tarfile.open` will return a :class:`TarFile`
@@ -90,7 +90,7 @@ Some facts and figures:
    specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
    in combination with e.g. ``sys.stdin``, a socket file object or a tape
    device. However, such a :class:`TarFile` object is limited in that it does
-   not allow to be accessed randomly, see :ref:`tar-examples`.  The currently
+   not allow random access, see :ref:`tar-examples`.  The currently
    possible modes:
 
    +-------------+--------------------------------------------+
@@ -110,10 +110,10 @@ Some facts and figures:
    +-------------+--------------------------------------------+
    | ``'w|'``    | Open an uncompressed *stream* for writing. |
    +-------------+--------------------------------------------+
-   | ``'w|gz'``  | Open an gzip compressed *stream* for       |
+   | ``'w|gz'``  | Open a gzip compressed *stream* for        |
    |             | writing.                                   |
    +-------------+--------------------------------------------+
-   | ``'w|bz2'`` | Open an bzip2 compressed *stream* for      |
+   | ``'w|bz2'`` | Open a bzip2 compressed *stream* for       |
    |             | writing.                                   |
    +-------------+--------------------------------------------+
 
@@ -229,7 +229,7 @@ details.
       Documentation of the higher-level archiving facilities provided by the
       standard :mod:`shutil` module.
 
-   `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
+   `GNU tar manual, Basic Tar Format <https://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
       Documentation for tar archive files, including GNU tar extensions.
 
 
@@ -438,20 +438,29 @@ be finalized; only the internally used file object will be closed. See the
 
    Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
    ``tarinfo.size`` bytes are read from it and added to the archive.  You can
-   create :class:`TarInfo` objects using :meth:`gettarinfo`.
+   create :class:`TarInfo` objects directly, or by using :meth:`gettarinfo`.
 
    .. note::
-
       On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
       avoid irritation about the file size.
 
 
 .. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
 
-   Create a :class:`TarInfo` object for either the file *name* or the file object
-   *fileobj* (using :func:`os.fstat` on its file descriptor).  You can modify some
-   of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
-   If given, *arcname* specifies an alternative name for the file in the archive.
+   Create a :class:`TarInfo` object from the result of :func:`os.stat` or
+   equivalent on an existing file.  The file is either named by *name*, or
+   specified as a file object *fileobj* with a file descriptor.  If
+   given, *arcname* specifies an alternative name for the file in the
+   archive, otherwise, the name is taken from *fileobj*’s
+   :attr:`~file.name` attribute, or the *name* argument.
+
+   You can modify some
+   of the :class:`TarInfo`’s attributes before you add it using :meth:`addfile`.
+   If the file object is not an ordinary file object positioned at the
+   beginning of the file, attributes such as :attr:`~TarInfo.size` may need
+   modifying.  This is the case for objects such as :class:`~gzip.GzipFile`.
+   The :attr:`~TarInfo.name` may also be modified, in which case *arcname*
+   could be a dummy string.
 
 
 .. method:: TarFile.close()
index 67eda21..fa0a27f 100644 (file)
@@ -64,7 +64,8 @@ The module defines the following user-callable functions:
    This function operates exactly as :func:`TemporaryFile` does, except that
    the file is guaranteed to have a visible name in the file system (on
    Unix, the directory entry is not unlinked).  That name can be retrieved
-   from the :attr:`name` attribute of the file object.  Whether the name can be
+   from the :attr:`name` attribute of the returned
+   file-like object.  Whether the name can be
    used to open the file a second time, while the named temporary file is
    still open, varies across platforms (it can be so used on Unix; it cannot
    on Windows NT or later).  If *delete* is true (the default), the file is
index 2b1be7b..aeafac5 100644 (file)
    pair: POSIX; I/O control
    pair: tty; I/O control
 
-This module provides an interface to the POSIX calls for tty I/O control.  For a
-complete description of these calls, see the POSIX or Unix manual pages.  It is
-only available for those Unix versions that support POSIX *termios* style tty
-I/O control (and then only if configured at installation time).
+This module provides an interface to the POSIX calls for tty I/O control. For a
+complete description of these calls, see :manpage:`termios(2)` Unix manual
+page.  It is only available for those Unix versions that support POSIX
+*termios* style tty I/O control configured during installation.
 
 All functions in this module take a file descriptor *fd* as their first
 argument.  This can be an integer file descriptor, such as returned by
index 434ef5a..be5a9e9 100644 (file)
@@ -171,7 +171,7 @@ the test passed or failed and thus minimize output.
 Running :mod:`test.regrtest` directly allows what resources are available for
 tests to use to be set. You do this by using the ``-u`` command-line
 option. Specifying ``all`` as the value for the ``-u`` option enables all
-possible resources: :program:`python -m test -uall`.
+possible resources: :program:`python -m test.regrtest -uall`.
 If all but one resource is desired (a more common case), a
 comma-separated list of resources that are not desired may be listed after
 ``all``. The command :program:`python -m test.regrtest -uall,-audio,-largefile`
@@ -418,7 +418,7 @@ The :mod:`test.test_support` module defines the following functions:
    Module and package deprecation messages are suppressed during this import
    if *deprecated* is :const:`True`.
 
-   This function will raise :exc:`unittest.SkipTest` is the named module
+   This function will raise :exc:`unittest.SkipTest` if the named module
    cannot be imported.
 
    Example use::
index ccb922b..e16f78c 100644 (file)
@@ -778,7 +778,7 @@ For example::
        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={})
index c2ea834..b4de643 100644 (file)
@@ -427,9 +427,12 @@ The module defines the following functions and data items:
 
    Note that unlike the C structure, the month value is a range of [1, 12], not
    [0, 11].  A year value will be handled as described under :ref:`Year 2000
-   (Y2K) issues <time-y2kissues>` above.  A ``-1`` argument as the daylight
-   savings flag, passed to :func:`mktime` will usually result in the correct
-   daylight savings state to be filled in.
+   (Y2K) issues <time-y2kissues>` above.
+
+   In calls to :func:`mktime`, :attr:`tm_isdst` may be set to 1 when daylight
+   savings time is in effect, and 0 when it is not.  A value of -1 indicates
+   that this is not known, and will usually result in the correct state being
+   filled in.
 
    When a tuple with an incorrect length is passed to a function expecting a
    :class:`struct_time`, or having elements of the wrong type, a
index 2cb3c9d..e7b3548 100644 (file)
@@ -16,7 +16,7 @@
 --------------
 
 This module provides a simple way to time small bits of Python code. It has both
-a :ref:`command-line-interface` as well as a :ref:`callable <python-interface>`
+a :ref:`timeit-command-line-interface` as well as a :ref:`callable <python-interface>`
 one.  It avoids a number of common traps for measuring execution times.
 See also Tim Peters' introduction to the "Algorithms" chapter in the *Python
 Cookbook*, published by O'Reilly.
@@ -25,7 +25,7 @@ Cookbook*, published by O'Reilly.
 Basic Examples
 --------------
 
-The following example shows how the :ref:`command-line-interface`
+The following example shows how the :ref:`timeit-command-line-interface`
 can be used to compare three different expressions:
 
 .. code-block:: sh
@@ -170,7 +170,7 @@ The module defines three convenience functions and a public class:
       where the traceback is sent; it defaults to :data:`sys.stderr`.
 
 
-.. _command-line-interface:
+.. _timeit-command-line-interface:
 
 Command-Line Interface
 ----------------------
index a2f31a0..ed6948f 100644 (file)
@@ -127,7 +127,7 @@ Basic Widgets
    The `ComboBox
    <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm>`_
    widget is similar to the combo box control in MS Windows. The user can select a
-   choice by either typing in the entry subwdget or selecting from the listbox
+   choice by either typing in the entry subwidget or selecting from the listbox
    subwidget.
 
 .. Python Demo of:
@@ -151,7 +151,7 @@ Basic Widgets
 
    The `LabelEntry
    <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm>`_
-   widget packages an entry widget and a label into one mega widget. It can be used
+   widget packages an entry widget and a label into one mega widget. It can
    be used to simplify the creation of "entry-form" type of interface.
 
 .. Python Demo of:
@@ -276,7 +276,7 @@ File Selectors
 
    The `ExFileSelectBox
    <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm>`_
-   widget is usually embedded in a tixExFileSelectDialog widget. It provides an
+   widget is usually embedded in a tixExFileSelectDialog widget. It provides a
    convenient method for the user to select files. The style of the
    :class:`ExFileSelectBox` widget is very similar to the standard file dialog on
    MS Windows 3.1.
index fa60c15..ab1da52 100644 (file)
@@ -26,22 +26,22 @@ is maintained at ActiveState.)
    `TKDocs <http://www.tkdocs.com/>`_
       Extensive tutorial plus friendlier widget pages for some of the widgets.
 
-   `Tkinter reference: a GUI for Python <http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html>`_
+   `Tkinter reference: a GUI for Python <https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html>`_
       On-line reference material.
 
    `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
       Online reference for tkinter supported by effbot.org.
 
-   `Tcl/Tk manual <http://www.tcl.tk/man/tcl8.5/>`_
+   `Tcl/Tk manual <https://www.tcl.tk/man/tcl8.5/>`_
       Official manual for the latest tcl/tk version.
 
-   `Programming Python <http://www.rmi.net/~lutz/about-pp4e.html>`_
+   `Programming Python <http://learning-python.com/books/about-pp4e.html>`_
       Book by Mark Lutz, has excellent coverage of Tkinter.
 
    `Modern Tkinter for Busy Python Developers <http://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
       Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.
 
-   `Python and Tkinter Programming <http://www.manning.com/grayson/>`_
+   `Python and Tkinter Programming <https://www.manning.com/books/python-and-tkinter-programming>`_
       The book by John Grayson (ISBN 1-884777-81-3).
 
 
index 3f25a2c..f4e4783 100644 (file)
@@ -28,7 +28,7 @@ The primary entry point is a :term:`generator`:
 
    The :func:`generate_tokens` generator requires one argument, *readline*,
    which must be a callable object which provides the same interface as the
-   :meth:`readline` method of built-in file objects (see section
+   :meth:`~file.readline` method of built-in file objects (see section
    :ref:`bltin-file-objects`).  Each call to the function should return one line
    of input as a string. Alternately, *readline* may be a callable object that
    signals completion by raising :exc:`StopIteration`.
@@ -47,11 +47,11 @@ An older entry point is retained for backward compatibility:
 
 .. function:: tokenize(readline[, tokeneater])
 
-   The :func:`tokenize` function accepts two parameters: one representing the input
-   stream, and one providing an output mechanism for :func:`tokenize`.
+   The :func:`.tokenize` function accepts two parameters: one representing the input
+   stream, and one providing an output mechanism for :func:`.tokenize`.
 
    The first parameter, *readline*, must be a callable object which provides the
-   same interface as the :meth:`readline` method of built-in file objects (see
+   same interface as the :meth:`~file.readline` method of built-in file objects (see
    section :ref:`bltin-file-objects`).  Each call to the function should return one
    line of input as a string. Alternately, *readline* may be a callable object that
    signals completion by raising :exc:`StopIteration`.
@@ -65,7 +65,7 @@ An older entry point is retained for backward compatibility:
 
 All constants from the :mod:`token` module are also exported from
 :mod:`tokenize`, as are two additional token type values that might be passed to
-the *tokeneater* function by :func:`tokenize`:
+the *tokeneater* function by :func:`.tokenize`:
 
 
 .. data:: COMMENT
index 6859d4b..7c78235 100644 (file)
@@ -14,29 +14,30 @@ interpreter.
 .. index:: object: traceback
 
 The module uses traceback objects --- this is the object type that is stored in
-the variables :data:`sys.exc_traceback` (deprecated) and :data:`sys.last_traceback` and
-returned as the third item from :func:`sys.exc_info`.
+the variables :data:`sys.exc_traceback` (deprecated) and
+:data:`sys.last_traceback` and returned as the third item from
+:func:`sys.exc_info`.
 
 The module defines the following functions:
 
 
-.. function:: print_tb(traceback[, limit[, file]])
+.. function:: print_tb(tb[, limit[, file]])
 
-   Print up to *limit* stack trace entries from *traceback*.  If *limit* is omitted
-   or ``None``, all entries are printed. If *file* is omitted or ``None``, the
-   output goes to ``sys.stderr``; otherwise it should be an open file or file-like
-   object to receive the output.
+   Print up to *limit* stack trace entries from the traceback object *tb*. If
+   *limit* is omitted or ``None``, all entries are printed. If *file* is omitted
+   or ``None``, the output goes to ``sys.stderr``; otherwise it should be an
+   open file or file-like object to receive the output.
 
 
-.. function:: print_exception(type, value, traceback[, limit[, file]])
+.. function:: print_exception(etype, value, tb[, limit[, file]])
 
-   Print exception information and up to *limit* stack trace entries from
-   *traceback* to *file*. This differs from :func:`print_tb` in the following ways:
-   (1) if *traceback* is not ``None``, it prints a header ``Traceback (most recent
-   call last):``; (2) it prints the exception *type* and *value* after the stack
-   trace; (3) if *type* is :exc:`SyntaxError` and *value* has the appropriate
-   format, it prints the line where the syntax error occurred with a caret
-   indicating the approximate position of the error.
+   Print exception information and up to *limit* stack trace entries from the
+   traceback *tb* to *file*. This differs from :func:`print_tb` in the following
+   ways: (1) if *tb* is not ``None``, it prints a header ``Traceback (most
+   recent call last):``; (2) it prints the exception *etype* and *value* after
+   the stack trace; (3) if *etype* is :exc:`SyntaxError` and *value* has the
+   appropriate format, it prints the line where the syntax error occurred with a
+   caret indicating the approximate position of the error.
 
 
 .. function:: print_exc([limit[, file]])
@@ -49,8 +50,8 @@ The module defines the following functions:
 
 .. function:: format_exc([limit])
 
-   This is like ``print_exc(limit)`` but returns a string instead of printing to a
-   file.
+   This is like ``print_exc(limit)`` but returns a string instead of printing to
+   file.
 
    .. versionadded:: 2.4
 
@@ -64,21 +65,21 @@ The module defines the following functions:
 
 .. function:: print_stack([f[, limit[, file]]])
 
-   This function prints a stack trace from its invocation point.  The optional *f*
-   argument can be used to specify an alternate stack frame to start.  The optional
-   *limit* and *file* arguments have the same meaning as for
+   This function prints a stack trace from its invocation point. The optional
+   *f* argument can be used to specify an alternate stack frame to start. The
+   optional limit* and *file* arguments have the same meaning as for
    :func:`print_exception`.
 
 
-.. function:: extract_tb(traceback[, limit])
+.. function:: extract_tb(tb[, limit])
 
    Return a list of up to *limit* "pre-processed" stack trace entries extracted
-   from the traceback object *traceback*.  It is useful for alternate formatting of
-   stack traces.  If *limit* is omitted or ``None``, all entries are extracted.  A
-   "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*,
-   *function name*, *text*) representing the information that is usually printed
-   for a stack trace.  The *text* is a string with leading and trailing whitespace
-   stripped; if the source is not available it is ``None``.
+   from the traceback object *tb*.  It is useful for alternate formatting of
+   stack traces.  If *limit* is omitted or ``None``, all entries are extracted.
+   "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*,
+   function name*, *text*) representing the information that is usually printed
+   for a stack trace.  The *text* is a string with leading and trailing
+   whitespace stripped; if the source is not available it is ``None``.
 
 
 .. function:: extract_stack([f[, limit]])
@@ -88,33 +89,35 @@ The module defines the following functions:
    arguments have the same meaning as for :func:`print_stack`.
 
 
-.. function:: format_list(list)
+.. function:: format_list(extracted_list)
 
    Given a list of tuples as returned by :func:`extract_tb` or
-   :func:`extract_stack`, return a list of strings ready for printing.  Each string
-   in the resulting list corresponds to the item with the same index in the
-   argument list.  Each string ends in a newline; the strings may contain internal
-   newlines as well, for those items whose source text line is not ``None``.
+   :func:`extract_stack`, return a list of strings ready for printing.  Each
+   string in the resulting list corresponds to the item with the same index in
+   the argument list.  Each string ends in a newline; the strings may contain
+   internal newlines as well, for those items whose source text line is not
+   ``None``.
 
 
-.. function:: format_exception_only(type, value)
+.. function:: format_exception_only(etype, value)
 
-   Format the exception part of a traceback.  The arguments are the exception type
-   and value such as given by ``sys.last_type`` and ``sys.last_value``.  The return
-   value is a list of strings, each ending in a newline.  Normally, the list
-   contains a single string; however, for :exc:`SyntaxError` exceptions, it
-   contains several lines that (when printed) display detailed information about
-   where the syntax error occurred.  The message indicating which exception
-   occurred is the always last string in the list.
+   Format the exception part of a traceback.  The arguments are the exception
+   type, *etype* and *value* such as given by ``sys.last_type`` and
+   ``sys.last_value``.  The return value is a list of strings, each ending in a
+   newline.  Normally, the list contains a single string; however, for
+   :exc:`SyntaxError` exceptions, it contains several lines that (when printed)
+   display detailed information about where the syntax error occurred.  The
+   message indicating which exception occurred is the always last string in the
+   list.
 
 
-.. function:: format_exception(type, value, tb[, limit])
+.. function:: format_exception(etype, value, tb[, limit])
 
    Format a stack trace and the exception information.  The arguments  have the
    same meaning as the corresponding arguments to :func:`print_exception`.  The
-   return value is a list of strings, each ending in a newline and some containing
-   internal newlines.  When these lines are concatenated and printed, exactly the
-   same text is printed as does :func:`print_exception`.
+   return value is a list of strings, each ending in a newline and some
+   containing internal newlines.  When these lines are concatenated and printed,
+   exactly the same text is printed as does :func:`print_exception`.
 
 
 .. function:: format_tb(tb[, limit])
@@ -129,10 +132,10 @@ The module defines the following functions:
 
 .. function:: tb_lineno(tb)
 
-   This function returns the current line number set in the traceback object.  This
-   function was necessary because in versions of Python prior to 2.3 when the
-   :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not updated
-   correctly.  This function has no use in versions past 2.3.
+   This function returns the current line number set in the traceback object.
+   This function was necessary because in versions of Python prior to 2.3 when
+   the :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not
+   updated correctly.  This function has no use in versions past 2.3.
 
 
 .. _traceback-example:
index ad4aa92..c458e73 100644 (file)
@@ -21,7 +21,7 @@ implementing a widget's behavior from the code implementing its appearance.
 
 .. seealso::
 
-   `Tk Widget Styling Support <http://www.tcl.tk/cgi-bin/tct/tip/48>`_
+   `Tk Widget Styling Support <https://www.tcl.tk/cgi-bin/tct/tip/48>`_
       The document which brought up theming support for Tk
 
 
@@ -293,7 +293,7 @@ Besides the methods inherited from :class:`Widget` (:meth:`Widget.cget`,
 :meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate`
 and :meth:`Widget.state`) and those inherited from :class:`Entry`
 (:meth:`Entry.bbox`, :meth:`Entry.delete`, :meth:`Entry.icursor`,
-:meth:`Entry.index`, :meth:`Entry.inset`, :meth:`Entry.selection`,
+:meth:`Entry.index`, :meth:`Entry.insert`, :meth:`Entry.selection`,
 :meth:`Entry.xview`), this class has some other methods, described at
 :class:`ttk.Combobox`.
 
@@ -686,7 +686,7 @@ the widget option ``displaycolumns``. The tree widget can also display column
 headings. Columns may be accessed by number or symbolic names listed in the
 widget option columns. See `Column Identifiers`_.
 
-Each item is identified by an unique name. The widget will generate item IDs
+Each item is identified by a unique name. The widget will generate item IDs
 if they are not supplied by the caller. There is a distinguished root item,
 named ``{}``. The root item itself is not displayed; its children appear at the
 top level of the hierarchy.
index 77cf014..5d7c987 100644 (file)
@@ -147,7 +147,7 @@ The module defines the following names:
 
 .. data:: InstanceType
 
-   The type of instances of user-defined classes.
+   The type of instances of user-defined old-style classes.
 
 
 .. data:: MethodType
index ca91cd7..64a1834 100644 (file)
@@ -115,19 +115,19 @@ Here is a short script to test three string methods::
 
   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()
@@ -147,7 +147,7 @@ and produce a report.
 
 The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
 to define instructions that will be executed before and after each test method.
-They are covered in more details in the section :ref:`organizing-tests`.
+They are covered in more detail in the section :ref:`organizing-tests`.
 
 The final block shows a simple way to run the tests. :func:`unittest.main`
 provides a command-line interface to the test script.  When run from the command
@@ -720,10 +720,12 @@ Test cases
       Method called immediately after the test method has been called and the
       result recorded.  This is called even if the test method raised an
       exception, so the implementation in subclasses may need to be particularly
-      careful about checking internal state.  Any exception, other than :exc:`AssertionError`
-      or :exc:`SkipTest`, raised by this method will be considered an error rather than a
-      test failure.  This method will only be called if the :meth:`setUp` succeeds,
-      regardless of the outcome of the test method. The default implementation does nothing.
+      careful about checking internal state.  Any exception, other than
+      :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
+      considered an additional error rather than a test failure (thus increasing
+      the total number of reported errors). This method will only be called if
+      the :meth:`setUp` succeeds, regardless of the outcome of the test method.
+      The default implementation does nothing.
 
 
    .. method:: setUpClass()
@@ -783,8 +785,9 @@ Test cases
 
    .. _assert-methods:
 
-   The :class:`TestCase` class provides a number of methods to check for and
-   report failures, such as:
+   The :class:`TestCase` class provides several assert methods to check for and
+   report failures.  The following table lists the most commonly used methods
+   (see the tables below for more assert methods):
 
    +-----------------------------------------+-----------------------------+---------------+
    | Method                                  | Checks that                 | New in        |
@@ -1763,9 +1766,10 @@ Loading and running tests
    instead of repeatedly creating new instances.
 
 
-.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1)
+.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, \
+                          failfast=False, buffer=False, resultclass=None)
 
-   A basic test runner implementation which prints results on standard error.  It
+   A basic test runner implementation which prints results on standard error. It
    has a few configurable parameters, but is essentially very simple.  Graphical
    applications which run test suites should provide alternate implementations.
 
index 927696a..3b5dc16 100644 (file)
@@ -27,7 +27,7 @@ reading, and no seek operations are available.
 .. seealso::
 
     The `Requests package <http://requests.readthedocs.org/>`_
-    is recommended for a higher-level http client interface.
+    is recommended for a higher-level HTTP client interface.
 
 .. warning:: When opening HTTPS URLs, it does not attempt to validate the
    server certificate.  Use at your own risk!
@@ -118,7 +118,7 @@ High-level interface
    causes environmental proxy settings to be used as discussed above.  For
    example::
 
-      # Use http://www.someproxy.com:3128 for http proxying
+      # Use http://www.someproxy.com:3128 for HTTP proxying
       proxies = {'http': 'http://www.someproxy.com:3128'}
       filehandle = urllib.urlopen(some_url, proxies=proxies)
       # Don't use any proxies
@@ -280,7 +280,7 @@ Utility functions
 
 .. function:: url2pathname(path)
 
-   Convert the path component *path* from an percent-encoded URL to the local syntax for a
+   Convert the path component *path* from a percent-encoded URL to the local syntax for a
    path.  This does not accept a complete URL.  This function uses :func:`unquote`
    to decode *path*.
 
@@ -292,11 +292,13 @@ Utility functions
    in case insensitive way, for all operating systems first, and when it cannot
    find it, looks for proxy information from Mac OSX System Configuration for
    Mac OS X and Windows Systems Registry for Windows.
+   If both lowercase and uppercase environment variables exist (and disagree),
+   lowercase is preferred.
 
 .. note::
     urllib also exposes certain utility functions like splittype, splithost and
-    others parsing url into various components. But it is recommended to use
-    :mod:`urlparse` for parsing urls rather than using these functions directly.
+    others parsing URL into various components. But it is recommended to use
+    :mod:`urlparse` for parsing URLs rather than using these functions directly.
     Python 3 does not expose these helper functions from :mod:`urllib.parse`
     module.
 
index 3fe4f25..8a4c80e 100644 (file)
@@ -21,7 +21,7 @@ redirections, cookies and more.
 .. seealso::
 
     The `Requests package <http://requests.readthedocs.org/>`_
-    is recommended for a higher-level http client interface.
+    is recommended for a higher-level HTTP client interface.
 
 
 The :mod:`urllib2` module defines the following functions:
@@ -64,7 +64,7 @@ The :mod:`urllib2` module defines the following functions:
 
    * :meth:`info` --- return the meta-information of the page, such as headers,
      in the form of an :class:`mimetools.Message` instance
-     (see `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
+     (see `Quick Reference to HTTP Headers <https://www.cs.tut.fi/~jkorpela/http.html>`_)
 
    * :meth:`getcode` --- return the HTTP status code of the response.
 
@@ -167,7 +167,7 @@ The following classes are provided:
 
    *headers* should be a dictionary, and will be treated as if :meth:`add_header`
    was called with each key and value as arguments.  This is often used to "spoof"
-   the ``User-Agent`` header, which is used by a browser to identify itself --
+   the ``User-Agent`` header value, which is used by a browser to identify itself --
    some HTTP servers only allow requests coming from common browsers as opposed
    to scripts.  For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
    (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s
@@ -950,6 +950,9 @@ HTTPErrorProcessor Objects
 Examples
 --------
 
+In addition to the examples below, more examples are given in
+:ref:`urllib-howto`.
+
 This example gets the python.org main page and displays the first 100 bytes of
 it::
 
@@ -1016,6 +1019,8 @@ Use the *headers* argument to the :class:`Request` constructor, or::
    import urllib2
    req = urllib2.Request('http://www.example.com/')
    req.add_header('Referer', 'http://www.python.org/')
+   # Customize the default User-Agent header value:
+   req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
    r = urllib2.urlopen(req)
 
 :class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
index c119190..1f05e5b 100644 (file)
@@ -258,7 +258,7 @@ The :mod:`urlparse` module defines the following functions:
 
    .. doctest::
 
-      >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
+      >>> urljoin('https://www.cwi.nl/%7Eguido/Python.html',
       ...         '//www.python.org/%7Eguido')
       'http://www.python.org/%7Eguido'
 
@@ -279,7 +279,7 @@ The :mod:`urlparse` module defines the following functions:
    :rfc:`3986` - Uniform Resource Identifiers
       This is the current standard (STD66). Any changes to urlparse module
       should conform to this. Certain deviations could be observed, which are
-      mostly due backward compatiblity purposes and for certain de-facto
+      mostly for backward compatibility purposes and for certain de-facto
       parsing requirements as commonly observed in major browsers.
 
    :rfc:`2732` - Format for Literal IPv6 Addresses in URL's.
@@ -290,7 +290,7 @@ The :mod:`urlparse` module defines the following functions:
       Names (URNs) and Uniform Resource Locators (URLs).
 
    :rfc:`2368` - The mailto URL scheme.
-      Parsing requirements for mailto url schemes.
+      Parsing requirements for mailto URL schemes.
 
    :rfc:`1808` - Relative Uniform Resource Locators
       This Request For Comments includes the rules for joining an absolute and a
@@ -337,22 +337,12 @@ described in those functions, as well as provide an additional method:
 The following classes provide the implementations of the parse results:
 
 
-.. class:: BaseResult
-
-   Base class for the concrete result classes.  This provides most of the attribute
-   definitions.  It does not provide a :meth:`geturl` method.  It is derived from
-   :class:`tuple`, but does not override the :meth:`__init__` or :meth:`__new__`
-   methods.
-
-
 .. class:: ParseResult(scheme, netloc, path, params, query, fragment)
 
-   Concrete class for :func:`urlparse` results.  The :meth:`__new__` method is
-   overridden to support checking that the right number of arguments are passed.
+   Concrete class for :func:`urlparse` results.
 
 
 .. class:: SplitResult(scheme, netloc, path, query, fragment)
 
-   Concrete class for :func:`urlsplit` results.  The :meth:`__new__` method is
-   overridden to support checking that the right number of arguments are passed.
+   Concrete class for :func:`urlsplit` results.
 
index 27658d6..40a0770 100644 (file)
@@ -256,7 +256,7 @@ Updating Code For New Versions of Python
 
 Warnings that are only of interest to the developer are ignored by default. As
 such you should make sure to test your code with typically ignored warnings
-made visible. You can do this from the command-line by passing :option:`-Wd`
+made visible. You can do this from the command-line by passing :option:`-Wd <-W>`
 to the interpreter (this is shorthand for :option:`-W default`).  This enables
 default handling for all warnings, including those that are ignored by default.
 To change what action is taken for encountered warnings you simply change what
index 1c3cdbb..e5a99ea 100644 (file)
@@ -245,7 +245,7 @@ methods of :class:`WeakKeyDictionary` objects.
 
 .. seealso::
 
-   :pep:`0205` - Weak References
+   :pep:`205` - Weak References
       The proposal and rationale for this feature, including links to earlier
       implementations and information about similar features in other languages.
 
index e6e7ea2..f74b89f 100644 (file)
@@ -33,7 +33,7 @@ browsers are not available on Unix, the controlling process will launch a new
 browser and wait.
 
 The script :program:`webbrowser` can be used as a command-line interface for the
-module. It accepts an URL as the argument. It accepts the following optional
+module. It accepts a URL as the argument. It accepts the following optional
 parameters: ``-n`` opens the URL in a new browser window, if possible;
 ``-t`` opens the URL in a new browser page ("tab"). The options are,
 naturally, mutually exclusive.  Usage example::
@@ -144,6 +144,14 @@ for the controller classes, all defined in this module.
 +-----------------------+-----------------------------------------+-------+
 | ``'safari'``          | :class:`MacOSX('safari')`               | \(3)  |
 +-----------------------+-----------------------------------------+-------+
+| ``'google-chrome'``   | :class:`Chrome('google-chrome')`        | \(4)  |
++-----------------------+-----------------------------------------+-------+
+| ``'chrome'``          | :class:`Chrome('chrome')`               | \(4)  |
++-----------------------+-----------------------------------------+-------+
+| ``'chromium'``        | :class:`Chromium('chromium')`           | \(4)  |
++-----------------------+-----------------------------------------+-------+
+| ``'chromium-browser'``| :class:`Chromium('chromium-browser')`   | \(4)  |
++-----------------------+-----------------------------------------+-------+
 
 Notes:
 
@@ -160,6 +168,9 @@ Notes:
 (3)
    Only on Mac OS X platform.
 
+(4)
+   Support for Chrome/Chromium has been added in version 2.7.5.
+
 Here are some simple examples::
 
    url = 'http://www.python.org/'
index 98989c3..e755d18 100644 (file)
@@ -26,8 +26,8 @@ for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
 and a validation tool that checks WSGI servers and applications for conformance
 to the WSGI specification (:pep:`333`).
 
-See http://www.wsgi.org for more information about WSGI, and links to tutorials
-and other resources.
+See https://wsgi.readthedocs.org/ for more information about WSGI, and links to
+tutorials and other resources.
 
 .. XXX If you're just trying to write a web application...
 
@@ -418,8 +418,8 @@ Paste" library.
       # 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 @@ This is a working "Hello World" WSGI application::
    # 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
index 4e7cd5a..b6d46fc 100644 (file)
@@ -33,10 +33,10 @@ DOM applications typically start by parsing some XML into a DOM.  With
 
    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>')
 
@@ -107,7 +107,7 @@ eventually take care of the objects in the tree.
 
 .. seealso::
 
-   `Document Object Model (DOM) Level 1 Specification <http://www.w3.org/TR/REC-DOM-Level-1/>`_
+   `Document Object Model (DOM) Level 1 Specification <https://www.w3.org/TR/REC-DOM-Level-1/>`_
       The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.
 
 
@@ -275,5 +275,5 @@ utility to most DOM users.
 
 .. [#] The encoding string included in XML output should conform to the
    appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
-   not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
-   and http://www.iana.org/assignments/character-sets/character-sets.xhtml.
+   not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
+   and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
index 6dba900..4d98015 100644 (file)
@@ -73,10 +73,10 @@ implementations are free to support the strict mapping from IDL).  See section
 
 .. seealso::
 
-   `Document Object Model (DOM) Level 2 Specification <http://www.w3.org/TR/DOM-Level-2-Core/>`_
+   `Document Object Model (DOM) Level 2 Specification <https://www.w3.org/TR/DOM-Level-2-Core/>`_
       The W3C recommendation upon which the Python DOM API is based.
 
-   `Document Object Model (DOM) Level 1 Specification <http://www.w3.org/TR/REC-DOM-Level-1/>`_
+   `Document Object Model (DOM) Level 1 Specification <https://www.w3.org/TR/REC-DOM-Level-1/>`_
       The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.
 
    `Python Language Mapping Specification <http://www.omg.org/spec/PYTH/1.2/PDF>`_
@@ -127,7 +127,7 @@ Some convenience constants are also provided:
 .. data:: XML_NAMESPACE
 
    The namespace URI associated with the reserved prefix ``xml``, as defined by
-   `Namespaces in XML <http://www.w3.org/TR/REC-xml-names/>`_ (section 4).
+   `Namespaces in XML <https://www.w3.org/TR/REC-xml-names/>`_ (section 4).
 
    .. versionadded:: 2.2
 
@@ -136,7 +136,7 @@ Some convenience constants are also provided:
 
    The namespace URI for namespace declarations, as defined by `Document Object
    Model (DOM) Level 2 Core Specification
-   <http://www.w3.org/TR/DOM-Level-2-Core/core.html>`_ (section 1.1.8).
+   <https://www.w3.org/TR/DOM-Level-2-Core/core.html>`_ (section 1.1.8).
 
    .. versionadded:: 2.2
 
@@ -144,7 +144,7 @@ Some convenience constants are also provided:
 .. data:: XHTML_NAMESPACE
 
    The URI of the XHTML namespace as defined by `XHTML 1.0: The Extensible
-   HyperText Markup Language <http://www.w3.org/TR/xhtml1/>`_ (section 3.1.1).
+   HyperText Markup Language <https://www.w3.org/TR/xhtml1/>`_ (section 3.1.1).
 
    .. versionadded:: 2.2
 
@@ -431,7 +431,7 @@ objects:
 .. method:: NodeList.item(i)
 
    Return the *i*'th item from the sequence, if there is one, or ``None``.  The
-   index *i* is not allowed to be less then zero or greater than or equal to the
+   index *i* is not allowed to be less than zero or greater than or equal to the
    length of the sequence.
 
 
@@ -895,7 +895,7 @@ attribute.
 .. exception:: NamespaceErr
 
    If an attempt is made to change any object in a way that is not permitted with
-   regard to the `Namespaces in XML <http://www.w3.org/TR/REC-xml-names/>`_
+   regard to the `Namespaces in XML <https://www.w3.org/TR/REC-xml-names/>`_
    recommendation, this exception is raised.
 
 
index 212a9e1..20cfc4c 100644 (file)
@@ -129,7 +129,7 @@ As an :class:`Element`, ``root`` has a tag and a dictionary of attributes::
 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 @@ the sub-tree below it (its children, their children, and so on).  For example,
 :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 @@ with a particular tag, and :attr:`Element.text` accesses the element's text
 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 @@ Let's say we want to add one to each country's rank, and add an ``updated``
 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 @@ We can remove elements using :meth:`Element.remove`.  Let's say we want to
 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')
 
@@ -274,7 +274,7 @@ If the XML input has `namespaces
 with prefixes in the form ``prefix:sometag`` get expanded to
 ``{uri}sometag`` where the *prefix* is replaced by the full *URI*.
 Also, if there is a `default namespace
-<http://www.w3.org/TR/2006/REC-xml-names-20060816/#defaulting>`__,
+<https://www.w3.org/TR/2006/REC-xml-names-20060816/#defaulting>`__,
 that full URI gets prepended to all of the non-prefixed tags.
 
 Here is an XML example that incorporates two namespaces, one with the
@@ -345,7 +345,7 @@ XPath support
 -------------
 
 This module provides limited support for
-`XPath expressions <http://www.w3.org/TR/xpath>`_ for locating elements in a
+`XPath expressions <https://www.w3.org/TR/xpath>`_ for locating elements in a
 tree.  The goal is to support a small subset of the abbreviated syntax; a full
 XPath engine is outside the scope of the module.
 
@@ -887,6 +887,7 @@ Example of changing the attribute "target" of every link in first paragraph::
     [<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:
@@ -901,7 +902,7 @@ QName Objects
    to get proper namespace handling on output.  *text_or_uri* is a string
    containing the QName value, in the form {uri}local, or, if the tag argument
    is given, the URI part of a QName.  If *tag* is given, the first argument is
-   interpreted as an URI, and this argument is interpreted as a local name.
+   interpreted as a URI, and this argument is interpreted as a local name.
    :class:`QName` instances are opaque.
 
 
@@ -1032,5 +1033,5 @@ This is an example of counting the maximum depth of an XML file::
 
 .. [#] The encoding string included in XML output should conform to the
    appropriate standards.  For example, "UTF-8" is valid, but "UTF8" is
-   not.  See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
-   and http://www.iana.org/assignments/character-sets/character-sets.xhtml.
+   not.  See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
+   and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
index e56eb2c..1945e1b 100644 (file)
@@ -62,7 +62,7 @@ kind                       sax       etree      minidom    pulldom   xmlrpc
 billion laughs             **Yes**   **Yes**    **Yes**    **Yes**   **Yes**
 quadratic blowup           **Yes**   **Yes**    **Yes**    **Yes**   **Yes**
 external entity expansion  **Yes**   No    (1)  No    (2)  **Yes**   No    (3)
-DTD retrieval              **Yes**   No         No         **Yes**   No
+`DTD`_ retrieval           **Yes**   No         No         **Yes**   No
 decompression bomb         No        No         No         No        **Yes**
 =========================  ========  =========  =========  ========  =========
 
@@ -94,7 +94,7 @@ external entity expansion
   parser retrieves the resource with e.g. HTTP or FTP requests and embeds the
   content into the XML document.
 
-DTD retrieval
+`DTD`_ retrieval
   Some XML libraries like Python's :mod:`xml.dom.pulldom` retrieve document type
   definitions from remote or local locations. The feature has similar
   implications as the external entity expansion issue.
@@ -131,6 +131,6 @@ well-defined XML features.
 
 .. _defusedxml: https://pypi.python.org/pypi/defusedxml/
 .. _defusedexpat: https://pypi.python.org/pypi/defusedexpat/
-.. _Billion Laughs: http://en.wikipedia.org/wiki/Billion_laughs
-.. _ZIP bomb: http://en.wikipedia.org/wiki/Zip_bomb
-.. _DTD: http://en.wikipedia.org/wiki/Document_Type_Definition
+.. _Billion Laughs: https://en.wikipedia.org/wiki/Billion_laughs
+.. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb
+.. _DTD: https://en.wikipedia.org/wiki/Document_type_definition
index 6956cd1..14af050 100644 (file)
@@ -101,7 +101,7 @@ The :class:`XMLReader` interface supports the following methods:
 
    Process an input source, producing SAX events. The *source* object can be a
    system identifier (a string identifying the input source -- typically a file
-   name or an URL), a file-like object, or an :class:`InputSource` object. When
+   name or a URL), a file-like object, or an :class:`InputSource` object. When
    :meth:`parse` returns, the input is completely processed, and the parser object
    can be discarded or reset. As a limitation, the current implementation only
    accepts byte streams; processing of character streams is for further study.
@@ -229,12 +229,12 @@ Instances of :class:`Locator` provide these methods:
 
 .. method:: Locator.getColumnNumber()
 
-   Return the column number where the current event ends.
+   Return the column number where the current event begins.
 
 
 .. method:: Locator.getLineNumber()
 
-   Return the line number where the current event ends.
+   Return the line number where the current event begins.
 
 
 .. method:: Locator.getPublicId()
index 833dc7a..e818c3d 100644 (file)
@@ -21,7 +21,7 @@
 
 --------------
 
-XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
+XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a
 transport.  With it, a client can call methods with parameters on a remote
 server (the server is named by a URI) and get back structured data.  This module
 supports writing XML-RPC client code; it handles all the details of translating
@@ -36,8 +36,8 @@ between conformable Python objects and XML on the wire.
 
 .. versionchanged:: 2.7.9
 
-   For https URIs, :mod:`xmlrpclib` now performs all the necessary certificate
-   and hostname checks by default
+   For HTTPS URIs, :mod:`xmlrpclib` now performs all the necessary certificate
+   and hostname checks by default.
 
 .. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime[, context]]]]]])
 
@@ -48,11 +48,15 @@ between conformable Python objects and XML on the wire.
    :class:`SafeTransport` instance for https: URLs and an internal HTTP
    :class:`Transport` instance otherwise.  The optional third argument is an
    encoding, by default UTF-8. The optional fourth argument is a debugging flag.
+
+   The following parameters govern the use of the returned proxy instance.
    If *allow_none* is true,  the Python constant ``None`` will be translated into
    XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
    a commonly-used extension to the XML-RPC specification, but isn't supported by
-   all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a
-   description.  The *use_datetime* flag can be used to cause date/time values to
+   all clients and servers; see `http://ontosys.com/xml-rpc/extensions.php
+   <https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php>`_
+   for a description.
+   The *use_datetime* flag can be used to cause date/time values to
    be presented as :class:`datetime.datetime` objects; this is false by default.
    :class:`datetime.datetime` objects may be passed to calls.
 
@@ -61,7 +65,7 @@ between conformable Python objects and XML on the wire.
    portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
    the remote server as part of the connection process when invoking an XML-RPC
    method.  You only need to use this if the remote server requires a Basic
-   Authentication user and password. If an HTTPS url is provided, *context* may
+   Authentication user and password. If an HTTPS URL is provided, *context* may
    be :class:`ssl.SSLContext` and configures the SSL settings of the underlying
    HTTPS connection.
 
@@ -71,40 +75,42 @@ between conformable Python objects and XML on the wire.
    methods it supports (service discovery) and fetch other server-associated
    metadata.
 
-   :class:`ServerProxy` instance methods take Python basic types and objects as
-   arguments and return Python basic types and classes.  Types that are conformable
-   (e.g. that can be marshalled through XML), include the following (and except
-   where noted, they are unmarshalled as the same Python type):
-
-   +---------------------------------+---------------------------------------------+
-   | Name                            | Meaning                                     |
-   +=================================+=============================================+
-   | :const:`boolean`                | The :const:`True` and :const:`False`        |
-   |                                 | constants                                   |
-   +---------------------------------+---------------------------------------------+
-   | :const:`integers`               | Pass in directly                            |
-   +---------------------------------+---------------------------------------------+
-   | :const:`floating-point numbers` | Pass in directly                            |
-   +---------------------------------+---------------------------------------------+
-   | :const:`strings`                | Pass in directly                            |
-   +---------------------------------+---------------------------------------------+
-   | :const:`arrays`                 | Any Python sequence type containing         |
-   |                                 | conformable elements. Arrays are returned   |
-   |                                 | as lists                                    |
-   +---------------------------------+---------------------------------------------+
-   | :const:`structures`             | A Python dictionary. Keys must be strings,  |
-   |                                 | values may be any conformable type. Objects |
-   |                                 | of user-defined classes can be passed in;   |
-   |                                 | only their *__dict__* attribute is          |
-   |                                 | transmitted.                                |
-   +---------------------------------+---------------------------------------------+
-   | :const:`dates`                  | in seconds since the epoch (pass in an      |
-   |                                 | instance of the :class:`DateTime` class) or |
-   |                                 | a :class:`datetime.datetime` instance.      |
-   +---------------------------------+---------------------------------------------+
-   | :const:`binary data`            | pass in an instance of the :class:`Binary`  |
-   |                                 | wrapper class                               |
-   +---------------------------------+---------------------------------------------+
+   Types that are conformable (e.g. that can be marshalled through XML),
+   include the following (and except where noted, they are unmarshalled
+   as the same Python type):
+
+   .. tabularcolumns:: |l|L|
+
+   +----------------------+-------------------------------------------------------+
+   | XML-RPC type         | Python type                                           |
+   +======================+=======================================================+
+   | ``boolean``          | :class:`bool`                                         |
+   +----------------------+-------------------------------------------------------+
+   | ``int`` or ``i4``    | :class:`int` or :class:`long` in range from           |
+   |                      | -2147483648 to 2147483647.                            |
+   +----------------------+-------------------------------------------------------+
+   | ``double``           | :class:`float`                                        |
+   +----------------------+-------------------------------------------------------+
+   | ``string``           | :class:`str` or :class:`unicode`                      |
+   +----------------------+-------------------------------------------------------+
+   | ``array``            | :class:`list` or :class:`tuple` containing            |
+   |                      | conformable elements.  Arrays are returned as         |
+   |                      | :class:`lists <list>`.                                |
+   +----------------------+-------------------------------------------------------+
+   | ``struct``           | :class:`dict`.  Keys must be strings, values may be   |
+   |                      | any conformable type.  Objects of user-defined        |
+   |                      | classes can be passed in; only their                  |
+   |                      | :attr:`~object.__dict__` attribute is transmitted.    |
+   +----------------------+-------------------------------------------------------+
+   | ``dateTime.iso8601`` | :class:`DateTime` or :class:`datetime.datetime`.      |
+   |                      | Returned type depends on values of the *use_datetime* |
+   |                      | flags.                                                |
+   +----------------------+-------------------------------------------------------+
+   | ``base64``           | :class:`Binary`                                       |
+   +----------------------+-------------------------------------------------------+
+   | ``nil``              | The ``None`` constant.  Passing is allowed only if    |
+   |                      | *allow_none* is true.                                 |
+   +----------------------+-------------------------------------------------------+
 
    This is the full set of data types supported by XML-RPC.  Method calls may also
    raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
@@ -168,7 +174,7 @@ returning a value, which may be either returned data in a conformant type or a
 :class:`Fault` or :class:`ProtocolError` object indicating an error.
 
 Servers that support the XML introspection API support some common methods
-grouped under the reserved :attr:`system` attribute:
+grouped under the reserved :attr:`~ServerProxy.system` attribute:
 
 
 .. method:: ServerProxy.system.listMethods()
@@ -229,7 +235,7 @@ A working example follows. The server code::
    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..."
@@ -249,24 +255,26 @@ The client code for the preceding server::
 DateTime Objects
 ----------------
 
-This class may be initialized with seconds since the epoch, a time
-tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
-instance.  It has the following methods, supported mainly for internal
-use by the marshalling/unmarshalling code:
+.. class:: DateTime
+
+   This class may be initialized with seconds since the epoch, a time
+   tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
+   instance.  It has the following methods, supported mainly for internal
+   use by the marshalling/unmarshalling code:
 
 
-.. method:: DateTime.decode(string)
+   .. method:: decode(string)
 
-   Accept a string as the instance's new time value.
+      Accept a string as the instance's new time value.
 
 
-.. method:: DateTime.encode(out)
+   .. method:: encode(out)
 
-   Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
-   object.
+      Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
+      object.
 
-It also supports certain of Python's built-in operators through  :meth:`__cmp__`
-and :meth:`__repr__` methods.
+   It also supports certain of Python's built-in operators through :meth:`__cmp__`
+   and :meth:`__repr__` methods.
 
 A working example follows. The server code::
 
@@ -300,36 +308,38 @@ The client code for the preceding server::
 Binary Objects
 --------------
 
-This class may be initialized from string data (which may include NULs). The
-primary access to the content of a :class:`Binary` object is provided by an
-attribute:
+.. class:: Binary
+
+   This class may be initialized from string data (which may include NULs). The
+   primary access to the content of a :class:`Binary` object is provided by an
+   attribute:
 
 
-.. attribute:: Binary.data
+   .. attribute:: data
 
-   The binary data encapsulated by the :class:`Binary` instance.  The data is
-   provided as an 8-bit string.
+      The binary data encapsulated by the :class:`Binary` instance.  The data is
+      provided as an 8-bit string.
 
-:class:`Binary` objects have the following methods, supported mainly for
-internal use by the marshalling/unmarshalling code:
+   :class:`Binary` objects have the following methods, supported mainly for
+   internal use by the marshalling/unmarshalling code:
 
 
-.. method:: Binary.decode(string)
+   .. method:: decode(string)
 
-   Accept a base64 string and decode it as the instance's new data.
+      Accept a base64 string and decode it as the instance's new data.
 
 
-.. method:: Binary.encode(out)
+   .. method:: encode(out)
 
-   Write the XML-RPC base 64 encoding of this binary item to the out stream object.
+      Write the XML-RPC base 64 encoding of this binary item to the *out* stream object.
 
-   The encoded data will have newlines every 76 characters as per
-   `RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
-   which was the de facto standard base64 specification when the
-   XML-RPC spec was written.
+      The encoded data will have newlines every 76 characters as per
+      `RFC 2045 section 6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_,
+      which was the de facto standard base64 specification when the
+      XML-RPC spec was written.
 
-It also supports certain of Python's built-in operators through a
-:meth:`__cmp__` method.
+   It also supports certain of Python's built-in operators through a
+   :meth:`__cmp__` method.
 
 Example usage of the binary objects.  We're going to transfer an image over
 XMLRPC::
@@ -360,18 +370,20 @@ The client gets the image and saves it to a file::
 Fault Objects
 -------------
 
-A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
-objects have the following attributes:
+.. class:: Fault
 
+   A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
+   objects have the following attributes:
 
-.. attribute:: Fault.faultCode
 
-   A string indicating the fault type.
+   .. attribute:: faultCode
 
+      A string indicating the fault type.
 
-.. attribute:: Fault.faultString
 
-   A string containing a diagnostic message associated with the fault.
+   .. attribute:: faultString
+
+      A string containing a diagnostic message associated with the fault.
 
 In the following example we're going to intentionally cause a :exc:`Fault` by
 returning a complex type object.  The server code::
@@ -380,7 +392,7 @@ returning a complex type object.  The server code::
 
    # 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))
@@ -408,37 +420,39 @@ The client code for the preceding server::
 ProtocolError Objects
 ---------------------
 
-A :class:`ProtocolError` object describes a protocol error in the underlying
-transport layer (such as a 404 'not found' error if the server named by the URI
-does not exist).  It has the following attributes:
+.. class:: ProtocolError
 
+   A :class:`ProtocolError` object describes a protocol error in the underlying
+   transport layer (such as a 404 'not found' error if the server named by the URI
+   does not exist).  It has the following attributes:
 
-.. attribute:: ProtocolError.url
 
-   The URI or URL that triggered the error.
+   .. attribute:: url
 
+      The URI or URL that triggered the error.
 
-.. attribute:: ProtocolError.errcode
 
-   The error code.
+   .. attribute:: errcode
 
+      The error code.
 
-.. attribute:: ProtocolError.errmsg
 
-   The error message or diagnostic string.
+   .. attribute:: errmsg
 
+      The error message or diagnostic string.
 
-.. attribute:: ProtocolError.headers
 
-   A string containing the headers of the HTTP/HTTPS request that triggered the
-   error.
+   .. attribute:: headers
+
+      A string containing the headers of the HTTP/HTTPS request that triggered the
+      error.
 
 In the following example we're going to intentionally cause a :exc:`ProtocolError`
-by providing an URI that doesn't point to an XMLRPC server::
+by providing a URI that doesn't point to an XMLRPC server::
 
    import xmlrpclib
 
-   # create a ServerProxy with an URI that doesn't respond to XMLRPC requests
+   # create a ServerProxy with a URI that doesn't respond to XMLRPC requests
    proxy = xmlrpclib.ServerProxy("http://www.google.com/")
 
    try:
@@ -564,7 +578,7 @@ Example of Client Usage
    except Error as v:
        print "ERROR", v
 
-To access an XML-RPC server through a proxy, you need to define  a custom
+To access an XML-RPC server through a HTTP proxy, you need to define a custom
 transport.  The following example shows how:
 
 .. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
@@ -576,18 +590,21 @@ transport.  The following example shows how:
    class ProxiedTransport(xmlrpclib.Transport):
        def set_proxy(self, proxy):
            self.proxy = proxy
+
        def make_connection(self, host):
            self.realhost = host
-           h = httplib.HTTP(self.proxy)
+           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)
 
    p = ProxiedTransport()
    p.set_proxy('proxy-server:8080')
-   server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
+   server = xmlrpclib.ServerProxy('http://time.xmlrpc.com/RPC2', transport=p)
    print server.currentTime.getCurrentTime()
 
 
@@ -600,7 +617,7 @@ See :ref:`simplexmlrpcserver-example`.
 .. rubric:: Footnotes
 
 .. [#] This approach has been first presented in `a discussion on xmlrpc.com
-   <http://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
+   <https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
 .. the link now points to webarchive since the one at
 .. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
 .. doesn't reply)
index 173dfb0..3322552 100644 (file)
@@ -15,8 +15,7 @@
 The ZIP file format is a common archive and compression standard. This module
 provides tools to create, read, write, append, and list a ZIP file.  Any
 advanced use of this module will require an understanding of the format, as
-defined in `PKZIP Application Note
-<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
+defined in `PKZIP Application Note`_.
 
 This module does not currently handle multi-disk ZIP files.
 It can handle ZIP files that use the ZIP64 extensions
@@ -83,7 +82,7 @@ The module defines the following items:
 
 .. seealso::
 
-   `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
+   `PKZIP Application Note`_
       Documentation on the ZIP file format by Phil Katz, the creator of the format and
       algorithms used.
 
@@ -435,8 +434,7 @@ Instances have the following attributes:
 
 .. attribute:: ZipInfo.extra
 
-   Expansion field data.  The `PKZIP Application Note
-   <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
+   Expansion field data.  The `PKZIP Application Note`_ contains
    some comments on the internal structure of the data contained in this string.
 
 
@@ -499,3 +497,4 @@ Instances have the following attributes:
 
    Size of the uncompressed file.
 
+.. _PKZIP Application Note: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
index 828e9fc..91305f6 100644 (file)
@@ -37,7 +37,7 @@ ZIP archives with an archive comment are currently not supported.
 
 .. seealso::
 
-   `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
+   `PKZIP Application Note <https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT>`_
       Documentation on the ZIP file format by Phil Katz, the creator of the format and
       algorithms used.
 
index 96e723b..9cffe27 100644 (file)
@@ -71,17 +71,33 @@ The available exception and functions in this module are:
 .. function:: compressobj([level[, method[, wbits[, memlevel[, strategy]]]]])
 
    Returns a compression object, to be used for compressing data streams that won't
-   fit into memory at once.  *level* is an integer from ``0`` to ``9`` controlling
+   fit into memory at once.  *level* is an integer from
+   ``0`` to ``9`` or ``-1``, controlling
    the level of compression; ``1`` is fastest and produces the least compression,
    ``9`` is slowest and produces the most.  ``0`` is no compression.  The default
-   value is ``6``.
+   value is ``-1`` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default
+   compromise between speed and compression (currently equivalent to level 6).
 
    *method* is the compression algorithm. Currently, the only supported value is
    ``DEFLATED``.
 
-   *wbits* is the base two logarithm of the size of the window buffer. This
-   should be an integer from ``8`` to ``15``. Higher values give better
-   compression, but use more memory. The default is 15.
+   The *wbits* argument controls the size of the history buffer (or the
+   "window size") used when compressing data, and whether a header and
+   trailer is included in the output.  It can take several ranges of values.
+   The default is 15.
+
+   * +9 to +15: The base-two logarithm of the window size, which
+     therefore ranges between 512 and 32768.  Larger values produce
+     better compression at the expense of greater memory usage.  The
+     resulting output will include a zlib-specific header and trailer.
+
+   * −9 to −15: Uses the absolute value of *wbits* as the
+     window size logarithm, while producing a raw output stream with no
+     header or trailing checksum.
+
+   * +25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the
+     window size logarithm, while including a basic :program:`gzip` header
+     and trailing checksum in the output.
 
    *memlevel* controls the amount of memory used for internal compression state.
    Valid values range from ``1`` to ``9``. Higher values using more memory,
@@ -128,20 +144,40 @@ The available exception and functions in this module are:
 .. function:: decompress(string[, wbits[, bufsize]])
 
    Decompresses the data in *string*, returning a string containing the
-   uncompressed data.  The *wbits* parameter controls the size of the window
-   buffer, and is discussed further below.
+   uncompressed data.  The *wbits* parameter depends on
+   the format of *string*, and is discussed further below.
    If *bufsize* is given, it is used as the initial size of the output
    buffer.  Raises the :exc:`error` exception if any error occurs.
 
-   The absolute value of *wbits* is the base two logarithm of the size of the
-   history buffer (the "window size") used when compressing data.  Its absolute
-   value should be between 8 and 15 for the most recent versions of the zlib
-   library, larger values resulting in better compression at the expense of greater
-   memory usage.  When decompressing a stream, *wbits* must not be smaller
+   .. _decompress-wbits:
+
+   The *wbits* parameter controls the size of the history buffer
+   (or "window size"), and what header and trailer format is expected.
+   It is similar to the parameter for :func:`compressobj`, but accepts
+   more ranges of values:
+
+   * +8 to +15: The base-two logarithm of the window size.  The input
+     must include a zlib header and trailer.
+
+   * 0: Automatically determine the window size from the zlib header.
+     Only supported since zlib 1.2.3.5.
+
+   * −8 to −15: Uses the absolute value of *wbits* as the window size
+     logarithm.  The input must be a raw stream with no header or trailer.
+
+   * +24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as
+     the window size logarithm.  The input must include a gzip header and
+     trailer.
+
+   * +40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as
+     the window size logarithm, and automatically accepts either
+     the zlib or gzip format.
+
+   When decompressing a stream, the window size must not be smaller
    than the size originally used to compress the stream; using a too-small
-   value will result in an exception. The default value is therefore the
-   highest value, 15.  When *wbits* is negative, the standard
-   :program:`gzip` header is suppressed.
+   value may result in an :exc:`error` exception. The default *wbits* value
+   is 15, which corresponds to the largest window size and requires a zlib
+   header and trailer to be included.
 
    *bufsize* is the initial size of the buffer used to hold decompressed data.  If
    more space is required, the buffer size will be increased as needed, so you
@@ -152,8 +188,11 @@ The available exception and functions in this module are:
 .. function:: decompressobj([wbits])
 
    Returns a decompression object, to be used for decompressing data streams that
-   won't fit into memory at once.  The *wbits* parameter controls the size of the
-   window buffer.
+   won't fit into memory at once.
+
+   The *wbits* parameter controls the size of the history buffer (or the
+   "window size"), and what header and trailer format is expected.  It has
+   the same meaning as `described for decompress() <#decompress-wbits>`__.
 
 Compression objects support the following methods:
 
index c47f478..ea37b5a 100644 (file)
@@ -11,12 +11,12 @@ History of the software
 =======================
 
 Python was created in the early 1990s by Guido van Rossum at Stichting
-Mathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands as a
+Mathematisch Centrum (CWI, see https://www.cwi.nl/) in the Netherlands as a
 successor of a language called ABC.  Guido remains Python's principal author,
 although it includes many contributions from others.
 
 In 1995, Guido continued his work on Python at the Corporation for National
-Research Initiatives (CNRI, see http://www.cnri.reston.va.us/) in Reston,
+Research Initiatives (CNRI, see https://www.cnri.reston.va.us/) in Reston,
 Virginia where he released several versions of the software.
 
 In May 2000, Guido and the Python core development team moved to BeOpen.com to
@@ -27,7 +27,7 @@ https://www.python.org/psf/) was formed, a non-profit organization created
 specifically to own Python-related Intellectual Property.  Zope Corporation is a
 sponsoring member of the PSF.
 
-All Python releases are Open Source (see http://opensource.org/ for the Open
+All Python releases are Open Source (see https://opensource.org/ for the Open
 Source Definition). Historically, most, but not all, Python releases have also
 been GPL-compatible; the table below summarizes the various releases.
 
@@ -73,181 +73,189 @@ Terms and conditions for accessing or otherwise using Python
 ============================================================
 
 
-.. centered:: PSF LICENSE AGREEMENT FOR PYTHON |release|
-
-#. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
-   the Individual or Organization ("Licensee") accessing and otherwise using Python
-   |release| software in source or binary form and its associated documentation.
-
-#. Subject to the terms and conditions of this License Agreement, PSF hereby
-   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-   analyze, test, perform and/or display publicly, prepare derivative works,
-   distribute, and otherwise use Python |release| alone or in any derivative
-   version, provided, however, that PSF's License Agreement and PSF's notice of
-   copyright, i.e., "Copyright © 2001-2015 Python Software Foundation; All Rights
-   Reserved" are retained in Python |release| alone or in any derivative version
-   prepared by Licensee.
-
-#. In the event Licensee prepares a derivative work that is based on or
-   incorporates Python |release| or any part thereof, and wants to make the
-   derivative work available to others as provided herein, then Licensee hereby
-   agrees to include in any such work a brief summary of the changes made to Python
-   |release|.
-
-#. PSF is making Python |release| available to Licensee on an "AS IS" basis.
-   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
-   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
-   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
-   USE OF PYTHON |release| WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-#. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |release|
-   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
-   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON |release|, OR ANY DERIVATIVE
-   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-#. This License Agreement will automatically terminate upon a material breach of
-   its terms and conditions.
-
-#. Nothing in this License Agreement shall be deemed to create any relationship
-   of agency, partnership, or joint venture between PSF and Licensee.  This License
-   Agreement does not grant permission to use PSF trademarks or trade name in a
-   trademark sense to endorse or promote products or services of Licensee, or any
-   third party.
-
-#. By copying, installing or otherwise using Python |release|, Licensee agrees
-   to be bound by the terms and conditions of this License Agreement.
-
-
-.. centered:: BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-
-
-.. centered:: BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
-
-#. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
-   160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
-   ("Licensee") accessing and otherwise using this software in source or binary
-   form and its associated documentation ("the Software").
-
-#. Subject to the terms and conditions of this BeOpen Python License Agreement,
-   BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
-   to reproduce, analyze, test, perform and/or display publicly, prepare derivative
-   works, distribute, and otherwise use the Software alone or in any derivative
-   version, provided, however, that the BeOpen Python License is retained in the
-   Software, alone or in any derivative version prepared by Licensee.
-
-#. BeOpen is making the Software available to Licensee on an "AS IS" basis.
-   BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
-   EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
-   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
-   USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-#. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
-   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
-   MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
-   ADVISED OF THE POSSIBILITY THEREOF.
-
-#. This License Agreement will automatically terminate upon a material breach of
-   its terms and conditions.
-
-#. This License Agreement shall be governed by and interpreted in all respects
-   by the law of the State of California, excluding conflict of law provisions.
-   Nothing in this License Agreement shall be deemed to create any relationship of
-   agency, partnership, or joint venture between BeOpen and Licensee.  This License
-   Agreement does not grant permission to use BeOpen trademarks or trade names in a
-   trademark sense to endorse or promote products or services of Licensee, or any
-   third party.  As an exception, the "BeOpen Python" logos available at
-   http://www.pythonlabs.com/logos.html may be used according to the permissions
-   granted on that web page.
-
-#. By copying, installing or otherwise using the software, Licensee agrees to be
-   bound by the terms and conditions of this License Agreement.
-
-
-.. centered:: CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
-
-#. This LICENSE AGREEMENT is between the Corporation for National Research
-   Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
-   ("CNRI"), and the Individual or Organization ("Licensee") accessing and
-   otherwise using Python 1.6.1 software in source or binary form and its
-   associated documentation.
-
-#. Subject to the terms and conditions of this License Agreement, CNRI hereby
-   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-   analyze, test, perform and/or display publicly, prepare derivative works,
-   distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
-   provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
-   i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
-   Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
-   prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
-   Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
-   is made available subject to the terms and conditions in CNRI's License
-   Agreement.  This Agreement together with Python 1.6.1 may be located on the
-   Internet using the following unique, persistent identifier (known as a handle):
-   1895.22/1013.  This Agreement may also be obtained from a proxy server on the
-   Internet using the following URL: http://hdl.handle.net/1895.22/1013."
-
-#. In the event Licensee prepares a derivative work that is based on or
-   incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
-   work available to others as provided herein, then Licensee hereby agrees to
-   include in any such work a brief summary of the changes made to Python 1.6.1.
-
-#. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
-   MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
-   BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
-   OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
-   PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-#. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
-   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
-   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
-   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-#. This License Agreement will automatically terminate upon a material breach of
-   its terms and conditions.
-
-#. This License Agreement shall be governed by the federal intellectual property
-   law of the United States, including without limitation the federal copyright
-   law, and, to the extent such U.S. federal law does not apply, by the law of the
-   Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
-   Notwithstanding the foregoing, with regard to derivative works based on Python
-   1.6.1 that incorporate non-separable material that was previously distributed
-   under the GNU General Public License (GPL), the law of the Commonwealth of
-   Virginia shall govern this License Agreement only as to issues arising under or
-   with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
-   this License Agreement shall be deemed to create any relationship of agency,
-   partnership, or joint venture between CNRI and Licensee.  This License Agreement
-   does not grant permission to use CNRI trademarks or trade name in a trademark
-   sense to endorse or promote products or services of Licensee, or any third
-   party.
-
-#. By clicking on the "ACCEPT" button where indicated, or by copying, installing
-   or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
-   conditions of this License Agreement.
-
-
-.. centered:: ACCEPT
-
-
-.. centered:: CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
-
-Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
-Netherlands.  All rights reserved.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted, provided that
-the above copyright notice appear in all copies and that both that copyright
-notice and this permission notice appear in supporting documentation, and that
-the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
-publicity pertaining to distribution of the software without specific, written
-prior permission.
-
-STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
-EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
-OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
-DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
-ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
+PSF LICENSE AGREEMENT FOR PYTHON |release|
+------------------------------------------
+
+.. parsed-literal::
+
+   1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
+      the Individual or Organization ("Licensee") accessing and otherwise using Python
+      |release| software in source or binary form and its associated documentation.
+
+   2. Subject to the terms and conditions of this License Agreement, PSF hereby
+      grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+      analyze, test, perform and/or display publicly, prepare derivative works,
+      distribute, and otherwise use Python |release| alone or in any derivative
+      version, provided, however, that PSF's License Agreement and PSF's notice of
+      copyright, i.e., "Copyright © 2001-2016 Python Software Foundation; All Rights
+      Reserved" are retained in Python |release| alone or in any derivative version
+      prepared by Licensee.
+
+   3. In the event Licensee prepares a derivative work that is based on or
+      incorporates Python |release| or any part thereof, and wants to make the
+      derivative work available to others as provided herein, then Licensee hereby
+      agrees to include in any such work a brief summary of the changes made to Python
+      |release|.
+
+   4. PSF is making Python |release| available to Licensee on an "AS IS" basis.
+      PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
+      EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
+      WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
+      USE OF PYTHON |release| WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
+
+   5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |release|
+      FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
+      MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON |release|, OR ANY DERIVATIVE
+      THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+   6. This License Agreement will automatically terminate upon a material breach of
+      its terms and conditions.
+
+   7. Nothing in this License Agreement shall be deemed to create any relationship
+      of agency, partnership, or joint venture between PSF and Licensee.  This License
+      Agreement does not grant permission to use PSF trademarks or trade name in a
+      trademark sense to endorse or promote products or services of Licensee, or any
+      third party.
+
+   8. By copying, installing or otherwise using Python |release|, Licensee agrees
+      to be bound by the terms and conditions of this License Agreement.
+
+
+BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
+-------------------------------------------
+
+BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
+
+.. parsed-literal::
+
+   1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
+      160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
+      ("Licensee") accessing and otherwise using this software in source or binary
+      form and its associated documentation ("the Software").
+
+   2. Subject to the terms and conditions of this BeOpen Python License Agreement,
+      BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
+      to reproduce, analyze, test, perform and/or display publicly, prepare derivative
+      works, distribute, and otherwise use the Software alone or in any derivative
+      version, provided, however, that the BeOpen Python License is retained in the
+      Software, alone or in any derivative version prepared by Licensee.
+
+   3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
+      BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
+      EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
+      WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
+      USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
+
+   4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
+      ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
+      MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
+      ADVISED OF THE POSSIBILITY THEREOF.
+
+   5. This License Agreement will automatically terminate upon a material breach of
+      its terms and conditions.
+
+   6. This License Agreement shall be governed by and interpreted in all respects
+      by the law of the State of California, excluding conflict of law provisions.
+      Nothing in this License Agreement shall be deemed to create any relationship of
+      agency, partnership, or joint venture between BeOpen and Licensee.  This License
+      Agreement does not grant permission to use BeOpen trademarks or trade names in a
+      trademark sense to endorse or promote products or services of Licensee, or any
+      third party.  As an exception, the "BeOpen Python" logos available at
+      http://www.pythonlabs.com/logos.html may be used according to the permissions
+      granted on that web page.
+
+   7. By copying, installing or otherwise using the software, Licensee agrees to be
+      bound by the terms and conditions of this License Agreement.
+
+
+CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
+---------------------------------------
+
+.. parsed-literal::
+
+   1. This LICENSE AGREEMENT is between the Corporation for National Research
+      Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
+      ("CNRI"), and the Individual or Organization ("Licensee") accessing and
+      otherwise using Python 1.6.1 software in source or binary form and its
+      associated documentation.
+
+   2. Subject to the terms and conditions of this License Agreement, CNRI hereby
+      grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+      analyze, test, perform and/or display publicly, prepare derivative works,
+      distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
+      provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
+      i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
+      Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
+      prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
+      Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
+      is made available subject to the terms and conditions in CNRI's License
+      Agreement.  This Agreement together with Python 1.6.1 may be located on the
+      Internet using the following unique, persistent identifier (known as a handle):
+      1895.22/1013.  This Agreement may also be obtained from a proxy server on the
+      Internet using the following URL: http://hdl.handle.net/1895.22/1013."
+
+   3. In the event Licensee prepares a derivative work that is based on or
+      incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
+      work available to others as provided herein, then Licensee hereby agrees to
+      include in any such work a brief summary of the changes made to Python 1.6.1.
+
+   4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
+      MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
+      BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
+      OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
+      PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
+
+   5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
+      ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
+      MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
+      THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+   6. This License Agreement will automatically terminate upon a material breach of
+      its terms and conditions.
+
+   7. This License Agreement shall be governed by the federal intellectual property
+      law of the United States, including without limitation the federal copyright
+      law, and, to the extent such U.S. federal law does not apply, by the law of the
+      Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
+      Notwithstanding the foregoing, with regard to derivative works based on Python
+      1.6.1 that incorporate non-separable material that was previously distributed
+      under the GNU General Public License (GPL), the law of the Commonwealth of
+      Virginia shall govern this License Agreement only as to issues arising under or
+      with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
+      this License Agreement shall be deemed to create any relationship of agency,
+      partnership, or joint venture between CNRI and Licensee.  This License Agreement
+      does not grant permission to use CNRI trademarks or trade name in a trademark
+      sense to endorse or promote products or services of Licensee, or any third
+      party.
+
+   8. By clicking on the "ACCEPT" button where indicated, or by copying, installing
+      or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
+      conditions of this License Agreement.
+
+
+CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
+--------------------------------------------------
+
+.. parsed-literal::
+
+   Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
+   Netherlands.  All rights reserved.
+
+   Permission to use, copy, modify, and distribute this software and its
+   documentation for any purpose and without fee is hereby granted, provided that
+   the above copyright notice appear in all copies and that both that copyright
+   notice and this permission notice appear in supporting documentation, and that
+   the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
+   publicity pertaining to distribution of the software without specific, written
+   prior permission.
+
+   STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+   SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+   EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
+   OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+   DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+   ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+   SOFTWARE.
 
 
 Licenses and Acknowledgements for Incorporated Software
@@ -329,18 +337,17 @@ Project, http://www.wide.ad.jp/. ::
       without specific prior written permission.
 
    THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
-   GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
-   FOR GAI_ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-   HOWEVER CAUSED AND ON GAI_ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN GAI_ANY WAY
+   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
 
-
 Floating point exception control
 --------------------------------
 
@@ -894,4 +901,3 @@ used for the build::
 
   Jean-loup Gailly        Mark Adler
   jloup@gzip.org          madler@alumni.caltech.edu
-
index 1251024..66ae530 100644 (file)
@@ -418,7 +418,7 @@ is equivalent to ::
 
 .. seealso::
 
-   :pep:`0343` - The "with" statement
+   :pep:`343` - The "with" statement
       The specification, background, and examples for the Python :keyword:`with`
       statement.
 
index c61c55b..fe0cea8 100644 (file)
@@ -909,11 +909,9 @@ Internal types
    definitions may change with future versions of the interpreter, but they are
    mentioned here for completeness.
 
-   Code objects
-      .. index::
-         single: bytecode
-         object: code
+   .. index:: bytecode, object; code, code object
 
+   Code objects
       Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
       The difference between a code object and a function object is that the function
       object contains an explicit reference to the function's globals (the module in
@@ -2397,7 +2395,7 @@ For more information on context managers, see :ref:`typecontextmanager`.
 
 .. seealso::
 
-   :pep:`0343` - The "with" statement
+   :pep:`343` - The "with" statement
       The specification, background, and examples for the Python :keyword:`with`
       statement.
 
index 427a63a..f18984b 100644 (file)
@@ -508,7 +508,7 @@ generator functions::
 
 .. seealso::
 
-   :pep:`0342` - Coroutines via Enhanced Generators
+   :pep:`342` - Coroutines via Enhanced Generators
       The proposal to enhance the API and syntax of generators, making them usable as
       simple coroutines.
 
@@ -761,7 +761,7 @@ A consequence of this is that although the ``*expression`` syntax may appear
 (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
@@ -1153,7 +1153,7 @@ types to support membership tests without being a sequence.  In particular,
 dictionaries (for keys) and sets support membership testing.
 
 For the list and tuple types, ``x in y`` is true if and only if there exists an
-index *i* such that ``x == y[i]`` is true.
+index *i* such that either ``x is y[i]`` or ``x == y[i]`` is true.
 
 For the Unicode and string types, ``x in y`` is true if and only if *x* is a
 substring of *y*.  An equivalent test is ``y.find(x) != -1``.  Note, *x* and *y*
index a84d8e8..d0959c5 100644 (file)
@@ -59,7 +59,7 @@ Python for .NET
    This implementation actually uses the CPython implementation, but is a managed
    .NET application and makes .NET libraries available.  It was created by Brian
    Lloyd.  For more information, see the `Python for .NET home page
-   <http://pythonnet.sourceforge.net>`_.
+   <https://pythonnet.github.io/>`_.
 
 IronPython
    An alternate Python for .NET.  Unlike Python.NET, this is a complete Python
index 0203e08..848bb9e 100644 (file)
@@ -87,7 +87,7 @@ attributes or items of mutable objects:
    target_list: `target` ("," `target`)* [","]
    target: `identifier`
          : | "(" `target_list` ")"
-         : | "[" `target_list` "]"
+         : | "[" [`target_list`] "]"
          : | `attributeref`
          : | `subscription`
          : | `slicing`
@@ -306,12 +306,12 @@ program:
 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__
@@ -538,10 +538,10 @@ section.
 
 .. seealso::
 
-   :pep:`0255` - Simple Generators
+   :pep:`255` - Simple Generators
       The proposal for adding generators and the :keyword:`yield` statement to Python.
 
-   :pep:`0342` - Coroutines via Enhanced Generators
+   :pep:`342` - Coroutines via Enhanced Generators
       The proposal that, among other generator enhancements, proposed allowing
       :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.
 
index 1699891..1b6b0e2 100644 (file)
@@ -131,7 +131,7 @@ pydoc_topic_labels = [
     'assert', 'assignment', 'atom-identifiers', 'atom-literals',
     'attribute-access', 'attribute-references', 'augassign', 'binary',
     'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
-    'bltin-null-object', 'bltin-type-objects', 'booleans',
+    'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
     'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
     'context-managers', 'continue', 'conversions', 'customization', 'debugger',
     'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'exec', 'execmodel',
index e7afc05..1c84473 100755 (executable)
@@ -42,7 +42,7 @@ directives = [
 ]
 
 all_directives = '(' + '|'.join(directives) + ')'
-seems_directive_re = re.compile(r'\.\. %s([^a-z:]|:(?!:))' % all_directives)
+seems_directive_re = re.compile(r'(?<!\.)\.\. %s([^a-z:]|:(?!:))' % all_directives)
 default_role_re = re.compile(r'(^| )`\w([^`]*?\w)?`($| )')
 leaked_markup_re = re.compile(r'[a-z]::\s|`|\.\.\s*\w+:')
 
@@ -81,7 +81,7 @@ def check_suspicious_constructs(fn, lines):
     """Check for suspicious reST constructs."""
     inprod = False
     for lno, line in enumerate(lines):
-        if seems_directive_re.match(line):
+        if seems_directive_re.search(line):
             yield lno+1, 'comment seems to be intended as a directive'
         if '.. productionlist::' in line:
             inprod = True
index 85a4318..7230eb3 100644 (file)
@@ -393,25 +393,30 @@ table.highlighttable td {
     padding: 0 0.5em 0 0.5em;
 }
 
-tt.descname {
+code.descname {
     background-color: transparent;
     font-weight: bold;
     font-size: 1.2em;
 }
 
-tt.descclassname {
+code.descclassname {
     background-color: transparent;
 }
 
-tt.xref, a tt {
+code.xref, a code {
     background-color: transparent;
     font-weight: bold;
 }
 
-h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
+h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
     background-color: transparent;
 }
 
+.highlight {
+    background: none !important;
+}
+
+
 /* -- math display ---------------------------------------------------------- */
 
 img.math {
index a3b1099..52e6c2d 100644 (file)
@@ -27,6 +27,7 @@ $(document).ready(function() {
             var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
             button.css(button_styles)
             button.attr('title', hide_text);
+            button.data('hidden', 'false');
             jthis.prepend(button);
         }
         // tracebacks (.gt) contain bare text elements that need to be
@@ -37,20 +38,24 @@ $(document).ready(function() {
     });
 
     // define the behavior of the button when it's clicked
-    $('.copybutton').toggle(
-        function() {
-            var button = $(this);
+    $('.copybutton').click(function(e){
+        e.preventDefault();
+        var button = $(this);
+        if (button.data('hidden') === 'false') {
+            // hide the code output
             button.parent().find('.go, .gp, .gt').hide();
             button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
             button.css('text-decoration', 'line-through');
             button.attr('title', show_text);
-        },
-        function() {
-            var button = $(this);
+            button.data('hidden', 'true');
+        } else {
+            // show the code output
             button.parent().find('.go, .gp, .gt').show();
             button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
             button.css('text-decoration', 'none');
             button.attr('title', hide_text);
-        });
+            button.data('hidden', 'false');
+        }
+    });
 });
 
index 49d8275..17b2366 100644 (file)
@@ -46,7 +46,7 @@ howto/pyporting,,::,Programming Language :: Python :: 2
 howto/pyporting,,::,Programming Language :: Python :: 3
 howto/regex,,::,
 howto/regex,,:foo,(?:foo)
-howto/urllib2,,:example,"for example ""joe@password:example.com"""
+howto/urllib2,,:password,"for example ""joe:password@example.com"""
 library/audioop,,:ipos,"# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],"
 library/bisect,,:hi,all(val >= x for val in a[i:hi])
 library/bisect,,:hi,all(val > x for val in a[i:hi])
@@ -173,7 +173,7 @@ using/cmdline,,:line,action:message:category:module:line
 using/cmdline,,:message,action:message:category:module:line
 using/cmdline,,:module,action:message:category:module:line
 using/cmdline,,:errorhandler,:errorhandler
-using/unix,,:Packaging,http://en.opensuse.org/Portal:Packaging
+using/unix,,:Packaging,https://en.opensuse.org/Portal:Packaging
 whatsnew/2.0,418,:len,
 whatsnew/2.3,,::,
 whatsnew/2.3,,:config,
index 66e09cc..2a885d7 100644 (file)
@@ -7,55 +7,96 @@
 {% endif %}
 
 {% block body %}
-<h1>Download Python {{ release }} Documentation</h1>
+<h1>{% trans %}Download Python {{ release }} Documentation{% endtrans %}</h1>
 
-{% if last_updated %}<p><b>Last updated on: {{ last_updated }}.</b></p>{% endif %}
+{% if last_updated %}
+  <p><b>{% trans %}Last updated on: {{ last_updated }}.{% endtrans %}</b></p>
+{% endif %}
 
-<p>To download an archive containing all the documents for this version of
-Python in one of various formats, follow one of links in this table. The numbers
-in the table are the size of the download files in megabytes.</p>
+<p>{% trans %}To download an archive containing all the documents for
+this version of Python in one of various formats, follow one of links
+in this table. The numbers in the table are the size of the download
+files in megabytes.{% endtrans %}</p>
 
 <table class="docutils">
-  <tr><th>Format</th><th>Packed as .zip</th><th>Packed as .tar.bz2</th></tr>
-  <tr><td>PDF (US-Letter paper size)</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.zip">Download</a> (ca. 8 MB)</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.tar.bz2">Download</a> (ca. 8 MB)</td>
+  <tr><th>{% trans %}Format{% endtrans %}</th>
+    <th>{% trans %}Packed as .zip{% endtrans %}</th>
+    <th>{% trans %}Packed as .tar.bz2{% endtrans %}</th>
+  </tr>
+  <tr><td>{% trans %}PDF (US-Letter paper size){% endtrans %}</td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.zip">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 8 MB){% endtrans %}
+    </td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.tar.bz2">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 8 MB){% endtrans %}
+    </td>
   </tr>
-  <tr><td>PDF (A4 paper size)</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.zip">Download</a> (ca. 8 MB)</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.tar.bz2">Download</a> (ca. 8 MB)</td>
+  <tr><td>{% trans %}PDF (A4 paper size){% endtrans %}</td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.zip">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 8 MB){% endtrans %}</td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.tar.bz2">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 8 MB){% endtrans %}</td>
   </tr>
-  <tr><td>HTML</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-html.zip">Download</a> (ca. 6 MB)</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-html.tar.bz2">Download</a> (ca. 4 MB)</td>
+  <tr><td>{% trans %}HTML{% endtrans %}</td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-html.zip">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 6 MB){% endtrans %}
+    </td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-html.tar.bz2">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 4 MB){% endtrans %}
+    </td>
   </tr>
-  <tr><td>Plain Text</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.zip">Download</a> (ca. 2 MB)</td>
-    <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.tar.bz2">Download</a> (ca. 1.5 MB)</td>
+  <tr>
+    <td>{% trans %}Plain Text{% endtrans %}</td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-text.zip">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 2 MB){% endtrans %}
+    </td>
+    <td>
+      <a href="{{ dlbase }}/python-{{ release }}-docs-text.tar.bz2">
+        {% trans %}Download{% endtrans %}
+      </a> {% trans %}(ca. 1.5 MB){% endtrans %}
+    </td>
   </tr>
 </table>
 
-<p>These archives contain all the content in the documentation.</p>
+<p>{% trans %}These archives contain all the content in the
+documentation.{% endtrans %}</p>
 
-<p>HTML Help (<tt>.chm</tt>) files are made available in the "Windows" section
-on the <a href="https://www.python.org/download/releases/{{ release[:5] }}/">Python
-download page</a>.</p>
+<p>{% trans download_page="https://www.python.org/download/releases/{{ release[:5] }}/" %}HTML Help
+(<tt>.chm</tt>) files are made available in the "Windows" section
+on the <a href={{ download_page }}>Python download page</a>.{% endtrans %}</p>
 
 
-<h2>Unpacking</h2>
+<h2>{% trans %}Unpacking{% endtrans %}</h2>
 
-<p>Unix users should download the .tar.bz2 archives; these are bzipped tar
-archives and can be handled in the usual way using tar and the bzip2
-program. The <a href="http://www.info-zip.org">InfoZIP</a> unzip program can be
-used to handle the ZIP archives if desired. The .tar.bz2 archives provide the
-best compression and fastest download times.</p>
+<p>{% trans %}Unix users should download the .tar.bz2 archives; these
+are bzipped tar archives and can be handled in the usual way using tar
+and the bzip2 program. The <a href="http://www.info-zip.org">InfoZIP</a> unzip
+program can be used to handle the ZIP archives if desired. The
+.tar.bz2 archives provide the best compression and fastest download
+times.{% endtrans %}</p>
 
-<p>Windows users can use the ZIP archives since those are customary on that
-platform. These are created on Unix using the InfoZIP zip program.</p>
+<p>{% trans %}Windows users can use the ZIP archives since those are
+customary on that platform. These are created on Unix using the
+InfoZIP zip program.{% endtrans %}</p>
 
 
-<h2>Problems</h2>
+<h2>{% trans %}Problems{% endtrans %}</h2>
 
-<p>If you have comments or suggestions for the Python documentation, please send
-email to <a href="mailto:docs@python.org">docs@python.org</a>.</p>
+<p>{% trans %}If you have comments or suggestions for the Python
+documentation, please send email to
+<a href="mailto:docs@python.org">docs@python.org</a>.{% endtrans %}</p>
 {% endblock %}
index 7f85470..6488c16 100644 (file)
@@ -1,59 +1,59 @@
 {% extends "defindex.html" %}
 {% block tables %}
-  <p><strong>Parts of the documentation:</strong></p>
+  <p><strong>{% trans %}Parts of the documentation:{% endtrans %}</strong></p>
   <table class="contentstable" align="center"><tr>
     <td width="50%">
-      <p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">What's new in Python {{ version }}?</a><br/>
-         <span class="linkdescr">or <a href="{{ pathto("whatsnew/index") }}">all "What's new" documents</a> since 2.0</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("tutorial/index") }}">Tutorial</a><br/>
-         <span class="linkdescr">start here</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">Library Reference</a><br/>
-         <span class="linkdescr">keep this under your pillow</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("reference/index") }}">Language Reference</a><br/>
-         <span class="linkdescr">describes syntax and language elements</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("using/index") }}">Python Setup and Usage</a><br/>
-         <span class="linkdescr">how to use Python on different platforms</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("howto/index") }}">Python HOWTOs</a><br/>
-         <span class="linkdescr">in-depth documents on specific topics</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">{% trans %}What's new in Python {{ version }}?{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans whatsnew_index=pathto("whatsnew/index") %}or <a href="{{ whatsnew_index }}">all "What's new" documents</a> since 2.0{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("tutorial/index") }}">{% trans %}Tutorial{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}start here{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">{% trans %}Library Reference{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}keep this under your pillow{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("reference/index") }}">{% trans %}Language Reference{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}describes syntax and language elements{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("using/index") }}">{% trans %}Python Setup and Usage{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}how to use Python on different platforms{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("howto/index") }}">{% trans %}Python HOWTOs{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}in-depth documents on specific topics{% endtrans %}</span></p>
     </td><td width="50%">
-      <p class="biglink"><a class="biglink" href="{{ pathto("extending/index") }}">Extending and Embedding</a><br/>
-         <span class="linkdescr">tutorial for C/C++ programmers</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("c-api/index") }}">Python/C API</a><br/>
-         <span class="linkdescr">reference for C/C++ programmers</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("install/index") }}">Installing Python Modules</a><br/>
-         <span class="linkdescr">information for installers &amp; sys-admins</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("distutils/index") }}">Distributing Python Modules</a><br/>
-         <span class="linkdescr">sharing modules with others</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("faq/index") }}">FAQs</a><br/>
-         <span class="linkdescr">frequently asked questions (with answers!)</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("installing/index") }}">{% trans %}Installing Python Modules{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}installing from the Python Package Index &amp; other sources{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("distributing/index") }}">{% trans %}Distributing Python Modules{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}publishing modules for installation by others{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("extending/index") }}">{% trans %}Extending and Embedding{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}tutorial for C/C++ programmers{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("c-api/index") }}">{% trans %}Python/C API{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}reference for C/C++ programmers{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("faq/index") }}">{% trans %}FAQs{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}frequently asked questions (with answers!){% endtrans %}</span></p>
     </td></tr>
   </table>
 
-  <p><strong>Indices and tables:</strong></p>
+  <p><strong>{% trans %}Indices and tables:{% endtrans %}</strong></p>
   <table class="contentstable" align="center"><tr>
     <td width="50%">
-      <p class="biglink"><a class="biglink" href="{{ pathto("py-modindex") }}">Global Module Index</a><br/>
-         <span class="linkdescr">quick access to all modules</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">General Index</a><br/>
-         <span class="linkdescr">all functions, classes, terms</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("glossary") }}">Glossary</a><br/>
-         <span class="linkdescr">the most important terms explained</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("py-modindex") }}">{% trans %}Global Module Index{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}quick access to all modules{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">{% trans %}General Index{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}all functions, classes, terms{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("glossary") }}">{% trans %}Glossary{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}the most important terms explained{% endtrans %}</span></p>
     </td><td width="50%">
-      <p class="biglink"><a class="biglink" href="{{ pathto("search") }}">Search page</a><br/>
-         <span class="linkdescr">search this documentation</span></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">Complete Table of Contents</a><br/>
-         <span class="linkdescr">lists all sections and subsections</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("search") }}">{% trans %}Search page{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}search this documentation{% endtrans %}</span></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">{% trans %}Complete Table of Contents{% endtrans %}</a><br/>
+         <span class="linkdescr">{% trans %}lists all sections and subsections{% endtrans %}</span></p>
     </td></tr>
   </table>
 
-  <p><strong>Meta information:</strong></p>
+  <p><strong>{% trans %}Meta information:{% endtrans %}</strong></p>
   <table class="contentstable" align="center"><tr>
     <td width="50%">
-      <p class="biglink"><a class="biglink" href="{{ pathto("bugs") }}">Reporting bugs</a></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("about") }}">About the documentation</a></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("bugs") }}">{% trans %}Reporting bugs{% endtrans %}</a></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("about") }}">{% trans %}About the documentation{% endtrans %}</a></p>
     </td><td width="50%">
-      <p class="biglink"><a class="biglink" href="{{ pathto("license") }}">History and License of Python</a></p>
-      <p class="biglink"><a class="biglink" href="{{ pathto("copyright") }}">Copyright</a></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("license") }}">{% trans %}History and License of Python{% endtrans %}</a></p>
+      <p class="biglink"><a class="biglink" href="{{ pathto("copyright") }}">{% trans %}Copyright{% endtrans %}</a></p>
     </td></tr>
   </table>
 {% endblock %}
index 4e10d69..d93021d 100644 (file)
@@ -1,17 +1,17 @@
-<h3>Download</h3>
-<p><a href="{{ pathto('download') }}">Download these documents</a></p>
-<h3>Docs for other versions</h3>
+<h3>{% trans %}Download{% endtrans %}</h3>
+<p><a href="{{ pathto('download') }}">{% trans %}Download these documents{% endtrans %}</a></p>
+<h3>{% trans %}Docs for other versions{% endtrans %}</h3>
 <ul>
-  <li><a href="https://docs.python.org/3.4/">Python 3.4 (stable)</a></li>
-  <li><a href="https://docs.python.org/3.5/">Python 3.5 (in development)</a></li>
-  <li><a href="https://www.python.org/doc/versions/">Old versions</a></li>
+  <li><a href="https://docs.python.org/3.4/">{% trans %}Python 3.4 (stable){% endtrans %}</a></li>
+  <li><a href="https://docs.python.org/3.5/">{% trans %}Python 3.5 (in development){% endtrans %}</a></li>
+  <li><a href="https://www.python.org/doc/versions/">{% trans %}Old versions{% endtrans %}</a></li>
 </ul>
 
-<h3>Other resources</h3>
+<h3>{% trans %}Other resources{% endtrans %}</h3>
 <ul>
   {# XXX: many of these should probably be merged in the main docs #}
-  <li><a href="https://www.python.org/dev/peps/">PEP Index</a></li>
-  <li><a href="https://wiki.python.org/moin/BeginnersGuide">Beginner's Guide</a></li>
-  <li><a href="https://wiki.python.org/moin/PythonBooks">Book List</a></li>
-  <li><a href="https://www.python.org/doc/av/">Audio/Visual Talks</a></li>
+  <li><a href="https://www.python.org/dev/peps/">{% trans %}PEP Index{% endtrans %}</a></li>
+  <li><a href="https://wiki.python.org/moin/BeginnersGuide">{% trans %}Beginner's Guide{% endtrans %}</a></li>
+  <li><a href="https://wiki.python.org/moin/PythonBooks">{% trans %}Book List{% endtrans %}</a></li>
+  <li><a href="https://www.python.org/doc/av/">{% trans %}Audio/Visual Talks{% endtrans %}</a></li>
 </ul>
index ec29ca2..78b3b27 100644 (file)
@@ -6,7 +6,7 @@
         <li>
           {%- if versionswitcher is defined %}
           <span class="version_switcher_placeholder">{{ release }}</span>
-          <a href="{{ pathto('index') }}">Documentation</a>{{ reldelim1 }}
+          <a href="{{ pathto('index') }}">{% trans %}Documentation{% endtrans %}</a>{{ reldelim1 }}
           {%- else %}
           <a href="{{ pathto('index') }}">{{ shorttitle }}</a>{{ reldelim1 }}
           {%- endif %}
 {% endblock %}
 {% block footer %}
     <div class="footer">
-    &copy; <a href="{{ pathto('copyright') }}">Copyright</a> {{ copyright|e }}.
+    &copy; <a href="{{ pathto('copyright') }}">{% trans %}Copyright{% endtrans %}</a> {{ copyright|e }}.
     <br />
-    The Python Software Foundation is a non-profit corporation.
-    <a href="https://www.python.org/psf/donations/">Please donate.</a>
+    {% trans %}The Python Software Foundation is a non-profit corporation.{% endtrans %}
+    <a href="https://www.python.org/psf/donations/">{% trans %}Please donate.{% endtrans %}</a>
     <br />
-    Last updated on {{ last_updated|e }}.
-    <a href="{{ pathto('bugs') }}">Found a bug</a>?
+    {% trans last_update=last_updated|e %}Last updated on {{ last_update }}.{% endtrans %}
+    {% trans pathto_bugs=pathto('bugs') %}<a href="{{ pathto_bugs }}">Found a bug</a>?{% endtrans %}
     <br />
-    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> {{ sphinx_version|e }}.
+    {% trans sphinx_version=sphinx_version|e %}Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> {{ sphinx_version }}.{% endtrans %}
     </div>
 {% endblock %}
 {% block sidebarsourcelink %}
 {%- if show_source and has_source and sourcename %}
 <h3>{{ _('This Page') }}</h3>
 <ul class="this-page-menu">
-  <li><a href="{{ pathto('bugs') }}">Report a Bug</a></li>
+  <li><a href="{{ pathto('bugs') }}">{% trans %}Report a Bug{% endtrans %}</a></li>
   <li><a href="{{ pathto('_sources/' + sourcename, true)|e }}"
-         rel="nofollow">Show Source</a></li>
+         rel="nofollow">{% trans %}Show Source{% endtrans %}</a></li>
 </ul>
 {%- endif %}
 {% endblock %}
index 7ab588b..73b7d1b 100644 (file)
@@ -92,7 +92,7 @@ in the script::
    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)
 
 
index d82adf6..b1f3f00 100644 (file)
@@ -210,6 +210,7 @@ definition looked like this::
    class MyClass:
        """A simple example class"""
        i = 12345
+
        def f(self):
            return 'hello world'
 
@@ -458,8 +459,10 @@ variable in the class is also ok.  For example::
 
    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 @@ argument::
    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 @@ will do nicely::
    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 @@ defines :meth:`~iterator.next`, then :meth:`__iter__` can just return ``self``::
        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
index 8ffaf3f..2af60d0 100644 (file)
@@ -284,7 +284,7 @@ You can see it if you really want to using :keyword:`print`::
 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
index 48faa9c..0e5891a 100644 (file)
@@ -452,7 +452,7 @@ objects, such as lists.
 
 Though tuples may seem similar to lists, they are often used in different
 situations and for different purposes.
-Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
+Tuples are :term:`immutable`, and usually contain a heterogeneous sequence of
 elements that are accessed via unpacking (see later in this section) or indexing
 (or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
 Lists are :term:`mutable`, and their elements are usually homogeneous and are
index 6f77def..f93a544 100644 (file)
@@ -180,14 +180,14 @@ One may also instantiate an exception first before raising it and add any
 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')
index 6fdc5f0..3e32af2 100644 (file)
@@ -326,10 +326,10 @@ beginning of the file as the reference point. ::
 
    >>> 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'
 
index 36acb06..d109018 100644 (file)
@@ -170,6 +170,6 @@ bpython_.
    :ref:`tut-customize`.
 
 
-.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
+.. _GNU Readline: https://tiswww.case.edu/php/chet/readline/rltop.html
 .. _IPython: http://ipython.scipy.org/
 .. _bpython: http://www.bpython-interpreter.org/
index e5ced49..b7be00e 100644 (file)
@@ -236,7 +236,7 @@ If you want to concatenate variables or a variable and a literal, use ``+``::
 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 @@ makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
 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
@@ -307,7 +307,7 @@ For non-negative indices, the length of a slice is the difference of the
 indices, if both are within bounds.  For example, the length of ``word[1:3]`` is
 2.
 
-Attempting to use a index that is too large will result in an error::
+Attempting to use an index that is too large will result in an error::
 
    >>> word[42]  # the word only has 6 characters
    Traceback (most recent call last):
@@ -357,9 +357,8 @@ The built-in function :func:`len` returns the length of a string::
       Both strings and Unicode strings support a large number of methods for
       basic transformations and searching.
 
-   :ref:`new-string-formatting`
-      Information about string formatting with :meth:`str.format` is described
-      here.
+   :ref:`formatstrings`
+      Information about string formatting with :meth:`str.format`.
 
    :ref:`string-formatting`
       The old formatting operations invoked when strings and Unicode strings are
index f5b8114..7b6fd9c 100644 (file)
@@ -33,7 +33,7 @@ called :file:`fibo.py` in the current directory with the following contents::
            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:
index f6239d6..4dab074 100644 (file)
@@ -283,7 +283,7 @@ file::
            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:
index 65fb093..50b74d1 100644 (file)
@@ -178,6 +178,7 @@ tasks in background while the main program continues to run::
            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)
index be7a5c1..89dfa6a 100644 (file)
@@ -43,7 +43,7 @@ More Python resources:
   for download.  Once you begin releasing code, you can register it here so that
   others can find it.
 
-* http://code.activestate.com/recipes/langs/python/: The Python Cookbook is a
+* https://code.activestate.com/recipes/langs/python/: The Python Cookbook is a
   sizable collection of code examples, larger modules, and useful scripts.
   Particularly notable contributions are collected in a book also titled Python
   Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.)
index 3f314b7..bcfcbd4 100644 (file)
@@ -613,6 +613,17 @@ conflict.
    times.
 
 
+.. envvar:: PYTHONHTTPSVERIFY
+
+   If this environment variable is set specifically to ``0``, then it is
+   equivalent to implicitly calling :func:`ssl._https_verify_certificates` with
+   ``enable=False`` when :mod:`ssl` is first imported.
+
+   Refer to the documentation of :func:`ssl._https_verify_certificates` for
+   details.
+
+   .. versionadded:: 2.7.12
+
 Debug-mode variables
 ~~~~~~~~~~~~~~~~~~~~
 
index 937a40a..ed91c76 100644 (file)
@@ -72,7 +72,7 @@ number of standard Unix command line editors, :program:`vim` and
 :program:`emacs` among them. If you want a more Mac-like editor,
 :program:`BBEdit` or :program:`TextWrangler` from Bare Bones Software (see
 http://www.barebones.com/products/bbedit/index.html) are good choices, as is
-:program:`TextMate` (see http://macromates.com/). Other editors include
+:program:`TextMate` (see https://macromates.com/). Other editors include
 :program:`Gvim` (http://macvim.org) and :program:`Aquamacs`
 (http://aquamacs.org/).
 
@@ -151,16 +151,16 @@ the foundation of most modern Mac development. Information on PyObjC is
 available from https://pythonhosted.org/pyobjc/.
 
 The standard Python GUI toolkit is :mod:`Tkinter`, based on the cross-platform
-Tk toolkit (http://www.tcl.tk). An Aqua-native version of Tk is bundled with OS
+Tk toolkit (https://www.tcl.tk). An Aqua-native version of Tk is bundled with OS
 X by Apple, and the latest version can be downloaded and installed from
-http://www.activestate.com; it can also be built from source.
+https://www.activestate.com; it can also be built from source.
 
 *wxPython* is another popular cross-platform GUI toolkit that runs natively on
 Mac OS X. Packages and documentation are available from http://www.wxpython.org.
 
 *PyQt* is another popular cross-platform GUI toolkit that runs natively on Mac
 OS X. More information can be found at
-http://www.riverbankcomputing.co.uk/software/pyqt/intro.
+https://riverbankcomputing.com/software/pyqt/intro.
 
 
 Distributing Python Applications on the Mac
index da4b743..dd754a6 100644 (file)
@@ -26,11 +26,11 @@ following links:
 
 .. seealso::
 
-   http://www.debian.org/doc/manuals/maint-guide/first.en.html
+   https://www.debian.org/doc/manuals/maint-guide/first.en.html
       for Debian users
-   http://en.opensuse.org/Portal:Packaging
+   https://en.opensuse.org/Portal:Packaging
       for OpenSuse users
-   http://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html
+   https://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html
       for Fedora users
    http://www.slackbook.org/html/package-management-making-packages.html
       for Slackware users
@@ -55,7 +55,7 @@ On FreeBSD and OpenBSD
 On OpenSolaris
 --------------
 
-You can get Python from `OpenCSW <http://www.opencsw.org/>`_.  Various versions
+You can get Python from `OpenCSW <https://www.opencsw.org/>`_.  Various versions
 of Python are available and can be installed with e.g. ``pkgutil -i python27``.
 
 
@@ -65,7 +65,7 @@ Building Python
 ===============
 
 If you want to compile CPython yourself, first thing you should do is get the
-`source <https://www.python.org/download/source/>`_. You can download either the
+`source <https://www.python.org/downloads/source/>`_. You can download either the
 latest release's source or just grab a fresh `clone
 <https://docs.python.org/devguide/setup.html#getting-the-source-code>`_.  (If you want
 to contribute patches, you will need a clone.)
@@ -143,10 +143,10 @@ Vim and Emacs are excellent editors which support Python very well.  For more
 information on how to code in Python in these editors, look at:
 
 * http://www.vim.org/scripts/script.php?script_id=790
-* http://sourceforge.net/projects/python-mode
+* https://sourceforge.net/projects/python-mode
 
 Geany is an excellent IDE with support for a lot of languages. For more
-information, read: http://www.geany.org/
+information, read: https://www.geany.org/
 
 Komodo edit is another extremely good IDE.  It also has support for a lot of
-languages. For more information, read http://komodoide.com/.
+languages. For more information, read https://komodoide.com/.
index d100303..f597476 100644 (file)
@@ -31,7 +31,7 @@ Check :pep:`11` for details on all unsupported platforms.
   following releases), this support was dropped and new releases are just
   expected to work on the Windows NT family.
 * `Windows CE <http://pythonce.sourceforge.net/>`_ is still supported.
-* The `Cygwin <http://cygwin.com/>`_ installer offers to install the Python
+* The `Cygwin <https://cygwin.com/>`_ installer offers to install the Python
   interpreter as well (cf. `Cygwin package source
   <ftp://ftp.uni-erlangen.de/pub/pc/gnuwin32/cygwin/mirrors/cygnus/
   release/python>`_, `Maintainer releases
@@ -42,7 +42,7 @@ for detailed information about platforms with precompiled installers.
 
 .. seealso::
 
-   `Python on XP <http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/>`_
+   `Python on XP <http://dooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/>`_
       "7 Minutes to "Hello World!""
       by Richard Dooling, 2006
 
@@ -52,9 +52,9 @@ for detailed information about platforms with precompiled installers.
       by Mark Pilgrim, 2004,
       ISBN 1-59059-356-1
 
-   `For Windows users <http://www.swaroopch.com/notes/python/#install_windows>`_
+   `For Windows users <http://python.swaroopch.com/installation.html#installation-on-windows>`_
       in "Installing Python"
-      in "`A Byte of Python <http://www.swaroopch.com/notes/python/>`_"
+      in "`A Byte of Python <http://python.swaroopch.com/>`_"
       by Swaroop C H, 2003
 
 
@@ -65,7 +65,7 @@ Besides the standard CPython distribution, there are modified packages including
 additional functionality.  The following is a list of popular versions and their
 key features:
 
-`ActivePython <http://www.activestate.com/Products/activepython/>`_
+`ActivePython <https://www.activestate.com/activepython/>`_
     Installer with multi-platform compatibility, documentation, PyWin32
 
 `Enthought Python Distribution <https://www.enthought.com/products/epd/>`_
@@ -123,13 +123,13 @@ Consult :command:`set /?` for details on this behaviour.
 
 .. seealso::
 
-   http://support.microsoft.com/kb/100843
+   https://support.microsoft.com/kb/100843
       Environment variables in Windows NT
 
-   http://support.microsoft.com/kb/310519
+   https://support.microsoft.com/kb/310519
       How To Manage Environment Variables in Windows XP
 
-   http://www.chem.gla.ac.uk/~louis/software/faq/q1.html
+   https://www.chem.gla.ac.uk/~louis/software/faq/q1.html
       Setting Environment variables, Louis J. Farrugia
 
 
@@ -242,18 +242,18 @@ The Windows-specific standard modules are documented in
 PyWin32
 -------
 
-The `PyWin32 <http://python.net/crew/mhammond/win32/>`_ module by Mark Hammond
+The `PyWin32 <https://pypi.python.org/pypi/pywin32>`_ module by Mark Hammond
 is a collection of modules for advanced Windows-specific support.  This includes
 utilities for:
 
-* `Component Object Model <http://www.microsoft.com/com/>`_ (COM)
+* `Component Object Model <https://www.microsoft.com/com/>`_ (COM)
 * Win32 API calls
 * Registry
 * Event log
-* `Microsoft Foundation Classes <http://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx>`_ (MFC)
+* `Microsoft Foundation Classes <https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx>`_ (MFC)
   user interfaces
 
-`PythonWin <http://web.archive.org/web/20060524042422/
+`PythonWin <https://web.archive.org/web/20060524042422/
 https://www.python.org/windows/pythonwin/>`_ is a sample MFC application
 shipped with PyWin32.  It is an embeddable IDE with a built-in debugger.
 
@@ -291,7 +291,7 @@ Compiling Python on Windows
 ===========================
 
 If you want to compile CPython yourself, first thing you should do is get the
-`source <https://www.python.org/download/source/>`_. You can download either the
+`source <https://www.python.org/downloads/source/>`_. You can download either the
 latest release's source or just grab a fresh `checkout
 <https://docs.python.org/devguide/setup.html#getting-the-source-code>`_.
 
index 67e1fc7..2cdd3a2 100644 (file)
@@ -61,7 +61,7 @@ how Python is developed: in May 2000 the Python developers began using the tools
 made available by SourceForge for storing  source code, tracking bug reports,
 and managing the queue of patch submissions.  To report bugs or submit patches
 for Python 2.0, use the bug tracking and patch manager tools available from
-Python's project page, located at http://sourceforge.net/projects/python/.
+Python's project page, located at https://sourceforge.net/projects/python/.
 
 The most important of the services now hosted at SourceForge is the Python CVS
 tree, the version-controlled repository containing the source code for Python.
@@ -130,7 +130,7 @@ Guidelines":
 Read the rest of PEP 1 for the details of the PEP editorial process, style, and
 format.  PEPs are kept in the Python CVS tree on SourceForge, though they're not
 part of the Python 2.0 distribution, and are also available in HTML form from
-https://www.python.org/peps/.  As of September 2000, there are 25 PEPS, ranging
+https://www.python.org/dev/peps/.  As of September 2000, there are 25 PEPS, ranging
 from PEP 201, "Lockstep Iteration", to PEP 225, "Elementwise/Objectwise
 Operators".
 
@@ -337,7 +337,7 @@ comprehension below is a syntax error, while the second one is correct::
    [ (x,y) for x in seq1 for y in seq2]
 
 The idea of list comprehensions originally comes from the functional programming
-language Haskell (http://www.haskell.org).  Greg Ewing argued most effectively
+language Haskell (https://www.haskell.org).  Greg Ewing argued most effectively
 for adding them to Python and wrote the initial list comprehension patch, which
 was then discussed for a seemingly endless time on the python-dev mailing list
 and kept up-to-date by Skip Montanaro.
index 019741c..c34ba8a 100644 (file)
@@ -219,7 +219,7 @@ comparison.  I won't cover the C API here, but will refer you to PEP 207, or to
 
 .. seealso::
 
-   :pep:`207` - Rich Comparisions
+   :pep:`207` - Rich Comparisons
       Written by Guido van Rossum, heavily based on earlier work by David Ascher, and
       implemented by Guido van Rossum.
 
@@ -562,7 +562,7 @@ You can start creating packages containing :file:`PKG-INFO` even if you're not
 using Python 2.1, since a new release of the Distutils will be made for users of
 earlier Python versions.  Version 1.0.2 of the Distutils includes the changes
 described in PEP 241, as well as various bugfixes and enhancements.  It will be
-available from  the Distutils SIG at https://www.python.org/sigs/distutils-sig/.
+available from the Distutils SIG at https://www.python.org/community/sigs/current/distutils-sig/.
 
 
 .. seealso::
@@ -731,7 +731,7 @@ of the more notable changes are:
          ...
 
   For a fuller discussion of the line I/O changes, see the python-dev summary for
-  January 1-15, 2001 at https://www.python.org/dev/summary/2001-01-1/.
+  January 1-15, 2001 at https://mail.python.org/pipermail/python-dev/2001-January/.
 
 * A new method, :meth:`popitem`, was added to dictionaries to enable
   destructively iterating through the contents of a dictionary; this can be faster
index 3eb9ce8..43bc2ab 100644 (file)
@@ -24,8 +24,8 @@ up irregularities and dark corners of the language design.
 This article doesn't attempt to provide a complete specification of the new
 features, but instead provides a convenient overview.  For full details, you
 should refer to the documentation for Python 2.2, such as the `Python Library
-Reference <https://www.python.org/doc/2.2/lib/lib.html>`_ and the `Python
-Reference Manual <https://www.python.org/doc/2.2/ref/ref.html>`_.  If you want to
+Reference <https://docs.python.org/2.2/lib/lib.html>`_ and the `Python
+Reference Manual <https://docs.python.org/2.2/ref/ref.html>`_.  If you want to
 understand the complete implementation and design rationale for a change, refer
 to the PEP for a particular new feature.
 
@@ -395,7 +395,7 @@ This section has just been a quick overview of the new features, giving enough
 of an explanation to start you programming, but many details have been
 simplified or ignored.  Where should you go to get a more complete picture?
 
-https://www.python.org/2.2/descrintro.html is a lengthy tutorial introduction to
+https://docs.python.org/dev/howto/descriptor.html is a lengthy tutorial introduction to
 the descriptor features, written by Guido van Rossum. If my description has
 whetted your appetite, go read this tutorial next, because it goes into much
 more detail about the new features while still remaining quite easy to read.
@@ -632,10 +632,10 @@ queen threatens another) and the Knight's Tour (a route that takes a knight to
 every square of an $NxN$ chessboard without visiting any square twice).
 
 The idea of generators comes from other programming languages, especially Icon
-(http://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
+(https://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
 Icon, every expression and function call behaves like a generator.  One example
 from "An Overview of the Icon Programming Language" at
-http://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
+https://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
 like::
 
    sentence := "Store it in the neighboring harbor"
@@ -720,7 +720,7 @@ possible types of the operands.
 
 (The controversy is over whether this is *really* a design flaw, and whether
 it's worth breaking existing code to fix this.  It's caused endless discussions
-on python-dev, and in July 2001 erupted into an storm of acidly sarcastic
+on python-dev, and in July 2001 erupted into a storm of acidly sarcastic
 postings on :newsgroup:`comp.lang.python`. I won't argue for either side here
 and will stick to describing what's  implemented in 2.2.  Read :pep:`238` for a
 summary of arguments and counter-arguments.)
@@ -758,8 +758,8 @@ Here are the changes 2.2 introduces:
   operators.
 
 * Python 2.2 supports some command-line arguments for testing whether code will
-  works with the changed division semantics.  Running python with :option:`-Q
-  warn` will cause a warning to be issued whenever division is applied to two
+  work with the changed division semantics.  Running python with :option:`-Q
+  warn <-Q>` will cause a warning to be issued whenever division is applied to two
   integers.  You can use this to find code that's affected by the change and fix
   it.  By default, Python 2.2 will simply perform classic division without a
   warning; the warning will be turned on by default in Python 2.3.
index d9f1b7e..bcf1b61 100644 (file)
@@ -218,10 +218,10 @@ queen threatens another) and the Knight's Tour (a route that takes a knight to
 every square of an $NxN$ chessboard without visiting any square twice).
 
 The idea of generators comes from other programming languages, especially Icon
-(http://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
+(https://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
 Icon, every expression and function call behaves like a generator.  One example
 from "An Overview of the Icon Programming Language" at
-http://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
+https://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
 like::
 
    sentence := "Store it in the neighboring harbor"
@@ -411,7 +411,7 @@ PEP 279: enumerate()
 
 A new built-in function, :func:`enumerate`, will make certain loops a bit
 clearer.  ``enumerate(thing)``, where *thing* is either an iterator or a
-sequence, returns a iterator that will return ``(0, thing[0])``, ``(1,
+sequence, returns an iterator that will return ``(0, thing[0])``, ``(1,
 thing[1])``, ``(2, thing[2])``, and so forth.
 
 A common idiom to change every element of a list looks like this::
@@ -1057,7 +1057,7 @@ Here are all of the changes that Python 2.3 makes to the core Python language.
 * A new warning, :exc:`PendingDeprecationWarning` was added to indicate features
   which are in the process of being deprecated.  The warning will *not* be printed
   by default.  To check for use of features that will be deprecated in the future,
-  supply :option:`-Walways::PendingDeprecationWarning::` on the command line or
+  supply :option:`-Walways::PendingDeprecationWarning:: <-W>` on the command line or
   use :func:`warnings.filterwarnings`.
 
 * The process of deprecating string-based exceptions, as in ``raise "Error
@@ -1080,9 +1080,9 @@ Here are all of the changes that Python 2.3 makes to the core Python language.
   hierarchy.  Classic classes are unaffected by this change.  Python 2.2
   originally used a topological sort of a class's ancestors, but 2.3 now uses the
   C3 algorithm as described in the paper `"A Monotonic Superclass Linearization
-  for Dylan" <http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>`_. To
+  for Dylan" <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910>`_. To
   understand the motivation for this change,  read Michele Simionato's article
-  `"Python 2.3 Method Resolution Order" <https://www.python.org/2.3/mro.html>`_, or
+  `"Python 2.3 Method Resolution Order" <http://www.phyast.pitt.edu/~micheles/mro.html>`_, or
   read the thread on python-dev starting with the message at
   https://mail.python.org/pipermail/python-dev/2002-October/029035.html. Samuele
   Pedroni first pointed out the problem and also implemented the fix by coding the
@@ -1306,7 +1306,7 @@ complete list of changes, or look through the CVS logs for all the details.
   partially sorted order such that, for every index *k*, ``heap[k] <=
   heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]``.  This makes it quick to remove the
   smallest item, and inserting a new item while maintaining the heap property is
-  O(lg n).  (See http://www.nist.gov/dads/HTML/priorityque.html for more
+  O(lg n).  (See https://xlinux.nist.gov/dads//HTML/priorityque.html for more
   information about the priority queue data structure.)
 
   The :mod:`heapq` module provides :func:`heappush` and :func:`heappop` functions
@@ -1734,7 +1734,7 @@ The optparse Module
 The :mod:`getopt` module provides simple parsing of command-line arguments.  The
 new :mod:`optparse` module (originally named Optik) provides more elaborate
 command-line parsing that follows the Unix conventions, automatically creates
-the output for :option:`--help`, and can perform different actions for different
+the output for :option:`!--help`, and can perform different actions for different
 options.
 
 You start by creating an instance of :class:`OptionParser` and telling it what
@@ -1858,7 +1858,7 @@ and bundle it with the source of your extension.
 
 .. seealso::
 
-   https://svn.python.org/view/python/trunk/Objects/obmalloc.c
+   https://hg.python.org/cpython/file/default/Objects/obmalloc.c
       For the full details of the pymalloc implementation, see the comments at
       the top of the file :file:`Objects/obmalloc.c` in the Python source code.
       The above link points to the file within the python.org SVN browser.
@@ -1949,7 +1949,7 @@ The RPM spec files, found in the :file:`Misc/RPM/` directory in the Python
 source distribution, were updated for 2.3.  (Contributed by Sean Reifschneider.)
 
 Other new platforms now supported by Python include AtheOS
-(http://www.atheos.cx/), GNU/Hurd, and OpenVMS.
+(http://atheos.cx/), GNU/Hurd, and OpenVMS.
 
 .. ======================================================================
 
@@ -1973,7 +1973,7 @@ Some of the more notable changes are:
   the Python program as part of its execution.
 
 * The :file:`regrtest.py` script now provides a way to allow "all resources
-  except *foo*."  A resource name passed to the :option:`-u` option can now be
+  except *foo*."  A resource name passed to the :option:`!-u` option can now be
   prefixed with a hyphen (``'-'``) to mean "remove this resource."  For example,
   the option '``-uall,-bsddb``' could be used to enable the use of all resources
   except ``bsddb``.
index 73ba5b9..5555e7d 100644 (file)
@@ -337,7 +337,7 @@ returned.
       wrote patches implementing function decorators, but the one that was actually
       checked in was patch #979728, written by Mark Russell.
 
-   https://www.python.org/moin/PythonDecoratorLibrary
+   https://wiki.python.org/moin/PythonDecoratorLibrary
       This Wiki page contains several examples of decorators.
 
 .. ======================================================================
@@ -687,7 +687,7 @@ includes a quick-start tutorial and a reference.
       The article uses Fortran code to illustrate many of the problems that floating-
       point inaccuracy can cause.
 
-   http://www2.hursley.ibm.com/decimal/
+   http://speleotrove.com/decimal/
       A description of a decimal-based representation.  This representation is being
       proposed as a standard, and underlies the new Python decimal type.  Much of this
       material was written by Mike Cowlishaw, designer of the Rexx language.
@@ -756,7 +756,7 @@ API that perform ASCII-only conversions, ignoring the locale setting:
   :c:type:`double` to an ASCII string.
 
 The code for these functions came from the GLib library
-(http://library.gnome.org/devel/glib/stable/), whose developers kindly
+(https://developer.gnome.org/glib/stable/), whose developers kindly
 relicensed the relevant functions and donated them to the Python Software
 Foundation.  The :mod:`locale` module  can now change the numeric locale,
 letting extensions such as GTK+  produce the correct results.
@@ -1481,10 +1481,10 @@ Some of the changes to Python's build process and to the C API are:
 
 * Python can now be built with additional profiling for the interpreter itself,
   intended as an aid to people developing the Python core.  Providing
-  :option:`----enable-profiling` to the :program:`configure` script will let you
+  :option:`--enable-profiling` to the :program:`configure` script will let you
   profile the interpreter with :program:`gprof`, and providing the
-  :option:`----with-tsc` switch enables profiling using the Pentium's Time-Stamp-
-  Counter register.  Note that the :option:`----with-tsc` switch is slightly
+  :option:`--with-tsc` switch enables profiling using the Pentium's Time-Stamp-
+  Counter register.  Note that the :option:`--with-tsc` switch is slightly
   misnamed, because the profiling feature also works on the PowerPC platform,
   though that processor architecture doesn't call that register "the TSC
   register".  (Contributed by Jeremy Hylton.)
index b0c0af0..4d23d12 100644 (file)
@@ -330,7 +330,7 @@ statement, only the ``from ... import`` form.
    :pep:`328` - Imports: Multi-Line and Absolute/Relative
       PEP written by Aahz; implemented by Thomas Wouters.
 
-   http://codespeak.net/py/current/doc/index.html
+   https://pylib.readthedocs.org/
       The py library by Holger Krekel, which contains the :mod:`py.std` package.
 
 .. ======================================================================
@@ -547,7 +547,7 @@ exhausted.
       Earlier versions of these features were proposed in  :pep:`288` by Raymond
       Hettinger and :pep:`325` by Samuele Pedroni.
 
-   http://en.wikipedia.org/wiki/Coroutine
+   https://en.wikipedia.org/wiki/Coroutine
       The Wikipedia entry for  coroutines.
 
    http://www.sidhe.org/~dan/blog/archives/000178.html
@@ -1095,7 +1095,7 @@ Here are all of the changes that Python 2.5 makes to the core Python language.
   log all the paths searched. In Python 2.5, a new :exc:`ImportWarning` warning is
   triggered when an import would have picked up a directory as a package but no
   :file:`__init__.py` was found.  This warning is silently ignored by default;
-  provide the :option:`-Wd` option when running the Python executable to display
+  provide the :option:`-Wd <-W>` option when running the Python executable to display
   the warning message. (Implemented by Thomas Wouters.)
 
 * The list of base classes in a class definition can now be empty.   As an
@@ -1126,7 +1126,7 @@ or ``exit()`` will now exit the interpreter as they expect.  (Implemented by
 Georg Brandl.)
 
 The Python executable now accepts the standard long options  :option:`--help`
-and :option:`--version`; on Windows,  it also accepts the :option:`/?` option
+and :option:`--version`; on Windows,  it also accepts the :option:`/? <-?>` option
 for displaying a help message. (Implemented by Georg Brandl.)
 
 .. ======================================================================
@@ -1528,7 +1528,7 @@ complete list of changes, or look through the SVN logs for all the details.
 * The :mod:`socket` module now supports :const:`AF_NETLINK` sockets on Linux,
   thanks to a patch from Philippe Biondi.   Netlink sockets are a Linux-specific
   mechanism for communications between a user-space process and kernel code; an
-  introductory  article about them is at http://www.linuxjournal.com/article/7356.
+  introductory  article about them is at https://www.linuxjournal.com/article/7356.
   In Python code, netlink addresses are represented as a tuple of 2 integers,
   ``(pid, group_mask)``.
 
@@ -1640,7 +1640,7 @@ complete list of changes, or look through the SVN logs for all the details.
 * The :mod:`webbrowser` module received a number of enhancements. It's now
   usable as a script with ``python -m webbrowser``, taking a URL as the argument;
   there are a number of switches  to control the behaviour (:option:`-n` for a new
-  browser window,  :option:`-t` for a new tab).  New module-level functions,
+  browser window,  :option:`!-t` for a new tab).  New module-level functions,
   :func:`open_new` and :func:`open_new_tab`, were added  to support this.  The
   module's :func:`open` function supports an additional feature, an *autoraise*
   parameter that signals whether to raise the open window when possible. A number
@@ -2013,7 +2013,7 @@ This example uses the iterator form::
    >>>
 
 For more information about the SQL dialect supported by SQLite, see
-http://www.sqlite.org.
+https://www.sqlite.org.
 
 
 .. seealso::
@@ -2021,7 +2021,7 @@ http://www.sqlite.org.
    http://www.pysqlite.org
       The pysqlite web page.
 
-   http://www.sqlite.org
+   https://www.sqlite.org
       The SQLite web page; the documentation describes the syntax and the available
       data types for the supported SQL dialect.
 
@@ -2088,7 +2088,7 @@ Changes to Python's build process and to the C API include:
   provided the results of their examination of the Python source code.  The
   analysis found about 60 bugs that  were quickly fixed.  Many of the bugs were
   refcounting problems, often occurring in error-handling code.  See
-  http://scan.coverity.com for the statistics.
+  https://scan.coverity.com for the statistics.
 
 * The largest change to the C API came from :pep:`353`, which modifies the
   interpreter to use a :c:type:`Py_ssize_t` type definition instead of
index edba4e1..4d06bc3 100644 (file)
@@ -151,10 +151,10 @@ The infrastructure committee of the Python Software Foundation
 therefore posted a call for issue trackers, asking volunteers to set
 up different products and import some of the bugs and patches from
 SourceForge.  Four different trackers were examined: `Jira
-<http://www.atlassian.com/software/jira/>`__,
-`Launchpad <http://www.launchpad.net>`__,
+<https://www.atlassian.com/software/jira/>`__,
+`Launchpad <https://launchpad.net/>`__,
 `Roundup <http://roundup.sourceforge.net/>`__, and
-`Trac <http://trac.edgewall.org/>`__.
+`Trac <https://trac.edgewall.org/>`__.
 The committee eventually settled on Jira
 and Roundup as the two candidates.  Jira is a commercial product that
 offers no-cost hosted instances to free-software projects; Roundup
@@ -215,7 +215,7 @@ the time required to finish the job.
 During the 2.6 development cycle, Georg Brandl put a lot of effort
 into building a new toolchain for processing the documentation.  The
 resulting package is called Sphinx, and is available from
-http://sphinx.pocoo.org/.
+http://sphinx-doc.org/.
 
 Sphinx concentrates on HTML output, producing attractively styled and
 modern HTML; printed output is still supported through conversion to
@@ -1427,7 +1427,7 @@ one, :func:`math.trunc`, that's been backported to Python 2.6.
    :pep:`3141` - A Type Hierarchy for Numbers
       PEP written by Jeffrey Yasskin.
 
-   `Scheme's numerical tower <http://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
+   `Scheme's numerical tower <https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
 
    `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
 
@@ -1792,7 +1792,7 @@ changes, or look through the Subversion logs for all the details.
 * The :mod:`bsddb` module also has a new maintainer, Jesús Cea Avion, and the package
   is now available as a standalone package.  The web page for the package is
   `www.jcea.es/programacion/pybsddb.htm
-  <http://www.jcea.es/programacion/pybsddb.htm>`__.
+  <https://www.jcea.es/programacion/pybsddb.htm>`__.
   The plan is to remove the package from the standard library
   in Python 3.0, because its pace of releases is much more frequent than
   Python's.
@@ -1922,7 +1922,7 @@ changes, or look through the Subversion logs for all the details.
   the left to six places.  (Contributed by Skip Montanaro; :issue:`1158`.)
 
 * The :mod:`decimal` module was updated to version 1.66 of
-  `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__.  New features
+  `the General Decimal Specification <http://speleotrove.com/decimal/decarith.html>`__.  New features
   include some methods for some basic mathematical functions such as
   :meth:`exp` and :meth:`log10`::
 
@@ -2885,7 +2885,7 @@ Improved SSL Support
 
 Bill Janssen made extensive improvements to Python 2.6's support for
 the Secure Sockets Layer by adding a new module, :mod:`ssl`, that's
-built atop the `OpenSSL <http://www.openssl.org/>`__ library.
+built atop the `OpenSSL <https://www.openssl.org/>`__ library.
 This new module provides more control over the protocol negotiated,
 the X.509 certificates used, and has better support for writing SSL
 servers (as opposed to clients) in Python.  The existing SSL support
@@ -3150,7 +3150,7 @@ Port-Specific Changes: Mac OS X
   :func:`macostools.touched` function to be removed because it depended on the
   :mod:`macfs` module.  (:issue:`1490190`)
 
-* Many other Mac OS modules have been deprecated and will removed in
+* Many other Mac OS modules have been deprecated and will be removed in
   Python 3.0:
   :mod:`_builtinSuites`,
   :mod:`aepack`,
index e2560c7..c391389 100644 (file)
@@ -1029,7 +1029,7 @@ changes, or look through the Subversion logs for all the details.
 
 * Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
   to version 4.8.4 of
-  `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
+  `the pybsddb package <https://www.jcea.es/programacion/pybsddb.htm>`__.
   The new version features better Python 3.x compatibility, various bug fixes,
   and adds several new BerkeleyDB flags and methods.
   (Updated by Jesús Cea Avión; :issue:`8156`.  The pybsddb
@@ -1157,7 +1157,7 @@ changes, or look through the Subversion logs for all the details.
 * The :mod:`ctypes` module now always converts ``None`` to a C NULL
   pointer for arguments declared as pointers.  (Changed by Thomas
   Heller; :issue:`4606`.)  The underlying `libffi library
-  <http://sourceware.org/libffi/>`__ has been updated to version
+  <https://sourceware.org/libffi/>`__ has been updated to version
   3.0.9, containing various fixes for different platforms.  (Updated
   by Matthias Klose; :issue:`8142`.)
 
@@ -1513,7 +1513,7 @@ changes, or look through the Subversion logs for all the details.
   (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
 
 * Updated module: the :mod:`sqlite3` module has been updated to
-  version 2.6.0 of the `pysqlite package <http://code.google.com/p/pysqlite/>`__. Version 2.6.0 includes a number of bugfixes, and adds
+  version 2.6.0 of the `pysqlite package <https://github.com/ghaering/pysqlite>`__. Version 2.6.0 includes a number of bugfixes, and adds
   the ability to load SQLite extensions from shared libraries.
   Call the ``enable_load_extension(True)`` method to enable extensions,
   and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
@@ -1530,7 +1530,7 @@ changes, or look through the Subversion logs for all the details.
   *ciphers* argument that's a string listing the encryption algorithms
   to be allowed; the format of the string is described
   `in the OpenSSL documentation
-  <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
+  <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`__.
   (Added by Antoine Pitrou; :issue:`8322`.)
 
   Another change makes the extension load all of OpenSSL's ciphers and
@@ -1783,7 +1783,7 @@ on being added to Tcl/Tck release 8.5.
 To learn more, read the :mod:`ttk` module documentation.  You may also
 wish to read the Tcl/Tk manual page describing the
 Ttk theme engine, available at
-http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
+https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
 screenshots of the Python/Ttk code in use are at
 http://code.google.com/p/python-ttk/wiki/Screenshots.
 
@@ -1820,12 +1820,12 @@ Consult the :mod:`unittest` module documentation for more details.
 
 The :func:`~unittest.main` function supports some other new options:
 
-* :option:`-b` or :option:`--buffer` will buffer the standard output
+* :option:`-b <unittest -b>` or :option:`--buffer` will buffer the standard output
   and standard error streams during each test.  If the test passes,
   any resulting output will be discarded; on failure, the buffered
   output will be displayed.
 
-* :option:`-c` or :option:`--catch` will cause the control-C interrupt
+* :option:`-c <unittest -c>` or :option:`--catch` will cause the control-C interrupt
   to be handled more gracefully.  Instead of interrupting the test
   process immediately, the currently running test will be completed
   and then the partial results up to the interruption will be reported.
@@ -1839,7 +1839,7 @@ The :func:`~unittest.main` function supports some other new options:
   :func:`~unittest.removeHandler` decorator that can be used to mark tests that
   should have the control-C handling disabled.
 
-* :option:`-f` or :option:`--failfast` makes
+* :option:`-f <unittest -f>` or :option:`--failfast` makes
   test execution stop immediately when a test fails instead of
   continuing to execute further tests.  (Suggested by Cliff Dyer and
   implemented by Michael Foord; :issue:`8074`.)
@@ -2079,7 +2079,7 @@ Changes to Python's build process and to the C API include:
 
 * The latest release of the GNU Debugger, GDB 7, can be `scripted
   using Python
-  <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
+  <https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
   When you begin debugging an executable program P, GDB will look for
   a file named ``P-gdb.py`` and automatically read it.  Dave Malcolm
   contributed a :file:`python-gdb.py` that adds a number of
@@ -2149,7 +2149,7 @@ Changes to Python's build process and to the C API include:
   with *updatepath* set to false.
 
   Security issue reported as `CVE-2008-5983
-  <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_;
+  <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_;
   discussed in :issue:`5753`, and fixed by Antoine Pitrou.
 
 * New macros: the Python header files now define the following macros:
@@ -2381,7 +2381,7 @@ Other Changes and Fixes
   takes an integer specifying how many tests run in parallel. This
   allows reducing the total runtime on multi-core machines.
   This option is compatible with several other options, including the
-  :option:`-R` switch which is known to produce long runtimes.
+  :option:`!-R` switch which is known to produce long runtimes.
   (Added by Antoine Pitrou, :issue:`6152`.)  This can also be used
   with a new :option:`-F` switch that runs selected tests in a loop
   until they fail.  (Added by Antoine Pitrou; :issue:`7312`.)
@@ -2588,7 +2588,7 @@ PEP 477: Backport ensurepip (PEP 453) to Python 2.7
 
 :pep:`477` approves the inclusion of the :pep:`453` ensurepip module and the
 improved documentation that was enabled by it in the Python 2.7 maintenance
-releases, appearing first in the the Python 2.7.9 release.
+releases, appearing first in the Python 2.7.9 release.
 
 
 Bootstrapping pip By Default
@@ -2649,11 +2649,12 @@ and :ref:`distutils-index`.
 PEP 476: Enabling certificate verification by default for stdlib http clients
 -----------------------------------------------------------------------------
 
-:mod:`httplib` and modules which use it, such as :mod:`urllib2` and
-:mod:`xmlrpclib`, will now verify that the server presents a certificate
-which is signed by a CA in the platform trust store and whose hostname matches
-the hostname being requested by default, significantly improving security for
-many applications.
+:pep:`476` updated :mod:`httplib` and modules which use it, such as
+:mod:`urllib2` and :mod:`xmlrpclib`, to now verify that the server
+presents a certificate which is signed by a Certificate Authority in the
+platform trust store and whose hostname matches the hostname being requested
+by default, significantly improving security for many applications. This
+change was made in the Python 2.7.9 release.
 
 For applications which require the old previous behavior, they can pass an
 alternate context::
@@ -2670,6 +2671,29 @@ alternate context::
 
     urllib2.urlopen("https://invalid-cert", context=context)
 
+
+PEP 493: HTTPS verification migration tools for Python 2.7
+----------------------------------------------------------
+
+:pep:`493` provides additional migration tools to support a more incremental
+infrastructure upgrade process for environments containing applications and
+services relying on the historically permissive processing of server
+certificates when establishing client HTTPS connections.  These additions were
+made in the Python 2.7.12 release.
+
+These tools are intended for use in cases where affected applications and
+services can't be modified to explicitly pass a more permissive SSL context
+when establishing the connection.
+
+For applications and services which can't be modified at all, the new
+``PYTHONHTTPSVERIFY`` environment variable may be set to ``0`` to revert an
+entire Python process back to the default permissive behaviour of Python 2.7.8
+and earlier.
+
+For cases where the connection establishment code can't be modified, but the
+overall application can be, the new :func:`ssl._https_verify_certificates`
+function can be used to adjust the default behaviour at runtime.
+
 .. ======================================================================
 
 .. _acks27:
index 38b2958..7456fd6 100644 (file)
@@ -70,7 +70,7 @@ PyAPI_DATA(PyTypeObject) PyCode_Type;
 /* Public interface */
 PyAPI_FUNC(PyCodeObject *) PyCode_New(
        int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *,
-       PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *); 
+       PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *);
         /* same as struct above */
 
 /* Creates a new empty code object with the specified source location. */
@@ -98,6 +98,15 @@ typedef struct _addr_pair {
 PyAPI_FUNC(int) _PyCode_CheckLineNumber(PyCodeObject* co,
                                         int lasti, PyAddrPair *bounds);
 
+/* Create a comparable key used to compare constants taking in account the
+ * object type. It is used to make sure types are not coerced (e.g., float and
+ * complex) _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms
+ *
+ * Return (type(obj), obj, ...): a tuple with variable size (at least 2 items)
+ * depending on the type and the value. The type is the first item to not
+ * compare bytes and str which can raise a BytesWarning exception. */
+PyAPI_FUNC(PyObject*) _PyCode_ConstantKey(PyObject *obj);
+
 PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts,
                                       PyObject *names, PyObject *lineno_obj);
 
index ece01c6..ef524a4 100644 (file)
@@ -108,6 +108,7 @@ PyAPI_DATA(PyTypeObject) PyDictValues_Type;
 
 PyAPI_FUNC(PyObject *) PyDict_New(void);
 PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key);
+PyAPI_FUNC(PyObject *) _PyDict_GetItemWithError(PyObject *mp, PyObject *key);
 PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item);
 PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
 PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
index 7cd616b..f19b1c5 100644 (file)
@@ -2,7 +2,7 @@
 /* List object interface */
 
 /*
-Another generally useful object type is an list of object pointers.
+Another generally useful object type is a list of object pointers.
 This is a mutable type: the list items can be changed, and items can be
 added or removed.  Out-of-range indices or non-list objects are ignored.
 
index bf0b621..e6a5c45 100644 (file)
@@ -33,7 +33,7 @@ PyAPI_FUNC(PyObject *) PyMemoryView_GetContiguous(PyObject *base,
        original buffer if a copy must be made.  If buffertype is
        PyBUF_WRITE and the buffer is not contiguous an error will
        be raised.  In this circumstance, the user can use
-       PyBUF_SHADOW to ensure that a writable temporary
+       PyBUF_SHADOW to ensure that a writable temporary
        contiguous buffer is returned.  The contents of this
        contiguous buffer will be copied back into the original
        object after the memoryview object is deleted as long as
index 4ee1f8e..9fc0583 100644 (file)
@@ -824,6 +824,39 @@ PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
 #define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0)
 #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0)
 
+/* Safely decref `op` and set `op` to `op2`.
+ *
+ * As in case of Py_CLEAR "the obvious" code can be deadly:
+ *
+ *     Py_DECREF(op);
+ *     op = op2;
+ *
+ * The safe way is:
+ *
+ *      Py_SETREF(op, op2);
+ *
+ * That arranges to set `op` to `op2` _before_ decref'ing, so that any code
+ * triggered as a side-effect of `op` getting torn down no longer believes
+ * `op` points to a valid object.
+ *
+ * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of
+ * Py_DECREF.
+ */
+
+#define Py_SETREF(op, op2)                      \
+    do {                                        \
+        PyObject *_py_tmp = (PyObject *)(op);   \
+        (op) = (op2);                           \
+        Py_DECREF(_py_tmp);                     \
+    } while (0)
+
+#define Py_XSETREF(op, op2)                     \
+    do {                                        \
+        PyObject *_py_tmp = (PyObject *)(op);   \
+        (op) = (op2);                           \
+        Py_XDECREF(_py_tmp);                    \
+    } while (0)
+
 /*
 These are provided as conveniences to Python runtime embedders, so that
 they can have object code that is not dependent on Python compilation flags.
index 3538831..e47005d 100644 (file)
 /*--start constants--*/
 #define PY_MAJOR_VERSION       2
 #define PY_MINOR_VERSION       7
-#define PY_MICRO_VERSION       11
+#define PY_MICRO_VERSION       12
 #define PY_RELEASE_LEVEL       PY_RELEASE_LEVEL_FINAL
 #define PY_RELEASE_SERIAL      0
 
 /* Version as a string */
-#define PY_VERSION             "2.7.11"
+#define PY_VERSION             "2.7.12"
 /*--end constants--*/
 
 /* Subversion Revision number of this file (not of the repository). Empty
index 2ef205e..51134ef 100644 (file)
@@ -215,7 +215,7 @@ PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
 
 /* Export the old function so that the existing API remains available: */
 PyAPI_FUNC(void) PyErr_BadInternalCall(void);
-PyAPI_FUNC(void) _PyErr_BadInternalCall(char *filename, int lineno);
+PyAPI_FUNC(void) _PyErr_BadInternalCall(const char *filename, int lineno);
 /* Mask the old API with a call to the new API for code compiled under
    Python 2.0: */
 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
index 24e7b8d..0c28f5c 100644 (file)
@@ -66,7 +66,7 @@
       * Therefore surpress the toolbox-glue in 64-bit mode.
       */
 
-    /* In 64-bit mode setpgrp always has no argments, in 32-bit
+    /* In 64-bit mode setpgrp always has no arguments, in 32-bit
      * mode that depends on the compilation environment
      */
 #       undef SETPGRP_HAVE_ARG
index 2151dda..cfb02b0 100644 (file)
@@ -155,7 +155,7 @@ PyAPI_DATA(PyThreadState*) _PyOS_ReadlineTState;
 
 /* Stack size, in "pointers" (so we get extra safety margins
    on 64-bit platforms).  On a 32-bit platform, this translates
-   to a 8k margin. */
+   to an 8k margin. */
 #define PYOS_STACK_MARGIN 2048
 
 #if defined(WIN32) && !defined(MS_WIN64) && defined(_MSC_VER) && _MSC_VER >= 1300
index 18b5b41..12cc093 100644 (file)
@@ -129,7 +129,7 @@ PyAPI_FUNC(PyObject*) PyString_AsEncodedObject(
 /* Encodes a string object and returns the result as Python string
    object.   
    
-   If the codec returns an Unicode object, the object is converted
+   If the codec returns a Unicode object, the object is converted
    back to a string using the default encoding.
 
    DEPRECATED - use PyString_AsEncodedObject() instead. */
@@ -152,7 +152,7 @@ PyAPI_FUNC(PyObject*) PyString_AsDecodedObject(
 /* Decodes a string object and returns the result as Python string
    object.  
    
-   If the codec returns an Unicode object, the object is converted
+   If the codec returns a Unicode object, the object is converted
    back to a string using the default encoding.
 
    DEPRECATED - use PyString_AsDecodedObject() instead. */
@@ -164,7 +164,7 @@ PyAPI_FUNC(PyObject*) PyString_AsDecodedString(
     );
 
 /* Provides access to the internal data buffer and size of a string
-   object or the default encoded version of an Unicode object. Passing
+   object or the default encoded version of a Unicode object. Passing
    NULL as *len parameter will force the string buffer to be
    0-terminated (passing a string with embedded NULL characters will
    cause an exception).  */
index 1269bf6..9184eb1 100644 (file)
@@ -513,7 +513,7 @@ PyAPI_FUNC(int) PyUnicode_Resize(
     Py_ssize_t length           /* New length */
     );
 
-/* Coerce obj to an Unicode object and return a reference with
+/* Coerce obj to a Unicode object and return a reference with
    *incremented* refcount.
 
    Coercion is done in the following way:
@@ -536,7 +536,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject(
     const char *errors          /* error handling */
     );
 
-/* Coerce obj to an Unicode object and return a reference with
+/* Coerce obj to a Unicode object and return a reference with
    *incremented* refcount.
 
    Unicode objects are passed back as-is (subclasses are converted to
@@ -1318,7 +1318,7 @@ PyAPI_FUNC(PyObject *) PyUnicode_Format(
 /* Checks whether element is contained in container and return 1/0
    accordingly.
 
-   element has to coerce to an one element Unicode string. -1 is
+   element has to coerce to a one element Unicode string. -1 is
    returned in case of an error. */
 
 PyAPI_FUNC(int) PyUnicode_Contains(
diff --git a/LICENSE b/LICENSE
index 88251f5..84a3337 100644 (file)
--- a/LICENSE
+++ b/LICENSE
@@ -74,8 +74,9 @@ analyze, test, perform and/or display publicly, prepare derivative works,
 distribute, and otherwise use Python alone or in any derivative version,
 provided, however, that PSF's License Agreement and PSF's notice of copyright,
 i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved"
-are retained in Python alone or in any derivative version prepared by Licensee.
+2011, 2012, 2013, 2014, 2015, 2016 Python Software Foundation; All Rights
+Reserved" are retained in Python alone or in any derivative version prepared by
+Licensee.
 
 3. In the event Licensee prepares a derivative work that is based on
 or incorporates Python or any part thereof, and wants to make
index deaf2f9..3df3323 100644 (file)
@@ -362,14 +362,25 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
             message = short
         explain = long
         self.log_error("code %d, message %s", code, message)
-        # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
-        content = (self.error_message_format %
-                   {'code': code, 'message': _quote_html(message), 'explain': explain})
         self.send_response(code, message)
-        self.send_header("Content-Type", self.error_content_type)
         self.send_header('Connection', 'close')
+
+        # Message body is omitted for cases described in:
+        #  - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
+        #  - RFC7231: 6.3.6. 205(Reset Content)
+        content = None
+        if code >= 200 and code not in (204, 205, 304):
+            # HTML encode to prevent Cross Site Scripting attacks
+            # (see bug #1100201)
+            content = (self.error_message_format % {
+                'code': code,
+                'message': _quote_html(message),
+                'explain': explain
+            })
+            self.send_header("Content-Type", self.error_content_type)
         self.end_headers()
-        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
+
+        if self.command != 'HEAD' and content:
             self.wfile.write(content)
 
     error_message_format = DEFAULT_ERROR_MESSAGE
index b1704d9..1082363 100644 (file)
@@ -190,7 +190,7 @@ as a string.
 Backwards Compatibility
 -----------------------
 
-In order to keep compatibilty with earlier versions of Cookie.py,
+In order to keep compatibility with earlier versions of Cookie.py,
 it is still possible to use Cookie.Cookie() to create a Cookie.  In
 fact, this simply returns a SmartCookie.
 
index 783d0ac..c140a27 100644 (file)
@@ -167,9 +167,9 @@ class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
         words = filter(None, words)
         path = os.getcwd()
         for word in words:
-            drive, word = os.path.splitdrive(word)
-            head, word = os.path.split(word)
-            if word in (os.curdir, os.pardir): continue
+            if os.path.dirname(word) or word in (os.curdir, os.pardir):
+                # Ignore components that are not a simple file/directory name
+                continue
             path = os.path.join(path, word)
         if trailing_slash:
             path += '/'
index 23ce6fc..122430e 100644 (file)
@@ -121,11 +121,6 @@ BaseServer:
 
 # Author of the BaseServer patch: Luke Kenneth Casson Leighton
 
-# XXX Warning!
-# There is a test suite for this module, but it cannot be run by the
-# standard regression test.
-# To run it manually, run Lib/test/test_socketserver.py.
-
 __version__ = "0.4"
 
 
@@ -296,6 +291,8 @@ class BaseServer:
             except:
                 self.handle_error(request, client_address)
                 self.shutdown_request(request)
+        else:
+            self.shutdown_request(request)
 
     def handle_timeout(self):
         """Called if no new request arrives within self.timeout.
@@ -642,7 +639,7 @@ class BaseRequestHandler:
     client address as self.client_address, and the server (in case it
     needs access to per-server information) as self.server.  Since a
     separate instance is created for each request, the handle() method
-    can define arbitrary other instance variariables.
+    can define other arbitrary instance variables.
 
     """
 
@@ -710,7 +707,7 @@ class StreamRequestHandler(BaseRequestHandler):
             try:
                 self.wfile.flush()
             except socket.error:
-                # An final socket error may have occurred here, such as
+                # A final socket error may have occurred here, such as
                 # the local error ECONNABORTED.
                 pass
         self.wfile.close()
@@ -719,9 +716,6 @@ class StreamRequestHandler(BaseRequestHandler):
 
 class DatagramRequestHandler(BaseRequestHandler):
 
-    # XXX Regrettably, I cannot get this working on Linux;
-    # s.recvfrom() doesn't return a meaningful client address.
-
     """Define self.rfile and self.wfile for datagram sockets."""
 
     def setup(self):
index a446aeb..d91cb51 100644 (file)
@@ -49,7 +49,7 @@ def lwp_cookie_str(cookie):
 class LWPCookieJar(FileCookieJar):
     """
     The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
-    "Set-Cookie3" is the format used by the libwww-perl libary, not known
+    "Set-Cookie3" is the format used by the libwww-perl library, not known
     to be compatible with any browser, but which is easy to read and
     doesn't lose information about RFC 2965 cookies.
 
index 2cd1428..d2aaae7 100644 (file)
@@ -151,13 +151,13 @@ def _find_appropriate_compiler(_config_vars):
     #    can only be found inside Xcode.app if the "Command Line Tools"
     #    are not installed.
     #
-    #    Futhermore, the compiler that can be used varies between
+    #    Furthermore, the compiler that can be used varies between
     #    Xcode releases. Up to Xcode 4 it was possible to use 'gcc-4.2'
     #    as the compiler, after that 'clang' should be used because
     #    gcc-4.2 is either not present, or a copy of 'llvm-gcc' that
     #    miscompiles Python.
 
-    # skip checks if the compiler was overriden with a CC env variable
+    # skip checks if the compiler was overridden with a CC env variable
     if 'CC' in os.environ:
         return _config_vars
 
@@ -193,7 +193,7 @@ def _find_appropriate_compiler(_config_vars):
     if cc != oldcc:
         # Found a replacement compiler.
         # Modify config vars using new compiler, if not already explicitly
-        # overriden by an env variable, preserving additional arguments.
+        # overridden by an env variable, preserving additional arguments.
         for cv in _COMPILER_CONFIG_VARS:
             if cv in _config_vars and cv not in os.environ:
                 cv_split = _config_vars[cv].split()
@@ -207,7 +207,7 @@ def _remove_universal_flags(_config_vars):
     """Remove all universal build arguments from config vars"""
 
     for cv in _UNIVERSAL_CONFIG_VARS:
-        # Do not alter a config var explicitly overriden by env var
+        # Do not alter a config var explicitly overridden by env var
         if cv in _config_vars and cv not in os.environ:
             flags = _config_vars[cv]
             flags = re.sub('-arch\s+\w+\s', ' ', flags)
@@ -228,7 +228,7 @@ def _remove_unsupported_archs(_config_vars):
     # build extensions on OSX 10.7 and later with the prebuilt
     # 32-bit installer on the python.org website.
 
-    # skip checks if the compiler was overriden with a CC env variable
+    # skip checks if the compiler was overridden with a CC env variable
     if 'CC' in os.environ:
         return _config_vars
 
@@ -244,7 +244,7 @@ def _remove_unsupported_archs(_config_vars):
             # across Xcode and compiler versions, there is no reliable way
             # to be sure why it failed.  Assume here it was due to lack of
             # PPC support and remove the related '-arch' flags from each
-            # config variables not explicitly overriden by an environment
+            # config variables not explicitly overridden by an environment
             # variable.  If the error was for some other reason, we hope the
             # failure will show up again when trying to compile an extension
             # module.
@@ -292,7 +292,7 @@ def _check_for_unavailable_sdk(_config_vars):
         sdk = m.group(1)
         if not os.path.exists(sdk):
             for cv in _UNIVERSAL_CONFIG_VARS:
-                # Do not alter a config var explicitly overriden by env var
+                # Do not alter a config var explicitly overridden by env var
                 if cv in _config_vars and cv not in os.environ:
                     flags = _config_vars[cv]
                     flags = re.sub(r'-isysroot\s+\S+(?:\s|$)', ' ', flags)
index 694b778..11348b2 100644 (file)
@@ -277,8 +277,9 @@ class IOBase:
     may raise a IOError when operations they do not support are called.
 
     The basic type used for binary data read from or written to a file is
-    bytes. bytearrays are accepted too, and in some cases (such as
-    readinto) needed. Text I/O classes work with str data.
+    the bytes type. Method arguments may also be bytearray or memoryview of
+    arrays of bytes. In some cases, such as readinto, a writable object such
+    as bytearray is required. Text I/O classes work with unicode data.
 
     Note that calling any method (even inquiries) on a closed stream is
     undefined. Implementations may raise IOError in this case.
@@ -420,7 +421,7 @@ class IOBase:
         return self.__closed
 
     def _checkClosed(self, msg=None):
-        """Internal: raise an ValueError if file is closed
+        """Internal: raise a ValueError if file is closed
         """
         if self.closed:
             raise ValueError("I/O operation on closed file."
@@ -649,7 +650,6 @@ class BufferedIOBase(IOBase):
         Raises BlockingIOError if the underlying raw stream has no
         data at the moment.
         """
-        # XXX This ought to work with anything that supports the buffer API
         data = self.read(len(b))
         n = len(data)
         try:
@@ -664,8 +664,7 @@ class BufferedIOBase(IOBase):
     def write(self, b):
         """Write the given buffer to the IO stream.
 
-        Return the number of bytes written, which is never less than
-        len(b).
+        Return the number of bytes written, which is always len(b).
 
         Raises BlockingIOError if the buffer is full and the
         underlying raw stream cannot accept more data at the moment.
@@ -997,7 +996,7 @@ class BufferedReader(_BufferedIOMixin):
                 break
             avail += len(chunk)
             chunks.append(chunk)
-        # n is more then avail only when an EOF occurred or when
+        # n is more than avail only when an EOF occurred or when
         # read() would have blocked.
         n = min(n, avail)
         out = b"".join(chunks)
@@ -2022,7 +2021,7 @@ class StringIO(TextIOWrapper):
 
     def __repr__(self):
         # TextIOWrapper tells the encoding in its repr. In StringIO,
-        # that's a implementation detail.
+        # that's an implementation detail.
         return object.__repr__(self)
 
     @property
index 1bd570d..feac05a 100644 (file)
@@ -75,6 +75,8 @@ class LocaleTime(object):
         self.__calc_date_time()
         if _getlang() != self.lang:
             raise ValueError("locale changed during initialization")
+        if time.tzname != self.tzname or time.daylight != self.daylight:
+            raise ValueError("timezone changed during initialization")
 
     def __pad(self, seq, front):
         # Add '' to seq to either the front (is True), else the back.
@@ -159,15 +161,17 @@ class LocaleTime(object):
 
     def __calc_timezone(self):
         # Set self.timezone by using time.tzname.
-        # Do not worry about possibility of time.tzname[0] == timetzname[1]
-        # and time.daylight; handle that in strptime .
+        # Do not worry about possibility of time.tzname[0] == time.tzname[1]
+        # and time.daylight; handle that in strptime.
         try:
             time.tzset()
         except AttributeError:
             pass
-        no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
-        if time.daylight:
-            has_saving = frozenset([time.tzname[1].lower()])
+        self.tzname = time.tzname
+        self.daylight = time.daylight
+        no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()])
+        if self.daylight:
+            has_saving = frozenset([self.tzname[1].lower()])
         else:
             has_saving = frozenset()
         self.timezone = (no_saving, has_saving)
@@ -296,12 +300,15 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
     """Return a time struct based on the input string and the format string."""
     global _TimeRE_cache, _regex_cache
     with _cache_lock:
-        if _getlang() != _TimeRE_cache.locale_time.lang:
+        locale_time = _TimeRE_cache.locale_time
+        if (_getlang() != locale_time.lang or
+            time.tzname != locale_time.tzname or
+            time.daylight != locale_time.daylight):
             _TimeRE_cache = TimeRE()
             _regex_cache.clear()
+            locale_time = _TimeRE_cache.locale_time
         if len(_regex_cache) > _CACHE_MAX_SIZE:
             _regex_cache.clear()
-        locale_time = _TimeRE_cache.locale_time
         format_regex = _regex_cache.get(format)
         if not format_regex:
             try:
@@ -438,6 +445,10 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
         week_starts_Mon = True if week_of_year_start == 0 else False
         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
                                             week_starts_Mon)
+        if julian <= 0:
+            year -= 1
+            yday = 366 if calendar.isleap(year) else 365
+            julian += yday
     # Cannot pre-calculate datetime_date() since can change in Julian
     # calculation and thus could have different value for the day of the week
     # calculation.
index 82c112c..38bc61e 100755 (executable)
@@ -64,9 +64,10 @@ def b64decode(s, altchars=None):
     length 2 (additional characters are ignored) which specifies the
     alternative alphabet used instead of the '+' and '/' characters.
 
-    The decoded string is returned.  A TypeError is raised if s were
-    incorrectly padded or if there are non-alphabet characters present in the
-    string.
+    The decoded string is returned.  A TypeError is raised if s is
+    incorrectly padded.  Characters that are neither in the normal base-64
+    alphabet nor the alternative alphabet are discarded prior to the padding
+    check.
     """
     if altchars is not None:
         s = s.translate(string.maketrans(altchars[:2], '+/'))
@@ -87,9 +88,10 @@ def standard_b64encode(s):
 def standard_b64decode(s):
     """Decode a string encoded with the standard Base64 alphabet.
 
-    s is the string to decode.  The decoded string is returned.  A TypeError
-    is raised if the string is incorrectly padded or if there are non-alphabet
-    characters present in the string.
+    Argument s is the string to decode.  The decoded string is returned.  A
+    TypeError is raised if the string is incorrectly padded.  Characters that
+    are not in the standard alphabet are discarded prior to the padding
+    check.
     """
     return b64decode(s)
 
@@ -97,19 +99,20 @@ _urlsafe_encode_translation = string.maketrans(b'+/', b'-_')
 _urlsafe_decode_translation = string.maketrans(b'-_', b'+/')
 
 def urlsafe_b64encode(s):
-    """Encode a string using a url-safe Base64 alphabet.
+    """Encode a string using the URL- and filesystem-safe Base64 alphabet.
 
-    s is the string to encode.  The encoded string is returned.  The alphabet
-    uses '-' instead of '+' and '_' instead of '/'.
+    Argument s is the string to encode.  The encoded string is returned.  The
+    alphabet uses '-' instead of '+' and '_' instead of '/'.
     """
     return b64encode(s).translate(_urlsafe_encode_translation)
 
 def urlsafe_b64decode(s):
-    """Decode a string encoded with the standard Base64 alphabet.
+    """Decode a string using the URL- and filesystem-safe Base64 alphabet.
 
-    s is the string to decode.  The decoded string is returned.  A TypeError
-    is raised if the string is incorrectly padded or if there are non-alphabet
-    characters present in the string.
+    Argument s is the string to decode.  The decoded string is returned.  A
+    TypeError is raised if the string is incorrectly padded.  Characters that
+    are not in the URL-safe base-64 alphabet, and are not a plus '+' or slash
+    '/', are discarded prior to the padding check.
 
     The alphabet uses '-' instead of '+' and '_' instead of '/'.
     """
@@ -267,7 +270,7 @@ def b16decode(s, casefold=False):
     a lowercase alphabet is acceptable as input.  For security purposes, the
     default is False.
 
-    The decoded string is returned.  A TypeError is raised if s were
+    The decoded string is returned.  A TypeError is raised if s is
     incorrectly padded or if there are non-alphabet characters present in the
     string.
     """
index 004e357..529dfad 100644 (file)
@@ -523,7 +523,7 @@ def get_new_database_path() :
     return path
 
 
-# This path can be overriden via "set_test_path_prefix()".
+# This path can be overridden via "set_test_path_prefix()".
 import os, os.path
 get_new_path.prefix=os.path.join(os.environ.get("TMPDIR",
     os.path.join(os.sep,"tmp")), "z-Berkeley_DB")
index 10ca8d6..fd87ea2 100644 (file)
@@ -41,7 +41,7 @@ class LockingTestCase(unittest.TestCase):
             print "locker ID: %s" % anID
         lock = self.env.lock_get(anID, "some locked thing", db.DB_LOCK_WRITE)
         if verbose:
-            print "Aquired lock: %s" % lock
+            print "Acquired lock: %s" % lock
         self.env.lock_put(lock)
         if verbose:
             print "Released lock: %s" % lock
@@ -158,7 +158,7 @@ class LockingTestCase(unittest.TestCase):
         for i in xrange(1000) :
             lock = self.env.lock_get(anID, "some locked thing", lockType)
             if verbose:
-                print "%s: Aquired %s lock: %s" % (name, lt, lock)
+                print "%s: Acquired %s lock: %s" % (name, lt, lock)
 
             self.env.lock_put(lock)
             if verbose:
index d3bd236..4c95a49 100644 (file)
@@ -142,7 +142,7 @@ class Calendar(object):
 
     def iterweekdays(self):
         """
-        Return a iterator for one week of weekday numbers starting with the
+        Return an iterator for one week of weekday numbers starting with the
         configured first one.
         """
         for i in range(self.firstweekday, self.firstweekday + 7):
index 64ba6d1..7c51b44 100755 (executable)
@@ -175,7 +175,7 @@ def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
 
 
 # parse query string function called from urlparse,
-# this is done in order to maintain backward compatiblity.
+# this is done in order to maintain backward compatibility.
 
 def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
     """Parse a query given as a string argument."""
index 1dcd233..f2ad972 100644 (file)
@@ -1,3 +1,15 @@
+'''This module implements specialized container datatypes providing
+alternatives to Python's general purpose built-in containers, dict,
+list, set, and tuple.
+
+* namedtuple   factory function for creating tuple subclasses with named fields
+* deque        list-like container with fast appends and pops on either end
+* Counter      dict subclass for counting hashable objects
+* OrderedDict  dict subclass that remembers the order entries were added
+* defaultdict  dict subclass that calls a factory function to supply missing values
+
+'''
+
 __all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict']
 # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
 # They should however be considered an integral part of collections.py.
@@ -302,7 +314,7 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
     >>> x, y = p                        # unpack like a regular tuple
     >>> x, y
     (11, 22)
-    >>> p.x + p.y                       # fields also accessable by name
+    >>> p.x + p.y                       # fields also accessible by name
     33
     >>> d = p._asdict()                 # convert to a dictionary
     >>> d['x']
index c227a2e..daf81a3 100644 (file)
@@ -315,7 +315,7 @@ def _reconstruct(x, info, deep, memo=None):
     if n > 2:
         state = info[2]
     else:
-        state = {}
+        state = None
     if n > 3:
         listiter = info[3]
     else:
@@ -329,7 +329,7 @@ def _reconstruct(x, info, deep, memo=None):
     y = callable(*args)
     memo[id(x)] = y
 
-    if state:
+    if state is not None:
         if deep:
             state = deepcopy(state, memo)
         if hasattr(y, '__setstate__'):
index 4e97c15..e24cfd2 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 """create and manipulate C data types in Python"""
 
 import os as _os, sys as _sys
@@ -386,8 +383,8 @@ class CDLL(object):
         return func
 
 class PyDLL(CDLL):
-    """This class represents the Python library itself.  It allows to
-    access Python API functions.  The GIL is not released, and
+    """This class represents the Python library itself.  It allows
+    accessing Python API functions.  The GIL is not released, and
     Python exceptions are handled correctly.
     """
     _func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
index f80e675..c0ba646 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 import sys
 from ctypes import *
 
index 4e10cbe..2866e9f 100644 (file)
@@ -1,4 +1,4 @@
-Files in this directory from from Bob Ippolito's py2app.
+Files in this directory come from Bob Ippolito's py2app.
 
 License: Any components of the py2app suite may be distributed under
 the MIT or PSF open source licenses.
index 36149d2..5621def 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 """
 Enough Mach-O to make your head spin.
 
index 9714ec6..1fdf8d6 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 """
 dyld emulation
 """
index ea3dd38..aa10750 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 """
 Generic dylib path manipulation
 """
index dd7fb2f..ad6ed55 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 """
 Generic framework path manipulation
 """
index 47e95ee..49aaab5 100644 (file)
@@ -24,20 +24,24 @@ class ArrayTestCase(unittest.TestCase):
             self.assertEqual(len(ia), alen)
 
             # slot values ok?
-            values = [ia[i] for i in range(len(init))]
+            values = [ia[i] for i in range(alen)]
             self.assertEqual(values, init)
 
+            # out-of-bounds accesses should be caught
+            with self.assertRaises(IndexError): ia[alen]
+            with self.assertRaises(IndexError): ia[-alen-1]
+
             # change the items
             from operator import setitem
             new_values = range(42, 42+alen)
             [setitem(ia, n, new_values[n]) for n in range(alen)]
-            values = [ia[i] for i in range(len(init))]
+            values = [ia[i] for i in range(alen)]
             self.assertEqual(values, new_values)
 
             # are the items initialized to 0?
             ia = int_array()
-            values = [ia[i] for i in range(len(init))]
-            self.assertEqual(values, [0] * len(init))
+            values = [ia[i] for i in range(alen)]
+            self.assertEqual(values, [0] * alen)
 
             # Too many initializers should be caught
             self.assertRaises(IndexError, int_array, *range(alen*2))
index 6915cda..24b0546 100644 (file)
@@ -53,9 +53,13 @@ class PointersTestCase(unittest.TestCase):
         # C code:
         #   int x = 12321;
         #   res = &x
-        res.contents = c_int(12321)
+        x = c_int(12321)
+        res.contents = x
         self.assertEqual(i.value, 54345)
 
+        x.value = -99
+        self.assertEqual(res.contents.value, -99)
+
     def test_callbacks_with_pointers(self):
         # a function type receiving a pointer
         PROTOTYPE = CFUNCTYPE(c_int, POINTER(c_int))
@@ -128,9 +132,10 @@ class PointersTestCase(unittest.TestCase):
 
     def test_basic(self):
         p = pointer(c_int(42))
-        # Although a pointer can be indexed, it ha no length
+        # Although a pointer can be indexed, it has no length
         self.assertRaises(TypeError, len, p)
         self.assertEqual(p[0], 42)
+        self.assertEqual(p[0:1], [42])
         self.assertEqual(p.contents.value, 42)
 
     def test_charpp(self):
index 2fa42bd..f983a6b 100644 (file)
@@ -326,6 +326,7 @@ class StructureTestCase(unittest.TestCase):
                                  "(Phone) <type 'exceptions.TypeError'>: "
                                  "expected string or Unicode object, int found")
         else:
+            # Compatibility no longer strictly required
             self.assertEqual(msg,
                                  "(Phone) exceptions.TypeError: "
                                  "expected string or Unicode object, int found")
index 14d69fe..fe7dcf0 100644 (file)
@@ -22,8 +22,7 @@ class ValuesTestCase(unittest.TestCase):
         ctdll = CDLL(_ctypes_test.__file__)
         self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")
 
-@unittest.skipUnless(sys.platform == 'win32', 'Windows-specific test')
-class Win_ValuesTestCase(unittest.TestCase):
+class PythonValuesTestCase(unittest.TestCase):
     """This test only works when python itself is a dll/shared library"""
 
     def test_optimizeflag(self):
index 1e882e3..b2c514d 100644 (file)
@@ -1,6 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
 import sys, os
 
 # find_library(name) returns the pathname of a library, or None.
@@ -137,16 +134,13 @@ elif os.name == "posix":
             cmd = 'if ! type objdump >/dev/null 2>&1; then exit 10; fi;' \
                   "objdump -p -j .dynamic 2>/dev/null " + f
             f = os.popen(cmd)
-            dump = f.read()
-            rv = f.close()
-            if rv == 10:
-                raise OSError, 'objdump command not found'
-            f = os.popen(cmd)
             try:
-                data = f.read()
+                dump = f.read()
             finally:
-                f.close()
-            res = re.search(r'\sSONAME\s+([^\s]+)', data)
+                rv = f.close()
+            if rv == 10:
+                raise OSError, 'objdump command not found'
+            res = re.search(r'\sSONAME\s+([^\s]+)', dump)
             if not res:
                 return None
             return res.group(1)
@@ -191,6 +185,7 @@ elif os.name == "posix":
             else:
                 cmd = 'env LC_ALL=C /usr/bin/crle 2>/dev/null'
 
+            paths = None
             for line in os.popen(cmd).readlines():
                 line = line.strip()
                 if line.startswith('Default Library Path (ELF):'):
@@ -228,7 +223,7 @@ elif os.name == "posix":
 
             # XXX assuming GLIBC's ldconfig (with option -p)
             expr = r'\s+(lib%s\.[^\s]+)\s+\(%s' % (re.escape(name), abi_type)
-            f = os.popen('/sbin/ldconfig -p 2>/dev/null')
+            f = os.popen('LC_ALL=C LANG=C /sbin/ldconfig -p 2>/dev/null')
             try:
                 data = f.read()
             finally:
index dafbb78..e7f569c 100644 (file)
@@ -1,7 +1,3 @@
-######################################################################
-#  This file should be kept compatible with Python 2.3, see PEP 291. #
-######################################################################
-
 # The most useful windows datatypes
 from ctypes import *
 
index d274552..4797a7d 100644 (file)
@@ -224,7 +224,7 @@ class InvalidOperation(DecimalException):
 class ConversionSyntax(InvalidOperation):
     """Trying to convert badly formed string.
 
-    This occurs and signals invalid-operation if an string is being
+    This occurs and signals invalid-operation if a string is being
     converted to a number and it does not conform to the numeric string
     syntax.  The result is [0,qNaN].
     """
@@ -1082,7 +1082,7 @@ class Decimal(object):
     def __pos__(self, context=None):
         """Returns a copy, unless it is a sNaN.
 
-        Rounds the number (if more then precision digits)
+        Rounds the number (if more than precision digits)
         """
         if self._is_special:
             ans = self._check_nans(context=context)
index 3880d84..1c6fbdb 100644 (file)
@@ -1487,7 +1487,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None,
                 yield _make_line(lines,'-',0), None, True
                 continue
             elif s.startswith(('--?+', '--+', '- ')):
-                # in delete block and see a intraline change or unchanged line
+                # in delete block and see an intraline change or unchanged line
                 # coming: yield the delete line and then blanks
                 from_line,to_line = _make_line(lines,'-',0), None
                 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
index c0c446f..62506a6 100644 (file)
@@ -842,8 +842,9 @@ main (int argc, char **argv) {
     def library_filename(self, libname, lib_type='static',     # or 'shared'
                          strip_dir=0, output_dir=''):
         assert output_dir is not None
-        if lib_type not in ("static", "shared", "dylib"):
-            raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\""
+        if lib_type not in ("static", "shared", "dylib", "xcode_stub"):
+            raise ValueError, ("""'lib_type' must be "static", "shared", """
+                               """"dylib", or "xcode_stub".""")
         fmt = getattr(self, lib_type + "_lib_format")
         ext = getattr(self, lib_type + "_lib_extension")
 
index 5d11687..c72a249 100644 (file)
@@ -10,9 +10,9 @@ cygwin in no-cygwin mode).
 #
 # * if you use a msvc compiled python version (1.5.2)
 #   1. you have to insert a __GNUC__ section in its config.h
-#   2. you have to generate a import library for its dll
+#   2. you have to generate an import library for its dll
 #      - create a def-file for python??.dll
-#      - create a import library using
+#      - create an import library using
 #             dlltool --dllname python15.dll --def python15.def \
 #                       --output-lib libpython15.a
 #
index 22de4ba..33d3e51 100644 (file)
@@ -54,7 +54,7 @@ else:
 
 # A map keyed by get_platform() return values to values accepted by
 # 'vcvarsall.bat'.  Note a cross-compile may combine these (eg, 'x86_amd64' is
-# the param to cross-compile on x86 targetting amd64.)
+# the param to cross-compile on x86 targeting amd64.)
 PLAT_TO_VCVARS = {
     'win32' : 'x86',
     'win-amd64' : 'amd64',
index d380cb6..3293c44 100644 (file)
@@ -251,7 +251,7 @@ class BuildExtTestCase(support.TempdirManager,
 
     def test_compiler_option(self):
         # cmd.compiler is an option and
-        # should not be overriden by a compiler instance
+        # should not be overridden by a compiler instance
         # when the command is run
         dist = Distribution()
         cmd = build_ext(dist)
index fec1ea6..3b893c1 100644 (file)
@@ -135,7 +135,7 @@ class UnixCCompilerTestCase(unittest.TestCase):
         self.assertEqual(self.cc.linker_so[0], 'my_cc')
 
     @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X')
-    def test_osx_explict_ldshared(self):
+    def test_osx_explicit_ldshared(self):
         # Issue #18080:
         # ensure that setting CC env variable does not change
         #   explicit LDSHARED setting for linker
index 2aa1cb1..4c35676 100644 (file)
@@ -79,7 +79,9 @@ class UnixCCompiler(CCompiler):
     static_lib_extension = ".a"
     shared_lib_extension = ".so"
     dylib_lib_extension = ".dylib"
+    xcode_stub_lib_extension = ".tbd"
     static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
+    xcode_stub_lib_format = dylib_lib_format
     if sys.platform == "cygwin":
         exe_extension = ".exe"
 
@@ -245,12 +247,28 @@ class UnixCCompiler(CCompiler):
     def find_library_file(self, dirs, lib, debug=0):
         shared_f = self.library_filename(lib, lib_type='shared')
         dylib_f = self.library_filename(lib, lib_type='dylib')
+        xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub')
         static_f = self.library_filename(lib, lib_type='static')
 
         if sys.platform == 'darwin':
             # On OSX users can specify an alternate SDK using
             # '-isysroot', calculate the SDK root if it is specified
             # (and use it further on)
+            #
+            # Note that, as of Xcode 7, Apple SDKs may contain textual stub
+            # libraries with .tbd extensions rather than the normal .dylib
+            # shared libraries installed in /.  The Apple compiler tool
+            # chain handles this transparently but it can cause problems
+            # for programs that are being built with an SDK and searching
+            # for specific libraries.  Callers of find_library_file need to
+            # keep in mind that the base filename of the returned SDK library
+            # file might have a different extension from that of the library
+            # file installed on the running system, for example:
+            #   /Applications/Xcode.app/Contents/Developer/Platforms/
+            #       MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
+            #       usr/lib/libedit.tbd
+            # vs
+            #   /usr/lib/libedit.dylib
             cflags = sysconfig.get_config_var('CFLAGS')
             m = re.search(r'-isysroot\s+(\S+)', cflags)
             if m is None:
@@ -264,6 +282,7 @@ class UnixCCompiler(CCompiler):
             shared = os.path.join(dir, shared_f)
             dylib = os.path.join(dir, dylib_f)
             static = os.path.join(dir, static_f)
+            xcode_stub = os.path.join(dir, xcode_stub_f)
 
             if sys.platform == 'darwin' and (
                 dir.startswith('/System/') or (
@@ -272,6 +291,7 @@ class UnixCCompiler(CCompiler):
                 shared = os.path.join(sysroot, dir[1:], shared_f)
                 dylib = os.path.join(sysroot, dir[1:], dylib_f)
                 static = os.path.join(sysroot, dir[1:], static_f)
+                xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f)
 
             # We're second-guessing the linker here, with not much hard
             # data to go on: GCC seems to prefer the shared library, so I'm
@@ -279,6 +299,8 @@ class UnixCCompiler(CCompiler):
             # ignoring even GCC's "-static" option.  So sue me.
             if os.path.exists(dylib):
                 return dylib
+            elif os.path.exists(xcode_stub):
+                return xcode_stub
             elif os.path.exists(shared):
                 return shared
             elif os.path.exists(static):
index 7c93370..d7358cd 100644 (file)
@@ -579,7 +579,7 @@ class Message:
         message, it will be set to "text/plain" and the new parameter and
         value will be appended as per RFC 2045.
 
-        An alternate header can specified in the header argument, and all
+        An alternate header can be specified in the header argument, and all
         parameters will be quoted as necessary unless requote is False.
 
         If charset is specified, the parameter will be encoded according to RFC
index 2fcaf25..6dad32a 100644 (file)
@@ -23,7 +23,7 @@ class Parser:
         textual representation of the message.
 
         The string must be formatted as a block of RFC 2822 headers and header
-        continuation lines, optionally preceeded by a `Unix-from' header.  The
+        continuation lines, optionally preceded by a `Unix-from' header.  The
         header block is terminated either by the end of the string or by a
         blank line.
 
index 6c8016f..067e1e2 100644 (file)
@@ -68,7 +68,7 @@ class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
         self.decoder = None
 
     def getstate(self):
-        # additonal state info from the base class must be None here,
+        # additional state info from the base class must be None here,
         # as it isn't passed along to the caller
         state = codecs.BufferedIncrementalDecoder.getstate(self)[0]
         # additional state info we pass to the caller:
index de0fbfb..14c9adb 100644 (file)
@@ -12,9 +12,9 @@ import tempfile
 __all__ = ["version", "bootstrap"]
 
 
-_SETUPTOOLS_VERSION = "18.2"
+_SETUPTOOLS_VERSION = "20.10.1"
 
-_PIP_VERSION = "7.1.2"
+_PIP_VERSION = "8.1.1"
 
 # pip currently requires ssl support, so we try to provide a nicer
 # error message when that is missing (http://bugs.python.org/issue19744)
diff --git a/Lib/ensurepip/_bundled/pip-7.1.2-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-7.1.2-py2.py3-none-any.whl
deleted file mode 100644 (file)
index 5e49015..0000000
Binary files a/Lib/ensurepip/_bundled/pip-7.1.2-py2.py3-none-any.whl and /dev/null differ
diff --git a/Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl
new file mode 100644 (file)
index 0000000..8632eb7
Binary files /dev/null and b/Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl differ
similarity index 60%
rename from Lib/ensurepip/_bundled/setuptools-18.2-py2.py3-none-any.whl
rename to Lib/ensurepip/_bundled/setuptools-20.10.1-py2.py3-none-any.whl
index f4288d6..9d1319a 100644 (file)
Binary files a/Lib/ensurepip/_bundled/setuptools-18.2-py2.py3-none-any.whl and b/Lib/ensurepip/_bundled/setuptools-20.10.1-py2.py3-none-any.whl differ
index 02dc4c6..b2e2f05 100644 (file)
@@ -64,13 +64,6 @@ deleted when the output file is closed.  In-place filtering is
 disabled when standard input is read.  XXX The current implementation
 does not work for MS-DOS 8+3 filesystems.
 
-Performance: this module is unfortunately one of the slower ways of
-processing large numbers of input lines.  Nevertheless, a significant
-speed-up has been obtained by using readlines(bufsize) instead of
-readline().  A new keyword argument, bufsize=N, is present on the
-input() function and the FileInput() class to override the default
-buffer size.
-
 XXX Possible additions:
 
 - optional getopt argument processing
@@ -86,6 +79,7 @@ __all__ = ["input","close","nextfile","filename","lineno","filelineno",
 
 _state = None
 
+# No longer used
 DEFAULT_BUFSIZE = 8*1024
 
 def input(files=None, inplace=0, backup="", bufsize=0,
@@ -207,17 +201,14 @@ class FileInput:
         self._files = files
         self._inplace = inplace
         self._backup = backup
-        self._bufsize = bufsize or DEFAULT_BUFSIZE
         self._savestdout = None
         self._output = None
         self._filename = None
-        self._lineno = 0
+        self._startlineno = 0
         self._filelineno = 0
         self._file = None
         self._isstdin = False
         self._backupfilename = None
-        self._buffer = []
-        self._bufindex = 0
         # restrict mode argument to reading modes
         if mode not in ('r', 'rU', 'U', 'rb'):
             raise ValueError("FileInput opening mode must be one of "
@@ -242,22 +233,18 @@ class FileInput:
         return self
 
     def next(self):
-        try:
-            line = self._buffer[self._bufindex]
-        except IndexError:
-            pass
-        else:
-            self._bufindex += 1
-            self._lineno += 1
-            self._filelineno += 1
-            return line
-        line = self.readline()
-        if not line:
-            raise StopIteration
-        return line
+        while 1:
+            line = self._readline()
+            if line:
+                self._filelineno += 1
+                return line
+            if not self._file:
+                raise StopIteration
+            self.nextfile()
+            # repeat with next file
 
     def __getitem__(self, i):
-        if i != self._lineno:
+        if i != self.lineno():
             raise RuntimeError, "accessing lines out of order"
         try:
             return self.next()
@@ -277,7 +264,11 @@ class FileInput:
                 output.close()
         finally:
             file = self._file
-            self._file = 0
+            self._file = None
+            try:
+                del self._readline  # restore FileInput._readline
+            except AttributeError:
+                pass
             try:
                 if file and not self._isstdin:
                     file.close()
@@ -289,75 +280,72 @@ class FileInput:
                     except OSError: pass
 
                 self._isstdin = False
-                self._buffer = []
-                self._bufindex = 0
 
     def readline(self):
-        try:
-            line = self._buffer[self._bufindex]
-        except IndexError:
-            pass
+        while 1:
+            line = self._readline()
+            if line:
+                self._filelineno += 1
+                return line
+            if not self._file:
+                return line
+            self.nextfile()
+            # repeat with next file
+
+    def _readline(self):
+        if not self._files:
+            return ""
+        self._filename = self._files[0]
+        self._files = self._files[1:]
+        self._startlineno = self.lineno()
+        self._filelineno = 0
+        self._file = None
+        self._isstdin = False
+        self._backupfilename = 0
+        if self._filename == '-':
+            self._filename = '<stdin>'
+            self._file = sys.stdin
+            self._isstdin = True
         else:
-            self._bufindex += 1
-            self._lineno += 1
-            self._filelineno += 1
-            return line
-        if not self._file:
-            if not self._files:
-                return ""
-            self._filename = self._files[0]
-            self._files = self._files[1:]
-            self._filelineno = 0
-            self._file = None
-            self._isstdin = False
-            self._backupfilename = 0
-            if self._filename == '-':
-                self._filename = '<stdin>'
-                self._file = sys.stdin
-                self._isstdin = True
-            else:
-                if self._inplace:
-                    self._backupfilename = (
-                        self._filename + (self._backup or os.extsep+"bak"))
-                    try: os.unlink(self._backupfilename)
-                    except os.error: pass
-                    # The next few lines may raise IOError
-                    os.rename(self._filename, self._backupfilename)
-                    self._file = open(self._backupfilename, self._mode)
+            if self._inplace:
+                self._backupfilename = (
+                    self._filename + (self._backup or os.extsep+"bak"))
+                try: os.unlink(self._backupfilename)
+                except os.error: pass
+                # The next few lines may raise IOError
+                os.rename(self._filename, self._backupfilename)
+                self._file = open(self._backupfilename, self._mode)
+                try:
+                    perm = os.fstat(self._file.fileno()).st_mode
+                except OSError:
+                    self._output = open(self._filename, "w")
+                else:
+                    fd = os.open(self._filename,
+                                    os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
+                                    perm)
+                    self._output = os.fdopen(fd, "w")
                     try:
-                        perm = os.fstat(self._file.fileno()).st_mode
+                        if hasattr(os, 'chmod'):
+                            os.chmod(self._filename, perm)
                     except OSError:
-                        self._output = open(self._filename, "w")
-                    else:
-                        fd = os.open(self._filename,
-                                     os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
-                                     perm)
-                        self._output = os.fdopen(fd, "w")
-                        try:
-                            if hasattr(os, 'chmod'):
-                                os.chmod(self._filename, perm)
-                        except OSError:
-                            pass
-                    self._savestdout = sys.stdout
-                    sys.stdout = self._output
+                        pass
+                self._savestdout = sys.stdout
+                sys.stdout = self._output
+            else:
+                # This may raise IOError
+                if self._openhook:
+                    self._file = self._openhook(self._filename, self._mode)
                 else:
-                    # This may raise IOError
-                    if self._openhook:
-                        self._file = self._openhook(self._filename, self._mode)
-                    else:
-                        self._file = open(self._filename, self._mode)
-        self._buffer = self._file.readlines(self._bufsize)
-        self._bufindex = 0
-        if not self._buffer:
-            self.nextfile()
-        # Recursive call
-        return self.readline()
+                    self._file = open(self._filename, self._mode)
+
+        self._readline = self._file.readline  # hide FileInput._readline
+        return self._readline()
 
     def filename(self):
         return self._filename
 
     def lineno(self):
-        return self._lineno
+        return self._startlineno + self._filelineno
 
     def filelineno(self):
         return self._filelineno
index 251d89c..084aadb 100644 (file)
@@ -28,7 +28,7 @@ option involved with the exception.
 # - RETURN_IN_ORDER option
 # - GNU extension with '-' as first character of option string
 # - optional arguments, specified by double colons
-# - a option string with a W followed by semicolon should
+# - an option string with a W followed by semicolon should
 #   treat "-W foo" as "--foo"
 
 __all__ = ["GetoptError","error","getopt","gnu_getopt"]
index de0dab1..07c6db4 100644 (file)
@@ -55,7 +55,7 @@ class GzipFile(io.BufferedIOBase):
         a file object.
 
         When fileobj is not None, the filename argument is only used to be
-        included in the gzip file header, which may includes the original
+        included in the gzip file header, which may include the original
         filename of the uncompressed file.  It defaults to the filename of
         fileobj, if discernible; otherwise, it defaults to the empty string,
         and in this case the original filename is not included in the header.
index 4b2c0c4..f8269e1 100644 (file)
@@ -56,7 +56,7 @@ representation for a tournament.  The numbers below are `k', not a[k]:
 
 
 In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'.  In
-an usual binary tournament we see in sports, each cell is the winner
+a usual binary tournament we see in sports, each cell is the winner
 over the two cells it tops, and we can trace the winner down the tree
 to see all opponents s/he had.  However, in many computer applications
 of such tournaments, we do not need to trace the history of a winner.
index 1556ab3..3692f93 100644 (file)
@@ -72,7 +72,7 @@ class Profile:
 
         Additional positional and keyword arguments may be passed
         along; the result of the call is returned, and exceptions are
-        allowed to propogate cleanly, while ensuring that profiling is
+        allowed to propagate cleanly, while ensuring that profiling is
         disabled on the way out.
         """
         return self._prof.runcall(func, args, kw)
index 1248f00..9381bda 100644 (file)
@@ -1,6 +1,6 @@
 """AutoComplete.py - An IDLE extension for automatically completing names.
 
-This extension can complete either attribute names of file names. It can pop
+This extension can complete either attribute names or file names. It can pop
 a window with all available names, for the user to select from.
 """
 import os
@@ -67,7 +67,7 @@ class AutoComplete:
 
     def try_open_completions_event(self, event):
         """Happens when it would be nice to open a completion list, but not
-        really necessary, for example after an dot, so function
+        really necessary, for example after a dot, so function
         calls won't be made.
         """
         lastchar = self.text.get("insert-1c")
index 5ff599d..3a50eb8 100644 (file)
@@ -24,7 +24,7 @@ Noam Raphael (Code Context, Call Tips, many other patches), and Chui Tey (RPC
 integration, debugger integration and persistent breakpoints).
 
 Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou,
-Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb,
+Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb,
 Nigel Rowe, Bruce Sherwood, Jeff Shute, and Weeble have submitted useful
 patches.  Thanks, guys!
 
index 985871b..968a344 100644 (file)
@@ -1574,7 +1574,7 @@ Mon Oct 12 23:59:27 1998  Guido van Rossum  <guido@cnri.reston.va.us>
        * Attic/PopupMenu.py: Pass a root to the help window.
 
        * SearchBinding.py:
-       Add parent argument to 'to to line number' dialog box.
+       Add parent argument to 'go to line number' dialog box.
 
 Sat Oct 10 19:15:32 1998  Guido van Rossum  <guido@cnri.reston.va.us>
 
index 7fbe4a7..c517065 100644 (file)
@@ -373,7 +373,7 @@ class StackViewer(ScrolledList):
     def __init__(self, master, flist, gui):
         if macosxSupport.isAquaTk():
             # At least on with the stock AquaTk version on OSX 10.4 you'll
-            # get an shaking GUI that eventually kills IDLE if the width
+            # get a shaking GUI that eventually kills IDLE if the width
             # argument is specified.
             ScrolledList.__init__(self, master)
         else:
index 3b39606..1233d80 100644 (file)
@@ -17,6 +17,8 @@ import tkFileDialog
 import tkMessageBox
 from SimpleDialog import SimpleDialog
 
+from idlelib.configHandler import idleConf
+
 # Try setting the locale, so that we can find out
 # what encoding to use
 try:
@@ -63,7 +65,7 @@ else:
 
 encoding = encoding.lower()
 
-coding_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)')
+coding_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)')
 blank_re = re.compile(r'^[ \t\f]*(?:[#\r\n]|$)')
 
 class EncodingMessage(SimpleDialog):
@@ -137,7 +139,6 @@ def coding_spec(str):
         raise LookupError, "Unknown encoding "+name
     return name
 
-
 class IOBinding:
 
     def __init__(self, editwin):
@@ -567,7 +568,6 @@ class IOBinding:
 
 def _io_binding(parent):  # htest #
     from Tkinter import Toplevel, Text
-    from idlelib.configHandler import idleConf
 
     root = Toplevel(parent)
     root.title("Test IOBinding")
@@ -578,15 +578,24 @@ def _io_binding(parent):  # htest #
             self.text = text
             self.flist = None
             self.text.bind("<Control-o>", self.open)
+            self.text.bind('<Control-p>', self.printer)
             self.text.bind("<Control-s>", self.save)
+            self.text.bind("<Alt-s>", self.saveas)
+            self.text.bind('<Control-c>', self.savecopy)
         def get_saved(self): return 0
         def set_saved(self, flag): pass
         def reset_undo(self): pass
+        def update_recent_files_list(self, filename): pass
         def open(self, event):
             self.text.event_generate("<<open-window-from-file>>")
+        def printer(self, event):
+            self.text.event_generate("<<print-window>>")
         def save(self, event):
             self.text.event_generate("<<save-window>>")
-        def update_recent_files_list(s, f): pass
+        def saveas(self, event):
+            self.text.event_generate("<<save-window-as-file>>")
+        def savecopy(self, event):
+            self.text.event_generate("<<save-copy-of-window-as-file>>")
 
     text = Text(root)
     text.pack()
index 31a4fb7..a157d7a 100644 (file)
@@ -101,7 +101,7 @@ class _SimpleBinder:
             self.widget.unbind(self.widgetinst, self.sequence, self.handlerid)
 
 # An int in range(1 << len(_modifiers)) represents a combination of modifiers
-# (if the least significent bit is on, _modifiers[0] is on, and so on).
+# (if the least significant bit is on, _modifiers[0] is on, and so on).
 # _state_subsets gives for each combination of modifiers, or *state*,
 # a list of the states which are a subset of it. This list is ordered by the
 # number of modifiers is the state - the most specific state comes first.
index e9e95fd..298a82a 100644 (file)
@@ -1,3 +1,35 @@
+What's New in IDLE 2.7.12?
+==========================
+*Release date: 2015-06-30?*
+
+- Issue #5124: Paste with text selected now replaces the selection on X11.
+  This matches how paste works on Windows, Mac, most modern Linux apps,
+  and ttk widgets.  Original patch by Serhiy Storchaka.
+
+- Issue #24759: Make clear in idlelib.idle_test.__init__ that the directory
+  is a private implementation of test.test_idle and tool for maintainers.
+
+- Issue #26673: When tk reports font size as 0, change to size 10.
+  Such fonts on Linux prevented the configuration dialog from opening.
+
+- Issue #27044: Add ConfigDialog.remove_var_callbacks to stop memory leaks.
+
+- In the 'IDLE-console differences' section of the IDLE doc, clarify
+  how running with IDLE affects sys.modules and the standard streams.
+
+- Issue #25507: fix incorrect change in IOBinding that prevented printing.
+  Change also prevented saving shell window with non-ascii characters.
+  Augment IOBinding htest to include all major IOBinding functions.
+
+- Issue #25905: Revert unwanted conversion of ' to \92 RIGHT SINGLE QUOTATION
+  MARK in README.txt and open this and NEWS.txt with 'ascii'.
+  Re-encode CREDITS.txt to utf-8 and open it with 'utf-8'.
+
+- Issue #26417: Prevent spurious errors and incorrect defaults when
+  installing IDLE 2.7 on OS X: default configuration settings are
+  no longer installed from OS X specific copies.
+
+
 What's New in IDLE 2.7.11?
 ==========================
 *Release date: 2015-12-06*
@@ -162,7 +194,7 @@ What's New in IDLE 2.7.9?
   move version to end.
 
 - Issue #14105: Idle debugger breakpoints no longer disappear
-  when inseting or deleting lines.
+  when inserting or deleting lines.
 
 
 What's New in IDLE 2.7.8?
index ea0d7de..3ea1a7d 100755 (executable)
@@ -1408,6 +1408,17 @@ class PseudoInputFile(PseudoFile):
         self.shell.close()
 
 
+def fix_x11_paste(root):
+    "Make paste replace selection on x11.  See issue #5124."
+    if root._windowingsystem == 'x11':
+        for cls in 'Text', 'Entry', 'Spinbox':
+            root.bind_class(
+                cls,
+                '<<Paste>>',
+                'catch {%W delete sel.first sel.last}\n' +
+                        root.bind_class(cls, '<<Paste>>'))
+
+
 usage_msg = """\
 
 USAGE: idle  [-deins] [-t title] [file]*
@@ -1537,8 +1548,10 @@ def main():
                                     'editor-on-startup', type='bool')
     enable_edit = enable_edit or edit_start
     enable_shell = enable_shell or not enable_edit
+
     # start editor and/or shell windows:
     root = Tk(className="Idle")
+    root.withdraw()
 
     # set application icon
     icondir = os.path.join(os.path.dirname(__file__), 'Icons')
@@ -1553,7 +1566,7 @@ def main():
         root.tk.call('wm', 'iconphoto', str(root), "-default", *icons)
 
     fixwordbreaks(root)
-    root.withdraw()
+    fix_x11_paste(root)
     flist = PyShellFileList(root)
     macosxSupport.setupApp(root, flist)
 
index b5663c2..7bf74c0 100644 (file)
@@ -1,6 +1,6 @@
 README.txt: an index to idlelib files and the IDLE menu.
 
-IDLE is Python\92s Integrated Development and Learning
+IDLE is Python's Integrated Development and Learning
 Environment.  The user documentation is part of the Library Reference and
 is available in IDLE by selecting Help => IDLE Help.  This README documents
 idlelib for IDLE developers and curious users.
index 2cb9398..54431f7 100644 (file)
@@ -68,7 +68,7 @@ class WidgetRedirector:
         '''Return OriginalCommand(operation) after registering function.
 
         Registration adds an operation: function pair to ._operations.
-        It also adds an widget function attribute that masks the Tkinter
+        It also adds a widget function attribute that masks the Tkinter
         class instance method.  Method masking operates independently
         from command dispatch.
 
index ef8e2de..c9adc08 100644 (file)
@@ -110,6 +110,7 @@ class AboutDialog(Toplevel):
                                 command=self.ShowIDLECredits)
         idle_credits_b.pack(side=LEFT, padx=10, pady=10)
 
+    # License, et all, are of type _sitebuiltins._Printer
     def ShowLicense(self):
         self.display_printer_text('About - License', license)
 
@@ -119,14 +120,16 @@ class AboutDialog(Toplevel):
     def ShowPythonCredits(self):
         self.display_printer_text('About - Python Credits', credits)
 
+    # Encode CREDITS.txt to utf-8 for proper version of Loewis.
+    # Specify others as ascii until need utf-8, so catch errors.
     def ShowIDLECredits(self):
-        self.display_file_text('About - Credits', 'CREDITS.txt', 'iso-8859-1')
+        self.display_file_text('About - Credits', 'CREDITS.txt', 'utf-8')
 
     def ShowIDLEAbout(self):
-        self.display_file_text('About - Readme', 'README.txt')
+        self.display_file_text('About - Readme', 'README.txt', 'ascii')
 
     def ShowIDLENEWS(self):
-        self.display_file_text('About - NEWS', 'NEWS.txt')
+        self.display_file_text('About - NEWS', 'NEWS.txt', 'utf-8')
 
     def display_printer_text(self, title, printer):
         printer._Printer__setup()
@@ -141,5 +144,7 @@ class AboutDialog(Toplevel):
         self.destroy()
 
 if __name__ == '__main__':
+    import unittest
+    unittest.main('idlelib.idle_test.test_helpabout', verbosity=2, exit=False)
     from idlelib.idle_test.htest import run
     run(AboutDialog)
index 585a871..e0f6907 100644 (file)
@@ -500,6 +500,16 @@ class ConfigDialog(Toplevel):
         self.autoSave.trace_variable('w', self.VarChanged_autoSave)
         self.encoding.trace_variable('w', self.VarChanged_encoding)
 
+    def remove_var_callbacks(self):
+        for var in (
+                self.fontSize, self.fontName, self.fontBold,
+                self.spaceNum, self.colour, self.builtinTheme,
+                self.customTheme, self.themeIsBuiltin, self.highlightTarget,
+                self.keyBinding, self.builtinKeys, self.customKeys,
+                self.keysAreBuiltin, self.winWidth, self.winHeight,
+                self.startupEdit, self.autoSave, self.encoding,):
+            var.trace_vdelete('w', var.trace_vinfo()[0][1])
+
     def VarChanged_font(self, *params):
         '''When one font attribute changes, save them all, as they are
         not independent from each other. In particular, when we are
@@ -1213,7 +1223,7 @@ class ConfigDialog(Toplevel):
 
         All values are treated as text, and it is up to the user to supply
         reasonable values. The only exception to this are the 'enable*' options,
-        which are boolean, and can be toggled with an True/False button.
+        which are boolean, and can be toggled with a True/False button.
         """
         parent = self.parent
         frame = self.tabPages.pages['Extensions'].frame
index efd5f3c..4c95a39 100644 (file)
@@ -721,7 +721,7 @@ class IdleConf:
                 actualFont = Font.actual(f)
                 family = actualFont['family']
                 size = actualFont['size']
-                if size < 0:
+                if size <= 0:
                     size = 10  # if font in pixels, ignore actual size
                 bold = actualFont['weight']=='bold'
         return (family, size, 'bold' if bold else 'normal')
index 9e0eba0..7e79e6d 100644 (file)
@@ -6,15 +6,15 @@
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
-    <title>24.6. IDLE &mdash; Python 2.7.10 documentation</title>
+    <title>24.6. IDLE &mdash; Python 2.7.11 documentation</title>
 
-    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
+    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
     <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
 
     <script type="text/javascript">
       var DOCUMENTATION_OPTIONS = {
         URL_ROOT:    '../',
-        VERSION:     '2.7.10',
+        VERSION:     '2.7.11',
         COLLAPSE_INDEX: false,
         FILE_SUFFIX: '.html',
         HAS_SOURCE:  true
     <script type="text/javascript" src="../_static/doctools.js"></script>
     <script type="text/javascript" src="../_static/sidebar.js"></script>
     <link rel="search" type="application/opensearchdescription+xml"
-          title="Search within Python 2.7.10 documentation"
+          title="Search within Python 2.7.11 documentation"
           href="../_static/opensearch.xml"/>
     <link rel="author" title="About these documents" href="../about.html" />
     <link rel="copyright" title="Copyright" href="../copyright.html" />
-    <link rel="top" title="Python 2.7.10 documentation" href="../index.html" />
+    <link rel="top" title="Python 2.7.11 documentation" href="../contents.html" />
     <link rel="up" title="24. Graphical User Interfaces with Tk" href="tk.html" />
     <link rel="next" title="24.7. Other Graphical User Interface Packages" href="othergui.html" />
     <link rel="prev" title="24.5. turtle — Turtle graphics for Tk" href="turtle.html" />
@@ -40,8 +40,8 @@
 
 
   </head>
-  <body>
-    <div class="related">
+  <body role="document">
+    <div class="related" role="navigation" aria-label="related navigation">
       <h3>Navigation</h3>
       <ul>
         <li class="right" style="margin-right: 10px">
                  style="vertical-align: middle; margin-top: -1px"/></li>
         <li><a href="https://www.python.org/">Python</a> &raquo;</li>
         <li>
-          <a href="../index.html">Python 2.7.10 documentation</a> &raquo;
+          <a href="../index.html">Python 2.7.11 documentation</a> &raquo;
         </li>
 
-          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
-          <li><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &raquo;</li>
+          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &raquo;</li>
+          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &raquo;</li>
       </ul>
     </div>
 
     <div class="document">
       <div class="documentwrapper">
         <div class="bodywrapper">
-          <div class="body">
+          <div class="body" role="main">
 
   <div class="section" id="idle">
 <span id="id1"></span><h1>24.6. IDLE<a class="headerlink" href="#idle" title="Permalink to this headline">¶</a></h1>
 <p id="index-0">IDLE is Python&#8217;s Integrated Development and Learning Environment.</p>
 <p>IDLE has the following features:</p>
 <ul class="simple">
-<li>coded in 100% pure Python, using the <tt class="xref py py-mod docutils literal"><span class="pre">tkinter</span></tt> GUI toolkit</li>
+<li>coded in 100% pure Python, using the <code class="xref py py-mod docutils literal"><span class="pre">tkinter</span></code> GUI toolkit</li>
 <li>cross-platform: works mostly the same on Windows, Unix, and Mac OS X</li>
 <li>Python shell window (interactive interpreter) with colorizing
 of code input, output, and error messages</li>
@@ -163,7 +163,7 @@ be undone.</dd>
 <dt>Find Selection</dt>
 <dd>Search for the currently selected string, if there is one.</dd>
 <dt>Find in Files...</dt>
-<dd>Open a file search dialog.  Put results in an new output window.</dd>
+<dd>Open a file search dialog.  Put results in a new output window.</dd>
 <dt>Replace...</dt>
 <dd>Open a search-and-replace dialog.</dd>
 <dt>Go to Line</dt>
@@ -224,10 +224,10 @@ Editor window.</dd>
 <dt>Run Module</dt>
 <dd>Do Check Module (above).  If no error, restart the shell to clean the
 environment, then execute the module.  Output is displayed in the Shell
-window.  Note that output requires use of <tt class="docutils literal"><span class="pre">print</span></tt> or <tt class="docutils literal"><span class="pre">write</span></tt>.
+window.  Note that output requires use of <code class="docutils literal"><span class="pre">print</span></code> or <code class="docutils literal"><span class="pre">write</span></code>.
 When execution is complete, the Shell retains focus and displays a prompt.
 At this point, one may interactively explore the result of execution.
-This is similar to executing a file with <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-i</span> <span class="pre">file</span></tt> at a command
+This is similar to executing a file with <code class="docutils literal"><span class="pre">python</span> <span class="pre">-i</span> <span class="pre">file</span></code> at a command
 line.</dd>
 </dl>
 </div>
@@ -339,47 +339,47 @@ debugger.  Breakpoints for a file are saved in the user&#8217;s .idlerc director
 </div>
 <div class="section" id="editing-and-navigation">
 <h2>24.6.2. Editing and navigation<a class="headerlink" href="#editing-and-navigation" title="Permalink to this headline">¶</a></h2>
-<p>In this section, &#8216;C&#8217; refers to the <tt class="kbd docutils literal"><span class="pre">Control</span></tt> key on Windows and Unix and
-the <tt class="kbd docutils literal"><span class="pre">Command</span></tt> key on Mac OSX.</p>
+<p>In this section, &#8216;C&#8217; refers to the <code class="kbd docutils literal"><span class="pre">Control</span></code> key on Windows and Unix and
+the <code class="kbd docutils literal"><span class="pre">Command</span></code> key on Mac OSX.</p>
 <ul>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">Backspace</span></tt> deletes to the left; <tt class="kbd docutils literal"><span class="pre">Del</span></tt> deletes to the right</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">Backspace</span></code> deletes to the left; <code class="kbd docutils literal"><span class="pre">Del</span></code> deletes to the right</p>
 </li>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">C-Backspace</span></tt> delete word left; <tt class="kbd docutils literal"><span class="pre">C-Del</span></tt> delete word to the right</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">C-Backspace</span></code> delete word left; <code class="kbd docutils literal"><span class="pre">C-Del</span></code> delete word to the right</p>
 </li>
-<li><p class="first">Arrow keys and <tt class="kbd docutils literal"><span class="pre">Page</span> <span class="pre">Up</span></tt>/<tt class="kbd docutils literal"><span class="pre">Page</span> <span class="pre">Down</span></tt> to move around</p>
+<li><p class="first">Arrow keys and <code class="kbd docutils literal"><span class="pre">Page</span> <span class="pre">Up</span></code>/<code class="kbd docutils literal"><span class="pre">Page</span> <span class="pre">Down</span></code> to move around</p>
 </li>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">C-LeftArrow</span></tt> and <tt class="kbd docutils literal"><span class="pre">C-RightArrow</span></tt> moves by words</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">C-LeftArrow</span></code> and <code class="kbd docutils literal"><span class="pre">C-RightArrow</span></code> moves by words</p>
 </li>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">Home</span></tt>/<tt class="kbd docutils literal"><span class="pre">End</span></tt> go to begin/end of line</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">Home</span></code>/<code class="kbd docutils literal"><span class="pre">End</span></code> go to begin/end of line</p>
 </li>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">C-Home</span></tt>/<tt class="kbd docutils literal"><span class="pre">C-End</span></tt> go to begin/end of file</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">C-Home</span></code>/<code class="kbd docutils literal"><span class="pre">C-End</span></code> go to begin/end of file</p>
 </li>
 <li><p class="first">Some useful Emacs bindings are inherited from Tcl/Tk:</p>
 <blockquote>
 <div><ul class="simple">
-<li><tt class="kbd docutils literal"><span class="pre">C-a</span></tt> beginning of line</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-e</span></tt> end of line</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-k</span></tt> kill line (but doesn&#8217;t put it in clipboard)</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-l</span></tt> center window around the insertion point</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-b</span></tt> go backwards one character without deleting (usually you can
+<li><code class="kbd docutils literal"><span class="pre">C-a</span></code> beginning of line</li>
+<li><code class="kbd docutils literal"><span class="pre">C-e</span></code> end of line</li>
+<li><code class="kbd docutils literal"><span class="pre">C-k</span></code> kill line (but doesn&#8217;t put it in clipboard)</li>
+<li><code class="kbd docutils literal"><span class="pre">C-l</span></code> center window around the insertion point</li>
+<li><code class="kbd docutils literal"><span class="pre">C-b</span></code> go backwards one character without deleting (usually you can
 also use the cursor key for this)</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-f</span></tt> go forward one character without deleting (usually you can
+<li><code class="kbd docutils literal"><span class="pre">C-f</span></code> go forward one character without deleting (usually you can
 also use the cursor key for this)</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-p</span></tt> go up one line (usually you can also use the cursor key for
+<li><code class="kbd docutils literal"><span class="pre">C-p</span></code> go up one line (usually you can also use the cursor key for
 this)</li>
-<li><tt class="kbd docutils literal"><span class="pre">C-d</span></tt> delete next character</li>
+<li><code class="kbd docutils literal"><span class="pre">C-d</span></code> delete next character</li>
 </ul>
 </div></blockquote>
 </li>
 </ul>
-<p>Standard keybindings (like <tt class="kbd docutils literal"><span class="pre">C-c</span></tt> to copy and <tt class="kbd docutils literal"><span class="pre">C-v</span></tt> to paste)
+<p>Standard keybindings (like <code class="kbd docutils literal"><span class="pre">C-c</span></code> to copy and <code class="kbd docutils literal"><span class="pre">C-v</span></code> to paste)
 may work.  Keybindings are selected in the Configure IDLE dialog.</p>
 <div class="section" id="automatic-indentation">
 <h3>24.6.2.1. Automatic indentation<a class="headerlink" href="#automatic-indentation" title="Permalink to this headline">¶</a></h3>
 <p>After a block-opening statement, the next line is indented by 4 spaces (in the
 Python Shell window by one tab).  After certain keywords (break, return etc.)
-the next line is dedented.  In leading indentation, <tt class="kbd docutils literal"><span class="pre">Backspace</span></tt> deletes up
-to 4 spaces if they are there. <tt class="kbd docutils literal"><span class="pre">Tab</span></tt> inserts spaces (in the Python
+the next line is dedented.  In leading indentation, <code class="kbd docutils literal"><span class="pre">Backspace</span></code> deletes up
+to 4 spaces if they are there. <code class="kbd docutils literal"><span class="pre">Tab</span></code> inserts spaces (in the Python
 Shell window one tab), number depends on Indent width. Currently tabs
 are restricted to four spaces due to Tcl/Tk limitations.</p>
 <p>See also the indent/dedent region commands in the edit menu.</p>
@@ -394,25 +394,25 @@ two seconds) after a &#8216;.&#8217; or (in a string) an os.sep is typed. If aft
 of those characters (plus zero or more other characters) a tab is typed
 the ACW will open immediately if a possible continuation is found.</p>
 <p>If there is only one possible completion for the characters entered, a
-<tt class="kbd docutils literal"><span class="pre">Tab</span></tt> will supply that completion without opening the ACW.</p>
+<code class="kbd docutils literal"><span class="pre">Tab</span></code> will supply that completion without opening the ACW.</p>
 <p>&#8216;Show Completions&#8217; will force open a completions window, by default the
-<tt class="kbd docutils literal"><span class="pre">C-space</span></tt> will open a completions window. In an empty
+<code class="kbd docutils literal"><span class="pre">C-space</span></code> will open a completions window. In an empty
 string, this will contain the files in the current directory. On a
 blank line, it will contain the built-in and user-defined functions and
 classes in the current name spaces, plus any modules imported. If some
 characters have been entered, the ACW will attempt to be more specific.</p>
 <p>If a string of characters is typed, the ACW selection will jump to the
-entry most closely matching those characters.  Entering a <tt class="kbd docutils literal"><span class="pre">tab</span></tt> will
+entry most closely matching those characters.  Entering a <code class="kbd docutils literal"><span class="pre">tab</span></code> will
 cause the longest non-ambiguous match to be entered in the Editor window or
-Shell.  Two <tt class="kbd docutils literal"><span class="pre">tab</span></tt> in a row will supply the current ACW selection, as
+Shell.  Two <code class="kbd docutils literal"><span class="pre">tab</span></code> in a row will supply the current ACW selection, as
 will return or a double click.  Cursor keys, Page Up/Down, mouse selection,
 and the scroll wheel all operate on the ACW.</p>
 <p>&#8220;Hidden&#8221; attributes can be accessed by typing the beginning of hidden
 name after a &#8216;.&#8217;, e.g. &#8216;_&#8217;. This allows access to modules with
-<tt class="docutils literal"><span class="pre">__all__</span></tt> set, or to class-private attributes.</p>
+<code class="docutils literal"><span class="pre">__all__</span></code> set, or to class-private attributes.</p>
 <p>Completions and the &#8216;Expand Word&#8217; facility can save a lot of typing!</p>
 <p>Completions are currently limited to those in the namespaces. Names in
-an Editor window which are not via <tt class="docutils literal"><span class="pre">__main__</span></tt> and <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><tt class="xref py py-data docutils literal"><span class="pre">sys.modules</span></tt></a> will
+an Editor window which are not via <code class="docutils literal"><span class="pre">__main__</span></code> and <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal"><span class="pre">sys.modules</span></code></a> will
 not be found.  Run the module once with your imports to correct this situation.
 Note that IDLE itself places quite a few modules in sys.modules, so
 much can be found by default, e.g. the re module.</p>
@@ -421,10 +421,10 @@ longer or disable the extension.</p>
 </div>
 <div class="section" id="calltips">
 <h3>24.6.2.3. Calltips<a class="headerlink" href="#calltips" title="Permalink to this headline">¶</a></h3>
-<p>A calltip is shown when one types <tt class="kbd docutils literal"><span class="pre">(</span></tt> after the name of an <em>acccessible</em>
+<p>A calltip is shown when one types <code class="kbd docutils literal"><span class="pre">(</span></code> after the name of an <em>acccessible</em>
 function.  A name expression may include dots and subscripts.  A calltip
 remains until it is clicked, the cursor is moved out of the argument area,
-or <tt class="kbd docutils literal"><span class="pre">)</span></tt> is typed.  When the cursor is in the argument part of a definition,
+or <code class="kbd docutils literal"><span class="pre">)</span></code> is typed.  When the cursor is in the argument part of a definition,
 the menu or shortcut display a calltip.</p>
 <p>A calltip consists of the function signature and the first line of the
 docstring.  For builtins without an accessible signature, the calltip
@@ -433,11 +433,11 @@ details may change.</p>
 <p>The set of <em>accessible</em> functions depends on what modules have been imported
 into the user process, including those imported by Idle itself,
 and what definitions have been run, all since the last restart.</p>
-<p>For example, restart the Shell and enter <tt class="docutils literal"><span class="pre">itertools.count(</span></tt>.  A calltip
+<p>For example, restart the Shell and enter <code class="docutils literal"><span class="pre">itertools.count(</span></code>.  A calltip
 appears because Idle imports itertools into the user process for its own use.
-(This could change.)  Enter <tt class="docutils literal"><span class="pre">turtle.write(</span></tt> and nothing appears.  Idle does
+(This could change.)  Enter <code class="docutils literal"><span class="pre">turtle.write(</span></code> and nothing appears.  Idle does
 not import turtle.  The menu or shortcut do nothing either.  Enter
-<tt class="docutils literal"><span class="pre">import</span> <span class="pre">turtle</span></tt> and then <tt class="docutils literal"><span class="pre">turtle.write(</span></tt> will work.</p>
+<code class="docutils literal"><span class="pre">import</span> <span class="pre">turtle</span></code> and then <code class="docutils literal"><span class="pre">turtle.write(</span></code> will work.</p>
 <p>In an editor, import statements have no effect until one runs the file.  One
 might want to run a file after writing the import statements at the top,
 or immediately run an existing file before editing.</p>
@@ -445,17 +445,17 @@ or immediately run an existing file before editing.</p>
 <div class="section" id="python-shell-window">
 <h3>24.6.2.4. Python Shell window<a class="headerlink" href="#python-shell-window" title="Permalink to this headline">¶</a></h3>
 <ul>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">C-c</span></tt> interrupts executing command</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">C-c</span></code> interrupts executing command</p>
 </li>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">C-d</span></tt> sends end-of-file; closes window if typed at a <tt class="docutils literal"><span class="pre">&gt;&gt;&gt;</span></tt> prompt</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">C-d</span></code> sends end-of-file; closes window if typed at a <code class="docutils literal"><span class="pre">&gt;&gt;&gt;</span></code> prompt</p>
 </li>
-<li><p class="first"><tt class="kbd docutils literal"><span class="pre">Alt-/</span></tt> (Expand word) is also useful to reduce typing</p>
+<li><p class="first"><code class="kbd docutils literal"><span class="pre">Alt-/</span></code> (Expand word) is also useful to reduce typing</p>
 <p>Command history</p>
 <ul class="simple">
-<li><tt class="kbd docutils literal"><span class="pre">Alt-p</span></tt> retrieves previous command matching what you have typed. On
-OS X use <tt class="kbd docutils literal"><span class="pre">C-p</span></tt>.</li>
-<li><tt class="kbd docutils literal"><span class="pre">Alt-n</span></tt> retrieves next. On OS X use <tt class="kbd docutils literal"><span class="pre">C-n</span></tt>.</li>
-<li><tt class="kbd docutils literal"><span class="pre">Return</span></tt> while on any previous command retrieves that command</li>
+<li><code class="kbd docutils literal"><span class="pre">Alt-p</span></code> retrieves previous command matching what you have typed. On
+OS X use <code class="kbd docutils literal"><span class="pre">C-p</span></code>.</li>
+<li><code class="kbd docutils literal"><span class="pre">Alt-n</span></code> retrieves next. On OS X use <code class="kbd docutils literal"><span class="pre">C-n</span></code>.</li>
+<li><code class="kbd docutils literal"><span class="pre">Return</span></code> while on any previous command retrieves that command</li>
 </ul>
 </li>
 </ul>
@@ -465,8 +465,8 @@ OS X use <tt class="kbd docutils literal"><span class="pre">C-p</span></tt>.</li
 <p>Idle defaults to black on white text, but colors text with special meanings.
 For the shell, these are shell output, shell error, user output, and
 user error.  For Python code, at the shell prompt or in an editor, these are
-keywords, builtin class and function names, names following <tt class="docutils literal"><span class="pre">class</span></tt> and
-<tt class="docutils literal"><span class="pre">def</span></tt>, strings, and comments. For any text window, these are the cursor (when
+keywords, builtin class and function names, names following <code class="docutils literal"><span class="pre">class</span></code> and
+<code class="docutils literal"><span class="pre">def</span></code>, strings, and comments. For any text window, these are the cursor (when
 present), found text (when possible), and selected text.</p>
 <p>Text coloring is done in the background, so uncolorized text is occasionally
 visible.  To change the color scheme, use the Configure IDLE dialog
@@ -476,15 +476,15 @@ text in popups and dialogs is not user-configurable.</p>
 </div>
 <div class="section" id="startup-and-code-execution">
 <h2>24.6.3. Startup and code execution<a class="headerlink" href="#startup-and-code-execution" title="Permalink to this headline">¶</a></h2>
-<p>Upon startup with the <tt class="docutils literal"><span class="pre">-s</span></tt> option, IDLE will execute the file referenced by
-the environment variables <span class="target" id="index-5"></span><tt class="xref std std-envvar docutils literal"><span class="pre">IDLESTARTUP</span></tt> or <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><tt class="xref std std-envvar docutils literal"><span class="pre">PYTHONSTARTUP</span></tt></a>.
-IDLE first checks for <tt class="docutils literal"><span class="pre">IDLESTARTUP</span></tt>; if <tt class="docutils literal"><span class="pre">IDLESTARTUP</span></tt> is present the file
-referenced is run.  If <tt class="docutils literal"><span class="pre">IDLESTARTUP</span></tt> is not present, IDLE checks for
-<tt class="docutils literal"><span class="pre">PYTHONSTARTUP</span></tt>.  Files referenced by these environment variables are
+<p>Upon startup with the <code class="docutils literal"><span class="pre">-s</span></code> option, IDLE will execute the file referenced by
+the environment variables <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal"><span class="pre">IDLESTARTUP</span></code> or <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal"><span class="pre">PYTHONSTARTUP</span></code></a>.
+IDLE first checks for <code class="docutils literal"><span class="pre">IDLESTARTUP</span></code>; if <code class="docutils literal"><span class="pre">IDLESTARTUP</span></code> is present the file
+referenced is run.  If <code class="docutils literal"><span class="pre">IDLESTARTUP</span></code> is not present, IDLE checks for
+<code class="docutils literal"><span class="pre">PYTHONSTARTUP</span></code>.  Files referenced by these environment variables are
 convenient places to store functions that are used frequently from the IDLE
 shell, or for executing import statements to import common modules.</p>
-<p>In addition, <tt class="docutils literal"><span class="pre">Tk</span></tt> also loads a startup file if it is present.  Note that the
-Tk file is loaded unconditionally.  This additional file is <tt class="docutils literal"><span class="pre">.Idle.py</span></tt> and is
+<p>In addition, <code class="docutils literal"><span class="pre">Tk</span></code> also loads a startup file if it is present.  Note that the
+Tk file is loaded unconditionally.  This additional file is <code class="docutils literal"><span class="pre">.Idle.py</span></code> and is
 looked for in the user&#8217;s home directory.  Statements in this file will be
 executed in the Tk namespace, so this file is not useful for importing
 functions to be used from IDLE&#8217;s Python shell.</p>
@@ -505,25 +505,27 @@ functions to be used from IDLE&#8217;s Python shell.</p>
 </div>
 <p>If there are arguments:</p>
 <ul class="simple">
-<li>If <tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">-c</span></tt>, or <tt class="docutils literal"><span class="pre">r</span></tt> is used, all arguments are placed in
-<tt class="docutils literal"><span class="pre">sys.argv[1:...]</span></tt> and <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is set to <tt class="docutils literal"><span class="pre">''</span></tt>, <tt class="docutils literal"><span class="pre">'-c'</span></tt>,
-or <tt class="docutils literal"><span class="pre">'-r'</span></tt>.  No editor window is opened, even if that is the default
+<li>If <code class="docutils literal"><span class="pre">-</span></code>, <code class="docutils literal"><span class="pre">-c</span></code>, or <code class="docutils literal"><span class="pre">r</span></code> is used, all arguments are placed in
+<code class="docutils literal"><span class="pre">sys.argv[1:...]</span></code> and <code class="docutils literal"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal"><span class="pre">''</span></code>, <code class="docutils literal"><span class="pre">'-c'</span></code>,
+or <code class="docutils literal"><span class="pre">'-r'</span></code>.  No editor window is opened, even if that is the default
 set in the Options dialog.</li>
 <li>Otherwise, arguments are files opened for editing and
-<tt class="docutils literal"><span class="pre">sys.argv</span></tt> reflects the arguments passed to IDLE itself.</li>
+<code class="docutils literal"><span class="pre">sys.argv</span></code> reflects the arguments passed to IDLE itself.</li>
 </ul>
 </div>
 <div class="section" id="idle-console-differences">
 <h3>24.6.3.2. IDLE-console differences<a class="headerlink" href="#idle-console-differences" title="Permalink to this headline">¶</a></h3>
 <p>As much as possible, the result of executing Python code with IDLE is the
 same as executing the same code in a console window.  However, the different
-interface and operation occasionally affects results.</p>
-<p>For instance, IDLE normally executes user code in a separate process from
-the IDLE GUI itself.  The IDLE versions of sys.stdin, .stdout, and .stderr in the
-execution process get input from and send output to the GUI process,
-which keeps control of the keyboard and screen.  This is normally transparent,
-but code that access these object will see different attribute values.
-Also, functions that directly access the keyboard and screen will not work.</p>
+interface and operation occasionally affects visible results.  For instance,
+<code class="docutils literal"><span class="pre">sys.modules</span></code> starts with more entries.</p>
+<p>IDLE also replaces <code class="docutils literal"><span class="pre">sys.stdin</span></code>, <code class="docutils literal"><span class="pre">sys.stdout</span></code>, and <code class="docutils literal"><span class="pre">sys.stderr</span></code> with
+objects that get input from and send output to the Shell window.
+When this window has the focus, it controls the keyboard and screen.
+This is normally transparent, but functions that directly access the keyboard
+and screen will not work.  If <code class="docutils literal"><span class="pre">sys</span></code> is reset with <code class="docutils literal"><span class="pre">reload(sys)</span></code>,
+IDLE&#8217;s changes are lost and things like <code class="docutils literal"><span class="pre">input</span></code>, <code class="docutils literal"><span class="pre">raw_input</span></code>, and
+<code class="docutils literal"><span class="pre">print</span></code> will not work correctly.</p>
 <p>With IDLE&#8217;s Shell, one enters, edits, and recalls complete statements.
 Some consoles only work with a single physical line at a time.</p>
 </div>
@@ -595,7 +597,7 @@ are currently:</p>
           </div>
         </div>
       </div>
-      <div class="sphinxsidebar">
+      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
         <div class="sphinxsidebarwrapper">
   <h3><a href="../contents.html">Table Of Contents</a></h3>
   <ul>
@@ -639,7 +641,7 @@ are currently:</p>
 
   <h4>Previous topic</h4>
   <p class="topless"><a href="turtle.html"
-                        title="previous chapter">24.5. <tt class="docutils literal"><span class="pre">turtle</span></tt> &#8212; Turtle graphics for Tk</a></p>
+                        title="previous chapter">24.5. <code class="docutils literal"><span class="pre">turtle</span></code> &#8212; Turtle graphics for Tk</a></p>
   <h4>Next topic</h4>
   <p class="topless"><a href="othergui.html"
                         title="next chapter">24.7. Other Graphical User Interface Packages</a></p>
@@ -650,7 +652,7 @@ are currently:</p>
          rel="nofollow">Show Source</a></li>
 </ul>
 
-<div id="searchbox" style="display: none">
+<div id="searchbox" style="display: none" role="search">
   <h3>Quick search</h3>
     <form class="search" action="../search.html" method="get">
       <input type="text" name="q" />
@@ -667,7 +669,7 @@ are currently:</p>
       </div>
       <div class="clearer"></div>
     </div>
-    <div class="related">
+    <div class="related" role="navigation" aria-label="related navigation">
       <h3>Navigation</h3>
       <ul>
         <li class="right" style="margin-right: 10px">
@@ -686,23 +688,23 @@ are currently:</p>
                  style="vertical-align: middle; margin-top: -1px"/></li>
         <li><a href="https://www.python.org/">Python</a> &raquo;</li>
         <li>
-          <a href="../index.html">Python 2.7.10 documentation</a> &raquo;
+          <a href="../index.html">Python 2.7.11 documentation</a> &raquo;
         </li>
 
-          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
-          <li><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &raquo;</li>
+          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &raquo;</li>
+          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &raquo;</li>
       </ul>
     </div>
     <div class="footer">
-    &copy; <a href="../copyright.html">Copyright</a> 1990-2015, Python Software Foundation.
+    &copy; <a href="../copyright.html">Copyright</a> 1990-2016, Python Software Foundation.
     <br />
     The Python Software Foundation is a non-profit corporation.
     <a href="https://www.python.org/psf/donations/">Please donate.</a>
     <br />
-    Last updated on Oct 13, 2015.
+    Last updated on May 02, 2016.
     <a href="../bugs.html">Found a bug</a>?
     <br />
-    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.3.
+    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
     </div>
 
   </body>
index 6398c77..ba098ca 100644 (file)
@@ -11,7 +11,7 @@ Help => IDLE Help: Display help.html with proper formatting.
 Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html
 (help.copy_strip)=> Lib/idlelib/help.html
 
-HelpParser - Parse help.html and and render to tk Text.
+HelpParser - Parse help.html and render to tk Text.
 
 HelpText - Display formatted help.html.
 
@@ -45,6 +45,8 @@ class HelpParser(HTMLParser):
     The overridden handle_xyz methods handle a subset of html tags.
     The supplied text should have the needed tag configurations.
     The behavior for unsupported tags, such as table, is undefined.
+    If the tags generated by Sphinx change, this class, especially
+    the handle_starttag and handle_endtags methods, might have to also.
     """
     def __init__(self, text):
         HTMLParser.__init__(self)
@@ -229,7 +231,28 @@ class HelpWindow(Toplevel):
 
 
 def copy_strip():
-    "Copy idle.html to idlelib/help.html, stripping trailing whitespace."
+    """Copy idle.html to idlelib/help.html, stripping trailing whitespace.
+
+    Files with trailing whitespace cannot be pushed to the hg cpython
+    repository.  For 3.x (on Windows), help.html is generated, after
+    editing idle.rst in the earliest maintenance version, with
+      sphinx-build -bhtml . build/html
+      python_d.exe -c "from idlelib.help import copy_strip; copy_strip()"
+    After refreshing TortoiseHG workshop to generate a diff,
+    check  both the diff and displayed text.  Push the diff along with
+    the idle.rst change and merge both into default (or an intermediate
+    maintenance version).
+
+    When the 'earlist' version gets its final maintenance release,
+    do an update as described above, without editing idle.rst, to
+    rebase help.html on the next version of idle.rst.  Do not worry
+    about version changes as version is not displayed.  Examine other
+    changes and the result of Help -> IDLE Help.
+
+    If maintenance and default versions of idle.rst diverge, and
+    merging does not go smoothly, then consider generating
+    separate help.html files from separate idle.htmls.
+    """
     src = join(abspath(dirname(dirname(dirname(__file__)))),
                'Doc', 'build', 'html', 'library', 'idle.html')
     dst = join(abspath(dirname(__file__)), 'help.html')
index 2339926..6967d70 100644 (file)
@@ -16,7 +16,7 @@ python -m idlelib.idle_test.htest
 
 The idle directory, idlelib, has over 60 xyz.py files. The idle_test
 subdirectory should contain a test_xyz.py for each, where 'xyz' is lowercased
-even if xyz.py is not. Here is a possible template, with the blanks after after
+even if xyz.py is not. Here is a possible template, with the blanks after
 '.' and 'as', and before and after '_' to be filled in.
 
 import unittest
@@ -42,48 +42,55 @@ if __name__ == "__main__":
 
 2. GUI Tests
 
-When run as part of the Python test suite, Idle gui tests need to run
-test.support.requires('gui') (test.test_support in 2.7).  A test is a gui test
+When run as part of the Python test suite, Idle GUI tests need to run
+test.test_support.requires('gui') (test.support in 3.x).  A test is a GUI test
 if it creates a Tk root or master object either directly or indirectly by
 instantiating a tkinter or idle class.  For the benefit of test processes that
-either have no graphical environment available or are not allowed to use it, gui
+either have no graphical environment available or are not allowed to use it, GUI
 tests must be 'guarded' by "requires('gui')" in a setUp function or method.
 This will typically be setUpClass.
 
-To avoid interfering with other gui tests, all gui objects must be destroyed and
-deleted by the end of the test.  Widgets, such as a Tk root, created in a setUpX
-function, should be destroyed in the corresponding tearDownX.  Module and class
-widget attributes should also be deleted..
+To avoid interfering with other GUI tests, all GUI objects must be destroyed and
+deleted by the end of the test.  The Tk root created in a setUpX function should
+be destroyed in the corresponding tearDownX and the module or class attribute
+deleted.  Others widgets should descend from the single root and the attributes
+deleted BEFORE root is destroyed.  See https://bugs.python.org/issue20567.
 
     @classmethod
     def setUpClass(cls):
         requires('gui')
         cls.root = tk.Tk()
+        cls.text = tk.Text(root)
 
     @classmethod
     def tearDownClass(cls):
+        del cls.text
         cls.root.destroy()
         del cls.root
 
+WARNING: In 2.7, "requires('gui') MUST NOT be called at module scope.
+See https://bugs.python.org/issue18910
 
 Requires('gui') causes the test(s) it guards to be skipped if any of
-a few conditions are met:
-    
+these conditions are met:
+
  - The tests are being run by regrtest.py, and it was started without enabling
    the "gui" resource with the "-u" command line option.
-   
+
  - The tests are being run on Windows by a service that is not allowed to
    interact with the graphical environment.
-   
+
+ - The tests are being run on Linux and X Windows is not available.
+
  - The tests are being run on Mac OSX in a process that cannot make a window
    manager connection.
-   
+
  - tkinter.Tk cannot be successfully instantiated for some reason.
+
  - test.support.use_resources has been set by something other than
    regrtest.py and does not contain "gui".
-   
-Tests of non-gui operations should avoid creating tk widgets. Incidental uses of
+
+Tests of non-GUI operations should avoid creating tk widgets. Incidental uses of
 tk variables and messageboxes can be replaced by the mock classes in
 idle_test/mock_tk.py. The mock text handles some uses of the tk Text widget.
 
@@ -98,7 +105,7 @@ when developing tests. The 'exit=False' option is needed in xyx.py files when an
 htest follows.
 
 The following command lines also run all test methods, including
-gui tests, in test_xyz.py. (Both '-m idlelib' and '-m idlelib.idle' start
+GUI tests, in test_xyz.py. (Both '-m idlelib' and '-m idlelib.idle' start
 Idle and so cannot run tests.)
 
 python -m idlelib.xyz
index 1bc9536..845c92d 100644 (file)
@@ -1,3 +1,9 @@
+'''idlelib.idle_test is a private implementation of test.test_idle,
+which tests the IDLE application as part of the stdlib test suite.
+Run IDLE tests alone with "python -m test.test_idle".
+This package and its contained modules are subject to change and
+any direct use is at your own risk.
+'''
 from os.path import dirname
 
 def load_tests(loader, standard_tests, pattern):
index a3e6d3a..f341409 100644 (file)
@@ -192,7 +192,10 @@ _io_binding_spec = {
     'msg': "Test the following bindings.\n"
            "<Control-o> to open file from dialog.\n"
            "Edit the file.\n"
+           "<Control-p> to print the file.\n"
            "<Control-s> to save the file.\n"
+           "<Alt-s> to save-as another file.\n"
+           "<Control-c> to save-copy-as another file.\n"
            "Check that changes were saved by opening the file elsewhere."
     }
 
index c2a7266..1e98590 100644 (file)
@@ -33,9 +33,8 @@ class AutoCompleteTest(unittest.TestCase):
 
     @classmethod
     def tearDownClass(cls):
+        del cls.editor, cls.text
         cls.root.destroy()
-        del cls.text
-        del cls.editor
         del cls.root
 
     def setUp(self):
index bdb7e8b..6be4fbf 100644 (file)
@@ -25,10 +25,10 @@ class AutoExpandTest(unittest.TestCase):
 
     @classmethod
     def tearDownClass(cls):
+        del cls.text, cls.auto_expand
         if hasattr(cls, 'tk'):
             cls.tk.destroy()
             del cls.tk
-        del cls.text, cls.auto_expand
 
     def tearDown(self):
         self.text.delete('1.0', 'end')
index 3fbc822..62727c0 100644 (file)
@@ -24,8 +24,8 @@ class ConfigDialogTest(unittest.TestCase):
         del cls.root
 
     def test_dialog(self):
-        d=ConfigDialog(self.root, 'Test', _utest=True)
-        d.destroy()
+        d = ConfigDialog(self.root, 'Test', _utest=True)
+        d.remove_var_callbacks()
 
 
 if __name__ == '__main__':
diff --git a/Lib/idlelib/idle_test/test_editmenu.py b/Lib/idlelib/idle_test/test_editmenu.py
new file mode 100644 (file)
index 0000000..1d36069
--- /dev/null
@@ -0,0 +1,98 @@
+'''Test (selected) IDLE Edit menu items.
+
+Edit modules have their own test files files
+'''
+from test.test_support import requires
+import Tkinter as tk
+import unittest
+from idlelib import PyShell
+
+class PasteTest(unittest.TestCase):
+    '''Test pasting into widgets that allow pasting.
+
+    On X11, replacing selections requires tk fix.
+    '''
+    @classmethod
+    def setUpClass(cls):
+        requires('gui')
+        cls.root = root = tk.Tk()
+        PyShell.fix_x11_paste(root)
+        cls.text = tk.Text(root)
+        cls.entry = tk.Entry(root)
+        cls.spin = tk.Spinbox(root)
+        root.clipboard_clear()
+        root.clipboard_append('two')
+
+    @classmethod
+    def tearDownClass(cls):
+        del cls.text, cls.entry, cls.spin
+        cls.root.clipboard_clear()
+        cls.root.update_idletasks()
+        cls.root.update()
+        cls.root.destroy()
+        del cls.root
+
+    def test_paste_text_no_selection(self):
+        "Test pasting into text without a selection."
+        text = self.text
+        tag, ans = '', 'onetwo\n'
+        text.delete('1.0', 'end')
+        text.insert('1.0', 'one', tag)
+        text.event_generate('<<Paste>>')
+        self.assertEqual(text.get('1.0', 'end'), ans)
+
+    def test_paste_text_selection(self):
+        "Test pasting into text with a selection."
+        text = self.text
+        tag, ans = 'sel', 'two\n'
+        text.delete('1.0', 'end')
+        text.insert('1.0', 'one', tag)
+        text.event_generate('<<Paste>>')
+        self.assertEqual(text.get('1.0', 'end'), ans)
+
+    def test_paste_entry_no_selection(self):
+        "Test pasting into an entry without a selection."
+        # On 3.6, generated <<Paste>> fails without empty select range
+        # for 'no selection'.  Live widget works fine.
+        entry = self.entry
+        end, ans = 0, 'onetwo'
+        entry.delete(0, 'end')
+        entry.insert(0, 'one')
+        entry.select_range(0, end)  # see note
+        entry.event_generate('<<Paste>>')
+        self.assertEqual(entry.get(), ans)
+
+    def test_paste_entry_selection(self):
+        "Test pasting into an entry with a selection."
+        entry = self.entry
+        end, ans = 'end', 'two'
+        entry.delete(0, 'end')
+        entry.insert(0, 'one')
+        entry.select_range(0, end)
+        entry.event_generate('<<Paste>>')
+        self.assertEqual(entry.get(), ans)
+
+    def test_paste_spin_no_selection(self):
+        "Test pasting into a spinbox without a selection."
+        # See note above for entry.
+        spin = self.spin
+        end, ans = 0, 'onetwo'
+        spin.delete(0, 'end')
+        spin.insert(0, 'one')
+        spin.selection('range', 0, end)  # see note
+        spin.event_generate('<<Paste>>')
+        self.assertEqual(spin.get(), ans)
+
+    def test_paste_spin_selection(self):
+        "Test pasting into a spinbox with a selection."
+        spin = self.spin
+        end, ans = 'end', 'two'
+        spin.delete(0, 'end')
+        spin.insert(0, 'one')
+        spin.selection('range', 0, end)
+        spin.event_generate('<<Paste>>')
+        self.assertEqual(spin.get(), ans)
+
+
+if __name__ == '__main__':
+    unittest.main(verbosity=2)
index 9185a96..938110d 100644 (file)
@@ -276,10 +276,9 @@ class FormatEventTest(unittest.TestCase):
 
     @classmethod
     def tearDownClass(cls):
+        del cls.text, cls.formatter
         cls.root.destroy()
         del cls.root
-        del cls.text
-        del cls.formatter
 
     def test_short_line(self):
         self.text.insert('1.0', "Short line\n")
diff --git a/Lib/idlelib/idle_test/test_helpabout.py b/Lib/idlelib/idle_test/test_helpabout.py
new file mode 100644 (file)
index 0000000..0046f87
--- /dev/null
@@ -0,0 +1,52 @@
+'''Test idlelib.help_about.
+
+Coverage:
+'''
+from idlelib import aboutDialog as help_about
+from idlelib import textView as textview
+from idlelib.idle_test.mock_idle import Func
+from idlelib.idle_test.mock_tk import Mbox
+import unittest
+
+About = help_about.AboutDialog
+class Dummy_about_dialog():
+    # Dummy class for testing file display functions.
+    idle_credits = About.ShowIDLECredits.im_func
+    idle_readme = About.ShowIDLEAbout.im_func
+    idle_news = About.ShowIDLENEWS.im_func
+    # Called by the above
+    display_file_text = About.display_file_text.im_func
+
+
+class DisplayFileTest(unittest.TestCase):
+    "Test that .txt files are found and properly decoded."
+    dialog = Dummy_about_dialog()
+
+    @classmethod
+    def setUpClass(cls):
+        cls.orig_mbox = textview.tkMessageBox
+        cls.orig_view = textview.view_text
+        cls.mbox = Mbox()
+        cls.view = Func()
+        textview.tkMessageBox = cls.mbox
+        textview.view_text = cls.view
+        cls.About = Dummy_about_dialog()
+
+    @classmethod
+    def tearDownClass(cls):
+        textview.tkMessageBox = cls.orig_mbox
+        textview.view_text = cls.orig_view.im_func
+
+    def test_file_isplay(self):
+        for handler in (self.dialog.idle_credits,
+                        self.dialog.idle_readme,
+                        self.dialog.idle_news):
+            self.mbox.showerror.message = ''
+            self.view.called = False
+            handler()
+            self.assertEqual(self.mbox.showerror.message, '')
+            self.assertEqual(self.view.called, True)
+
+
+if __name__ == '__main__':
+    unittest.main(verbosity=2)
index 0e81b63..4af7b49 100644 (file)
@@ -23,10 +23,9 @@ class textviewClassTest(unittest.TestCase):
 
     @classmethod
     def tearDownClass(cls):
+        del cls.TV
         cls.root.destroy()
-        TV = cls.TV
-        del cls.root, cls.TV
-        del TV.transient, TV.grab_set, TV.wait_window
+        del cls.root
 
     def setUp(self):
         TV = self.TV
index 26710f1..da1d8a1 100644 (file)
@@ -68,15 +68,6 @@ class ShellWarnTest(unittest.TestCase):
                     'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
             self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines())
 
-class ImportWarnTest(unittest.TestCase):
-    def test_idlever(self):
-        with warnings.catch_warnings(record=True) as w:
-            warnings.simplefilter("always")
-            import idlelib.idlever
-            self.assertEqual(len(w), 1)
-            self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
-            self.assertIn("version", str(w[-1].message))
-
 
 if __name__ == '__main__':
     unittest.main(verbosity=2, exit=False)
index 5a231fd..7129bb7 100644 (file)
@@ -14,14 +14,14 @@ class InitCloseTest(unittest.TestCase):
     @classmethod
     def setUpClass(cls):
         requires('gui')
-        cls.tk = Tk()
-        cls.text = Text(cls.tk)
+        cls.root = Tk()
+        cls.text = Text(cls.root)
 
     @classmethod
     def tearDownClass(cls):
-        cls.text.destroy()
-        cls.tk.destroy()
-        del cls.text, cls.tk
+        del cls.text
+        cls.root.destroy()
+        del cls.root
 
     def test_init(self):
         redir = WidgetRedirector(self.text)
@@ -43,14 +43,14 @@ class WidgetRedirectorTest(unittest.TestCase):
     @classmethod
     def setUpClass(cls):
         requires('gui')
-        cls.tk = Tk()
-        cls.text = Text(cls.tk)
+        cls.root = Tk()
+        cls.text = Text(cls.root)
 
     @classmethod
     def tearDownClass(cls):
-        cls.text.destroy()
-        cls.tk.destroy()
-        del cls.text, cls.tk
+        del cls.text
+        cls.root.destroy()
+        del cls.root
 
     def setUp(self):
         self.redir = WidgetRedirector(self.text)
@@ -108,13 +108,13 @@ class WidgetRedirectorTest(unittest.TestCase):
     def test_command_dispatch(self):
         # Test that .__init__ causes redirection of tk calls
         # through redir.dispatch
-        self.tk.call(self.text._w, 'insert', 'hello')
+        self.root.call(self.text._w, 'insert', 'hello')
         self.assertEqual(self.func.args, ('hello',))
         self.assertEqual(self.text.get('1.0', 'end'), '\n')
         # Ensure that called through redir .dispatch and not through
         # self.text.insert by having mock raise TclError.
         self.func.__init__(TclError())
-        self.assertEqual(self.tk.call(self.text._w, 'insert', 'boo'), '')
+        self.assertEqual(self.root.call(self.text._w, 'insert', 'boo'), '')
 
 
 
index 5c4aabd..43328e7 100644 (file)
@@ -1,4 +1,4 @@
-"""RPC Implemention, originally written for the Python Idle IDE
+"""RPC Implementation, originally written for the Python Idle IDE
 
 For security reasons, GvR requested that Idle's Python execution server process
 connect to the Idle process, which listens for the connection.  Since Idle has
index 8687d40..b8c4ac1 100644 (file)
@@ -79,6 +79,10 @@ def view_file(parent, title, filename, encoding=None, modal=True):
         tkMessageBox.showerror(title='File Load Error',
                                message='Unable to load file %r .' % filename,
                                parent=parent)
+    except UnicodeDecodeError as err:
+        showerror(title='Unicode Decode Error',
+                  message=str(err),
+                  parent=parent)
     else:
         return view_text(parent, title, textFile.read(), modal)
 
index 1f28e56..3266e01 100644 (file)
@@ -221,7 +221,7 @@ class Tk(Tkinter.Tk, tixCommand):
         self.tk.eval('package require Tix')
 
     def destroy(self):
-        # For safety, remove an delete_window binding before destroy
+        # For safety, remove the delete_window binding before destroy
         self.protocol("WM_DELETE_WINDOW", "")
         Tkinter.Tk.destroy(self)
 
@@ -702,7 +702,7 @@ class DirSelectBox(TixWidget):
 
 class ExFileSelectBox(TixWidget):
     """ExFileSelectBox - MS Windows style file select box.
-    It provides an convenient method for the user to select files.
+    It provides a convenient method for the user to select files.
 
     Subwidget       Class
     ---------       -----
@@ -760,7 +760,7 @@ class DirSelectDialog(TixWidget):
 # Should inherit from a Dialog class
 class ExFileSelectDialog(TixWidget):
     """ExFileSelectDialog - MS Windows style file select dialog.
-    It provides an convenient method for the user to select files.
+    It provides a convenient method for the user to select files.
 
     Subwidgets       Class
     ----------       -----
@@ -1052,8 +1052,8 @@ class InputOnly(TixWidget):
 
 class LabelEntry(TixWidget):
     """LabelEntry - Entry field with label. Packages an entry widget
-    and a label into one mega widget. It can beused be used to simplify
-    the creation of ``entry-form'' type of interface.
+    and a label into one mega widget. It can be used to simplify the creation
+    of ``entry-form'' type of interface.
 
     Subwidgets       Class
     ----------       -----
index 2e37d9e..1b09f91 100644 (file)
@@ -3,7 +3,7 @@
 This is very preliminary.  I currently only support dnd *within* one
 application, between different windows (or within the same window).
 
-I an trying to make this as generic as possible -- not dependent on
+I am trying to make this as generic as possible -- not dependent on
 the use of a particular widget or icon type, etc.  I also hope that
 this will work with Pmw.
 
index b4f6b3c..e825afa 100644 (file)
@@ -1244,7 +1244,7 @@ class Misc:
         nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
         # Missing: (a, c, d, m, o, v, B, R)
         e = Event()
-        # serial field: valid vor all events
+        # serial field: valid for all events
         # number of button: ButtonPress and ButtonRelease events only
         # height field: Configure, ConfigureRequest, Create,
         # ResizeRequest, and Expose events only
@@ -1252,11 +1252,11 @@ class Misc:
         # time field: "valid for events that contain a time field"
         # width field: Configure, ConfigureRequest, Create, ResizeRequest,
         # and Expose events only
-        # x field: "valid for events that contain a x field"
+        # x field: "valid for events that contain an x field"
         # y field: "valid for events that contain a y field"
         # keysym as decimal: KeyPress and KeyRelease events only
         # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
-        # KeyRelease,and Motion events
+        # KeyRelease, and Motion events
         e.serial = getint(nsign)
         e.num = getint_event(b)
         try: e.focus = getboolean(f)
@@ -1335,8 +1335,9 @@ class Misc:
         raise TypeError("Tkinter objects don't support 'in' tests.")
     def keys(self):
         """Return a list of all resource names of this widget."""
-        return [x[0][1:] for x in
-                self.tk.splitlist(self.tk.call(self._w, 'configure'))]
+        splitlist = self.tk.splitlist
+        return [splitlist(x)[0][1:] for x in
+                splitlist(self.tk.call(self._w, 'configure'))]
     def __str__(self):
         """Return the window path name of this widget."""
         return self._w
@@ -2486,7 +2487,7 @@ class Checkbutton(Widget):
         self.tk.call(self._w, 'toggle')
 
 class Entry(Widget, XView):
-    """Entry widget which allows to display simple text."""
+    """Entry widget which allows displaying simple text."""
     def __init__(self, master=None, cnf={}, **kw):
         """Construct an entry widget with the parent MASTER.
 
@@ -2682,7 +2683,7 @@ class Listbox(Widget, XView, YView):
     itemconfig = itemconfigure
 
 class Menu(Widget):
-    """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
+    """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
     def __init__(self, master=None, cnf={}, **kw):
         """Construct menu widget with the parent MASTER.
 
@@ -2777,7 +2778,7 @@ class Menu(Widget):
                     self.deletecommand(c)
         self.tk.call(self._w, 'delete', index1, index2)
     def entrycget(self, index, option):
-        """Return the resource value of an menu item for OPTION at INDEX."""
+        """Return the resource value of a menu item for OPTION at INDEX."""
         return self.tk.call(self._w, 'entrycget', index, '-' + option)
     def entryconfigure(self, index, cnf=None, **kw):
         """Configure a menu item at INDEX."""
@@ -3379,16 +3380,20 @@ class PhotoImage(Image):
         destImage = PhotoImage(master=self.tk)
         self.tk.call(destImage, 'copy', self.name)
         return destImage
-    def zoom(self,x,y=''):
+    def zoom(self, x, y=''):
         """Return a new PhotoImage with the same image as this widget
-        but zoom it with X and Y."""
+        but zoom it with a factor of x in the X direction and y in the Y
+        direction.  If y is not given, the default value is the same as x.
+        """
         destImage = PhotoImage(master=self.tk)
         if y=='': y=x
         self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
         return destImage
-    def subsample(self,x,y=''):
+    def subsample(self, x, y=''):
         """Return a new PhotoImage based on the same image as this widget
-        but use only every Xth or Yth pixel."""
+        but use only every Xth or Yth pixel.  If y is not given, the
+        default value is the same as x.
+        """
         destImage = PhotoImage(master=self.tk)
         if y=='': y=x
         self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
index 78c1f02..941fb31 100644 (file)
@@ -12,6 +12,8 @@ requires('gui')
 
 class PackTest(AbstractWidgetTest, unittest.TestCase):
 
+    test_keys = None
+
     def create2(self):
         pack = tkinter.Toplevel(self.root, name='pack')
         pack.wm_geometry('300x200+0+0')
@@ -276,6 +278,8 @@ class PackTest(AbstractWidgetTest, unittest.TestCase):
 
 class PlaceTest(AbstractWidgetTest, unittest.TestCase):
 
+    test_keys = None
+
     def create2(self):
         t = tkinter.Toplevel(self.root, width=300, height=200, bd=0)
         t.wm_geometry('300x200+0+0')
@@ -478,6 +482,8 @@ class PlaceTest(AbstractWidgetTest, unittest.TestCase):
 
 class GridTest(AbstractWidgetTest, unittest.TestCase):
 
+    test_keys = None
+
     def tearDown(self):
         cols, rows = self.root.grid_size()
         for i in range(cols + 1):
index 1916e34..4da3096 100644 (file)
@@ -99,7 +99,7 @@ class FrameTest(AbstractToplevelTest, unittest.TestCase):
         'background', 'borderwidth',
         'class', 'colormap', 'container', 'cursor', 'height',
         'highlightbackground', 'highlightcolor', 'highlightthickness',
-        'relief', 'takefocus', 'visual', 'width',
+        'padx', 'pady', 'relief', 'takefocus', 'visual', 'width',
     )
 
     def create(self, **kwargs):
@@ -633,7 +633,7 @@ class CanvasTest(AbstractWidgetTest, unittest.TestCase):
         'highlightbackground', 'highlightcolor', 'highlightthickness',
         'insertbackground', 'insertborderwidth',
         'insertofftime', 'insertontime', 'insertwidth',
-        'relief', 'scrollregion',
+        'offset', 'relief', 'scrollregion',
         'selectbackground', 'selectborderwidth', 'selectforeground',
         'state', 'takefocus',
         'xscrollcommand', 'xscrollincrement',
@@ -655,6 +655,15 @@ class CanvasTest(AbstractWidgetTest, unittest.TestCase):
         widget = self.create()
         self.checkBooleanParam(widget, 'confine')
 
+    def test_offset(self):
+        widget = self.create()
+        self.assertEqual(widget['offset'], '0,0')
+        self.checkParams(widget, 'offset',
+                'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center')
+        self.checkParam(widget, 'offset', '10,20')
+        self.checkParam(widget, 'offset', '#5,6')
+        self.checkInvalidParam(widget, 'offset', 'spam')
+
     def test_scrollregion(self):
         widget = self.create()
         self.checkParam(widget, 'scrollregion', '0 0 200 150')
index 714d950..ea3f81c 100644 (file)
@@ -195,7 +195,7 @@ class InternalFunctionsTest(unittest.TestCase):
 
         ## Testing type = vsapi
         # vsapi type expects at least a class name and a part_id, so this
-        # should raise an ValueError since it tries to get two elements from
+        # should raise a ValueError since it tries to get two elements from
         # an empty tuple
         self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi')
 
index 71de83f..f874a9c 100644 (file)
@@ -189,7 +189,7 @@ class AbstractLabelTest(AbstractWidgetTest):
 @add_standard_options(StandardTtkOptionsTests)
 class LabelTest(AbstractLabelTest, unittest.TestCase):
     OPTIONS = (
-        'anchor', 'background',
+        'anchor', 'background', 'borderwidth',
         'class', 'compound', 'cursor', 'font', 'foreground',
         'image', 'justify', 'padding', 'relief', 'state', 'style',
         'takefocus', 'text', 'textvariable',
@@ -210,7 +210,8 @@ class LabelTest(AbstractLabelTest, unittest.TestCase):
 class ButtonTest(AbstractLabelTest, unittest.TestCase):
     OPTIONS = (
         'class', 'command', 'compound', 'cursor', 'default',
-        'image', 'state', 'style', 'takefocus', 'text', 'textvariable',
+        'image', 'padding', 'state', 'style',
+        'takefocus', 'text', 'textvariable',
         'underline', 'width',
     )
 
@@ -234,7 +235,7 @@ class CheckbuttonTest(AbstractLabelTest, unittest.TestCase):
         'class', 'command', 'compound', 'cursor',
         'image',
         'offvalue', 'onvalue',
-        'state', 'style',
+        'padding', 'state', 'style',
         'takefocus', 'text', 'textvariable',
         'underline', 'variable', 'width',
     )
@@ -278,136 +279,10 @@ class CheckbuttonTest(AbstractLabelTest, unittest.TestCase):
 
 
 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
-class ComboboxTest(AbstractWidgetTest, unittest.TestCase):
-    OPTIONS = (
-        'class', 'cursor', 'exportselection', 'height',
-        'justify', 'postcommand', 'state', 'style',
-        'takefocus', 'textvariable', 'values', 'width',
-    )
-
-    def setUp(self):
-        super(ComboboxTest, self).setUp()
-        self.combo = self.create()
-
-    def create(self, **kwargs):
-        return ttk.Combobox(self.root, **kwargs)
-
-    def test_height(self):
-        widget = self.create()
-        self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i')
-
-    def test_state(self):
-        widget = self.create()
-        self.checkParams(widget, 'state', 'active', 'disabled', 'normal')
-
-    def _show_drop_down_listbox(self):
-        width = self.combo.winfo_width()
-        self.combo.event_generate('<ButtonPress-1>', x=width - 5, y=5)
-        self.combo.event_generate('<ButtonRelease-1>', x=width - 5, y=5)
-        self.combo.update_idletasks()
-
-
-    def test_virtual_event(self):
-        success = []
-
-        self.combo['values'] = [1]
-        self.combo.bind('<<ComboboxSelected>>',
-            lambda evt: success.append(True))
-        self.combo.pack()
-        self.combo.wait_visibility()
-
-        height = self.combo.winfo_height()
-        self._show_drop_down_listbox()
-        self.combo.update()
-        self.combo.event_generate('<Return>')
-        self.combo.update()
-
-        self.assertTrue(success)
-
-
-    def test_postcommand(self):
-        success = []
-
-        self.combo['postcommand'] = lambda: success.append(True)
-        self.combo.pack()
-        self.combo.wait_visibility()
-
-        self._show_drop_down_listbox()
-        self.assertTrue(success)
-
-        # testing postcommand removal
-        self.combo['postcommand'] = ''
-        self._show_drop_down_listbox()
-        self.assertEqual(len(success), 1)
-
-
-    def test_values(self):
-        def check_get_current(getval, currval):
-            self.assertEqual(self.combo.get(), getval)
-            self.assertEqual(self.combo.current(), currval)
-
-        self.assertEqual(self.combo['values'],
-                         () if tcl_version < (8, 5) else '')
-        check_get_current('', -1)
-
-        self.checkParam(self.combo, 'values', 'mon tue wed thur',
-                        expected=('mon', 'tue', 'wed', 'thur'))
-        self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur'))
-        self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string'))
-        self.checkParam(self.combo, 'values', () if tcl_version < (8, 5) else '')
-
-        self.combo['values'] = ['a', 1, 'c']
-
-        self.combo.set('c')
-        check_get_current('c', 2)
-
-        self.combo.current(0)
-        check_get_current('a', 0)
-
-        self.combo.set('d')
-        check_get_current('d', -1)
-
-        # testing values with empty string
-        self.combo.set('')
-        self.combo['values'] = (1, 2, '', 3)
-        check_get_current('', 2)
-
-        # testing values with empty string set through configure
-        self.combo.configure(values=[1, '', 2])
-        self.assertEqual(self.combo['values'],
-                         ('1', '', '2') if self.wantobjects else
-                         '1 {} 2')
-
-        # testing values with spaces
-        self.combo['values'] = ['a b', 'a\tb', 'a\nb']
-        self.assertEqual(self.combo['values'],
-                         ('a b', 'a\tb', 'a\nb') if self.wantobjects else
-                         '{a b} {a\tb} {a\nb}')
-
-        # testing values with special characters
-        self.combo['values'] = [r'a\tb', '"a"', '} {']
-        self.assertEqual(self.combo['values'],
-                         (r'a\tb', '"a"', '} {') if self.wantobjects else
-                         r'a\\tb {"a"} \}\ \{')
-
-        # out of range
-        self.assertRaises(tkinter.TclError, self.combo.current,
-            len(self.combo['values']))
-        # it expects an integer (or something that can be converted to int)
-        self.assertRaises(tkinter.TclError, self.combo.current, '')
-
-        # testing creating combobox with empty string in values
-        combo2 = ttk.Combobox(self.root, values=[1, 2, ''])
-        self.assertEqual(combo2['values'],
-                         ('1', '2', '') if self.wantobjects else '1 2 {}')
-        combo2.destroy()
-
-
-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
 class EntryTest(AbstractWidgetTest, unittest.TestCase):
     OPTIONS = (
         'background', 'class', 'cursor',
-        'exportselection', 'font',
+        'exportselection', 'font', 'foreground',
         'invalidcommand', 'justify',
         'show', 'state', 'style', 'takefocus', 'textvariable',
         'validate', 'validatecommand', 'width', 'xscrollcommand',
@@ -536,6 +411,131 @@ class EntryTest(AbstractWidgetTest, unittest.TestCase):
 
 
 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
+class ComboboxTest(EntryTest, unittest.TestCase):
+    OPTIONS = (
+        'background', 'class', 'cursor', 'exportselection',
+        'font', 'foreground', 'height', 'invalidcommand',
+        'justify', 'postcommand', 'show', 'state', 'style',
+        'takefocus', 'textvariable',
+        'validate', 'validatecommand', 'values',
+        'width', 'xscrollcommand',
+    )
+
+    def setUp(self):
+        super(ComboboxTest, self).setUp()
+        self.combo = self.create()
+
+    def create(self, **kwargs):
+        return ttk.Combobox(self.root, **kwargs)
+
+    def test_height(self):
+        widget = self.create()
+        self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i')
+
+    def _show_drop_down_listbox(self):
+        width = self.combo.winfo_width()
+        self.combo.event_generate('<ButtonPress-1>', x=width - 5, y=5)
+        self.combo.event_generate('<ButtonRelease-1>', x=width - 5, y=5)
+        self.combo.update_idletasks()
+
+
+    def test_virtual_event(self):
+        success = []
+
+        self.combo['values'] = [1]
+        self.combo.bind('<<ComboboxSelected>>',
+            lambda evt: success.append(True))
+        self.combo.pack()
+        self.combo.wait_visibility()
+
+        height = self.combo.winfo_height()
+        self._show_drop_down_listbox()
+        self.combo.update()
+        self.combo.event_generate('<Return>')
+        self.combo.update()
+
+        self.assertTrue(success)
+
+
+    def test_postcommand(self):
+        success = []
+
+        self.combo['postcommand'] = lambda: success.append(True)
+        self.combo.pack()
+        self.combo.wait_visibility()
+
+        self._show_drop_down_listbox()
+        self.assertTrue(success)
+
+        # testing postcommand removal
+        self.combo['postcommand'] = ''
+        self._show_drop_down_listbox()
+        self.assertEqual(len(success), 1)
+
+
+    def test_values(self):
+        def check_get_current(getval, currval):
+            self.assertEqual(self.combo.get(), getval)
+            self.assertEqual(self.combo.current(), currval)
+
+        self.assertEqual(self.combo['values'],
+                         () if tcl_version < (8, 5) else '')
+        check_get_current('', -1)
+
+        self.checkParam(self.combo, 'values', 'mon tue wed thur',
+                        expected=('mon', 'tue', 'wed', 'thur'))
+        self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur'))
+        self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string'))
+        self.checkParam(self.combo, 'values', () if tcl_version < (8, 5) else '')
+
+        self.combo['values'] = ['a', 1, 'c']
+
+        self.combo.set('c')
+        check_get_current('c', 2)
+
+        self.combo.current(0)
+        check_get_current('a', 0)
+
+        self.combo.set('d')
+        check_get_current('d', -1)
+
+        # testing values with empty string
+        self.combo.set('')
+        self.combo['values'] = (1, 2, '', 3)
+        check_get_current('', 2)
+
+        # testing values with empty string set through configure
+        self.combo.configure(values=[1, '', 2])
+        self.assertEqual(self.combo['values'],
+                         ('1', '', '2') if self.wantobjects else
+                         '1 {} 2')
+
+        # testing values with spaces
+        self.combo['values'] = ['a b', 'a\tb', 'a\nb']
+        self.assertEqual(self.combo['values'],
+                         ('a b', 'a\tb', 'a\nb') if self.wantobjects else
+                         '{a b} {a\tb} {a\nb}')
+
+        # testing values with special characters
+        self.combo['values'] = [r'a\tb', '"a"', '} {']
+        self.assertEqual(self.combo['values'],
+                         (r'a\tb', '"a"', '} {') if self.wantobjects else
+                         r'a\\tb {"a"} \}\ \{')
+
+        # out of range
+        self.assertRaises(tkinter.TclError, self.combo.current,
+            len(self.combo['values']))
+        # it expects an integer (or something that can be converted to int)
+        self.assertRaises(tkinter.TclError, self.combo.current, '')
+
+        # testing creating combobox with empty string in values
+        combo2 = ttk.Combobox(self.root, values=[1, 2, ''])
+        self.assertEqual(combo2['values'],
+                         ('1', '2', '') if self.wantobjects else '1 2 {}')
+        combo2.destroy()
+
+
+@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
 class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
     OPTIONS = (
         'class', 'cursor', 'height',
@@ -675,7 +675,7 @@ class RadiobuttonTest(AbstractLabelTest, unittest.TestCase):
     OPTIONS = (
         'class', 'command', 'compound', 'cursor',
         'image',
-        'state', 'style',
+        'padding', 'state', 'style',
         'takefocus', 'text', 'textvariable',
         'underline', 'value', 'variable', 'width',
     )
@@ -725,7 +725,7 @@ class RadiobuttonTest(AbstractLabelTest, unittest.TestCase):
 class MenubuttonTest(AbstractLabelTest, unittest.TestCase):
     OPTIONS = (
         'class', 'compound', 'cursor', 'direction',
-        'image', 'menu', 'state', 'style',
+        'image', 'menu', 'padding', 'state', 'style',
         'takefocus', 'text', 'textvariable',
         'underline', 'width',
     )
@@ -903,7 +903,7 @@ class ScrollbarTest(AbstractWidgetTest, unittest.TestCase):
 @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
 class NotebookTest(AbstractWidgetTest, unittest.TestCase):
     OPTIONS = (
-        'class', 'cursor', 'height', 'padding', 'style', 'takefocus',
+        'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width',
     )
 
     def setUp(self):
index 1b24324..33f716f 100644 (file)
@@ -224,6 +224,32 @@ class AbstractWidgetTest(AbstractTkTest):
                 self.fail('Invalid bounding box: %r' % (bbox,))
                 break
 
+    def test_keys(self):
+        widget = self.create()
+        keys = widget.keys()
+        # XXX
+        if not isinstance(widget, Scale):
+            self.assertEqual(sorted(keys), sorted(widget.configure()))
+        for k in keys:
+            widget[k]
+        # Test if OPTIONS contains all keys
+        if test.test_support.verbose:
+            aliases = {
+                'bd': 'borderwidth',
+                'bg': 'background',
+                'fg': 'foreground',
+                'invcmd': 'invalidcommand',
+                'vcmd': 'validatecommand',
+            }
+            keys = set(keys)
+            expected = set(self.OPTIONS)
+            for k in sorted(keys - expected):
+                if not (k in aliases and
+                        aliases[k] in keys and
+                        aliases[k] in expected):
+                    print('%s.OPTIONS doesn\'t contain "%s"' %
+                          (self.__class__.__name__, k))
+
 
 class StandardOptionsTests(object):
     STANDARD_OPTIONS = (
index 08cb040..f7d0433 100644 (file)
@@ -291,7 +291,7 @@ def _val_or_dict(tk, options, *args):
     """Format options then call Tk command with args and options and return
     the appropriate result.
 
-    If no option is specified, a dict is returned. If a option is
+    If no option is specified, a dict is returned. If an option is
     specified with the None value, the value for that option is returned.
     Otherwise, the function just sets the passed options and the caller
     shouldn't be expecting a return value anyway."""
@@ -1014,7 +1014,7 @@ class Progressbar(Widget):
         """Begin autoincrement mode: schedules a recurring timer event
         that calls method step every interval milliseconds.
 
-        interval defaults to 50 milliseconds (20 steps/second) if ommited."""
+        interval defaults to 50 milliseconds (20 steps/second) if omitted."""
         self.tk.call(self._w, "start", interval)
 
 
@@ -1476,7 +1476,7 @@ class LabeledScale(Frame, object):
     can be accessed through instance.label"""
 
     def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
-        """Construct an horizontal LabeledScale with parent master, a
+        """Construct a horizontal LabeledScale with parent master, a
         variable to be associated with the Ttk Scale widget and its range.
         If variable is not specified, a Tkinter.IntVar is created.
 
index 2276dc9..501f834 100644 (file)
@@ -216,7 +216,7 @@ def reduce_tree(node, parent=None):
                 #reduce to None
                 new_node = None
             elif repeater_node.children[0].value == '+':
-                #reduce to a single occurence i.e. do nothing
+                #reduce to a single occurrence i.e. do nothing
                 pass
             else:
                 #TODO: handle {min, max} repeaters
index f6421ba..d437b96 100644 (file)
@@ -50,7 +50,7 @@ class BaseFix(object):
         """Initializer.  Subclass may override.
 
         Args:
-            options: an dict containing the options passed to RefactoringTool
+            options: a dict containing the options passed to RefactoringTool
             that could be used to customize the fixer through the command line.
             log: a list to append warnings and other messages to.
         """
index 8399a13..45f9937 100644 (file)
@@ -25,7 +25,7 @@ from ..fixer_util import Name, syms, Node, Leaf
 
 def has_metaclass(parent):
     """ we have to check the cls_node without changing it.
-        There are two possiblities:
+        There are two possibilities:
           1)  clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
           2)  clsdef => simple_stmt => expr_stmt => Leaf('__meta')
     """
index 093e5f9..d31a9da 100644 (file)
@@ -3,7 +3,7 @@
 
 """Pattern compiler.
 
-The grammer is taken from PatternGrammar.txt.
+The grammar is taken from PatternGrammar.txt.
 
 The compiler compiles a pattern to a pytree.*Pattern instance.
 """
index d64a3e6..8cae873 100644 (file)
@@ -236,7 +236,7 @@ class Untokenizer:
                 startline = False
             toks_append(tokval)
 
-cookie_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)')
+cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)')
 blank_re = re.compile(r'^[ \t\f]*(?:[#\r\n]|$)')
 
 def _get_normal_name(orig_enc):
index bd23897..98386c5 100644 (file)
@@ -184,7 +184,7 @@ class RefactoringTool(object):
 
         Args:
             fixer_names: a list of fixers to import
-            options: an dict with configuration.
+            options: a dict with configuration.
             explicit: a list of fixers to run even if they are explicit.
         """
         self.fixers = fixer_names
index 15c53ba..5aab163 100644 (file)
@@ -1,14 +1,12 @@
-""" Locale support.
+"""Locale support module.
 
-    The module provides low-level access to the C lib's locale APIs
-    and adds high level number formatting APIs as well as a locale
-    aliasing engine to complement these.
-
-    The aliasing engine includes support for many commonly used locale
-    names and maps them to values suitable for passing to the C lib's
-    setlocale() function. It also includes default encodings for all
-    supported locale names.
+The module provides low-level access to the C lib's locale APIs and adds high
+level number formatting APIs as well as a locale aliasing engine to complement
+these.
 
+The aliasing engine includes support for many commonly used locale names and
+maps them to values suitable for passing to the C lib's setlocale() function. It
+also includes default encodings for all supported locale names.
 """
 
 import sys
@@ -18,6 +16,10 @@ import re
 import operator
 import functools
 
+# keep a copy of the builtin str type, because 'str' name is overridden
+# in globals by a function below
+_str = str
+
 try:
     _unicode = unicode
 except NameError:
@@ -299,7 +301,7 @@ def currency(val, symbol=True, grouping=False, international=False):
     return s.replace('<', '').replace('>', '')
 
 def str(val):
-    """Convert float to integer, taking the locale into account."""
+    """Convert float to string, taking the locale into account."""
     return format("%.12g", val)
 
 def atof(string, func=float):
@@ -573,7 +575,7 @@ def setlocale(category, locale=None):
         category may be given as one of the LC_* values.
 
     """
-    if locale and type(locale) is not type(""):
+    if locale and not isinstance(locale, (_str, _unicode)):
         # convert to string
         locale = normalize(_build_localename(locale))
     return _setlocale(category, locale)
@@ -1833,7 +1835,7 @@ windows_locale = {
     0x1809: "en_IE", # English - Ireland
     0x1c09: "en_ZA", # English - South Africa
     0x2009: "en_JA", # English - Jamaica
-    0x2409: "en_CB", # English - Carribbean
+    0x2409: "en_CB", # English - Caribbean
     0x2809: "en_BZ", # English - Belize
     0x2c09: "en_TT", # English - Trinidad
     0x3009: "en_ZW", # English - Zimbabwe
index fa9ebe8..caf151d 100644 (file)
@@ -465,7 +465,15 @@ class Formatter(object):
         record.message = record.getMessage()
         if self.usesTime():
             record.asctime = self.formatTime(record, self.datefmt)
-        s = self._fmt % record.__dict__
+        try:
+            s = self._fmt % record.__dict__
+        except UnicodeDecodeError as e:
+            # Issue 25664. The logger name may be Unicode. Try again ...
+            try:
+                record.name = record.name.decode('utf-8')
+                s = self._fmt % record.__dict__
+            except UnicodeDecodeError:
+                raise e
         if record.exc_info:
             # Cache the traceback text to avoid converting it multiple times
             # (it's constant anyway)
index 3866953..b1e5faa 100644 (file)
@@ -1774,7 +1774,7 @@ class BabylMessage(Message):
     """Message with Babyl-specific properties."""
 
     def __init__(self, message=None):
-        """Initialize an BabylMessage instance."""
+        """Initialize a BabylMessage instance."""
         self._labels = []
         self._visible = Message()
         Message.__init__(self, message)
index a39b543..157d455 100644 (file)
@@ -382,6 +382,7 @@ def _default_mime_types():
     global common_types
 
     suffix_map = {
+        '.svgz': '.svg.gz',
         '.tgz': '.tar.gz',
         '.taz': '.tar.gz',
         '.tz': '.tar.gz',
@@ -420,6 +421,7 @@ def _default_mime_types():
         '.cpio'   : 'application/x-cpio',
         '.csh'    : 'application/x-csh',
         '.css'    : 'text/css',
+        '.csv'    : 'text/csv',
         '.dll'    : 'application/octet-stream',
         '.doc'    : 'application/msword',
         '.dot'    : 'application/msword',
@@ -499,6 +501,7 @@ def _default_mime_types():
         '.src'    : 'application/x-wais-source',
         '.sv4cpio': 'application/x-sv4cpio',
         '.sv4crc' : 'application/x-sv4crc',
+        '.svg'    : 'image/svg+xml',
         '.swf'    : 'application/x-shockwave-flash',
         '.t'      : 'application/x-troff',
         '.tar'    : 'application/x-tar',
@@ -514,6 +517,7 @@ def _default_mime_types():
         '.ustar'  : 'application/x-ustar',
         '.vcf'    : 'text/x-vcard',
         '.wav'    : 'audio/x-wav',
+        '.webm'   : 'video/webm',
         '.wiz'    : 'application/msword',
         '.wsdl'   : 'application/xml',
         '.xbm'    : 'image/x-xbitmap',
index f16b2c7..e2fee41 100644 (file)
@@ -1,5 +1,4 @@
 """Find modules used by a script, using introspection."""
-# This module should be kept compatible with Python 2.2, see PEP 291.
 
 from __future__ import generators
 import dis
@@ -13,15 +12,35 @@ import struct
 if hasattr(sys.__stdout__, "newlines"):
     READ_MODE = "U"  # universal line endings
 else:
-    # remain compatible with Python  < 2.3
+    # Python < 2.3 compatibility, no longer strictly required
     READ_MODE = "r"
 
-LOAD_CONST = chr(dis.opname.index('LOAD_CONST'))
-IMPORT_NAME = chr(dis.opname.index('IMPORT_NAME'))
-STORE_NAME = chr(dis.opname.index('STORE_NAME'))
-STORE_GLOBAL = chr(dis.opname.index('STORE_GLOBAL'))
-STORE_OPS = [STORE_NAME, STORE_GLOBAL]
-HAVE_ARGUMENT = chr(dis.HAVE_ARGUMENT)
+LOAD_CONST = dis.opmap['LOAD_CONST']
+IMPORT_NAME = dis.opmap['IMPORT_NAME']
+STORE_NAME = dis.opmap['STORE_NAME']
+STORE_GLOBAL = dis.opmap['STORE_GLOBAL']
+STORE_OPS = STORE_NAME, STORE_GLOBAL
+HAVE_ARGUMENT = dis.HAVE_ARGUMENT
+EXTENDED_ARG = dis.EXTENDED_ARG
+
+def _unpack_opargs(code):
+    # enumerate() is not an option, since we sometimes process
+    # multiple elements on a single pass through the loop
+    extended_arg = 0
+    n = len(code)
+    i = 0
+    while i < n:
+        op = ord(code[i])
+        offset = i
+        i = i+1
+        arg = None
+        if op >= HAVE_ARGUMENT:
+            arg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
+            extended_arg = 0
+            i = i+2
+            if op == EXTENDED_ARG:
+                extended_arg = arg*65536
+        yield (offset, op, arg)
 
 # Modulefinder does a good job at simulating Python's, but it can not
 # handle __path__ modifications packages make at runtime.  Therefore there
@@ -344,53 +363,40 @@ class ModuleFinder:
         code = co.co_code
         names = co.co_names
         consts = co.co_consts
-        while code:
-            c = code[0]
+        opargs = [(op, arg) for _, op, arg in _unpack_opargs(code)
+                  if op != EXTENDED_ARG]
+        for i, (op, oparg) in enumerate(opargs):
             if c in STORE_OPS:
-                oparg, = unpack('<H', code[1:3])
                 yield "store", (names[oparg],)
-                code = code[3:]
                 continue
-            if c == LOAD_CONST and code[3] == IMPORT_NAME:
-                oparg_1, oparg_2 = unpack('<xHxH', code[:6])
-                yield "import", (consts[oparg_1], names[oparg_2])
-                code = code[6:]
+            if (op == IMPORT_NAME and i >= 1
+                    and opargs[i-1][0] == LOAD_CONST):
+                fromlist = consts[opargs[i-1][1]]
+                yield "import", (fromlist, names[oparg])
                 continue
-            if c >= HAVE_ARGUMENT:
-                code = code[3:]
-            else:
-                code = code[1:]
 
-    def scan_opcodes_25(self, co,
-                     unpack = struct.unpack):
+    def scan_opcodes_25(self, co):
         # Scan the code, and yield 'interesting' opcode combinations
-        # Python 2.5 version (has absolute and relative imports)
         code = co.co_code
         names = co.co_names
         consts = co.co_consts
-        LOAD_LOAD_AND_IMPORT = LOAD_CONST + LOAD_CONST + IMPORT_NAME
-        while code:
-            c = code[0]
-            if c in STORE_OPS:
-                oparg, = unpack('<H', code[1:3])
+        opargs = [(op, arg) for _, op, arg in _unpack_opargs(code)
+                  if op != EXTENDED_ARG]
+        for i, (op, oparg) in enumerate(opargs):
+            if op in STORE_OPS:
                 yield "store", (names[oparg],)
-                code = code[3:]
                 continue
-            if code[:9:3] == LOAD_LOAD_AND_IMPORT:
-                oparg_1, oparg_2, oparg_3 = unpack('<xHxHxH', code[:9])
-                level = consts[oparg_1]
+            if (op == IMPORT_NAME and i >= 2
+                    and opargs[i-1][0] == opargs[i-2][0] == LOAD_CONST):
+                level = consts[opargs[i-2][1]]
+                fromlist = consts[opargs[i-1][1]]
                 if level == -1: # normal import
-                    yield "import", (consts[oparg_2], names[oparg_3])
+                    yield "import", (fromlist, names[oparg])
                 elif level == 0: # absolute import
-                    yield "absolute_import", (consts[oparg_2], names[oparg_3])
+                    yield "absolute_import", (fromlist, names[oparg])
                 else: # relative import
-                    yield "relative_import", (level, consts[oparg_2], names[oparg_3])
-                code = code[9:]
+                    yield "relative_import", (level, fromlist, names[oparg])
                 continue
-            if c >= HAVE_ARGUMENT:
-                code = code[3:]
-            else:
-                code = code[1:]
 
     def scan_code(self, co, m):
         code = co.co_code
index 907a739..0352b60 100644 (file)
@@ -2,7 +2,11 @@
 # Copyright (C) 2005 Martin v. Löwis
 # Licensed to PSF under a Contributor Agreement.
 from _msi import *
-import os, string, re, sys
+import glob
+import os
+import re
+import string
+import sys
 
 AMD64 = "AMD64" in sys.version
 Itanium = "Itanium" in sys.version
index 003f040..b84eb22 100644 (file)
@@ -731,7 +731,7 @@ _Validation_records = [
 (u'CustomAction',u'Type',u'N',1,16383,None, None, None, None, u'The numeric custom action type, consisting of source location, code type, entry, option flags.',),
 (u'CustomAction',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Primary key, name of action, normally appears in sequence table unless private use.',),
 (u'CustomAction',u'Source',u'Y',None, None, None, None, u'CustomSource',None, u'The table reference of the source of the code.',),
-(u'CustomAction',u'Target',u'Y',None, None, None, None, u'Formatted',None, u'Excecution parameter, depends on the type of custom action',),
+(u'CustomAction',u'Target',u'Y',None, None, None, None, u'Formatted',None, u'Execution parameter, depends on the type of custom action',),
 (u'DrLocator',u'Signature_',u'N',None, None, None, None, u'Identifier',None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature table.',),
 (u'DrLocator',u'Path',u'Y',None, None, None, None, u'AnyPath',None, u'The path on the user system. This is a either a subpath below the value of the Parent or a full path. The path may contain properties enclosed within [ ] that will be expanded.',),
 (u'DrLocator',u'Depth',u'Y',0,32767,None, None, None, None, u'The depth below the path to which the Signature_ is recursively searched. If absent, the depth is assumed to be 0.',),
index 08d35d8..7763965 100644 (file)
@@ -884,7 +884,7 @@ def RebuildProxy(func, token, serializer, kwds):
 
 def MakeProxyType(name, exposed, _cache={}):
     '''
-    Return an proxy type whose methods are given by `exposed`
+    Return a proxy type whose methods are given by `exposed`
     '''
     exposed = tuple(exposed)
     try:
index f8acba4..3d8f428 100644 (file)
@@ -9,7 +9,7 @@ the first queue entry is removed and its function(argument) pair called,
 implying it now has the lock.
 
 Of course, no multi-threading is implied -- hence the funny interface
-for lock, where a function is called once the lock is aquired.
+for lock, where a function is called once the lock is acquired.
 """
 from warnings import warnpy3k
 warnpy3k("the mutex module has been removed in Python 3.0", stacklevel=2)
index 58951b9..0b85b0b 100644 (file)
@@ -141,7 +141,7 @@ def splitunc(p):
     Return a 2-tuple (unc, rest); either part may be empty.
     If unc is not empty, it has the form '//host/mount' (or similar
     using backslashes).  unc+rest is always the input path.
-    Paths containing drive letters never have an UNC part.
+    Paths containing drive letters never have a UNC part.
     """
     if p[1:2] == ':':
         return '', p # Drive letter present
@@ -227,7 +227,7 @@ def islink(path):
 lexists = exists
 
 # Is a path a mount point?  Either a root (with or without drive letter)
-# or an UNC path with at most a / or \ after the mount point.
+# or a UNC path with at most a / or \ after the mount point.
 
 def ismount(path):
     """Test whether a path is a mount point (defined as root of drive)"""
index 433276d..bec492d 100644 (file)
@@ -914,7 +914,7 @@ class OptionContainer:
       _short_opt : { string : Option }
         dictionary mapping short option strings, eg. "-f" or "-X",
         to the Option instances that implement them.  If an Option
-        has multiple short option strings, it will appears in this
+        has multiple short option strings, it will appear in this
         dictionary multiple times. [1]
       _long_opt : { string : Option }
         dictionary mapping long option strings, eg. "--file" or
@@ -1375,7 +1375,7 @@ class OptionParser (OptionContainer):
         sys.argv[1:]).  Any errors result in a call to 'error()', which
         by default prints the usage message to stderr and calls
         sys.exit() with an error message.  On success returns a pair
-        (values, args) where 'values' is an Values instance (with all
+        (values, args) where 'values' is a Values instance (with all
         your option values) and 'args' is the list of arguments left
         over after parsing options.
         """
index 0b32d63..6691b7d 100644 (file)
@@ -62,7 +62,7 @@ def splitunc(p):
     Return a 2-tuple (unc, rest); either part may be empty.
     If unc is not empty, it has the form '//host/mount' (or similar
     using backslashes).  unc+rest is always the input path.
-    Paths containing drive letters never have an UNC part.
+    Paths containing drive letters never have a UNC part.
     """
     if p[1:2] == ':':
         return '', p # Drive letter present
@@ -105,7 +105,7 @@ lexists = exists
 # Is a path a directory?
 
 # Is a path a mount point?  Either a root (with or without drive letter)
-# or an UNC path with at most a / or \ after the mount point.
+# or a UNC path with at most a / or \ after the mount point.
 
 def ismount(path):
     """Test whether a path is a mount point (defined as root of drive)"""
index 375be2f..c8c1c93 100644 (file)
@@ -48,7 +48,7 @@ If a file ".pdbrc" exists in your home directory or in the current
 directory, it is read in and executed as if it had been typed at the
 debugger prompt.  This is particularly useful for aliases.  If both
 files exist, the one in the home directory is read first and aliases
-defined there can be overriden by the local file.
+defined there can be overridden by the local file.
 
 Aside from aliases, the debugger is not directly programmable; but it
 is implemented as a class from which you can derive your own debugger
index 13c926f..f06e7f8 100644 (file)
@@ -329,7 +329,7 @@ def _parse_object(file):
 #################################################################
 
 #
-# External - Create a form an link to an instance variable.
+# External - Create a form and link to an instance variable.
 #
 def create_full_form(inst, (fdata, odatalist)):
     form = create_form(fdata)
index 32e8b9d..14231cb 100644 (file)
@@ -328,7 +328,7 @@ def _parse_object(file):
 #################################################################
 
 #
-# External - Create a form an link to an instance variable.
+# External - Create a form and link to an instance variable.
 #
 def create_full_form(inst, (fdata, odatalist)):
     form = create_form(fdata)
index 38f4159..2f535d2 100644 (file)
@@ -34,7 +34,7 @@ TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon"
 # Creator for C files:
 CREATOR="CWIE"
 
-# The previous definitions can be overriden by creating a module
+# The previous definitions can be overridden by creating a module
 # bgenlocationscustomize.py and putting it in site-packages (or anywere else
 # on sys.path, actually)
 try:
index ddbe1ba..0afdc04 100644 (file)
@@ -102,7 +102,7 @@ class _Prop_version(aetools.NProperty):
 files = file
 
 class internet_location_file(aetools.ComponentItem):
-    """internet location file - An file containing an internet location """
+    """internet location file - A file containing an internet location """
     want = 'inlf'
 class _Prop_location(aetools.NProperty):
     """location - the internet location """
index 9dcb85f..ff7be3c 100644 (file)
@@ -58,7 +58,7 @@ class _Prop_application_file(aetools.NProperty):
 application_processes = application_process
 
 class desk_accessory_process(aetools.ComponentItem):
-    """desk accessory process - A process launched from an desk accessory file """
+    """desk accessory process - A process launched from a desk accessory file """
     want = 'pcda'
 class _Prop_desk_accessory_file(aetools.NProperty):
     """desk accessory file - a reference to the desk accessory file from which this process was launched """
index 3dbdfe0..63455ce 100755 (executable)
@@ -650,7 +650,7 @@ def win32_ver(release='', version='', csd='', ptype=''):
                 csd = 'SP' + csd[13:]
 
     # VER_NT_SERVER = 3
-    if getattr(winver, 'product_type', None) == 3:
+    if getattr(winver, 'product', None) == 3:
         release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
                    _WIN32_SERVER_RELEASES.get((maj, None)) or
                    release)
@@ -1314,9 +1314,11 @@ def processor():
 ### Various APIs for extracting information from sys.version
 
 _sys_version_parser = re.compile(
-    r'([\w.+]+)\s*'
-    '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
-    '\[([^\]]+)\]?')
+    r'([\w.+]+)\s*'  # "version<space>"
+    r'\(#?([^,]+)'  # "(#buildno"
+    r'(?:,\s*([\w ]*)'  # ", builddate"
+    r'(?:,\s*([\w :]*))?)?\)\s*'  # ", buildtime)<space>"
+    r'\[([^\]]+)\]?')  # "[compiler]"
 
 _ironpython_sys_version_parser = re.compile(
     r'IronPython\s*'
@@ -1395,6 +1397,8 @@ def _sys_version(sys_version=None):
                 'failed to parse Jython sys.version: %s' %
                 repr(sys_version))
         version, buildno, builddate, buildtime, _ = match.groups()
+        if builddate is None:
+            builddate = ''
         compiler = sys.platform
 
     elif "PyPy" in sys_version:
@@ -1417,7 +1421,10 @@ def _sys_version(sys_version=None):
         version, buildno, builddate, buildtime, compiler = \
               match.groups()
         name = 'CPython'
-        builddate = builddate + ' ' + buildtime
+        if builddate is None:
+            builddate = ''
+        elif buildtime:
+            builddate = builddate + ' ' + buildtime
 
     if hasattr(sys, 'subversion'):
         # sys.subversion was added in Python 2.5
index 6578481..8f92822 100644 (file)
@@ -375,7 +375,7 @@ symbolic links encountered in the path."""
     path, ok = _joinrealpath('', filename, {})
     return abspath(path)
 
-# Join two paths, normalizing ang eliminating any symbolic links
+# Join two paths, normalizing and eliminating any symbolic links
 # encountered in the second path.
 def _joinrealpath(path, rest, seen):
     if isabs(rest):
index 4338994..3908f47 100644 (file)
@@ -60,7 +60,7 @@ class Stats:
     """
 
     def __init__(self, *args, **kwds):
-        # I can't figure out how to explictly specify a stream keyword arg
+        # I can't figure out how to explicitly specify a stream keyword arg
         # with *args:
         #   def __init__(self, *args, stream=sys.stdout): ...
         # so I use **kwds and sqauwk if something unexpected is passed in.
index 5790624..272f514 100644 (file)
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-# Autogenerated by Sphinx on Sat Nov 21 13:35:13 2015
+# Autogenerated by Sphinx on Sat Jun 11 14:41:12 2016
 topics = {'assert': '\n'
            'The "assert" statement\n'
            '**********************\n'
@@ -13,29 +13,27 @@ topics = {'assert': '\n'
            'The simple form, "assert expression", is equivalent to\n'
            '\n'
            '   if __debug__:\n'
-           '      if not expression: raise AssertionError\n'
+           '       if not expression: raise AssertionError\n'
            '\n'
            'The extended form, "assert expression1, expression2", is '
            'equivalent to\n'
            '\n'
            '   if __debug__:\n'
-           '      if not expression1: raise AssertionError(expression2)\n'
+           '       if not expression1: raise AssertionError(expression2)\n'
            '\n'
            'These equivalences assume that "__debug__" and "AssertionError" '
            'refer\n'
            'to the built-in variables with those names.  In the current\n'
-           'implementation, the built-in variable "__debug__" is "True" '
-           'under\n'
+           'implementation, the built-in variable "__debug__" is "True" under\n'
            'normal circumstances, "False" when optimization is requested '
            '(command\n'
-           'line option -O).  The current code generator emits no code for '
-           'an\n'
-           'assert statement when optimization is requested at compile '
-           'time.  Note\n'
+           'line option -O).  The current code generator emits no code for an\n'
+           'assert statement when optimization is requested at compile time.  '
+           'Note\n'
            'that it is unnecessary to include the source code for the '
            'expression\n'
-           'that failed in the error message; it will be displayed as part '
-           'of the\n'
+           'that failed in the error message; it will be displayed as part of '
+           'the\n'
            'stack trace.\n'
            '\n'
            'Assignments to "__debug__" are illegal.  The value for the '
@@ -45,8 +43,8 @@ topics = {'assert': '\n'
                'Assignment statements\n'
                '*********************\n'
                '\n'
-               'Assignment statements are used to (re)bind names to values '
-               'and to\n'
+               'Assignment statements are used to (re)bind names to values and '
+               'to\n'
                'modify attributes or items of mutable objects:\n'
                '\n'
                '   assignment_stmt ::= (target_list "=")+ (expression_list | '
@@ -54,37 +52,35 @@ topics = {'assert': '\n'
                '   target_list     ::= target ("," target)* [","]\n'
                '   target          ::= identifier\n'
                '              | "(" target_list ")"\n'
-               '              | "[" target_list "]"\n'
+               '              | "[" [target_list] "]"\n'
                '              | attributeref\n'
                '              | subscription\n'
                '              | slicing\n'
                '\n'
-               '(See section Primaries for the syntax definitions for the '
-               'last three\n'
+               '(See section Primaries for the syntax definitions for the last '
+               'three\n'
                'symbols.)\n'
                '\n'
                'An assignment statement evaluates the expression list '
                '(remember that\n'
-               'this can be a single expression or a comma-separated list, '
-               'the latter\n'
+               'this can be a single expression or a comma-separated list, the '
+               'latter\n'
                'yielding a tuple) and assigns the single resulting object to '
                'each of\n'
                'the target lists, from left to right.\n'
                '\n'
-               'Assignment is defined recursively depending on the form of '
-               'the target\n'
+               'Assignment is defined recursively depending on the form of the '
+               'target\n'
                '(list). When a target is part of a mutable object (an '
                'attribute\n'
-               'reference, subscription or slicing), the mutable object '
-               'must\n'
+               'reference, subscription or slicing), the mutable object must\n'
                'ultimately perform the assignment and decide about its '
                'validity, and\n'
-               'may raise an exception if the assignment is unacceptable.  '
-               'The rules\n'
-               'observed by various types and the exceptions raised are '
-               'given with the\n'
-               'definition of the object types (see section The standard '
-               'type\n'
+               'may raise an exception if the assignment is unacceptable.  The '
+               'rules\n'
+               'observed by various types and the exceptions raised are given '
+               'with the\n'
+               'definition of the object types (see section The standard type\n'
                'hierarchy).\n'
                '\n'
                'Assignment of an object to a target list is recursively '
@@ -97,10 +93,10 @@ topics = {'assert': '\n'
                '\n'
                '* If the target list is a comma-separated list of targets: '
                'The\n'
-               '  object must be an iterable with the same number of items '
-               'as there\n'
-               '  are targets in the target list, and the items are '
-               'assigned, from\n'
+               '  object must be an iterable with the same number of items as '
+               'there\n'
+               '  are targets in the target list, and the items are assigned, '
+               'from\n'
                '  left to right, to the corresponding targets.\n'
                '\n'
                'Assignment of an object to a single target is recursively '
@@ -109,20 +105,19 @@ topics = {'assert': '\n'
                '\n'
                '* If the target is an identifier (name):\n'
                '\n'
-               '  * If the name does not occur in a "global" statement in '
-               'the\n'
-               '    current code block: the name is bound to the object in '
-               'the current\n'
+               '  * If the name does not occur in a "global" statement in the\n'
+               '    current code block: the name is bound to the object in the '
+               'current\n'
                '    local namespace.\n'
                '\n'
-               '  * Otherwise: the name is bound to the object in the '
-               'current global\n'
+               '  * Otherwise: the name is bound to the object in the current '
+               'global\n'
                '    namespace.\n'
                '\n'
-               '  The name is rebound if it was already bound.  This may '
-               'cause the\n'
-               '  reference count for the object previously bound to the '
-               'name to reach\n'
+               '  The name is rebound if it was already bound.  This may cause '
+               'the\n'
+               '  reference count for the object previously bound to the name '
+               'to reach\n'
                '  zero, causing the object to be deallocated and its '
                'destructor (if it\n'
                '  has one) to be called.\n'
@@ -133,19 +128,17 @@ topics = {'assert': '\n'
                'same number\n'
                '  of items as there are targets in the target list, and its '
                'items are\n'
-               '  assigned, from left to right, to the corresponding '
-               'targets.\n'
+               '  assigned, from left to right, to the corresponding targets.\n'
                '\n'
                '* If the target is an attribute reference: The primary '
                'expression in\n'
-               '  the reference is evaluated.  It should yield an object '
-               'with\n'
-               '  assignable attributes; if this is not the case, '
-               '"TypeError" is\n'
+               '  the reference is evaluated.  It should yield an object with\n'
+               '  assignable attributes; if this is not the case, "TypeError" '
+               'is\n'
                '  raised.  That object is then asked to assign the assigned '
                'object to\n'
-               '  the given attribute; if it cannot perform the assignment, '
-               'it raises\n'
+               '  the given attribute; if it cannot perform the assignment, it '
+               'raises\n'
                '  an exception (usually but not necessarily '
                '"AttributeError").\n'
                '\n'
@@ -169,8 +162,8 @@ topics = {'assert': '\n'
                '     class Cls:\n'
                '         x = 3             # class variable\n'
                '     inst = Cls()\n'
-               '     inst.x = inst.x + 1   # writes inst.x as 4 leaving '
-               'Cls.x as 3\n'
+               '     inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x '
+               'as 3\n'
                '\n'
                '  This description does not necessarily apply to descriptor\n'
                '  attributes, such as properties created with "property()".\n'
@@ -191,8 +184,8 @@ topics = {'assert': '\n'
                'be a\n'
                "  nonnegative integer less than the sequence's length, and "
                'the\n'
-               '  sequence is asked to assign the assigned object to its '
-               'item with\n'
+               '  sequence is asked to assign the assigned object to its item '
+               'with\n'
                '  that index.  If the index is out of range, "IndexError" is '
                'raised\n'
                '  (assignment to a subscripted sequence cannot add new items '
@@ -201,55 +194,55 @@ topics = {'assert': '\n'
                '\n'
                '  If the primary is a mapping object (such as a dictionary), '
                'the\n'
-               "  subscript must have a type compatible with the mapping's "
-               'key type,\n'
+               "  subscript must have a type compatible with the mapping's key "
+               'type,\n'
                '  and the mapping is then asked to create a key/datum pair '
                'which maps\n'
                '  the subscript to the assigned object.  This can either '
                'replace an\n'
-               '  existing key/value pair with the same key value, or insert '
-               'new\n'
+               '  existing key/value pair with the same key value, or insert '
+               'new\n'
                '  key/value pair (if no key with the same value existed).\n'
                '\n'
                '* If the target is a slicing: The primary expression in the\n'
-               '  reference is evaluated.  It should yield a mutable '
-               'sequence object\n'
-               '  (such as a list).  The assigned object should be a '
-               'sequence object\n'
+               '  reference is evaluated.  It should yield a mutable sequence '
+               'object\n'
+               '  (such as a list).  The assigned object should be a sequence '
+               'object\n'
                '  of the same type.  Next, the lower and upper bound '
                'expressions are\n'
                '  evaluated, insofar they are present; defaults are zero and '
                'the\n'
                "  sequence's length.  The bounds should evaluate to (small) "
                'integers.\n'
-               "  If either bound is negative, the sequence's length is "
-               'added to it.\n'
+               "  If either bound is negative, the sequence's length is added "
+               'to it.\n'
                '  The resulting bounds are clipped to lie between zero and '
                'the\n'
-               "  sequence's length, inclusive.  Finally, the sequence "
-               'object is asked\n'
+               "  sequence's length, inclusive.  Finally, the sequence object "
+               'is asked\n'
                '  to replace the slice with the items of the assigned '
                'sequence.  The\n'
-               '  length of the slice may be different from the length of '
-               'the assigned\n'
+               '  length of the slice may be different from the length of the '
+               'assigned\n'
                '  sequence, thus changing the length of the target sequence, '
                'if the\n'
                '  object allows it.\n'
                '\n'
                '**CPython implementation detail:** In the current '
                'implementation, the\n'
-               'syntax for targets is taken to be the same as for '
-               'expressions, and\n'
+               'syntax for targets is taken to be the same as for expressions, '
+               'and\n'
                'invalid syntax is rejected during the code generation phase, '
                'causing\n'
                'less detailed error messages.\n'
                '\n'
                'WARNING: Although the definition of assignment implies that '
                'overlaps\n'
-               'between the left-hand side and the right-hand side are '
-               "'safe' (for\n"
-               'example "a, b = b, a" swaps two variables), overlaps '
-               '*within* the\n'
+               "between the left-hand side and the right-hand side are 'safe' "
+               '(for\n'
+               'example "a, b = b, a" swaps two variables), overlaps *within* '
+               'the\n'
                'collection of assigned-to variables are not safe!  For '
                'instance, the\n'
                'following program prints "[0, 2]":\n'
@@ -275,8 +268,8 @@ topics = {'assert': '\n'
                '"//=" | "%=" | "**="\n'
                '             | ">>=" | "<<=" | "&=" | "^=" | "|="\n'
                '\n'
-               '(See section Primaries for the syntax definitions for the '
-               'last three\n'
+               '(See section Primaries for the syntax definitions for the last '
+               'three\n'
                'symbols.)\n'
                '\n'
                'An augmented assignment evaluates the target (which, unlike '
@@ -301,16 +294,15 @@ topics = {'assert': '\n'
                'old object\n'
                'is modified instead.\n'
                '\n'
-               'With the exception of assigning to tuples and multiple '
-               'targets in a\n'
-               'single statement, the assignment done by augmented '
-               'assignment\n'
+               'With the exception of assigning to tuples and multiple targets '
+               'in a\n'
+               'single statement, the assignment done by augmented assignment\n'
                'statements is handled the same way as normal assignments. '
                'Similarly,\n'
                'with the exception of the possible *in-place* behavior, the '
                'binary\n'
-               'operation performed by augmented assignment is the same as '
-               'the normal\n'
+               'operation performed by augmented assignment is the same as the '
+               'normal\n'
                'binary operations.\n'
                '\n'
                'For targets which are attribute references, the same caveat '
@@ -339,24 +331,24 @@ topics = {'assert': '\n'
                      'characters and\n'
                      'does not end in two or more underscores, it is '
                      'considered a *private\n'
-                     'name* of that class. Private names are transformed to '
-                     'longer form\n'
+                     'name* of that class. Private names are transformed to '
+                     'longer form\n'
                      'before code is generated for them.  The transformation '
                      'inserts the\n'
                      'class name, with leading underscores removed and a '
                      'single underscore\n'
                      'inserted, in front of the name.  For example, the '
                      'identifier "__spam"\n'
-                     'occurring in a class named "Ham" will be transformed '
-                     'to "_Ham__spam".\n'
+                     'occurring in a class named "Ham" will be transformed to '
+                     '"_Ham__spam".\n'
                      'This transformation is independent of the syntactical '
                      'context in which\n'
                      'the identifier is used.  If the transformed name is '
                      'extremely long\n'
                      '(longer than 255 characters), implementation defined '
                      'truncation may\n'
-                     'happen. If the class name consists only of '
-                     'underscores, no\n'
+                     'happen. If the class name consists only of underscores, '
+                     'no\n'
                      'transformation is done.\n',
  'atom-literals': '\n'
                   'Literals\n'
@@ -368,18 +360,18 @@ topics = {'assert': '\n'
                   '   literal ::= stringliteral | integer | longinteger\n'
                   '               | floatnumber | imagnumber\n'
                   '\n'
-                  'Evaluation of a literal yields an object of the given '
-                  'type (string,\n'
+                  'Evaluation of a literal yields an object of the given type '
+                  '(string,\n'
                   'integer, long integer, floating point number, complex '
                   'number) with the\n'
-                  'given value.  The value may be approximated in the case '
-                  'of floating\n'
+                  'given value.  The value may be approximated in the case of '
+                  'floating\n'
                   'point and imaginary (complex) literals.  See section '
                   'Literals for\n'
                   'details.\n'
                   '\n'
-                  'All literals correspond to immutable data types, and '
-                  'hence the\n'
+                  'All literals correspond to immutable data types, and hence '
+                  'the\n'
                   "object's identity is less important than its value.  "
                   'Multiple\n'
                   'evaluations of literals with the same value (either the '
@@ -394,8 +386,8 @@ topics = {'assert': '\n'
                      '\n'
                      'The following methods can be defined to customize the '
                      'meaning of\n'
-                     'attribute access (use of, assignment to, or deletion '
-                     'of "x.name") for\n'
+                     'attribute access (use of, assignment to, or deletion of '
+                     '"x.name") for\n'
                      'class instances.\n'
                      '\n'
                      'object.__getattr__(self, name)\n'
@@ -414,8 +406,8 @@ topics = {'assert': '\n'
                      'normal mechanism,\n'
                      '   "__getattr__()" is not called.  (This is an '
                      'intentional asymmetry\n'
-                     '   between "__getattr__()" and "__setattr__()".) This '
-                     'is done both for\n'
+                     '   between "__getattr__()" and "__setattr__()".) This is '
+                     'done both for\n'
                      '   efficiency reasons and because otherwise '
                      '"__getattr__()" would have\n'
                      '   no way to access other attributes of the instance.  '
@@ -424,8 +416,7 @@ topics = {'assert': '\n'
                      'control by not\n'
                      '   inserting any values in the instance attribute '
                      'dictionary (but\n'
-                     '   instead inserting them in another object).  See '
-                     'the\n'
+                     '   instead inserting them in another object).  See the\n'
                      '   "__getattribute__()" method below for a way to '
                      'actually get total\n'
                      '   control in new-style classes.\n'
@@ -434,10 +425,10 @@ topics = {'assert': '\n'
                      '\n'
                      '   Called when an attribute assignment is attempted.  '
                      'This is called\n'
-                     '   instead of the normal mechanism (i.e. store the '
-                     'value in the\n'
-                     '   instance dictionary).  *name* is the attribute '
-                     'name, *value* is the\n'
+                     '   instead of the normal mechanism (i.e. store the value '
+                     'in the\n'
+                     '   instance dictionary).  *name* is the attribute name, '
+                     '*value* is the\n'
                      '   value to be assigned to it.\n'
                      '\n'
                      '   If "__setattr__()" wants to assign to an instance '
@@ -448,10 +439,10 @@ topics = {'assert': '\n'
                      'insert the value in\n'
                      '   the dictionary of instance attributes, e.g., '
                      '"self.__dict__[name] =\n'
-                     '   value".  For new-style classes, rather than '
-                     'accessing the instance\n'
-                     '   dictionary, it should call the base class method '
-                     'with the same\n'
+                     '   value".  For new-style classes, rather than accessing '
+                     'the instance\n'
+                     '   dictionary, it should call the base class method with '
+                     'the same\n'
                      '   name, for example, "object.__setattr__(self, name, '
                      'value)".\n'
                      '\n'
@@ -459,16 +450,15 @@ topics = {'assert': '\n'
                      '\n'
                      '   Like "__setattr__()" but for attribute deletion '
                      'instead of\n'
-                     '   assignment.  This should only be implemented if '
-                     '"del obj.name" is\n'
+                     '   assignment.  This should only be implemented if "del '
+                     'obj.name" is\n'
                      '   meaningful for the object.\n'
                      '\n'
                      '\n'
                      'More attribute access for new-style classes\n'
                      '===========================================\n'
                      '\n'
-                     'The following methods only apply to new-style '
-                     'classes.\n'
+                     'The following methods only apply to new-style classes.\n'
                      '\n'
                      'object.__getattribute__(self, name)\n'
                      '\n'
@@ -480,18 +470,18 @@ topics = {'assert': '\n'
                      '"__getattribute__()" either\n'
                      '   calls it explicitly or raises an "AttributeError". '
                      'This method\n'
-                     '   should return the (computed) attribute value or '
-                     'raise an\n'
+                     '   should return the (computed) attribute value or raise '
+                     'an\n'
                      '   "AttributeError" exception. In order to avoid '
                      'infinite recursion in\n'
                      '   this method, its implementation should always call '
                      'the base class\n'
-                     '   method with the same name to access any attributes '
-                     'it needs, for\n'
+                     '   method with the same name to access any attributes it '
+                     'needs, for\n'
                      '   example, "object.__getattribute__(self, name)".\n'
                      '\n'
-                     '   Note: This method may still be bypassed when '
-                     'looking up special\n'
+                     '   Note: This method may still be bypassed when looking '
+                     'up special\n'
                      '     methods as the result of implicit invocation via '
                      'language syntax\n'
                      '     or built-in functions. See Special method lookup '
@@ -502,39 +492,39 @@ topics = {'assert': '\n'
                      'Implementing Descriptors\n'
                      '========================\n'
                      '\n'
-                     'The following methods only apply when an instance of '
-                     'the class\n'
+                     'The following methods only apply when an instance of the '
+                     'class\n'
                      'containing the method (a so-called *descriptor* class) '
                      'appears in an\n'
                      '*owner* class (the descriptor must be in either the '
                      "owner's class\n"
                      'dictionary or in the class dictionary for one of its '
                      'parents).  In the\n'
-                     'examples below, "the attribute" refers to the '
-                     'attribute whose name is\n'
+                     'examples below, "the attribute" refers to the attribute '
+                     'whose name is\n'
                      "the key of the property in the owner class' "
                      '"__dict__".\n'
                      '\n'
                      'object.__get__(self, instance, owner)\n'
                      '\n'
-                     '   Called to get the attribute of the owner class '
-                     '(class attribute\n'
+                     '   Called to get the attribute of the owner class (class '
+                     'attribute\n'
                      '   access) or of an instance of that class (instance '
                      'attribute\n'
                      '   access). *owner* is always the owner class, while '
                      '*instance* is the\n'
-                     '   instance that the attribute was accessed through, '
-                     'or "None" when\n'
-                     '   the attribute is accessed through the *owner*.  '
-                     'This method should\n'
+                     '   instance that the attribute was accessed through, or '
+                     '"None" when\n'
+                     '   the attribute is accessed through the *owner*.  This '
+                     'method should\n'
                      '   return the (computed) attribute value or raise an '
                      '"AttributeError"\n'
                      '   exception.\n'
                      '\n'
                      'object.__set__(self, instance, value)\n'
                      '\n'
-                     '   Called to set the attribute on an instance '
-                     '*instance* of the owner\n'
+                     '   Called to set the attribute on an instance *instance* '
+                     'of the owner\n'
                      '   class to a new value, *value*.\n'
                      '\n'
                      'object.__delete__(self, instance)\n'
@@ -553,14 +543,14 @@ topics = {'assert': '\n'
                      'overridden by methods\n'
                      'in the descriptor protocol:  "__get__()", "__set__()", '
                      'and\n'
-                     '"__delete__()". If any of those methods are defined '
-                     'for an object, it\n'
+                     '"__delete__()". If any of those methods are defined for '
+                     'an object, it\n'
                      'is said to be a descriptor.\n'
                      '\n'
                      'The default behavior for attribute access is to get, '
                      'set, or delete\n'
-                     "the attribute from an object's dictionary. For "
-                     'instance, "a.x" has a\n'
+                     "the attribute from an object's dictionary. For instance, "
+                     '"a.x" has a\n'
                      'lookup chain starting with "a.__dict__[\'x\']", then\n'
                      '"type(a).__dict__[\'x\']", and continuing through the '
                      'base classes of\n'
@@ -568,24 +558,24 @@ topics = {'assert': '\n'
                      '\n'
                      'However, if the looked-up value is an object defining '
                      'one of the\n'
-                     'descriptor methods, then Python may override the '
-                     'default behavior and\n'
-                     'invoke the descriptor method instead.  Where this '
-                     'occurs in the\n'
+                     'descriptor methods, then Python may override the default '
+                     'behavior and\n'
+                     'invoke the descriptor method instead.  Where this occurs '
+                     'in the\n'
                      'precedence chain depends on which descriptor methods '
                      'were defined and\n'
                      'how they were called.  Note that descriptors are only '
                      'invoked for new\n'
-                     'style objects or classes (ones that subclass '
-                     '"object()" or "type()").\n'
+                     'style objects or classes (ones that subclass "object()" '
+                     'or "type()").\n'
                      '\n'
                      'The starting point for descriptor invocation is a '
                      'binding, "a.x". How\n'
                      'the arguments are assembled depends on "a":\n'
                      '\n'
                      'Direct Call\n'
-                     '   The simplest and least common call is when user '
-                     'code directly\n'
+                     '   The simplest and least common call is when user code '
+                     'directly\n'
                      '   invokes a descriptor method:    "x.__get__(a)".\n'
                      '\n'
                      'Instance Binding\n'
@@ -595,8 +585,8 @@ topics = {'assert': '\n'
                      'type(a))".\n'
                      '\n'
                      'Class Binding\n'
-                     '   If binding to a new-style class, "A.x" is '
-                     'transformed into the\n'
+                     '   If binding to a new-style class, "A.x" is transformed '
+                     'into the\n'
                      '   call: "A.__dict__[\'x\'].__get__(None, A)".\n'
                      '\n'
                      'Super Binding\n'
@@ -617,16 +607,16 @@ topics = {'assert': '\n'
                      '"__delete__()".  If it\n'
                      'does not define "__get__()", then accessing the '
                      'attribute will return\n'
-                     'the descriptor object itself unless there is a value '
-                     "in the object's\n"
+                     'the descriptor object itself unless there is a value in '
+                     "the object's\n"
                      'instance dictionary.  If the descriptor defines '
                      '"__set__()" and/or\n'
                      '"__delete__()", it is a data descriptor; if it defines '
                      'neither, it is\n'
                      'a non-data descriptor.  Normally, data descriptors '
                      'define both\n'
-                     '"__get__()" and "__set__()", while non-data '
-                     'descriptors have just the\n'
+                     '"__get__()" and "__set__()", while non-data descriptors '
+                     'have just the\n'
                      '"__get__()" method.  Data descriptors with "__set__()" '
                      'and "__get__()"\n'
                      'defined always override a redefinition in an instance '
@@ -645,37 +635,37 @@ topics = {'assert': '\n'
                      '\n'
                      'The "property()" function is implemented as a data '
                      'descriptor.\n'
-                     'Accordingly, instances cannot override the behavior of '
-                     'property.\n'
+                     'Accordingly, instances cannot override the behavior of '
+                     'property.\n'
                      '\n'
                      '\n'
                      '__slots__\n'
                      '=========\n'
                      '\n'
-                     'By default, instances of both old and new-style '
-                     'classes have a\n'
-                     'dictionary for attribute storage.  This wastes space '
-                     'for objects\n'
+                     'By default, instances of both old and new-style classes '
+                     'have a\n'
+                     'dictionary for attribute storage.  This wastes space for '
+                     'objects\n'
                      'having very few instance variables.  The space '
                      'consumption can become\n'
                      'acute when creating large numbers of instances.\n'
                      '\n'
-                     'The default can be overridden by defining *__slots__* '
-                     'in a new-style\n'
+                     'The default can be overridden by defining *__slots__* in '
+                     'a new-style\n'
                      'class definition.  The *__slots__* declaration takes a '
                      'sequence of\n'
                      'instance variables and reserves just enough space in '
                      'each instance to\n'
-                     'hold a value for each variable.  Space is saved '
-                     'because *__dict__* is\n'
+                     'hold a value for each variable.  Space is saved because '
+                     '*__dict__* is\n'
                      'not created for each instance.\n'
                      '\n'
                      '__slots__\n'
                      '\n'
                      '   This class variable can be assigned a string, '
                      'iterable, or sequence\n'
-                     '   of strings with variable names used by instances.  '
-                     'If defined in a\n'
+                     '   of strings with variable names used by instances.  If '
+                     'defined in a\n'
                      '   new-style class, *__slots__* reserves space for the '
                      'declared\n'
                      '   variables and prevents the automatic creation of '
@@ -686,10 +676,10 @@ topics = {'assert': '\n'
                      '\n'
                      'Notes on using *__slots__*\n'
                      '\n'
-                     '* When inheriting from a class without *__slots__*, '
-                     'the *__dict__*\n'
-                     '  attribute of that class will always be accessible, '
-                     'so a *__slots__*\n'
+                     '* When inheriting from a class without *__slots__*, the '
+                     '*__dict__*\n'
+                     '  attribute of that class will always be accessible, so '
+                     'a *__slots__*\n'
                      '  definition in the subclass is meaningless.\n'
                      '\n'
                      '* Without a *__dict__* variable, instances cannot be '
@@ -708,14 +698,14 @@ topics = {'assert': '\n'
                      '"\'__dict__\'" to the\n'
                      '  *__slots__* declaration would not enable the '
                      'assignment of new\n'
-                     '  attributes not specifically listed in the sequence '
-                     'of instance\n'
+                     '  attributes not specifically listed in the sequence of '
+                     'instance\n'
                      '  variable names.\n'
                      '\n'
                      '* Without a *__weakref__* variable for each instance, '
                      'classes\n'
-                     '  defining *__slots__* do not support weak references '
-                     'to its\n'
+                     '  defining *__slots__* do not support weak references to '
+                     'its\n'
                      '  instances. If weak reference support is needed, then '
                      'add\n'
                      '  "\'__weakref__\'" to the sequence of strings in the '
@@ -732,15 +722,14 @@ topics = {'assert': '\n'
                      'creating\n'
                      '  descriptors (Implementing Descriptors) for each '
                      'variable name.  As a\n'
-                     '  result, class attributes cannot be used to set '
-                     'default values for\n'
-                     '  instance variables defined by *__slots__*; '
-                     'otherwise, the class\n'
-                     '  attribute would overwrite the descriptor '
-                     'assignment.\n'
+                     '  result, class attributes cannot be used to set default '
+                     'values for\n'
+                     '  instance variables defined by *__slots__*; otherwise, '
+                     'the class\n'
+                     '  attribute would overwrite the descriptor assignment.\n'
                      '\n'
-                     '* The action of a *__slots__* declaration is limited '
-                     'to the class\n'
+                     '* The action of a *__slots__* declaration is limited to '
+                     'the class\n'
                      '  where it is defined.  As a result, subclasses will '
                      'have a *__dict__*\n'
                      '  unless they also define *__slots__* (which must only '
@@ -751,16 +740,16 @@ topics = {'assert': '\n'
                      'class, the\n'
                      '  instance variable defined by the base class slot is '
                      'inaccessible\n'
-                     '  (except by retrieving its descriptor directly from '
-                     'the base class).\n'
-                     '  This renders the meaning of the program undefined.  '
-                     'In the future, a\n'
+                     '  (except by retrieving its descriptor directly from the '
+                     'base class).\n'
+                     '  This renders the meaning of the program undefined.  In '
+                     'the future, a\n'
                      '  check may be added to prevent this.\n'
                      '\n'
-                     '* Nonempty *__slots__* does not work for classes '
-                     'derived from\n'
-                     '  "variable-length" built-in types such as "long", '
-                     '"str" and "tuple".\n'
+                     '* Nonempty *__slots__* does not work for classes derived '
+                     'from\n'
+                     '  "variable-length" built-in types such as "long", "str" '
+                     'and "tuple".\n'
                      '\n'
                      '* Any non-string iterable may be assigned to '
                      '*__slots__*. Mappings\n'
@@ -768,8 +757,8 @@ topics = {'assert': '\n'
                      'meaning may be\n'
                      '  assigned to the values corresponding to each key.\n'
                      '\n'
-                     '* *__class__* assignment works only if both classes '
-                     'have the same\n'
+                     '* *__class__* assignment works only if both classes have '
+                     'the same\n'
                      '  *__slots__*.\n'
                      '\n'
                      '  Changed in version 2.6: Previously, *__class__* '
@@ -788,12 +777,12 @@ topics = {'assert': '\n'
                          'that supports\n'
                          'attribute references, e.g., a module, list, or an '
                          'instance.  This\n'
-                         'object is then asked to produce the attribute '
-                         'whose name is the\n'
-                         'identifier.  If this attribute is not available, '
-                         'the exception\n'
-                         '"AttributeError" is raised. Otherwise, the type '
-                         'and value of the\n'
+                         'object is then asked to produce the attribute whose '
+                         'name is the\n'
+                         'identifier.  If this attribute is not available, the '
+                         'exception\n'
+                         '"AttributeError" is raised. Otherwise, the type and '
+                         'value of the\n'
                          'object produced is determined by the object.  '
                          'Multiple evaluations of\n'
                          'the same attribute reference may yield different '
@@ -802,8 +791,8 @@ topics = {'assert': '\n'
               'Augmented assignment statements\n'
               '*******************************\n'
               '\n'
-              'Augmented assignment is the combination, in a single '
-              'statement, of a\n'
+              'Augmented assignment is the combination, in a single statement, '
+              'of a\n'
               'binary operation and an assignment statement:\n'
               '\n'
               '   augmented_assignment_stmt ::= augtarget augop '
@@ -814,8 +803,8 @@ topics = {'assert': '\n'
               '"//=" | "%=" | "**="\n'
               '             | ">>=" | "<<=" | "&=" | "^=" | "|="\n'
               '\n'
-              '(See section Primaries for the syntax definitions for the '
-              'last three\n'
+              '(See section Primaries for the syntax definitions for the last '
+              'three\n'
               'symbols.)\n'
               '\n'
               'An augmented assignment evaluates the target (which, unlike '
@@ -830,26 +819,25 @@ topics = {'assert': '\n'
               '\n'
               'An augmented assignment expression like "x += 1" can be '
               'rewritten as\n'
-              '"x = x + 1" to achieve a similar, but not exactly equal '
-              'effect. In the\n'
+              '"x = x + 1" to achieve a similar, but not exactly equal effect. '
+              'In the\n'
               'augmented version, "x" is only evaluated once. Also, when '
               'possible,\n'
               'the actual operation is performed *in-place*, meaning that '
               'rather than\n'
-              'creating a new object and assigning that to the target, the '
-              'old object\n'
+              'creating a new object and assigning that to the target, the old '
+              'object\n'
               'is modified instead.\n'
               '\n'
-              'With the exception of assigning to tuples and multiple '
-              'targets in a\n'
-              'single statement, the assignment done by augmented '
-              'assignment\n'
+              'With the exception of assigning to tuples and multiple targets '
+              'in a\n'
+              'single statement, the assignment done by augmented assignment\n'
               'statements is handled the same way as normal assignments. '
               'Similarly,\n'
               'with the exception of the possible *in-place* behavior, the '
               'binary\n'
-              'operation performed by augmented assignment is the same as '
-              'the normal\n'
+              'operation performed by augmented assignment is the same as the '
+              'normal\n'
               'binary operations.\n'
               '\n'
               'For targets which are attribute references, the same caveat '
@@ -861,10 +849,9 @@ topics = {'assert': '\n'
            '****************************\n'
            '\n'
            'The binary arithmetic operations have the conventional priority\n'
-           'levels.  Note that some of these operations also apply to '
-           'certain non-\n'
-           'numeric types.  Apart from the power operator, there are only '
-           'two\n'
+           'levels.  Note that some of these operations also apply to certain '
+           'non-\n'
+           'numeric types.  Apart from the power operator, there are only two\n'
            'levels, one for multiplicative operators and one for additive\n'
            'operators:\n'
            '\n'
@@ -875,26 +862,20 @@ topics = {'assert': '\n'
            '\n'
            'The "*" (multiplication) operator yields the product of its '
            'arguments.\n'
-           'The arguments must either both be numbers, or one argument must '
-           'be an\n'
-           'integer (plain or long) and the other must be a sequence. In '
-           'the\n'
-           'former case, the numbers are converted to a common type and '
-           'then\n'
-           'multiplied together.  In the latter case, sequence repetition '
-           'is\n'
-           'performed; a negative repetition factor yields an empty '
-           'sequence.\n'
+           'The arguments must either both be numbers, or one argument must be '
+           'an\n'
+           'integer (plain or long) and the other must be a sequence. In the\n'
+           'former case, the numbers are converted to a common type and then\n'
+           'multiplied together.  In the latter case, sequence repetition is\n'
+           'performed; a negative repetition factor yields an empty sequence.\n'
            '\n'
-           'The "/" (division) and "//" (floor division) operators yield '
-           'the\n'
+           'The "/" (division) and "//" (floor division) operators yield the\n'
            'quotient of their arguments.  The numeric arguments are first\n'
-           'converted to a common type. Plain or long integer division '
-           'yields an\n'
+           'converted to a common type. Plain or long integer division yields '
+           'an\n'
            'integer of the same type; the result is that of mathematical '
            'division\n'
-           "with the 'floor' function applied to the result. Division by "
-           'zero\n'
+           "with the 'floor' function applied to the result. Division by zero\n"
            'raises the "ZeroDivisionError" exception.\n'
            '\n'
            'The "%" (modulo) operator yields the remainder from the division '
@@ -906,23 +887,20 @@ topics = {'assert': '\n'
            'point\n'
            'numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals '
            '"4*0.7 +\n'
-           '0.34".)  The modulo operator always yields a result with the '
-           'same sign\n'
-           'as its second operand (or zero); the absolute value of the '
-           'result is\n'
+           '0.34".)  The modulo operator always yields a result with the same '
+           'sign\n'
+           'as its second operand (or zero); the absolute value of the result '
+           'is\n'
            'strictly smaller than the absolute value of the second operand '
            '[2].\n'
            '\n'
            'The integer division and modulo operators are connected by the\n'
-           'following identity: "x == (x/y)*y + (x%y)".  Integer division '
-           'and\n'
-           'modulo are also connected with the built-in function '
-           '"divmod()":\n'
+           'following identity: "x == (x/y)*y + (x%y)".  Integer division and\n'
+           'modulo are also connected with the built-in function "divmod()":\n'
            '"divmod(x, y) == (x/y, x%y)".  These identities don\'t hold for\n'
            'floating point numbers; there similar identities hold '
            'approximately\n'
-           'where "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" '
-           '[3].\n'
+           'where "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" [3].\n'
            '\n'
            'In addition to performing the modulo operation on numbers, the '
            '"%"\n'
@@ -930,8 +908,7 @@ topics = {'assert': '\n'
            'perform\n'
            'string formatting (also known as interpolation). The syntax for '
            'string\n'
-           'formatting is described in the Python Library Reference, '
-           'section\n'
+           'formatting is described in the Python Library Reference, section\n'
            'String Formatting Operations.\n'
            '\n'
            'Deprecated since version 2.3: The floor division operator, the '
@@ -941,8 +918,7 @@ topics = {'assert': '\n'
            'using\n'
            'the "abs()" function if appropriate.\n'
            '\n'
-           'The "+" (addition) operator yields the sum of its arguments. '
-           'The\n'
+           'The "+" (addition) operator yields the sum of its arguments. The\n'
            'arguments must either both be numbers or both sequences of the '
            'same\n'
            'type.  In the former case, the numbers are converted to a common '
@@ -997,10 +973,10 @@ topics = {'assert': '\n'
                        'through their "func_code" attribute. See also the '
                        '"code" module.\n'
                        '\n'
-                       'A code object can be executed or evaluated by '
-                       'passing it (instead of a\n'
-                       'source string) to the "exec" statement or the '
-                       'built-in "eval()"\n'
+                       'A code object can be executed or evaluated by passing '
+                       'it (instead of a\n'
+                       'source string) to the "exec" statement or the built-in '
+                       '"eval()"\n'
                        'function.\n'
                        '\n'
                        'See The standard type hierarchy for more '
@@ -1009,15 +985,437 @@ topics = {'assert': '\n'
                           'The Ellipsis Object\n'
                           '*******************\n'
                           '\n'
-                          'This object is used by extended slice notation '
-                          '(see Slicings).  It\n'
+                          'This object is used by extended slice notation (see '
+                          'Slicings).  It\n'
                           'supports no special operations.  There is exactly '
                           'one ellipsis object,\n'
                           'named "Ellipsis" (a built-in name).\n'
                           '\n'
-                          'It is written as "Ellipsis".  When in a '
-                          'subscript, it can also be\n'
+                          'It is written as "Ellipsis".  When in a subscript, '
+                          'it can also be\n'
                           'written as "...", for example "seq[...]".\n',
+ 'bltin-file-objects': '\n'
+                       'File Objects\n'
+                       '************\n'
+                       '\n'
+                       'File objects are implemented using C\'s "stdio" '
+                       'package and can be\n'
+                       'created with the built-in "open()" function.  File '
+                       'objects are also\n'
+                       'returned by some other built-in functions and methods, '
+                       'such as\n'
+                       '"os.popen()" and "os.fdopen()" and the "makefile()" '
+                       'method of socket\n'
+                       'objects. Temporary files can be created using the '
+                       '"tempfile" module,\n'
+                       'and high-level file operations such as copying, '
+                       'moving, and deleting\n'
+                       'files and directories can be achieved with the '
+                       '"shutil" module.\n'
+                       '\n'
+                       'When a file operation fails for an I/O-related reason, '
+                       'the exception\n'
+                       '"IOError" is raised.  This includes situations where '
+                       'the operation is\n'
+                       'not defined for some reason, like "seek()" on a tty '
+                       'device or writing\n'
+                       'a file opened for reading.\n'
+                       '\n'
+                       'Files have the following methods:\n'
+                       '\n'
+                       'file.close()\n'
+                       '\n'
+                       '   Close the file.  A closed file cannot be read or '
+                       'written any more.\n'
+                       '   Any operation which requires that the file be open '
+                       'will raise a\n'
+                       '   "ValueError" after the file has been closed.  '
+                       'Calling "close()"\n'
+                       '   more than once is allowed.\n'
+                       '\n'
+                       '   As of Python 2.5, you can avoid having to call this '
+                       'method\n'
+                       '   explicitly if you use the "with" statement.  For '
+                       'example, the\n'
+                       '   following code will automatically close *f* when '
+                       'the "with" block\n'
+                       '   is exited:\n'
+                       '\n'
+                       '      from __future__ import with_statement # This '
+                       "isn't required in Python 2.6\n"
+                       '\n'
+                       '      with open("hello.txt") as f:\n'
+                       '          for line in f:\n'
+                       '              print line,\n'
+                       '\n'
+                       '   In older versions of Python, you would have needed '
+                       'to do this to\n'
+                       '   get the same effect:\n'
+                       '\n'
+                       '      f = open("hello.txt")\n'
+                       '      try:\n'
+                       '          for line in f:\n'
+                       '              print line,\n'
+                       '      finally:\n'
+                       '          f.close()\n'
+                       '\n'
+                       '   Note: Not all "file-like" types in Python support '
+                       'use as a\n'
+                       '     context manager for the "with" statement.  If '
+                       'your code is\n'
+                       '     intended to work with any file-like object, you '
+                       'can use the\n'
+                       '     function "contextlib.closing()" instead of using '
+                       'the object\n'
+                       '     directly.\n'
+                       '\n'
+                       'file.flush()\n'
+                       '\n'
+                       '   Flush the internal buffer, like "stdio"\'s '
+                       '"fflush()".  This may be\n'
+                       '   a no-op on some file-like objects.\n'
+                       '\n'
+                       '   Note: "flush()" does not necessarily write the '
+                       "file's data to\n"
+                       '     disk. Use "flush()" followed by "os.fsync()" to '
+                       'ensure this\n'
+                       '     behavior.\n'
+                       '\n'
+                       'file.fileno()\n'
+                       '\n'
+                       '   Return the integer "file descriptor" that is used '
+                       'by the underlying\n'
+                       '   implementation to request I/O operations from the '
+                       'operating system.\n'
+                       '   This can be useful for other, lower level '
+                       'interfaces that use file\n'
+                       '   descriptors, such as the "fcntl" module or '
+                       '"os.read()" and friends.\n'
+                       '\n'
+                       '   Note: File-like objects which do not have a real '
+                       'file descriptor\n'
+                       '     should *not* provide this method!\n'
+                       '\n'
+                       'file.isatty()\n'
+                       '\n'
+                       '   Return "True" if the file is connected to a '
+                       'tty(-like) device, else\n'
+                       '   "False".\n'
+                       '\n'
+                       '   Note: If a file-like object is not associated with '
+                       'a real file,\n'
+                       '     this method should *not* be implemented.\n'
+                       '\n'
+                       'file.next()\n'
+                       '\n'
+                       '   A file object is its own iterator, for example '
+                       '"iter(f)" returns\n'
+                       '   *f* (unless *f* is closed).  When a file is used as '
+                       'an iterator,\n'
+                       '   typically in a "for" loop (for example, "for line '
+                       'in f: print\n'
+                       '   line.strip()"), the "next()" method is called '
+                       'repeatedly.  This\n'
+                       '   method returns the next input line, or raises '
+                       '"StopIteration" when\n'
+                       '   EOF is hit when the file is open for reading '
+                       '(behavior is undefined\n'
+                       '   when the file is open for writing).  In order to '
+                       'make a "for" loop\n'
+                       '   the most efficient way of looping over the lines of '
+                       'a file (a very\n'
+                       '   common operation), the "next()" method uses a '
+                       'hidden read-ahead\n'
+                       '   buffer.  As a consequence of using a read-ahead '
+                       'buffer, combining\n'
+                       '   "next()" with other file methods (like '
+                       '"readline()") does not work\n'
+                       '   right.  However, using "seek()" to reposition the '
+                       'file to an\n'
+                       '   absolute position will flush the read-ahead '
+                       'buffer.\n'
+                       '\n'
+                       '   New in version 2.3.\n'
+                       '\n'
+                       'file.read([size])\n'
+                       '\n'
+                       '   Read at most *size* bytes from the file (less if '
+                       'the read hits EOF\n'
+                       '   before obtaining *size* bytes).  If the *size* '
+                       'argument is negative\n'
+                       '   or omitted, read all data until EOF is reached.  '
+                       'The bytes are\n'
+                       '   returned as a string object.  An empty string is '
+                       'returned when EOF\n'
+                       '   is encountered immediately.  (For certain files, '
+                       'like ttys, it\n'
+                       '   makes sense to continue reading after an EOF is '
+                       'hit.)  Note that\n'
+                       '   this method may call the underlying C function '
+                       '"fread()" more than\n'
+                       '   once in an effort to acquire as close to *size* '
+                       'bytes as possible.\n'
+                       '   Also note that when in non-blocking mode, less data '
+                       'than was\n'
+                       '   requested may be returned, even if no *size* '
+                       'parameter was given.\n'
+                       '\n'
+                       '   Note: This function is simply a wrapper for the '
+                       'underlying\n'
+                       '     "fread()" C function, and will behave the same in '
+                       'corner cases,\n'
+                       '     such as whether the EOF value is cached.\n'
+                       '\n'
+                       'file.readline([size])\n'
+                       '\n'
+                       '   Read one entire line from the file.  A trailing '
+                       'newline character\n'
+                       '   is kept in the string (but may be absent when a '
+                       'file ends with an\n'
+                       '   incomplete line). [6] If the *size* argument is '
+                       'present and non-\n'
+                       '   negative, it is a maximum byte count (including the '
+                       'trailing\n'
+                       '   newline) and an incomplete line may be returned. '
+                       'When *size* is not\n'
+                       '   0, an empty string is returned *only* when EOF is '
+                       'encountered\n'
+                       '   immediately.\n'
+                       '\n'
+                       '   Note: Unlike "stdio"\'s "fgets()", the returned '
+                       'string contains\n'
+                       '     null characters ("\'\\0\'") if they occurred in '
+                       'the input.\n'
+                       '\n'
+                       'file.readlines([sizehint])\n'
+                       '\n'
+                       '   Read until EOF using "readline()" and return a list '
+                       'containing the\n'
+                       '   lines thus read.  If the optional *sizehint* '
+                       'argument is present,\n'
+                       '   instead of reading up to EOF, whole lines totalling '
+                       'approximately\n'
+                       '   *sizehint* bytes (possibly after rounding up to an '
+                       'internal buffer\n'
+                       '   size) are read.  Objects implementing a file-like '
+                       'interface may\n'
+                       '   choose to ignore *sizehint* if it cannot be '
+                       'implemented, or cannot\n'
+                       '   be implemented efficiently.\n'
+                       '\n'
+                       'file.xreadlines()\n'
+                       '\n'
+                       '   This method returns the same thing as "iter(f)".\n'
+                       '\n'
+                       '   New in version 2.1.\n'
+                       '\n'
+                       '   Deprecated since version 2.3: Use "for line in '
+                       'file" instead.\n'
+                       '\n'
+                       'file.seek(offset[, whence])\n'
+                       '\n'
+                       '   Set the file\'s current position, like "stdio"\'s '
+                       '"fseek()". The\n'
+                       '   *whence* argument is optional and defaults to  '
+                       '"os.SEEK_SET" or "0"\n'
+                       '   (absolute file positioning); other values are '
+                       '"os.SEEK_CUR" or "1"\n'
+                       '   (seek relative to the current position) and '
+                       '"os.SEEK_END" or "2"\n'
+                       "   (seek relative to the file's end).  There is no "
+                       'return value.\n'
+                       '\n'
+                       '   For example, "f.seek(2, os.SEEK_CUR)" advances the '
+                       'position by two\n'
+                       '   and "f.seek(-3, os.SEEK_END)" sets the position to '
+                       'the third to\n'
+                       '   last.\n'
+                       '\n'
+                       '   Note that if the file is opened for appending (mode '
+                       '"\'a\'" or\n'
+                       '   "\'a+\'"), any "seek()" operations will be undone '
+                       'at the next write.\n'
+                       '   If the file is only opened for writing in append '
+                       'mode (mode "\'a\'"),\n'
+                       '   this method is essentially a no-op, but it remains '
+                       'useful for files\n'
+                       '   opened in append mode with reading enabled (mode '
+                       '"\'a+\'").  If the\n'
+                       '   file is opened in text mode (without "\'b\'"), only '
+                       'offsets returned\n'
+                       '   by "tell()" are legal.  Use of other offsets causes '
+                       'undefined\n'
+                       '   behavior.\n'
+                       '\n'
+                       '   Note that not all file objects are seekable.\n'
+                       '\n'
+                       '   Changed in version 2.6: Passing float values as '
+                       'offset has been\n'
+                       '   deprecated.\n'
+                       '\n'
+                       'file.tell()\n'
+                       '\n'
+                       "   Return the file's current position, like "
+                       '"stdio"\'s "ftell()".\n'
+                       '\n'
+                       '   Note: On Windows, "tell()" can return illegal '
+                       'values (after an\n'
+                       '     "fgets()") when reading files with Unix-style '
+                       'line-endings. Use\n'
+                       '     binary mode ("\'rb\'") to circumvent this '
+                       'problem.\n'
+                       '\n'
+                       'file.truncate([size])\n'
+                       '\n'
+                       "   Truncate the file's size.  If the optional *size* "
+                       'argument is\n'
+                       '   present, the file is truncated to (at most) that '
+                       'size.  The size\n'
+                       '   defaults to the current position. The current file '
+                       'position is not\n'
+                       '   changed.  Note that if a specified size exceeds the '
+                       "file's current\n"
+                       '   size, the result is platform-dependent:  '
+                       'possibilities include that\n'
+                       '   the file may remain unchanged, increase to the '
+                       'specified size as if\n'
+                       '   zero-filled, or increase to the specified size with '
+                       'undefined new\n'
+                       '   content. Availability:  Windows, many Unix '
+                       'variants.\n'
+                       '\n'
+                       'file.write(str)\n'
+                       '\n'
+                       '   Write a string to the file.  There is no return '
+                       'value.  Due to\n'
+                       '   buffering, the string may not actually show up in '
+                       'the file until\n'
+                       '   the "flush()" or "close()" method is called.\n'
+                       '\n'
+                       'file.writelines(sequence)\n'
+                       '\n'
+                       '   Write a sequence of strings to the file.  The '
+                       'sequence can be any\n'
+                       '   iterable object producing strings, typically a list '
+                       'of strings.\n'
+                       '   There is no return value. (The name is intended to '
+                       'match\n'
+                       '   "readlines()"; "writelines()" does not add line '
+                       'separators.)\n'
+                       '\n'
+                       'Files support the iterator protocol.  Each iteration '
+                       'returns the same\n'
+                       'result as "readline()", and iteration ends when the '
+                       '"readline()"\n'
+                       'method returns an empty string.\n'
+                       '\n'
+                       'File objects also offer a number of other interesting '
+                       'attributes.\n'
+                       'These are not required for file-like objects, but '
+                       'should be\n'
+                       'implemented if they make sense for the particular '
+                       'object.\n'
+                       '\n'
+                       'file.closed\n'
+                       '\n'
+                       '   bool indicating the current state of the file '
+                       'object.  This is a\n'
+                       '   read-only attribute; the "close()" method changes '
+                       'the value. It may\n'
+                       '   not be available on all file-like objects.\n'
+                       '\n'
+                       'file.encoding\n'
+                       '\n'
+                       '   The encoding that this file uses. When Unicode '
+                       'strings are written\n'
+                       '   to a file, they will be converted to byte strings '
+                       'using this\n'
+                       '   encoding. In addition, when the file is connected '
+                       'to a terminal,\n'
+                       '   the attribute gives the encoding that the terminal '
+                       'is likely to use\n'
+                       '   (that  information might be incorrect if the user '
+                       'has misconfigured\n'
+                       '   the  terminal). The attribute is read-only and may '
+                       'not be present\n'
+                       '   on all file-like objects. It may also be "None", in '
+                       'which case the\n'
+                       '   file uses the system default encoding for '
+                       'converting Unicode\n'
+                       '   strings.\n'
+                       '\n'
+                       '   New in version 2.3.\n'
+                       '\n'
+                       'file.errors\n'
+                       '\n'
+                       '   The Unicode error handler used along with the '
+                       'encoding.\n'
+                       '\n'
+                       '   New in version 2.6.\n'
+                       '\n'
+                       'file.mode\n'
+                       '\n'
+                       '   The I/O mode for the file.  If the file was created '
+                       'using the\n'
+                       '   "open()" built-in function, this will be the value '
+                       'of the *mode*\n'
+                       '   parameter.  This is a read-only attribute and may '
+                       'not be present on\n'
+                       '   all file-like objects.\n'
+                       '\n'
+                       'file.name\n'
+                       '\n'
+                       '   If the file object was created using "open()", the '
+                       'name of the\n'
+                       '   file. Otherwise, some string that indicates the '
+                       'source of the file\n'
+                       '   object, of the form "<...>".  This is a read-only '
+                       'attribute and may\n'
+                       '   not be present on all file-like objects.\n'
+                       '\n'
+                       'file.newlines\n'
+                       '\n'
+                       '   If Python was built with *universal newlines* '
+                       'enabled (the default)\n'
+                       '   this read-only attribute exists, and for files '
+                       'opened in universal\n'
+                       '   newline read mode it keeps track of the types of '
+                       'newlines\n'
+                       '   encountered while reading the file. The values it '
+                       'can take are\n'
+                       '   "\'\\r\'", "\'\\n\'", "\'\\r\\n\'", "None" '
+                       '(unknown, no newlines read yet) or\n'
+                       '   a tuple containing all the newline types seen, to '
+                       'indicate that\n'
+                       '   multiple newline conventions were encountered. For '
+                       'files not opened\n'
+                       '   in universal newlines read mode the value of this '
+                       'attribute will be\n'
+                       '   "None".\n'
+                       '\n'
+                       'file.softspace\n'
+                       '\n'
+                       '   Boolean that indicates whether a space character '
+                       'needs to be\n'
+                       '   printed before another value when using the "print" '
+                       'statement.\n'
+                       '   Classes that are trying to simulate a file object '
+                       'should also have\n'
+                       '   a writable "softspace" attribute, which should be '
+                       'initialized to\n'
+                       '   zero.  This will be automatic for most classes '
+                       'implemented in\n'
+                       '   Python (care may be needed for objects that '
+                       'override attribute\n'
+                       '   access); types implemented in C will have to '
+                       'provide a writable\n'
+                       '   "softspace" attribute.\n'
+                       '\n'
+                       '   Note: This attribute is not used to control the '
+                       '"print"\n'
+                       '     statement, but to allow the implementation of '
+                       '"print" to keep\n'
+                       '     track of its internal state.\n',
  'bltin-null-object': '\n'
                       'The Null Object\n'
                       '***************\n'
@@ -1035,8 +1433,8 @@ topics = {'assert': '\n'
                        '\n'
                        'Type objects represent the various object types.  An '
                        "object's type is\n"
-                       'accessed by the built-in function "type()".  There '
-                       'are no special\n'
+                       'accessed by the built-in function "type()".  There are '
+                       'no special\n'
                        'operations on types.  The standard module "types" '
                        'defines names for\n'
                        'all standard built-in types.\n'
@@ -1050,12 +1448,11 @@ topics = {'assert': '\n'
              '   and_test ::= not_test | and_test "and" not_test\n'
              '   not_test ::= comparison | "not" not_test\n'
              '\n'
-             'In the context of Boolean operations, and also when '
-             'expressions are\n'
+             'In the context of Boolean operations, and also when expressions '
+             'are\n'
              'used by control flow statements, the following values are '
              'interpreted\n'
-             'as false: "False", "None", numeric zero of all types, and '
-             'empty\n'
+             'as false: "False", "None", numeric zero of all types, and empty\n'
              'strings and containers (including strings, tuples, lists,\n'
              'dictionaries, sets and frozensets).  All other values are '
              'interpreted\n'
@@ -1069,14 +1466,14 @@ topics = {'assert': '\n'
              '\n'
              'The expression "x and y" first evaluates *x*; if *x* is false, '
              'its\n'
-             'value is returned; otherwise, *y* is evaluated and the '
-             'resulting value\n'
+             'value is returned; otherwise, *y* is evaluated and the resulting '
+             'value\n'
              'is returned.\n'
              '\n'
-             'The expression "x or y" first evaluates *x*; if *x* is true, '
-             'its value\n'
-             'is returned; otherwise, *y* is evaluated and the resulting '
-             'value is\n'
+             'The expression "x or y" first evaluates *x*; if *x* is true, its '
+             'value\n'
+             'is returned; otherwise, *y* is evaluated and the resulting value '
+             'is\n'
              'returned.\n'
              '\n'
              '(Note that neither "and" nor "or" restrict the value and type '
@@ -1099,18 +1496,15 @@ topics = {'assert': '\n'
           '\n'
           '   break_stmt ::= "break"\n'
           '\n'
-          '"break" may only occur syntactically nested in a "for" or '
-          '"while"\n'
-          'loop, but not nested in a function or class definition within '
-          'that\n'
+          '"break" may only occur syntactically nested in a "for" or "while"\n'
+          'loop, but not nested in a function or class definition within that\n'
           'loop.\n'
           '\n'
           'It terminates the nearest enclosing loop, skipping the optional '
           '"else"\n'
           'clause if the loop has one.\n'
           '\n'
-          'If a "for" loop is terminated by "break", the loop control '
-          'target\n'
+          'If a "for" loop is terminated by "break", the loop control target\n'
           'keeps its current value.\n'
           '\n'
           'When "break" passes control out of a "try" statement with a '
@@ -1124,8 +1518,8 @@ topics = {'assert': '\n'
                    '\n'
                    'object.__call__(self[, args...])\n'
                    '\n'
-                   '   Called when the instance is "called" as a function; '
-                   'if this method\n'
+                   '   Called when the instance is "called" as a function; if '
+                   'this method\n'
                    '   is defined, "x(arg1, arg2, ...)" is a shorthand for\n'
                    '   "x.__call__(arg1, arg2, ...)".\n',
  'calls': '\n'
@@ -1145,8 +1539,8 @@ topics = {'assert': '\n'
           '                       ["," "**" expression]\n'
           '                     | keyword_arguments ["," "*" expression]\n'
           '                       ["," "**" expression]\n'
-          '                     | "*" expression ["," keyword_arguments] '
-          '["," "**" expression]\n'
+          '                     | "*" expression ["," keyword_arguments] ["," '
+          '"**" expression]\n'
           '                     | "**" expression\n'
           '   positional_arguments ::= expression ("," expression)*\n'
           '   keyword_arguments    ::= keyword_item ("," keyword_item)*\n'
@@ -1156,11 +1550,9 @@ topics = {'assert': '\n'
           'arguments but does not affect the semantics.\n'
           '\n'
           'The primary must evaluate to a callable object (user-defined\n'
-          'functions, built-in functions, methods of built-in objects, '
-          'class\n'
+          'functions, built-in functions, methods of built-in objects, class\n'
           'objects, methods of class instances, and certain class instances\n'
-          'themselves are callable; extensions may define additional '
-          'callable\n'
+          'themselves are callable; extensions may define additional callable\n'
           'object types).  All argument expressions are evaluated before the '
           'call\n'
           'is attempted.  Please refer to section Function definitions for '
@@ -1168,8 +1560,8 @@ topics = {'assert': '\n'
           'syntax of formal *parameter* lists.\n'
           '\n'
           'If keyword arguments are present, they are first converted to\n'
-          'positional arguments, as follows.  First, a list of unfilled '
-          'slots is\n'
+          'positional arguments, as follows.  First, a list of unfilled slots '
+          'is\n'
           'created for the formal parameters.  If there are N positional\n'
           'arguments, they are placed in the first N slots.  Next, for each\n'
           'keyword argument, the identifier is used to determine the\n'
@@ -1177,24 +1569,21 @@ topics = {'assert': '\n'
           'formal\n'
           'parameter name, the first slot is used, and so on).  If the slot '
           'is\n'
-          'already filled, a "TypeError" exception is raised. Otherwise, '
-          'the\n'
+          'already filled, a "TypeError" exception is raised. Otherwise, the\n'
           'value of the argument is placed in the slot, filling it (even if '
           'the\n'
-          'expression is "None", it fills the slot).  When all arguments '
-          'have\n'
+          'expression is "None", it fills the slot).  When all arguments have\n'
           'been processed, the slots that are still unfilled are filled with '
           'the\n'
           'corresponding default value from the function definition.  '
           '(Default\n'
-          'values are calculated, once, when the function is defined; thus, '
-          'a\n'
+          'values are calculated, once, when the function is defined; thus, a\n'
           'mutable object such as a list or dictionary used as default value '
           'will\n'
           "be shared by all calls that don't specify an argument value for "
           'the\n'
-          'corresponding slot; this should usually be avoided.)  If there '
-          'are any\n'
+          'corresponding slot; this should usually be avoided.)  If there are '
+          'any\n'
           'unfilled slots for which no default value is specified, a '
           '"TypeError"\n'
           'exception is raised.  Otherwise, the list of filled slots is used '
@@ -1219,13 +1608,10 @@ topics = {'assert': '\n'
           'formal\n'
           'parameter receives a tuple containing the excess positional '
           'arguments\n'
-          '(or an empty tuple if there were no excess positional '
-          'arguments).\n'
+          '(or an empty tuple if there were no excess positional arguments).\n'
           '\n'
-          'If any keyword argument does not correspond to a formal '
-          'parameter\n'
-          'name, a "TypeError" exception is raised, unless a formal '
-          'parameter\n'
+          'If any keyword argument does not correspond to a formal parameter\n'
+          'name, a "TypeError" exception is raised, unless a formal parameter\n'
           'using the syntax "**identifier" is present; in this case, that '
           'formal\n'
           'parameter receives a dictionary containing the excess keyword\n'
@@ -1239,8 +1625,8 @@ topics = {'assert': '\n'
           'must evaluate to an iterable.  Elements from this iterable are '
           'treated\n'
           'as if they were additional positional arguments; if there are\n'
-          'positional arguments *x1*, ..., *xN*, and "expression" evaluates '
-          'to a\n'
+          'positional arguments *x1*, ..., *xN*, and "expression" evaluates to '
+          'a\n'
           'sequence *y1*, ..., *yM*, this is equivalent to a call with M+N\n'
           'positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n'
           '\n'
@@ -1248,12 +1634,11 @@ topics = {'assert': '\n'
           'may\n'
           'appear *after* some keyword arguments, it is processed *before* '
           'the\n'
-          'keyword arguments (and the "**expression" argument, if any -- '
-          'see\n'
+          'keyword arguments (and the "**expression" argument, if any -- see\n'
           'below).  So:\n'
           '\n'
           '   >>> def f(a, b):\n'
-          '   ...  print a, b\n'
+          '   ...     print a, b\n'
           '   ...\n'
           '   >>> f(b=1, *(2,))\n'
           '   2 1\n'
@@ -1271,32 +1656,25 @@ topics = {'assert': '\n'
           'arise.\n'
           '\n'
           'If the syntax "**expression" appears in the function call,\n'
-          '"expression" must evaluate to a mapping, the contents of which '
-          'are\n'
-          'treated as additional keyword arguments.  In the case of a '
-          'keyword\n'
-          'appearing in both "expression" and as an explicit keyword '
-          'argument, a\n'
+          '"expression" must evaluate to a mapping, the contents of which are\n'
+          'treated as additional keyword arguments.  In the case of a keyword\n'
+          'appearing in both "expression" and as an explicit keyword argument, '
+          'a\n'
           '"TypeError" exception is raised.\n'
           '\n'
-          'Formal parameters using the syntax "*identifier" or '
-          '"**identifier"\n'
-          'cannot be used as positional argument slots or as keyword '
-          'argument\n'
+          'Formal parameters using the syntax "*identifier" or "**identifier"\n'
+          'cannot be used as positional argument slots or as keyword argument\n'
           'names.  Formal parameters using the syntax "(sublist)" cannot be '
           'used\n'
-          'as keyword argument names; the outermost sublist corresponds to '
-          'a\n'
+          'as keyword argument names; the outermost sublist corresponds to a\n'
           'single unnamed argument slot, and the argument value is assigned '
           'to\n'
-          'the sublist using the usual tuple assignment rules after all '
-          'other\n'
+          'the sublist using the usual tuple assignment rules after all other\n'
           'parameter processing is done.\n'
           '\n'
-          'A call always returns some value, possibly "None", unless it '
-          'raises an\n'
-          'exception.  How this value is computed depends on the type of '
-          'the\n'
+          'A call always returns some value, possibly "None", unless it raises '
+          'an\n'
+          'exception.  How this value is computed depends on the type of the\n'
           'callable object.\n'
           '\n'
           'If it is---\n'
@@ -1307,14 +1685,13 @@ topics = {'assert': '\n'
           'the\n'
           '   formal parameters to the arguments; this is described in '
           'section\n'
-          '   Function definitions.  When the code block executes a '
-          '"return"\n'
+          '   Function definitions.  When the code block executes a "return"\n'
           '   statement, this specifies the return value of the function '
           'call.\n'
           '\n'
           'a built-in function or method:\n'
-          '   The result is up to the interpreter; see Built-in Functions '
-          'for the\n'
+          '   The result is up to the interpreter; see Built-in Functions for '
+          'the\n'
           '   descriptions of built-in functions and methods.\n'
           '\n'
           'a class object:\n'
@@ -1323,13 +1700,12 @@ topics = {'assert': '\n'
           'a class instance method:\n'
           '   The corresponding user-defined function is called, with an '
           'argument\n'
-          '   list that is one longer than the argument list of the call: '
-          'the\n'
+          '   list that is one longer than the argument list of the call: the\n'
           '   instance becomes the first argument.\n'
           '\n'
           'a class instance:\n'
-          '   The class must define a "__call__()" method; the effect is '
-          'then the\n'
+          '   The class must define a "__call__()" method; the effect is then '
+          'the\n'
           '   same as if that method was called.\n',
  'class': '\n'
           'Class definitions\n'
@@ -1343,8 +1719,8 @@ topics = {'assert': '\n'
           '   inheritance ::= "(" [expression_list] ")"\n'
           '   classname   ::= identifier\n'
           '\n'
-          'A class definition is an executable statement.  It first '
-          'evaluates the\n'
+          'A class definition is an executable statement.  It first evaluates '
+          'the\n'
           'inheritance list, if present.  Each item in the inheritance list\n'
           'should evaluate to a class object or class type which allows\n'
           "subclassing.  The class's suite is then executed in a new "
@@ -1354,8 +1730,8 @@ topics = {'assert': '\n'
           'namespace and the original global namespace. (Usually, the suite\n'
           "contains only function definitions.)  When the class's suite "
           'finishes\n'
-          'execution, its execution frame is discarded but its local '
-          'namespace is\n'
+          'execution, its execution frame is discarded but its local namespace '
+          'is\n'
           'saved. [4] A class object is then created using the inheritance '
           'list\n'
           'for the base classes and the saved local namespace for the '
@@ -1374,16 +1750,15 @@ topics = {'assert': '\n'
           'with\n'
           'the same name when accessed in this way. Class variables can be '
           'used\n'
-          'as defaults for instance variables, but using mutable values '
-          'there can\n'
+          'as defaults for instance variables, but using mutable values there '
+          'can\n'
           'lead to unexpected results.  For *new-style class*es, descriptors '
           'can\n'
-          'be used to create instance variables with different '
-          'implementation\n'
+          'be used to create instance variables with different implementation\n'
           'details.\n'
           '\n'
-          'Class definitions, like function definitions, may be wrapped by '
-          'one or\n'
+          'Class definitions, like function definitions, may be wrapped by one '
+          'or\n'
           'more *decorator* expressions.  The evaluation rules for the '
           'decorator\n'
           'expressions are the same as for functions.  The result must be a '
@@ -1404,8 +1779,7 @@ topics = {'assert': '\n'
           '    function body is transformed into the function\'s "__doc__"\n'
           "    attribute and therefore the function's *docstring*.\n"
           '\n'
-          '[4] A string literal appearing as the first statement in the '
-          'class\n'
+          '[4] A string literal appearing as the first statement in the class\n'
           '    body is transformed into the namespace\'s "__doc__" item and\n'
           "    therefore the class's *docstring*.\n",
  'comparisons': '\n'
@@ -1416,13 +1790,13 @@ topics = {'assert': '\n'
                 'priority,\n'
                 'which is lower than that of any arithmetic, shifting or '
                 'bitwise\n'
-                'operation.  Also unlike C, expressions like "a < b < c" '
-                'have the\n'
+                'operation.  Also unlike C, expressions like "a < b < c" have '
+                'the\n'
                 'interpretation that is conventional in mathematics:\n'
                 '\n'
                 '   comparison    ::= or_expr ( comp_operator or_expr )*\n'
-                '   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" '
-                '"!="\n'
+                '   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" '
+                '"!="\n'
                 '                     | "is" ["not"] | ["not"] "in"\n'
                 '\n'
                 'Comparisons yield boolean values: "True" or "False".\n'
@@ -1431,14 +1805,14 @@ topics = {'assert': '\n'
                 'is\n'
                 'equivalent to "x < y and y <= z", except that "y" is '
                 'evaluated only\n'
-                'once (but in both cases "z" is not evaluated at all when "x '
-                'y" is\n'
+                'once (but in both cases "z" is not evaluated at all when "x '
+                'y" is\n'
                 'found to be false).\n'
                 '\n'
-                'Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions '
-                'and *op1*,\n'
-                '*op2*, ..., *opN* are comparison operators, then "a op1 b '
-                'op2 c ... y\n'
+                'Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and '
+                '*op1*,\n'
+                '*op2*, ..., *opN* are comparison operators, then "a op1 b op2 '
+                'c ... y\n'
                 'opN z" is equivalent to "a op1 b and b op2 c and ... y opN '
                 'z", except\n'
                 'that each expression is evaluated at most once.\n'
@@ -1449,16 +1823,16 @@ topics = {'assert': '\n'
                 '(though\n'
                 'perhaps not pretty).\n'
                 '\n'
-                'The forms "<>" and "!=" are equivalent; for consistency '
-                'with C, "!="\n'
+                'The forms "<>" and "!=" are equivalent; for consistency with '
+                'C, "!="\n'
                 'is preferred; where "!=" is mentioned below "<>" is also '
                 'accepted.\n'
                 'The "<>" spelling is considered obsolescent.\n'
                 '\n'
                 'The operators "<", ">", "==", ">=", "<=", and "!=" compare '
                 'the values\n'
-                'of two objects.  The objects need not have the same type. '
-                'If both are\n'
+                'of two objects.  The objects need not have the same type. If '
+                'both are\n'
                 'numbers, they are converted to a common type.  Otherwise, '
                 'objects of\n'
                 'different types *always* compare unequal, and are ordered '
@@ -1478,8 +1852,7 @@ topics = {'assert': '\n'
                 'of\n'
                 'different types are likely to change.)\n'
                 '\n'
-                'Comparison of objects of the same type depends on the '
-                'type:\n'
+                'Comparison of objects of the same type depends on the type:\n'
                 '\n'
                 '* Numbers are compared arithmetically.\n'
                 '\n'
@@ -1494,56 +1867,57 @@ topics = {'assert': '\n'
                 'comparison\n'
                 '  of corresponding elements.  This means that to compare '
                 'equal, each\n'
-                '  element must compare equal and the two sequences must be '
-                'of the same\n'
+                '  element must compare equal and the two sequences must be of '
+                'the same\n'
                 '  type and have the same length.\n'
                 '\n'
                 '  If not equal, the sequences are ordered the same as their '
                 'first\n'
                 '  differing elements.  For example, "cmp([1,2,x], [1,2,y])" '
                 'returns\n'
-                '  the same as "cmp(x,y)".  If the corresponding element '
-                'does not\n'
-                '  exist, the shorter sequence is ordered first (for '
-                'example, "[1,2] <\n'
+                '  the same as "cmp(x,y)".  If the corresponding element does '
+                'not\n'
+                '  exist, the shorter sequence is ordered first (for example, '
+                '"[1,2] <\n'
                 '  [1,2,3]").\n'
                 '\n'
-                '* Mappings (dictionaries) compare equal if and only if '
-                'their sorted\n'
+                '* Mappings (dictionaries) compare equal if and only if their '
+                'sorted\n'
                 '  (key, value) lists compare equal. [5] Outcomes other than '
                 'equality\n'
                 '  are resolved consistently, but are not otherwise defined. '
                 '[6]\n'
                 '\n'
-                '* Most other objects of built-in types compare unequal '
-                'unless they\n'
+                '* Most other objects of built-in types compare unequal unless '
+                'they\n'
                 '  are the same object; the choice whether one object is '
                 'considered\n'
-                '  smaller or larger than another one is made arbitrarily '
-                'but\n'
+                '  smaller or larger than another one is made arbitrarily but\n'
                 '  consistently within one execution of a program.\n'
                 '\n'
                 'The operators "in" and "not in" test for collection '
                 'membership.  "x in\n'
                 's" evaluates to true if *x* is a member of the collection '
                 '*s*, and\n'
-                'false otherwise.  "x not in s" returns the negation of "x '
-                'in s". The\n'
+                'false otherwise.  "x not in s" returns the negation of "x in '
+                's". The\n'
                 'collection membership test has traditionally been bound to '
                 'sequences;\n'
-                'an object is a member of a collection if the collection is '
-                'sequence\n'
+                'an object is a member of a collection if the collection is '
+                'sequence\n'
                 'and contains an element equal to that object.  However, it '
                 'make sense\n'
                 'for many other object types to support membership tests '
                 'without being\n'
-                'a sequence.  In particular, dictionaries (for keys) and '
-                'sets support\n'
+                'a sequence.  In particular, dictionaries (for keys) and sets '
+                'support\n'
                 'membership testing.\n'
                 '\n'
-                'For the list and tuple types, "x in y" is true if and only '
-                'if there\n'
-                'exists an index *i* such that "x == y[i]" is true.\n'
+                'For the list and tuple types, "x in y" is true if and only if '
+                'there\n'
+                'exists an index *i* such that either "x is y[i]" or "x == '
+                'y[i]" is\n'
+                'true.\n'
                 '\n'
                 'For the Unicode and string types, "x in y" is true if and '
                 'only if *x*\n'
@@ -1556,31 +1930,31 @@ topics = {'assert': '\n'
                 'substring of any other string, so """ in "abc"" will return '
                 '"True".\n'
                 '\n'
-                'Changed in version 2.3: Previously, *x* was required to be '
-                'string of\n'
+                'Changed in version 2.3: Previously, *x* was required to be '
+                'string of\n'
                 'length "1".\n'
                 '\n'
                 'For user-defined classes which define the "__contains__()" '
                 'method, "x\n'
                 'in y" is true if and only if "y.__contains__(x)" is true.\n'
                 '\n'
-                'For user-defined classes which do not define '
-                '"__contains__()" but do\n'
-                'define "__iter__()", "x in y" is true if some value "z" '
-                'with "x == z"\n'
+                'For user-defined classes which do not define "__contains__()" '
+                'but do\n'
+                'define "__iter__()", "x in y" is true if some value "z" with '
+                '"x == z"\n'
                 'is produced while iterating over "y".  If an exception is '
                 'raised\n'
                 'during the iteration, it is as if "in" raised that '
                 'exception.\n'
                 '\n'
-                'Lastly, the old-style iteration protocol is tried: if a '
-                'class defines\n'
+                'Lastly, the old-style iteration protocol is tried: if a class '
+                'defines\n'
                 '"__getitem__()", "x in y" is true if and only if there is a '
                 'non-\n'
                 'negative integer index *i* such that "x == y[i]", and all '
                 'lower\n'
-                'integer indices do not raise "IndexError" exception. (If '
-                'any other\n'
+                'integer indices do not raise "IndexError" exception. (If any '
+                'other\n'
                 'exception is raised, it is as if "in" raised that '
                 'exception).\n'
                 '\n'
@@ -1588,8 +1962,8 @@ topics = {'assert': '\n'
                 'value of\n'
                 '"in".\n'
                 '\n'
-                'The operators "is" and "is not" test for object identity: '
-                '"x is y" is\n'
+                'The operators "is" and "is not" test for object identity: "x '
+                'is y" is\n'
                 'true if and only if *x* and *y* are the same object.  "x is '
                 'not y"\n'
                 'yields the inverse truth value. [7]\n',
@@ -1599,40 +1973,37 @@ topics = {'assert': '\n'
              '\n'
              'Compound statements contain (groups of) other statements; they '
              'affect\n'
-             'or control the execution of those other statements in some '
-             'way.  In\n'
+             'or control the execution of those other statements in some way.  '
+             'In\n'
              'general, compound statements span multiple lines, although in '
              'simple\n'
-             'incarnations a whole compound statement may be contained in '
-             'one line.\n'
+             'incarnations a whole compound statement may be contained in one '
+             'line.\n'
              '\n'
              'The "if", "while" and "for" statements implement traditional '
              'control\n'
              'flow constructs.  "try" specifies exception handlers and/or '
              'cleanup\n'
-             'code for a group of statements.  Function and class '
-             'definitions are\n'
+             'code for a group of statements.  Function and class definitions '
+             'are\n'
              'also syntactically compound statements.\n'
              '\n'
-             "Compound statements consist of one or more 'clauses.'  A "
-             'clause\n'
+             "Compound statements consist of one or more 'clauses.'  A clause\n"
              "consists of a header and a 'suite.'  The clause headers of a\n"
              'particular compound statement are all at the same indentation '
              'level.\n'
              'Each clause header begins with a uniquely identifying keyword '
              'and ends\n'
-             'with a colon.  A suite is a group of statements controlled by '
-             'a\n'
-             'clause.  A suite can be one or more semicolon-separated '
-             'simple\n'
+             'with a colon.  A suite is a group of statements controlled by a\n'
+             'clause.  A suite can be one or more semicolon-separated simple\n'
              'statements on the same line as the header, following the '
              "header's\n"
              'colon, or it can be one or more indented statements on '
              'subsequent\n'
              'lines.  Only the latter form of suite can contain nested '
              'compound\n'
-             'statements; the following is illegal, mostly because it '
-             "wouldn't be\n"
+             "statements; the following is illegal, mostly because it wouldn't "
+             'be\n'
              'clear to which "if" clause a following "else" clause would '
              'belong:\n'
              '\n'
@@ -1640,8 +2011,8 @@ topics = {'assert': '\n'
              '\n'
              'Also note that the semicolon binds tighter than the colon in '
              'this\n'
-             'context, so that in the following example, either all or none '
-             'of the\n'
+             'context, so that in the following example, either all or none of '
+             'the\n'
              '"print" statements are executed:\n'
              '\n'
              '   if x < y < z: print x; print y; print z\n'
@@ -1661,14 +2032,13 @@ topics = {'assert': '\n'
              '   statement     ::= stmt_list NEWLINE | compound_stmt\n'
              '   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n'
              '\n'
-             'Note that statements always end in a "NEWLINE" possibly '
-             'followed by a\n'
+             'Note that statements always end in a "NEWLINE" possibly followed '
+             'by a\n'
              '"DEDENT". Also note that optional continuation clauses always '
              'begin\n'
-             'with a keyword that cannot start a statement, thus there are '
-             'no\n'
-             'ambiguities (the \'dangling "else"\' problem is solved in '
-             'Python by\n'
+             'with a keyword that cannot start a statement, thus there are no\n'
+             'ambiguities (the \'dangling "else"\' problem is solved in Python '
+             'by\n'
              'requiring nested "if" statements to be indented).\n'
              '\n'
              'The formatting of the grammar rules in the following sections '
@@ -1701,8 +2071,8 @@ topics = {'assert': '\n'
              'The "while" statement\n'
              '=====================\n'
              '\n'
-             'The "while" statement is used for repeated execution as long '
-             'as an\n'
+             'The "while" statement is used for repeated execution as long as '
+             'an\n'
              'expression is true:\n'
              '\n'
              '   while_stmt ::= "while" expression ":" suite\n'
@@ -1710,8 +2080,8 @@ topics = {'assert': '\n'
              '\n'
              'This repeatedly tests the expression and, if it is true, '
              'executes the\n'
-             'first suite; if the expression is false (which may be the '
-             'first time\n'
+             'first suite; if the expression is false (which may be the first '
+             'time\n'
              'it is tested) the suite of the "else" clause, if present, is '
              'executed\n'
              'and the loop terminates.\n'
@@ -1720,8 +2090,8 @@ topics = {'assert': '\n'
              'loop\n'
              'without executing the "else" clause\'s suite.  A "continue" '
              'statement\n'
-             'executed in the first suite skips the rest of the suite and '
-             'goes back\n'
+             'executed in the first suite skips the rest of the suite and goes '
+             'back\n'
              'to testing the expression.\n'
              '\n'
              '\n'
@@ -1745,10 +2115,10 @@ topics = {'assert': '\n'
              'Each\n'
              'item in turn is assigned to the target list using the standard '
              'rules\n'
-             'for assignments, and then the suite is executed.  When the '
-             'items are\n'
-             'exhausted (which is immediately when the sequence is empty), '
-             'the suite\n'
+             'for assignments, and then the suite is executed.  When the items '
+             'are\n'
+             'exhausted (which is immediately when the sequence is empty), the '
+             'suite\n'
              'in the "else" clause, if present, is executed, and the loop\n'
              'terminates.\n'
              '\n'
@@ -1762,38 +2132,38 @@ topics = {'assert': '\n'
              'next\n'
              'item.\n'
              '\n'
-             'The suite may assign to the variable(s) in the target list; '
-             'this does\n'
+             'The suite may assign to the variable(s) in the target list; this '
+             'does\n'
              'not affect the next item assigned to it.\n'
              '\n'
-             'The target list is not deleted when the loop is finished, but '
-             'if the\n'
+             'The target list is not deleted when the loop is finished, but if '
+             'the\n'
              'sequence is empty, it will not have been assigned to at all by '
              'the\n'
-             'loop.  Hint: the built-in function "range()" returns a '
-             'sequence of\n'
-             'integers suitable to emulate the effect of Pascal\'s "for i := '
-             'to b\n'
+             'loop.  Hint: the built-in function "range()" returns a sequence '
+             'of\n'
+             'integers suitable to emulate the effect of Pascal\'s "for i := '
+             'to b\n'
              'do"; e.g., "range(3)" returns the list "[0, 1, 2]".\n'
              '\n'
-             'Note: There is a subtlety when the sequence is being modified '
-             'by the\n'
-             '  loop (this can only occur for mutable sequences, i.e. '
-             'lists). An\n'
+             'Note: There is a subtlety when the sequence is being modified by '
+             'the\n'
+             '  loop (this can only occur for mutable sequences, i.e. lists). '
+             'An\n'
              '  internal counter is used to keep track of which item is used '
              'next,\n'
-             '  and this is incremented on each iteration.  When this '
-             'counter has\n'
-             '  reached the length of the sequence the loop terminates.  '
-             'This means\n'
+             '  and this is incremented on each iteration.  When this counter '
+             'has\n'
+             '  reached the length of the sequence the loop terminates.  This '
+             'means\n'
              '  that if the suite deletes the current (or a previous) item '
              'from the\n'
              '  sequence, the next item will be skipped (since it gets the '
              'index of\n'
              '  the current item which has already been treated).  Likewise, '
              'if the\n'
-             '  suite inserts an item in the sequence before the current '
-             'item, the\n'
+             '  suite inserts an item in the sequence before the current item, '
+             'the\n'
              '  current item will be treated again the next time through the '
              'loop.\n'
              '  This can lead to nasty bugs that can be avoided by making a\n'
@@ -1806,8 +2176,8 @@ topics = {'assert': '\n'
              'The "try" statement\n'
              '===================\n'
              '\n'
-             'The "try" statement specifies exception handlers and/or '
-             'cleanup code\n'
+             'The "try" statement specifies exception handlers and/or cleanup '
+             'code\n'
              'for a group of statements:\n'
              '\n'
              '   try_stmt  ::= try1_stmt | try2_stmt\n'
@@ -1820,15 +2190,15 @@ topics = {'assert': '\n'
              '                 "finally" ":" suite\n'
              '\n'
              'Changed in version 2.5: In previous versions of Python,\n'
-             '"try"..."except"..."finally" did not work. "try"..."except" '
-             'had to be\n'
+             '"try"..."except"..."finally" did not work. "try"..."except" had '
+             'to be\n'
              'nested in "try"..."finally".\n'
              '\n'
              'The "except" clause(s) specify one or more exception handlers. '
              'When no\n'
              'exception occurs in the "try" clause, no exception handler is\n'
-             'executed. When an exception occurs in the "try" suite, a '
-             'search for an\n'
+             'executed. When an exception occurs in the "try" suite, a search '
+             'for an\n'
              'exception handler is started.  This search inspects the except '
              'clauses\n'
              'in turn until one is found that matches the exception.  An '
@@ -1847,8 +2217,8 @@ topics = {'assert': '\n'
              '\n'
              'If no except clause matches the exception, the search for an '
              'exception\n'
-             'handler continues in the surrounding code and on the '
-             'invocation stack.\n'
+             'handler continues in the surrounding code and on the invocation '
+             'stack.\n'
              '[1]\n'
              '\n'
              'If the evaluation of an expression in the header of an except '
@@ -1863,54 +2233,51 @@ topics = {'assert': '\n'
              '\n'
              'When a matching except clause is found, the exception is '
              'assigned to\n'
-             'the target specified in that except clause, if present, and '
-             'the except\n'
+             'the target specified in that except clause, if present, and the '
+             'except\n'
              "clause's suite is executed.  All except clauses must have an\n"
              'executable block.  When the end of this block is reached, '
              'execution\n'
-             'continues normally after the entire try statement.  (This '
-             'means that\n'
+             'continues normally after the entire try statement.  (This means '
+             'that\n'
              'if two nested handlers exist for the same exception, and the '
              'exception\n'
-             'occurs in the try clause of the inner handler, the outer '
-             'handler will\n'
+             'occurs in the try clause of the inner handler, the outer handler '
+             'will\n'
              'not handle the exception.)\n'
              '\n'
-             "Before an except clause's suite is executed, details about "
-             'the\n'
-             'exception are assigned to three variables in the "sys" '
-             'module:\n'
+             "Before an except clause's suite is executed, details about the\n"
+             'exception are assigned to three variables in the "sys" module:\n'
              '"sys.exc_type" receives the object identifying the exception;\n'
              '"sys.exc_value" receives the exception\'s parameter;\n'
              '"sys.exc_traceback" receives a traceback object (see section '
              'The\n'
              'standard type hierarchy) identifying the point in the program '
              'where\n'
-             'the exception occurred. These details are also available '
-             'through the\n'
+             'the exception occurred. These details are also available through '
+             'the\n'
              '"sys.exc_info()" function, which returns a tuple "(exc_type,\n'
-             'exc_value, exc_traceback)".  Use of the corresponding '
-             'variables is\n'
-             'deprecated in favor of this function, since their use is '
-             'unsafe in a\n'
-             'threaded program.  As of Python 1.5, the variables are '
-             'restored to\n'
+             'exc_value, exc_traceback)".  Use of the corresponding variables '
+             'is\n'
+             'deprecated in favor of this function, since their use is unsafe '
+             'in a\n'
+             'threaded program.  As of Python 1.5, the variables are restored '
+             'to\n'
              'their previous values (before the call) when returning from a '
              'function\n'
              'that handled an exception.\n'
              '\n'
-             'The optional "else" clause is executed if and when control '
-             'flows off\n'
-             'the end of the "try" clause. [2] Exceptions in the "else" '
-             'clause are\n'
+             'The optional "else" clause is executed if and when control flows '
+             'off\n'
+             'the end of the "try" clause. [2] Exceptions in the "else" clause '
+             'are\n'
              'not handled by the preceding "except" clauses.\n'
              '\n'
              'If "finally" is present, it specifies a \'cleanup\' handler.  '
              'The "try"\n'
-             'clause is executed, including any "except" and "else" '
-             'clauses.  If an\n'
-             'exception occurs in any of the clauses and is not handled, '
-             'the\n'
+             'clause is executed, including any "except" and "else" clauses.  '
+             'If an\n'
+             'exception occurs in any of the clauses and is not handled, the\n'
              'exception is temporarily saved. The "finally" clause is '
              'executed.  If\n'
              'there is a saved exception, it is re-raised at the end of the\n'
@@ -1933,23 +2300,22 @@ topics = {'assert': '\n'
              'during\n'
              'execution of the "finally" clause.\n'
              '\n'
-             'When a "return", "break" or "continue" statement is executed '
-             'in the\n'
+             'When a "return", "break" or "continue" statement is executed in '
+             'the\n'
              '"try" suite of a "try"..."finally" statement, the "finally" '
              'clause is\n'
              'also executed \'on the way out.\' A "continue" statement is '
              'illegal in\n'
-             'the "finally" clause. (The reason is a problem with the '
-             'current\n'
+             'the "finally" clause. (The reason is a problem with the current\n'
              'implementation --- this restriction may be lifted in the '
              'future).\n'
              '\n'
              'The return value of a function is determined by the last '
              '"return"\n'
-             'statement executed.  Since the "finally" clause always '
-             'executes, a\n'
-             '"return" statement executed in the "finally" clause will '
-             'always be the\n'
+             'statement executed.  Since the "finally" clause always executes, '
+             'a\n'
+             '"return" statement executed in the "finally" clause will always '
+             'be the\n'
              'last one executed:\n'
              '\n'
              '   >>> def foo():\n'
@@ -1991,13 +2357,11 @@ topics = {'assert': '\n'
              '"with_item")\n'
              '   is evaluated to obtain a context manager.\n'
              '\n'
-             '2. The context manager\'s "__exit__()" is loaded for later '
-             'use.\n'
+             '2. The context manager\'s "__exit__()" is loaded for later use.\n'
              '\n'
              '3. The context manager\'s "__enter__()" method is invoked.\n'
              '\n'
-             '4. If a target was included in the "with" statement, the '
-             'return\n'
+             '4. If a target was included in the "with" statement, the return\n'
              '   value from "__enter__()" is assigned to it.\n'
              '\n'
              '   Note: The "with" statement guarantees that if the '
@@ -2012,12 +2376,11 @@ topics = {'assert': '\n'
              '\n'
              '5. The suite is executed.\n'
              '\n'
-             '6. The context manager\'s "__exit__()" method is invoked. If '
-             'an\n'
+             '6. The context manager\'s "__exit__()" method is invoked. If an\n'
              '   exception caused the suite to be exited, its type, value, '
              'and\n'
-             '   traceback are passed as arguments to "__exit__()". '
-             'Otherwise, three\n'
+             '   traceback are passed as arguments to "__exit__()". Otherwise, '
+             'three\n'
              '   "None" arguments are supplied.\n'
              '\n'
              '   If the suite was exited due to an exception, and the return '
@@ -2026,16 +2389,14 @@ topics = {'assert': '\n'
              'reraised.\n'
              '   If the return value was true, the exception is suppressed, '
              'and\n'
-             '   execution continues with the statement following the '
-             '"with"\n'
+             '   execution continues with the statement following the "with"\n'
              '   statement.\n'
              '\n'
              '   If the suite was exited for any reason other than an '
              'exception, the\n'
              '   return value from "__exit__()" is ignored, and execution '
              'proceeds\n'
-             '   at the normal location for the kind of exit that was '
-             'taken.\n'
+             '   at the normal location for the kind of exit that was taken.\n'
              '\n'
              'With more than one item, the context managers are processed as '
              'if\n'
@@ -2059,10 +2420,11 @@ topics = {'assert': '\n'
              'Changed in version 2.7: Support for multiple context '
              'expressions.\n'
              '\n'
-             'See also: **PEP 0343** - The "with" statement\n'
+             'See also:\n'
              '\n'
-             '     The specification, background, and examples for the '
-             'Python "with"\n'
+             '  **PEP 343** - The "with" statement\n'
+             '     The specification, background, and examples for the Python '
+             '"with"\n'
              '     statement.\n'
              '\n'
              '\n'
@@ -2075,8 +2437,8 @@ topics = {'assert': '\n'
              '\n'
              '   decorated      ::= decorators (classdef | funcdef)\n'
              '   decorators     ::= decorator+\n'
-             '   decorator      ::= "@" dotted_name ["(" [argument_list '
-             '[","]] ")"] NEWLINE\n'
+             '   decorator      ::= "@" dotted_name ["(" [argument_list [","]] '
+             '")"] NEWLINE\n'
              '   funcdef        ::= "def" funcname "(" [parameter_list] ")" '
              '":" suite\n'
              '   dotted_name    ::= identifier ("." identifier)*\n'
@@ -2089,23 +2451,20 @@ topics = {'assert': '\n'
              '   parameter      ::= identifier | "(" sublist ")"\n'
              '   funcname       ::= identifier\n'
              '\n'
-             'A function definition is an executable statement.  Its '
-             'execution binds\n'
+             'A function definition is an executable statement.  Its execution '
+             'binds\n'
              'the function name in the current local namespace to a function '
              'object\n'
-             '(a wrapper around the executable code for the function).  '
-             'This\n'
+             '(a wrapper around the executable code for the function).  This\n'
              'function object contains a reference to the current global '
              'namespace\n'
-             'as the global namespace to be used when the function is '
-             'called.\n'
+             'as the global namespace to be used when the function is called.\n'
              '\n'
-             'The function definition does not execute the function body; '
-             'this gets\n'
+             'The function definition does not execute the function body; this '
+             'gets\n'
              'executed only when the function is called. [3]\n'
              '\n'
-             'A function definition may be wrapped by one or more '
-             '*decorator*\n'
+             'A function definition may be wrapped by one or more *decorator*\n'
              'expressions. Decorator expressions are evaluated when the '
              'function is\n'
              'defined, in the scope that contains the function definition.  '
@@ -2114,8 +2473,8 @@ topics = {'assert': '\n'
              'object\n'
              'as the only argument. The returned value is bound to the '
              'function name\n'
-             'instead of the function object.  Multiple decorators are '
-             'applied in\n'
+             'instead of the function object.  Multiple decorators are applied '
+             'in\n'
              'nested fashion. For example, the following code:\n'
              '\n'
              '   @f1(arg)\n'
@@ -2135,8 +2494,7 @@ topics = {'assert': '\n'
              '*argument* may\n'
              "be omitted from a call, in which case the parameter's default "
              'value is\n'
-             'substituted.  If a parameter has a default value, all '
-             'following\n'
+             'substituted.  If a parameter has a default value, all following\n'
              'parameters must also have a default value --- this is a '
              'syntactic\n'
              'restriction that is not expressed by the grammar.\n'
@@ -2145,20 +2503,19 @@ topics = {'assert': '\n'
              'definition\n'
              'is executed.**  This means that the expression is evaluated '
              'once, when\n'
-             'the function is defined, and that the same "pre-computed" '
-             'value is\n'
-             'used for each call.  This is especially important to '
-             'understand when a\n'
+             'the function is defined, and that the same "pre-computed" value '
+             'is\n'
+             'used for each call.  This is especially important to understand '
+             'when a\n'
              'default parameter is a mutable object, such as a list or a '
              'dictionary:\n'
              'if the function modifies the object (e.g. by appending an item '
              'to a\n'
              'list), the default value is in effect modified. This is '
              'generally not\n'
-             'what was intended.  A way around this  is to use "None" as '
-             'the\n'
-             'default, and explicitly test for it in the body of the '
-             'function, e.g.:\n'
+             'what was intended.  A way around this  is to use "None" as the\n'
+             'default, and explicitly test for it in the body of the function, '
+             'e.g.:\n'
              '\n'
              '   def whats_on_the_telly(penguin=None):\n'
              '       if penguin is None:\n'
@@ -2166,14 +2523,14 @@ topics = {'assert': '\n'
              '       penguin.append("property of the zoo")\n'
              '       return penguin\n'
              '\n'
-             'Function call semantics are described in more detail in '
-             'section Calls.\n'
+             'Function call semantics are described in more detail in section '
+             'Calls.\n'
              'A function call always assigns values to all parameters '
              'mentioned in\n'
              'the parameter list, either from position arguments, from '
              'keyword\n'
-             'arguments, or from default values.  If the form '
-             '""*identifier"" is\n'
+             'arguments, or from default values.  If the form ""*identifier"" '
+             'is\n'
              'present, it is initialized to a tuple receiving any excess '
              'positional\n'
              'parameters, defaulting to the empty tuple.  If the form\n'
@@ -2183,10 +2540,9 @@ topics = {'assert': '\n'
              'empty\n'
              'dictionary.\n'
              '\n'
-             'It is also possible to create anonymous functions (functions '
-             'not bound\n'
-             'to a name), for immediate use in expressions.  This uses '
-             'lambda\n'
+             'It is also possible to create anonymous functions (functions not '
+             'bound\n'
+             'to a name), for immediate use in expressions.  This uses lambda\n'
              'expressions, described in section Lambdas.  Note that the '
              'lambda\n'
              'expression is merely a shorthand for a simplified function '
@@ -2205,8 +2561,7 @@ topics = {'assert': '\n'
              'function\n'
              'that can be returned or passed around.  Free variables used in '
              'the\n'
-             'nested function can access the local variables of the '
-             'function\n'
+             'nested function can access the local variables of the function\n'
              'containing the def.  See section Naming and binding for '
              'details.\n'
              '\n'
@@ -2237,16 +2592,16 @@ topics = {'assert': '\n'
              'finishes\n'
              'execution, its execution frame is discarded but its local '
              'namespace is\n'
-             'saved. [4] A class object is then created using the '
-             'inheritance list\n'
+             'saved. [4] A class object is then created using the inheritance '
+             'list\n'
              'for the base classes and the saved local namespace for the '
              'attribute\n'
              'dictionary.  The class name is bound to this class object in '
              'the\n'
              'original local namespace.\n'
              '\n'
-             "**Programmer's note:** Variables defined in the class "
-             'definition are\n'
+             "**Programmer's note:** Variables defined in the class definition "
+             'are\n'
              'class variables; they are shared by all instances.  To create '
              'instance\n'
              'variables, they can be set in a method with "self.name = '
@@ -2255,8 +2610,8 @@ topics = {'assert': '\n'
              'notation\n'
              '""self.name"", and an instance variable hides a class variable '
              'with\n'
-             'the same name when accessed in this way. Class variables can '
-             'be used\n'
+             'the same name when accessed in this way. Class variables can be '
+             'used\n'
              'as defaults for instance variables, but using mutable values '
              'there can\n'
              'lead to unexpected results.  For *new-style class*es, '
@@ -2265,32 +2620,28 @@ topics = {'assert': '\n'
              'implementation\n'
              'details.\n'
              '\n'
-             'Class definitions, like function definitions, may be wrapped '
-             'by one or\n'
+             'Class definitions, like function definitions, may be wrapped by '
+             'one or\n'
              'more *decorator* expressions.  The evaluation rules for the '
              'decorator\n'
-             'expressions are the same as for functions.  The result must be '
-             'class\n'
+             'expressions are the same as for functions.  The result must be '
+             'class\n'
              'object, which is then bound to the class name.\n'
              '\n'
              '-[ Footnotes ]-\n'
              '\n'
-             '[1] The exception is propagated to the invocation stack '
-             'unless\n'
-             '    there is a "finally" clause which happens to raise '
-             'another\n'
+             '[1] The exception is propagated to the invocation stack unless\n'
+             '    there is a "finally" clause which happens to raise another\n'
              '    exception. That new exception causes the old one to be '
              'lost.\n'
              '\n'
              '[2] Currently, control "flows off the end" except in the case '
              'of\n'
-             '    an exception or the execution of a "return", "continue", '
-             'or\n'
+             '    an exception or the execution of a "return", "continue", or\n'
              '    "break" statement.\n'
              '\n'
              '[3] A string literal appearing as the first statement in the\n'
-             "    function body is transformed into the function's "
-             '"__doc__"\n'
+             '    function body is transformed into the function\'s "__doc__"\n'
              "    attribute and therefore the function's *docstring*.\n"
              '\n'
              '[4] A string literal appearing as the first statement in the '
@@ -2312,15 +2663,15 @@ topics = {'assert': '\n'
                      'runtime context\n'
                      'for the execution of the block of code.  Context '
                      'managers are normally\n'
-                     'invoked using the "with" statement (described in '
-                     'section The with\n'
+                     'invoked using the "with" statement (described in section '
+                     'The with\n'
                      'statement), but can also be used by directly invoking '
                      'their methods.\n'
                      '\n'
                      'Typical uses of context managers include saving and '
                      'restoring various\n'
-                     'kinds of global state, locking and unlocking '
-                     'resources, closing opened\n'
+                     'kinds of global state, locking and unlocking resources, '
+                     'closing opened\n'
                      'files, etc.\n'
                      '\n'
                      'For more information on context managers, see Context '
@@ -2328,39 +2679,40 @@ topics = {'assert': '\n'
                      '\n'
                      'object.__enter__(self)\n'
                      '\n'
-                     '   Enter the runtime context related to this object. '
-                     'The "with"\n'
-                     "   statement will bind this method's return value to "
-                     'the target(s)\n'
+                     '   Enter the runtime context related to this object. The '
+                     '"with"\n'
+                     "   statement will bind this method's return value to the "
+                     'target(s)\n'
                      '   specified in the "as" clause of the statement, if '
                      'any.\n'
                      '\n'
                      'object.__exit__(self, exc_type, exc_value, traceback)\n'
                      '\n'
-                     '   Exit the runtime context related to this object. '
-                     'The parameters\n'
-                     '   describe the exception that caused the context to '
-                     'be exited. If the\n'
+                     '   Exit the runtime context related to this object. The '
+                     'parameters\n'
+                     '   describe the exception that caused the context to be '
+                     'exited. If the\n'
                      '   context was exited without an exception, all three '
                      'arguments will\n'
                      '   be "None".\n'
                      '\n'
-                     '   If an exception is supplied, and the method wishes '
-                     'to suppress the\n'
+                     '   If an exception is supplied, and the method wishes to '
+                     'suppress the\n'
                      '   exception (i.e., prevent it from being propagated), '
                      'it should\n'
-                     '   return a true value. Otherwise, the exception will '
-                     'be processed\n'
+                     '   return a true value. Otherwise, the exception will be '
+                     'processed\n'
                      '   normally upon exit from this method.\n'
                      '\n'
-                     '   Note that "__exit__()" methods should not reraise '
-                     'the passed-in\n'
+                     '   Note that "__exit__()" methods should not reraise the '
+                     'passed-in\n'
                      "   exception; this is the caller's responsibility.\n"
                      '\n'
-                     'See also: **PEP 0343** - The "with" statement\n'
+                     'See also:\n'
                      '\n'
-                     '     The specification, background, and examples for '
-                     'the Python "with"\n'
+                     '  **PEP 343** - The "with" statement\n'
+                     '     The specification, background, and examples for the '
+                     'Python "with"\n'
                      '     statement.\n',
  'continue': '\n'
              'The "continue" statement\n'
@@ -2376,8 +2728,7 @@ topics = {'assert': '\n'
              'the\n'
              'nearest enclosing loop.\n'
              '\n'
-             'When "continue" passes control out of a "try" statement with '
-             'a\n'
+             'When "continue" passes control out of a "try" statement with a\n'
              '"finally" clause, that "finally" clause is executed before '
              'really\n'
              'starting the next loop cycle.\n',
@@ -2403,8 +2754,8 @@ topics = {'assert': '\n'
                 'the\n'
                 '  other is converted to floating point;\n'
                 '\n'
-                '* otherwise, if either argument is a long integer, the '
-                'other is\n'
+                '* otherwise, if either argument is a long integer, the other '
+                'is\n'
                 '  converted to long integer;\n'
                 '\n'
                 '* otherwise, both must be plain integers and no conversion '
@@ -2424,14 +2775,14 @@ topics = {'assert': '\n'
                   '\n'
                   '   Called to create a new instance of class *cls*.  '
                   '"__new__()" is a\n'
-                  '   static method (special-cased so you need not declare '
-                  'it as such)\n'
-                  '   that takes the class of which an instance was '
-                  'requested as its\n'
+                  '   static method (special-cased so you need not declare it '
+                  'as such)\n'
+                  '   that takes the class of which an instance was requested '
+                  'as its\n'
                   '   first argument.  The remaining arguments are those '
                   'passed to the\n'
-                  '   object constructor expression (the call to the '
-                  'class).  The return\n'
+                  '   object constructor expression (the call to the class).  '
+                  'The return\n'
                   '   value of "__new__()" should be the new object instance '
                   '(usually an\n'
                   '   instance of *cls*).\n'
@@ -2441,8 +2792,8 @@ topics = {'assert': '\n'
                   '   invoking the superclass\'s "__new__()" method using\n'
                   '   "super(currentclass, cls).__new__(cls[, ...])" with '
                   'appropriate\n'
-                  '   arguments and then modifying the newly-created '
-                  'instance as\n'
+                  '   arguments and then modifying the newly-created instance '
+                  'as\n'
                   '   necessary before returning it.\n'
                   '\n'
                   '   If "__new__()" returns an instance of *cls*, then the '
@@ -2469,8 +2820,8 @@ topics = {'assert': '\n'
                   '\n'
                   '   Called after the instance has been created (by '
                   '"__new__()"), but\n'
-                  '   before it is returned to the caller.  The arguments '
-                  'are those\n'
+                  '   before it is returned to the caller.  The arguments are '
+                  'those\n'
                   '   passed to the class constructor expression.  If a base '
                   'class has an\n'
                   '   "__init__()" method, the derived class\'s "__init__()" '
@@ -2490,14 +2841,14 @@ topics = {'assert': '\n'
                   '\n'
                   'object.__del__(self)\n'
                   '\n'
-                  '   Called when the instance is about to be destroyed.  '
-                  'This is also\n'
-                  '   called a destructor.  If a base class has a '
-                  '"__del__()" method, the\n'
+                  '   Called when the instance is about to be destroyed.  This '
+                  'is also\n'
+                  '   called a destructor.  If a base class has a "__del__()" '
+                  'method, the\n'
                   '   derived class\'s "__del__()" method, if any, must '
                   'explicitly call it\n'
-                  '   to ensure proper deletion of the base class part of '
-                  'the instance.\n'
+                  '   to ensure proper deletion of the base class part of the '
+                  'instance.\n'
                   '   Note that it is possible (though not recommended!) for '
                   'the\n'
                   '   "__del__()" method to postpone destruction of the '
@@ -2512,12 +2863,12 @@ topics = {'assert': '\n'
                   '\n'
                   '   Note: "del x" doesn\'t directly call "x.__del__()" --- '
                   'the former\n'
-                  '     decrements the reference count for "x" by one, and '
-                  'the latter is\n'
-                  '     only called when "x"\'s reference count reaches '
-                  'zero.  Some common\n'
-                  '     situations that may prevent the reference count of '
-                  'an object from\n'
+                  '     decrements the reference count for "x" by one, and the '
+                  'latter is\n'
+                  '     only called when "x"\'s reference count reaches zero.  '
+                  'Some common\n'
+                  '     situations that may prevent the reference count of an '
+                  'object from\n'
                   '     going to zero include: circular references between '
                   'objects (e.g.,\n'
                   '     a doubly-linked list or a tree data structure with '
@@ -2526,59 +2877,58 @@ topics = {'assert': '\n'
                   'stack frame of\n'
                   '     a function that caught an exception (the traceback '
                   'stored in\n'
-                  '     "sys.exc_traceback" keeps the stack frame alive); or '
-                  'reference\n'
+                  '     "sys.exc_traceback" keeps the stack frame alive); or '
+                  'reference\n'
                   '     to the object on the stack frame that raised an '
                   'unhandled\n'
                   '     exception in interactive mode (the traceback stored '
                   'in\n'
                   '     "sys.last_traceback" keeps the stack frame alive).  '
                   'The first\n'
-                  '     situation can only be remedied by explicitly '
-                  'breaking the cycles;\n'
+                  '     situation can only be remedied by explicitly breaking '
+                  'the cycles;\n'
                   '     the latter two situations can be resolved by storing '
                   '"None" in\n'
-                  '     "sys.exc_traceback" or "sys.last_traceback".  '
-                  'Circular references\n'
+                  '     "sys.exc_traceback" or "sys.last_traceback".  Circular '
+                  'references\n'
                   '     which are garbage are detected when the option cycle '
                   'detector is\n'
-                  "     enabled (it's on by default), but can only be "
-                  'cleaned up if there\n'
+                  "     enabled (it's on by default), but can only be cleaned "
+                  'up if there\n'
                   '     are no Python-level "__del__()" methods involved. '
                   'Refer to the\n'
-                  '     documentation for the "gc" module for more '
-                  'information about how\n'
+                  '     documentation for the "gc" module for more information '
+                  'about how\n'
                   '     "__del__()" methods are handled by the cycle '
                   'detector,\n'
-                  '     particularly the description of the "garbage" '
-                  'value.\n'
+                  '     particularly the description of the "garbage" value.\n'
                   '\n'
                   '   Warning: Due to the precarious circumstances under '
                   'which\n'
-                  '     "__del__()" methods are invoked, exceptions that '
-                  'occur during\n'
-                  '     their execution are ignored, and a warning is '
-                  'printed to\n'
+                  '     "__del__()" methods are invoked, exceptions that occur '
+                  'during\n'
+                  '     their execution are ignored, and a warning is printed '
+                  'to\n'
                   '     "sys.stderr" instead. Also, when "__del__()" is '
                   'invoked in\n'
                   '     response to a module being deleted (e.g., when '
                   'execution of the\n'
                   '     program is done), other globals referenced by the '
                   '"__del__()"\n'
-                  '     method may already have been deleted or in the '
-                  'process of being\n'
-                  '     torn down (e.g. the import machinery shutting '
-                  'down).  For this\n'
+                  '     method may already have been deleted or in the process '
+                  'of being\n'
+                  '     torn down (e.g. the import machinery shutting down).  '
+                  'For this\n'
                   '     reason, "__del__()" methods should do the absolute '
                   'minimum needed\n'
                   '     to maintain external invariants.  Starting with '
                   'version 1.5,\n'
-                  '     Python guarantees that globals whose name begins '
-                  'with a single\n'
-                  '     underscore are deleted from their module before '
-                  'other globals are\n'
-                  '     deleted; if no other references to such globals '
-                  'exist, this may\n'
+                  '     Python guarantees that globals whose name begins with '
+                  'a single\n'
+                  '     underscore are deleted from their module before other '
+                  'globals are\n'
+                  '     deleted; if no other references to such globals exist, '
+                  'this may\n'
                   '     help in assuring that imported modules are still '
                   'available at the\n'
                   '     time when the "__del__()" method is called.\n'
@@ -2591,24 +2941,24 @@ topics = {'assert': '\n'
                   'conversions\n'
                   '   (reverse quotes) to compute the "official" string '
                   'representation of\n'
-                  '   an object.  If at all possible, this should look like '
-                  'valid\n'
+                  '   an object.  If at all possible, this should look like '
+                  'valid\n'
                   '   Python expression that could be used to recreate an '
                   'object with the\n'
-                  '   same value (given an appropriate environment).  If '
-                  'this is not\n'
+                  '   same value (given an appropriate environment).  If this '
+                  'is not\n'
                   '   possible, a string of the form "<...some useful '
                   'description...>"\n'
                   '   should be returned.  The return value must be a string '
                   'object. If a\n'
                   '   class defines "__repr__()" but not "__str__()", then '
                   '"__repr__()"\n'
-                  '   is also used when an "informal" string representation '
-                  'of instances\n'
+                  '   is also used when an "informal" string representation of '
+                  'instances\n'
                   '   of that class is required.\n'
                   '\n'
-                  '   This is typically used for debugging, so it is '
-                  'important that the\n'
+                  '   This is typically used for debugging, so it is important '
+                  'that the\n'
                   '   representation is information-rich and unambiguous.\n'
                   '\n'
                   'object.__str__(self)\n'
@@ -2617,8 +2967,8 @@ topics = {'assert': '\n'
                   '"print"\n'
                   '   statement to compute the "informal" string '
                   'representation of an\n'
-                  '   object.  This differs from "__repr__()" in that it '
-                  'does not have to\n'
+                  '   object.  This differs from "__repr__()" in that it does '
+                  'not have to\n'
                   '   be a valid Python expression: a more convenient or '
                   'concise\n'
                   '   representation may be used instead. The return value '
@@ -2638,8 +2988,8 @@ topics = {'assert': '\n'
                   'are called\n'
                   '   for comparison operators in preference to "__cmp__()" '
                   'below. The\n'
-                  '   correspondence between operator symbols and method '
-                  'names is as\n'
+                  '   correspondence between operator symbols and method names '
+                  'is as\n'
                   '   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls '
                   '"x.__le__(y)",\n'
                   '   "x==y" calls "x.__eq__(y)", "x!=y" and "x<>y" call '
@@ -2649,21 +2999,21 @@ topics = {'assert': '\n'
                   '\n'
                   '   A rich comparison method may return the singleton '
                   '"NotImplemented"\n'
-                  '   if it does not implement the operation for a given '
-                  'pair of\n'
+                  '   if it does not implement the operation for a given pair '
+                  'of\n'
                   '   arguments. By convention, "False" and "True" are '
                   'returned for a\n'
-                  '   successful comparison. However, these methods can '
-                  'return any value,\n'
+                  '   successful comparison. However, these methods can return '
+                  'any value,\n'
                   '   so if the comparison operator is used in a Boolean '
                   'context (e.g.,\n'
-                  '   in the condition of an "if" statement), Python will '
-                  'call "bool()"\n'
+                  '   in the condition of an "if" statement), Python will call '
+                  '"bool()"\n'
                   '   on the value to determine if the result is true or '
                   'false.\n'
                   '\n'
-                  '   There are no implied relationships among the '
-                  'comparison operators.\n'
+                  '   There are no implied relationships among the comparison '
+                  'operators.\n'
                   '   The truth of "x==y" does not imply that "x!=y" is '
                   'false.\n'
                   '   Accordingly, when defining "__eq__()", one should also '
@@ -2676,19 +3026,17 @@ topics = {'assert': '\n'
                   'operations and\n'
                   '   are usable as dictionary keys.\n'
                   '\n'
-                  '   There are no swapped-argument versions of these '
-                  'methods (to be used\n'
+                  '   There are no swapped-argument versions of these methods '
+                  '(to be used\n'
                   '   when the left argument does not support the operation '
                   'but the right\n'
                   '   argument does); rather, "__lt__()" and "__gt__()" are '
                   "each other's\n"
-                  '   reflection, "__le__()" and "__ge__()" are each '
-                  "other's reflection,\n"
-                  '   and "__eq__()" and "__ne__()" are their own '
-                  'reflection.\n'
+                  '   reflection, "__le__()" and "__ge__()" are each other\'s '
+                  'reflection,\n'
+                  '   and "__eq__()" and "__ne__()" are their own reflection.\n'
                   '\n'
-                  '   Arguments to rich comparison methods are never '
-                  'coerced.\n'
+                  '   Arguments to rich comparison methods are never coerced.\n'
                   '\n'
                   '   To automatically generate ordering operations from a '
                   'single root\n'
@@ -2696,18 +3044,18 @@ topics = {'assert': '\n'
                   '\n'
                   'object.__cmp__(self, other)\n'
                   '\n'
-                  '   Called by comparison operations if rich comparison '
-                  '(see above) is\n'
-                  '   not defined.  Should return a negative integer if '
-                  '"self < other",\n'
+                  '   Called by comparison operations if rich comparison (see '
+                  'above) is\n'
+                  '   not defined.  Should return a negative integer if "self '
+                  '< other",\n'
                   '   zero if "self == other", a positive integer if "self > '
                   'other".  If\n'
                   '   no "__cmp__()", "__eq__()" or "__ne__()" operation is '
                   'defined,\n'
                   '   class instances are compared by object identity '
                   '("address").  See\n'
-                  '   also the description of "__hash__()" for some '
-                  'important notes on\n'
+                  '   also the description of "__hash__()" for some important '
+                  'notes on\n'
                   '   creating *hashable* objects which support custom '
                   'comparison\n'
                   '   operations and are usable as dictionary keys. (Note: '
@@ -2722,44 +3070,44 @@ topics = {'assert': '\n'
                   '\n'
                   'object.__hash__(self)\n'
                   '\n'
-                  '   Called by built-in function "hash()" and for '
-                  'operations on members\n'
-                  '   of hashed collections including "set", "frozenset", '
-                  'and "dict".\n'
+                  '   Called by built-in function "hash()" and for operations '
+                  'on members\n'
+                  '   of hashed collections including "set", "frozenset", and '
+                  '"dict".\n'
                   '   "__hash__()" should return an integer.  The only '
                   'required property\n'
                   '   is that objects which compare equal have the same hash '
                   'value; it is\n'
                   '   advised to somehow mix together (e.g. using exclusive '
                   'or) the hash\n'
-                  '   values for the components of the object that also play '
-                  'part in\n'
+                  '   values for the components of the object that also play '
+                  'part in\n'
                   '   comparison of objects.\n'
                   '\n'
                   '   If a class does not define a "__cmp__()" or "__eq__()" '
                   'method it\n'
-                  '   should not define a "__hash__()" operation either; if '
-                  'it defines\n'
+                  '   should not define a "__hash__()" operation either; if it '
+                  'defines\n'
                   '   "__cmp__()" or "__eq__()" but not "__hash__()", its '
                   'instances will\n'
-                  '   not be usable in hashed collections.  If a class '
-                  'defines mutable\n'
+                  '   not be usable in hashed collections.  If a class defines '
+                  'mutable\n'
                   '   objects and implements a "__cmp__()" or "__eq__()" '
                   'method, it\n'
                   '   should not implement "__hash__()", since hashable '
                   'collection\n'
                   "   implementations require that a object's hash value is "
                   'immutable (if\n'
-                  "   the object's hash value changes, it will be in the "
-                  'wrong hash\n'
+                  "   the object's hash value changes, it will be in the wrong "
+                  'hash\n'
                   '   bucket).\n'
                   '\n'
                   '   User-defined classes have "__cmp__()" and "__hash__()" '
                   'methods by\n'
-                  '   default; with them, all objects compare unequal '
-                  '(except with\n'
-                  '   themselves) and "x.__hash__()" returns a result '
-                  'derived from\n'
+                  '   default; with them, all objects compare unequal (except '
+                  'with\n'
+                  '   themselves) and "x.__hash__()" returns a result derived '
+                  'from\n'
                   '   "id(x)".\n'
                   '\n'
                   '   Classes which inherit a "__hash__()" method from a '
@@ -2770,8 +3118,8 @@ topics = {'assert': '\n'
                   'switching to a\n'
                   '   value-based concept of equality instead of the default '
                   'identity\n'
-                  '   based equality) can explicitly flag themselves as '
-                  'being unhashable\n'
+                  '   based equality) can explicitly flag themselves as being '
+                  'unhashable\n'
                   '   by setting "__hash__ = None" in the class definition. '
                   'Doing so\n'
                   '   means that not only will instances of the class raise '
@@ -2786,10 +3134,10 @@ topics = {'assert': '\n'
                   'explicitly\n'
                   '   raise "TypeError").\n'
                   '\n'
-                  '   Changed in version 2.5: "__hash__()" may now also '
-                  'return a long\n'
-                  '   integer object; the 32-bit integer is then derived '
-                  'from the hash of\n'
+                  '   Changed in version 2.5: "__hash__()" may now also return '
+                  'a long\n'
+                  '   integer object; the 32-bit integer is then derived from '
+                  'the hash of\n'
                   '   that object.\n'
                   '\n'
                   '   Changed in version 2.6: "__hash__" may now be set to '
@@ -2798,14 +3146,14 @@ topics = {'assert': '\n'
                   '\n'
                   'object.__nonzero__(self)\n'
                   '\n'
-                  '   Called to implement truth value testing and the '
-                  'built-in operation\n'
+                  '   Called to implement truth value testing and the built-in '
+                  'operation\n'
                   '   "bool()"; should return "False" or "True", or their '
                   'integer\n'
                   '   equivalents "0" or "1".  When this method is not '
                   'defined,\n'
-                  '   "__len__()" is called, if it is defined, and the '
-                  'object is\n'
+                  '   "__len__()" is called, if it is defined, and the object '
+                  'is\n'
                   '   considered true if its result is nonzero. If a class '
                   'defines\n'
                   '   neither "__len__()" nor "__nonzero__()", all its '
@@ -2814,8 +3162,8 @@ topics = {'assert': '\n'
                   '\n'
                   'object.__unicode__(self)\n'
                   '\n'
-                  '   Called to implement "unicode()" built-in; should '
-                  'return a Unicode\n'
+                  '   Called to implement "unicode()" built-in; should return '
+                  'a Unicode\n'
                   '   object. When this method is not defined, string '
                   'conversion is\n'
                   '   attempted, and the result of string conversion is '
@@ -2831,12 +3179,12 @@ topics = {'assert': '\n'
              '\n'
              'The module "pdb" defines an interactive source code debugger '
              'for\n'
-             'Python programs.  It supports setting (conditional) '
-             'breakpoints and\n'
+             'Python programs.  It supports setting (conditional) breakpoints '
+             'and\n'
              'single stepping at the source line level, inspection of stack '
              'frames,\n'
-             'source code listing, and evaluation of arbitrary Python code '
-             'in the\n'
+             'source code listing, and evaluation of arbitrary Python code in '
+             'the\n'
              'context of any stack frame.  It also supports post-mortem '
              'debugging\n'
              'and can be called under program control.\n'
@@ -2845,8 +3193,8 @@ topics = {'assert': '\n'
              'class\n'
              '"Pdb". This is currently undocumented but easily understood by '
              'reading\n'
-             'the source.  The extension interface uses the modules "bdb" '
-             'and "cmd".\n'
+             'the source.  The extension interface uses the modules "bdb" and '
+             '"cmd".\n'
              '\n'
              'The debugger\'s prompt is "(Pdb)". Typical usage to run a '
              'program under\n'
@@ -2871,12 +3219,12 @@ topics = {'assert': '\n'
              '\n'
              'When invoked as a script, pdb will automatically enter '
              'post-mortem\n'
-             'debugging if the program being debugged exits abnormally. '
-             'After post-\n'
+             'debugging if the program being debugged exits abnormally. After '
+             'post-\n'
              'mortem debugging (or after normal exit of the program), pdb '
              'will\n'
-             "restart the program. Automatic restarting preserves pdb's "
-             'state (such\n'
+             "restart the program. Automatic restarting preserves pdb's state "
+             '(such\n'
              'as breakpoints) and in most cases is more useful than quitting '
              'the\n'
              "debugger upon program's exit.\n"
@@ -2920,10 +3268,10 @@ topics = {'assert': '\n'
              '\n'
              '   Execute the *statement* (given as a string) under debugger '
              'control.\n'
-             '   The debugger prompt appears before any code is executed; '
-             'you can\n'
-             '   set breakpoints and type "continue", or you can step '
-             'through the\n'
+             '   The debugger prompt appears before any code is executed; you '
+             'can\n'
+             '   set breakpoints and type "continue", or you can step through '
+             'the\n'
              '   statement using "step" or "next" (all these commands are '
              'explained\n'
              '   below).  The optional *globals* and *locals* arguments '
@@ -2931,17 +3279,14 @@ topics = {'assert': '\n'
              '   environment in which the code is executed; by default the\n'
              '   dictionary of the module "__main__" is used.  (See the '
              'explanation\n'
-             '   of the "exec" statement or the "eval()" built-in '
-             'function.)\n'
+             '   of the "exec" statement or the "eval()" built-in function.)\n'
              '\n'
              'pdb.runeval(expression[, globals[, locals]])\n'
              '\n'
-             '   Evaluate the *expression* (given as a string) under '
-             'debugger\n'
+             '   Evaluate the *expression* (given as a string) under debugger\n'
              '   control.  When "runeval()" returns, it returns the value of '
              'the\n'
-             '   expression.  Otherwise this function is similar to '
-             '"run()".\n'
+             '   expression.  Otherwise this function is similar to "run()".\n'
              '\n'
              'pdb.runcall(function[, argument, ...])\n'
              '\n'
@@ -2957,16 +3302,15 @@ topics = {'assert': '\n'
              '\n'
              '   Enter the debugger at the calling stack frame.  This is '
              'useful to\n'
-             '   hard-code a breakpoint at a given point in a program, even '
-             'if the\n'
-             '   code is not otherwise being debugged (e.g. when an '
-             'assertion\n'
+             '   hard-code a breakpoint at a given point in a program, even if '
+             'the\n'
+             '   code is not otherwise being debugged (e.g. when an assertion\n'
              '   fails).\n'
              '\n'
              'pdb.post_mortem([traceback])\n'
              '\n'
-             '   Enter post-mortem debugging of the given *traceback* '
-             'object.  If no\n'
+             '   Enter post-mortem debugging of the given *traceback* object.  '
+             'If no\n'
              '   *traceback* is given, it uses the one of the exception that '
              'is\n'
              '   currently being handled (an exception must be being handled '
@@ -2980,23 +3324,23 @@ topics = {'assert': '\n'
              '\n'
              'The "run*" functions and "set_trace()" are aliases for '
              'instantiating\n'
-             'the "Pdb" class and calling the method of the same name.  If '
-             'you want\n'
+             'the "Pdb" class and calling the method of the same name.  If you '
+             'want\n'
              'to access further features, you have to do this yourself:\n'
              '\n'
-             "class class pdb.Pdb(completekey='tab', stdin=None, "
-             'stdout=None, skip=None)\n'
+             "class pdb.Pdb(completekey='tab', stdin=None, stdout=None, "
+             'skip=None)\n'
              '\n'
              '   "Pdb" is the debugger class.\n'
              '\n'
-             '   The *completekey*, *stdin* and *stdout* arguments are '
-             'passed to the\n'
+             '   The *completekey*, *stdin* and *stdout* arguments are passed '
+             'to the\n'
              '   underlying "cmd.Cmd" class; see the description there.\n'
              '\n'
              '   The *skip* argument, if given, must be an iterable of '
              'glob-style\n'
-             '   module name patterns.  The debugger will not step into '
-             'frames that\n'
+             '   module name patterns.  The debugger will not step into frames '
+             'that\n'
              '   originate in a module that matches one of these patterns. '
              '[1]\n'
              '\n'
@@ -3011,8 +3355,7 @@ topics = {'assert': '\n'
              '   runcall(function[, argument, ...])\n'
              '   set_trace()\n'
              '\n'
-             '      See the documentation for the functions explained '
-             'above.\n',
+             '      See the documentation for the functions explained above.\n',
  'del': '\n'
         'The "del" statement\n'
         '*******************\n'
@@ -3021,29 +3364,24 @@ topics = {'assert': '\n'
         '\n'
         'Deletion is recursively defined very similar to the way assignment '
         'is\n'
-        'defined. Rather than spelling it out in full details, here are '
-        'some\n'
+        'defined. Rather than spelling it out in full details, here are some\n'
         'hints.\n'
         '\n'
-        'Deletion of a target list recursively deletes each target, from '
-        'left\n'
+        'Deletion of a target list recursively deletes each target, from left\n'
         'to right.\n'
         '\n'
         'Deletion of a name removes the binding of that name  from the local '
         'or\n'
-        'global namespace, depending on whether the name occurs in a '
-        '"global"\n'
+        'global namespace, depending on whether the name occurs in a "global"\n'
         'statement in the same code block.  If the name is unbound, a\n'
         '"NameError" exception will be raised.\n'
         '\n'
-        'It is illegal to delete a name from the local namespace if it '
-        'occurs\n'
+        'It is illegal to delete a name from the local namespace if it occurs\n'
         'as a free variable in a nested block.\n'
         '\n'
         'Deletion of attribute references, subscriptions and slicings is '
         'passed\n'
-        'to the primary object involved; deletion of a slicing is in '
-        'general\n'
+        'to the primary object involved; deletion of a slicing is in general\n'
         'equivalent to assignment of an empty slice of the right type (but '
         'even\n'
         'this is determined by the sliced object).\n',
@@ -3051,32 +3389,28 @@ topics = {'assert': '\n'
          'Dictionary displays\n'
          '*******************\n'
          '\n'
-         'A dictionary display is a possibly empty series of key/datum '
-         'pairs\n'
+         'A dictionary display is a possibly empty series of key/datum pairs\n'
          'enclosed in curly braces:\n'
          '\n'
-         '   dict_display       ::= "{" [key_datum_list | '
-         'dict_comprehension] "}"\n'
+         '   dict_display       ::= "{" [key_datum_list | dict_comprehension] '
+         '"}"\n'
          '   key_datum_list     ::= key_datum ("," key_datum)* [","]\n'
          '   key_datum          ::= expression ":" expression\n'
          '   dict_comprehension ::= expression ":" expression comp_for\n'
          '\n'
          'A dictionary display yields a new dictionary object.\n'
          '\n'
-         'If a comma-separated sequence of key/datum pairs is given, they '
-         'are\n'
+         'If a comma-separated sequence of key/datum pairs is given, they are\n'
          'evaluated from left to right to define the entries of the '
          'dictionary:\n'
          'each key object is used as a key into the dictionary to store the\n'
-         'corresponding datum.  This means that you can specify the same '
-         'key\n'
+         'corresponding datum.  This means that you can specify the same key\n'
          "multiple times in the key/datum list, and the final dictionary's "
          'value\n'
          'for that key will be the last one given.\n'
          '\n'
          'A dict comprehension, in contrast to list and set comprehensions,\n'
-         'needs two expressions separated with a colon followed by the '
-         'usual\n'
+         'needs two expressions separated with a colon followed by the usual\n'
          '"for" and "if" clauses. When the comprehension is run, the '
          'resulting\n'
          'key and value elements are inserted in the new dictionary in the '
@@ -3085,10 +3419,8 @@ topics = {'assert': '\n'
          '\n'
          'Restrictions on the types of the key values are listed earlier in\n'
          'section The standard type hierarchy.  (To summarize, the key type\n'
-         'should be *hashable*, which excludes all mutable objects.)  '
-         'Clashes\n'
-         'between duplicate keys are not detected; the last datum '
-         '(textually\n'
+         'should be *hashable*, which excludes all mutable objects.)  Clashes\n'
+         'between duplicate keys are not detected; the last datum (textually\n'
          'rightmost in the display) stored for a given key value prevails.\n',
  'dynamic-features': '\n'
                      'Interaction with dynamic features\n'
@@ -3099,15 +3431,15 @@ topics = {'assert': '\n'
                      'in conjunction with nested scopes that contain free '
                      'variables.\n'
                      '\n'
-                     'If a variable is referenced in an enclosing scope, it '
-                     'is illegal to\n'
+                     'If a variable is referenced in an enclosing scope, it is '
+                     'illegal to\n'
                      'delete the name.  An error will be reported at compile '
                      'time.\n'
                      '\n'
                      'If the wild card form of import --- "import *" --- is '
                      'used in a\n'
-                     'function and the function contains or is a nested '
-                     'block with free\n'
+                     'function and the function contains or is a nested block '
+                     'with free\n'
                      'variables, the compiler will raise a "SyntaxError".\n'
                      '\n'
                      'If "exec" is used in a function and the function '
@@ -3120,10 +3452,10 @@ topics = {'assert': '\n'
                      'illegal, but\n'
                      '"exec obj in ns" would be legal.)\n'
                      '\n'
-                     'The "eval()", "execfile()", and "input()" functions '
-                     'and the "exec"\n'
-                     'statement do not have access to the full environment '
-                     'for resolving\n'
+                     'The "eval()", "execfile()", and "input()" functions and '
+                     'the "exec"\n'
+                     'statement do not have access to the full environment for '
+                     'resolving\n'
                      'names.  Names may be resolved in the local and global '
                      'namespaces of\n'
                      'the caller.  Free variables are not resolved in the '
@@ -3149,10 +3481,8 @@ topics = {'assert': '\n'
          'one\n'
          'by one until one is found to be true (see section Boolean '
          'operations\n'
-         'for the definition of true and false); then that suite is '
-         'executed\n'
-         '(and no other part of the "if" statement is executed or '
-         'evaluated).\n'
+         'for the definition of true and false); then that suite is executed\n'
+         '(and no other part of the "if" statement is executed or evaluated).\n'
          'If all expressions are false, the suite of the "else" clause, if\n'
          'present, is executed.\n',
  'exceptions': '\n'
@@ -3165,20 +3495,19 @@ topics = {'assert': '\n'
                'exceptional\n'
                'conditions.  An exception is *raised* at the point where the '
                'error is\n'
-               'detected; it may be *handled* by the surrounding code block '
-               'or by any\n'
-               'code block that directly or indirectly invoked the code '
-               'block where\n'
+               'detected; it may be *handled* by the surrounding code block or '
+               'by any\n'
+               'code block that directly or indirectly invoked the code block '
+               'where\n'
                'the error occurred.\n'
                '\n'
                'The Python interpreter raises an exception when it detects a '
                'run-time\n'
-               'error (such as division by zero).  A Python program can '
-               'also\n'
+               'error (such as division by zero).  A Python program can also\n'
                'explicitly raise an exception with the "raise" statement. '
                'Exception\n'
-               'handlers are specified with the "try" ... "except" '
-               'statement.  The\n'
+               'handlers are specified with the "try" ... "except" statement.  '
+               'The\n'
                '"finally" clause of such a statement can be used to specify '
                'cleanup\n'
                'code which does not handle the exception, but is executed '
@@ -3215,22 +3544,22 @@ topics = {'assert': '\n'
                '\n'
                'Exceptions can also be identified by strings, in which case '
                'the\n'
-               '"except" clause is selected by object identity.  An '
-               'arbitrary value\n'
+               '"except" clause is selected by object identity.  An arbitrary '
+               'value\n'
                'can be raised along with the identifying string which can be '
                'passed to\n'
                'the handler.\n'
                '\n'
-               'Note: Messages to exceptions are not part of the Python '
-               'API.  Their\n'
+               'Note: Messages to exceptions are not part of the Python API.  '
+               'Their\n'
                '  contents may change from one version of Python to the next '
                'without\n'
                '  warning and should not be relied on by code which will run '
                'under\n'
                '  multiple versions of the interpreter.\n'
                '\n'
-               'See also the description of the "try" statement in section '
-               'The try\n'
+               'See also the description of the "try" statement in section The '
+               'try\n'
                'statement and "raise" statement in section The raise '
                'statement.\n'
                '\n'
@@ -3245,26 +3574,23 @@ topics = {'assert': '\n'
          'The "exec" statement\n'
          '********************\n'
          '\n'
-         '   exec_stmt ::= "exec" or_expr ["in" expression ["," '
-         'expression]]\n'
+         '   exec_stmt ::= "exec" or_expr ["in" expression ["," expression]]\n'
          '\n'
          'This statement supports dynamic execution of Python code.  The '
          'first\n'
-         'expression should evaluate to either a Unicode string, a '
-         '*Latin-1*\n'
-         'encoded string, an open file object, a code object, or a tuple.  '
-         'If it\n'
+         'expression should evaluate to either a Unicode string, a *Latin-1*\n'
+         'encoded string, an open file object, a code object, or a tuple.  If '
+         'it\n'
          'is a string, the string is parsed as a suite of Python statements\n'
-         'which is then executed (unless a syntax error occurs). [1] If it '
-         'is an\n'
+         'which is then executed (unless a syntax error occurs). [1] If it is '
+         'an\n'
          'open file, the file is parsed until EOF and executed. If it is a '
          'code\n'
          'object, it is simply executed.  For the interpretation of a tuple, '
          'see\n'
          "below.  In all cases, the code that's executed is expected to be "
          'valid\n'
-         'as file input (see section File input).  Be aware that the '
-         '"return"\n'
+         'as file input (see section File input).  Be aware that the "return"\n'
          'and "yield" statements may not be used outside of function '
          'definitions\n'
          'even within the context of code passed to the "exec" statement.\n'
@@ -3274,19 +3600,16 @@ topics = {'assert': '\n'
          'in the current scope.  If only the first expression after "in" is\n'
          'specified, it should be a dictionary, which will be used for both '
          'the\n'
-         'global and the local variables.  If two expressions are given, '
-         'they\n'
+         'global and the local variables.  If two expressions are given, they\n'
          'are used for the global and local variables, respectively. If\n'
          'provided, *locals* can be any mapping object. Remember that at '
          'module\n'
-         'level, globals and locals are the same dictionary. If two '
-         'separate\n'
+         'level, globals and locals are the same dictionary. If two separate\n'
          'objects are given as *globals* and *locals*, the code will be '
          'executed\n'
          'as if it were embedded in a class definition.\n'
          '\n'
-         'The first expression may also be a tuple of length 2 or 3.  In '
-         'this\n'
+         'The first expression may also be a tuple of length 2 or 3.  In this\n'
          'case, the optional parts must be omitted.  The form "exec(expr,\n'
          'globals)" is equivalent to "exec expr in globals", while the form\n'
          '"exec(expr, globals, locals)" is equivalent to "exec expr in '
@@ -3298,8 +3621,7 @@ topics = {'assert': '\n'
          'Changed in version 2.4: Formerly, *locals* was required to be a\n'
          'dictionary.\n'
          '\n'
-         'As a side effect, an implementation may insert additional keys '
-         'into\n'
+         'As a side effect, an implementation may insert additional keys into\n'
          'the dictionaries given besides those corresponding to variable '
          'names\n'
          'set by the executed code.  For example, the current implementation '
@@ -3313,8 +3635,7 @@ topics = {'assert': '\n'
          'by the built-in function "eval()".  The built-in functions '
          '"globals()"\n'
          'and "locals()" return the current global and local dictionary,\n'
-         'respectively, which may be useful to pass around for use by '
-         '"exec".\n'
+         'respectively, which may be useful to pass around for use by "exec".\n'
          '\n'
          '-[ Footnotes ]-\n'
          '\n'
@@ -3339,10 +3660,10 @@ topics = {'assert': '\n'
               'function block\n'
               'containing the use.\n'
               '\n'
-              'A *block* is a piece of Python program text that is executed '
-              'as a\n'
-              'unit. The following are blocks: a module, a function body, '
-              'and a class\n'
+              'A *block* is a piece of Python program text that is executed as '
+              'a\n'
+              'unit. The following are blocks: a module, a function body, and '
+              'a class\n'
               'definition. Each command typed interactively is a block.  A '
               'script\n'
               'file (a file given as standard input to the interpreter or '
@@ -3369,12 +3690,12 @@ topics = {'assert': '\n'
               'execution has\n'
               'completed.\n'
               '\n'
-              'A *scope* defines the visibility of a name within a block.  '
-              'If a local\n'
-              'variable is defined in a block, its scope includes that '
-              'block.  If the\n'
-              'definition occurs in a function block, the scope extends to '
-              'any blocks\n'
+              'A *scope* defines the visibility of a name within a block.  If '
+              'a local\n'
+              'variable is defined in a block, its scope includes that block.  '
+              'If the\n'
+              'definition occurs in a function block, the scope extends to any '
+              'blocks\n'
               'contained within the defining one, unless a contained block '
               'introduces\n'
               'a different binding for the name.  The scope of names defined '
@@ -3393,8 +3714,8 @@ topics = {'assert': '\n'
               '\n'
               'When a name is used in a code block, it is resolved using the '
               'nearest\n'
-              'enclosing scope.  The set of all such scopes visible to a '
-              'code block\n'
+              'enclosing scope.  The set of all such scopes visible to a code '
+              'block\n'
               "is called the block's *environment*.\n"
               '\n'
               'If a name is bound in a block, it is a local variable of that '
@@ -3403,30 +3724,30 @@ topics = {'assert': '\n'
               'variable.  (The\n'
               'variables of the module code block are local and global.)  If '
               'a\n'
-              'variable is used in a code block but not defined there, it is '
-              '*free\n'
+              'variable is used in a code block but not defined there, it is '
+              '*free\n'
               'variable*.\n'
               '\n'
               'When a name is not found at all, a "NameError" exception is '
               'raised.\n'
-              'If the name refers to a local variable that has not been '
-              'bound, a\n'
+              'If the name refers to a local variable that has not been bound, '
+              'a\n'
               '"UnboundLocalError" exception is raised.  "UnboundLocalError" '
               'is a\n'
               'subclass of "NameError".\n'
               '\n'
               'The following constructs bind names: formal parameters to '
               'functions,\n'
-              '"import" statements, class and function definitions (these '
-              'bind the\n'
-              'class or function name in the defining block), and targets '
-              'that are\n'
+              '"import" statements, class and function definitions (these bind '
+              'the\n'
+              'class or function name in the defining block), and targets that '
+              'are\n'
               'identifiers if occurring in an assignment, "for" loop header, '
               'in the\n'
-              'second position of an "except" clause header or after "as" in '
-              '"with"\n'
-              'statement.  The "import" statement of the form "from ... '
-              'import *"\n'
+              'second position of an "except" clause header or after "as" in '
+              '"with"\n'
+              'statement.  The "import" statement of the form "from ... import '
+              '*"\n'
               'binds all names defined in the imported module, except those '
               'beginning\n'
               'with an underscore.  This form may only be used at the module '
@@ -3436,8 +3757,8 @@ topics = {'assert': '\n'
               'bound for\n'
               'this purpose (though the actual semantics are to unbind the '
               'name).  It\n'
-              'is illegal to unbind a name that is referenced by an '
-              'enclosing scope;\n'
+              'is illegal to unbind a name that is referenced by an enclosing '
+              'scope;\n'
               'the compiler will report a "SyntaxError".\n'
               '\n'
               'Each assignment or import statement occurs within a block '
@@ -3448,8 +3769,8 @@ topics = {'assert': '\n'
               '\n'
               'If a name binding operation occurs anywhere within a code '
               'block, all\n'
-              'uses of the name within the block are treated as references '
-              'to the\n'
+              'uses of the name within the block are treated as references to '
+              'the\n'
               'current block.  This can lead to errors when a name is used '
               'within a\n'
               'block before it is bound. This rule is subtle.  Python lacks\n'
@@ -3461,26 +3782,26 @@ topics = {'assert': '\n'
               'binding\n'
               'operations.\n'
               '\n'
-              'If the global statement occurs within a block, all uses of '
-              'the name\n'
-              'specified in the statement refer to the binding of that name '
-              'in the\n'
+              'If the global statement occurs within a block, all uses of the '
+              'name\n'
+              'specified in the statement refer to the binding of that name in '
+              'the\n'
               'top-level namespace. Names are resolved in the top-level '
               'namespace by\n'
               'searching the global namespace, i.e. the namespace of the '
               'module\n'
               'containing the code block, and the builtins namespace, the '
               'namespace\n'
-              'of the module "__builtin__".  The global namespace is '
-              'searched first.\n'
+              'of the module "__builtin__".  The global namespace is searched '
+              'first.\n'
               'If the name is not found there, the builtins namespace is '
               'searched.\n'
               'The global statement must precede all uses of the name.\n'
               '\n'
-              'The builtins namespace associated with the execution of a '
-              'code block\n'
-              'is actually found by looking up the name "__builtins__" in '
-              'its global\n'
+              'The builtins namespace associated with the execution of a code '
+              'block\n'
+              'is actually found by looking up the name "__builtins__" in its '
+              'global\n'
               'namespace; this should be a dictionary or a module (in the '
               'latter case\n'
               "the module's dictionary is used).  By default, when in the "
@@ -3489,8 +3810,8 @@ topics = {'assert': '\n'
               '(note: no\n'
               '\'s\'); when in any other module, "__builtins__" is an alias '
               'for the\n'
-              'dictionary of the "__builtin__" module itself.  '
-              '"__builtins__" can be\n'
+              'dictionary of the "__builtin__" module itself.  "__builtins__" '
+              'can be\n'
               'set to a user-created dictionary to create a weak form of '
               'restricted\n'
               'execution.\n'
@@ -3500,8 +3821,7 @@ topics = {'assert': '\n'
               'Users\n'
               'wanting to override values in the builtins namespace should '
               '"import"\n'
-              'the "__builtin__" (no \'s\') module and modify its '
-              'attributes\n'
+              'the "__builtin__" (no \'s\') module and modify its attributes\n'
               'appropriately.\n'
               '\n'
               'The namespace for a module is automatically created the first '
@@ -3514,17 +3834,17 @@ topics = {'assert': '\n'
               'operation\n'
               'in the same block.  If the nearest enclosing scope for a free '
               'variable\n'
-              'contains a global statement, the free variable is treated as '
-              'global.\n'
+              'contains a global statement, the free variable is treated as '
+              'global.\n'
               '\n'
-              'A class definition is an executable statement that may use '
-              'and define\n'
+              'A class definition is an executable statement that may use and '
+              'define\n'
               'names. These references follow the normal rules for name '
               'resolution.\n'
               'The namespace of the class definition becomes the attribute '
               'dictionary\n'
-              'of the class.  Names defined at the class scope are not '
-              'visible in\n'
+              'of the class.  Names defined at the class scope are not visible '
+              'in\n'
               'methods.\n'
               '\n'
               '\n'
@@ -3533,8 +3853,7 @@ topics = {'assert': '\n'
               '\n'
               'There are several cases where Python statements are illegal '
               'when used\n'
-              'in conjunction with nested scopes that contain free '
-              'variables.\n'
+              'in conjunction with nested scopes that contain free variables.\n'
               '\n'
               'If a variable is referenced in an enclosing scope, it is '
               'illegal to\n'
@@ -3546,13 +3865,13 @@ topics = {'assert': '\n'
               'free\n'
               'variables, the compiler will raise a "SyntaxError".\n'
               '\n'
-              'If "exec" is used in a function and the function contains or '
-              'is a\n'
+              'If "exec" is used in a function and the function contains or is '
+              'a\n'
               'nested block with free variables, the compiler will raise a\n'
               '"SyntaxError" unless the exec explicitly specifies the local '
               'namespace\n'
-              'for the "exec".  (In other words, "exec obj" would be '
-              'illegal, but\n'
+              'for the "exec".  (In other words, "exec obj" would be illegal, '
+              'but\n'
               '"exec obj in ns" would be legal.)\n'
               '\n'
               'The "eval()", "execfile()", and "input()" functions and the '
@@ -3565,10 +3884,10 @@ topics = {'assert': '\n'
               'enclosing\n'
               'namespace, but in the global namespace. [1] The "exec" '
               'statement and\n'
-              'the "eval()" and "execfile()" functions have optional '
-              'arguments to\n'
-              'override the global and local namespace.  If only one '
-              'namespace is\n'
+              'the "eval()" and "execfile()" functions have optional arguments '
+              'to\n'
+              'override the global and local namespace.  If only one namespace '
+              'is\n'
               'specified, it is used for both.\n'
               '\n'
               '\n'
@@ -3577,12 +3896,11 @@ topics = {'assert': '\n'
               '\n'
               'Exceptions are a means of breaking out of the normal flow of '
               'control\n'
-              'of a code block in order to handle errors or other '
-              'exceptional\n'
+              'of a code block in order to handle errors or other exceptional\n'
               'conditions.  An exception is *raised* at the point where the '
               'error is\n'
-              'detected; it may be *handled* by the surrounding code block '
-              'or by any\n'
+              'detected; it may be *handled* by the surrounding code block or '
+              'by any\n'
               'code block that directly or indirectly invoked the code block '
               'where\n'
               'the error occurred.\n'
@@ -3592,8 +3910,8 @@ topics = {'assert': '\n'
               'error (such as division by zero).  A Python program can also\n'
               'explicitly raise an exception with the "raise" statement. '
               'Exception\n'
-              'handlers are specified with the "try" ... "except" '
-              'statement.  The\n'
+              'handlers are specified with the "try" ... "except" statement.  '
+              'The\n'
               '"finally" clause of such a statement can be used to specify '
               'cleanup\n'
               'code which does not handle the exception, but is executed '
@@ -3602,12 +3920,12 @@ topics = {'assert': '\n'
               '\n'
               'Python uses the "termination" model of error handling: an '
               'exception\n'
-              'handler can find out what happened and continue execution at '
-              'an outer\n'
+              'handler can find out what happened and continue execution at an '
+              'outer\n'
               'level, but it cannot repair the cause of the error and retry '
               'the\n'
-              'failing operation (except by re-entering the offending piece '
-              'of code\n'
+              'failing operation (except by re-entering the offending piece of '
+              'code\n'
               'from the top).\n'
               '\n'
               'When an exception is not handled at all, the interpreter '
@@ -3644,8 +3962,8 @@ topics = {'assert': '\n'
               'under\n'
               '  multiple versions of the interpreter.\n'
               '\n'
-              'See also the description of the "try" statement in section '
-              'The try\n'
+              'See also the description of the "try" statement in section The '
+              'try\n'
               'statement and "raise" statement in section The raise '
               'statement.\n'
               '\n'
@@ -3664,8 +3982,8 @@ topics = {'assert': '\n'
               '\n'
               'An expression list containing at least one comma yields a '
               'tuple.  The\n'
-              'length of the tuple is the number of expressions in the '
-              'list.  The\n'
+              'length of the tuple is the number of expressions in the list.  '
+              'The\n'
               'expressions are evaluated from left to right.\n'
               '\n'
               'The trailing comma is required only to create a single tuple '
@@ -3681,8 +3999,7 @@ topics = {'assert': '\n'
              'Floating point literals\n'
              '***********************\n'
              '\n'
-             'Floating point literals are described by the following '
-             'lexical\n'
+             'Floating point literals are described by the following lexical\n'
              'definitions:\n'
              '\n'
              '   floatnumber   ::= pointfloat | exponentfloat\n'
@@ -3698,16 +4015,15 @@ topics = {'assert': '\n'
              'For\n'
              'example, "077e010" is legal, and denotes the same number as '
              '"77e10".\n'
-             'The allowed range of floating point literals is '
-             'implementation-\n'
+             'The allowed range of floating point literals is implementation-\n'
              'dependent. Some examples of floating point literals:\n'
              '\n'
              '   3.14    10.    .001    1e100    3.14e-10    0e0\n'
              '\n'
-             'Note that numeric literals do not include a sign; a phrase '
-             'like "-1"\n'
-             'is actually an expression composed of the unary operator "-" '
-             'and the\n'
+             'Note that numeric literals do not include a sign; a phrase like '
+             '"-1"\n'
+             'is actually an expression composed of the unary operator "-" and '
+             'the\n'
              'literal "1".\n',
  'for': '\n'
         'The "for" statement\n'
@@ -3724,17 +4040,14 @@ topics = {'assert': '\n'
         'object.  An iterator is created for the result of the\n'
         '"expression_list".  The suite is then executed once for each item\n'
         'provided by the iterator, in the order of ascending indices.  Each\n'
-        'item in turn is assigned to the target list using the standard '
-        'rules\n'
-        'for assignments, and then the suite is executed.  When the items '
-        'are\n'
+        'item in turn is assigned to the target list using the standard rules\n'
+        'for assignments, and then the suite is executed.  When the items are\n'
         'exhausted (which is immediately when the sequence is empty), the '
         'suite\n'
         'in the "else" clause, if present, is executed, and the loop\n'
         'terminates.\n'
         '\n'
-        'A "break" statement executed in the first suite terminates the '
-        'loop\n'
+        'A "break" statement executed in the first suite terminates the loop\n'
         'without executing the "else" clause\'s suite.  A "continue" '
         'statement\n'
         'executed in the first suite skips the rest of the suite and '
@@ -3746,21 +4059,17 @@ topics = {'assert': '\n'
         'does\n'
         'not affect the next item assigned to it.\n'
         '\n'
-        'The target list is not deleted when the loop is finished, but if '
-        'the\n'
+        'The target list is not deleted when the loop is finished, but if the\n'
         'sequence is empty, it will not have been assigned to at all by the\n'
         'loop.  Hint: the built-in function "range()" returns a sequence of\n'
         'integers suitable to emulate the effect of Pascal\'s "for i := a to '
         'b\n'
         'do"; e.g., "range(3)" returns the list "[0, 1, 2]".\n'
         '\n'
-        'Note: There is a subtlety when the sequence is being modified by '
-        'the\n'
+        'Note: There is a subtlety when the sequence is being modified by the\n'
         '  loop (this can only occur for mutable sequences, i.e. lists). An\n'
-        '  internal counter is used to keep track of which item is used '
-        'next,\n'
-        '  and this is incremented on each iteration.  When this counter '
-        'has\n'
+        '  internal counter is used to keep track of which item is used next,\n'
+        '  and this is incremented on each iteration.  When this counter has\n'
         '  reached the length of the sequence the loop terminates.  This '
         'means\n'
         '  that if the suite deletes the current (or a previous) item from '
@@ -3769,10 +4078,8 @@ topics = {'assert': '\n'
         'of\n'
         '  the current item which has already been treated).  Likewise, if '
         'the\n'
-        '  suite inserts an item in the sequence before the current item, '
-        'the\n'
-        '  current item will be treated again the next time through the '
-        'loop.\n'
+        '  suite inserts an item in the sequence before the current item, the\n'
+        '  current item will be treated again the next time through the loop.\n'
         '  This can lead to nasty bugs that can be avoided by making a\n'
         '  temporary copy using a slice of the whole sequence, e.g.,\n'
         '\n'
@@ -3792,18 +4099,18 @@ topics = {'assert': '\n'
                   'curly braces\n'
                   '"{}". Anything that is not contained in braces is '
                   'considered literal\n'
-                  'text, which is copied unchanged to the output.  If you '
-                  'need to include\n'
-                  'a brace character in the literal text, it can be escaped '
-                  'by doubling:\n'
+                  'text, which is copied unchanged to the output.  If you need '
+                  'to include\n'
+                  'a brace character in the literal text, it can be escaped by '
+                  'doubling:\n'
                   '"{{" and "}}".\n'
                   '\n'
                   'The grammar for a replacement field is as follows:\n'
                   '\n'
                   '      replacement_field ::= "{" [field_name] ["!" '
                   'conversion] [":" format_spec] "}"\n'
-                  '      field_name        ::= arg_name ("." attribute_name '
-                  '"[" element_index "]")*\n'
+                  '      field_name        ::= arg_name ("." attribute_name '
+                  '"[" element_index "]")*\n'
                   '      arg_name          ::= [identifier | integer]\n'
                   '      attribute_name    ::= identifier\n'
                   '      element_index     ::= integer | index_string\n'
@@ -3813,10 +4120,10 @@ topics = {'assert': '\n'
                   '      format_spec       ::= <described in the next '
                   'section>\n'
                   '\n'
-                  'In less formal terms, the replacement field can start '
-                  'with a\n'
-                  '*field_name* that specifies the object whose value is to '
-                  'be formatted\n'
+                  'In less formal terms, the replacement field can start with '
+                  'a\n'
+                  '*field_name* that specifies the object whose value is to be '
+                  'formatted\n'
                   'and inserted into the output instead of the replacement '
                   'field. The\n'
                   '*field_name* is optionally followed by a  *conversion* '
@@ -3839,39 +4146,39 @@ topics = {'assert': '\n'
                   'are 0, 1, 2,\n'
                   '... in sequence, they can all be omitted (not just some) '
                   'and the\n'
-                  'numbers 0, 1, 2, ... will be automatically inserted in '
-                  'that order.\n'
+                  'numbers 0, 1, 2, ... will be automatically inserted in that '
+                  'order.\n'
                   'Because *arg_name* is not quote-delimited, it is not '
                   'possible to\n'
                   'specify arbitrary dictionary keys (e.g., the strings '
                   '"\'10\'" or\n'
                   '"\':-]\'") within a format string. The *arg_name* can be '
                   'followed by any\n'
-                  'number of index or attribute expressions. An expression '
-                  'of the form\n'
-                  '"\'.name\'" selects the named attribute using '
-                  '"getattr()", while an\n'
+                  'number of index or attribute expressions. An expression of '
+                  'the form\n'
+                  '"\'.name\'" selects the named attribute using "getattr()", '
+                  'while an\n'
                   'expression of the form "\'[index]\'" does an index lookup '
                   'using\n'
                   '"__getitem__()".\n'
                   '\n'
-                  'Changed in version 2.7: The positional argument '
-                  'specifiers can be\n'
+                  'Changed in version 2.7: The positional argument specifiers '
+                  'can be\n'
                   'omitted, so "\'{} {}\'" is equivalent to "\'{0} {1}\'".\n'
                   '\n'
                   'Some simple format string examples:\n'
                   '\n'
-                  '   "First, thou shalt count to {0}" # References first '
+                  '   "First, thou shalt count to {0}"  # References first '
                   'positional argument\n'
-                  '   "Bring me a {}"                  # Implicitly '
+                  '   "Bring me a {}"                   # Implicitly '
                   'references the first positional argument\n'
-                  '   "From {} to {}"                  # Same as "From {0} '
-                  'to {1}"\n'
-                  '   "My quest is {name}"             # References keyword '
+                  '   "From {} to {}"                   # Same as "From {0} to '
+                  '{1}"\n'
+                  '   "My quest is {name}"              # References keyword '
                   "argument 'name'\n"
-                  '   "Weight in tons {0.weight}"      # \'weight\' '
-                  'attribute of first positional arg\n'
-                  '   "Units destroyed: {players[0]}"  # First element of '
+                  '   "Weight in tons {0.weight}"       # \'weight\' attribute '
+                  'of first positional arg\n'
+                  '   "Units destroyed: {players[0]}"   # First element of '
                   "keyword argument 'players'.\n"
                   '\n'
                   'The *conversion* field causes a type coercion before '
@@ -3898,12 +4205,12 @@ topics = {'assert': '\n'
                   '   "Bring out the holy {name!r}"    # Calls repr() on the '
                   'argument first\n'
                   '\n'
-                  'The *format_spec* field contains a specification of how '
-                  'the value\n'
-                  'should be presented, including such details as field '
-                  'width, alignment,\n'
-                  'padding, decimal precision and so on.  Each value type '
-                  'can define its\n'
+                  'The *format_spec* field contains a specification of how the '
+                  'value\n'
+                  'should be presented, including such details as field width, '
+                  'alignment,\n'
+                  'padding, decimal precision and so on.  Each value type can '
+                  'define its\n'
                   'own "formatting mini-language" or interpretation of the '
                   '*format_spec*.\n'
                   '\n'
@@ -3913,15 +4220,16 @@ topics = {'assert': '\n'
                   '\n'
                   'A *format_spec* field can also include nested replacement '
                   'fields\n'
-                  'within it. These nested replacement fields can contain '
-                  'only a field\n'
-                  'name; conversion flags and format specifications are not '
-                  'allowed.  The\n'
-                  'replacement fields within the format_spec are substituted '
-                  'before the\n'
-                  '*format_spec* string is interpreted. This allows the '
-                  'formatting of a\n'
-                  'value to be dynamically specified.\n'
+                  'within it. These nested replacement fields may contain a '
+                  'field name,\n'
+                  'conversion flag and format specification, but deeper '
+                  'nesting is not\n'
+                  'allowed.  The replacement fields within the format_spec '
+                  'are\n'
+                  'substituted before the *format_spec* string is interpreted. '
+                  'This\n'
+                  'allows the formatting of a value to be dynamically '
+                  'specified.\n'
                   '\n'
                   'See the Format examples section for some examples.\n'
                   '\n'
@@ -3929,10 +4237,10 @@ topics = {'assert': '\n'
                   'Format Specification Mini-Language\n'
                   '==================================\n'
                   '\n'
-                  '"Format specifications" are used within replacement '
-                  'fields contained\n'
-                  'within a format string to define how individual values '
-                  'are presented\n'
+                  '"Format specifications" are used within replacement fields '
+                  'contained\n'
+                  'within a format string to define how individual values are '
+                  'presented\n'
                   '(see Format String Syntax).  They can also be passed '
                   'directly to the\n'
                   'built-in "format()" function.  Each formattable type may '
@@ -3941,14 +4249,14 @@ topics = {'assert': '\n'
                   '\n'
                   'Most built-in types implement the following options for '
                   'format\n'
-                  'specifications, although some of the formatting options '
-                  'are only\n'
+                  'specifications, although some of the formatting options are '
+                  'only\n'
                   'supported by the numeric types.\n'
                   '\n'
-                  'A general convention is that an empty format string '
-                  '("""") produces\n'
-                  'the same result as if you had called "str()" on the '
-                  'value. A non-empty\n'
+                  'A general convention is that an empty format string ("""") '
+                  'produces\n'
+                  'the same result as if you had called "str()" on the value. '
+                  'A non-empty\n'
                   'format string typically modifies the result.\n'
                   '\n'
                   'The general form of a *standard format specifier* is:\n'
@@ -3960,18 +4268,22 @@ topics = {'assert': '\n'
                   '   sign        ::= "+" | "-" | " "\n'
                   '   width       ::= integer\n'
                   '   precision   ::= integer\n'
-                  '   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | '
-                  '"F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n'
+                  '   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" '
+                  '| "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n'
                   '\n'
                   'If a valid *align* value is specified, it can be preceded '
                   'by a *fill*\n'
-                  'character that can be any character and defaults to a '
-                  'space if\n'
-                  'omitted. Note that it is not possible to use "{" and "}" '
-                  'as *fill*\n'
-                  'char while using the "str.format()" method; this '
-                  'limitation however\n'
-                  'doesn\'t affect the "format()" function.\n'
+                  'character that can be any character and defaults to a space '
+                  'if\n'
+                  'omitted. It is not possible to use a literal curly brace '
+                  '(""{"" or\n'
+                  '""}"") as the *fill* character when using the '
+                  '"str.format()" method.\n'
+                  'However, it is possible to insert a curly brace with a '
+                  'nested\n'
+                  "replacement field.  This limitation doesn't affect the "
+                  '"format()"\n'
+                  'function.\n'
                   '\n'
                   'The meaning of the various alignment options is as '
                   'follows:\n'
@@ -4001,8 +4313,10 @@ topics = {'assert': '\n'
                   'printing fields   |\n'
                   "   |           | in the form '+000000120'. This alignment "
                   'option is only    |\n'
-                  '   |           | valid for numeric '
-                  'types.                                   |\n'
+                  '   |           | valid for numeric types.  It becomes the '
+                  "default when '0'  |\n"
+                  '   |           | immediately precedes the field '
+                  'width.                      |\n'
                   '   '
                   '+-----------+------------------------------------------------------------+\n'
                   '   | "\'^\'"     | Forces the field to be centered within '
@@ -4030,8 +4344,8 @@ topics = {'assert': '\n'
                   '|\n'
                   '   '
                   '+===========+============================================================+\n'
-                  '   | "\'+\'"     | indicates that a sign should be used '
-                  'for both positive as  |\n'
+                  '   | "\'+\'"     | indicates that a sign should be used for '
+                  'both positive as  |\n'
                   '   |           | well as negative '
                   'numbers.                                  |\n'
                   '   '
@@ -4049,12 +4363,12 @@ topics = {'assert': '\n'
                   '   '
                   '+-----------+------------------------------------------------------------+\n'
                   '\n'
-                  'The "\'#\'" option is only valid for integers, and only '
-                  'for binary,\n'
+                  'The "\'#\'" option is only valid for integers, and only for '
+                  'binary,\n'
                   'octal, or hexadecimal output.  If present, it specifies '
                   'that the\n'
-                  'output will be prefixed by "\'0b\'", "\'0o\'", or '
-                  '"\'0x\'", respectively.\n'
+                  'output will be prefixed by "\'0b\'", "\'0o\'", or "\'0x\'", '
+                  'respectively.\n'
                   '\n'
                   'The "\',\'" option signals the use of a comma for a '
                   'thousands separator.\n'
@@ -4062,27 +4376,28 @@ topics = {'assert': '\n'
                   'presentation type\n'
                   'instead.\n'
                   '\n'
-                  'Changed in version 2.7: Added the "\',\'" option (see '
-                  'also **PEP 378**).\n'
+                  'Changed in version 2.7: Added the "\',\'" option (see also '
+                  '**PEP 378**).\n'
                   '\n'
                   '*width* is a decimal integer defining the minimum field '
                   'width.  If not\n'
                   'specified, then the field width will be determined by the '
                   'content.\n'
                   '\n'
-                  'Preceding the *width* field by a zero ("\'0\'") character '
-                  'enables sign-\n'
-                  'aware zero-padding for numeric types.  This is equivalent '
-                  'to a *fill*\n'
-                  'character of "\'0\'" with an *alignment* type of '
-                  '"\'=\'".\n'
+                  'When no explicit alignment is given, preceding the *width* '
+                  'field by a\n'
+                  'zero ("\'0\'") character enables sign-aware zero-padding '
+                  'for numeric\n'
+                  'types.  This is equivalent to a *fill* character of "\'0\'" '
+                  'with an\n'
+                  '*alignment* type of "\'=\'".\n'
                   '\n'
                   'The *precision* is a decimal number indicating how many '
                   'digits should\n'
                   'be displayed after the decimal point for a floating point '
                   'value\n'
-                  'formatted with "\'f\'" and "\'F\'", or before and after '
-                  'the decimal point\n'
+                  'formatted with "\'f\'" and "\'F\'", or before and after the '
+                  'decimal point\n'
                   'for a floating point value formatted with "\'g\'" or '
                   '"\'G\'".  For non-\n'
                   'number types the field indicates the maximum field size - '
@@ -4103,8 +4418,8 @@ topics = {'assert': '\n'
                   '|\n'
                   '   '
                   '+===========+============================================================+\n'
-                  '   | "\'s\'"     | String format. This is the default '
-                  'type for strings and    |\n'
+                  '   | "\'s\'"     | String format. This is the default type '
+                  'for strings and    |\n'
                   '   |           | may be '
                   'omitted.                                            |\n'
                   '   '
@@ -4137,8 +4452,8 @@ topics = {'assert': '\n'
                   'base 10.            |\n'
                   '   '
                   '+-----------+------------------------------------------------------------+\n'
-                  '   | "\'o\'"     | Octal format. Outputs the number in '
-                  'base 8.                |\n'
+                  '   | "\'o\'"     | Octal format. Outputs the number in base '
+                  '8.                |\n'
                   '   '
                   '+-----------+------------------------------------------------------------+\n'
                   '   | "\'x\'"     | Hex format. Outputs the number in base '
@@ -4170,8 +4485,8 @@ topics = {'assert': '\n'
                   'be formatted\n'
                   'with the floating point presentation types listed below '
                   '(except "\'n\'"\n'
-                  'and None). When doing so, "float()" is used to convert '
-                  'the integer to\n'
+                  'and None). When doing so, "float()" is used to convert the '
+                  'integer to\n'
                   'a floating point number before formatting.\n'
                   '\n'
                   'The available presentation types for floating point and '
@@ -4185,10 +4500,10 @@ topics = {'assert': '\n'
                   '|\n'
                   '   '
                   '+===========+============================================================+\n'
-                  '   | "\'e\'"     | Exponent notation. Prints the number '
-                  'in scientific         |\n'
-                  "   |           | notation using the letter 'e' to "
-                  'indicate the exponent.    |\n'
+                  '   | "\'e\'"     | Exponent notation. Prints the number in '
+                  'scientific         |\n'
+                  "   |           | notation using the letter 'e' to indicate "
+                  'the exponent.    |\n'
                   '   |           | The default precision is '
                   '"6".                              |\n'
                   '   '
@@ -4217,28 +4532,28 @@ topics = {'assert': '\n'
                   'format or in      |\n'
                   '   |           | scientific notation, depending on its '
                   'magnitude.  The      |\n'
-                  '   |           | precise rules are as follows: suppose '
-                  'that the result      |\n'
+                  '   |           | precise rules are as follows: suppose that '
+                  'the result      |\n'
                   '   |           | formatted with presentation type "\'e\'" '
                   'and precision "p-1" |\n'
-                  '   |           | would have exponent "exp".  Then if "-4 '
-                  '<= exp < p", the   |\n'
-                  '   |           | number is formatted with presentation '
-                  'type "\'f\'" and       |\n'
+                  '   |           | would have exponent "exp".  Then if "-4 <= '
+                  'exp < p", the   |\n'
+                  '   |           | number is formatted with presentation type '
+                  '"\'f\'" and       |\n'
                   '   |           | precision "p-1-exp".  Otherwise, the '
                   'number is formatted   |\n'
                   '   |           | with presentation type "\'e\'" and '
                   'precision "p-1". In both  |\n'
                   '   |           | cases insignificant trailing zeros are '
                   'removed from the    |\n'
-                  '   |           | significand, and the decimal point is '
-                  'also removed if      |\n'
+                  '   |           | significand, and the decimal point is also '
+                  'removed if      |\n'
                   '   |           | there are no remaining digits following '
                   'it.  Positive and  |\n'
                   '   |           | negative infinity, positive and negative '
                   'zero, and nans,   |\n'
-                  '   |           | are formatted as "inf", "-inf", "0", '
-                  '"-0" and "nan"        |\n'
+                  '   |           | are formatted as "inf", "-inf", "0", "-0" '
+                  'and "nan"        |\n'
                   '   |           | respectively, regardless of the '
                   'precision.  A precision of |\n'
                   '   |           | "0" is treated as equivalent to a '
@@ -4263,8 +4578,8 @@ topics = {'assert': '\n'
                   'characters.                                      |\n'
                   '   '
                   '+-----------+------------------------------------------------------------+\n'
-                  '   | "\'%\'"     | Percentage. Multiplies the number by '
-                  '100 and displays in   |\n'
+                  '   | "\'%\'"     | Percentage. Multiplies the number by 100 '
+                  'and displays in   |\n'
                   '   |           | fixed ("\'f\'") format, followed by a '
                   'percent sign.          |\n'
                   '   '
@@ -4278,16 +4593,15 @@ topics = {'assert': '\n'
                   'Format examples\n'
                   '===============\n'
                   '\n'
-                  'This section contains examples of the new format syntax '
-                  'and comparison\n'
-                  'with the old "%"-formatting.\n'
+                  'This section contains examples of the "str.format()" syntax '
+                  'and\n'
+                  'comparison with the old "%"-formatting.\n'
                   '\n'
                   'In most of the cases the syntax is similar to the old '
                   '"%"-formatting,\n'
-                  'with the addition of the "{}" and with ":" used instead '
-                  'of "%". For\n'
-                  'example, "\'%03.2f\'" can be translated to '
-                  '"\'{:03.2f}\'".\n'
+                  'with the addition of the "{}" and with ":" used instead of '
+                  '"%". For\n'
+                  'example, "\'%03.2f\'" can be translated to "\'{:03.2f}\'".\n'
                   '\n'
                   'The new format syntax also supports new and different '
                   'options, shown\n'
@@ -4326,8 +4640,8 @@ topics = {'assert': '\n'
                   "   >>> ('The complex number {0} is formed from the real "
                   "part {0.real} '\n"
                   "   ...  'and the imaginary part {0.imag}.').format(c)\n"
-                  "   'The complex number (3-5j) is formed from the real "
-                  "part 3.0 and the imaginary part -5.0.'\n"
+                  "   'The complex number (3-5j) is formed from the real part "
+                  "3.0 and the imaginary part -5.0.'\n"
                   '   >>> class Point(object):\n'
                   '   ...     def __init__(self, x, y):\n'
                   '   ...         self.x, self.y = x, y\n'
@@ -4348,8 +4662,7 @@ topics = {'assert': '\n'
                   '\n'
                   '   >>> "repr() shows quotes: {!r}; str() doesn\'t: '
                   '{!s}".format(\'test1\', \'test2\')\n'
-                  '   "repr() shows quotes: \'test1\'; str() doesn\'t: '
-                  'test2"\n'
+                  '   "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n'
                   '\n'
                   'Aligning the text and specifying a width:\n'
                   '\n'
@@ -4371,8 +4684,8 @@ topics = {'assert': '\n'
                   "   >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space "
                   'for positive numbers\n'
                   "   ' 3.140000; -3.140000'\n"
-                  "   >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only "
-                  "the minus -- same as '{:f}; {:f}'\n"
+                  "   >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the "
+                  "minus -- same as '{:f}; {:f}'\n"
                   "   '3.140000; -3.140000'\n"
                   '\n'
                   'Replacing "%x" and "%o" and converting the value to '
@@ -4447,8 +4760,8 @@ topics = {'assert': '\n'
              '\n'
              '   decorated      ::= decorators (classdef | funcdef)\n'
              '   decorators     ::= decorator+\n'
-             '   decorator      ::= "@" dotted_name ["(" [argument_list '
-             '[","]] ")"] NEWLINE\n'
+             '   decorator      ::= "@" dotted_name ["(" [argument_list [","]] '
+             '")"] NEWLINE\n'
              '   funcdef        ::= "def" funcname "(" [parameter_list] ")" '
              '":" suite\n'
              '   dotted_name    ::= identifier ("." identifier)*\n'
@@ -4461,23 +4774,20 @@ topics = {'assert': '\n'
              '   parameter      ::= identifier | "(" sublist ")"\n'
              '   funcname       ::= identifier\n'
              '\n'
-             'A function definition is an executable statement.  Its '
-             'execution binds\n'
+             'A function definition is an executable statement.  Its execution '
+             'binds\n'
              'the function name in the current local namespace to a function '
              'object\n'
-             '(a wrapper around the executable code for the function).  '
-             'This\n'
+             '(a wrapper around the executable code for the function).  This\n'
              'function object contains a reference to the current global '
              'namespace\n'
-             'as the global namespace to be used when the function is '
-             'called.\n'
+             'as the global namespace to be used when the function is called.\n'
              '\n'
-             'The function definition does not execute the function body; '
-             'this gets\n'
+             'The function definition does not execute the function body; this '
+             'gets\n'
              'executed only when the function is called. [3]\n'
              '\n'
-             'A function definition may be wrapped by one or more '
-             '*decorator*\n'
+             'A function definition may be wrapped by one or more *decorator*\n'
              'expressions. Decorator expressions are evaluated when the '
              'function is\n'
              'defined, in the scope that contains the function definition.  '
@@ -4486,8 +4796,8 @@ topics = {'assert': '\n'
              'object\n'
              'as the only argument. The returned value is bound to the '
              'function name\n'
-             'instead of the function object.  Multiple decorators are '
-             'applied in\n'
+             'instead of the function object.  Multiple decorators are applied '
+             'in\n'
              'nested fashion. For example, the following code:\n'
              '\n'
              '   @f1(arg)\n'
@@ -4507,8 +4817,7 @@ topics = {'assert': '\n'
              '*argument* may\n'
              "be omitted from a call, in which case the parameter's default "
              'value is\n'
-             'substituted.  If a parameter has a default value, all '
-             'following\n'
+             'substituted.  If a parameter has a default value, all following\n'
              'parameters must also have a default value --- this is a '
              'syntactic\n'
              'restriction that is not expressed by the grammar.\n'
@@ -4517,20 +4826,19 @@ topics = {'assert': '\n'
              'definition\n'
              'is executed.**  This means that the expression is evaluated '
              'once, when\n'
-             'the function is defined, and that the same "pre-computed" '
-             'value is\n'
-             'used for each call.  This is especially important to '
-             'understand when a\n'
+             'the function is defined, and that the same "pre-computed" value '
+             'is\n'
+             'used for each call.  This is especially important to understand '
+             'when a\n'
              'default parameter is a mutable object, such as a list or a '
              'dictionary:\n'
              'if the function modifies the object (e.g. by appending an item '
              'to a\n'
              'list), the default value is in effect modified. This is '
              'generally not\n'
-             'what was intended.  A way around this  is to use "None" as '
-             'the\n'
-             'default, and explicitly test for it in the body of the '
-             'function, e.g.:\n'
+             'what was intended.  A way around this  is to use "None" as the\n'
+             'default, and explicitly test for it in the body of the function, '
+             'e.g.:\n'
              '\n'
              '   def whats_on_the_telly(penguin=None):\n'
              '       if penguin is None:\n'
@@ -4538,14 +4846,14 @@ topics = {'assert': '\n'
              '       penguin.append("property of the zoo")\n'
              '       return penguin\n'
              '\n'
-             'Function call semantics are described in more detail in '
-             'section Calls.\n'
+             'Function call semantics are described in more detail in section '
+             'Calls.\n'
              'A function call always assigns values to all parameters '
              'mentioned in\n'
              'the parameter list, either from position arguments, from '
              'keyword\n'
-             'arguments, or from default values.  If the form '
-             '""*identifier"" is\n'
+             'arguments, or from default values.  If the form ""*identifier"" '
+             'is\n'
              'present, it is initialized to a tuple receiving any excess '
              'positional\n'
              'parameters, defaulting to the empty tuple.  If the form\n'
@@ -4555,10 +4863,9 @@ topics = {'assert': '\n'
              'empty\n'
              'dictionary.\n'
              '\n'
-             'It is also possible to create anonymous functions (functions '
-             'not bound\n'
-             'to a name), for immediate use in expressions.  This uses '
-             'lambda\n'
+             'It is also possible to create anonymous functions (functions not '
+             'bound\n'
+             'to a name), for immediate use in expressions.  This uses lambda\n'
              'expressions, described in section Lambdas.  Note that the '
              'lambda\n'
              'expression is merely a shorthand for a simplified function '
@@ -4577,8 +4884,7 @@ topics = {'assert': '\n'
              'function\n'
              'that can be returned or passed around.  Free variables used in '
              'the\n'
-             'nested function can access the local variables of the '
-             'function\n'
+             'nested function can access the local variables of the function\n'
              'containing the def.  See section Naming and binding for '
              'details.\n',
  'global': '\n'
@@ -4596,18 +4902,17 @@ topics = {'assert': '\n'
            'variable without "global", although free variables may refer to\n'
            'globals without being declared global.\n'
            '\n'
-           'Names listed in a "global" statement must not be used in the '
-           'same code\n'
+           'Names listed in a "global" statement must not be used in the same '
+           'code\n'
            'block textually preceding that "global" statement.\n'
            '\n'
            'Names listed in a "global" statement must not be defined as '
            'formal\n'
-           'parameters or in a "for" loop control target, "class" '
-           'definition,\n'
+           'parameters or in a "for" loop control target, "class" definition,\n'
            'function definition, or "import" statement.\n'
            '\n'
-           '**CPython implementation detail:** The current implementation '
-           'does not\n'
+           '**CPython implementation detail:** The current implementation does '
+           'not\n'
            'enforce the latter two restrictions, but programs should not '
            'abuse\n'
            'this freedom, as future implementations may enforce them or '
@@ -4619,12 +4924,11 @@ topics = {'assert': '\n'
            'applies only to code parsed at the same time as the "global"\n'
            'statement. In particular, a "global" statement contained in an '
            '"exec"\n'
-           'statement does not affect the code block *containing* the '
-           '"exec"\n'
-           'statement, and code contained in an "exec" statement is '
-           'unaffected by\n'
-           '"global" statements in the code containing the "exec" '
-           'statement.  The\n'
+           'statement does not affect the code block *containing* the "exec"\n'
+           'statement, and code contained in an "exec" statement is unaffected '
+           'by\n'
+           '"global" statements in the code containing the "exec" statement.  '
+           'The\n'
            'same applies to the "eval()", "execfile()" and "compile()" '
            'functions.\n',
  'id-classes': '\n'
@@ -4640,17 +4944,16 @@ topics = {'assert': '\n'
                '"_*"\n'
                '   Not imported by "from module import *".  The special '
                'identifier "_"\n'
-               '   is used in the interactive interpreter to store the '
-               'result of the\n'
-               '   last evaluation; it is stored in the "__builtin__" '
-               'module.  When\n'
-               '   not in interactive mode, "_" has no special meaning and '
-               'is not\n'
+               '   is used in the interactive interpreter to store the result '
+               'of the\n'
+               '   last evaluation; it is stored in the "__builtin__" module.  '
+               'When\n'
+               '   not in interactive mode, "_" has no special meaning and is '
+               'not\n'
                '   defined. See section The import statement.\n'
                '\n'
                '   Note: The name "_" is often used in conjunction with\n'
-               '     internationalization; refer to the documentation for '
-               'the\n'
+               '     internationalization; refer to the documentation for the\n'
                '     "gettext" module for more information on this '
                'convention.\n'
                '\n'
@@ -4661,8 +4964,8 @@ topics = {'assert': '\n'
                'Current\n'
                '   system names are discussed in the Special method names '
                'section and\n'
-               '   elsewhere.  More will likely be defined in future '
-               'versions of\n'
+               '   elsewhere.  More will likely be defined in future versions '
+               'of\n'
                '   Python.  *Any* use of "__*__" names, in any context, that '
                'does not\n'
                '   follow explicitly documented use, is subject to breakage '
@@ -4674,8 +4977,8 @@ topics = {'assert': '\n'
                'within the\n'
                '   context of a class definition, are re-written to use a '
                'mangled form\n'
-               '   to help avoid name clashes between "private" attributes '
-               'of base and\n'
+               '   to help avoid name clashes between "private" attributes of '
+               'base and\n'
                '   derived classes. See section Identifiers (Names).\n',
  'identifiers': '\n'
                 'Identifiers and keywords\n'
@@ -4718,8 +5021,8 @@ topics = {'assert': '\n'
                 'is not a keyword, you cannot assign a different object to '
                 'it.\n'
                 '\n'
-                'Changed in version 2.5: Using "as" and "with" as '
-                'identifiers triggers\n'
+                'Changed in version 2.5: Using "as" and "with" as identifiers '
+                'triggers\n'
                 'a warning.  To use them as keywords, enable the '
                 '"with_statement"\n'
                 'future feature .\n'
@@ -4739,12 +5042,12 @@ topics = {'assert': '\n'
                 '"_*"\n'
                 '   Not imported by "from module import *".  The special '
                 'identifier "_"\n'
-                '   is used in the interactive interpreter to store the '
-                'result of the\n'
+                '   is used in the interactive interpreter to store the result '
+                'of the\n'
                 '   last evaluation; it is stored in the "__builtin__" '
                 'module.  When\n'
-                '   not in interactive mode, "_" has no special meaning and '
-                'is not\n'
+                '   not in interactive mode, "_" has no special meaning and is '
+                'not\n'
                 '   defined. See section The import statement.\n'
                 '\n'
                 '   Note: The name "_" is often used in conjunction with\n'
@@ -4756,14 +5059,14 @@ topics = {'assert': '\n'
                 '"__*__"\n'
                 '   System-defined names. These names are defined by the '
                 'interpreter\n'
-                '   and its implementation (including the standard '
-                'library).  Current\n'
+                '   and its implementation (including the standard library).  '
+                'Current\n'
                 '   system names are discussed in the Special method names '
                 'section and\n'
-                '   elsewhere.  More will likely be defined in future '
-                'versions of\n'
-                '   Python.  *Any* use of "__*__" names, in any context, '
-                'that does not\n'
+                '   elsewhere.  More will likely be defined in future versions '
+                'of\n'
+                '   Python.  *Any* use of "__*__" names, in any context, that '
+                'does not\n'
                 '   follow explicitly documented use, is subject to breakage '
                 'without\n'
                 '   warning.\n'
@@ -4773,8 +5076,8 @@ topics = {'assert': '\n'
                 'within the\n'
                 '   context of a class definition, are re-written to use a '
                 'mangled form\n'
-                '   to help avoid name clashes between "private" attributes '
-                'of base and\n'
+                '   to help avoid name clashes between "private" attributes of '
+                'base and\n'
                 '   derived classes. See section Identifiers (Names).\n',
  'if': '\n'
        'The "if" statement\n'
@@ -4788,8 +5091,7 @@ topics = {'assert': '\n'
        '\n'
        'It selects exactly one of the suites by evaluating the expressions '
        'one\n'
-       'by one until one is found to be true (see section Boolean '
-       'operations\n'
+       'by one until one is found to be true (see section Boolean operations\n'
        'for the definition of true and false); then that suite is executed\n'
        '(and no other part of the "if" statement is executed or evaluated).\n'
        'If all expressions are false, the suite of the "else" clause, if\n'
@@ -4809,8 +5111,8 @@ topics = {'assert': '\n'
               'numbers\n'
               'and have the same restrictions on their range.  To create a '
               'complex\n'
-              'number with a nonzero real part, add a floating point number '
-              'to it,\n'
+              'number with a nonzero real part, add a floating point number to '
+              'it,\n'
               'e.g., "(3+4j)".  Some examples of imaginary literals:\n'
               '\n'
               '   3.14j   10.j    10j     .001j   1e100j  3.14e-10j\n',
@@ -4835,8 +5137,7 @@ topics = {'assert': '\n'
            'and\n'
            'initialize it if necessary; (2) define a name or names in the '
            'local\n'
-           'namespace (of the scope where the "import" statement occurs). '
-           'The\n'
+           'namespace (of the scope where the "import" statement occurs). The\n'
            'statement comes in two forms differing on whether it uses the '
            '"from"\n'
            'keyword. The first form (without "from") repeats these steps for '
@@ -4845,37 +5146,33 @@ topics = {'assert': '\n'
            'once,\n'
            'and then performs step (2) repeatedly.\n'
            '\n'
-           'To understand how step (1) occurs, one must first understand '
-           'how\n'
+           'To understand how step (1) occurs, one must first understand how\n'
            'Python handles hierarchical naming of modules. To help organize\n'
            'modules and provide a hierarchy in naming, Python has a concept '
            'of\n'
-           'packages. A package can contain other packages and modules '
-           'while\n'
+           'packages. A package can contain other packages and modules while\n'
            'modules cannot contain other modules or packages. From a file '
            'system\n'
            'perspective, packages are directories and modules are files.\n'
            '\n'
-           'Once the name of the module is known (unless otherwise '
-           'specified, the\n'
-           'term "module" will refer to both packages and modules), '
-           'searching for\n'
+           'Once the name of the module is known (unless otherwise specified, '
+           'the\n'
+           'term "module" will refer to both packages and modules), searching '
+           'for\n'
            'the module or package can begin. The first place checked is\n'
            '"sys.modules", the cache of all modules that have been imported\n'
            'previously. If the module is found there then it is used in step '
            '(2)\n'
            'of import.\n'
            '\n'
-           'If the module is not found in the cache, then "sys.meta_path" '
-           'is\n'
+           'If the module is not found in the cache, then "sys.meta_path" is\n'
            'searched (the specification for "sys.meta_path" can be found in '
            '**PEP\n'
-           '302**). The object is a list of *finder* objects which are '
-           'queried in\n'
+           '302**). The object is a list of *finder* objects which are queried '
+           'in\n'
            'order as to whether they know how to load the module by calling '
            'their\n'
-           '"find_module()" method with the name of the module. If the '
-           'module\n'
+           '"find_module()" method with the name of the module. If the module\n'
            'happens to be contained within a package (as denoted by the '
            'existence\n'
            'of a dot in the name), then a second argument to "find_module()" '
@@ -4883,39 +5180,35 @@ topics = {'assert': '\n'
            'given as the value of the "__path__" attribute from the parent '
            'package\n'
            '(everything up to the last dot in the name of the module being\n'
-           'imported). If a finder can find the module it returns a '
-           '*loader*\n'
+           'imported). If a finder can find the module it returns a *loader*\n'
            '(discussed later) or returns "None".\n'
            '\n'
            'If none of the finders on "sys.meta_path" are able to find the '
            'module\n'
-           'then some implicitly defined finders are queried. '
-           'Implementations of\n'
+           'then some implicitly defined finders are queried. Implementations '
+           'of\n'
            'Python vary in what implicit meta path finders are defined. The '
            'one\n'
-           'they all do define, though, is one that handles '
-           '"sys.path_hooks",\n'
+           'they all do define, though, is one that handles "sys.path_hooks",\n'
            '"sys.path_importer_cache", and "sys.path".\n'
            '\n'
            'The implicit finder searches for the requested module in the '
            '"paths"\n'
            'specified in one of two places ("paths" do not have to be file '
            'system\n'
-           'paths). If the module being imported is supposed to be '
-           'contained\n'
+           'paths). If the module being imported is supposed to be contained\n'
            'within a package then the second argument passed to '
            '"find_module()",\n'
-           '"__path__" on the parent package, is used as the source of '
-           'paths. If\n'
+           '"__path__" on the parent package, is used as the source of paths. '
+           'If\n'
            'the module is not contained in a package then "sys.path" is used '
            'as\n'
            'the source of paths.\n'
            '\n'
-           'Once the source of paths is chosen it is iterated over to find '
-           'a\n'
+           'Once the source of paths is chosen it is iterated over to find a\n'
            'finder that can handle that path. The dict at\n'
-           '"sys.path_importer_cache" caches finders for paths and is '
-           'checked for\n'
+           '"sys.path_importer_cache" caches finders for paths and is checked '
+           'for\n'
            'a finder. If the path does not have a finder cached then\n'
            '"sys.path_hooks" is searched by calling each object in the list '
            'with a\n'
@@ -4923,8 +5216,7 @@ topics = {'assert': '\n'
            '"ImportError". If a finder is returned then it is cached in\n'
            '"sys.path_importer_cache" and then used for that path entry. If '
            'no\n'
-           'finder can be found but the path exists then a value of "None" '
-           'is\n'
+           'finder can be found but the path exists then a value of "None" is\n'
            'stored in "sys.path_importer_cache" to signify that an implicit, '
            'file-\n'
            'based finder that handles modules stored as individual files '
@@ -4936,22 +5228,21 @@ topics = {'assert': '\n'
            'If no finder can find the module then "ImportError" is raised.\n'
            'Otherwise some finder returned a loader whose "load_module()" '
            'method\n'
-           'is called with the name of the module to load (see **PEP 302** '
-           'for the\n'
+           'is called with the name of the module to load (see **PEP 302** for '
+           'the\n'
            'original definition of loaders). A loader has several '
            'responsibilities\n'
            'to perform on a module it loads. First, if the module already '
            'exists\n'
-           'in "sys.modules" (a possibility if the loader is called outside '
-           'of the\n'
-           'import machinery) then it is to use that module for '
-           'initialization and\n'
+           'in "sys.modules" (a possibility if the loader is called outside of '
+           'the\n'
+           'import machinery) then it is to use that module for initialization '
+           'and\n'
            'not a new module. But if the module does not exist in '
            '"sys.modules"\n'
-           'then it is to be added to that dict before initialization '
-           'begins. If\n'
-           'an error occurs during loading of the module and it was added '
-           'to\n'
+           'then it is to be added to that dict before initialization begins. '
+           'If\n'
+           'an error occurs during loading of the module and it was added to\n'
            '"sys.modules" it is to be removed from the dict. If an error '
            'occurs\n'
            'but the module was already in "sys.modules" it is left in the '
@@ -4970,70 +5261,66 @@ topics = {'assert': '\n'
            'packages\n'
            'contained within the package being imported. "__package__" is '
            'optional\n'
-           'but should be set to the name of package that contains the '
-           'module or\n'
+           'but should be set to the name of package that contains the module '
+           'or\n'
            'package (the empty string is used for module not contained in a\n'
-           'package). "__loader__" is also optional but should be set to '
-           'the\n'
+           'package). "__loader__" is also optional but should be set to the\n'
            'loader object that is loading the module.\n'
            '\n'
            'If an error occurs during loading then the loader raises '
            '"ImportError"\n'
-           'if some other exception is not already being propagated. '
-           'Otherwise the\n'
+           'if some other exception is not already being propagated. Otherwise '
+           'the\n'
            'loader returns the module that was loaded and initialized.\n'
            '\n'
-           'When step (1) finishes without raising an exception, step (2) '
-           'can\n'
+           'When step (1) finishes without raising an exception, step (2) can\n'
            'begin.\n'
            '\n'
-           'The first form of "import" statement binds the module name in '
-           'the\n'
+           'The first form of "import" statement binds the module name in the\n'
            'local namespace to the module object, and then goes on to import '
            'the\n'
-           'next identifier, if any.  If the module name is followed by '
-           '"as", the\n'
+           'next identifier, if any.  If the module name is followed by "as", '
+           'the\n'
            'name following "as" is used as the local name for the module.\n'
            '\n'
            'The "from" form does not bind the module name: it goes through '
            'the\n'
-           'list of identifiers, looks each one of them up in the module '
-           'found in\n'
-           'step (1), and binds the name in the local namespace to the '
-           'object thus\n'
+           'list of identifiers, looks each one of them up in the module found '
+           'in\n'
+           'step (1), and binds the name in the local namespace to the object '
+           'thus\n'
            'found.  As with the first form of "import", an alternate local '
            'name\n'
-           'can be supplied by specifying ""as" localname".  If a name is '
-           'not\n'
+           'can be supplied by specifying ""as" localname".  If a name is not\n'
            'found, "ImportError" is raised.  If the list of identifiers is\n'
            'replaced by a star ("\'*\'"), all public names defined in the '
            'module are\n'
            'bound in the local namespace of the "import" statement..\n'
            '\n'
-           'The *public names* defined by a module are determined by '
-           'checking the\n'
-           'module\'s namespace for a variable named "__all__"; if defined, '
-           'it must\n'
+           'The *public names* defined by a module are determined by checking '
+           'the\n'
+           'module\'s namespace for a variable named "__all__"; if defined, it '
+           'must\n'
            'be a sequence of strings which are names defined or imported by '
            'that\n'
            'module.  The names given in "__all__" are all considered public '
            'and\n'
            'are required to exist.  If "__all__" is not defined, the set of '
            'public\n'
-           "names includes all names found in the module's namespace which "
-           'do not\n'
+           "names includes all names found in the module's namespace which do "
+           'not\n'
            'begin with an underscore character ("\'_\'"). "__all__" should '
            'contain\n'
            'the entire public API. It is intended to avoid accidentally '
            'exporting\n'
-           'items that are not part of the API (such as library modules '
-           'which were\n'
+           'items that are not part of the API (such as library modules which '
+           'were\n'
            'imported and used within the module).\n'
            '\n'
            'The "from" form with "*" may only occur in a module scope.  If '
            'the\n'
-           'wild card form of import --- "import *" --- is used in a '
-           'function and\n'
+           'wild card form of import --- "import *" --- is used in a function '
+           'and\n'
            'the function contains or is a nested block with free variables, '
            'the\n'
            'compiler will raise a "SyntaxError".\n'
@@ -5046,22 +5333,19 @@ topics = {'assert': '\n'
            'within\n'
            'the same top package without having to mention the package name. '
            'By\n'
-           'using leading dots in the specified module or package after '
-           '"from" you\n'
-           'can specify how high to traverse up the current package '
-           'hierarchy\n'
-           'without specifying exact names. One leading dot means the '
-           'current\n'
-           'package where the module making the import exists. Two dots '
-           'means up\n'
+           'using leading dots in the specified module or package after "from" '
+           'you\n'
+           'can specify how high to traverse up the current package hierarchy\n'
+           'without specifying exact names. One leading dot means the current\n'
+           'package where the module making the import exists. Two dots means '
+           'up\n'
            'one package level. Three dots is up two levels, etc. So if you '
            'execute\n'
            '"from . import mod" from a module in the "pkg" package then you '
            'will\n'
-           'end up importing "pkg.mod". If you execute "from ..subpkg2 '
-           'import mod"\n'
-           'from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". '
-           'The\n'
+           'end up importing "pkg.mod". If you execute "from ..subpkg2 import '
+           'mod"\n'
+           'from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\n'
            'specification for relative imports is contained within **PEP '
            '328**.\n'
            '\n'
@@ -5075,22 +5359,21 @@ topics = {'assert': '\n'
            '\n'
            'A *future statement* is a directive to the compiler that a '
            'particular\n'
-           'module should be compiled using syntax or semantics that will '
-           'be\n'
+           'module should be compiled using syntax or semantics that will be\n'
            'available in a specified future release of Python.  The future\n'
            'statement is intended to ease migration to future versions of '
            'Python\n'
            'that introduce incompatible changes to the language.  It allows '
            'use of\n'
-           'the new features on a per-module basis before the release in '
-           'which the\n'
+           'the new features on a per-module basis before the release in which '
+           'the\n'
            'feature becomes standard.\n'
            '\n'
-           '   future_statement ::= "from" "__future__" "import" feature '
-           '["as" name]\n'
+           '   future_statement ::= "from" "__future__" "import" feature ["as" '
+           'name]\n'
            '                        ("," feature ["as" name])*\n'
-           '                        | "from" "__future__" "import" "(" '
-           'feature ["as" name]\n'
+           '                        | "from" "__future__" "import" "(" feature '
+           '["as" name]\n'
            '                        ("," feature ["as" name])* [","] ")"\n'
            '   feature          ::= identifier\n'
            '   name             ::= identifier\n'
@@ -5115,15 +5398,13 @@ topics = {'assert': '\n'
            'because\n'
            'they are always enabled.\n'
            '\n'
-           'A future statement is recognized and treated specially at '
-           'compile\n'
+           'A future statement is recognized and treated specially at compile\n'
            'time: Changes to the semantics of core constructs are often\n'
            'implemented by generating different code.  It may even be the '
            'case\n'
            'that a new feature introduces new incompatible syntax (such as a '
            'new\n'
-           'reserved word), in which case the compiler may need to parse '
-           'the\n'
+           'reserved word), in which case the compiler may need to parse the\n'
            'module differently.  Such decisions cannot be pushed off until\n'
            'runtime.\n'
            '\n'
@@ -5137,31 +5418,28 @@ topics = {'assert': '\n'
            'statement:\n'
            'there is a standard module "__future__", described later, and it '
            'will\n'
-           'be imported in the usual way at the time the future statement '
-           'is\n'
+           'be imported in the usual way at the time the future statement is\n'
            'executed.\n'
            '\n'
-           'The interesting runtime semantics depend on the specific '
-           'feature\n'
+           'The interesting runtime semantics depend on the specific feature\n'
            'enabled by the future statement.\n'
            '\n'
            'Note that there is nothing special about the statement:\n'
            '\n'
            '   import __future__ [as name]\n'
            '\n'
-           "That is not a future statement; it's an ordinary import "
-           'statement with\n'
+           "That is not a future statement; it's an ordinary import statement "
+           'with\n'
            'no special semantics or syntax restrictions.\n'
            '\n'
            'Code compiled by an "exec" statement or calls to the built-in\n'
-           'functions "compile()" and "execfile()" that occur in a module '
-           '"M"\n'
+           'functions "compile()" and "execfile()" that occur in a module "M"\n'
            'containing a future statement will, by default, use the new  '
            'syntax or\n'
            'semantics associated with the future statement.  This can, '
            'starting\n'
-           'with Python 2.2 be controlled by optional arguments to '
-           '"compile()" ---\n'
+           'with Python 2.2 be controlled by optional arguments to "compile()" '
+           '---\n'
            'see the documentation of that function for details.\n'
            '\n'
            'A future statement typed at an interactive interpreter prompt '
@@ -5169,20 +5447,20 @@ topics = {'assert': '\n'
            'take effect for the rest of the interpreter session.  If an\n'
            'interpreter is started with the "-i" option, is passed a script '
            'name\n'
-           'to execute, and the script includes a future statement, it will '
-           'be in\n'
+           'to execute, and the script includes a future statement, it will be '
+           'in\n'
            'effect in the interactive session started after the script is\n'
            'executed.\n'
            '\n'
-           'See also: **PEP 236** - Back to the __future__\n'
+           'See also:\n'
            '\n'
+           '  **PEP 236** - Back to the __future__\n'
            '     The original proposal for the __future__ mechanism.\n',
  'in': '\n'
        'Comparisons\n'
        '***********\n'
        '\n'
-       'Unlike C, all comparison operations in Python have the same '
-       'priority,\n'
+       'Unlike C, all comparison operations in Python have the same priority,\n'
        'which is lower than that of any arithmetic, shifting or bitwise\n'
        'operation.  Also unlike C, expressions like "a < b < c" have the\n'
        'interpretation that is conventional in mathematics:\n'
@@ -5198,12 +5476,9 @@ topics = {'assert': '\n'
        'once (but in both cases "z" is not evaluated at all when "x < y" is\n'
        'found to be false).\n'
        '\n'
-       'Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and '
-       '*op1*,\n'
-       '*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... '
-       'y\n'
-       'opN z" is equivalent to "a op1 b and b op2 c and ... y opN z", '
-       'except\n'
+       'Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n'
+       '*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... y\n'
+       'opN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except\n'
        'that each expression is evaluated at most once.\n'
        '\n'
        'Note that "a op1 b op2 c" doesn\'t imply any kind of comparison '
@@ -5211,22 +5486,17 @@ topics = {'assert': '\n'
        '*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\n'
        'perhaps not pretty).\n'
        '\n'
-       'The forms "<>" and "!=" are equivalent; for consistency with C, '
-       '"!="\n'
+       'The forms "<>" and "!=" are equivalent; for consistency with C, "!="\n'
        'is preferred; where "!=" is mentioned below "<>" is also accepted.\n'
        'The "<>" spelling is considered obsolescent.\n'
        '\n'
-       'The operators "<", ">", "==", ">=", "<=", and "!=" compare the '
-       'values\n'
-       'of two objects.  The objects need not have the same type. If both '
-       'are\n'
-       'numbers, they are converted to a common type.  Otherwise, objects '
-       'of\n'
+       'The operators "<", ">", "==", ">=", "<=", and "!=" compare the values\n'
+       'of two objects.  The objects need not have the same type. If both are\n'
+       'numbers, they are converted to a common type.  Otherwise, objects of\n'
        'different types *always* compare unequal, and are ordered '
        'consistently\n'
        'but arbitrarily. You can control comparison behavior of objects of\n'
-       'non-built-in types by defining a "__cmp__" method or rich '
-       'comparison\n'
+       'non-built-in types by defining a "__cmp__" method or rich comparison\n'
        'methods like "__gt__", described in section Special method names.\n'
        '\n'
        '(This unusual definition of comparison was used to simplify the\n'
@@ -5239,14 +5509,12 @@ topics = {'assert': '\n'
        '* Numbers are compared arithmetically.\n'
        '\n'
        '* Strings are compared lexicographically using the numeric\n'
-       '  equivalents (the result of the built-in function "ord()") of '
-       'their\n'
+       '  equivalents (the result of the built-in function "ord()") of their\n'
        '  characters. Unicode and 8-bit strings are fully interoperable in\n'
        '  this behavior. [4]\n'
        '\n'
        '* Tuples and lists are compared lexicographically using comparison\n'
-       '  of corresponding elements.  This means that to compare equal, '
-       'each\n'
+       '  of corresponding elements.  This means that to compare equal, each\n'
        '  element must compare equal and the two sequences must be of the '
        'same\n'
        '  type and have the same length.\n'
@@ -5254,13 +5522,11 @@ topics = {'assert': '\n'
        '  If not equal, the sequences are ordered the same as their first\n'
        '  differing elements.  For example, "cmp([1,2,x], [1,2,y])" returns\n'
        '  the same as "cmp(x,y)".  If the corresponding element does not\n'
-       '  exist, the shorter sequence is ordered first (for example, "[1,2] '
-       '<\n'
+       '  exist, the shorter sequence is ordered first (for example, "[1,2] <\n'
        '  [1,2,3]").\n'
        '\n'
        '* Mappings (dictionaries) compare equal if and only if their sorted\n'
-       '  (key, value) lists compare equal. [5] Outcomes other than '
-       'equality\n'
+       '  (key, value) lists compare equal. [5] Outcomes other than equality\n'
        '  are resolved consistently, but are not otherwise defined. [6]\n'
        '\n'
        '* Most other objects of built-in types compare unequal unless they\n'
@@ -5271,49 +5537,39 @@ topics = {'assert': '\n'
        'The operators "in" and "not in" test for collection membership.  "x '
        'in\n'
        's" evaluates to true if *x* is a member of the collection *s*, and\n'
-       'false otherwise.  "x not in s" returns the negation of "x in s". '
-       'The\n'
-       'collection membership test has traditionally been bound to '
-       'sequences;\n'
-       'an object is a member of a collection if the collection is a '
-       'sequence\n'
-       'and contains an element equal to that object.  However, it make '
-       'sense\n'
-       'for many other object types to support membership tests without '
-       'being\n'
-       'a sequence.  In particular, dictionaries (for keys) and sets '
-       'support\n'
+       'false otherwise.  "x not in s" returns the negation of "x in s". The\n'
+       'collection membership test has traditionally been bound to sequences;\n'
+       'an object is a member of a collection if the collection is a sequence\n'
+       'and contains an element equal to that object.  However, it make sense\n'
+       'for many other object types to support membership tests without being\n'
+       'a sequence.  In particular, dictionaries (for keys) and sets support\n'
        'membership testing.\n'
        '\n'
        'For the list and tuple types, "x in y" is true if and only if there\n'
-       'exists an index *i* such that "x == y[i]" is true.\n'
+       'exists an index *i* such that either "x is y[i]" or "x == y[i]" is\n'
+       'true.\n'
        '\n'
-       'For the Unicode and string types, "x in y" is true if and only if '
-       '*x*\n'
+       'For the Unicode and string types, "x in y" is true if and only if *x*\n'
        'is a substring of *y*.  An equivalent test is "y.find(x) != -1".\n'
        'Note, *x* and *y* need not be the same type; consequently, "u\'ab\' '
        'in\n'
-       '\'abc\'" will return "True". Empty strings are always considered to '
-       'be a\n'
+       '\'abc\'" will return "True". Empty strings are always considered to be '
+       'a\n'
        'substring of any other string, so """ in "abc"" will return "True".\n'
        '\n'
        'Changed in version 2.3: Previously, *x* was required to be a string '
        'of\n'
        'length "1".\n'
        '\n'
-       'For user-defined classes which define the "__contains__()" method, '
-       '"x\n'
+       'For user-defined classes which define the "__contains__()" method, "x\n'
        'in y" is true if and only if "y.__contains__(x)" is true.\n'
        '\n'
-       'For user-defined classes which do not define "__contains__()" but '
-       'do\n'
-       'define "__iter__()", "x in y" is true if some value "z" with "x == '
-       'z"\n'
+       'For user-defined classes which do not define "__contains__()" but do\n'
+       'define "__iter__()", "x in y" is true if some value "z" with "x == z"\n'
        'is produced while iterating over "y".  If an exception is raised\n'
        'during the iteration, it is as if "in" raised that exception.\n'
        '\n'
-       'Lastly, the old-style iteration protocol is tried: if a class '
-       'defines\n'
+       'Lastly, the old-style iteration protocol is tried: if a class defines\n'
        '"__getitem__()", "x in y" is true if and only if there is a non-\n'
        'negative integer index *i* such that "x == y[i]", and all lower\n'
        'integer indices do not raise "IndexError" exception. (If any other\n'
@@ -5322,8 +5578,7 @@ topics = {'assert': '\n'
        'The operator "not in" is defined to have the inverse true value of\n'
        '"in".\n'
        '\n'
-       'The operators "is" and "is not" test for object identity: "x is y" '
-       'is\n'
+       'The operators "is" and "is not" test for object identity: "x is y" is\n'
        'true if and only if *x* and *y* are the same object.  "x is not y"\n'
        'yields the inverse truth value. [7]\n',
  'integers': '\n'
@@ -5335,11 +5590,10 @@ topics = {'assert': '\n'
              'lexical definitions:\n'
              '\n'
              '   longinteger    ::= integer ("l" | "L")\n'
-             '   integer        ::= decimalinteger | octinteger | hexinteger '
-             'bininteger\n'
+             '   integer        ::= decimalinteger | octinteger | hexinteger '
+             'bininteger\n'
              '   decimalinteger ::= nonzerodigit digit* | "0"\n'
-             '   octinteger     ::= "0" ("o" | "O") octdigit+ | "0" '
-             'octdigit+\n'
+             '   octinteger     ::= "0" ("o" | "O") octdigit+ | "0" octdigit+\n'
              '   hexinteger     ::= "0" ("x" | "X") hexdigit+\n'
              '   bininteger     ::= "0" ("b" | "B") bindigit+\n'
              '   nonzerodigit   ::= "1"..."9"\n'
@@ -5351,11 +5605,11 @@ topics = {'assert': '\n'
              'allowed as\n'
              'suffix for long integers, it is strongly recommended to always '
              'use\n'
-             '"\'L\'", since the letter "\'l\'" looks too much like the '
-             'digit "\'1\'".\n'
+             '"\'L\'", since the letter "\'l\'" looks too much like the digit '
+             '"\'1\'".\n'
              '\n'
-             'Plain integer literals that are above the largest '
-             'representable plain\n'
+             'Plain integer literals that are above the largest representable '
+             'plain\n'
              'integer (e.g., 2147483647 when using 32-bit arithmetic) are '
              'accepted\n'
              'as if they were long integers instead. [1]  There is no limit '
@@ -5368,19 +5622,16 @@ topics = {'assert': '\n'
              'literals (second and third rows):\n'
              '\n'
              '   7     2147483647                        0177\n'
-             '   3L    79228162514264337593543950336L    0377L   '
-             '0x100000000L\n'
+             '   3L    79228162514264337593543950336L    0377L   0x100000000L\n'
              '         79228162514264337593543950336             0xdeadbeef\n',
  'lambda': '\n'
            'Lambdas\n'
            '*******\n'
            '\n'
            '   lambda_expr     ::= "lambda" [parameter_list]: expression\n'
-           '   old_lambda_expr ::= "lambda" [parameter_list]: '
-           'old_expression\n'
+           '   old_lambda_expr ::= "lambda" [parameter_list]: old_expression\n'
            '\n'
-           'Lambda expressions (sometimes called lambda forms) have the '
-           'same\n'
+           'Lambda expressions (sometimes called lambda forms) have the same\n'
            'syntactic position as expressions.  They are a shorthand to '
            'create\n'
            'anonymous functions; the expression "lambda arguments: '
@@ -5418,18 +5669,16 @@ topics = {'assert': '\n'
           '\n'
           'A list display yields a new list object.  Its contents are '
           'specified\n'
-          'by providing either a list of expressions or a list '
-          'comprehension.\n'
+          'by providing either a list of expressions or a list comprehension.\n'
           'When a comma-separated list of expressions is supplied, its '
           'elements\n'
           'are evaluated from left to right and placed into the list object '
           'in\n'
-          'that order.  When a list comprehension is supplied, it consists '
-          'of a\n'
+          'that order.  When a list comprehension is supplied, it consists of '
+          'a\n'
           'single expression followed by at least one "for" clause and zero '
           'or\n'
-          'more "for" or "if" clauses.  In this case, the elements of the '
-          'new\n'
+          'more "for" or "if" clauses.  In this case, the elements of the new\n'
           'list are those that would be produced by considering each of the '
           '"for"\n'
           'or "if" clauses a block, nesting from left to right, and '
@@ -5448,8 +5697,7 @@ topics = {'assert': '\n'
            'block\n'
            'containing the use.\n'
            '\n'
-           'A *block* is a piece of Python program text that is executed as '
-           'a\n'
+           'A *block* is a piece of Python program text that is executed as a\n'
            'unit. The following are blocks: a module, a function body, and a '
            'class\n'
            'definition. Each command typed interactively is a block.  A '
@@ -5460,8 +5708,7 @@ topics = {'assert': '\n'
            'block.\n'
            'A script command (a command specified on the interpreter command '
            'line\n'
-           "with the '**-c**' option) is a code block.  The file read by "
-           'the\n'
+           "with the '**-c**' option) is a code block.  The file read by the\n"
            'built-in function "execfile()" is a code block.  The string '
            'argument\n'
            'passed to the built-in function "eval()" and to the "exec" '
@@ -5474,14 +5721,14 @@ topics = {'assert': '\n'
            'contains\n'
            'some administrative information (used for debugging) and '
            'determines\n'
-           "where and how execution continues after the code block's "
-           'execution has\n'
+           "where and how execution continues after the code block's execution "
+           'has\n'
            'completed.\n'
            '\n'
            'A *scope* defines the visibility of a name within a block.  If a '
            'local\n'
-           'variable is defined in a block, its scope includes that block.  '
-           'If the\n'
+           'variable is defined in a block, its scope includes that block.  If '
+           'the\n'
            'definition occurs in a function block, the scope extends to any '
            'blocks\n'
            'contained within the defining one, unless a contained block '
@@ -5492,8 +5739,7 @@ topics = {'assert': '\n'
            'the\n'
            'code blocks of methods -- this includes generator expressions '
            'since\n'
-           'they are implemented using a function scope.  This means that '
-           'the\n'
+           'they are implemented using a function scope.  This means that the\n'
            'following will fail:\n'
            '\n'
            '   class A:\n'
@@ -5508,8 +5754,8 @@ topics = {'assert': '\n'
            '\n'
            'If a name is bound in a block, it is a local variable of that '
            'block.\n'
-           'If a name is bound at the module level, it is a global '
-           'variable.  (The\n'
+           'If a name is bound at the module level, it is a global variable.  '
+           '(The\n'
            'variables of the module code block are local and global.)  If a\n'
            'variable is used in a code block but not defined there, it is a '
            '*free\n'
@@ -5517,8 +5763,7 @@ topics = {'assert': '\n'
            '\n'
            'When a name is not found at all, a "NameError" exception is '
            'raised.\n'
-           'If the name refers to a local variable that has not been bound, '
-           'a\n'
+           'If the name refers to a local variable that has not been bound, a\n'
            '"UnboundLocalError" exception is raised.  "UnboundLocalError" is '
            'a\n'
            'subclass of "NameError".\n'
@@ -5548,8 +5793,8 @@ topics = {'assert': '\n'
            'scope;\n'
            'the compiler will report a "SyntaxError".\n'
            '\n'
-           'Each assignment or import statement occurs within a block '
-           'defined by a\n'
+           'Each assignment or import statement occurs within a block defined '
+           'by a\n'
            'class or function definition or at the module level (the '
            'top-level\n'
            'code block).\n'
@@ -5558,13 +5803,11 @@ topics = {'assert': '\n'
            'all\n'
            'uses of the name within the block are treated as references to '
            'the\n'
-           'current block.  This can lead to errors when a name is used '
-           'within a\n'
+           'current block.  This can lead to errors when a name is used within '
+           'a\n'
            'block before it is bound. This rule is subtle.  Python lacks\n'
-           'declarations and allows name binding operations to occur '
-           'anywhere\n'
-           'within a code block.  The local variables of a code block can '
-           'be\n'
+           'declarations and allows name binding operations to occur anywhere\n'
+           'within a code block.  The local variables of a code block can be\n'
            'determined by scanning the entire text of the block for name '
            'binding\n'
            'operations.\n'
@@ -5573,10 +5816,9 @@ topics = {'assert': '\n'
            'name\n'
            'specified in the statement refer to the binding of that name in '
            'the\n'
-           'top-level namespace. Names are resolved in the top-level '
-           'namespace by\n'
-           'searching the global namespace, i.e. the namespace of the '
-           'module\n'
+           'top-level namespace. Names are resolved in the top-level namespace '
+           'by\n'
+           'searching the global namespace, i.e. the namespace of the module\n'
            'containing the code block, and the builtins namespace, the '
            'namespace\n'
            'of the module "__builtin__".  The global namespace is searched '
@@ -5589,16 +5831,16 @@ topics = {'assert': '\n'
            'block\n'
            'is actually found by looking up the name "__builtins__" in its '
            'global\n'
-           'namespace; this should be a dictionary or a module (in the '
-           'latter case\n'
+           'namespace; this should be a dictionary or a module (in the latter '
+           'case\n'
            "the module's dictionary is used).  By default, when in the "
            '"__main__"\n'
-           'module, "__builtins__" is the built-in module "__builtin__" '
-           '(note: no\n'
+           'module, "__builtins__" is the built-in module "__builtin__" (note: '
+           'no\n'
            '\'s\'); when in any other module, "__builtins__" is an alias for '
            'the\n'
-           'dictionary of the "__builtin__" module itself.  "__builtins__" '
-           'can be\n'
+           'dictionary of the "__builtin__" module itself.  "__builtins__" can '
+           'be\n'
            'set to a user-created dictionary to create a weak form of '
            'restricted\n'
            'execution.\n'
@@ -5610,8 +5852,8 @@ topics = {'assert': '\n'
            'the "__builtin__" (no \'s\') module and modify its attributes\n'
            'appropriately.\n'
            '\n'
-           'The namespace for a module is automatically created the first '
-           'time a\n'
+           'The namespace for a module is automatically created the first time '
+           'a\n'
            'module is imported.  The main module for a script is always '
            'called\n'
            '"__main__".\n'
@@ -5646,12 +5888,10 @@ topics = {'assert': '\n'
            'delete the name.  An error will be reported at compile time.\n'
            '\n'
            'If the wild card form of import --- "import *" --- is used in a\n'
-           'function and the function contains or is a nested block with '
-           'free\n'
+           'function and the function contains or is a nested block with free\n'
            'variables, the compiler will raise a "SyntaxError".\n'
            '\n'
-           'If "exec" is used in a function and the function contains or is '
-           'a\n'
+           'If "exec" is used in a function and the function contains or is a\n'
            'nested block with free variables, the compiler will raise a\n'
            '"SyntaxError" unless the exec explicitly specifies the local '
            'namespace\n'
@@ -5681,14 +5921,13 @@ topics = {'assert': '\n'
             'There are four types of numeric literals: plain integers, long\n'
             'integers, floating point numbers, and imaginary numbers.  There '
             'are no\n'
-            'complex literals (complex numbers can be formed by adding a '
-            'real\n'
+            'complex literals (complex numbers can be formed by adding a real\n'
             'number and an imaginary number).\n'
             '\n'
             'Note that numeric literals do not include a sign; a phrase like '
             '"-1"\n'
-            'is actually an expression composed of the unary operator '
-            '\'"-"\' and the\n'
+            'is actually an expression composed of the unary operator \'"-"\' '
+            'and the\n'
             'literal "1".\n',
  'numeric-types': '\n'
                   'Emulating numeric types\n'
@@ -5696,8 +5935,8 @@ topics = {'assert': '\n'
                   '\n'
                   'The following methods can be defined to emulate numeric '
                   'objects.\n'
-                  'Methods corresponding to operations that are not '
-                  'supported by the\n'
+                  'Methods corresponding to operations that are not supported '
+                  'by the\n'
                   'particular kind of number implemented (e.g., bitwise '
                   'operations for\n'
                   'non-integral numbers) should be left undefined.\n'
@@ -5721,14 +5960,14 @@ topics = {'assert': '\n'
                   '"pow()", "**",\n'
                   '   "<<", ">>", "&", "^", "|").  For instance, to evaluate '
                   'the\n'
-                  '   expression "x + y", where *x* is an instance of a '
-                  'class that has an\n'
+                  '   expression "x + y", where *x* is an instance of a class '
+                  'that has an\n'
                   '   "__add__()" method, "x.__add__(y)" is called.  The '
                   '"__divmod__()"\n'
                   '   method should be the equivalent to using '
                   '"__floordiv__()" and\n'
-                  '   "__mod__()"; it should not be related to '
-                  '"__truediv__()" (described\n'
+                  '   "__mod__()"; it should not be related to "__truediv__()" '
+                  '(described\n'
                   '   below).  Note that "__pow__()" should be defined to '
                   'accept an\n'
                   '   optional third argument if the ternary version of the '
@@ -5737,8 +5976,7 @@ topics = {'assert': '\n'
                   '\n'
                   '   If one of those methods does not support the operation '
                   'with the\n'
-                  '   supplied arguments, it should return '
-                  '"NotImplemented".\n'
+                  '   supplied arguments, it should return "NotImplemented".\n'
                   '\n'
                   'object.__div__(self, other)\n'
                   'object.__truediv__(self, other)\n'
@@ -5749,10 +5987,9 @@ topics = {'assert': '\n'
                   '"__future__.division" is in\n'
                   '   effect, otherwise "__div__()" is used.  If only one of '
                   'these two\n'
-                  '   methods is defined, the object will not support '
-                  'division in the\n'
-                  '   alternate context; "TypeError" will be raised '
-                  'instead.\n'
+                  '   methods is defined, the object will not support division '
+                  'in the\n'
+                  '   alternate context; "TypeError" will be raised instead.\n'
                   '\n'
                   'object.__radd__(self, other)\n'
                   'object.__rsub__(self, other)\n'
@@ -5775,10 +6012,10 @@ topics = {'assert': '\n'
                   '"pow()", "**",\n'
                   '   "<<", ">>", "&", "^", "|") with reflected (swapped) '
                   'operands.\n'
-                  '   These functions are only called if the left operand '
-                  'does not\n'
-                  '   support the corresponding operation and the operands '
-                  'are of\n'
+                  '   These functions are only called if the left operand does '
+                  'not\n'
+                  '   support the corresponding operation and the operands are '
+                  'of\n'
                   '   different types. [2] For instance, to evaluate the '
                   'expression "x -\n'
                   '   y", where *y* is an instance of a class that has an '
@@ -5797,8 +6034,8 @@ topics = {'assert': '\n'
                   'reflected method\n'
                   '     for the operation, this method will be called before '
                   'the left\n'
-                  "     operand's non-reflected method.  This behavior "
-                  'allows subclasses\n'
+                  "     operand's non-reflected method.  This behavior allows "
+                  'subclasses\n'
                   "     to override their ancestors' operations.\n"
                   '\n'
                   'object.__iadd__(self, other)\n'
@@ -5817,10 +6054,10 @@ topics = {'assert': '\n'
                   '\n'
                   '   These methods are called to implement the augmented '
                   'arithmetic\n'
-                  '   assignments ("+=", "-=", "*=", "/=", "//=", "%=", '
-                  '"**=", "<<=",\n'
-                  '   ">>=", "&=", "^=", "|=").  These methods should '
-                  'attempt to do the\n'
+                  '   assignments ("+=", "-=", "*=", "/=", "//=", "%=", "**=", '
+                  '"<<=",\n'
+                  '   ">>=", "&=", "^=", "|=").  These methods should attempt '
+                  'to do the\n'
                   '   operation in-place (modifying *self*) and return the '
                   'result (which\n'
                   '   could be, but does not have to be, *self*).  If a '
@@ -5852,8 +6089,8 @@ topics = {'assert': '\n'
                   'object.__long__(self)\n'
                   'object.__float__(self)\n'
                   '\n'
-                  '   Called to implement the built-in functions '
-                  '"complex()", "int()",\n'
+                  '   Called to implement the built-in functions "complex()", '
+                  '"int()",\n'
                   '   "long()", and "float()".  Should return a value of the '
                   'appropriate\n'
                   '   type.\n'
@@ -5879,8 +6116,8 @@ topics = {'assert': '\n'
                   '\n'
                   '   Called to implement "mixed-mode" numeric arithmetic.  '
                   'Should either\n'
-                  '   return a 2-tuple containing *self* and *other* '
-                  'converted to a\n'
+                  '   return a 2-tuple containing *self* and *other* converted '
+                  'to a\n'
                   '   common numeric type, or "None" if conversion is '
                   'impossible.  When\n'
                   '   the common type would be the type of "other", it is '
@@ -5902,57 +6139,51 @@ topics = {'assert': '\n'
             'Python\n'
             'program is represented by objects or by relations between '
             'objects. (In\n'
-            "a sense, and in conformance to Von Neumann's model of a "
-            '"stored\n'
+            'a sense, and in conformance to Von Neumann\'s model of a "stored\n'
             'program computer," code is also represented by objects.)\n'
             '\n'
             "Every object has an identity, a type and a value.  An object's\n"
-            '*identity* never changes once it has been created; you may '
-            'think of it\n'
+            '*identity* never changes once it has been created; you may think '
+            'of it\n'
             'as the object\'s address in memory.  The \'"is"\' operator '
             'compares the\n'
-            'identity of two objects; the "id()" function returns an '
-            'integer\n'
-            'representing its identity (currently implemented as its '
-            'address). An\n'
+            'identity of two objects; the "id()" function returns an integer\n'
+            'representing its identity (currently implemented as its address). '
+            'An\n'
             "object's *type* is also unchangeable. [1] An object's type "
             'determines\n'
             'the operations that the object supports (e.g., "does it have a\n'
             'length?") and also defines the possible values for objects of '
             'that\n'
-            'type.  The "type()" function returns an object\'s type (which '
-            'is an\n'
+            'type.  The "type()" function returns an object\'s type (which is '
+            'an\n'
             'object itself).  The *value* of some objects can change.  '
             'Objects\n'
             'whose value can change are said to be *mutable*; objects whose '
             'value\n'
             'is unchangeable once they are created are called *immutable*. '
             '(The\n'
-            'value of an immutable container object that contains a '
-            'reference to a\n'
+            'value of an immutable container object that contains a reference '
+            'to a\n'
             "mutable object can change when the latter's value is changed; "
             'however\n'
             'the container is still considered immutable, because the '
             'collection of\n'
-            'objects it contains cannot be changed.  So, immutability is '
-            'not\n'
+            'objects it contains cannot be changed.  So, immutability is not\n'
             'strictly the same as having an unchangeable value, it is more '
             'subtle.)\n'
-            "An object's mutability is determined by its type; for "
-            'instance,\n'
+            "An object's mutability is determined by its type; for instance,\n"
             'numbers, strings and tuples are immutable, while dictionaries '
             'and\n'
             'lists are mutable.\n'
             '\n'
             'Objects are never explicitly destroyed; however, when they '
             'become\n'
-            'unreachable they may be garbage-collected.  An implementation '
-            'is\n'
-            'allowed to postpone garbage collection or omit it altogether '
-            '--- it is\n'
+            'unreachable they may be garbage-collected.  An implementation is\n'
+            'allowed to postpone garbage collection or omit it altogether --- '
+            'it is\n'
             'a matter of implementation quality how garbage collection is\n'
-            'implemented, as long as no objects are collected that are '
-            'still\n'
+            'implemented, as long as no objects are collected that are still\n'
             'reachable.\n'
             '\n'
             '**CPython implementation detail:** CPython currently uses a '
@@ -5960,23 +6191,21 @@ topics = {'assert': '\n'
             'counting scheme with (optional) delayed detection of cyclically '
             'linked\n'
             'garbage, which collects most objects as soon as they become\n'
-            'unreachable, but is not guaranteed to collect garbage '
-            'containing\n'
+            'unreachable, but is not guaranteed to collect garbage containing\n'
             'circular references.  See the documentation of the "gc" module '
             'for\n'
             'information on controlling the collection of cyclic garbage. '
             'Other\n'
             'implementations act differently and CPython may change. Do not '
             'depend\n'
-            'on immediate finalization of objects when they become '
-            'unreachable (ex:\n'
+            'on immediate finalization of objects when they become unreachable '
+            '(ex:\n'
             'always close files).\n'
             '\n'
             "Note that the use of the implementation's tracing or debugging\n"
             'facilities may keep objects alive that would normally be '
             'collectable.\n'
-            'Also note that catching an exception with a '
-            '\'"try"..."except"\'\n'
+            'Also note that catching an exception with a \'"try"..."except"\'\n'
             'statement may keep objects alive.\n'
             '\n'
             'Some objects contain references to "external" resources such as '
@@ -5989,8 +6218,7 @@ topics = {'assert': '\n'
             'way to\n'
             'release the external resource, usually a "close()" method. '
             'Programs\n'
-            'are strongly recommended to explicitly close such objects.  '
-            'The\n'
+            'are strongly recommended to explicitly close such objects.  The\n'
             '\'"try"..."finally"\' statement provides a convenient way to do '
             'this.\n'
             '\n'
@@ -5999,14 +6227,13 @@ topics = {'assert': '\n'
             '*containers*. Examples of containers are tuples, lists and\n'
             "dictionaries.  The references are part of a container's value.  "
             'In\n'
-            'most cases, when we talk about the value of a container, we '
-            'imply the\n'
+            'most cases, when we talk about the value of a container, we imply '
+            'the\n'
             'values, not the identities of the contained objects; however, '
             'when we\n'
-            'talk about the mutability of a container, only the identities '
-            'of the\n'
-            'immediately contained objects are implied.  So, if an '
-            'immutable\n'
+            'talk about the mutability of a container, only the identities of '
+            'the\n'
+            'immediately contained objects are implied.  So, if an immutable\n'
             'container (like a tuple) contains a reference to a mutable '
             'object, its\n'
             'value changes if that mutable object is changed.\n'
@@ -6014,18 +6241,16 @@ topics = {'assert': '\n'
             'Types affect almost all aspects of object behavior.  Even the\n'
             'importance of object identity is affected in some sense: for '
             'immutable\n'
-            'types, operations that compute new values may actually return '
-            'a\n'
+            'types, operations that compute new values may actually return a\n'
             'reference to any existing object with the same type and value, '
             'while\n'
-            'for mutable objects this is not allowed.  E.g., after "a = 1; b '
-            '1",\n'
+            'for mutable objects this is not allowed.  E.g., after "a = 1; b '
+            '1",\n'
             '"a" and "b" may or may not refer to the same object with the '
             'value\n'
-            'one, depending on the implementation, but after "c = []; d = '
-            '[]", "c"\n'
-            'and "d" are guaranteed to refer to two different, unique, '
-            'newly\n'
+            'one, depending on the implementation, but after "c = []; d = []", '
+            '"c"\n'
+            'and "d" are guaranteed to refer to two different, unique, newly\n'
             'created empty lists. (Note that "c = d = []" assigns the same '
             'object\n'
             'to both "c" and "d".)\n',
@@ -6033,8 +6258,8 @@ topics = {'assert': '\n'
                      'Operator precedence\n'
                      '*******************\n'
                      '\n'
-                     'The following table summarizes the operator '
-                     'precedences in Python,\n'
+                     'The following table summarizes the operator precedences '
+                     'in Python,\n'
                      'from lowest precedence (least binding) to highest '
                      'precedence (most\n'
                      'binding). Operators in the same box have the same '
@@ -6043,8 +6268,8 @@ topics = {'assert': '\n'
                      'Operators in\n'
                      'the same box group left to right (except for '
                      'comparisons, including\n'
-                     'tests, which all have the same precedence and chain '
-                     'from left to right\n'
+                     'tests, which all have the same precedence and chain from '
+                     'left to right\n'
                      '--- see section Comparisons --- and exponentiation, '
                      'which groups from\n'
                      'right to left).\n'
@@ -6116,16 +6341,16 @@ topics = {'assert': '\n'
                      '\n'
                      '[1] In Python 2.3 and later releases, a list '
                      'comprehension "leaks"\n'
-                     '    the control variables of each "for" it contains '
-                     'into the\n'
+                     '    the control variables of each "for" it contains into '
+                     'the\n'
                      '    containing scope.  However, this behavior is '
                      'deprecated, and\n'
                      '    relying on it will not work in Python 3.\n'
                      '\n'
                      '[2] While "abs(x%y) < abs(y)" is true mathematically, '
                      'for floats\n'
-                     '    it may not be true numerically due to roundoff.  '
-                     'For example, and\n'
+                     '    it may not be true numerically due to roundoff.  For '
+                     'example, and\n'
                      '    assuming a platform on which a Python float is an '
                      'IEEE 754 double-\n'
                      '    precision number, in order that "-1e-100 % 1e100" '
@@ -6136,8 +6361,8 @@ topics = {'assert': '\n'
                      'function\n'
                      '    "math.fmod()" returns a result whose sign matches '
                      'the sign of the\n'
-                     '    first argument instead, and so returns "-1e-100" '
-                     'in this case.\n'
+                     '    first argument instead, and so returns "-1e-100" in '
+                     'this case.\n'
                      '    Which approach is more appropriate depends on the '
                      'application.\n'
                      '\n'
@@ -6145,16 +6370,16 @@ topics = {'assert': '\n'
                      "y, it's\n"
                      '    possible for "floor(x/y)" to be one larger than '
                      '"(x-x%y)/y" due to\n'
-                     '    rounding.  In such cases, Python returns the '
-                     'latter result, in\n'
-                     '    order to preserve that "divmod(x,y)[0] * y + x % '
-                     'y" be very close\n'
+                     '    rounding.  In such cases, Python returns the latter '
+                     'result, in\n'
+                     '    order to preserve that "divmod(x,y)[0] * y + x % y" '
+                     'be very close\n'
                      '    to "x".\n'
                      '\n'
-                     '[4] While comparisons between unicode strings make '
-                     'sense at the\n'
-                     '    byte level, they may be counter-intuitive to '
-                     'users. For example,\n'
+                     '[4] While comparisons between unicode strings make sense '
+                     'at the\n'
+                     '    byte level, they may be counter-intuitive to users. '
+                     'For example,\n'
                      '    the strings "u"\\u00C7"" and "u"\\u0043\\u0327"" '
                      'compare differently,\n'
                      '    even though they both represent the same unicode '
@@ -6176,22 +6401,22 @@ topics = {'assert': '\n'
                      'earlier version of\n'
                      '    Python compared dictionaries by identity only, but '
                      'this caused\n'
-                     '    surprises because people expected to be able to '
-                     'test a dictionary\n'
+                     '    surprises because people expected to be able to test '
+                     'a dictionary\n'
                      '    for emptiness by comparing it to "{}".\n'
                      '\n'
-                     '[7] Due to automatic garbage-collection, free lists, '
-                     'and the\n'
+                     '[7] Due to automatic garbage-collection, free lists, and '
+                     'the\n'
                      '    dynamic nature of descriptors, you may notice '
                      'seemingly unusual\n'
-                     '    behaviour in certain uses of the "is" operator, '
-                     'like those\n'
+                     '    behaviour in certain uses of the "is" operator, like '
+                     'those\n'
                      '    involving comparisons between instance methods, or '
                      'constants.\n'
                      '    Check their documentation for more info.\n'
                      '\n'
-                     '[8] The "%" operator is also used for string '
-                     'formatting; the same\n'
+                     '[8] The "%" operator is also used for string formatting; '
+                     'the same\n'
                      '    precedence applies.\n'
                      '\n'
                      '[9] The power operator "**" binds less tightly than an '
@@ -6216,40 +6441,34 @@ topics = {'assert': '\n'
           'The power operator\n'
           '******************\n'
           '\n'
-          'The power operator binds more tightly than unary operators on '
-          'its\n'
+          'The power operator binds more tightly than unary operators on its\n'
           'left; it binds less tightly than unary operators on its right.  '
           'The\n'
           'syntax is:\n'
           '\n'
           '   power ::= primary ["**" u_expr]\n'
           '\n'
-          'Thus, in an unparenthesized sequence of power and unary '
-          'operators, the\n'
+          'Thus, in an unparenthesized sequence of power and unary operators, '
+          'the\n'
           'operators are evaluated from right to left (this does not '
           'constrain\n'
           'the evaluation order for the operands): "-1**2" results in "-1".\n'
           '\n'
-          'The power operator has the same semantics as the built-in '
-          '"pow()"\n'
+          'The power operator has the same semantics as the built-in "pow()"\n'
           'function, when called with two arguments: it yields its left '
           'argument\n'
           'raised to the power of its right argument.  The numeric arguments '
           'are\n'
-          'first converted to a common type.  The result type is that of '
-          'the\n'
+          'first converted to a common type.  The result type is that of the\n'
           'arguments after coercion.\n'
           '\n'
-          'With mixed operand types, the coercion rules for binary '
-          'arithmetic\n'
-          'operators apply. For int and long int operands, the result has '
-          'the\n'
+          'With mixed operand types, the coercion rules for binary arithmetic\n'
+          'operators apply. For int and long int operands, the result has the\n'
           'same type as the operands (after coercion) unless the second '
           'argument\n'
-          'is negative; in that case, all arguments are converted to float '
-          'and a\n'
-          'float result is delivered. For example, "10**2" returns "100", '
-          'but\n'
+          'is negative; in that case, all arguments are converted to float and '
+          'a\n'
+          'float result is delivered. For example, "10**2" returns "100", but\n'
           '"10**-2" returns "0.01". (This last feature was added in Python '
           '2.2.\n'
           'In Python 2.1 and before, if both arguments were of integer types '
@@ -6267,17 +6486,15 @@ topics = {'assert': '\n'
           '   print_stmt ::= "print" ([expression ("," expression)* [","]]\n'
           '                  | ">>" expression [("," expression)+ [","]])\n'
           '\n'
-          '"print" evaluates each expression in turn and writes the '
-          'resulting\n'
+          '"print" evaluates each expression in turn and writes the resulting\n'
           'object to standard output (see below).  If an object is not a '
           'string,\n'
           'it is first converted to a string using the rules for string\n'
-          'conversions.  The (resulting or original) string is then '
-          'written.  A\n'
+          'conversions.  The (resulting or original) string is then written.  '
+          'A\n'
           'space is written before each object is (converted and) written, '
           'unless\n'
-          'the output system believes it is positioned at the beginning of '
-          'a\n'
+          'the output system believes it is positioned at the beginning of a\n'
           'line.  This is the case (1) when no characters have yet been '
           'written\n'
           'to standard output, (2) when the last character written to '
@@ -6309,12 +6526,11 @@ topics = {'assert': '\n'
           '\n'
           '"print" also has an extended form, defined by the second portion '
           'of\n'
-          'the syntax described above. This form is sometimes referred to '
-          'as\n'
+          'the syntax described above. This form is sometimes referred to as\n'
           '""print" chevron." In this form, the first expression after the '
           '">>"\n'
-          'must evaluate to a "file-like" object, specifically an object '
-          'that has\n'
+          'must evaluate to a "file-like" object, specifically an object that '
+          'has\n'
           'a "write()" method as described above.  With this extended form, '
           'the\n'
           'subsequent expressions are printed to this file object.  If the '
@@ -6335,12 +6551,11 @@ topics = {'assert': '\n'
           'in\n'
           'the current scope, a "TypeError" exception is raised indicating '
           'that\n'
-          'this is an error (if running under IDLE, a "Queue.Empty" '
-          'exception is\n'
+          'this is an error (if running under IDLE, a "Queue.Empty" exception '
+          'is\n'
           'raised instead).\n'
           '\n'
-          'Otherwise, "raise" evaluates the expressions to get three '
-          'objects,\n'
+          'Otherwise, "raise" evaluates the expressions to get three objects,\n'
           'using "None" as the value of omitted expressions.  The first two\n'
           'objects are used to determine the *type* and *value* of the '
           'exception.\n'
@@ -6354,8 +6569,8 @@ topics = {'assert': '\n'
           'exception.\n'
           'The second object is used to determine the exception value: If it '
           'is\n'
-          'an instance of the class, the instance becomes the exception '
-          'value. If\n'
+          'an instance of the class, the instance becomes the exception value. '
+          'If\n'
           'the second object is a tuple, it is used as the argument list for '
           'the\n'
           'class constructor; if it is "None", an empty argument list is '
@@ -6368,17 +6583,14 @@ topics = {'assert': '\n'
           'If a third object is present and not "None", it must be a '
           'traceback\n'
           'object (see section The standard type hierarchy), and it is\n'
-          'substituted instead of the current location as the place where '
-          'the\n'
+          'substituted instead of the current location as the place where the\n'
           'exception occurred.  If the third object is present and not a\n'
           'traceback object or "None", a "TypeError" exception is raised.  '
           'The\n'
           'three-expression form of "raise" is useful to re-raise an '
           'exception\n'
-          'transparently in an except clause, but "raise" with no '
-          'expressions\n'
-          'should be preferred if the exception to be re-raised was the '
-          'most\n'
+          'transparently in an except clause, but "raise" with no expressions\n'
+          'should be preferred if the exception to be re-raised was the most\n'
           'recently active exception in the current scope.\n'
           '\n'
           'Additional information on exceptions can be found in section\n'
@@ -6395,12 +6607,11 @@ topics = {'assert': '\n'
            'definition,\n'
            'not within a nested class definition.\n'
            '\n'
-           'If an expression list is present, it is evaluated, else "None" '
-           'is\n'
+           'If an expression list is present, it is evaluated, else "None" is\n'
            'substituted.\n'
            '\n'
-           '"return" leaves the current function call with the expression '
-           'list (or\n'
+           '"return" leaves the current function call with the expression list '
+           '(or\n'
            '"None") as return value.\n'
            '\n'
            'When "return" passes control out of a "try" statement with a '
@@ -6409,8 +6620,7 @@ topics = {'assert': '\n'
            'the\n'
            'function.\n'
            '\n'
-           'In a generator function, the "return" statement is not allowed '
-           'to\n'
+           'In a generator function, the "return" statement is not allowed to\n'
            'include an "expression_list".  In that context, a bare "return"\n'
            'indicates that the generator is done and will cause '
            '"StopIteration" to\n'
@@ -6421,28 +6631,26 @@ topics = {'assert': '\n'
                    '\n'
                    'The following methods can be defined to implement '
                    'container objects.\n'
-                   'Containers usually are sequences (such as lists or '
-                   'tuples) or mappings\n'
-                   '(like dictionaries), but can represent other containers '
-                   'as well.  The\n'
-                   'first set of methods is used either to emulate a '
-                   'sequence or to\n'
-                   'emulate a mapping; the difference is that for a '
-                   'sequence, the\n'
-                   'allowable keys should be the integers *k* for which "0 '
-                   '<= k < N" where\n'
-                   '*N* is the length of the sequence, or slice objects, '
-                   'which define a\n'
-                   'range of items. (For backwards compatibility, the '
-                   'method\n'
-                   '"__getslice__()" (see below) can also be defined to '
-                   'handle simple, but\n'
-                   'not extended slices.) It is also recommended that '
-                   'mappings provide the\n'
+                   'Containers usually are sequences (such as lists or tuples) '
+                   'or mappings\n'
+                   '(like dictionaries), but can represent other containers as '
+                   'well.  The\n'
+                   'first set of methods is used either to emulate a sequence '
+                   'or to\n'
+                   'emulate a mapping; the difference is that for a sequence, '
+                   'the\n'
+                   'allowable keys should be the integers *k* for which "0 <= '
+                   'k < N" where\n'
+                   '*N* is the length of the sequence, or slice objects, which '
+                   'define a\n'
+                   'range of items. (For backwards compatibility, the method\n'
+                   '"__getslice__()" (see below) can also be defined to handle '
+                   'simple, but\n'
+                   'not extended slices.) It is also recommended that mappings '
+                   'provide the\n'
                    'methods "keys()", "values()", "items()", "has_key()", '
                    '"get()",\n'
-                   '"clear()", "setdefault()", "iterkeys()", '
-                   '"itervalues()",\n'
+                   '"clear()", "setdefault()", "iterkeys()", "itervalues()",\n'
                    '"iteritems()", "pop()", "popitem()", "copy()", and '
                    '"update()" behaving\n'
                    "similar to those for Python's standard dictionary "
@@ -6455,8 +6663,8 @@ topics = {'assert': '\n'
                    'provide\n'
                    'methods "append()", "count()", "index()", "extend()", '
                    '"insert()",\n'
-                   '"pop()", "remove()", "reverse()" and "sort()", like '
-                   'Python standard\n'
+                   '"pop()", "remove()", "reverse()" and "sort()", like Python '
+                   'standard\n'
                    'list objects.  Finally, sequence types should implement '
                    'addition\n'
                    '(meaning concatenation) and multiplication (meaning '
@@ -6469,8 +6677,8 @@ topics = {'assert': '\n'
                    'operators.  It is\n'
                    'recommended that both mappings and sequences implement '
                    'the\n'
-                   '"__contains__()" method to allow efficient use of the '
-                   '"in" operator;\n'
+                   '"__contains__()" method to allow efficient use of the "in" '
+                   'operator;\n'
                    'for mappings, "in" should be equivalent of "has_key()"; '
                    'for sequences,\n'
                    'it should search through the values.  It is further '
@@ -6487,8 +6695,8 @@ topics = {'assert': '\n'
                    '\n'
                    '   Called to implement the built-in function "len()".  '
                    'Should return\n'
-                   '   the length of the object, an integer ">=" 0.  Also, '
-                   'an object that\n'
+                   '   the length of the object, an integer ">=" 0.  Also, an '
+                   'object that\n'
                    '   doesn\'t define a "__nonzero__()" method and whose '
                    '"__len__()"\n'
                    '   method returns zero is considered to be false in a '
@@ -6500,8 +6708,8 @@ topics = {'assert': '\n'
                    'sequence types,\n'
                    '   the accepted keys should be integers and slice '
                    'objects.  Note that\n'
-                   '   the special interpretation of negative indexes (if '
-                   'the class wishes\n'
+                   '   the special interpretation of negative indexes (if the '
+                   'class wishes\n'
                    '   to emulate a sequence type) is up to the '
                    '"__getitem__()" method. If\n'
                    '   *key* is of an inappropriate type, "TypeError" may be '
@@ -6510,14 +6718,14 @@ topics = {'assert': '\n'
                    '(after any\n'
                    '   special interpretation of negative values), '
                    '"IndexError" should be\n'
-                   '   raised. For mapping types, if *key* is missing (not '
-                   'in the\n'
+                   '   raised. For mapping types, if *key* is missing (not in '
+                   'the\n'
                    '   container), "KeyError" should be raised.\n'
                    '\n'
                    '   Note: "for" loops expect that an "IndexError" will be '
                    'raised for\n'
-                   '     illegal indexes to allow proper detection of the '
-                   'end of the\n'
+                   '     illegal indexes to allow proper detection of the end '
+                   'of the\n'
                    '     sequence.\n'
                    '\n'
                    'object.__missing__(self, key)\n'
@@ -6532,8 +6740,8 @@ topics = {'assert': '\n'
                    'note as for\n'
                    '   "__getitem__()".  This should only be implemented for '
                    'mappings if\n'
-                   '   the objects support changes to the values for keys, '
-                   'or if new keys\n'
+                   '   the objects support changes to the values for keys, or '
+                   'if new keys\n'
                    '   can be added, or for sequences if elements can be '
                    'replaced.  The\n'
                    '   same exceptions should be raised for improper *key* '
@@ -6542,33 +6750,33 @@ topics = {'assert': '\n'
                    '\n'
                    'object.__delitem__(self, key)\n'
                    '\n'
-                   '   Called to implement deletion of "self[key]".  Same '
-                   'note as for\n'
+                   '   Called to implement deletion of "self[key]".  Same note '
+                   'as for\n'
                    '   "__getitem__()".  This should only be implemented for '
                    'mappings if\n'
                    '   the objects support removal of keys, or for sequences '
                    'if elements\n'
-                   '   can be removed from the sequence.  The same '
-                   'exceptions should be\n'
+                   '   can be removed from the sequence.  The same exceptions '
+                   'should be\n'
                    '   raised for improper *key* values as for the '
                    '"__getitem__()" method.\n'
                    '\n'
                    'object.__iter__(self)\n'
                    '\n'
-                   '   This method is called when an iterator is required '
-                   'for a container.\n'
+                   '   This method is called when an iterator is required for '
+                   'a container.\n'
                    '   This method should return a new iterator object that '
                    'can iterate\n'
                    '   over all the objects in the container.  For mappings, '
                    'it should\n'
-                   '   iterate over the keys of the container, and should '
-                   'also be made\n'
+                   '   iterate over the keys of the container, and should also '
+                   'be made\n'
                    '   available as the method "iterkeys()".\n'
                    '\n'
                    '   Iterator objects also need to implement this method; '
                    'they are\n'
-                   '   required to return themselves.  For more information '
-                   'on iterator\n'
+                   '   required to return themselves.  For more information on '
+                   'iterator\n'
                    '   objects, see Iterator Types.\n'
                    '\n'
                    'object.__reversed__(self)\n'
@@ -6582,8 +6790,8 @@ topics = {'assert': '\n'
                    '\n'
                    '   If the "__reversed__()" method is not provided, the '
                    '"reversed()"\n'
-                   '   built-in will fall back to using the sequence '
-                   'protocol ("__len__()"\n'
+                   '   built-in will fall back to using the sequence protocol '
+                   '("__len__()"\n'
                    '   and "__getitem__()").  Objects that support the '
                    'sequence protocol\n'
                    '   should only provide "__reversed__()" if they can '
@@ -6596,21 +6804,21 @@ topics = {'assert': '\n'
                    '\n'
                    'The membership test operators ("in" and "not in") are '
                    'normally\n'
-                   'implemented as an iteration through a sequence.  '
-                   'However, container\n'
+                   'implemented as an iteration through a sequence.  However, '
+                   'container\n'
                    'objects can supply the following special method with a '
                    'more efficient\n'
-                   'implementation, which also does not require the object '
-                   'be a sequence.\n'
+                   'implementation, which also does not require the object be '
+                   'a sequence.\n'
                    '\n'
                    'object.__contains__(self, item)\n'
                    '\n'
-                   '   Called to implement membership test operators.  '
-                   'Should return true\n'
+                   '   Called to implement membership test operators.  Should '
+                   'return true\n'
                    '   if *item* is in *self*, false otherwise.  For mapping '
                    'objects, this\n'
-                   '   should consider the keys of the mapping rather than '
-                   'the values or\n'
+                   '   should consider the keys of the mapping rather than the '
+                   'values or\n'
                    '   the key-item pairs.\n'
                    '\n'
                    '   For objects that don\'t define "__contains__()", the '
@@ -6624,28 +6832,25 @@ topics = {'assert': '\n'
              'Shifting operations\n'
              '*******************\n'
              '\n'
-             'The shifting operations have lower priority than the '
-             'arithmetic\n'
+             'The shifting operations have lower priority than the arithmetic\n'
              'operations:\n'
              '\n'
              '   shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n'
              '\n'
              'These operators accept plain or long integers as arguments.  '
              'The\n'
-             'arguments are converted to a common type.  They shift the '
-             'first\n'
+             'arguments are converted to a common type.  They shift the first\n'
              'argument to the left or right by the number of bits given by '
              'the\n'
              'second argument.\n'
              '\n'
              'A right shift by *n* bits is defined as division by "pow(2, '
              'n)".  A\n'
-             'left shift by *n* bits is defined as multiplication with '
-             '"pow(2, n)".\n'
+             'left shift by *n* bits is defined as multiplication with "pow(2, '
+             'n)".\n'
              'Negative shift counts raise a "ValueError" exception.\n'
              '\n'
-             'Note: In the current implementation, the right-hand operand '
-             'is\n'
+             'Note: In the current implementation, the right-hand operand is\n'
              '  required to be at most "sys.maxsize".  If the right-hand '
              'operand is\n'
              '  larger than "sys.maxsize" an "OverflowError" exception is '
@@ -6656,8 +6861,8 @@ topics = {'assert': '\n'
              '\n'
              'A slicing selects a range of items in a sequence object (e.g., '
              'a\n'
-             'string, tuple or list).  Slicings may be used as expressions '
-             'or as\n'
+             'string, tuple or list).  Slicings may be used as expressions or '
+             'as\n'
              'targets in assignment or "del" statements.  The syntax for a '
              'slicing:\n'
              '\n'
@@ -6680,11 +6885,9 @@ topics = {'assert': '\n'
              'subscription\n'
              'can be interpreted as a slicing.  Rather than further '
              'complicating the\n'
-             'syntax, this is disambiguated by defining that in this case '
-             'the\n'
+             'syntax, this is disambiguated by defining that in this case the\n'
              'interpretation as a subscription takes priority over the\n'
-             'interpretation as a slicing (this is the case if the slice '
-             'list\n'
+             'interpretation as a slicing (this is the case if the slice list\n'
              'contains no proper slice nor ellipses).  Similarly, when the '
              'slice\n'
              'list has exactly one short slice and no trailing comma, the\n'
@@ -6692,8 +6895,8 @@ topics = {'assert': '\n'
              'an\n'
              'extended slicing.\n'
              '\n'
-             'The semantics for a simple slicing are as follows.  The '
-             'primary must\n'
+             'The semantics for a simple slicing are as follows.  The primary '
+             'must\n'
              'evaluate to a sequence object.  The lower and upper bound '
              'expressions,\n'
              'if present, must evaluate to plain integers; defaults are zero '
@@ -6701,8 +6904,7 @@ topics = {'assert': '\n'
              '"sys.maxint", respectively.  If either bound is negative, the\n'
              "sequence's length is added to it.  The slicing now selects all "
              'items\n'
-             'with index *k* such that "i <= k < j" where *i* and *j* are '
-             'the\n'
+             'with index *k* such that "i <= k < j" where *i* and *j* are the\n'
              'specified lower and upper bounds.  This may be an empty '
              'sequence.  It\n'
              'is not an error if *i* or *j* lie outside the range of valid '
@@ -6711,14 +6913,13 @@ topics = {'assert': '\n'
              '\n'
              'The semantics for an extended slicing are as follows.  The '
              'primary\n'
-             'must evaluate to a mapping object, and it is indexed with a '
-             'key that\n'
+             'must evaluate to a mapping object, and it is indexed with a key '
+             'that\n'
              'is constructed from the slice list, as follows.  If the slice '
              'list\n'
-             'contains at least one comma, the key is a tuple containing '
-             'the\n'
-             'conversion of the slice items; otherwise, the conversion of '
-             'the lone\n'
+             'contains at least one comma, the key is a tuple containing the\n'
+             'conversion of the slice items; otherwise, the conversion of the '
+             'lone\n'
              'slice item is the key.  The conversion of a slice item that is '
              'an\n'
              'expression is that expression.  The conversion of an ellipsis '
@@ -6780,24 +6981,24 @@ topics = {'assert': '\n'
                  '\n'
                  'class.__mro__\n'
                  '\n'
-                 '   This attribute is a tuple of classes that are '
-                 'considered when\n'
+                 '   This attribute is a tuple of classes that are considered '
+                 'when\n'
                  '   looking for base classes during method resolution.\n'
                  '\n'
                  'class.mro()\n'
                  '\n'
-                 '   This method can be overridden by a metaclass to '
-                 'customize the\n'
-                 '   method resolution order for its instances.  It is '
-                 'called at class\n'
+                 '   This method can be overridden by a metaclass to customize '
+                 'the\n'
+                 '   method resolution order for its instances.  It is called '
+                 'at class\n'
                  '   instantiation, and its result is stored in "__mro__".\n'
                  '\n'
                  'class.__subclasses__()\n'
                  '\n'
                  '   Each new-style class keeps a list of weak references to '
                  'its\n'
-                 '   immediate subclasses.  This method returns a list of '
-                 'all those\n'
+                 '   immediate subclasses.  This method returns a list of all '
+                 'those\n'
                  '   references still alive. Example:\n'
                  '\n'
                  '      >>> int.__subclasses__()\n'
@@ -6809,8 +7010,8 @@ topics = {'assert': '\n'
                  'found\n'
                  '    in the Python Reference Manual (Basic customization).\n'
                  '\n'
-                 '[2] As a consequence, the list "[1, 2]" is considered '
-                 'equal to\n'
+                 '[2] As a consequence, the list "[1, 2]" is considered equal '
+                 'to\n'
                  '    "[1.0, 2.0]", and similarly for tuples.\n'
                  '\n'
                  "[3] They must have since the parser can't tell the type of "
@@ -6829,8 +7030,8 @@ topics = {'assert': '\n'
                  '\n'
                  '[6] The advantage of leaving the newline on is that '
                  'returning an\n'
-                 '    empty string is then an unambiguous EOF indication.  '
-                 'It is also\n'
+                 '    empty string is then an unambiguous EOF indication.  It '
+                 'is also\n'
                  '    possible (in cases where it might matter, for example, '
                  'if you want\n'
                  '    to make an exact copy of a file while scanning its '
@@ -6842,20 +7043,20 @@ topics = {'assert': '\n'
                  'Special method names\n'
                  '********************\n'
                  '\n'
-                 'A class can implement certain operations that are invoked '
-                 'by special\n'
+                 'A class can implement certain operations that are invoked by '
+                 'special\n'
                  'syntax (such as arithmetic operations or subscripting and '
                  'slicing) by\n'
                  "defining methods with special names. This is Python's "
                  'approach to\n'
-                 '*operator overloading*, allowing classes to define their '
-                 'own behavior\n'
+                 '*operator overloading*, allowing classes to define their own '
+                 'behavior\n'
                  'with respect to language operators.  For instance, if a '
                  'class defines\n'
                  'a method named "__getitem__()", and "x" is an instance of '
                  'this class,\n'
-                 'then "x[i]" is roughly equivalent to "x.__getitem__(i)" '
-                 'for old-style\n'
+                 'then "x[i]" is roughly equivalent to "x.__getitem__(i)" for '
+                 'old-style\n'
                  'classes and "type(x).__getitem__(x, i)" for new-style '
                  'classes.  Except\n'
                  'where mentioned, attempts to execute an operation raise an '
@@ -6872,10 +7073,9 @@ topics = {'assert': '\n'
                  'some\n'
                  'sequences may work well with retrieval of individual '
                  'elements, but\n'
-                 'extracting a slice may not make sense.  (One example of '
-                 'this is the\n'
-                 '"NodeList" interface in the W3C\'s Document Object '
-                 'Model.)\n'
+                 'extracting a slice may not make sense.  (One example of this '
+                 'is the\n'
+                 '"NodeList" interface in the W3C\'s Document Object Model.)\n'
                  '\n'
                  '\n'
                  'Basic customization\n'
@@ -6889,8 +7089,8 @@ topics = {'assert': '\n'
                  'as such)\n'
                  '   that takes the class of which an instance was requested '
                  'as its\n'
-                 '   first argument.  The remaining arguments are those '
-                 'passed to the\n'
+                 '   first argument.  The remaining arguments are those passed '
+                 'to the\n'
                  '   object constructor expression (the call to the class).  '
                  'The return\n'
                  '   value of "__new__()" should be the new object instance '
@@ -6909,13 +7109,13 @@ topics = {'assert': '\n'
                  '   If "__new__()" returns an instance of *cls*, then the '
                  'new\n'
                  '   instance\'s "__init__()" method will be invoked like\n'
-                 '   "__init__(self[, ...])", where *self* is the new '
-                 'instance and the\n'
+                 '   "__init__(self[, ...])", where *self* is the new instance '
+                 'and the\n'
                  '   remaining arguments are the same as were passed to '
                  '"__new__()".\n'
                  '\n'
-                 '   If "__new__()" does not return an instance of *cls*, '
-                 'then the new\n'
+                 '   If "__new__()" does not return an instance of *cls*, then '
+                 'the new\n'
                  '   instance\'s "__init__()" method will not be invoked.\n'
                  '\n'
                  '   "__new__()" is intended mainly to allow subclasses of '
@@ -6945,14 +7145,14 @@ topics = {'assert': '\n'
                  'constructing\n'
                  '   objects ("__new__()" to create it, and "__init__()" to '
                  'customise\n'
-                 '   it), no non-"None" value may be returned by '
-                 '"__init__()"; doing so\n'
+                 '   it), no non-"None" value may be returned by "__init__()"; '
+                 'doing so\n'
                  '   will cause a "TypeError" to be raised at runtime.\n'
                  '\n'
                  'object.__del__(self)\n'
                  '\n'
-                 '   Called when the instance is about to be destroyed.  '
-                 'This is also\n'
+                 '   Called when the instance is about to be destroyed.  This '
+                 'is also\n'
                  '   called a destructor.  If a base class has a "__del__()" '
                  'method, the\n'
                  '   derived class\'s "__del__()" method, if any, must '
@@ -6963,8 +7163,8 @@ topics = {'assert': '\n'
                  'the\n'
                  '   "__del__()" method to postpone destruction of the '
                  'instance by\n'
-                 '   creating a new reference to it.  It may then be called '
-                 'at a later\n'
+                 '   creating a new reference to it.  It may then be called at '
+                 'a later\n'
                  '   time when this new reference is deleted.  It is not '
                  'guaranteed that\n'
                  '   "__del__()" methods are called for objects that still '
@@ -6973,72 +7173,69 @@ topics = {'assert': '\n'
                  '\n'
                  '   Note: "del x" doesn\'t directly call "x.__del__()" --- '
                  'the former\n'
-                 '     decrements the reference count for "x" by one, and '
-                 'the latter is\n'
-                 '     only called when "x"\'s reference count reaches '
-                 'zero.  Some common\n'
+                 '     decrements the reference count for "x" by one, and the '
+                 'latter is\n'
+                 '     only called when "x"\'s reference count reaches zero.  '
+                 'Some common\n'
                  '     situations that may prevent the reference count of an '
                  'object from\n'
                  '     going to zero include: circular references between '
                  'objects (e.g.,\n'
                  '     a doubly-linked list or a tree data structure with '
                  'parent and\n'
-                 '     child pointers); a reference to the object on the '
-                 'stack frame of\n'
+                 '     child pointers); a reference to the object on the stack '
+                 'frame of\n'
                  '     a function that caught an exception (the traceback '
                  'stored in\n'
-                 '     "sys.exc_traceback" keeps the stack frame alive); or '
-                 'reference\n'
+                 '     "sys.exc_traceback" keeps the stack frame alive); or '
+                 'reference\n'
                  '     to the object on the stack frame that raised an '
                  'unhandled\n'
-                 '     exception in interactive mode (the traceback stored '
-                 'in\n'
-                 '     "sys.last_traceback" keeps the stack frame alive).  '
-                 'The first\n'
+                 '     exception in interactive mode (the traceback stored in\n'
+                 '     "sys.last_traceback" keeps the stack frame alive).  The '
+                 'first\n'
                  '     situation can only be remedied by explicitly breaking '
                  'the cycles;\n'
                  '     the latter two situations can be resolved by storing '
                  '"None" in\n'
-                 '     "sys.exc_traceback" or "sys.last_traceback".  '
-                 'Circular references\n'
+                 '     "sys.exc_traceback" or "sys.last_traceback".  Circular '
+                 'references\n'
                  '     which are garbage are detected when the option cycle '
                  'detector is\n'
                  "     enabled (it's on by default), but can only be cleaned "
                  'up if there\n'
-                 '     are no Python-level "__del__()" methods involved. '
-                 'Refer to the\n'
-                 '     documentation for the "gc" module for more '
-                 'information about how\n'
-                 '     "__del__()" methods are handled by the cycle '
-                 'detector,\n'
+                 '     are no Python-level "__del__()" methods involved. Refer '
+                 'to the\n'
+                 '     documentation for the "gc" module for more information '
+                 'about how\n'
+                 '     "__del__()" methods are handled by the cycle detector,\n'
                  '     particularly the description of the "garbage" value.\n'
                  '\n'
-                 '   Warning: Due to the precarious circumstances under '
-                 'which\n'
-                 '     "__del__()" methods are invoked, exceptions that '
-                 'occur during\n'
+                 '   Warning: Due to the precarious circumstances under which\n'
+                 '     "__del__()" methods are invoked, exceptions that occur '
+                 'during\n'
                  '     their execution are ignored, and a warning is printed '
                  'to\n'
-                 '     "sys.stderr" instead. Also, when "__del__()" is '
-                 'invoked in\n'
+                 '     "sys.stderr" instead. Also, when "__del__()" is invoked '
+                 'in\n'
                  '     response to a module being deleted (e.g., when '
                  'execution of the\n'
                  '     program is done), other globals referenced by the '
                  '"__del__()"\n'
-                 '     method may already have been deleted or in the '
-                 'process of being\n'
+                 '     method may already have been deleted or in the process '
+                 'of being\n'
                  '     torn down (e.g. the import machinery shutting down).  '
                  'For this\n'
                  '     reason, "__del__()" methods should do the absolute '
                  'minimum needed\n'
-                 '     to maintain external invariants.  Starting with '
-                 'version 1.5,\n'
-                 '     Python guarantees that globals whose name begins with '
-                 'single\n'
+                 '     to maintain external invariants.  Starting with version '
+                 '1.5,\n'
+                 '     Python guarantees that globals whose name begins with '
+                 'single\n'
                  '     underscore are deleted from their module before other '
                  'globals are\n'
-                 '     deleted; if no other references to such globals '
-                 'exist, this may\n'
+                 '     deleted; if no other references to such globals exist, '
+                 'this may\n'
                  '     help in assuring that imported modules are still '
                  'available at the\n'
                  '     time when the "__del__()" method is called.\n'
@@ -7063,26 +7260,26 @@ topics = {'assert': '\n'
                  'object. If a\n'
                  '   class defines "__repr__()" but not "__str__()", then '
                  '"__repr__()"\n'
-                 '   is also used when an "informal" string representation '
-                 'of instances\n'
+                 '   is also used when an "informal" string representation of '
+                 'instances\n'
                  '   of that class is required.\n'
                  '\n'
-                 '   This is typically used for debugging, so it is '
-                 'important that the\n'
+                 '   This is typically used for debugging, so it is important '
+                 'that the\n'
                  '   representation is information-rich and unambiguous.\n'
                  '\n'
                  'object.__str__(self)\n'
                  '\n'
                  '   Called by the "str()" built-in function and by the '
                  '"print"\n'
-                 '   statement to compute the "informal" string '
-                 'representation of an\n'
+                 '   statement to compute the "informal" string representation '
+                 'of an\n'
                  '   object.  This differs from "__repr__()" in that it does '
                  'not have to\n'
                  '   be a valid Python expression: a more convenient or '
                  'concise\n'
-                 '   representation may be used instead. The return value '
-                 'must be a\n'
+                 '   representation may be used instead. The return value must '
+                 'be a\n'
                  '   string object.\n'
                  '\n'
                  'object.__lt__(self, other)\n'
@@ -7098,8 +7295,8 @@ topics = {'assert': '\n'
                  'are called\n'
                  '   for comparison operators in preference to "__cmp__()" '
                  'below. The\n'
-                 '   correspondence between operator symbols and method '
-                 'names is as\n'
+                 '   correspondence between operator symbols and method names '
+                 'is as\n'
                  '   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls '
                  '"x.__le__(y)",\n'
                  '   "x==y" calls "x.__eq__(y)", "x!=y" and "x<>y" call '
@@ -7111,21 +7308,20 @@ topics = {'assert': '\n'
                  '"NotImplemented"\n'
                  '   if it does not implement the operation for a given pair '
                  'of\n'
-                 '   arguments. By convention, "False" and "True" are '
-                 'returned for a\n'
-                 '   successful comparison. However, these methods can '
-                 'return any value,\n'
+                 '   arguments. By convention, "False" and "True" are returned '
+                 'for a\n'
+                 '   successful comparison. However, these methods can return '
+                 'any value,\n'
                  '   so if the comparison operator is used in a Boolean '
                  'context (e.g.,\n'
-                 '   in the condition of an "if" statement), Python will '
-                 'call "bool()"\n'
+                 '   in the condition of an "if" statement), Python will call '
+                 '"bool()"\n'
                  '   on the value to determine if the result is true or '
                  'false.\n'
                  '\n'
                  '   There are no implied relationships among the comparison '
                  'operators.\n'
-                 '   The truth of "x==y" does not imply that "x!=y" is '
-                 'false.\n'
+                 '   The truth of "x==y" does not imply that "x!=y" is false.\n'
                  '   Accordingly, when defining "__eq__()", one should also '
                  'define\n'
                  '   "__ne__()" so that the operators will behave as '
@@ -7138,17 +7334,15 @@ topics = {'assert': '\n'
                  '\n'
                  '   There are no swapped-argument versions of these methods '
                  '(to be used\n'
-                 '   when the left argument does not support the operation '
-                 'but the right\n'
+                 '   when the left argument does not support the operation but '
+                 'the right\n'
                  '   argument does); rather, "__lt__()" and "__gt__()" are '
                  "each other's\n"
                  '   reflection, "__le__()" and "__ge__()" are each other\'s '
                  'reflection,\n'
-                 '   and "__eq__()" and "__ne__()" are their own '
-                 'reflection.\n'
+                 '   and "__eq__()" and "__ne__()" are their own reflection.\n'
                  '\n'
-                 '   Arguments to rich comparison methods are never '
-                 'coerced.\n'
+                 '   Arguments to rich comparison methods are never coerced.\n'
                  '\n'
                  '   To automatically generate ordering operations from a '
                  'single root\n'
@@ -7158,8 +7352,8 @@ topics = {'assert': '\n'
                  '\n'
                  '   Called by comparison operations if rich comparison (see '
                  'above) is\n'
-                 '   not defined.  Should return a negative integer if "self '
-                 'other",\n'
+                 '   not defined.  Should return a negative integer if "self '
+                 'other",\n'
                  '   zero if "self == other", a positive integer if "self > '
                  'other".  If\n'
                  '   no "__cmp__()", "__eq__()" or "__ne__()" operation is '
@@ -7170,8 +7364,7 @@ topics = {'assert': '\n'
                  'notes on\n'
                  '   creating *hashable* objects which support custom '
                  'comparison\n'
-                 '   operations and are usable as dictionary keys. (Note: '
-                 'the\n'
+                 '   operations and are usable as dictionary keys. (Note: the\n'
                  '   restriction that exceptions are not propagated by '
                  '"__cmp__()" has\n'
                  '   been removed since Python 1.5.)\n'
@@ -7186,32 +7379,32 @@ topics = {'assert': '\n'
                  'on members\n'
                  '   of hashed collections including "set", "frozenset", and '
                  '"dict".\n'
-                 '   "__hash__()" should return an integer.  The only '
-                 'required property\n'
+                 '   "__hash__()" should return an integer.  The only required '
+                 'property\n'
                  '   is that objects which compare equal have the same hash '
                  'value; it is\n'
-                 '   advised to somehow mix together (e.g. using exclusive '
-                 'or) the hash\n'
-                 '   values for the components of the object that also play '
-                 'part in\n'
+                 '   advised to somehow mix together (e.g. using exclusive or) '
+                 'the hash\n'
+                 '   values for the components of the object that also play '
+                 'part in\n'
                  '   comparison of objects.\n'
                  '\n'
                  '   If a class does not define a "__cmp__()" or "__eq__()" '
                  'method it\n'
-                 '   should not define a "__hash__()" operation either; if '
-                 'it defines\n'
+                 '   should not define a "__hash__()" operation either; if it '
+                 'defines\n'
                  '   "__cmp__()" or "__eq__()" but not "__hash__()", its '
                  'instances will\n'
-                 '   not be usable in hashed collections.  If a class '
-                 'defines mutable\n'
+                 '   not be usable in hashed collections.  If a class defines '
+                 'mutable\n'
                  '   objects and implements a "__cmp__()" or "__eq__()" '
                  'method, it\n'
                  '   should not implement "__hash__()", since hashable '
                  'collection\n'
                  "   implementations require that a object's hash value is "
                  'immutable (if\n'
-                 "   the object's hash value changes, it will be in the "
-                 'wrong hash\n'
+                 "   the object's hash value changes, it will be in the wrong "
+                 'hash\n'
                  '   bucket).\n'
                  '\n'
                  '   User-defined classes have "__cmp__()" and "__hash__()" '
@@ -7222,10 +7415,10 @@ topics = {'assert': '\n'
                  'from\n'
                  '   "id(x)".\n'
                  '\n'
-                 '   Classes which inherit a "__hash__()" method from a '
-                 'parent class but\n'
-                 '   change the meaning of "__cmp__()" or "__eq__()" such '
-                 'that the hash\n'
+                 '   Classes which inherit a "__hash__()" method from a parent '
+                 'class but\n'
+                 '   change the meaning of "__cmp__()" or "__eq__()" such that '
+                 'the hash\n'
                  '   value returned is no longer appropriate (e.g. by '
                  'switching to a\n'
                  '   value-based concept of equality instead of the default '
@@ -7234,8 +7427,7 @@ topics = {'assert': '\n'
                  'unhashable\n'
                  '   by setting "__hash__ = None" in the class definition. '
                  'Doing so\n'
-                 '   means that not only will instances of the class raise '
-                 'an\n'
+                 '   means that not only will instances of the class raise an\n'
                  '   appropriate "TypeError" when a program attempts to '
                  'retrieve their\n'
                  '   hash value, but they will also be correctly identified '
@@ -7246,8 +7438,8 @@ topics = {'assert': '\n'
                  'explicitly\n'
                  '   raise "TypeError").\n'
                  '\n'
-                 '   Changed in version 2.5: "__hash__()" may now also '
-                 'return a long\n'
+                 '   Changed in version 2.5: "__hash__()" may now also return '
+                 'a long\n'
                  '   integer object; the 32-bit integer is then derived from '
                  'the hash of\n'
                  '   that object.\n'
@@ -7258,8 +7450,8 @@ topics = {'assert': '\n'
                  '\n'
                  'object.__nonzero__(self)\n'
                  '\n'
-                 '   Called to implement truth value testing and the '
-                 'built-in operation\n'
+                 '   Called to implement truth value testing and the built-in '
+                 'operation\n'
                  '   "bool()"; should return "False" or "True", or their '
                  'integer\n'
                  '   equivalents "0" or "1".  When this method is not '
@@ -7274,8 +7466,8 @@ topics = {'assert': '\n'
                  '\n'
                  'object.__unicode__(self)\n'
                  '\n'
-                 '   Called to implement "unicode()" built-in; should return '
-                 'Unicode\n'
+                 '   Called to implement "unicode()" built-in; should return '
+                 'Unicode\n'
                  '   object. When this method is not defined, string '
                  'conversion is\n'
                  '   attempted, and the result of string conversion is '
@@ -7296,8 +7488,8 @@ topics = {'assert': '\n'
                  '\n'
                  '   Called when an attribute lookup has not found the '
                  'attribute in the\n'
-                 '   usual places (i.e. it is not an instance attribute nor '
-                 'is it found\n'
+                 '   usual places (i.e. it is not an instance attribute nor is '
+                 'it found\n'
                  '   in the class tree for "self").  "name" is the attribute '
                  'name. This\n'
                  '   method should return the (computed) attribute value or '
@@ -7310,14 +7502,14 @@ topics = {'assert': '\n'
                  'asymmetry\n'
                  '   between "__getattr__()" and "__setattr__()".) This is '
                  'done both for\n'
-                 '   efficiency reasons and because otherwise '
-                 '"__getattr__()" would have\n'
-                 '   no way to access other attributes of the instance.  '
-                 'Note that at\n'
-                 '   least for instance variables, you can fake total '
-                 'control by not\n'
-                 '   inserting any values in the instance attribute '
-                 'dictionary (but\n'
+                 '   efficiency reasons and because otherwise "__getattr__()" '
+                 'would have\n'
+                 '   no way to access other attributes of the instance.  Note '
+                 'that at\n'
+                 '   least for instance variables, you can fake total control '
+                 'by not\n'
+                 '   inserting any values in the instance attribute dictionary '
+                 '(but\n'
                  '   instead inserting them in another object).  See the\n'
                  '   "__getattribute__()" method below for a way to actually '
                  'get total\n'
@@ -7327,8 +7519,8 @@ topics = {'assert': '\n'
                  '\n'
                  '   Called when an attribute assignment is attempted.  This '
                  'is called\n'
-                 '   instead of the normal mechanism (i.e. store the value '
-                 'in the\n'
+                 '   instead of the normal mechanism (i.e. store the value in '
+                 'the\n'
                  '   instance dictionary).  *name* is the attribute name, '
                  '*value* is the\n'
                  '   value to be assigned to it.\n'
@@ -7341,10 +7533,10 @@ topics = {'assert': '\n'
                  'the value in\n'
                  '   the dictionary of instance attributes, e.g., '
                  '"self.__dict__[name] =\n'
-                 '   value".  For new-style classes, rather than accessing '
-                 'the instance\n'
-                 '   dictionary, it should call the base class method with '
-                 'the same\n'
+                 '   value".  For new-style classes, rather than accessing the '
+                 'instance\n'
+                 '   dictionary, it should call the base class method with the '
+                 'same\n'
                  '   name, for example, "object.__setattr__(self, name, '
                  'value)".\n'
                  '\n'
@@ -7368,12 +7560,11 @@ topics = {'assert': '\n'
                  'for\n'
                  '   instances of the class. If the class also defines '
                  '"__getattr__()",\n'
-                 '   the latter will not be called unless '
-                 '"__getattribute__()" either\n'
+                 '   the latter will not be called unless "__getattribute__()" '
+                 'either\n'
                  '   calls it explicitly or raises an "AttributeError". This '
                  'method\n'
-                 '   should return the (computed) attribute value or raise '
-                 'an\n'
+                 '   should return the (computed) attribute value or raise an\n'
                  '   "AttributeError" exception. In order to avoid infinite '
                  'recursion in\n'
                  '   this method, its implementation should always call the '
@@ -7398,8 +7589,8 @@ topics = {'assert': '\n'
                  'class\n'
                  'containing the method (a so-called *descriptor* class) '
                  'appears in an\n'
-                 '*owner* class (the descriptor must be in either the '
-                 "owner's class\n"
+                 "*owner* class (the descriptor must be in either the owner's "
+                 'class\n'
                  'dictionary or in the class dictionary for one of its '
                  'parents).  In the\n'
                  'examples below, "the attribute" refers to the attribute '
@@ -7424,14 +7615,14 @@ topics = {'assert': '\n'
                  '\n'
                  'object.__set__(self, instance, value)\n'
                  '\n'
-                 '   Called to set the attribute on an instance *instance* '
-                 'of the owner\n'
+                 '   Called to set the attribute on an instance *instance* of '
+                 'the owner\n'
                  '   class to a new value, *value*.\n'
                  '\n'
                  'object.__delete__(self, instance)\n'
                  '\n'
-                 '   Called to delete the attribute on an instance '
-                 '*instance* of the\n'
+                 '   Called to delete the attribute on an instance *instance* '
+                 'of the\n'
                  '   owner class.\n'
                  '\n'
                  '\n'
@@ -7440,16 +7631,15 @@ topics = {'assert': '\n'
                  '\n'
                  'In general, a descriptor is an object attribute with '
                  '"binding\n'
-                 'behavior", one whose attribute access has been overridden '
-                 'by methods\n'
-                 'in the descriptor protocol:  "__get__()", "__set__()", '
-                 'and\n'
+                 'behavior", one whose attribute access has been overridden by '
+                 'methods\n'
+                 'in the descriptor protocol:  "__get__()", "__set__()", and\n'
                  '"__delete__()". If any of those methods are defined for an '
                  'object, it\n'
                  'is said to be a descriptor.\n'
                  '\n'
-                 'The default behavior for attribute access is to get, set, '
-                 'or delete\n'
+                 'The default behavior for attribute access is to get, set, or '
+                 'delete\n'
                  "the attribute from an object's dictionary. For instance, "
                  '"a.x" has a\n'
                  'lookup chain starting with "a.__dict__[\'x\']", then\n'
@@ -7457,12 +7647,12 @@ topics = {'assert': '\n'
                  'classes of\n'
                  '"type(a)" excluding metaclasses.\n'
                  '\n'
-                 'However, if the looked-up value is an object defining one '
-                 'of the\n'
+                 'However, if the looked-up value is an object defining one of '
+                 'the\n'
                  'descriptor methods, then Python may override the default '
                  'behavior and\n'
-                 'invoke the descriptor method instead.  Where this occurs '
-                 'in the\n'
+                 'invoke the descriptor method instead.  Where this occurs in '
+                 'the\n'
                  'precedence chain depends on which descriptor methods were '
                  'defined and\n'
                  'how they were called.  Note that descriptors are only '
@@ -7495,8 +7685,8 @@ topics = {'assert': '\n'
                  '"super(B,\n'
                  '   obj).m()" searches "obj.__class__.__mro__" for the base '
                  'class "A"\n'
-                 '   immediately preceding "B" and then invokes the '
-                 'descriptor with the\n'
+                 '   immediately preceding "B" and then invokes the descriptor '
+                 'with the\n'
                  '   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n'
                  '\n'
                  'For instance bindings, the precedence of descriptor '
@@ -7507,16 +7697,16 @@ topics = {'assert': '\n'
                  '"__delete__()".  If it\n'
                  'does not define "__get__()", then accessing the attribute '
                  'will return\n'
-                 'the descriptor object itself unless there is a value in '
-                 "the object's\n"
-                 'instance dictionary.  If the descriptor defines '
-                 '"__set__()" and/or\n'
+                 'the descriptor object itself unless there is a value in the '
+                 "object's\n"
+                 'instance dictionary.  If the descriptor defines "__set__()" '
+                 'and/or\n'
                  '"__delete__()", it is a data descriptor; if it defines '
                  'neither, it is\n'
                  'a non-data descriptor.  Normally, data descriptors define '
                  'both\n'
-                 '"__get__()" and "__set__()", while non-data descriptors '
-                 'have just the\n'
+                 '"__get__()" and "__set__()", while non-data descriptors have '
+                 'just the\n'
                  '"__get__()" method.  Data descriptors with "__set__()" and '
                  '"__get__()"\n'
                  'defined always override a redefinition in an instance '
@@ -7526,8 +7716,8 @@ topics = {'assert': '\n'
                  '\n'
                  'Python methods (including "staticmethod()" and '
                  '"classmethod()") are\n'
-                 'implemented as non-data descriptors.  Accordingly, '
-                 'instances can\n'
+                 'implemented as non-data descriptors.  Accordingly, instances '
+                 'can\n'
                  'redefine and override methods.  This allows individual '
                  'instances to\n'
                  'acquire behaviors that differ from other instances of the '
@@ -7542,8 +7732,8 @@ topics = {'assert': '\n'
                  '__slots__\n'
                  '---------\n'
                  '\n'
-                 'By default, instances of both old and new-style classes '
-                 'have a\n'
+                 'By default, instances of both old and new-style classes have '
+                 'a\n'
                  'dictionary for attribute storage.  This wastes space for '
                  'objects\n'
                  'having very few instance variables.  The space consumption '
@@ -7588,16 +7778,15 @@ topics = {'assert': '\n'
                  'Attempts to\n'
                  '  assign to an unlisted variable name raises '
                  '"AttributeError". If\n'
-                 '  dynamic assignment of new variables is desired, then '
-                 'add\n'
+                 '  dynamic assignment of new variables is desired, then add\n'
                  '  "\'__dict__\'" to the sequence of strings in the '
                  '*__slots__*\n'
                  '  declaration.\n'
                  '\n'
-                 '  Changed in version 2.3: Previously, adding '
-                 '"\'__dict__\'" to the\n'
-                 '  *__slots__* declaration would not enable the assignment '
-                 'of new\n'
+                 '  Changed in version 2.3: Previously, adding "\'__dict__\'" '
+                 'to the\n'
+                 '  *__slots__* declaration would not enable the assignment of '
+                 'new\n'
                  '  attributes not specifically listed in the sequence of '
                  'instance\n'
                  '  variable names.\n'
@@ -7606,16 +7795,14 @@ topics = {'assert': '\n'
                  'classes\n'
                  '  defining *__slots__* do not support weak references to '
                  'its\n'
-                 '  instances. If weak reference support is needed, then '
-                 'add\n'
+                 '  instances. If weak reference support is needed, then add\n'
                  '  "\'__weakref__\'" to the sequence of strings in the '
                  '*__slots__*\n'
                  '  declaration.\n'
                  '\n'
                  '  Changed in version 2.3: Previously, adding '
                  '"\'__weakref__\'" to the\n'
-                 '  *__slots__* declaration would not enable support for '
-                 'weak\n'
+                 '  *__slots__* declaration would not enable support for weak\n'
                  '  references.\n'
                  '\n'
                  '* *__slots__* are implemented at the class level by '
@@ -7624,14 +7811,14 @@ topics = {'assert': '\n'
                  'name.  As a\n'
                  '  result, class attributes cannot be used to set default '
                  'values for\n'
-                 '  instance variables defined by *__slots__*; otherwise, '
-                 'the class\n'
+                 '  instance variables defined by *__slots__*; otherwise, the '
+                 'class\n'
                  '  attribute would overwrite the descriptor assignment.\n'
                  '\n'
-                 '* The action of a *__slots__* declaration is limited to '
-                 'the class\n'
-                 '  where it is defined.  As a result, subclasses will have '
-                 '*__dict__*\n'
+                 '* The action of a *__slots__* declaration is limited to the '
+                 'class\n'
+                 '  where it is defined.  As a result, subclasses will have '
+                 '*__dict__*\n'
                  '  unless they also define *__slots__* (which must only '
                  'contain names\n'
                  '  of any *additional* slots).\n'
@@ -7642,27 +7829,27 @@ topics = {'assert': '\n'
                  'inaccessible\n'
                  '  (except by retrieving its descriptor directly from the '
                  'base class).\n'
-                 '  This renders the meaning of the program undefined.  In '
-                 'the future, a\n'
+                 '  This renders the meaning of the program undefined.  In the '
+                 'future, a\n'
                  '  check may be added to prevent this.\n'
                  '\n'
                  '* Nonempty *__slots__* does not work for classes derived '
                  'from\n'
-                 '  "variable-length" built-in types such as "long", "str" '
-                 'and "tuple".\n'
+                 '  "variable-length" built-in types such as "long", "str" and '
+                 '"tuple".\n'
                  '\n'
                  '* Any non-string iterable may be assigned to *__slots__*. '
                  'Mappings\n'
-                 '  may also be used; however, in the future, special '
-                 'meaning may be\n'
+                 '  may also be used; however, in the future, special meaning '
+                 'may be\n'
                  '  assigned to the values corresponding to each key.\n'
                  '\n'
-                 '* *__class__* assignment works only if both classes have '
-                 'the same\n'
+                 '* *__class__* assignment works only if both classes have the '
+                 'same\n'
                  '  *__slots__*.\n'
                  '\n'
-                 '  Changed in version 2.6: Previously, *__class__* '
-                 'assignment raised an\n'
+                 '  Changed in version 2.6: Previously, *__class__* assignment '
+                 'raised an\n'
                  '  error if either new or old class had *__slots__*.\n'
                  '\n'
                  '\n'
@@ -7694,28 +7881,27 @@ topics = {'assert': '\n'
                  '"__new__()"\n'
                  'method -- "type.__new__()" can then be called from this '
                  'method to\n'
-                 'create a class with different properties.  This example '
-                 'adds a new\n'
-                 'element to the class dictionary before creating the '
-                 'class:\n'
+                 'create a class with different properties.  This example adds '
+                 'a new\n'
+                 'element to the class dictionary before creating the class:\n'
                  '\n'
                  '   class metacls(type):\n'
                  '       def __new__(mcs, name, bases, dict):\n'
                  "           dict['foo'] = 'metacls was here'\n"
                  '           return type.__new__(mcs, name, bases, dict)\n'
                  '\n'
-                 'You can of course also override other class methods (or '
-                 'add new\n'
-                 'methods); for example defining a custom "__call__()" '
-                 'method in the\n'
+                 'You can of course also override other class methods (or add '
+                 'new\n'
+                 'methods); for example defining a custom "__call__()" method '
+                 'in the\n'
                  'metaclass allows custom behavior when the class is called, '
                  'e.g. not\n'
                  'always creating a new instance.\n'
                  '\n'
                  '__metaclass__\n'
                  '\n'
-                 '   This variable can be any callable accepting arguments '
-                 'for "name",\n'
+                 '   This variable can be any callable accepting arguments for '
+                 '"name",\n'
                  '   "bases", and "dict".  Upon class creation, the callable '
                  'is used\n'
                  '   instead of the built-in "type()".\n'
@@ -7730,8 +7916,8 @@ topics = {'assert': '\n'
                  '\n'
                  '* Otherwise, if there is at least one base class, its '
                  'metaclass is\n'
-                 '  used (this looks for a *__class__* attribute first and '
-                 'if not found,\n'
+                 '  used (this looks for a *__class__* attribute first and if '
+                 'not found,\n'
                  '  uses its type).\n'
                  '\n'
                  '* Otherwise, if a global variable named __metaclass__ '
@@ -7742,8 +7928,8 @@ topics = {'assert': '\n'
                  '(types.ClassType) is\n'
                  '  used.\n'
                  '\n'
-                 'The potential uses for metaclasses are boundless. Some '
-                 'ideas that have\n'
+                 'The potential uses for metaclasses are boundless. Some ideas '
+                 'that have\n'
                  'been explored including logging, interface checking, '
                  'automatic\n'
                  'delegation, automatic property creation, proxies, '
@@ -7760,26 +7946,26 @@ topics = {'assert': '\n'
                  'behavior of the\n'
                  '"isinstance()" and "issubclass()" built-in functions.\n'
                  '\n'
-                 'In particular, the metaclass "abc.ABCMeta" implements '
-                 'these methods in\n'
-                 'order to allow the addition of Abstract Base Classes '
-                 '(ABCs) as\n'
+                 'In particular, the metaclass "abc.ABCMeta" implements these '
+                 'methods in\n'
+                 'order to allow the addition of Abstract Base Classes (ABCs) '
+                 'as\n'
                  '"virtual base classes" to any class or type (including '
                  'built-in\n'
                  'types), including other ABCs.\n'
                  '\n'
                  'class.__instancecheck__(self, instance)\n'
                  '\n'
-                 '   Return true if *instance* should be considered a '
-                 '(direct or\n'
+                 '   Return true if *instance* should be considered a (direct '
+                 'or\n'
                  '   indirect) instance of *class*. If defined, called to '
                  'implement\n'
                  '   "isinstance(instance, class)".\n'
                  '\n'
                  'class.__subclasscheck__(self, subclass)\n'
                  '\n'
-                 '   Return true if *subclass* should be considered a '
-                 '(direct or\n'
+                 '   Return true if *subclass* should be considered a (direct '
+                 'or\n'
                  '   indirect) subclass of *class*.  If defined, called to '
                  'implement\n'
                  '   "issubclass(subclass, class)".\n'
@@ -7793,9 +7979,9 @@ topics = {'assert': '\n'
                  'on instances, only in this case the instance is itself a '
                  'class.\n'
                  '\n'
-                 'See also: **PEP 3119** - Introducing Abstract Base '
-                 'Classes\n'
+                 'See also:\n'
                  '\n'
+                 '  **PEP 3119** - Introducing Abstract Base Classes\n'
                  '     Includes the specification for customizing '
                  '"isinstance()" and\n'
                  '     "issubclass()" behavior through "__instancecheck__()" '
@@ -7821,18 +8007,18 @@ topics = {'assert': '\n'
                  'Emulating container types\n'
                  '=========================\n'
                  '\n'
-                 'The following methods can be defined to implement '
-                 'container objects.\n'
+                 'The following methods can be defined to implement container '
+                 'objects.\n'
                  'Containers usually are sequences (such as lists or tuples) '
                  'or mappings\n'
                  '(like dictionaries), but can represent other containers as '
                  'well.  The\n'
-                 'first set of methods is used either to emulate a sequence '
-                 'or to\n'
+                 'first set of methods is used either to emulate a sequence or '
+                 'to\n'
                  'emulate a mapping; the difference is that for a sequence, '
                  'the\n'
-                 'allowable keys should be the integers *k* for which "0 <= '
-                 '< N" where\n'
+                 'allowable keys should be the integers *k* for which "0 <= '
+                 '< N" where\n'
                  '*N* is the length of the sequence, or slice objects, which '
                  'define a\n'
                  'range of items. (For backwards compatibility, the method\n'
@@ -7845,8 +8031,8 @@ topics = {'assert': '\n'
                  '"clear()", "setdefault()", "iterkeys()", "itervalues()",\n'
                  '"iteritems()", "pop()", "popitem()", "copy()", and '
                  '"update()" behaving\n'
-                 "similar to those for Python's standard dictionary "
-                 'objects.  The\n'
+                 "similar to those for Python's standard dictionary objects.  "
+                 'The\n'
                  '"UserDict" module provides a "DictMixin" class to help '
                  'create those\n'
                  'methods from a base set of "__getitem__()", '
@@ -7863,24 +8049,23 @@ topics = {'assert': '\n'
                  'repetition) by\n'
                  'defining the methods "__add__()", "__radd__()", '
                  '"__iadd__()",\n'
-                 '"__mul__()", "__rmul__()" and "__imul__()" described '
-                 'below; they\n'
+                 '"__mul__()", "__rmul__()" and "__imul__()" described below; '
+                 'they\n'
                  'should not define "__coerce__()" or other numerical '
                  'operators.  It is\n'
-                 'recommended that both mappings and sequences implement '
-                 'the\n'
+                 'recommended that both mappings and sequences implement the\n'
                  '"__contains__()" method to allow efficient use of the "in" '
                  'operator;\n'
-                 'for mappings, "in" should be equivalent of "has_key()"; '
-                 'for sequences,\n'
+                 'for mappings, "in" should be equivalent of "has_key()"; for '
+                 'sequences,\n'
                  'it should search through the values.  It is further '
                  'recommended that\n'
                  'both mappings and sequences implement the "__iter__()" '
                  'method to allow\n'
                  'efficient iteration through the container; for mappings, '
                  '"__iter__()"\n'
-                 'should be the same as "iterkeys()"; for sequences, it '
-                 'should iterate\n'
+                 'should be the same as "iterkeys()"; for sequences, it should '
+                 'iterate\n'
                  'through the values.\n'
                  '\n'
                  'object.__len__(self)\n'
@@ -7898,42 +8083,42 @@ topics = {'assert': '\n'
                  '\n'
                  '   Called to implement evaluation of "self[key]". For '
                  'sequence types,\n'
-                 '   the accepted keys should be integers and slice '
-                 'objects.  Note that\n'
+                 '   the accepted keys should be integers and slice objects.  '
+                 'Note that\n'
                  '   the special interpretation of negative indexes (if the '
                  'class wishes\n'
-                 '   to emulate a sequence type) is up to the '
-                 '"__getitem__()" method. If\n'
+                 '   to emulate a sequence type) is up to the "__getitem__()" '
+                 'method. If\n'
                  '   *key* is of an inappropriate type, "TypeError" may be '
                  'raised; if of\n'
                  '   a value outside the set of indexes for the sequence '
                  '(after any\n'
-                 '   special interpretation of negative values), '
-                 '"IndexError" should be\n'
+                 '   special interpretation of negative values), "IndexError" '
+                 'should be\n'
                  '   raised. For mapping types, if *key* is missing (not in '
                  'the\n'
                  '   container), "KeyError" should be raised.\n'
                  '\n'
                  '   Note: "for" loops expect that an "IndexError" will be '
                  'raised for\n'
-                 '     illegal indexes to allow proper detection of the end '
-                 'of the\n'
+                 '     illegal indexes to allow proper detection of the end of '
+                 'the\n'
                  '     sequence.\n'
                  '\n'
                  'object.__missing__(self, key)\n'
                  '\n'
-                 '   Called by "dict"."__getitem__()" to implement '
-                 '"self[key]" for dict\n'
+                 '   Called by "dict"."__getitem__()" to implement "self[key]" '
+                 'for dict\n'
                  '   subclasses when key is not in the dictionary.\n'
                  '\n'
                  'object.__setitem__(self, key, value)\n'
                  '\n'
-                 '   Called to implement assignment to "self[key]".  Same '
-                 'note as for\n'
+                 '   Called to implement assignment to "self[key]".  Same note '
+                 'as for\n'
                  '   "__getitem__()".  This should only be implemented for '
                  'mappings if\n'
-                 '   the objects support changes to the values for keys, or '
-                 'if new keys\n'
+                 '   the objects support changes to the values for keys, or if '
+                 'new keys\n'
                  '   can be added, or for sequences if elements can be '
                  'replaced.  The\n'
                  '   same exceptions should be raised for improper *key* '
@@ -7946,8 +8131,8 @@ topics = {'assert': '\n'
                  'as for\n'
                  '   "__getitem__()".  This should only be implemented for '
                  'mappings if\n'
-                 '   the objects support removal of keys, or for sequences '
-                 'if elements\n'
+                 '   the objects support removal of keys, or for sequences if '
+                 'elements\n'
                  '   can be removed from the sequence.  The same exceptions '
                  'should be\n'
                  '   raised for improper *key* values as for the '
@@ -7955,18 +8140,18 @@ topics = {'assert': '\n'
                  '\n'
                  'object.__iter__(self)\n'
                  '\n'
-                 '   This method is called when an iterator is required for '
-                 'container.\n'
-                 '   This method should return a new iterator object that '
-                 'can iterate\n'
-                 '   over all the objects in the container.  For mappings, '
-                 'it should\n'
+                 '   This method is called when an iterator is required for '
+                 'container.\n'
+                 '   This method should return a new iterator object that can '
+                 'iterate\n'
+                 '   over all the objects in the container.  For mappings, it '
+                 'should\n'
                  '   iterate over the keys of the container, and should also '
                  'be made\n'
                  '   available as the method "iterkeys()".\n'
                  '\n'
-                 '   Iterator objects also need to implement this method; '
-                 'they are\n'
+                 '   Iterator objects also need to implement this method; they '
+                 'are\n'
                  '   required to return themselves.  For more information on '
                  'iterator\n'
                  '   objects, see Iterator Types.\n'
@@ -7977,17 +8162,17 @@ topics = {'assert': '\n'
                  'implement\n'
                  '   reverse iteration.  It should return a new iterator '
                  'object that\n'
-                 '   iterates over all the objects in the container in '
-                 'reverse order.\n'
+                 '   iterates over all the objects in the container in reverse '
+                 'order.\n'
                  '\n'
                  '   If the "__reversed__()" method is not provided, the '
                  '"reversed()"\n'
                  '   built-in will fall back to using the sequence protocol '
                  '("__len__()"\n'
-                 '   and "__getitem__()").  Objects that support the '
-                 'sequence protocol\n'
-                 '   should only provide "__reversed__()" if they can '
-                 'provide an\n'
+                 '   and "__getitem__()").  Objects that support the sequence '
+                 'protocol\n'
+                 '   should only provide "__reversed__()" if they can provide '
+                 'an\n'
                  '   implementation that is more efficient than the one '
                  'provided by\n'
                  '   "reversed()".\n'
@@ -7998,10 +8183,10 @@ topics = {'assert': '\n'
                  'normally\n'
                  'implemented as an iteration through a sequence.  However, '
                  'container\n'
-                 'objects can supply the following special method with a '
-                 'more efficient\n'
-                 'implementation, which also does not require the object be '
-                 'sequence.\n'
+                 'objects can supply the following special method with a more '
+                 'efficient\n'
+                 'implementation, which also does not require the object be '
+                 'sequence.\n'
                  '\n'
                  'object.__contains__(self, item)\n'
                  '\n'
@@ -8017,8 +8202,8 @@ topics = {'assert': '\n'
                  'membership test\n'
                  '   first tries iteration via "__iter__()", then the old '
                  'sequence\n'
-                 '   iteration protocol via "__getitem__()", see this '
-                 'section in the\n'
+                 '   iteration protocol via "__getitem__()", see this section '
+                 'in the\n'
                  '   language reference.\n'
                  '\n'
                  '\n'
@@ -8029,8 +8214,8 @@ topics = {'assert': '\n'
                  'emulate\n'
                  'sequence objects.  Immutable sequences methods should at '
                  'most only\n'
-                 'define "__getslice__()"; mutable sequences might define '
-                 'all three\n'
+                 'define "__getslice__()"; mutable sequences might define all '
+                 'three\n'
                  'methods.\n'
                  '\n'
                  'object.__getslice__(self, i, j)\n'
@@ -8046,29 +8231,29 @@ topics = {'assert': '\n'
                  '\n'
                  '   Called to implement evaluation of "self[i:j]". The '
                  'returned object\n'
-                 '   should be of the same type as *self*.  Note that '
-                 'missing *i* or *j*\n'
+                 '   should be of the same type as *self*.  Note that missing '
+                 '*i* or *j*\n'
                  '   in the slice expression are replaced by zero or '
                  '"sys.maxsize",\n'
-                 '   respectively.  If negative indexes are used in the '
-                 'slice, the\n'
+                 '   respectively.  If negative indexes are used in the slice, '
+                 'the\n'
                  '   length of the sequence is added to that index. If the '
                  'instance does\n'
-                 '   not implement the "__len__()" method, an '
-                 '"AttributeError" is\n'
+                 '   not implement the "__len__()" method, an "AttributeError" '
+                 'is\n'
                  '   raised. No guarantee is made that indexes adjusted this '
                  'way are not\n'
                  '   still negative.  Indexes which are greater than the '
                  'length of the\n'
                  '   sequence are not modified. If no "__getslice__()" is '
                  'found, a slice\n'
-                 '   object is created instead, and passed to '
-                 '"__getitem__()" instead.\n'
+                 '   object is created instead, and passed to "__getitem__()" '
+                 'instead.\n'
                  '\n'
                  'object.__setslice__(self, i, j, sequence)\n'
                  '\n'
-                 '   Called to implement assignment to "self[i:j]". Same '
-                 'notes for *i*\n'
+                 '   Called to implement assignment to "self[i:j]". Same notes '
+                 'for *i*\n'
                  '   and *j* as for "__getslice__()".\n'
                  '\n'
                  '   This method is deprecated. If no "__setslice__()" is '
@@ -8085,10 +8270,9 @@ topics = {'assert': '\n'
                  'for *i* and\n'
                  '   *j* as for "__getslice__()". This method is deprecated. '
                  'If no\n'
-                 '   "__delslice__()" is found, or for extended slicing of '
-                 'the form\n'
-                 '   "self[i:j:k]", a slice object is created, and passed '
-                 'to\n'
+                 '   "__delslice__()" is found, or for extended slicing of the '
+                 'form\n'
+                 '   "self[i:j:k]", a slice object is created, and passed to\n'
                  '   "__delitem__()", instead of "__delslice__()" being '
                  'called.\n'
                  '\n'
@@ -8096,8 +8280,8 @@ topics = {'assert': '\n'
                  'slice with a\n'
                  'single colon is used, and the slice method is available.  '
                  'For slice\n'
-                 'operations involving extended slice notation, or in '
-                 'absence of the\n'
+                 'operations involving extended slice notation, or in absence '
+                 'of the\n'
                  'slice methods, "__getitem__()", "__setitem__()" or '
                  '"__delitem__()" is\n'
                  'called with a slice object as argument.\n'
@@ -8106,8 +8290,8 @@ topics = {'assert': '\n'
                  'or module\n'
                  'compatible with earlier versions of Python (assuming that '
                  'methods\n'
-                 '"__getitem__()", "__setitem__()" and "__delitem__()" '
-                 'support slice\n'
+                 '"__getitem__()", "__setitem__()" and "__delitem__()" support '
+                 'slice\n'
                  'objects as arguments):\n'
                  '\n'
                  '   class MyClass:\n'
@@ -8139,8 +8323,8 @@ topics = {'assert': '\n'
                  'receive them\n'
                  'as provided, but the "__*slice__()" methods get a "cooked" '
                  'form of the\n'
-                 'index values.  For each negative index value, the length '
-                 'of the\n'
+                 'index values.  For each negative index value, the length of '
+                 'the\n'
                  'sequence is added to the index before calling the method '
                  '(which may\n'
                  'still result in a negative index); this is the customary '
@@ -8149,12 +8333,12 @@ topics = {'assert': '\n'
                  '"__*item__()"\n'
                  'methods are expected to do this as well.  However, since '
                  'they should\n'
-                 'already be doing that, negative indexes cannot be passed '
-                 'in; they must\n'
+                 'already be doing that, negative indexes cannot be passed in; '
+                 'they must\n'
                  'be constrained to the bounds of the sequence before being '
                  'passed to\n'
-                 'the "__*item__()" methods. Calling "max(0, i)" '
-                 'conveniently returns\n'
+                 'the "__*item__()" methods. Calling "max(0, i)" conveniently '
+                 'returns\n'
                  'the proper value.\n'
                  '\n'
                  '\n'
@@ -8192,10 +8376,10 @@ topics = {'assert': '\n'
                  'that has an\n'
                  '   "__add__()" method, "x.__add__(y)" is called.  The '
                  '"__divmod__()"\n'
-                 '   method should be the equivalent to using '
-                 '"__floordiv__()" and\n'
-                 '   "__mod__()"; it should not be related to '
-                 '"__truediv__()" (described\n'
+                 '   method should be the equivalent to using "__floordiv__()" '
+                 'and\n'
+                 '   "__mod__()"; it should not be related to "__truediv__()" '
+                 '(described\n'
                  '   below).  Note that "__pow__()" should be defined to '
                  'accept an\n'
                  '   optional third argument if the ternary version of the '
@@ -8211,12 +8395,12 @@ topics = {'assert': '\n'
                  '\n'
                  '   The division operator ("/") is implemented by these '
                  'methods.  The\n'
-                 '   "__truediv__()" method is used when '
-                 '"__future__.division" is in\n'
+                 '   "__truediv__()" method is used when "__future__.division" '
+                 'is in\n'
                  '   effect, otherwise "__div__()" is used.  If only one of '
                  'these two\n'
-                 '   methods is defined, the object will not support '
-                 'division in the\n'
+                 '   methods is defined, the object will not support division '
+                 'in the\n'
                  '   alternate context; "TypeError" will be raised instead.\n'
                  '\n'
                  'object.__radd__(self, other)\n'
@@ -8236,14 +8420,14 @@ topics = {'assert': '\n'
                  '\n'
                  '   These methods are called to implement the binary '
                  'arithmetic\n'
-                 '   operations ("+", "-", "*", "/", "%", "divmod()", '
-                 '"pow()", "**",\n'
+                 '   operations ("+", "-", "*", "/", "%", "divmod()", "pow()", '
+                 '"**",\n'
                  '   "<<", ">>", "&", "^", "|") with reflected (swapped) '
                  'operands.\n'
-                 '   These functions are only called if the left operand '
-                 'does not\n'
-                 '   support the corresponding operation and the operands '
-                 'are of\n'
+                 '   These functions are only called if the left operand does '
+                 'not\n'
+                 '   support the corresponding operation and the operands are '
+                 'of\n'
                  '   different types. [2] For instance, to evaluate the '
                  'expression "x -\n'
                  '   y", where *y* is an instance of a class that has an '
@@ -8258,8 +8442,8 @@ topics = {'assert': '\n'
                  '\n'
                  "   Note: If the right operand's type is a subclass of the "
                  'left\n'
-                 "     operand's type and that subclass provides the "
-                 'reflected method\n'
+                 "     operand's type and that subclass provides the reflected "
+                 'method\n'
                  '     for the operation, this method will be called before '
                  'the left\n'
                  "     operand's non-reflected method.  This behavior allows "
@@ -8282,8 +8466,8 @@ topics = {'assert': '\n'
                  '\n'
                  '   These methods are called to implement the augmented '
                  'arithmetic\n'
-                 '   assignments ("+=", "-=", "*=", "/=", "//=", "%=", '
-                 '"**=", "<<=",\n'
+                 '   assignments ("+=", "-=", "*=", "/=", "//=", "%=", "**=", '
+                 '"<<=",\n'
                  '   ">>=", "&=", "^=", "|=").  These methods should attempt '
                  'to do the\n'
                  '   operation in-place (modifying *self*) and return the '
@@ -8300,16 +8484,16 @@ topics = {'assert': '\n'
                  'class that\n'
                  '   does not define a "__iadd__()" method, "x.__add__(y)" '
                  'and\n'
-                 '   "y.__radd__(x)" are considered, as with the evaluation '
-                 'of "x + y".\n'
+                 '   "y.__radd__(x)" are considered, as with the evaluation of '
+                 '"x + y".\n'
                  '\n'
                  'object.__neg__(self)\n'
                  'object.__pos__(self)\n'
                  'object.__abs__(self)\n'
                  'object.__invert__(self)\n'
                  '\n'
-                 '   Called to implement the unary arithmetic operations '
-                 '("-", "+",\n'
+                 '   Called to implement the unary arithmetic operations ("-", '
+                 '"+",\n'
                  '   "abs()" and "~").\n'
                  '\n'
                  'object.__complex__(self)\n'
@@ -8344,8 +8528,8 @@ topics = {'assert': '\n'
                  '\n'
                  '   Called to implement "mixed-mode" numeric arithmetic.  '
                  'Should either\n'
-                 '   return a 2-tuple containing *self* and *other* '
-                 'converted to a\n'
+                 '   return a 2-tuple containing *self* and *other* converted '
+                 'to a\n'
                  '   common numeric type, or "None" if conversion is '
                  'impossible.  When\n'
                  '   the common type would be the type of "other", it is '
@@ -8356,8 +8540,8 @@ topics = {'assert': '\n'
                  'implementation of the\n'
                  '   other type cannot be changed, it is useful to do the '
                  'conversion to\n'
-                 '   the other type here).  A return value of '
-                 '"NotImplemented" is\n'
+                 '   the other type here).  A return value of "NotImplemented" '
+                 'is\n'
                  '   equivalent to returning "None".\n'
                  '\n'
                  '\n'
@@ -8369,14 +8553,14 @@ topics = {'assert': '\n'
                  'has evolved, the coercion rules have become hard to '
                  'document\n'
                  'precisely; documenting what one version of one particular\n'
-                 'implementation does is undesirable.  Instead, here are '
-                 'some informal\n'
+                 'implementation does is undesirable.  Instead, here are some '
+                 'informal\n'
                  'guidelines regarding coercion.  In Python 3, coercion will '
                  'not be\n'
                  'supported.\n'
                  '\n'
-                 '* If the left operand of a % operator is a string or '
-                 'Unicode object,\n'
+                 '* If the left operand of a % operator is a string or Unicode '
+                 'object,\n'
                  '  no coercion takes place and the string formatting '
                  'operation is\n'
                  '  invoked instead.\n'
@@ -8400,29 +8584,29 @@ topics = {'assert': '\n'
                  'implemented\n'
                  '  at all.\n'
                  '\n'
-                 '* Below, "__op__()" and "__rop__()" are used to signify '
-                 'the generic\n'
-                 '  method names corresponding to an operator; "__iop__()" '
-                 'is used for\n'
-                 '  the corresponding in-place operator.  For example, for '
-                 'the operator\n'
+                 '* Below, "__op__()" and "__rop__()" are used to signify the '
+                 'generic\n'
+                 '  method names corresponding to an operator; "__iop__()" is '
+                 'used for\n'
+                 '  the corresponding in-place operator.  For example, for the '
+                 'operator\n'
                  '  \'"+"\', "__add__()" and "__radd__()" are used for the '
                  'left and right\n'
                  '  variant of the binary operator, and "__iadd__()" for the '
                  'in-place\n'
                  '  variant.\n'
                  '\n'
-                 '* For objects *x* and *y*, first "x.__op__(y)" is tried.  '
-                 'If this is\n'
+                 '* For objects *x* and *y*, first "x.__op__(y)" is tried.  If '
+                 'this is\n'
                  '  not implemented or returns "NotImplemented", '
                  '"y.__rop__(x)" is\n'
                  '  tried.  If this is also not implemented or returns '
                  '"NotImplemented",\n'
-                 '  a "TypeError" exception is raised.  But see the '
-                 'following exception:\n'
+                 '  a "TypeError" exception is raised.  But see the following '
+                 'exception:\n'
                  '\n'
-                 '* Exception to the previous item: if the left operand is '
-                 'an instance\n'
+                 '* Exception to the previous item: if the left operand is an '
+                 'instance\n'
                  '  of a built-in type or a new-style class, and the right '
                  'operand is an\n'
                  '  instance of a proper subclass of that type or class and '
@@ -8442,44 +8626,42 @@ topics = {'assert': '\n'
                  'always\n'
                  '  acceptable.\n'
                  '\n'
-                 '* When either operand type defines a coercion, this '
-                 'coercion is\n'
+                 '* When either operand type defines a coercion, this coercion '
+                 'is\n'
                  '  called before that type\'s "__op__()" or "__rop__()" '
                  'method is\n'
-                 '  called, but no sooner.  If the coercion returns an '
-                 'object of a\n'
-                 '  different type for the operand whose coercion is '
-                 'invoked, part of\n'
+                 '  called, but no sooner.  If the coercion returns an object '
+                 'of a\n'
+                 '  different type for the operand whose coercion is invoked, '
+                 'part of\n'
                  '  the process is redone using the new object.\n'
                  '\n'
-                 '* When an in-place operator (like \'"+="\') is used, if '
-                 'the left\n'
-                 '  operand implements "__iop__()", it is invoked without '
-                 'any coercion.\n'
+                 '* When an in-place operator (like \'"+="\') is used, if the '
+                 'left\n'
+                 '  operand implements "__iop__()", it is invoked without any '
+                 'coercion.\n'
                  '  When the operation falls back to "__op__()" and/or '
                  '"__rop__()", the\n'
                  '  normal coercion rules apply.\n'
                  '\n'
-                 '* In "x + y", if *x* is a sequence that implements '
-                 'sequence\n'
+                 '* In "x + y", if *x* is a sequence that implements sequence\n'
                  '  concatenation, sequence concatenation is invoked.\n'
                  '\n'
                  '* In "x * y", if one operand is a sequence that implements '
                  'sequence\n'
-                 '  repetition, and the other is an integer ("int" or '
-                 '"long"), sequence\n'
+                 '  repetition, and the other is an integer ("int" or "long"), '
+                 'sequence\n'
                  '  repetition is invoked.\n'
                  '\n'
-                 '* Rich comparisons (implemented by methods "__eq__()" and '
-                 'so on)\n'
-                 '  never use coercion.  Three-way comparison (implemented '
-                 'by\n'
+                 '* Rich comparisons (implemented by methods "__eq__()" and so '
+                 'on)\n'
+                 '  never use coercion.  Three-way comparison (implemented by\n'
                  '  "__cmp__()") does use coercion under the same conditions '
                  'as other\n'
                  '  binary operations use it.\n'
                  '\n'
-                 '* In the current implementation, the built-in numeric '
-                 'types "int",\n'
+                 '* In the current implementation, the built-in numeric types '
+                 '"int",\n'
                  '  "long", "float", and "complex" do not use coercion. All '
                  'these types\n'
                  '  implement a "__coerce__()" method, for use by the '
@@ -8506,10 +8688,10 @@ topics = {'assert': '\n'
                  'runtime context\n'
                  'for the execution of the block of code.  Context managers '
                  'are normally\n'
-                 'invoked using the "with" statement (described in section '
-                 'The with\n'
-                 'statement), but can also be used by directly invoking '
-                 'their methods.\n'
+                 'invoked using the "with" statement (described in section The '
+                 'with\n'
+                 'statement), but can also be used by directly invoking their '
+                 'methods.\n'
                  '\n'
                  'Typical uses of context managers include saving and '
                  'restoring various\n'
@@ -8550,8 +8732,9 @@ topics = {'assert': '\n'
                  'passed-in\n'
                  "   exception; this is the caller's responsibility.\n"
                  '\n'
-                 'See also: **PEP 0343** - The "with" statement\n'
+                 'See also:\n'
                  '\n'
+                 '  **PEP 343** - The "with" statement\n'
                  '     The specification, background, and examples for the '
                  'Python "with"\n'
                  '     statement.\n'
@@ -8560,8 +8743,8 @@ topics = {'assert': '\n'
                  'Special method lookup for old-style classes\n'
                  '===========================================\n'
                  '\n'
-                 'For old-style classes, special methods are always looked '
-                 'up in exactly\n'
+                 'For old-style classes, special methods are always looked up '
+                 'in exactly\n'
                  'the same way as any other method or attribute. This is the '
                  'case\n'
                  'regardless of whether the method is being looked up '
@@ -8592,10 +8775,10 @@ topics = {'assert': '\n'
                  '\n'
                  'For new-style classes, implicit invocations of special '
                  'methods are\n'
-                 'only guaranteed to work correctly if defined on an '
-                 "object's type, not\n"
-                 "in the object's instance dictionary.  That behaviour is "
-                 'the reason why\n'
+                 "only guaranteed to work correctly if defined on an object's "
+                 'type, not\n'
+                 "in the object's instance dictionary.  That behaviour is the "
+                 'reason why\n'
                  'the following code raises an exception (unlike the '
                  'equivalent example\n'
                  'with old-style classes):\n'
@@ -8614,8 +8797,8 @@ topics = {'assert': '\n'
                  'special\n'
                  'methods such as "__hash__()" and "__repr__()" that are '
                  'implemented by\n'
-                 'all objects, including type objects. If the implicit '
-                 'lookup of these\n'
+                 'all objects, including type objects. If the implicit lookup '
+                 'of these\n'
                  'methods used the conventional lookup process, they would '
                  'fail when\n'
                  'invoked on the type object itself:\n'
@@ -8625,15 +8808,14 @@ topics = {'assert': '\n'
                  '   >>> int.__hash__() == hash(int)\n'
                  '   Traceback (most recent call last):\n'
                  '     File "<stdin>", line 1, in <module>\n'
-                 "   TypeError: descriptor '__hash__' of 'int' object needs "
-                 'an argument\n'
+                 "   TypeError: descriptor '__hash__' of 'int' object needs an "
+                 'argument\n'
                  '\n'
                  'Incorrectly attempting to invoke an unbound method of a '
                  'class in this\n'
                  "way is sometimes referred to as 'metaclass confusion', and "
                  'is avoided\n'
-                 'by bypassing the instance when looking up special '
-                 'methods:\n'
+                 'by bypassing the instance when looking up special methods:\n'
                  '\n'
                  '   >>> type(1).__hash__(1) == hash(1)\n'
                  '   True\n'
@@ -8672,8 +8854,8 @@ topics = {'assert': '\n'
                  '   >>> len(c)                      # Implicit lookup\n'
                  '   10\n'
                  '\n'
-                 'Bypassing the "__getattribute__()" machinery in this '
-                 'fashion provides\n'
+                 'Bypassing the "__getattribute__()" machinery in this fashion '
+                 'provides\n'
                  'significant scope for speed optimisations within the '
                  'interpreter, at\n'
                  'the cost of some flexibility in the handling of special '
@@ -8686,14 +8868,14 @@ topics = {'assert': '\n'
                  '\n'
                  "[1] It *is* possible in some cases to change an object's "
                  'type,\n'
-                 '    under certain controlled conditions. It generally '
-                 "isn't a good\n"
+                 "    under certain controlled conditions. It generally isn't "
+                 'a good\n'
                  '    idea though, since it can lead to some very strange '
                  'behaviour if\n'
                  '    it is handled incorrectly.\n'
                  '\n'
-                 '[2] For operands of the same type, it is assumed that if '
-                 'the non-\n'
+                 '[2] For operands of the same type, it is assumed that if the '
+                 'non-\n'
                  '    reflected method (such as "__add__()") fails the '
                  'operation is not\n'
                  '    supported, which is why the reflected method is not '
@@ -8704,8 +8886,8 @@ topics = {'assert': '\n'
                    '\n'
                    'Below are listed the string methods which both 8-bit '
                    'strings and\n'
-                   'Unicode objects support.  Some of them are also '
-                   'available on\n'
+                   'Unicode objects support.  Some of them are also available '
+                   'on\n'
                    '"bytearray" objects.\n'
                    '\n'
                    "In addition, Python's strings support the sequence type "
@@ -8730,8 +8912,8 @@ topics = {'assert': '\n'
                    '\n'
                    'str.center(width[, fillchar])\n'
                    '\n'
-                   '   Return centered in a string of length *width*. '
-                   'Padding is done\n'
+                   '   Return centered in a string of length *width*. Padding '
+                   'is done\n'
                    '   using the specified *fillchar* (default is a space).\n'
                    '\n'
                    '   Changed in version 2.4: Support for the *fillchar* '
@@ -8751,8 +8933,8 @@ topics = {'assert': '\n'
                    '*encoding*.\n'
                    '   *encoding* defaults to the default string encoding.  '
                    '*errors* may\n'
-                   '   be given to set a different error handling scheme.  '
-                   'The default is\n'
+                   '   be given to set a different error handling scheme.  The '
+                   'default is\n'
                    '   "\'strict\'", meaning that encoding errors raise '
                    '"UnicodeError".\n'
                    '   Other possible values are "\'ignore\'", "\'replace\'" '
@@ -8774,28 +8956,27 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return an encoded version of the string.  Default '
                    'encoding is the\n'
-                   '   current default string encoding.  *errors* may be '
-                   'given to set a\n'
+                   '   current default string encoding.  *errors* may be given '
+                   'to set a\n'
                    '   different error handling scheme.  The default for '
                    '*errors* is\n'
                    '   "\'strict\'", meaning that encoding errors raise a '
                    '"UnicodeError".\n'
-                   '   Other possible values are "\'ignore\'", '
-                   '"\'replace\'",\n'
-                   '   "\'xmlcharrefreplace\'", "\'backslashreplace\'" and '
-                   'any other name\n'
+                   '   Other possible values are "\'ignore\'", "\'replace\'",\n'
+                   '   "\'xmlcharrefreplace\'", "\'backslashreplace\'" and any '
+                   'other name\n'
                    '   registered via "codecs.register_error()", see section '
                    'Codec Base\n'
-                   '   Classes. For a list of possible encodings, see '
-                   'section Standard\n'
+                   '   Classes. For a list of possible encodings, see section '
+                   'Standard\n'
                    '   Encodings.\n'
                    '\n'
                    '   New in version 2.0.\n'
                    '\n'
                    '   Changed in version 2.3: Support for '
                    '"\'xmlcharrefreplace\'" and\n'
-                   '   "\'backslashreplace\'" and other error handling '
-                   'schemes added.\n'
+                   '   "\'backslashreplace\'" and other error handling schemes '
+                   'added.\n'
                    '\n'
                    '   Changed in version 2.7: Support for keyword arguments '
                    'added.\n'
@@ -8804,12 +8985,12 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return "True" if the string ends with the specified '
                    '*suffix*,\n'
-                   '   otherwise return "False".  *suffix* can also be a '
-                   'tuple of suffixes\n'
-                   '   to look for.  With optional *start*, test beginning '
-                   'at that\n'
-                   '   position.  With optional *end*, stop comparing at '
-                   'that position.\n'
+                   '   otherwise return "False".  *suffix* can also be a tuple '
+                   'of suffixes\n'
+                   '   to look for.  With optional *start*, test beginning at '
+                   'that\n'
+                   '   position.  With optional *end*, stop comparing at that '
+                   'position.\n'
                    '\n'
                    '   Changed in version 2.5: Accept tuples as *suffix*.\n'
                    '\n'
@@ -8817,28 +8998,28 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return a copy of the string where all tab characters '
                    'are replaced\n'
-                   '   by one or more spaces, depending on the current '
-                   'column and the\n'
+                   '   by one or more spaces, depending on the current column '
+                   'and the\n'
                    '   given tab size.  Tab positions occur every *tabsize* '
                    'characters\n'
-                   '   (default is 8, giving tab positions at columns 0, 8, '
-                   '16 and so on).\n'
-                   '   To expand the string, the current column is set to '
-                   'zero and the\n'
+                   '   (default is 8, giving tab positions at columns 0, 8, 16 '
+                   'and so on).\n'
+                   '   To expand the string, the current column is set to zero '
+                   'and the\n'
                    '   string is examined character by character.  If the '
                    'character is a\n'
-                   '   tab ("\\t"), one or more space characters are '
-                   'inserted in the result\n'
+                   '   tab ("\\t"), one or more space characters are inserted '
+                   'in the result\n'
                    '   until the current column is equal to the next tab '
                    'position. (The\n'
-                   '   tab character itself is not copied.)  If the '
-                   'character is a newline\n'
-                   '   ("\\n") or return ("\\r"), it is copied and the '
-                   'current column is\n'
-                   '   reset to zero.  Any other character is copied '
-                   'unchanged and the\n'
-                   '   current column is incremented by one regardless of '
-                   'how the\n'
+                   '   tab character itself is not copied.)  If the character '
+                   'is a newline\n'
+                   '   ("\\n") or return ("\\r"), it is copied and the current '
+                   'column is\n'
+                   '   reset to zero.  Any other character is copied unchanged '
+                   'and the\n'
+                   '   current column is incremented by one regardless of how '
+                   'the\n'
                    '   character is represented when printed.\n'
                    '\n'
                    "   >>> '01\\t012\\t0123\\t01234'.expandtabs()\n"
@@ -8850,11 +9031,11 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return the lowest index in the string where substring '
                    '*sub* is\n'
-                   '   found, such that *sub* is contained in the slice '
-                   '"s[start:end]".\n'
-                   '   Optional arguments *start* and *end* are interpreted '
-                   'as in slice\n'
-                   '   notation.  Return "-1" if *sub* is not found.\n'
+                   '   found within the slice "s[start:end]".  Optional '
+                   'arguments *start*\n'
+                   '   and *end* are interpreted as in slice notation.  Return '
+                   '"-1" if\n'
+                   '   *sub* is not found.\n'
                    '\n'
                    '   Note: The "find()" method should be used only if you '
                    'need to know\n'
@@ -8873,12 +9054,12 @@ topics = {'assert': '\n'
                    'replacement fields\n'
                    '   delimited by braces "{}".  Each replacement field '
                    'contains either\n'
-                   '   the numeric index of a positional argument, or the '
-                   'name of a\n'
+                   '   the numeric index of a positional argument, or the name '
+                   'of a\n'
                    '   keyword argument.  Returns a copy of the string where '
                    'each\n'
-                   '   replacement field is replaced with the string value '
-                   'of the\n'
+                   '   replacement field is replaced with the string value of '
+                   'the\n'
                    '   corresponding argument.\n'
                    '\n'
                    '   >>> "The sum of 1 + 2 is {0}".format(1+2)\n'
@@ -8889,10 +9070,10 @@ topics = {'assert': '\n'
                    '   formatting options that can be specified in format '
                    'strings.\n'
                    '\n'
-                   '   This method of string formatting is the new standard '
-                   'in Python 3,\n'
-                   '   and should be preferred to the "%" formatting '
-                   'described in String\n'
+                   '   This method of string formatting is the new standard in '
+                   'Python 3,\n'
+                   '   and should be preferred to the "%" formatting described '
+                   'in String\n'
                    '   Formatting Operations in new code.\n'
                    '\n'
                    '   New in version 2.6.\n'
@@ -8921,8 +9102,8 @@ topics = {'assert': '\n'
                    '\n'
                    'str.isdigit()\n'
                    '\n'
-                   '   Return true if all characters in the string are '
-                   'digits and there is\n'
+                   '   Return true if all characters in the string are digits '
+                   'and there is\n'
                    '   at least one character, false otherwise.\n'
                    '\n'
                    '   For 8-bit strings, this method is locale-dependent.\n'
@@ -8938,10 +9119,9 @@ topics = {'assert': '\n'
                    '\n'
                    'str.isspace()\n'
                    '\n'
-                   '   Return true if there are only whitespace characters '
-                   'in the string\n'
-                   '   and there is at least one character, false '
-                   'otherwise.\n'
+                   '   Return true if there are only whitespace characters in '
+                   'the string\n'
+                   '   and there is at least one character, false otherwise.\n'
                    '\n'
                    '   For 8-bit strings, this method is locale-dependent.\n'
                    '\n'
@@ -8951,8 +9131,8 @@ topics = {'assert': '\n'
                    'there is at\n'
                    '   least one character, for example uppercase characters '
                    'may only\n'
-                   '   follow uncased characters and lowercase characters '
-                   'only cased ones.\n'
+                   '   follow uncased characters and lowercase characters only '
+                   'cased ones.\n'
                    '   Return false otherwise.\n'
                    '\n'
                    '   For 8-bit strings, this method is locale-dependent.\n'
@@ -8970,18 +9150,18 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return a string which is the concatenation of the '
                    'strings in the\n'
-                   '   *iterable* *iterable*.  The separator between '
-                   'elements is the\n'
+                   '   *iterable* *iterable*.  The separator between elements '
+                   'is the\n'
                    '   string providing this method.\n'
                    '\n'
                    'str.ljust(width[, fillchar])\n'
                    '\n'
-                   '   Return the string left justified in a string of '
-                   'length *width*.\n'
-                   '   Padding is done using the specified *fillchar* '
-                   '(default is a\n'
-                   '   space).  The original string is returned if *width* '
-                   'is less than or\n'
+                   '   Return the string left justified in a string of length '
+                   '*width*.\n'
+                   '   Padding is done using the specified *fillchar* (default '
+                   'is a\n'
+                   '   space).  The original string is returned if *width* is '
+                   'less than or\n'
                    '   equal to "len(s)".\n'
                    '\n'
                    '   Changed in version 2.4: Support for the *fillchar* '
@@ -9017,8 +9197,8 @@ topics = {'assert': '\n'
                    '\n'
                    'str.partition(sep)\n'
                    '\n'
-                   '   Split the string at the first occurrence of *sep*, '
-                   'and return a\n'
+                   '   Split the string at the first occurrence of *sep*, and '
+                   'return a\n'
                    '   3-tuple containing the part before the separator, the '
                    'separator\n'
                    '   itself, and the part after the separator.  If the '
@@ -9033,18 +9213,18 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return a copy of the string with all occurrences of '
                    'substring *old*\n'
-                   '   replaced by *new*.  If the optional argument *count* '
-                   'is given, only\n'
+                   '   replaced by *new*.  If the optional argument *count* is '
+                   'given, only\n'
                    '   the first *count* occurrences are replaced.\n'
                    '\n'
                    'str.rfind(sub[, start[, end]])\n'
                    '\n'
-                   '   Return the highest index in the string where '
-                   'substring *sub* is\n'
+                   '   Return the highest index in the string where substring '
+                   '*sub* is\n'
                    '   found, such that *sub* is contained within '
                    '"s[start:end]".\n'
-                   '   Optional arguments *start* and *end* are interpreted '
-                   'as in slice\n'
+                   '   Optional arguments *start* and *end* are interpreted as '
+                   'in slice\n'
                    '   notation.  Return "-1" on failure.\n'
                    '\n'
                    'str.rindex(sub[, start[, end]])\n'
@@ -9055,10 +9235,10 @@ topics = {'assert': '\n'
                    '\n'
                    'str.rjust(width[, fillchar])\n'
                    '\n'
-                   '   Return the string right justified in a string of '
-                   'length *width*.\n'
-                   '   Padding is done using the specified *fillchar* '
-                   '(default is a\n'
+                   '   Return the string right justified in a string of length '
+                   '*width*.\n'
+                   '   Padding is done using the specified *fillchar* (default '
+                   'is a\n'
                    '   space). The original string is returned if *width* is '
                    'less than or\n'
                    '   equal to "len(s)".\n'
@@ -9090,8 +9270,8 @@ topics = {'assert': '\n'
                    'specified or\n'
                    '   "None", any whitespace string is a separator.  Except '
                    'for splitting\n'
-                   '   from the right, "rsplit()" behaves like "split()" '
-                   'which is\n'
+                   '   from the right, "rsplit()" behaves like "split()" which '
+                   'is\n'
                    '   described in detail below.\n'
                    '\n'
                    '   New in version 2.4.\n'
@@ -9131,8 +9311,7 @@ topics = {'assert': '\n'
                    '\n'
                    '   If *sep* is given, consecutive delimiters are not '
                    'grouped together\n'
-                   '   and are deemed to delimit empty strings (for '
-                   'example,\n'
+                   '   and are deemed to delimit empty strings (for example,\n'
                    '   "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', '
                    '\'2\']").  The *sep* argument\n'
                    '   may consist of multiple characters (for example,\n'
@@ -9149,13 +9328,13 @@ topics = {'assert': '\n'
                    'empty strings\n'
                    '   at the start or end if the string has leading or '
                    'trailing\n'
-                   '   whitespace.  Consequently, splitting an empty string '
-                   'or a string\n'
+                   '   whitespace.  Consequently, splitting an empty string or '
+                   'a string\n'
                    '   consisting of just whitespace with a "None" separator '
                    'returns "[]".\n'
                    '\n'
-                   '   For example, "\' 1  2   3  \'.split()" returns '
-                   '"[\'1\', \'2\', \'3\']", and\n'
+                   '   For example, "\' 1  2   3  \'.split()" returns "[\'1\', '
+                   '\'2\', \'3\']", and\n'
                    '   "\'  1  2   3  \'.split(None, 1)" returns "[\'1\', '
                    '\'2   3  \']".\n'
                    '\n'
@@ -9173,13 +9352,13 @@ topics = {'assert': '\n'
                    'fg\\rkl\\r\\n\'.splitlines()" returns "[\'ab\n'
                    '   c\', \'\', \'de fg\', \'kl\']", while the same call '
                    'with\n'
-                   '   "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', '
-                   '\'de fg\\r\', \'kl\\r\\n\']".\n'
+                   '   "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de '
+                   'fg\\r\', \'kl\\r\\n\']".\n'
                    '\n'
                    '   Unlike "split()" when a delimiter string *sep* is '
                    'given, this\n'
-                   '   method returns an empty list for the empty string, '
-                   'and a terminal\n'
+                   '   method returns an empty list for the empty string, and '
+                   'a terminal\n'
                    '   line break does not result in an extra line.\n'
                    '\n'
                    'str.startswith(prefix[, start[, end]])\n'
@@ -9201,12 +9380,12 @@ topics = {'assert': '\n'
                    'trailing\n'
                    '   characters removed. The *chars* argument is a string '
                    'specifying the\n'
-                   '   set of characters to be removed. If omitted or '
-                   '"None", the *chars*\n'
+                   '   set of characters to be removed. If omitted or "None", '
+                   'the *chars*\n'
                    '   argument defaults to removing whitespace. The *chars* '
                    'argument is\n'
-                   '   not a prefix or suffix; rather, all combinations of '
-                   'its values are\n'
+                   '   not a prefix or suffix; rather, all combinations of its '
+                   'values are\n'
                    '   stripped:\n'
                    '\n'
                    "   >>> '   spacious   '.strip()\n"
@@ -9234,16 +9413,15 @@ topics = {'assert': '\n'
                    '\n'
                    '   The algorithm uses a simple language-independent '
                    'definition of a\n'
-                   '   word as groups of consecutive letters.  The '
-                   'definition works in\n'
+                   '   word as groups of consecutive letters.  The definition '
+                   'works in\n'
                    '   many contexts but it means that apostrophes in '
                    'contractions and\n'
-                   '   possessives form word boundaries, which may not be '
-                   'the desired\n'
+                   '   possessives form word boundaries, which may not be the '
+                   'desired\n'
                    '   result:\n'
                    '\n'
-                   '      >>> "they\'re bill\'s friends from the '
-                   'UK".title()\n'
+                   '      >>> "they\'re bill\'s friends from the UK".title()\n'
                    '      "They\'Re Bill\'S Friends From The Uk"\n'
                    '\n'
                    '   A workaround for apostrophes can be constructed using '
@@ -9288,10 +9466,10 @@ topics = {'assert': '\n'
                    '   New in version 2.6: Support for a "None" *table* '
                    'argument.\n'
                    '\n'
-                   '   For Unicode objects, the "translate()" method does '
-                   'not accept the\n'
-                   '   optional *deletechars* argument.  Instead, it returns '
-                   'copy of the\n'
+                   '   For Unicode objects, the "translate()" method does not '
+                   'accept the\n'
+                   '   optional *deletechars* argument.  Instead, it returns '
+                   'copy of the\n'
                    '   *s* where all characters have been mapped through the '
                    'given\n'
                    '   translation table which must be a mapping of Unicode '
@@ -9302,8 +9480,8 @@ topics = {'assert': '\n'
                    'deleted.  Note,\n'
                    '   a more flexible approach is to create a custom '
                    'character mapping\n'
-                   '   codec using the "codecs" module (see '
-                   '"encodings.cp1251" for an\n'
+                   '   codec using the "codecs" module (see "encodings.cp1251" '
+                   'for an\n'
                    '   example).\n'
                    '\n'
                    'str.upper()\n'
@@ -9326,8 +9504,8 @@ topics = {'assert': '\n'
                    'string of\n'
                    '   length *width*.  A sign prefix is handled correctly.  '
                    'The original\n'
-                   '   string is returned if *width* is less than or equal '
-                   'to "len(s)".\n'
+                   '   string is returned if *width* is less than or equal to '
+                   '"len(s)".\n'
                    '\n'
                    '   New in version 2.2.2.\n'
                    '\n'
@@ -9338,8 +9516,8 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return "True" if there are only numeric characters in '
                    'S, "False"\n'
-                   '   otherwise. Numeric characters include digit '
-                   'characters, and all\n'
+                   '   otherwise. Numeric characters include digit characters, '
+                   'and all\n'
                    '   characters that have the Unicode numeric value '
                    'property, e.g.\n'
                    '   U+2155, VULGAR FRACTION ONE FIFTH.\n'
@@ -9348,8 +9526,8 @@ topics = {'assert': '\n'
                    '\n'
                    '   Return "True" if there are only decimal characters in '
                    'S, "False"\n'
-                   '   otherwise. Decimal characters include digit '
-                   'characters, and all\n'
+                   '   otherwise. Decimal characters include digit characters, '
+                   'and all\n'
                    '   characters that can be used to form decimal-radix '
                    'numbers, e.g.\n'
                    '   U+0660, ARABIC-INDIC DIGIT ZERO.\n',
@@ -9360,10 +9538,9 @@ topics = {'assert': '\n'
             'String literals are described by the following lexical '
             'definitions:\n'
             '\n'
-            '   stringliteral   ::= [stringprefix](shortstring | '
-            'longstring)\n'
-            '   stringprefix    ::= "r" | "u" | "ur" | "R" | "U" | "UR" | '
-            '"Ur" | "uR"\n'
+            '   stringliteral   ::= [stringprefix](shortstring | longstring)\n'
+            '   stringprefix    ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" '
+            '| "uR"\n'
             '                    | "b" | "B" | "br" | "Br" | "bR" | "BR"\n'
             '   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' '
             'shortstringitem* \'"\'\n'
@@ -9378,8 +9555,8 @@ topics = {'assert': '\n'
             '\n'
             'One syntactic restriction not indicated by these productions is '
             'that\n'
-            'whitespace is not allowed between the "stringprefix" and the '
-            'rest of\n'
+            'whitespace is not allowed between the "stringprefix" and the rest '
+            'of\n'
             'the string literal. The source character set is defined by the\n'
             'encoding declaration; it is ASCII if no encoding declaration is '
             'given\n'
@@ -9387,8 +9564,8 @@ topics = {'assert': '\n'
             '\n'
             'In plain English: String literals can be enclosed in matching '
             'single\n'
-            'quotes ("\'") or double quotes (""").  They can also be '
-            'enclosed in\n'
+            'quotes ("\'") or double quotes (""").  They can also be enclosed '
+            'in\n'
             'matching groups of three single or double quotes (these are '
             'generally\n'
             'referred to as *triple-quoted strings*).  The backslash ("\\")\n'
@@ -9396,12 +9573,12 @@ topics = {'assert': '\n'
             'special\n'
             'meaning, such as newline, backslash itself, or the quote '
             'character.\n'
-            'String literals may optionally be prefixed with a letter '
-            '"\'r\'" or\n'
-            '"\'R\'"; such strings are called *raw strings* and use '
-            'different rules\n'
-            'for interpreting backslash escape sequences.  A prefix of '
-            '"\'u\'" or\n'
+            'String literals may optionally be prefixed with a letter "\'r\'" '
+            'or\n'
+            '"\'R\'"; such strings are called *raw strings* and use different '
+            'rules\n'
+            'for interpreting backslash escape sequences.  A prefix of "\'u\'" '
+            'or\n'
             '"\'U\'" makes the string a Unicode string.  Unicode strings use '
             'the\n'
             'Unicode character set as defined by the Unicode Consortium and '
@@ -9413,26 +9590,24 @@ topics = {'assert': '\n'
             'literal\n'
             'in Python 3 (e.g. when code is automatically converted with '
             '2to3).  A\n'
-            '"\'u\'" or "\'b\'" prefix may be followed by an "\'r\'" '
-            'prefix.\n'
+            '"\'u\'" or "\'b\'" prefix may be followed by an "\'r\'" prefix.\n'
             '\n'
             'In triple-quoted strings, unescaped newlines and quotes are '
             'allowed\n'
-            '(and are retained), except that three unescaped quotes in a '
-            'row\n'
+            '(and are retained), except that three unescaped quotes in a row\n'
             'terminate the string.  (A "quote" is the character used to open '
             'the\n'
             'string, i.e. either "\'" or """.)\n'
             '\n'
-            'Unless an "\'r\'" or "\'R\'" prefix is present, escape '
-            'sequences in\n'
-            'strings are interpreted according to rules similar to those '
-            'used by\n'
+            'Unless an "\'r\'" or "\'R\'" prefix is present, escape sequences '
+            'in\n'
+            'strings are interpreted according to rules similar to those used '
+            'by\n'
             'Standard C.  The recognized escape sequences are:\n'
             '\n'
             '+-------------------+-----------------------------------+---------+\n'
-            '| Escape Sequence   | Meaning                           | '
-            'Notes   |\n'
+            '| Escape Sequence   | Meaning                           | Notes   '
+            '|\n'
             '+===================+===================================+=========+\n'
             '| "\\newline"        | Ignored                           '
             '|         |\n'
@@ -9460,8 +9635,8 @@ topics = {'assert': '\n'
             '+-------------------+-----------------------------------+---------+\n'
             '| "\\N{name}"        | Character named *name* in the     '
             '|         |\n'
-            '|                   | Unicode database (Unicode only)   '
-            '|         |\n'
+            '|                   | Unicode database (Unicode only)   |         '
+            '|\n'
             '+-------------------+-----------------------------------+---------+\n'
             '| "\\r"              | ASCII Carriage Return (CR)        '
             '|         |\n'
@@ -9471,13 +9646,13 @@ topics = {'assert': '\n'
             '+-------------------+-----------------------------------+---------+\n'
             '| "\\uxxxx"          | Character with 16-bit hex value   | '
             '(1)     |\n'
-            '|                   | *xxxx* (Unicode only)             '
-            '|         |\n'
+            '|                   | *xxxx* (Unicode only)             |         '
+            '|\n'
             '+-------------------+-----------------------------------+---------+\n'
             '| "\\Uxxxxxxxx"      | Character with 32-bit hex value   | '
             '(2)     |\n'
-            '|                   | *xxxxxxxx* (Unicode only)         '
-            '|         |\n'
+            '|                   | *xxxxxxxx* (Unicode only)         |         '
+            '|\n'
             '+-------------------+-----------------------------------+---------+\n'
             '| "\\v"              | ASCII Vertical Tab (VT)           '
             '|         |\n'
@@ -9495,40 +9670,36 @@ topics = {'assert': '\n'
             'can\n'
             '   be encoded using this escape sequence.\n'
             '\n'
-            '2. Any Unicode character can be encoded this way, but '
-            'characters\n'
+            '2. Any Unicode character can be encoded this way, but characters\n'
             '   outside the Basic Multilingual Plane (BMP) will be encoded '
             'using a\n'
-            '   surrogate pair if Python is compiled to use 16-bit code '
-            'units (the\n'
+            '   surrogate pair if Python is compiled to use 16-bit code units '
+            '(the\n'
             '   default).\n'
             '\n'
             '3. As in Standard C, up to three octal digits are accepted.\n'
             '\n'
             '4. Unlike in Standard C, exactly two hex digits are required.\n'
             '\n'
-            '5. In a string literal, hexadecimal and octal escapes denote '
-            'the\n'
-            '   byte with the given value; it is not necessary that the '
-            'byte\n'
-            '   encodes a character in the source character set. In a '
-            'Unicode\n'
+            '5. In a string literal, hexadecimal and octal escapes denote the\n'
+            '   byte with the given value; it is not necessary that the byte\n'
+            '   encodes a character in the source character set. In a Unicode\n'
             '   literal, these escapes denote a Unicode character with the '
             'given\n'
             '   value.\n'
             '\n'
-            'Unlike Standard C, all unrecognized escape sequences are left '
-            'in the\n'
+            'Unlike Standard C, all unrecognized escape sequences are left in '
+            'the\n'
             'string unchanged, i.e., *the backslash is left in the string*.  '
             '(This\n'
             'behavior is useful when debugging: if an escape sequence is '
             'mistyped,\n'
-            'the resulting output is more easily recognized as broken.)  It '
-            'is also\n'
+            'the resulting output is more easily recognized as broken.)  It is '
+            'also\n'
             'important to note that the escape sequences marked as "(Unicode '
             'only)"\n'
-            'in the table above fall into the category of unrecognized '
-            'escapes for\n'
+            'in the table above fall into the category of unrecognized escapes '
+            'for\n'
             'non-Unicode string literals.\n'
             '\n'
             'When an "\'r\'" or "\'R\'" prefix is present, a character '
@@ -9536,22 +9707,21 @@ topics = {'assert': '\n'
             'backslash is included in the string without change, and *all\n'
             'backslashes are left in the string*.  For example, the string '
             'literal\n'
-            '"r"\\n"" consists of two characters: a backslash and a '
-            'lowercase "\'n\'".\n'
-            'String quotes can be escaped with a backslash, but the '
-            'backslash\n'
+            '"r"\\n"" consists of two characters: a backslash and a lowercase '
+            '"\'n\'".\n'
+            'String quotes can be escaped with a backslash, but the backslash\n'
             'remains in the string; for example, "r"\\""" is a valid string '
             'literal\n'
             'consisting of two characters: a backslash and a double quote; '
             '"r"\\""\n'
-            'is not a valid string literal (even a raw string cannot end in '
-            'an odd\n'
+            'is not a valid string literal (even a raw string cannot end in an '
+            'odd\n'
             'number of backslashes).  Specifically, *a raw string cannot end '
             'in a\n'
             'single backslash* (since the backslash would escape the '
             'following\n'
-            'quote character).  Note also that a single backslash followed '
-            'by a\n'
+            'quote character).  Note also that a single backslash followed by '
+            'a\n'
             'newline is interpreted as those two characters as part of the '
             'string,\n'
             '*not* as a line continuation.\n'
@@ -9560,8 +9730,8 @@ topics = {'assert': '\n'
             '"\'u\'" or\n'
             '"\'U\'" prefix, then the "\\uXXXX" and "\\UXXXXXXXX" escape '
             'sequences are\n'
-            'processed while  *all other backslashes are left in the '
-            'string*. For\n'
+            'processed while  *all other backslashes are left in the string*. '
+            'For\n'
             'example, the string literal "ur"\\u0062\\n"" consists of three '
             'Unicode\n'
             "characters: 'LATIN SMALL LETTER B', 'REVERSE SOLIDUS', and "
@@ -9569,15 +9739,15 @@ topics = {'assert': '\n'
             "SMALL LETTER N'. Backslashes can be escaped with a preceding\n"
             'backslash; however, both remain in the string.  As a result, '
             '"\\uXXXX"\n'
-            'escape sequences are only recognized when there are an odd '
-            'number of\n'
+            'escape sequences are only recognized when there are an odd number '
+            'of\n'
             'backslashes.\n',
  'subscriptions': '\n'
                   'Subscriptions\n'
                   '*************\n'
                   '\n'
-                  'A subscription selects an item of a sequence (string, '
-                  'tuple or list)\n'
+                  'A subscription selects an item of a sequence (string, tuple '
+                  'or list)\n'
                   'or mapping (dictionary) object:\n'
                   '\n'
                   '   subscription ::= primary "[" expression_list "]"\n'
@@ -9601,10 +9771,10 @@ topics = {'assert': '\n'
                   'the sequence\n'
                   'is added to it (so that, e.g., "x[-1]" selects the last '
                   'item of "x".)\n'
-                  'The resulting value must be a nonnegative integer less '
-                  'than the number\n'
-                  'of items in the sequence, and the subscription selects '
-                  'the item whose\n'
+                  'The resulting value must be a nonnegative integer less than '
+                  'the number\n'
+                  'of items in the sequence, and the subscription selects the '
+                  'item whose\n'
                   'index is that value (counting from zero).\n'
                   '\n'
                   "A string's items are characters.  A character is not a "
@@ -9640,8 +9810,7 @@ topics = {'assert': '\n'
           '\n'
           'Operations and built-in functions that have a Boolean result '
           'always\n'
-          'return "0" or "False" for false and "1" or "True" for true, '
-          'unless\n'
+          'return "0" or "False" for false and "1" or "True" for true, unless\n'
           'otherwise stated. (Important exception: the Boolean operations '
           '"or"\n'
           'and "and" always return one of their operands.)\n',
@@ -9649,14 +9818,13 @@ topics = {'assert': '\n'
         'The "try" statement\n'
         '*******************\n'
         '\n'
-        'The "try" statement specifies exception handlers and/or cleanup '
-        'code\n'
+        'The "try" statement specifies exception handlers and/or cleanup code\n'
         'for a group of statements:\n'
         '\n'
         '   try_stmt  ::= try1_stmt | try2_stmt\n'
         '   try1_stmt ::= "try" ":" suite\n'
-        '                 ("except" [expression [("as" | ",") identifier]] '
-        '":" suite)+\n'
+        '                 ("except" [expression [("as" | ",") identifier]] ":" '
+        'suite)+\n'
         '                 ["else" ":" suite]\n'
         '                 ["finally" ":" suite]\n'
         '   try2_stmt ::= "try" ":" suite\n'
@@ -9677,16 +9845,12 @@ topics = {'assert': '\n'
         'in turn until one is found that matches the exception.  An '
         'expression-\n'
         'less except clause, if present, must be last; it matches any\n'
-        'exception.  For an except clause with an expression, that '
-        'expression\n'
-        'is evaluated, and the clause matches the exception if the '
-        'resulting\n'
-        'object is "compatible" with the exception.  An object is '
-        'compatible\n'
+        'exception.  For an except clause with an expression, that expression\n'
+        'is evaluated, and the clause matches the exception if the resulting\n'
+        'object is "compatible" with the exception.  An object is compatible\n'
         'with an exception if it is the class or a base class of the '
         'exception\n'
-        'object, or a tuple containing an item compatible with the '
-        'exception.\n'
+        'object, or a tuple containing an item compatible with the exception.\n'
         '\n'
         'If no except clause matches the exception, the search for an '
         'exception\n'
@@ -9694,25 +9858,20 @@ topics = {'assert': '\n'
         'stack.\n'
         '[1]\n'
         '\n'
-        'If the evaluation of an expression in the header of an except '
-        'clause\n'
+        'If the evaluation of an expression in the header of an except clause\n'
         'raises an exception, the original search for a handler is canceled '
         'and\n'
-        'a search starts for the new exception in the surrounding code and '
-        'on\n'
+        'a search starts for the new exception in the surrounding code and on\n'
         'the call stack (it is treated as if the entire "try" statement '
         'raised\n'
         'the exception).\n'
         '\n'
-        'When a matching except clause is found, the exception is assigned '
-        'to\n'
+        'When a matching except clause is found, the exception is assigned to\n'
         'the target specified in that except clause, if present, and the '
         'except\n'
         "clause's suite is executed.  All except clauses must have an\n"
-        'executable block.  When the end of this block is reached, '
-        'execution\n'
-        'continues normally after the entire try statement.  (This means '
-        'that\n'
+        'executable block.  When the end of this block is reached, execution\n'
+        'continues normally after the entire try statement.  (This means that\n'
         'if two nested handlers exist for the same exception, and the '
         'exception\n'
         'occurs in the try clause of the inner handler, the outer handler '
@@ -9724,23 +9883,18 @@ topics = {'assert': '\n'
         '"sys.exc_type" receives the object identifying the exception;\n'
         '"sys.exc_value" receives the exception\'s parameter;\n'
         '"sys.exc_traceback" receives a traceback object (see section The\n'
-        'standard type hierarchy) identifying the point in the program '
-        'where\n'
-        'the exception occurred. These details are also available through '
-        'the\n'
+        'standard type hierarchy) identifying the point in the program where\n'
+        'the exception occurred. These details are also available through the\n'
         '"sys.exc_info()" function, which returns a tuple "(exc_type,\n'
         'exc_value, exc_traceback)".  Use of the corresponding variables is\n'
-        'deprecated in favor of this function, since their use is unsafe in '
-        'a\n'
+        'deprecated in favor of this function, since their use is unsafe in a\n'
         'threaded program.  As of Python 1.5, the variables are restored to\n'
         'their previous values (before the call) when returning from a '
         'function\n'
         'that handled an exception.\n'
         '\n'
-        'The optional "else" clause is executed if and when control flows '
-        'off\n'
-        'the end of the "try" clause. [2] Exceptions in the "else" clause '
-        'are\n'
+        'The optional "else" clause is executed if and when control flows off\n'
+        'the end of the "try" clause. [2] Exceptions in the "else" clause are\n'
         'not handled by the preceding "except" clauses.\n'
         '\n'
         'If "finally" is present, it specifies a \'cleanup\' handler.  The '
@@ -9768,8 +9922,7 @@ topics = {'assert': '\n'
         'The exception information is not available to the program during\n'
         'execution of the "finally" clause.\n'
         '\n'
-        'When a "return", "break" or "continue" statement is executed in '
-        'the\n'
+        'When a "return", "break" or "continue" statement is executed in the\n'
         '"try" suite of a "try"..."finally" statement, the "finally" clause '
         'is\n'
         'also executed \'on the way out.\' A "continue" statement is illegal '
@@ -9802,16 +9955,15 @@ topics = {'assert': '\n'
           '\n'
           'Below is a list of the types that are built into Python.  '
           'Extension\n'
-          'modules (written in C, Java, or other languages, depending on '
-          'the\n'
+          'modules (written in C, Java, or other languages, depending on the\n'
           'implementation) can define additional types.  Future versions of\n'
           'Python may add types to the type hierarchy (e.g., rational '
           'numbers,\n'
           'efficiently stored arrays of integers, etc.).\n'
           '\n'
           'Some of the type descriptions below contain a paragraph listing\n'
-          "'special attributes.'  These are attributes that provide access "
-          'to the\n'
+          "'special attributes.'  These are attributes that provide access to "
+          'the\n'
           'implementation and are not intended for general use.  Their '
           'definition\n'
           'may change in the future.\n'
@@ -9819,8 +9971,8 @@ topics = {'assert': '\n'
           'None\n'
           '   This type has a single value.  There is a single object with '
           'this\n'
-          '   value. This object is accessed through the built-in name '
-          '"None". It\n'
+          '   value. This object is accessed through the built-in name "None". '
+          'It\n'
           '   is used to signify the absence of a value in many situations, '
           'e.g.,\n'
           "   it is returned from functions that don't explicitly return\n"
@@ -9836,8 +9988,8 @@ topics = {'assert': '\n'
           'the\n'
           '   operands provided.  (The interpreter will then try the '
           'reflected\n'
-          '   operation, or some other fallback, depending on the '
-          'operator.)  Its\n'
+          '   operation, or some other fallback, depending on the operator.)  '
+          'Its\n'
           '   truth value is true.\n'
           '\n'
           'Ellipsis\n'
@@ -9853,8 +10005,7 @@ topics = {'assert': '\n'
           'by\n'
           '   arithmetic operators and arithmetic built-in functions.  '
           'Numeric\n'
-          '   objects are immutable; once created their value never '
-          'changes.\n'
+          '   objects are immutable; once created their value never changes.\n'
           '   Python numbers are of course strongly related to mathematical\n'
           '   numbers, but subject to the limitations of numerical '
           'representation\n'
@@ -9872,53 +10023,47 @@ topics = {'assert': '\n'
           '      There are three types of integers:\n'
           '\n'
           '      Plain integers\n'
-          '         These represent numbers in the range -2147483648 '
-          'through\n'
+          '         These represent numbers in the range -2147483648 through\n'
           '         2147483647. (The range may be larger on machines with a\n'
           '         larger natural word size, but not smaller.)  When the '
           'result\n'
-          '         of an operation would fall outside this range, the '
-          'result is\n'
+          '         of an operation would fall outside this range, the result '
+          'is\n'
           '         normally returned as a long integer (in some cases, the\n'
           '         exception "OverflowError" is raised instead).  For the\n'
-          '         purpose of shift and mask operations, integers are '
-          'assumed to\n'
+          '         purpose of shift and mask operations, integers are assumed '
+          'to\n'
           "         have a binary, 2's complement notation using 32 or more "
           'bits,\n'
           '         and hiding no bits from the user (i.e., all 4294967296\n'
           '         different bit patterns correspond to different values).\n'
           '\n'
           '      Long integers\n'
-          '         These represent numbers in an unlimited range, subject '
-          'to\n'
+          '         These represent numbers in an unlimited range, subject to\n'
           '         available (virtual) memory only.  For the purpose of '
           'shift\n'
           '         and mask operations, a binary representation is assumed, '
           'and\n'
           "         negative numbers are represented in a variant of 2's\n"
-          '         complement which gives the illusion of an infinite '
-          'string of\n'
+          '         complement which gives the illusion of an infinite string '
+          'of\n'
           '         sign bits extending to the left.\n'
           '\n'
           '      Booleans\n'
-          '         These represent the truth values False and True.  The '
-          'two\n'
+          '         These represent the truth values False and True.  The two\n'
           '         objects representing the values "False" and "True" are '
           'the\n'
           '         only Boolean objects. The Boolean type is a subtype of '
           'plain\n'
-          '         integers, and Boolean values behave like the values 0 '
-          'and 1,\n'
-          '         respectively, in almost all contexts, the exception '
-          'being\n'
-          '         that when converted to a string, the strings ""False"" '
-          'or\n'
+          '         integers, and Boolean values behave like the values 0 and '
+          '1,\n'
+          '         respectively, in almost all contexts, the exception being\n'
+          '         that when converted to a string, the strings ""False"" or\n'
           '         ""True"" are returned, respectively.\n'
           '\n'
           '      The rules for integer representation are intended to give '
           'the\n'
-          '      most meaningful interpretation of shift and mask '
-          'operations\n'
+          '      most meaningful interpretation of shift and mask operations\n'
           '      involving negative integers and the least surprises when\n'
           '      switching between the plain and long integer domains.  Any\n'
           '      operation, if it yields a result in the plain integer '
@@ -9933,16 +10078,14 @@ topics = {'assert': '\n'
           '      These represent machine-level double precision floating '
           'point\n'
           '      numbers. You are at the mercy of the underlying machine\n'
-          '      architecture (and C or Java implementation) for the '
-          'accepted\n'
+          '      architecture (and C or Java implementation) for the accepted\n'
           '      range and handling of overflow. Python does not support '
           'single-\n'
           '      precision floating point numbers; the savings in processor '
           'and\n'
-          '      memory usage that are usually the reason for using these '
-          'are\n'
-          '      dwarfed by the overhead of using objects in Python, so '
-          'there is\n'
+          '      memory usage that are usually the reason for using these are\n'
+          '      dwarfed by the overhead of using objects in Python, so there '
+          'is\n'
           '      no reason to complicate the language with two kinds of '
           'floating\n'
           '      point numbers.\n'
@@ -9962,12 +10105,11 @@ topics = {'assert': '\n'
           'items\n'
           '   of a sequence. When the length of a sequence is *n*, the index '
           'set\n'
-          '   contains the numbers 0, 1, ..., *n*-1.  Item *i* of sequence '
-          '*a* is\n'
+          '   contains the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* '
+          'is\n'
           '   selected by "a[i]".\n'
           '\n'
-          '   Sequences also support slicing: "a[i:j]" selects all items '
-          'with\n'
+          '   Sequences also support slicing: "a[i:j]" selects all items with\n'
           '   index *k* such that *i* "<=" *k* "<" *j*.  When used as an\n'
           '   expression, a slice is a sequence of the same type.  This '
           'implies\n'
@@ -9982,8 +10124,8 @@ topics = {'assert': '\n'
           '   Sequences are distinguished according to their mutability:\n'
           '\n'
           '   Immutable sequences\n'
-          '      An object of an immutable sequence type cannot change once '
-          'it is\n'
+          '      An object of an immutable sequence type cannot change once it '
+          'is\n'
           '      created.  (If the object contains references to other '
           'objects,\n'
           '      these other objects may be mutable and may be changed; '
@@ -9997,68 +10139,58 @@ topics = {'assert': '\n'
           '      Strings\n'
           '         The items of a string are characters.  There is no '
           'separate\n'
-          '         character type; a character is represented by a string '
-          'of one\n'
+          '         character type; a character is represented by a string of '
+          'one\n'
           '         item. Characters represent (at least) 8-bit bytes.  The\n'
           '         built-in functions "chr()" and "ord()" convert between\n'
-          '         characters and nonnegative integers representing the '
-          'byte\n'
+          '         characters and nonnegative integers representing the byte\n'
           '         values.  Bytes with the values 0-127 usually represent '
           'the\n'
           '         corresponding ASCII values, but the interpretation of '
           'values\n'
           '         is up to the program.  The string data type is also used '
           'to\n'
-          '         represent arrays of bytes, e.g., to hold data read from '
-          'a\n'
+          '         represent arrays of bytes, e.g., to hold data read from a\n'
           '         file.\n'
           '\n'
           '         (On systems whose native character set is not ASCII, '
           'strings\n'
-          '         may use EBCDIC in their internal representation, '
-          'provided the\n'
-          '         functions "chr()" and "ord()" implement a mapping '
-          'between\n'
+          '         may use EBCDIC in their internal representation, provided '
+          'the\n'
+          '         functions "chr()" and "ord()" implement a mapping between\n'
           '         ASCII and EBCDIC, and string comparison preserves the '
           'ASCII\n'
           '         order. Or perhaps someone can propose a better rule?)\n'
           '\n'
           '      Unicode\n'
-          '         The items of a Unicode object are Unicode code units.  '
-          'A\n'
+          '         The items of a Unicode object are Unicode code units.  A\n'
           '         Unicode code unit is represented by a Unicode object of '
           'one\n'
           '         item and can hold either a 16-bit or 32-bit value\n'
-          '         representing a Unicode ordinal (the maximum value for '
-          'the\n'
-          '         ordinal is given in "sys.maxunicode", and depends on '
-          'how\n'
+          '         representing a Unicode ordinal (the maximum value for the\n'
+          '         ordinal is given in "sys.maxunicode", and depends on how\n'
           '         Python is configured at compile time).  Surrogate pairs '
           'may\n'
-          '         be present in the Unicode object, and will be reported '
-          'as two\n'
+          '         be present in the Unicode object, and will be reported as '
+          'two\n'
           '         separate items.  The built-in functions "unichr()" and\n'
           '         "ord()" convert between code units and nonnegative '
           'integers\n'
           '         representing the Unicode ordinals as defined in the '
           'Unicode\n'
-          '         Standard 3.0. Conversion from and to other encodings '
-          'are\n'
+          '         Standard 3.0. Conversion from and to other encodings are\n'
           '         possible through the Unicode method "encode()" and the '
           'built-\n'
           '         in function "unicode()".\n'
           '\n'
           '      Tuples\n'
-          '         The items of a tuple are arbitrary Python objects. '
-          'Tuples of\n'
-          '         two or more items are formed by comma-separated lists '
+          '         The items of a tuple are arbitrary Python objects. Tuples '
           'of\n'
-          "         expressions.  A tuple of one item (a 'singleton') can "
-          'be\n'
-          '         formed by affixing a comma to an expression (an '
-          'expression by\n'
-          '         itself does not create a tuple, since parentheses must '
-          'be\n'
+          '         two or more items are formed by comma-separated lists of\n'
+          "         expressions.  A tuple of one item (a 'singleton') can be\n"
+          '         formed by affixing a comma to an expression (an expression '
+          'by\n'
+          '         itself does not create a tuple, since parentheses must be\n'
           '         usable for grouping of expressions).  An empty tuple can '
           'be\n'
           '         formed by an empty pair of parentheses.\n'
@@ -10066,8 +10198,8 @@ topics = {'assert': '\n'
           '   Mutable sequences\n'
           '      Mutable sequences can be changed after they are created.  '
           'The\n'
-          '      subscription and slicing notations can be used as the '
-          'target of\n'
+          '      subscription and slicing notations can be used as the target '
+          'of\n'
           '      assignment and "del" (delete) statements.\n'
           '\n'
           '      There are currently two intrinsic mutable sequence types:\n'
@@ -10084,8 +10216,7 @@ topics = {'assert': '\n'
           '      Byte Arrays\n'
           '         A bytearray object is a mutable array. They are created '
           'by\n'
-          '         the built-in "bytearray()" constructor.  Aside from '
-          'being\n'
+          '         the built-in "bytearray()" constructor.  Aside from being\n'
           '         mutable (and hence unhashable), byte arrays otherwise '
           'provide\n'
           '         the same interface and functionality as immutable bytes\n'
@@ -10103,15 +10234,13 @@ topics = {'assert': '\n'
           '   returns the number of items in a set. Common uses for sets are '
           'fast\n'
           '   membership testing, removing duplicates from a sequence, and\n'
-          '   computing mathematical operations such as intersection, '
-          'union,\n'
+          '   computing mathematical operations such as intersection, union,\n'
           '   difference, and symmetric difference.\n'
           '\n'
           '   For set elements, the same immutability rules apply as for\n'
           '   dictionary keys. Note that numeric types obey the normal rules '
           'for\n'
-          '   numeric comparison: if two numbers compare equal (e.g., "1" '
-          'and\n'
+          '   numeric comparison: if two numbers compare equal (e.g., "1" and\n'
           '   "1.0"), only one of them can be contained in a set.\n'
           '\n'
           '   There are currently two intrinsic set types:\n'
@@ -10134,8 +10263,8 @@ topics = {'assert': '\n'
           'Mappings\n'
           '   These represent finite sets of objects indexed by arbitrary '
           'index\n'
-          '   sets. The subscript notation "a[k]" selects the item indexed '
-          'by "k"\n'
+          '   sets. The subscript notation "a[k]" selects the item indexed by '
+          '"k"\n'
           '   from the mapping "a"; this can be used in expressions and as '
           'the\n'
           '   target of assignments or "del" statements. The built-in '
@@ -10151,10 +10280,9 @@ topics = {'assert': '\n'
           '      keys are values containing lists or dictionaries or other\n'
           '      mutable types that are compared by value rather than by '
           'object\n'
-          '      identity, the reason being that the efficient '
-          'implementation of\n'
-          "      dictionaries requires a key's hash value to remain "
-          'constant.\n'
+          '      identity, the reason being that the efficient implementation '
+          'of\n'
+          "      dictionaries requires a key's hash value to remain constant.\n"
           '      Numeric types used for keys obey the normal rules for '
           'numeric\n'
           '      comparison: if two numbers compare equal (e.g., "1" and '
@@ -10162,8 +10290,7 @@ topics = {'assert': '\n'
           '      then they can be used interchangeably to index the same\n'
           '      dictionary entry.\n'
           '\n'
-          '      Dictionaries are mutable; they can be created by the '
-          '"{...}"\n'
+          '      Dictionaries are mutable; they can be created by the "{...}"\n'
           '      notation (see section Dictionary displays).\n'
           '\n'
           '      The extension modules "dbm", "gdbm", and "bsddb" provide\n'
@@ -10175,8 +10302,7 @@ topics = {'assert': '\n'
           '\n'
           '   User-defined functions\n'
           '      A user-defined function object is created by a function\n'
-          '      definition (see section Function definitions).  It should '
-          'be\n'
+          '      definition (see section Function definitions).  It should be\n'
           '      called with an argument list containing the same number of '
           'items\n'
           "      as the function's formal parameter list.\n"
@@ -10189,28 +10315,28 @@ topics = {'assert': '\n'
           '|             |\n'
           '      '
           '+=========================+=================================+=============+\n'
-          '      | "__doc__" "func_doc"    | The function\'s '
-          'documentation    | Writable    |\n'
+          '      | "__doc__" "func_doc"    | The function\'s documentation    '
+          '| Writable    |\n'
           '      |                         | string, or "None" if            '
           '|             |\n'
           '      |                         | unavailable.                    '
           '|             |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__name__" "func_name"  | The function\'s '
-          'name.            | Writable    |\n'
+          '      | "__name__" "func_name"  | The function\'s name.            '
+          '| Writable    |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__module__"            | The name of the module the      '
-          'Writable    |\n'
+          '      | "__module__"            | The name of the module the      '
+          'Writable    |\n'
           '      |                         | function was defined in, or     '
           '|             |\n'
           '      |                         | "None" if unavailable.          '
           '|             |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__defaults__"          | A tuple containing default      '
-          'Writable    |\n'
+          '      | "__defaults__"          | A tuple containing default      '
+          'Writable    |\n'
           '      | "func_defaults"         | argument values for those       '
           '|             |\n'
           '      |                         | arguments that have defaults,   '
@@ -10221,16 +10347,16 @@ topics = {'assert': '\n'
           '|             |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__code__" "func_code"  | The code object representing    '
-          'Writable    |\n'
+          '      | "__code__" "func_code"  | The code object representing    '
+          'Writable    |\n'
           '      |                         | the compiled function body.     '
           '|             |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__globals__"           | A reference to the dictionary   '
-          'Read-only   |\n'
-          '      | "func_globals"          | that holds the '
-          "function's       |             |\n"
+          '      | "__globals__"           | A reference to the dictionary   '
+          'Read-only   |\n'
+          '      | "func_globals"          | that holds the function\'s       '
+          '|             |\n'
           '      |                         | global variables --- the global '
           '|             |\n'
           '      |                         | namespace of the module in      '
@@ -10239,14 +10365,14 @@ topics = {'assert': '\n'
           '|             |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__dict__" "func_dict"  | The namespace supporting        '
-          'Writable    |\n'
+          '      | "__dict__" "func_dict"  | The namespace supporting        '
+          'Writable    |\n'
           '      |                         | arbitrary function attributes.  '
           '|             |\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
-          '      | "__closure__"           | "None" or a tuple of cells that '
-          'Read-only   |\n'
+          '      | "__closure__"           | "None" or a tuple of cells that '
+          'Read-only   |\n'
           '      | "func_closure"          | contain bindings for the        '
           '|             |\n'
           "      |                         | function's free variables.      "
@@ -10254,24 +10380,22 @@ topics = {'assert': '\n'
           '      '
           '+-------------------------+---------------------------------+-------------+\n'
           '\n'
-          '      Most of the attributes labelled "Writable" check the type '
-          'of the\n'
+          '      Most of the attributes labelled "Writable" check the type of '
+          'the\n'
           '      assigned value.\n'
           '\n'
           '      Changed in version 2.4: "func_name" is now writable.\n'
           '\n'
           '      Changed in version 2.6: The double-underscore attributes\n'
-          '      "__closure__", "__code__", "__defaults__", and '
-          '"__globals__"\n'
+          '      "__closure__", "__code__", "__defaults__", and "__globals__"\n'
           '      were introduced as aliases for the corresponding "func_*"\n'
           '      attributes for forwards compatibility with Python 3.\n'
           '\n'
-          '      Function objects also support getting and setting '
-          'arbitrary\n'
+          '      Function objects also support getting and setting arbitrary\n'
           '      attributes, which can be used, for example, to attach '
           'metadata\n'
-          '      to functions.  Regular attribute dot-notation is used to '
-          'get and\n'
+          '      to functions.  Regular attribute dot-notation is used to get '
+          'and\n'
           '      set such attributes. *Note that the current implementation '
           'only\n'
           '      supports function attributes on user-defined functions. '
@@ -10279,8 +10403,7 @@ topics = {'assert': '\n'
           '      attributes on built-in functions may be supported in the\n'
           '      future.*\n'
           '\n'
-          "      Additional information about a function's definition can "
-          'be\n'
+          "      Additional information about a function's definition can be\n"
           '      retrieved from its code object; see the description of '
           'internal\n'
           '      types below.\n'
@@ -10288,32 +10411,26 @@ topics = {'assert': '\n'
           '   User-defined methods\n'
           '      A user-defined method object combines a class, a class '
           'instance\n'
-          '      (or "None") and any callable object (normally a '
-          'user-defined\n'
+          '      (or "None") and any callable object (normally a user-defined\n'
           '      function).\n'
           '\n'
           '      Special read-only attributes: "im_self" is the class '
           'instance\n'
-          '      object, "im_func" is the function object; "im_class" is '
-          'the\n'
-          '      class of "im_self" for bound methods or the class that '
-          'asked for\n'
+          '      object, "im_func" is the function object; "im_class" is the\n'
+          '      class of "im_self" for bound methods or the class that asked '
+          'for\n'
           '      the method for unbound methods; "__doc__" is the method\'s\n'
-          '      documentation (same as "im_func.__doc__"); "__name__" is '
-          'the\n'
+          '      documentation (same as "im_func.__doc__"); "__name__" is the\n'
           '      method name (same as "im_func.__name__"); "__module__" is '
           'the\n'
           '      name of the module the method was defined in, or "None" if\n'
           '      unavailable.\n'
           '\n'
-          '      Changed in version 2.2: "im_self" used to refer to the '
-          'class\n'
+          '      Changed in version 2.2: "im_self" used to refer to the class\n'
           '      that defined the method.\n'
           '\n'
-          '      Changed in version 2.6: For Python 3 '
-          'forward-compatibility,\n'
-          '      "im_func" is also available as "__func__", and "im_self" '
-          'as\n'
+          '      Changed in version 2.6: For Python 3 forward-compatibility,\n'
+          '      "im_func" is also available as "__func__", and "im_self" as\n'
           '      "__self__".\n'
           '\n'
           '      Methods also support accessing (but not setting) the '
@@ -10321,24 +10438,21 @@ topics = {'assert': '\n'
           '      function attributes on the underlying function object.\n'
           '\n'
           '      User-defined method objects may be created when getting an\n'
-          '      attribute of a class (perhaps via an instance of that '
-          'class), if\n'
-          '      that attribute is a user-defined function object, an '
-          'unbound\n'
+          '      attribute of a class (perhaps via an instance of that class), '
+          'if\n'
+          '      that attribute is a user-defined function object, an unbound\n'
           '      user-defined method object, or a class method object. When '
           'the\n'
           '      attribute is a user-defined method object, a new method '
           'object\n'
-          '      is only created if the class from which it is being '
-          'retrieved is\n'
-          '      the same as, or a derived class of, the class stored in '
-          'the\n'
-          '      original method object; otherwise, the original method '
-          'object is\n'
+          '      is only created if the class from which it is being retrieved '
+          'is\n'
+          '      the same as, or a derived class of, the class stored in the\n'
+          '      original method object; otherwise, the original method object '
+          'is\n'
           '      used as it is.\n'
           '\n'
-          '      When a user-defined method object is created by retrieving '
-          'a\n'
+          '      When a user-defined method object is created by retrieving a\n'
           '      user-defined function object from a class, its "im_self"\n'
           '      attribute is "None" and the method object is said to be '
           'unbound.\n'
@@ -10354,18 +10468,15 @@ topics = {'assert': '\n'
           '      attribute is the original function object.\n'
           '\n'
           '      When a user-defined method object is created by retrieving\n'
-          '      another method object from a class or instance, the '
-          'behaviour is\n'
-          '      the same as for a function object, except that the '
-          '"im_func"\n'
+          '      another method object from a class or instance, the behaviour '
+          'is\n'
+          '      the same as for a function object, except that the "im_func"\n'
           '      attribute of the new instance is not the original method '
           'object\n'
           '      but its "im_func" attribute.\n'
           '\n'
-          '      When a user-defined method object is created by retrieving '
-          'a\n'
-          '      class method object from a class or instance, its '
-          '"im_self"\n'
+          '      When a user-defined method object is created by retrieving a\n'
+          '      class method object from a class or instance, its "im_self"\n'
           '      attribute is the class itself, and its "im_func" attribute '
           'is\n'
           '      the function object underlying the class method.\n'
@@ -10381,8 +10492,8 @@ topics = {'assert': '\n'
           '      underlying function ("im_func") is called, inserting the '
           'class\n'
           '      instance ("im_self") in front of the argument list.  For\n'
-          '      instance, when "C" is a class which contains a definition '
-          'for a\n'
+          '      instance, when "C" is a class which contains a definition for '
+          'a\n'
           '      function "f()", and "x" is an instance of "C", calling '
           '"x.f(1)"\n'
           '      is equivalent to calling "C.f(x, 1)".\n'
@@ -10397,8 +10508,8 @@ topics = {'assert': '\n'
           'underlying\n'
           '      function.\n'
           '\n'
-          '      Note that the transformation from function object to '
-          '(unbound or\n'
+          '      Note that the transformation from function object to (unbound '
+          'or\n'
           '      bound) method object happens each time the attribute is\n'
           '      retrieved from the class or instance. In some cases, a '
           'fruitful\n'
@@ -10426,23 +10537,20 @@ topics = {'assert': '\n'
           '      the iterator\'s "next()" method will cause the function to\n'
           '      execute until it provides a value using the "yield" '
           'statement.\n'
-          '      When the function executes a "return" statement or falls '
-          'off the\n'
+          '      When the function executes a "return" statement or falls off '
+          'the\n'
           '      end, a "StopIteration" exception is raised and the iterator '
           'will\n'
           '      have reached the end of the set of values to be returned.\n'
           '\n'
           '   Built-in functions\n'
-          '      A built-in function object is a wrapper around a C '
-          'function.\n'
-          '      Examples of built-in functions are "len()" and '
-          '"math.sin()"\n'
+          '      A built-in function object is a wrapper around a C function.\n'
+          '      Examples of built-in functions are "len()" and "math.sin()"\n'
           '      ("math" is a standard built-in module). The number and type '
           'of\n'
           '      the arguments are determined by the C function. Special '
           'read-\n'
-          '      only attributes: "__doc__" is the function\'s '
-          'documentation\n'
+          '      only attributes: "__doc__" is the function\'s documentation\n'
           '      string, or "None" if unavailable; "__name__" is the '
           "function's\n"
           '      name; "__self__" is set to "None" (but see the next item);\n'
@@ -10454,10 +10562,8 @@ topics = {'assert': '\n'
           '      This is really a different disguise of a built-in function, '
           'this\n'
           '      time containing an object passed to the C function as an\n'
-          '      implicit extra argument.  An example of a built-in method '
-          'is\n'
-          '      "alist.append()", assuming *alist* is a list object. In '
-          'this\n'
+          '      implicit extra argument.  An example of a built-in method is\n'
+          '      "alist.append()", assuming *alist* is a list object. In this\n'
           '      case, the special read-only attribute "__self__" is set to '
           'the\n'
           '      object denoted by *alist*.\n'
@@ -10465,8 +10571,7 @@ topics = {'assert': '\n'
           '   Class Types\n'
           '      Class types, or "new-style classes," are callable.  These\n'
           '      objects normally act as factories for new instances of\n'
-          '      themselves, but variations are possible for class types '
-          'that\n'
+          '      themselves, but variations are possible for class types that\n'
           '      override "__new__()".  The arguments of the call are passed '
           'to\n'
           '      "__new__()" and, in the typical case, to "__init__()" to\n'
@@ -10489,22 +10594,18 @@ topics = {'assert': '\n'
           '      "x(arguments)" is a shorthand for "x.__call__(arguments)".\n'
           '\n'
           'Modules\n'
-          '   Modules are imported by the "import" statement (see section '
-          'The\n'
+          '   Modules are imported by the "import" statement (see section The\n'
           '   import statement). A module object has a namespace implemented '
           'by a\n'
           '   dictionary object (this is the dictionary referenced by the\n'
           '   func_globals attribute of functions defined in the module).\n'
           '   Attribute references are translated to lookups in this '
           'dictionary,\n'
-          '   e.g., "m.x" is equivalent to "m.__dict__["x"]". A module '
-          'object\n'
-          '   does not contain the code object used to initialize the '
-          'module\n'
+          '   e.g., "m.x" is equivalent to "m.__dict__["x"]". A module object\n'
+          '   does not contain the code object used to initialize the module\n'
           "   (since it isn't needed once the initialization is done).\n"
           '\n'
-          "   Attribute assignment updates the module's namespace "
-          'dictionary,\n'
+          "   Attribute assignment updates the module's namespace dictionary,\n"
           '   e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".\n'
           '\n'
           '   Special read-only attribute: "__dict__" is the module\'s '
@@ -10514,8 +10615,8 @@ topics = {'assert': '\n'
           '   **CPython implementation detail:** Because of the way CPython\n'
           '   clears module dictionaries, the module dictionary will be '
           'cleared\n'
-          '   when the module falls out of scope even if the dictionary '
-          'still has\n'
+          '   when the module falls out of scope even if the dictionary still '
+          'has\n'
           '   live references.  To avoid this, copy the dictionary or keep '
           'the\n'
           '   module around while using its dictionary directly.\n'
@@ -10525,8 +10626,7 @@ topics = {'assert': '\n'
           '   "__doc__" is the module\'s documentation string, or "None" if\n'
           '   unavailable; "__file__" is the pathname of the file from which '
           'the\n'
-          '   module was loaded, if it was loaded from a file. The '
-          '"__file__"\n'
+          '   module was loaded, if it was loaded from a file. The "__file__"\n'
           '   attribute is not present for C modules that are statically '
           'linked\n'
           '   into the interpreter; for extension modules loaded dynamically '
@@ -10548,14 +10648,13 @@ topics = {'assert': '\n'
           '   there are a number of hooks which allow for other means of '
           'locating\n'
           '   attributes). When the attribute name is not found there, the\n'
-          '   attribute search continues in the base classes.  For '
-          'old-style\n'
+          '   attribute search continues in the base classes.  For old-style\n'
           '   classes, the search is depth-first, left-to-right in the order '
           'of\n'
           '   occurrence in the base class list. New-style classes use the '
           'more\n'
-          '   complex C3 method resolution order which behaves correctly '
-          'even in\n'
+          '   complex C3 method resolution order which behaves correctly even '
+          'in\n'
           "   the presence of 'diamond' inheritance structures where there "
           'are\n'
           '   multiple inheritance paths leading back to a common ancestor.\n'
@@ -10566,20 +10665,14 @@ topics = {'assert': '\n'
           '\n'
           '   When a class attribute reference (for class "C", say) would '
           'yield a\n'
-          '   user-defined function object or an unbound user-defined '
-          'method\n'
-          '   object whose associated class is either "C" or one of its '
-          'base\n'
-          '   classes, it is transformed into an unbound user-defined '
-          'method\n'
-          '   object whose "im_class" attribute is "C". When it would yield '
-          'a\n'
+          '   user-defined function object or an unbound user-defined method\n'
+          '   object whose associated class is either "C" or one of its base\n'
+          '   classes, it is transformed into an unbound user-defined method\n'
+          '   object whose "im_class" attribute is "C". When it would yield a\n'
           '   class method object, it is transformed into a bound '
           'user-defined\n'
-          '   method object whose "im_self" attribute is "C".  When it '
-          'would\n'
-          '   yield a static method object, it is transformed into the '
-          'object\n'
+          '   method object whose "im_self" attribute is "C".  When it would\n'
+          '   yield a static method object, it is transformed into the object\n'
           '   wrapped by the static method object. See section Implementing\n'
           '   Descriptors for another way in which attributes retrieved from '
           'a\n'
@@ -10601,8 +10694,8 @@ topics = {'assert': '\n'
           'the\n'
           '   dictionary containing the class\'s namespace; "__bases__" is a '
           'tuple\n'
-          '   (possibly empty or a singleton) containing the base classes, '
-          'in the\n'
+          '   (possibly empty or a singleton) containing the base classes, in '
+          'the\n'
           '   order of their occurrence in the base class list; "__doc__" is '
           'the\n'
           "   class's documentation string, or None if undefined.\n"
@@ -10612,33 +10705,26 @@ topics = {'assert': '\n'
           'above).\n'
           '   A class instance has a namespace implemented as a dictionary '
           'which\n'
-          '   is the first place in which attribute references are '
-          'searched.\n'
+          '   is the first place in which attribute references are searched.\n'
           "   When an attribute is not found there, and the instance's class "
           'has\n'
-          '   an attribute by that name, the search continues with the '
-          'class\n'
+          '   an attribute by that name, the search continues with the class\n'
           '   attributes.  If a class attribute is found that is a '
           'user-defined\n'
-          '   function object or an unbound user-defined method object '
-          'whose\n'
-          '   associated class is the class (call it "C") of the instance '
-          'for\n'
-          '   which the attribute reference was initiated or one of its '
-          'bases, it\n'
+          '   function object or an unbound user-defined method object whose\n'
+          '   associated class is the class (call it "C") of the instance for\n'
+          '   which the attribute reference was initiated or one of its bases, '
+          'it\n'
           '   is transformed into a bound user-defined method object whose\n'
           '   "im_class" attribute is "C" and whose "im_self" attribute is '
           'the\n'
           '   instance. Static method and class method objects are also\n'
-          '   transformed, as if they had been retrieved from class "C"; '
-          'see\n'
-          '   above under "Classes". See section Implementing Descriptors '
-          'for\n'
+          '   transformed, as if they had been retrieved from class "C"; see\n'
+          '   above under "Classes". See section Implementing Descriptors for\n'
           '   another way in which attributes of a class retrieved via its\n'
           '   instances may differ from the objects actually stored in the\n'
           '   class\'s "__dict__". If no class attribute is found, and the\n'
-          '   object\'s class has a "__getattr__()" method, that is called '
-          'to\n'
+          '   object\'s class has a "__getattr__()" method, that is called to\n'
           '   satisfy the lookup.\n'
           '\n'
           "   Attribute assignments and deletions update the instance's\n"
@@ -10656,8 +10742,8 @@ topics = {'assert': '\n'
           '   "__class__" is the instance\'s class.\n'
           '\n'
           'Files\n'
-          '   A file object represents an open file.  File objects are '
-          'created by\n'
+          '   A file object represents an open file.  File objects are created '
+          'by\n'
           '   the "open()" built-in function, and also by "os.popen()",\n'
           '   "os.fdopen()", and the "makefile()" method of socket objects '
           '(and\n'
@@ -10666,15 +10752,13 @@ topics = {'assert': '\n'
           '"sys.stderr"\n'
           '   are initialized to file objects corresponding to the '
           "interpreter's\n"
-          '   standard input, output and error streams.  See File Objects '
-          'for\n'
+          '   standard input, output and error streams.  See File Objects for\n'
           '   complete documentation of file objects.\n'
           '\n'
           'Internal types\n'
           '   A few types used internally by the interpreter are exposed to '
           'the\n'
-          '   user. Their definitions may change with future versions of '
-          'the\n'
+          '   user. Their definitions may change with future versions of the\n'
           '   interpreter, but they are mentioned here for completeness.\n'
           '\n'
           '   Code objects\n'
@@ -10685,12 +10769,11 @@ topics = {'assert': '\n'
           'explicit\n'
           "      reference to the function's globals (the module in which it "
           'was\n'
-          '      defined), while a code object contains no context; also '
-          'the\n'
+          '      defined), while a code object contains no context; also the\n'
           '      default argument values are stored in the function object, '
           'not\n'
-          '      in the code object (because they represent values '
-          'calculated at\n'
+          '      in the code object (because they represent values calculated '
+          'at\n'
           '      run-time).  Unlike function objects, code objects are '
           'immutable\n'
           '      and contain no references (directly or indirectly) to '
@@ -10703,8 +10786,7 @@ topics = {'assert': '\n'
           '(including\n'
           '      arguments with default values); "co_nlocals" is the number '
           'of\n'
-          '      local variables used by the function (including '
-          'arguments);\n'
+          '      local variables used by the function (including arguments);\n'
           '      "co_varnames" is a tuple containing the names of the local\n'
           '      variables (starting with the argument names); "co_cellvars" '
           'is a\n'
@@ -10730,8 +10812,8 @@ topics = {'assert': '\n'
           '\n'
           '      The following flag bits are defined for "co_flags": bit '
           '"0x04"\n'
-          '      is set if the function uses the "*arguments" syntax to '
-          'accept an\n'
+          '      is set if the function uses the "*arguments" syntax to accept '
+          'an\n'
           '      arbitrary number of positional arguments; bit "0x08" is set '
           'if\n'
           '      the function uses the "**keywords" syntax to accept '
@@ -10743,8 +10825,8 @@ topics = {'assert': '\n'
           'division")\n'
           '      also use bits in "co_flags" to indicate whether a code '
           'object\n'
-          '      was compiled with a particular feature enabled: bit '
-          '"0x2000" is\n'
+          '      was compiled with a particular feature enabled: bit "0x2000" '
+          'is\n'
           '      set if the function was compiled with future division '
           'enabled;\n'
           '      bits "0x10" and "0x1000" were used in earlier versions of\n'
@@ -10753,49 +10835,41 @@ topics = {'assert': '\n'
           '      Other bits in "co_flags" are reserved for internal use.\n'
           '\n'
           '      If a code object represents a function, the first item in\n'
-          '      "co_consts" is the documentation string of the function, '
-          'or\n'
+          '      "co_consts" is the documentation string of the function, or\n'
           '      "None" if undefined.\n'
           '\n'
           '   Frame objects\n'
-          '      Frame objects represent execution frames.  They may occur '
-          'in\n'
+          '      Frame objects represent execution frames.  They may occur in\n'
           '      traceback objects (see below).\n'
           '\n'
           '      Special read-only attributes: "f_back" is to the previous '
           'stack\n'
-          '      frame (towards the caller), or "None" if this is the '
-          'bottom\n'
+          '      frame (towards the caller), or "None" if this is the bottom\n'
           '      stack frame; "f_code" is the code object being executed in '
           'this\n'
           '      frame; "f_locals" is the dictionary used to look up local\n'
           '      variables; "f_globals" is used for global variables;\n'
           '      "f_builtins" is used for built-in (intrinsic) names;\n'
-          '      "f_restricted" is a flag indicating whether the function '
-          'is\n'
-          '      executing in restricted execution mode; "f_lasti" gives '
-          'the\n'
+          '      "f_restricted" is a flag indicating whether the function is\n'
+          '      executing in restricted execution mode; "f_lasti" gives the\n'
           '      precise instruction (this is an index into the bytecode '
           'string\n'
           '      of the code object).\n'
           '\n'
-          '      Special writable attributes: "f_trace", if not "None", is '
-          'a\n'
+          '      Special writable attributes: "f_trace", if not "None", is a\n'
           '      function called at the start of each source code line (this '
           'is\n'
           '      used by the debugger); "f_exc_type", "f_exc_value",\n'
-          '      "f_exc_traceback" represent the last exception raised in '
-          'the\n'
+          '      "f_exc_traceback" represent the last exception raised in the\n'
           '      parent frame provided another exception was ever raised in '
           'the\n'
-          '      current frame (in all other cases they are None); '
-          '"f_lineno" is\n'
+          '      current frame (in all other cases they are None); "f_lineno" '
+          'is\n'
           '      the current line number of the frame --- writing to this '
           'from\n'
           '      within a trace function jumps to the given line (only for '
           'the\n'
-          '      bottom-most frame).  A debugger can implement a Jump '
-          'command\n'
+          '      bottom-most frame).  A debugger can implement a Jump command\n'
           '      (aka Set Next Statement) by writing to f_lineno.\n'
           '\n'
           '   Traceback objects\n'
@@ -10803,16 +10877,16 @@ topics = {'assert': '\n'
           'A\n'
           '      traceback object is created when an exception occurs.  When '
           'the\n'
-          '      search for an exception handler unwinds the execution '
-          'stack, at\n'
+          '      search for an exception handler unwinds the execution stack, '
+          'at\n'
           '      each unwound level a traceback object is inserted in front '
           'of\n'
           '      the current traceback.  When an exception handler is '
           'entered,\n'
           '      the stack trace is made available to the program. (See '
           'section\n'
-          '      The try statement.) It is accessible as '
-          '"sys.exc_traceback", and\n'
+          '      The try statement.) It is accessible as "sys.exc_traceback", '
+          'and\n'
           '      also as the third item of the tuple returned by\n'
           '      "sys.exc_info()".  The latter is the preferred interface, '
           'since\n'
@@ -10822,14 +10896,14 @@ topics = {'assert': '\n'
           'trace\n'
           '      is written (nicely formatted) to the standard error stream; '
           'if\n'
-          '      the interpreter is interactive, it is also made available '
-          'to the\n'
+          '      the interpreter is interactive, it is also made available to '
+          'the\n'
           '      user as "sys.last_traceback".\n'
           '\n'
-          '      Special read-only attributes: "tb_next" is the next level '
-          'in the\n'
-          '      stack trace (towards the frame where the exception '
-          'occurred), or\n'
+          '      Special read-only attributes: "tb_next" is the next level in '
+          'the\n'
+          '      stack trace (towards the frame where the exception occurred), '
+          'or\n'
           '      "None" if there is no next level; "tb_frame" points to the\n'
           '      execution frame of the current level; "tb_lineno" gives the '
           'line\n'
@@ -10847,24 +10921,22 @@ topics = {'assert': '\n'
           'slice\n'
           '      syntax* is used. This is a slice using two colons, or '
           'multiple\n'
-          '      slices or ellipses separated by commas, e.g., '
-          '"a[i:j:step]",\n'
+          '      slices or ellipses separated by commas, e.g., "a[i:j:step]",\n'
           '      "a[i:j, k:l]", or "a[..., i:j]".  They are also created by '
           'the\n'
           '      built-in "slice()" function.\n'
           '\n'
           '      Special read-only attributes: "start" is the lower bound; '
           '"stop"\n'
-          '      is the upper bound; "step" is the step value; each is '
-          '"None" if\n'
+          '      is the upper bound; "step" is the step value; each is "None" '
+          'if\n'
           '      omitted.  These attributes can have any type.\n'
           '\n'
           '      Slice objects support one method:\n'
           '\n'
           '      slice.indices(self, length)\n'
           '\n'
-          '         This method takes a single integer argument *length* '
-          'and\n'
+          '         This method takes a single integer argument *length* and\n'
           '         computes information about the extended slice that the '
           'slice\n'
           '         object would describe if applied to a sequence of '
@@ -10883,16 +10955,13 @@ topics = {'assert': '\n'
           '      Static method objects provide a way of defeating the\n'
           '      transformation of function objects to method objects '
           'described\n'
-          '      above. A static method object is a wrapper around any '
-          'other\n'
-          '      object, usually a user-defined method object. When a '
-          'static\n'
-          '      method object is retrieved from a class or a class '
-          'instance, the\n'
-          '      object actually returned is the wrapped object, which is '
-          'not\n'
-          '      subject to any further transformation. Static method '
-          'objects are\n'
+          '      above. A static method object is a wrapper around any other\n'
+          '      object, usually a user-defined method object. When a static\n'
+          '      method object is retrieved from a class or a class instance, '
+          'the\n'
+          '      object actually returned is the wrapped object, which is not\n'
+          '      subject to any further transformation. Static method objects '
+          'are\n'
           '      not themselves callable, although the objects they wrap '
           'usually\n'
           '      are. Static method objects are created by the built-in\n'
@@ -10903,10 +10972,9 @@ topics = {'assert': '\n'
           'wrapper\n'
           '      around another object that alters the way in which that '
           'object\n'
-          '      is retrieved from classes and class instances. The '
-          'behaviour of\n'
-          '      class method objects upon such retrieval is described '
-          'above,\n'
+          '      is retrieved from classes and class instances. The behaviour '
+          'of\n'
+          '      class method objects upon such retrieval is described above,\n'
           '      under "User-defined methods". Class method objects are '
           'created\n'
           '      by the built-in "classmethod()" constructor.\n',
@@ -10914,17 +10982,17 @@ topics = {'assert': '\n'
                    'Functions\n'
                    '*********\n'
                    '\n'
-                   'Function objects are created by function definitions.  '
-                   'The only\n'
+                   'Function objects are created by function definitions.  The '
+                   'only\n'
                    'operation on a function object is to call it: '
                    '"func(argument-list)".\n'
                    '\n'
-                   'There are really two flavors of function objects: '
-                   'built-in functions\n'
+                   'There are really two flavors of function objects: built-in '
+                   'functions\n'
                    'and user-defined functions.  Both support the same '
                    'operation (to call\n'
-                   'the function), but the implementation is different, '
-                   'hence the\n'
+                   'the function), but the implementation is different, hence '
+                   'the\n'
                    'different object types.\n'
                    '\n'
                    'See Function definitions for more information.\n',
@@ -10938,15 +11006,15 @@ topics = {'assert': '\n'
                  'standard\n'
                  'mapping type, the *dictionary*.  (For other containers see '
                  'the built\n'
-                 'in "list", "set", and "tuple" classes, and the '
-                 '"collections" module.)\n'
+                 'in "list", "set", and "tuple" classes, and the "collections" '
+                 'module.)\n'
                  '\n'
                  "A dictionary's keys are *almost* arbitrary values.  Values "
                  'that are\n'
                  'not *hashable*, that is, values containing lists, '
                  'dictionaries or\n'
-                 'other mutable types (that are compared by value rather '
-                 'than by object\n'
+                 'other mutable types (that are compared by value rather than '
+                 'by object\n'
                  'identity) may not be used as keys.  Numeric types used for '
                  'keys obey\n'
                  'the normal rules for numeric comparison: if two numbers '
@@ -10967,14 +11035,13 @@ topics = {'assert': '\n'
                  '"dict"\n'
                  'constructor.\n'
                  '\n'
-                 'class class dict(**kwarg)\n'
-                 'class class dict(mapping, **kwarg)\n'
-                 'class class dict(iterable, **kwarg)\n'
+                 'class dict(**kwarg)\n'
+                 'class dict(mapping, **kwarg)\n'
+                 'class dict(iterable, **kwarg)\n'
                  '\n'
                  '   Return a new dictionary initialized from an optional '
                  'positional\n'
-                 '   argument and a possibly empty set of keyword '
-                 'arguments.\n'
+                 '   argument and a possibly empty set of keyword arguments.\n'
                  '\n'
                  '   If no positional argument is given, an empty dictionary '
                  'is created.\n'
@@ -10994,8 +11061,8 @@ topics = {'assert': '\n'
                  'for that key\n'
                  '   becomes the corresponding value in the new dictionary.\n'
                  '\n'
-                 '   If keyword arguments are given, the keyword arguments '
-                 'and their\n'
+                 '   If keyword arguments are given, the keyword arguments and '
+                 'their\n'
                  '   values are added to the dictionary created from the '
                  'positional\n'
                  '   argument.  If a key being added is already present, the '
@@ -11010,24 +11077,22 @@ topics = {'assert': '\n'
                  '\n'
                  '      >>> a = dict(one=1, two=2, three=3)\n'
                  "      >>> b = {'one': 1, 'two': 2, 'three': 3}\n"
-                 "      >>> c = dict(zip(['one', 'two', 'three'], [1, 2, "
-                 '3]))\n'
-                 "      >>> d = dict([('two', 2), ('one', 1), ('three', "
-                 '3)])\n'
+                 "      >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\n"
+                 "      >>> d = dict([('two', 2), ('one', 1), ('three', 3)])\n"
                  "      >>> e = dict({'three': 3, 'one': 1, 'two': 2})\n"
                  '      >>> a == b == c == d == e\n'
                  '      True\n'
                  '\n'
-                 '   Providing keyword arguments as in the first example '
-                 'only works for\n'
+                 '   Providing keyword arguments as in the first example only '
+                 'works for\n'
                  '   keys that are valid Python identifiers.  Otherwise, any '
                  'valid keys\n'
                  '   can be used.\n'
                  '\n'
                  '   New in version 2.2.\n'
                  '\n'
-                 '   Changed in version 2.3: Support for building a '
-                 'dictionary from\n'
+                 '   Changed in version 2.3: Support for building a dictionary '
+                 'from\n'
                  '   keyword arguments added.\n'
                  '\n'
                  '   These are the operations that dictionaries support (and '
@@ -11044,8 +11109,8 @@ topics = {'assert': '\n'
                  '"KeyError" if\n'
                  '      *key* is not in the map.\n'
                  '\n'
-                 '      If a subclass of dict defines a method '
-                 '"__missing__()" and *key*\n'
+                 '      If a subclass of dict defines a method "__missing__()" '
+                 'and *key*\n'
                  '      is not present, the "d[key]" operation calls that '
                  'method with\n'
                  '      the key *key* as argument.  The "d[key]" operation '
@@ -11055,8 +11120,8 @@ topics = {'assert': '\n'
                  'methods invoke\n'
                  '      "__missing__()". If "__missing__()" is not defined, '
                  '"KeyError"\n'
-                 '      is raised. "__missing__()" must be a method; it '
-                 'cannot be an\n'
+                 '      is raised. "__missing__()" must be a method; it cannot '
+                 'be an\n'
                  '      instance variable:\n'
                  '\n'
                  '         >>> class Counter(dict):\n'
@@ -11069,14 +11134,13 @@ topics = {'assert': '\n'
                  "         >>> c['red']\n"
                  '         1\n'
                  '\n'
-                 '      The example above shows part of the implementation '
-                 'of\n'
+                 '      The example above shows part of the implementation of\n'
                  '      "collections.Counter".  A different "__missing__" '
                  'method is used\n'
                  '      by "collections.defaultdict".\n'
                  '\n'
-                 '      New in version 2.5: Recognition of __missing__ '
-                 'methods of dict\n'
+                 '      New in version 2.5: Recognition of __missing__ methods '
+                 'of dict\n'
                  '      subclasses.\n'
                  '\n'
                  '   d[key] = value\n'
@@ -11146,10 +11210,10 @@ topics = {'assert': '\n'
                  '      Return a copy of the dictionary\'s list of "(key, '
                  'value)" pairs.\n'
                  '\n'
-                 '      **CPython implementation detail:** Keys and values '
-                 'are listed in\n'
-                 '      an arbitrary order which is non-random, varies '
-                 'across Python\n'
+                 '      **CPython implementation detail:** Keys and values are '
+                 'listed in\n'
+                 '      an arbitrary order which is non-random, varies across '
+                 'Python\n'
                  "      implementations, and depends on the dictionary's "
                  'history of\n'
                  '      insertions and deletions.\n'
@@ -11164,12 +11228,12 @@ topics = {'assert': '\n'
                  '"zip()":\n'
                  '      "pairs = zip(d.values(), d.keys())".  The same '
                  'relationship\n'
-                 '      holds for the "iterkeys()" and "itervalues()" '
-                 'methods: "pairs =\n'
+                 '      holds for the "iterkeys()" and "itervalues()" methods: '
+                 '"pairs =\n'
                  '      zip(d.itervalues(), d.iterkeys())" provides the same '
                  'value for\n'
-                 '      "pairs". Another way to create the same list is '
-                 '"pairs = [(v, k)\n'
+                 '      "pairs". Another way to create the same list is "pairs '
+                 '= [(v, k)\n'
                  '      for (k, v) in d.iteritems()]".\n'
                  '\n'
                  '   iteritems()\n'
@@ -11192,8 +11256,8 @@ topics = {'assert': '\n'
                  'the note for\n'
                  '      "dict.items()".\n'
                  '\n'
-                 '      Using "iterkeys()" while adding or deleting entries '
-                 'in the\n'
+                 '      Using "iterkeys()" while adding or deleting entries in '
+                 'the\n'
                  '      dictionary may raise a "RuntimeError" or fail to '
                  'iterate over\n'
                  '      all entries.\n'
@@ -11202,12 +11266,12 @@ topics = {'assert': '\n'
                  '\n'
                  '   itervalues()\n'
                  '\n'
-                 "      Return an iterator over the dictionary's values.  "
-                 'See the note\n'
+                 "      Return an iterator over the dictionary's values.  See "
+                 'the note\n'
                  '      for "dict.items()".\n'
                  '\n'
-                 '      Using "itervalues()" while adding or deleting '
-                 'entries in the\n'
+                 '      Using "itervalues()" while adding or deleting entries '
+                 'in the\n'
                  '      dictionary may raise a "RuntimeError" or fail to '
                  'iterate over\n'
                  '      all entries.\n'
@@ -11224,8 +11288,8 @@ topics = {'assert': '\n'
                  '\n'
                  '      If *key* is in the dictionary, remove it and return '
                  'its value,\n'
-                 '      else return *default*.  If *default* is not given '
-                 'and *key* is\n'
+                 '      else return *default*.  If *default* is not given and '
+                 '*key* is\n'
                  '      not in the dictionary, a "KeyError" is raised.\n'
                  '\n'
                  '      New in version 2.3.\n'
@@ -11236,8 +11300,7 @@ topics = {'assert': '\n'
                  'from the\n'
                  '      dictionary.\n'
                  '\n'
-                 '      "popitem()" is useful to destructively iterate over '
-                 'a\n'
+                 '      "popitem()" is useful to destructively iterate over a\n'
                  '      dictionary, as often used in set algorithms.  If the '
                  'dictionary\n'
                  '      is empty, calling "popitem()" raises a "KeyError".\n'
@@ -11246,8 +11309,8 @@ topics = {'assert': '\n'
                  '\n'
                  '      If *key* is in the dictionary, return its value.  If '
                  'not, insert\n'
-                 '      *key* with a value of *default* and return '
-                 '*default*.  *default*\n'
+                 '      *key* with a value of *default* and return *default*.  '
+                 '*default*\n'
                  '      defaults to "None".\n'
                  '\n'
                  '   update([other])\n'
@@ -11256,39 +11319,38 @@ topics = {'assert': '\n'
                  '*other*,\n'
                  '      overwriting existing keys.  Return "None".\n'
                  '\n'
-                 '      "update()" accepts either another dictionary object '
-                 'or an\n'
+                 '      "update()" accepts either another dictionary object or '
+                 'an\n'
                  '      iterable of key/value pairs (as tuples or other '
                  'iterables of\n'
-                 '      length two).  If keyword arguments are specified, '
-                 'the dictionary\n'
+                 '      length two).  If keyword arguments are specified, the '
+                 'dictionary\n'
                  '      is then updated with those key/value pairs: '
                  '"d.update(red=1,\n'
                  '      blue=2)".\n'
                  '\n'
-                 '      Changed in version 2.4: Allowed the argument to be '
-                 'an iterable\n'
+                 '      Changed in version 2.4: Allowed the argument to be an '
+                 'iterable\n'
                  '      of key/value pairs and allowed keyword arguments.\n'
                  '\n'
                  '   values()\n'
                  '\n'
-                 "      Return a copy of the dictionary's list of values.  "
-                 'See the note\n'
+                 "      Return a copy of the dictionary's list of values.  See "
+                 'the note\n'
                  '      for "dict.items()".\n'
                  '\n'
                  '   viewitems()\n'
                  '\n'
                  '      Return a new view of the dictionary\'s items ("(key, '
                  'value)"\n'
-                 '      pairs).  See below for documentation of view '
-                 'objects.\n'
+                 '      pairs).  See below for documentation of view objects.\n'
                  '\n'
                  '      New in version 2.7.\n'
                  '\n'
                  '   viewkeys()\n'
                  '\n'
-                 "      Return a new view of the dictionary's keys.  See "
-                 'below for\n'
+                 "      Return a new view of the dictionary's keys.  See below "
+                 'for\n'
                  '      documentation of view objects.\n'
                  '\n'
                  '      New in version 2.7.\n'
@@ -11335,12 +11397,12 @@ topics = {'assert': '\n'
                  'which is\n'
                  '   non-random, varies across Python implementations, and '
                  'depends on\n'
-                 "   the dictionary's history of insertions and deletions. "
-                 'If keys,\n'
+                 "   the dictionary's history of insertions and deletions. If "
+                 'keys,\n'
                  '   values and items views are iterated over with no '
                  'intervening\n'
-                 '   modifications to the dictionary, the order of items '
-                 'will directly\n'
+                 '   modifications to the dictionary, the order of items will '
+                 'directly\n'
                  '   correspond.  This allows the creation of "(value, key)" '
                  'pairs using\n'
                  '   "zip()": "pairs = zip(d.values(), d.keys())".  Another '
@@ -11369,8 +11431,8 @@ topics = {'assert': '\n'
                  'views are not\n'
                  'treated as set-like since the entries are generally not '
                  'unique.)  Then\n'
-                 'these set operations are available ("other" refers either '
-                 'to another\n'
+                 'these set operations are available ("other" refers either to '
+                 'another\n'
                  'view or a set):\n'
                  '\n'
                  'dictview & other\n'
@@ -11381,15 +11443,15 @@ topics = {'assert': '\n'
                  '\n'
                  'dictview | other\n'
                  '\n'
-                 '   Return the union of the dictview and the other object '
-                 'as a new set.\n'
+                 '   Return the union of the dictview and the other object as '
+                 'a new set.\n'
                  '\n'
                  'dictview - other\n'
                  '\n'
-                 '   Return the difference between the dictview and the '
-                 'other object\n'
-                 "   (all elements in *dictview* that aren't in *other*) as "
-                 'new set.\n'
+                 '   Return the difference between the dictview and the other '
+                 'object\n'
+                 "   (all elements in *dictview* that aren't in *other*) as "
+                 'new set.\n'
                  '\n'
                  'dictview ^ other\n'
                  '\n'
@@ -11420,8 +11482,7 @@ topics = {'assert': '\n'
                  '   >>> list(values)\n'
                  '   [2, 1, 1, 500]\n'
                  '\n'
-                 '   >>> # view objects are dynamic and reflect dict '
-                 'changes\n'
+                 '   >>> # view objects are dynamic and reflect dict changes\n'
                  "   >>> del dishes['eggs']\n"
                  "   >>> del dishes['sausage']\n"
                  '   >>> list(keys)\n'
@@ -11436,14 +11497,14 @@ topics = {'assert': '\n'
                  '\n'
                  'Methods are functions that are called using the attribute '
                  'notation.\n'
-                 'There are two flavors: built-in methods (such as '
-                 '"append()" on lists)\n'
-                 'and class instance methods.  Built-in methods are '
-                 'described with the\n'
+                 'There are two flavors: built-in methods (such as "append()" '
+                 'on lists)\n'
+                 'and class instance methods.  Built-in methods are described '
+                 'with the\n'
                  'types that support them.\n'
                  '\n'
-                 'The implementation adds two special read-only attributes '
-                 'to class\n'
+                 'The implementation adds two special read-only attributes to '
+                 'class\n'
                  'instance methods: "m.im_self" is the object on which the '
                  'method\n'
                  'operates, and "m.im_func" is the function implementing the '
@@ -11485,12 +11546,12 @@ topics = {'assert': '\n'
                  '   ...         pass\n'
                  '   ...\n'
                  '   >>> c = C()\n'
-                 "   >>> c.method.whoami = 'my name is method'  # can't set "
-                 'on the method\n'
+                 "   >>> c.method.whoami = 'my name is method'  # can't set on "
+                 'the method\n'
                  '   Traceback (most recent call last):\n'
                  '     File "<stdin>", line 1, in <module>\n'
-                 "   AttributeError: 'instancemethod' object has no "
-                 "attribute 'whoami'\n"
+                 "   AttributeError: 'instancemethod' object has no attribute "
+                 "'whoami'\n"
                  "   >>> c.method.im_func.whoami = 'my name is method'\n"
                  '   >>> c.method.whoami\n'
                  "   'my name is method'\n"
@@ -11500,16 +11561,16 @@ topics = {'assert': '\n'
                  'Modules\n'
                  '*******\n'
                  '\n'
-                 'The only special operation on a module is attribute '
-                 'access: "m.name",\n'
-                 'where *m* is a module and *name* accesses a name defined '
-                 "in *m*'s\n"
+                 'The only special operation on a module is attribute access: '
+                 '"m.name",\n'
+                 'where *m* is a module and *name* accesses a name defined in '
+                 "*m*'s\n"
                  'symbol table. Module attributes can be assigned to.  (Note '
                  'that the\n'
                  '"import" statement is not, strictly speaking, an operation '
                  'on a module\n'
-                 'object; "import foo" does not require a module object '
-                 'named *foo* to\n'
+                 'object; "import foo" does not require a module object named '
+                 '*foo* to\n'
                  'exist, rather it requires an (external) *definition* for a '
                  'module\n'
                  'named *foo* somewhere.)\n'
@@ -11520,12 +11581,12 @@ topics = {'assert': '\n'
                  'this\n'
                  "dictionary will actually change the module's symbol table, "
                  'but direct\n'
-                 'assignment to the "__dict__" attribute is not possible '
-                 '(you can write\n'
-                 '"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", '
-                 "but you can't\n"
-                 'write "m.__dict__ = {}").  Modifying "__dict__" directly '
-                 'is not\n'
+                 'assignment to the "__dict__" attribute is not possible (you '
+                 'can write\n'
+                 '"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", but '
+                 "you can't\n"
+                 'write "m.__dict__ = {}").  Modifying "__dict__" directly is '
+                 'not\n'
                  'recommended.\n'
                  '\n'
                  'Modules built into the interpreter are written like this: '
@@ -11543,16 +11604,16 @@ topics = {'assert': '\n'
              'lists,\n'
              'tuples, bytearrays, buffers, and xrange objects.\n'
              '\n'
-             'For other containers see the built in "dict" and "set" '
-             'classes, and\n'
+             'For other containers see the built in "dict" and "set" classes, '
+             'and\n'
              'the "collections" module.\n'
              '\n'
              'String literals are written in single or double quotes: '
              '"\'xyzzy\'",\n'
              '""frobozz"".  See String literals for more about string '
              'literals.\n'
-             'Unicode strings are much like strings, but are specified in '
-             'the syntax\n'
+             'Unicode strings are much like strings, but are specified in the '
+             'syntax\n'
              'using a preceding "\'u\'" character: "u\'abc\'", "u"def"". In '
              'addition to\n'
              'the functionality described here, there are also '
@@ -11561,37 +11622,34 @@ topics = {'assert': '\n'
              'constructed\n'
              'with square brackets, separating items with commas: "[a, b, '
              'c]".\n'
-             'Tuples are constructed by the comma operator (not within '
-             'square\n'
+             'Tuples are constructed by the comma operator (not within square\n'
              'brackets), with or without enclosing parentheses, but an empty '
              'tuple\n'
-             'must have the enclosing parentheses, such as "a, b, c" or '
-             '"()".  A\n'
+             'must have the enclosing parentheses, such as "a, b, c" or "()".  '
+             'A\n'
              'single item tuple must have a trailing comma, such as "(d,)".\n'
              '\n'
              'Bytearray objects are created with the built-in function\n'
              '"bytearray()".\n'
              '\n'
-             'Buffer objects are not directly supported by Python syntax, '
-             'but can be\n'
+             'Buffer objects are not directly supported by Python syntax, but '
+             'can be\n'
              'created by calling the built-in function "buffer()".  They '
              "don't\n"
              'support concatenation or repetition.\n'
              '\n'
              'Objects of type xrange are similar to buffers in that there is '
              'no\n'
-             'specific syntax to create them, but they are created using '
-             'the\n'
-             '"xrange()" function.  They don\'t support slicing, '
-             'concatenation or\n'
-             'repetition, and using "in", "not in", "min()" or "max()" on '
-             'them is\n'
+             'specific syntax to create them, but they are created using the\n'
+             '"xrange()" function.  They don\'t support slicing, concatenation '
+             'or\n'
+             'repetition, and using "in", "not in", "min()" or "max()" on them '
+             'is\n'
              'inefficient.\n'
              '\n'
-             'Most sequence types support the following operations.  The '
-             '"in" and\n'
-             '"not in" operations have the same priorities as the '
-             'comparison\n'
+             'Most sequence types support the following operations.  The "in" '
+             'and\n'
+             '"not in" operations have the same priorities as the comparison\n'
              'operations.  The "+" and "*" operations have the same priority '
              'as the\n'
              'corresponding numeric operations. [3] Additional methods are '
@@ -11659,8 +11717,7 @@ topics = {'assert': '\n'
              '\n'
              'Sequence types also support comparisons. In particular, tuples '
              'and\n'
-             'lists are compared lexicographically by comparing '
-             'corresponding\n'
+             'lists are compared lexicographically by comparing corresponding\n'
              'elements. This means that to compare equal, every element must '
              'compare\n'
              'equal and the two sequences must be of the same type and have '
@@ -11674,14 +11731,14 @@ topics = {'assert': '\n'
              '"not\n'
              '   in" operations act like a substring test.  In Python '
              'versions\n'
-             '   before 2.3, *x* had to be a string of length 1. In Python '
-             '2.3 and\n'
+             '   before 2.3, *x* had to be a string of length 1. In Python 2.3 '
+             'and\n'
              '   beyond, *x* may be a string of any length.\n'
              '\n'
-             '2. Values of *n* less than "0" are treated as "0" (which '
-             'yields an\n'
-             '   empty sequence of the same type as *s*).  Note that items '
-             'in the\n'
+             '2. Values of *n* less than "0" are treated as "0" (which yields '
+             'an\n'
+             '   empty sequence of the same type as *s*).  Note that items in '
+             'the\n'
              '   sequence *s* are not copied; they are referenced multiple '
              'times.\n'
              '   This often haunts new Python programmers; consider:\n'
@@ -11697,10 +11754,8 @@ topics = {'assert': '\n'
              'containing\n'
              '   an empty list, so all three elements of "[[]] * 3" are '
              'references\n'
-             '   to this single empty list.  Modifying any of the elements '
-             'of\n'
-             '   "lists" modifies this single list. You can create a list '
-             'of\n'
+             '   to this single empty list.  Modifying any of the elements of\n'
+             '   "lists" modifies this single list. You can create a list of\n'
              '   different lists this way:\n'
              '\n'
              '   >>> lists = [[] for i in range(3)]\n'
@@ -11716,8 +11771,8 @@ topics = {'assert': '\n'
              '\n'
              '3. If *i* or *j* is negative, the index is relative to the end '
              'of\n'
-             '   the string: "len(s) + i" or "len(s) + j" is substituted.  '
-             'But note\n'
+             '   the string: "len(s) + i" or "len(s) + j" is substituted.  But '
+             'note\n'
              '   that "-0" is still "0".\n'
              '\n'
              '4. The slice of *s* from *i* to *j* is defined as the sequence '
@@ -11726,19 +11781,18 @@ topics = {'assert': '\n'
              'is\n'
              '   greater than "len(s)", use "len(s)".  If *i* is omitted or '
              '"None",\n'
-             '   use "0".  If *j* is omitted or "None", use "len(s)".  If '
-             '*i* is\n'
+             '   use "0".  If *j* is omitted or "None", use "len(s)".  If *i* '
+             'is\n'
              '   greater than or equal to *j*, the slice is empty.\n'
              '\n'
-             '5. The slice of *s* from *i* to *j* with step *k* is defined '
-             'as the\n'
-             '   sequence of items with index  "x = i + n*k" such that "0 <= '
-             '<\n'
+             '5. The slice of *s* from *i* to *j* with step *k* is defined as '
+             'the\n'
+             '   sequence of items with index  "x = i + n*k" such that "0 <= '
+             '<\n'
              '   (j-i)/k".  In other words, the indices are "i", "i+k", '
              '"i+2*k",\n'
              '   "i+3*k" and so on, stopping when *j* is reached (but never\n'
-             '   including *j*).  If *i* or *j* is greater than "len(s)", '
-             'use\n'
+             '   including *j*).  If *i* or *j* is greater than "len(s)", use\n'
              '   "len(s)".  If *i* or *j* are omitted or "None", they become '
              '"end"\n'
              '   values (which end depends on the sign of *k*).  Note, *k* '
@@ -11748,10 +11802,9 @@ topics = {'assert': '\n'
              '6. **CPython implementation detail:** If *s* and *t* are both\n'
              '   strings, some Python implementations such as CPython can '
              'usually\n'
-             '   perform an in-place optimization for assignments of the '
-             'form "s = s\n'
-             '   + t" or "s += t".  When applicable, this optimization '
-             'makes\n'
+             '   perform an in-place optimization for assignments of the form '
+             '"s = s\n'
+             '   + t" or "s += t".  When applicable, this optimization makes\n'
              '   quadratic run-time much less likely.  This optimization is '
              'both\n'
              '   version and implementation dependent.  For performance '
@@ -11762,8 +11815,7 @@ topics = {'assert': '\n'
              'and\n'
              '   implementations.\n'
              '\n'
-             '   Changed in version 2.4: Formerly, string concatenation '
-             'never\n'
+             '   Changed in version 2.4: Formerly, string concatenation never\n'
              '   occurred in-place.\n'
              '\n'
              '\n'
@@ -11775,10 +11827,8 @@ topics = {'assert': '\n'
              'Unicode objects support.  Some of them are also available on\n'
              '"bytearray" objects.\n'
              '\n'
-             "In addition, Python's strings support the sequence type "
-             'methods\n'
-             'described in the Sequence Types --- str, unicode, list, '
-             'tuple,\n'
+             "In addition, Python's strings support the sequence type methods\n"
+             'described in the Sequence Types --- str, unicode, list, tuple,\n'
              'bytearray, buffer, xrange section. To output formatted strings '
              'use\n'
              'template strings or the "%" operator described in the String\n'
@@ -11800,13 +11850,12 @@ topics = {'assert': '\n'
              'done\n'
              '   using the specified *fillchar* (default is a space).\n'
              '\n'
-             '   Changed in version 2.4: Support for the *fillchar* '
-             'argument.\n'
+             '   Changed in version 2.4: Support for the *fillchar* argument.\n'
              '\n'
              'str.count(sub[, start[, end]])\n'
              '\n'
-             '   Return the number of non-overlapping occurrences of '
-             'substring *sub*\n'
+             '   Return the number of non-overlapping occurrences of substring '
+             '*sub*\n'
              '   in the range [*start*, *end*].  Optional arguments *start* '
              'and\n'
              '   *end* are interpreted as in slice notation.\n'
@@ -11815,14 +11864,14 @@ topics = {'assert': '\n'
              '\n'
              '   Decodes the string using the codec registered for '
              '*encoding*.\n'
-             '   *encoding* defaults to the default string encoding.  '
-             '*errors* may\n'
+             '   *encoding* defaults to the default string encoding.  *errors* '
+             'may\n'
              '   be given to set a different error handling scheme.  The '
              'default is\n'
              '   "\'strict\'", meaning that encoding errors raise '
              '"UnicodeError".\n'
-             '   Other possible values are "\'ignore\'", "\'replace\'" and '
-             'any other\n'
+             '   Other possible values are "\'ignore\'", "\'replace\'" and any '
+             'other\n'
              '   name registered via "codecs.register_error()", see section '
              'Codec\n'
              '   Base Classes.\n'
@@ -11833,13 +11882,12 @@ topics = {'assert': '\n'
              'schemes\n'
              '   added.\n'
              '\n'
-             '   Changed in version 2.7: Support for keyword arguments '
-             'added.\n'
+             '   Changed in version 2.7: Support for keyword arguments added.\n'
              '\n'
              'str.encode([encoding[, errors]])\n'
              '\n'
-             '   Return an encoded version of the string.  Default encoding '
-             'is the\n'
+             '   Return an encoded version of the string.  Default encoding is '
+             'the\n'
              '   current default string encoding.  *errors* may be given to '
              'set a\n'
              '   different error handling scheme.  The default for *errors* '
@@ -11847,8 +11895,8 @@ topics = {'assert': '\n'
              '   "\'strict\'", meaning that encoding errors raise a '
              '"UnicodeError".\n'
              '   Other possible values are "\'ignore\'", "\'replace\'",\n'
-             '   "\'xmlcharrefreplace\'", "\'backslashreplace\'" and any '
-             'other name\n'
+             '   "\'xmlcharrefreplace\'", "\'backslashreplace\'" and any other '
+             'name\n'
              '   registered via "codecs.register_error()", see section Codec '
              'Base\n'
              '   Classes. For a list of possible encodings, see section '
@@ -11862,8 +11910,7 @@ topics = {'assert': '\n'
              '   "\'backslashreplace\'" and other error handling schemes '
              'added.\n'
              '\n'
-             '   Changed in version 2.7: Support for keyword arguments '
-             'added.\n'
+             '   Changed in version 2.7: Support for keyword arguments added.\n'
              '\n'
              'str.endswith(suffix[, start[, end]])\n'
              '\n'
@@ -11871,8 +11918,7 @@ topics = {'assert': '\n'
              '*suffix*,\n'
              '   otherwise return "False".  *suffix* can also be a tuple of '
              'suffixes\n'
-             '   to look for.  With optional *start*, test beginning at '
-             'that\n'
+             '   to look for.  With optional *start*, test beginning at that\n'
              '   position.  With optional *end*, stop comparing at that '
              'position.\n'
              '\n'
@@ -11890,10 +11936,10 @@ topics = {'assert': '\n'
              'so on).\n'
              '   To expand the string, the current column is set to zero and '
              'the\n'
-             '   string is examined character by character.  If the '
-             'character is a\n'
-             '   tab ("\\t"), one or more space characters are inserted in '
-             'the result\n'
+             '   string is examined character by character.  If the character '
+             'is a\n'
+             '   tab ("\\t"), one or more space characters are inserted in the '
+             'result\n'
              '   until the current column is equal to the next tab position. '
              '(The\n'
              '   tab character itself is not copied.)  If the character is a '
@@ -11914,16 +11960,16 @@ topics = {'assert': '\n'
              '\n'
              '   Return the lowest index in the string where substring *sub* '
              'is\n'
-             '   found, such that *sub* is contained in the slice '
-             '"s[start:end]".\n'
-             '   Optional arguments *start* and *end* are interpreted as in '
-             'slice\n'
-             '   notation.  Return "-1" if *sub* is not found.\n'
+             '   found within the slice "s[start:end]".  Optional arguments '
+             '*start*\n'
+             '   and *end* are interpreted as in slice notation.  Return "-1" '
+             'if\n'
+             '   *sub* is not found.\n'
              '\n'
-             '   Note: The "find()" method should be used only if you need '
-             'to know\n'
-             '     the position of *sub*.  To check if *sub* is a substring '
-             'or not,\n'
+             '   Note: The "find()" method should be used only if you need to '
+             'know\n'
+             '     the position of *sub*.  To check if *sub* is a substring or '
+             'not,\n'
              '     use the "in" operator:\n'
              '\n'
              "        >>> 'Py' in 'Python'\n"
@@ -11937,8 +11983,7 @@ topics = {'assert': '\n'
              'fields\n'
              '   delimited by braces "{}".  Each replacement field contains '
              'either\n'
-             '   the numeric index of a positional argument, or the name of '
-             'a\n'
+             '   the numeric index of a positional argument, or the name of a\n'
              '   keyword argument.  Returns a copy of the string where each\n'
              '   replacement field is replaced with the string value of the\n'
              '   corresponding argument.\n'
@@ -11947,8 +11992,7 @@ topics = {'assert': '\n'
              "   'The sum of 1 + 2 is 3'\n"
              '\n'
              '   See Format String Syntax for a description of the various\n'
-             '   formatting options that can be specified in format '
-             'strings.\n'
+             '   formatting options that can be specified in format strings.\n'
              '\n'
              '   This method of string formatting is the new standard in '
              'Python 3,\n'
@@ -11966,8 +12010,8 @@ topics = {'assert': '\n'
              '\n'
              'str.isalnum()\n'
              '\n'
-             '   Return true if all characters in the string are '
-             'alphanumeric and\n'
+             '   Return true if all characters in the string are alphanumeric '
+             'and\n'
              '   there is at least one character, false otherwise.\n'
              '\n'
              '   For 8-bit strings, this method is locale-dependent.\n'
@@ -11992,8 +12036,7 @@ topics = {'assert': '\n'
              '\n'
              '   Return true if all cased characters [4] in the string are '
              'lowercase\n'
-             '   and there is at least one cased character, false '
-             'otherwise.\n'
+             '   and there is at least one cased character, false otherwise.\n'
              '\n'
              '   For 8-bit strings, this method is locale-dependent.\n'
              '\n'
@@ -12007,12 +12050,12 @@ topics = {'assert': '\n'
              '\n'
              'str.istitle()\n'
              '\n'
-             '   Return true if the string is a titlecased string and there '
-             'is at\n'
+             '   Return true if the string is a titlecased string and there is '
+             'at\n'
              '   least one character, for example uppercase characters may '
              'only\n'
-             '   follow uncased characters and lowercase characters only '
-             'cased ones.\n'
+             '   follow uncased characters and lowercase characters only cased '
+             'ones.\n'
              '   Return false otherwise.\n'
              '\n'
              '   For 8-bit strings, this method is locale-dependent.\n'
@@ -12021,15 +12064,14 @@ topics = {'assert': '\n'
              '\n'
              '   Return true if all cased characters [4] in the string are '
              'uppercase\n'
-             '   and there is at least one cased character, false '
-             'otherwise.\n'
+             '   and there is at least one cased character, false otherwise.\n'
              '\n'
              '   For 8-bit strings, this method is locale-dependent.\n'
              '\n'
              'str.join(iterable)\n'
              '\n'
-             '   Return a string which is the concatenation of the strings '
-             'in the\n'
+             '   Return a string which is the concatenation of the strings in '
+             'the\n'
              '   *iterable* *iterable*.  The separator between elements is '
              'the\n'
              '   string providing this method.\n'
@@ -12038,14 +12080,12 @@ topics = {'assert': '\n'
              '\n'
              '   Return the string left justified in a string of length '
              '*width*.\n'
-             '   Padding is done using the specified *fillchar* (default is '
-             'a\n'
+             '   Padding is done using the specified *fillchar* (default is a\n'
              '   space).  The original string is returned if *width* is less '
              'than or\n'
              '   equal to "len(s)".\n'
              '\n'
-             '   Changed in version 2.4: Support for the *fillchar* '
-             'argument.\n'
+             '   Changed in version 2.4: Support for the *fillchar* argument.\n'
              '\n'
              'str.lower()\n'
              '\n'
@@ -12057,12 +12097,12 @@ topics = {'assert': '\n'
              '\n'
              'str.lstrip([chars])\n'
              '\n'
-             '   Return a copy of the string with leading characters '
-             'removed.  The\n'
-             '   *chars* argument is a string specifying the set of '
-             'characters to be\n'
-             '   removed.  If omitted or "None", the *chars* argument '
-             'defaults to\n'
+             '   Return a copy of the string with leading characters removed.  '
+             'The\n'
+             '   *chars* argument is a string specifying the set of characters '
+             'to be\n'
+             '   removed.  If omitted or "None", the *chars* argument defaults '
+             'to\n'
              '   removing whitespace.  The *chars* argument is not a prefix; '
              'rather,\n'
              '   all combinations of its values are stripped:\n'
@@ -12072,13 +12112,12 @@ topics = {'assert': '\n'
              "   >>> 'www.example.com'.lstrip('cmowz.')\n"
              "   'example.com'\n"
              '\n'
-             '   Changed in version 2.2.2: Support for the *chars* '
-             'argument.\n'
+             '   Changed in version 2.2.2: Support for the *chars* argument.\n'
              '\n'
              'str.partition(sep)\n'
              '\n'
-             '   Split the string at the first occurrence of *sep*, and '
-             'return a\n'
+             '   Split the string at the first occurrence of *sep*, and return '
+             'a\n'
              '   3-tuple containing the part before the separator, the '
              'separator\n'
              '   itself, and the part after the separator.  If the separator '
@@ -12091,16 +12130,16 @@ topics = {'assert': '\n'
              '\n'
              'str.replace(old, new[, count])\n'
              '\n'
-             '   Return a copy of the string with all occurrences of '
-             'substring *old*\n'
+             '   Return a copy of the string with all occurrences of substring '
+             '*old*\n'
              '   replaced by *new*.  If the optional argument *count* is '
              'given, only\n'
              '   the first *count* occurrences are replaced.\n'
              '\n'
              'str.rfind(sub[, start[, end]])\n'
              '\n'
-             '   Return the highest index in the string where substring '
-             '*sub* is\n'
+             '   Return the highest index in the string where substring *sub* '
+             'is\n'
              '   found, such that *sub* is contained within "s[start:end]".\n'
              '   Optional arguments *start* and *end* are interpreted as in '
              'slice\n'
@@ -12116,19 +12155,17 @@ topics = {'assert': '\n'
              '\n'
              '   Return the string right justified in a string of length '
              '*width*.\n'
-             '   Padding is done using the specified *fillchar* (default is '
-             'a\n'
+             '   Padding is done using the specified *fillchar* (default is a\n'
              '   space). The original string is returned if *width* is less '
              'than or\n'
              '   equal to "len(s)".\n'
              '\n'
-             '   Changed in version 2.4: Support for the *fillchar* '
-             'argument.\n'
+             '   Changed in version 2.4: Support for the *fillchar* argument.\n'
              '\n'
              'str.rpartition(sep)\n'
              '\n'
-             '   Split the string at the last occurrence of *sep*, and '
-             'return a\n'
+             '   Split the string at the last occurrence of *sep*, and return '
+             'a\n'
              '   3-tuple containing the part before the separator, the '
              'separator\n'
              '   itself, and the part after the separator.  If the separator '
@@ -12141,10 +12178,9 @@ topics = {'assert': '\n'
              '\n'
              'str.rsplit([sep[, maxsplit]])\n'
              '\n'
-             '   Return a list of the words in the string, using *sep* as '
-             'the\n'
-             '   delimiter string. If *maxsplit* is given, at most '
-             '*maxsplit* splits\n'
+             '   Return a list of the words in the string, using *sep* as the\n'
+             '   delimiter string. If *maxsplit* is given, at most *maxsplit* '
+             'splits\n'
              '   are done, the *rightmost* ones.  If *sep* is not specified '
              'or\n'
              '   "None", any whitespace string is a separator.  Except for '
@@ -12158,10 +12194,10 @@ topics = {'assert': '\n'
              '\n'
              '   Return a copy of the string with trailing characters '
              'removed.  The\n'
-             '   *chars* argument is a string specifying the set of '
-             'characters to be\n'
-             '   removed.  If omitted or "None", the *chars* argument '
-             'defaults to\n'
+             '   *chars* argument is a string specifying the set of characters '
+             'to be\n'
+             '   removed.  If omitted or "None", the *chars* argument defaults '
+             'to\n'
              '   removing whitespace.  The *chars* argument is not a suffix; '
              'rather,\n'
              '   all combinations of its values are stripped:\n'
@@ -12171,13 +12207,11 @@ topics = {'assert': '\n'
              "   >>> 'mississippi'.rstrip('ipz')\n"
              "   'mississ'\n"
              '\n'
-             '   Changed in version 2.2.2: Support for the *chars* '
-             'argument.\n'
+             '   Changed in version 2.2.2: Support for the *chars* argument.\n'
              '\n'
              'str.split([sep[, maxsplit]])\n'
              '\n'
-             '   Return a list of the words in the string, using *sep* as '
-             'the\n'
+             '   Return a list of the words in the string, using *sep* as the\n'
              '   delimiter string.  If *maxsplit* is given, at most '
              '*maxsplit*\n'
              '   splits are done (thus, the list will have at most '
@@ -12190,11 +12224,11 @@ topics = {'assert': '\n'
              '   If *sep* is given, consecutive delimiters are not grouped '
              'together\n'
              '   and are deemed to delimit empty strings (for example,\n'
-             '   "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', \'2\']").  '
-             'The *sep* argument\n'
+             '   "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', \'2\']").  The '
+             '*sep* argument\n'
              '   may consist of multiple characters (for example,\n'
-             '   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', '
-             '\'3\']"). Splitting an\n'
+             '   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). '
+             'Splitting an\n'
              '   empty string with a specified separator returns "[\'\']".\n'
              '\n'
              '   If *sep* is not specified or is "None", a different '
@@ -12206,8 +12240,8 @@ topics = {'assert': '\n'
              '   at the start or end if the string has leading or trailing\n'
              '   whitespace.  Consequently, splitting an empty string or a '
              'string\n'
-             '   consisting of just whitespace with a "None" separator '
-             'returns "[]".\n'
+             '   consisting of just whitespace with a "None" separator returns '
+             '"[]".\n'
              '\n'
              '   For example, "\' 1  2   3  \'.split()" returns "[\'1\', '
              '\'2\', \'3\']", and\n'
@@ -12243,8 +12277,7 @@ topics = {'assert': '\n'
              'for.\n'
              '   With optional *start*, test string beginning at that '
              'position.\n'
-             '   With optional *end*, stop comparing string at that '
-             'position.\n'
+             '   With optional *end*, stop comparing string at that position.\n'
              '\n'
              '   Changed in version 2.5: Accept tuples as *prefix*.\n'
              '\n'
@@ -12266,8 +12299,7 @@ topics = {'assert': '\n'
              "   >>> 'www.example.com'.strip('cmowz.')\n"
              "   'example'\n"
              '\n'
-             '   Changed in version 2.2.2: Support for the *chars* '
-             'argument.\n'
+             '   Changed in version 2.2.2: Support for the *chars* argument.\n'
              '\n'
              'str.swapcase()\n'
              '\n'
@@ -12286,8 +12318,8 @@ topics = {'assert': '\n'
              '\n'
              '   The algorithm uses a simple language-independent definition '
              'of a\n'
-             '   word as groups of consecutive letters.  The definition '
-             'works in\n'
+             '   word as groups of consecutive letters.  The definition works '
+             'in\n'
              '   many contexts but it means that apostrophes in contractions '
              'and\n'
              '   possessives form word boundaries, which may not be the '
@@ -12304,10 +12336,8 @@ topics = {'assert': '\n'
              '      >>> import re\n'
              '      >>> def titlecase(s):\n'
              '      ...     return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n'
-             '      ...                   lambda mo: mo.group(0)[0].upper() '
-             '+\n'
-             '      ...                              '
-             'mo.group(0)[1:].lower(),\n'
+             '      ...                   lambda mo: mo.group(0)[0].upper() +\n'
+             '      ...                              mo.group(0)[1:].lower(),\n'
              '      ...                   s)\n'
              '      ...\n'
              '      >>> titlecase("they\'re bill\'s friends.")\n'
@@ -12317,8 +12347,8 @@ topics = {'assert': '\n'
              '\n'
              'str.translate(table[, deletechars])\n'
              '\n'
-             '   Return a copy of the string where all characters occurring '
-             'in the\n'
+             '   Return a copy of the string where all characters occurring in '
+             'the\n'
              '   optional argument *deletechars* are removed, and the '
              'remaining\n'
              '   characters have been mapped through the given translation '
@@ -12327,10 +12357,9 @@ topics = {'assert': '\n'
              '\n'
              '   You can use the "maketrans()" helper function in the '
              '"string"\n'
-             '   module to create a translation table. For string objects, '
-             'set the\n'
-             '   *table* argument to "None" for translations that only '
-             'delete\n'
+             '   module to create a translation table. For string objects, set '
+             'the\n'
+             '   *table* argument to "None" for translations that only delete\n'
              '   characters:\n'
              '\n'
              "   >>> 'read this short text'.translate(None, 'aeiou')\n"
@@ -12338,18 +12367,17 @@ topics = {'assert': '\n'
              '\n'
              '   New in version 2.6: Support for a "None" *table* argument.\n'
              '\n'
-             '   For Unicode objects, the "translate()" method does not '
-             'accept the\n'
-             '   optional *deletechars* argument.  Instead, it returns a '
-             'copy of the\n'
-             '   *s* where all characters have been mapped through the '
-             'given\n'
-             '   translation table which must be a mapping of Unicode '
-             'ordinals to\n'
+             '   For Unicode objects, the "translate()" method does not accept '
+             'the\n'
+             '   optional *deletechars* argument.  Instead, it returns a copy '
+             'of the\n'
+             '   *s* where all characters have been mapped through the given\n'
+             '   translation table which must be a mapping of Unicode ordinals '
+             'to\n'
              '   Unicode ordinals, Unicode strings or "None". Unmapped '
              'characters\n'
-             '   are left untouched. Characters mapped to "None" are '
-             'deleted.  Note,\n'
+             '   are left untouched. Characters mapped to "None" are deleted.  '
+             'Note,\n'
              '   a more flexible approach is to create a custom character '
              'mapping\n'
              '   codec using the "codecs" module (see "encodings.cp1251" for '
@@ -12362,18 +12390,16 @@ topics = {'assert': '\n'
              '[4]\n'
              '   converted to uppercase.  Note that "str.upper().isupper()" '
              'might be\n'
-             '   "False" if "s" contains uncased characters or if the '
-             'Unicode\n'
-             '   category of the resulting character(s) is not "Lu" '
-             '(Letter,\n'
+             '   "False" if "s" contains uncased characters or if the Unicode\n'
+             '   category of the resulting character(s) is not "Lu" (Letter,\n'
              '   uppercase), but e.g. "Lt" (Letter, titlecase).\n'
              '\n'
              '   For 8-bit strings, this method is locale-dependent.\n'
              '\n'
              'str.zfill(width)\n'
              '\n'
-             '   Return the numeric string left filled with zeros in a '
-             'string of\n'
+             '   Return the numeric string left filled with zeros in a string '
+             'of\n'
              '   length *width*.  A sign prefix is handled correctly.  The '
              'original\n'
              '   string is returned if *width* is less than or equal to '
@@ -12415,22 +12441,21 @@ topics = {'assert': '\n'
              '*format* is\n'
              'a string or Unicode object), "%" conversion specifications in '
              '*format*\n'
-             'are replaced with zero or more elements of *values*.  The '
-             'effect is\n'
-             'similar to the using "sprintf()" in the C language.  If '
-             '*format* is a\n'
+             'are replaced with zero or more elements of *values*.  The effect '
+             'is\n'
+             'similar to the using "sprintf()" in the C language.  If *format* '
+             'is a\n'
              'Unicode object, or if any of the objects being converted using '
              'the\n'
              '"%s" conversion are Unicode objects, the result will also be a '
              'Unicode\n'
              'object.\n'
              '\n'
-             'If *format* requires a single argument, *values* may be a '
-             'single non-\n'
+             'If *format* requires a single argument, *values* may be a single '
+             'non-\n'
              'tuple object. [5]  Otherwise, *values* must be a tuple with '
              'exactly\n'
-             'the number of items specified by the format string, or a '
-             'single\n'
+             'the number of items specified by the format string, or a single\n'
              'mapping object (for example, a dictionary).\n'
              '\n'
              'A conversion specifier contains two or more characters and has '
@@ -12444,22 +12469,19 @@ topics = {'assert': '\n'
              'sequence\n'
              '   of characters (for example, "(somename)").\n'
              '\n'
-             '3. Conversion flags (optional), which affect the result of '
-             'some\n'
+             '3. Conversion flags (optional), which affect the result of some\n'
              '   conversion types.\n'
              '\n'
-             '4. Minimum field width (optional).  If specified as an '
-             '"\'*\'"\n'
-             '   (asterisk), the actual width is read from the next element '
-             'of the\n'
-             '   tuple in *values*, and the object to convert comes after '
+             '4. Minimum field width (optional).  If specified as an "\'*\'"\n'
+             '   (asterisk), the actual width is read from the next element of '
              'the\n'
+             '   tuple in *values*, and the object to convert comes after the\n'
              '   minimum field width and optional precision.\n'
              '\n'
              '5. Precision (optional), given as a "\'.\'" (dot) followed by '
              'the\n'
-             '   precision.  If specified as "\'*\'" (an asterisk), the '
-             'actual width\n'
+             '   precision.  If specified as "\'*\'" (an asterisk), the actual '
+             'width\n'
              '   is read from the next element of the tuple in *values*, and '
              'the\n'
              '   value to convert comes after the precision.\n'
@@ -12468,10 +12490,10 @@ topics = {'assert': '\n'
              '\n'
              '7. Conversion type.\n'
              '\n'
-             'When the right argument is a dictionary (or other mapping '
-             'type), then\n'
-             'the formats in the string *must* include a parenthesised '
-             'mapping key\n'
+             'When the right argument is a dictionary (or other mapping type), '
+             'then\n'
+             'the formats in the string *must* include a parenthesised mapping '
+             'key\n'
              'into that dictionary inserted immediately after the "\'%\'" '
              'character.\n'
              'The mapping key selects the value to be formatted from the '
@@ -12502,8 +12524,8 @@ topics = {'assert': '\n'
              '| "\'0\'"     | The conversion will be zero padded for numeric '
              'values.                |\n'
              '+-----------+-----------------------------------------------------------------------+\n'
-             '| "\'-\'"     | The converted value is left adjusted '
-             '(overrides the "\'0\'" conversion  |\n'
+             '| "\'-\'"     | The converted value is left adjusted (overrides '
+             'the "\'0\'" conversion  |\n'
              '|           | if both are '
              'given).                                                   |\n'
              '+-----------+-----------------------------------------------------------------------+\n'
@@ -12520,15 +12542,15 @@ topics = {'assert': '\n'
              '\n'
              'A length modifier ("h", "l", or "L") may be present, but is '
              'ignored as\n'
-             'it is not necessary for Python -- so e.g. "%ld" is identical '
-             'to "%d".\n'
+             'it is not necessary for Python -- so e.g. "%ld" is identical to '
+             '"%d".\n'
              '\n'
              'The conversion types are:\n'
              '\n'
              '+--------------+-------------------------------------------------------+---------+\n'
              '| Conversion   | '
-             'Meaning                                               | '
-             'Notes   |\n'
+             'Meaning                                               | Notes   '
+             '|\n'
              '+==============+=======================================================+=========+\n'
              '| "\'d\'"        | Signed integer '
              'decimal.                               |         |\n'
@@ -12562,23 +12584,23 @@ topics = {'assert': '\n'
              '+--------------+-------------------------------------------------------+---------+\n'
              '| "\'g\'"        | Floating point format. Uses lowercase '
              'exponential     | (4)     |\n'
-             '|              | format if exponent is less than -4 or not '
-             'less than   |         |\n'
+             '|              | format if exponent is less than -4 or not less '
+             'than   |         |\n'
              '|              | precision, decimal format '
              'otherwise.                  |         |\n'
              '+--------------+-------------------------------------------------------+---------+\n'
              '| "\'G\'"        | Floating point format. Uses uppercase '
              'exponential     | (4)     |\n'
-             '|              | format if exponent is less than -4 or not '
-             'less than   |         |\n'
+             '|              | format if exponent is less than -4 or not less '
+             'than   |         |\n'
              '|              | precision, decimal format '
              'otherwise.                  |         |\n'
              '+--------------+-------------------------------------------------------+---------+\n'
              '| "\'c\'"        | Single character (accepts integer or single '
              'character |         |\n'
              '|              | '
-             'string).                                              '
-             '|         |\n'
+             'string).                                              |         '
+             '|\n'
              '+--------------+-------------------------------------------------------+---------+\n'
              '| "\'r\'"        | String (converts any Python object using '
              'repr()).     | (5)     |\n'
@@ -12596,16 +12618,16 @@ topics = {'assert': '\n'
              '\n'
              '1. The alternate form causes a leading zero ("\'0\'") to be '
              'inserted\n'
-             '   between left-hand padding and the formatting of the number '
-             'if the\n'
+             '   between left-hand padding and the formatting of the number if '
+             'the\n'
              '   leading character of the result is not already a zero.\n'
              '\n'
              '2. The alternate form causes a leading "\'0x\'" or "\'0X\'" '
              '(depending\n'
              '   on whether the "\'x\'" or "\'X\'" format was used) to be '
              'inserted\n'
-             '   between left-hand padding and the formatting of the number '
-             'if the\n'
+             '   between left-hand padding and the formatting of the number if '
+             'the\n'
              '   leading character of the result is not already a zero.\n'
              '\n'
              '3. The alternate form causes the result to always contain a '
@@ -12631,8 +12653,7 @@ topics = {'assert': '\n'
              '   The precision determines the maximal number of characters '
              'used.\n'
              '\n'
-             '6. If the object or format provided is a "unicode" string, '
-             'the\n'
+             '6. If the object or format provided is a "unicode" string, the\n'
              '   resulting string will also be "unicode".\n'
              '\n'
              '   The precision determines the maximal number of characters '
@@ -12646,8 +12667,7 @@ topics = {'assert': '\n'
              '\n'
              'Changed in version 2.7: "%f" conversions for numbers whose '
              'absolute\n'
-             'value is over 1e50 are no longer replaced by "%g" '
-             'conversions.\n'
+             'value is over 1e50 are no longer replaced by "%g" conversions.\n'
              '\n'
              'Additional string operations are defined in standard modules '
              '"string"\n'
@@ -12661,8 +12681,8 @@ topics = {'assert': '\n'
              'used for\n'
              'looping.  The advantage of the "xrange" type is that an '
              '"xrange"\n'
-             'object will always take the same amount of memory, no matter '
-             'the size\n'
+             'object will always take the same amount of memory, no matter the '
+             'size\n'
              'of the range it represents.  There are no consistent '
              'performance\n'
              'advantages.\n'
@@ -12675,8 +12695,8 @@ topics = {'assert': '\n'
              'Mutable Sequence Types\n'
              '======================\n'
              '\n'
-             'List and "bytearray" objects support additional operations '
-             'that allow\n'
+             'List and "bytearray" objects support additional operations that '
+             'allow\n'
              'in-place modification of the object. Other mutable sequence '
              'types\n'
              '(when added to the language) should also support these '
@@ -12696,8 +12716,8 @@ topics = {'assert': '\n'
              '|                                | '
              '*x*                              |                       |\n'
              '+--------------------------------+----------------------------------+-----------------------+\n'
-             '| "s[i:j] = t"                   | slice of *s* from *i* to '
-             '*j* is  |                       |\n'
+             '| "s[i:j] = t"                   | slice of *s* from *i* to *j* '
+             'is  |                       |\n'
              '|                                | replaced by the contents of '
              'the  |                       |\n'
              '|                                | iterable '
@@ -12763,12 +12783,11 @@ topics = {'assert': '\n'
              '\n'
              'Notes:\n'
              '\n'
-             '1. *t* must have the same length as the slice it is  '
-             'replacing.\n'
+             '1. *t* must have the same length as the slice it is  replacing.\n'
              '\n'
              '2. The C implementation of Python has historically accepted\n'
-             '   multiple parameters and implicitly joined them into a '
-             'tuple; this\n'
+             '   multiple parameters and implicitly joined them into a tuple; '
+             'this\n'
              '   no longer works in Python 2.0.  Use of this misfeature has '
              'been\n'
              '   deprecated since Python 1.4.\n'
@@ -12776,8 +12795,8 @@ topics = {'assert': '\n'
              '3. *x* can be any iterable object.\n'
              '\n'
              '4. Raises "ValueError" when *x* is not found in *s*. When a\n'
-             '   negative index is passed as the second or third parameter '
-             'to the\n'
+             '   negative index is passed as the second or third parameter to '
+             'the\n'
              '   "index()" method, the list length is added, as for slice '
              'indices.\n'
              '   If it is still negative, it is truncated to zero, as for '
@@ -12800,28 +12819,28 @@ topics = {'assert': '\n'
              'were\n'
              '   truncated to zero.\n'
              '\n'
-             '6. The "pop()" method\'s optional argument *i* defaults to '
-             '"-1", so\n'
+             '6. The "pop()" method\'s optional argument *i* defaults to "-1", '
+             'so\n'
              '   that by default the last item is removed and returned.\n'
              '\n'
              '7. The "sort()" and "reverse()" methods modify the list in '
              'place\n'
-             '   for economy of space when sorting or reversing a large '
-             'list.  To\n'
+             '   for economy of space when sorting or reversing a large list.  '
+             'To\n'
              "   remind you that they operate by side effect, they don't "
              'return the\n'
              '   sorted or reversed list.\n'
              '\n'
-             '8. The "sort()" method takes optional arguments for '
-             'controlling the\n'
+             '8. The "sort()" method takes optional arguments for controlling '
+             'the\n'
              '   comparisons.\n'
              '\n'
-             '   *cmp* specifies a custom comparison function of two '
-             'arguments (list\n'
+             '   *cmp* specifies a custom comparison function of two arguments '
+             '(list\n'
              '   items) which should return a negative, zero or positive '
              'number\n'
-             '   depending on whether the first argument is considered '
-             'smaller than,\n'
+             '   depending on whether the first argument is considered smaller '
+             'than,\n'
              '   equal to, or larger than the second argument: "cmp=lambda '
              'x,y:\n'
              '   cmp(x.lower(), y.lower())".  The default value is "None".\n'
@@ -12836,12 +12855,12 @@ topics = {'assert': '\n'
              'list\n'
              '   elements are sorted as if each comparison were reversed.\n'
              '\n'
-             '   In general, the *key* and *reverse* conversion processes '
-             'are much\n'
+             '   In general, the *key* and *reverse* conversion processes are '
+             'much\n'
              '   faster than specifying an equivalent *cmp* function.  This '
              'is\n'
-             '   because *cmp* is called multiple times for each list '
-             'element while\n'
+             '   because *cmp* is called multiple times for each list element '
+             'while\n'
              '   *key* and *reverse* touch each element only once.  Use\n'
              '   "functools.cmp_to_key()" to convert an old-style *cmp* '
              'function to\n'
@@ -12865,8 +12884,8 @@ topics = {'assert': '\n'
              '   then by salary grade).\n'
              '\n'
              '10. **CPython implementation detail:** While a list is being\n'
-             '    sorted, the effect of attempting to mutate, or even '
-             'inspect, the\n'
+             '    sorted, the effect of attempting to mutate, or even inspect, '
+             'the\n'
              '    list is undefined.  The C implementation of Python 2.3 and '
              'newer\n'
              '    makes the list appear empty for the duration, and raises\n'
@@ -12900,17 +12919,17 @@ topics = {'assert': '\n'
                      '\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
                      '| Operation                      | '
-                     'Result                           | '
-                     'Notes                 |\n'
+                     'Result                           | Notes                 '
+                     '|\n'
                      '+================================+==================================+=======================+\n'
                      '| "s[i] = x"                     | item *i* of *s* is '
                      'replaced by   |                       |\n'
                      '|                                | '
-                     '*x*                              '
-                     '|                       |\n'
+                     '*x*                              |                       '
+                     '|\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
-                     '| "s[i:j] = t"                   | slice of *s* from '
-                     '*i* to *j* is  |                       |\n'
+                     '| "s[i:j] = t"                   | slice of *s* from *i* '
+                     'to *j* is  |                       |\n'
                      '|                                | replaced by the '
                      'contents of the  |                       |\n'
                      '|                                | iterable '
@@ -12921,24 +12940,24 @@ topics = {'assert': '\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
                      '| "s[i:j:k] = t"                 | the elements of '
                      '"s[i:j:k]" are   | (1)                   |\n'
-                     '|                                | replaced by those '
-                     'of *t*         |                       |\n'
+                     '|                                | replaced by those of '
+                     '*t*         |                       |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
-                     '| "del s[i:j:k]"                 | removes the '
-                     'elements of          |                       |\n'
+                     '| "del s[i:j:k]"                 | removes the elements '
+                     'of          |                       |\n'
                      '|                                | "s[i:j:k]" from the '
                      'list         |                       |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
                      '| "s.append(x)"                  | same as '
                      '"s[len(s):len(s)] = [x]" | (2)                   |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
-                     '| "s.extend(x)" or "s += t"      | for the most part '
-                     'the same as    | (3)                   |\n'
+                     '| "s.extend(x)" or "s += t"      | for the most part the '
+                     'same as    | (3)                   |\n'
                      '|                                | "s[len(s):len(s)] = '
                      'x"           |                       |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
-                     '| "s *= n"                       | updates *s* with '
-                     'its contents    | (11)                  |\n'
+                     '| "s *= n"                       | updates *s* with its '
+                     'contents    | (11)                  |\n'
                      '|                                | repeated *n* '
                      'times               |                       |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
@@ -12949,8 +12968,8 @@ topics = {'assert': '\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
                      '| "s.index(x[, i[, j]])"         | return smallest *k* '
                      'such that    | (4)                   |\n'
-                     '|                                | "s[k] == x" and "i '
-                     '<= k < j"     |                       |\n'
+                     '|                                | "s[k] == x" and "i <= '
+                     'k < j"     |                       |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
                      '| "s.insert(i, x)"               | same as "s[i:i] = '
                      '[x]"           | (5)                   |\n'
@@ -12963,14 +12982,14 @@ topics = {'assert': '\n'
                      '| "s.remove(x)"                  | same as "del '
                      's[s.index(x)]"      | (4)                   |\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
-                     '| "s.reverse()"                  | reverses the items '
-                     'of *s* in     | (7)                   |\n'
+                     '| "s.reverse()"                  | reverses the items of '
+                     '*s* in     | (7)                   |\n'
                      '|                                | '
-                     'place                            '
-                     '|                       |\n'
+                     'place                            |                       '
+                     '|\n'
                      '+--------------------------------+----------------------------------+-----------------------+\n'
-                     '| "s.sort([cmp[, key[,           | sort the items of '
-                     '*s* in place   | (7)(8)(9)(10)         |\n'
+                     '| "s.sort([cmp[, key[,           | sort the items of *s* '
+                     'in place   | (7)(8)(9)(10)         |\n'
                      '| reverse]]])"                   '
                      '|                                  '
                      '|                       |\n'
@@ -12983,8 +13002,8 @@ topics = {'assert': '\n'
                      '\n'
                      '2. The C implementation of Python has historically '
                      'accepted\n'
-                     '   multiple parameters and implicitly joined them into '
-                     'tuple; this\n'
+                     '   multiple parameters and implicitly joined them into '
+                     'tuple; this\n'
                      '   no longer works in Python 2.0.  Use of this '
                      'misfeature has been\n'
                      '   deprecated since Python 1.4.\n'
@@ -12997,33 +13016,33 @@ topics = {'assert': '\n'
                      'parameter to the\n'
                      '   "index()" method, the list length is added, as for '
                      'slice indices.\n'
-                     '   If it is still negative, it is truncated to zero, '
-                     'as for slice\n'
+                     '   If it is still negative, it is truncated to zero, as '
+                     'for slice\n'
                      '   indices.\n'
                      '\n'
-                     '   Changed in version 2.3: Previously, "index()" '
-                     "didn't have arguments\n"
+                     '   Changed in version 2.3: Previously, "index()" didn\'t '
+                     'have arguments\n'
                      '   for specifying start and stop positions.\n'
                      '\n'
                      '5. When a negative index is passed as the first '
                      'parameter to the\n'
                      '   "insert()" method, the list length is added, as for '
                      'slice indices.\n'
-                     '   If it is still negative, it is truncated to zero, '
-                     'as for slice\n'
+                     '   If it is still negative, it is truncated to zero, as '
+                     'for slice\n'
                      '   indices.\n'
                      '\n'
                      '   Changed in version 2.3: Previously, all negative '
                      'indices were\n'
                      '   truncated to zero.\n'
                      '\n'
-                     '6. The "pop()" method\'s optional argument *i* '
-                     'defaults to "-1", so\n'
+                     '6. The "pop()" method\'s optional argument *i* defaults '
+                     'to "-1", so\n'
                      '   that by default the last item is removed and '
                      'returned.\n'
                      '\n'
-                     '7. The "sort()" and "reverse()" methods modify the '
-                     'list in place\n'
+                     '7. The "sort()" and "reverse()" methods modify the list '
+                     'in place\n'
                      '   for economy of space when sorting or reversing a '
                      'large list.  To\n'
                      '   remind you that they operate by side effect, they '
@@ -13038,8 +13057,8 @@ topics = {'assert': '\n'
                      'arguments (list\n'
                      '   items) which should return a negative, zero or '
                      'positive number\n'
-                     '   depending on whether the first argument is '
-                     'considered smaller than,\n'
+                     '   depending on whether the first argument is considered '
+                     'smaller than,\n'
                      '   equal to, or larger than the second argument: '
                      '"cmp=lambda x,y:\n'
                      '   cmp(x.lower(), y.lower())".  The default value is '
@@ -13051,17 +13070,17 @@ topics = {'assert': '\n'
                      '"key=str.lower".  The\n'
                      '   default value is "None".\n'
                      '\n'
-                     '   *reverse* is a boolean value.  If set to "True", '
-                     'then the list\n'
+                     '   *reverse* is a boolean value.  If set to "True", then '
+                     'the list\n'
                      '   elements are sorted as if each comparison were '
                      'reversed.\n'
                      '\n'
                      '   In general, the *key* and *reverse* conversion '
                      'processes are much\n'
-                     '   faster than specifying an equivalent *cmp* '
-                     'function.  This is\n'
-                     '   because *cmp* is called multiple times for each '
-                     'list element while\n'
+                     '   faster than specifying an equivalent *cmp* function.  '
+                     'This is\n'
+                     '   because *cmp* is called multiple times for each list '
+                     'element while\n'
                      '   *key* and *reverse* touch each element only once.  '
                      'Use\n'
                      '   "functools.cmp_to_key()" to convert an old-style '
@@ -13077,24 +13096,24 @@ topics = {'assert': '\n'
                      '\n'
                      '9. Starting with Python 2.3, the "sort()" method is '
                      'guaranteed to\n'
-                     '   be stable.  A sort is stable if it guarantees not '
-                     'to change the\n'
+                     '   be stable.  A sort is stable if it guarantees not to '
+                     'change the\n'
                      '   relative order of elements that compare equal --- '
                      'this is helpful\n'
-                     '   for sorting in multiple passes (for example, sort '
-                     'by department,\n'
+                     '   for sorting in multiple passes (for example, sort by '
+                     'department,\n'
                      '   then by salary grade).\n'
                      '\n'
                      '10. **CPython implementation detail:** While a list is '
                      'being\n'
-                     '    sorted, the effect of attempting to mutate, or '
-                     'even inspect, the\n'
+                     '    sorted, the effect of attempting to mutate, or even '
+                     'inspect, the\n'
                      '    list is undefined.  The C implementation of Python '
                      '2.3 and newer\n'
                      '    makes the list appear empty for the duration, and '
                      'raises\n'
-                     '    "ValueError" if it can detect that the list has '
-                     'been mutated\n'
+                     '    "ValueError" if it can detect that the list has been '
+                     'mutated\n'
                      '    during a sort.\n'
                      '\n'
                      '11. The value *n* is an integer, or an object '
@@ -13103,8 +13122,8 @@ topics = {'assert': '\n'
                      'clear the\n'
                      '    sequence.  Items in the sequence are not copied; '
                      'they are\n'
-                     '    referenced multiple times, as explained for "s * '
-                     'n" under Sequence\n'
+                     '    referenced multiple times, as explained for "s * n" '
+                     'under Sequence\n'
                      '    Types --- str, unicode, list, tuple, bytearray, '
                      'buffer, xrange.\n',
  'unary': '\n'
@@ -13116,8 +13135,7 @@ topics = {'assert': '\n'
           '\n'
           '   u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n'
           '\n'
-          'The unary "-" (minus) operator yields the negation of its '
-          'numeric\n'
+          'The unary "-" (minus) operator yields the negation of its numeric\n'
           'argument.\n'
           '\n'
           'The unary "+" (plus) operator yields its numeric argument '
@@ -13128,15 +13146,14 @@ topics = {'assert': '\n'
           'plain or long integer argument.  The bitwise inversion of "x" is\n'
           'defined as "-(x+1)".  It only applies to integral numbers.\n'
           '\n'
-          'In all three cases, if the argument does not have the proper '
-          'type, a\n'
+          'In all three cases, if the argument does not have the proper type, '
+          'a\n'
           '"TypeError" exception is raised.\n',
  'while': '\n'
           'The "while" statement\n'
           '*********************\n'
           '\n'
-          'The "while" statement is used for repeated execution as long as '
-          'an\n'
+          'The "while" statement is used for repeated execution as long as an\n'
           'expression is true:\n'
           '\n'
           '   while_stmt ::= "while" expression ":" suite\n'
@@ -13163,11 +13180,9 @@ topics = {'assert': '\n'
          '\n'
          'New in version 2.5.\n'
          '\n'
-         'The "with" statement is used to wrap the execution of a block '
-         'with\n'
+         'The "with" statement is used to wrap the execution of a block with\n'
          'methods defined by a context manager (see section With Statement\n'
-         'Context Managers). This allows common '
-         '"try"..."except"..."finally"\n'
+         'Context Managers). This allows common "try"..."except"..."finally"\n'
          'usage patterns to be encapsulated for convenient reuse.\n'
          '\n'
          '   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n'
@@ -13176,8 +13191,7 @@ topics = {'assert': '\n'
          'The execution of the "with" statement with one "item" proceeds as\n'
          'follows:\n'
          '\n'
-         '1. The context expression (the expression given in the '
-         '"with_item")\n'
+         '1. The context expression (the expression given in the "with_item")\n'
          '   is evaluated to obtain a context manager.\n'
          '\n'
          '2. The context manager\'s "__exit__()" is loaded for later use.\n'
@@ -13187,14 +13201,11 @@ topics = {'assert': '\n'
          '4. If a target was included in the "with" statement, the return\n'
          '   value from "__enter__()" is assigned to it.\n'
          '\n'
-         '   Note: The "with" statement guarantees that if the '
-         '"__enter__()"\n'
-         '     method returns without an error, then "__exit__()" will '
-         'always be\n'
-         '     called. Thus, if an error occurs during the assignment to '
-         'the\n'
-         '     target list, it will be treated the same as an error '
-         'occurring\n'
+         '   Note: The "with" statement guarantees that if the "__enter__()"\n'
+         '     method returns without an error, then "__exit__()" will always '
+         'be\n'
+         '     called. Thus, if an error occurs during the assignment to the\n'
+         '     target list, it will be treated the same as an error occurring\n'
          '     within the suite would be. See step 6 below.\n'
          '\n'
          '5. The suite is executed.\n'
@@ -13231,16 +13242,16 @@ topics = {'assert': '\n'
          '       with B() as b:\n'
          '           suite\n'
          '\n'
-         'Note: In Python 2.5, the "with" statement is only allowed when '
-         'the\n'
+         'Note: In Python 2.5, the "with" statement is only allowed when the\n'
          '  "with_statement" feature has been enabled.  It is always enabled '
          'in\n'
          '  Python 2.6.\n'
          '\n'
          'Changed in version 2.7: Support for multiple context expressions.\n'
          '\n'
-         'See also: **PEP 0343** - The "with" statement\n'
+         'See also:\n'
          '\n'
+         '  **PEP 343** - The "with" statement\n'
          '     The specification, background, and examples for the Python '
          '"with"\n'
          '     statement.\n',
@@ -13271,20 +13282,17 @@ topics = {'assert': '\n'
           'frozen and the value of "expression_list" is returned to '
           '"next()"\'s\n'
           'caller.  By "frozen" we mean that all local state is retained,\n'
-          'including the current bindings of local variables, the '
-          'instruction\n'
-          'pointer, and the internal evaluation stack: enough information '
-          'is\n'
-          'saved so that the next time "next()" is invoked, the function '
-          'can\n'
+          'including the current bindings of local variables, the instruction\n'
+          'pointer, and the internal evaluation stack: enough information is\n'
+          'saved so that the next time "next()" is invoked, the function can\n'
           'proceed exactly as if the "yield" statement were just another '
           'external\n'
           'call.\n'
           '\n'
           'As of Python version 2.5, the "yield" statement is now allowed in '
           'the\n'
-          '"try" clause of a "try" ...  "finally" construct.  If the '
-          'generator is\n'
+          '"try" clause of a "try" ...  "finally" construct.  If the generator '
+          'is\n'
           'not resumed before it is finalized (by reaching a zero reference '
           'count\n'
           "or by being garbage collected), the generator-iterator's "
@@ -13298,19 +13306,19 @@ topics = {'assert': '\n'
           '\n'
           'Note: In Python 2.2, the "yield" statement was only allowed when '
           'the\n'
-          '  "generators" feature has been enabled.  This "__future__" '
-          'import\n'
+          '  "generators" feature has been enabled.  This "__future__" import\n'
           '  statement was used to enable the feature:\n'
           '\n'
           '     from __future__ import generators\n'
           '\n'
-          'See also: **PEP 0255** - Simple Generators\n'
+          'See also:\n'
           '\n'
+          '  **PEP 255** - Simple Generators\n'
           '     The proposal for adding generators and the "yield" statement '
           'to\n'
           '     Python.\n'
           '\n'
-          '  **PEP 0342** - Coroutines via Enhanced Generators\n'
+          '  **PEP 342** - Coroutines via Enhanced Generators\n'
           '     The proposal that, among other generator enhancements, '
           'proposed\n'
           '     allowing "yield" to appear inside a "try" ... "finally" '
index c1d0865..9a5b8a2 100644 (file)
@@ -961,7 +961,7 @@ def formatdate(timeval=None):
 
     According to RFC 1123, day and month names must always be in
     English.  If not for that, this code could use strftime().  It
-    can't because strftime() honors the locale and could generated
+    can't because strftime() honors the locale and could generate
     non-English names.
     """
     if timeval is None:
index 73f8d80..7f61c67 100644 (file)
@@ -102,13 +102,16 @@ class Completer:
         """
         import keyword
         matches = []
+        seen = {"__builtins__"}
         n = len(text)
         for word in keyword.kwlist:
             if word[:n] == text:
+                seen.add(word)
                 matches.append(word)
-        for nspace in [__builtin__.__dict__, self.namespace]:
+        for nspace in [self.namespace, __builtin__.__dict__]:
             for word, val in nspace.items():
-                if word[:n] == text and word != "__builtins__":
+                if word[:n] == text and word not in seen:
+                    seen.add(word)
                     matches.append(self._callable_postfix(val, word))
         return matches
 
index b46b753..a7137a3 100644 (file)
@@ -136,7 +136,7 @@ class RobotFileParser:
 
         # Until the robots.txt file has been read or found not
         # to exist, we must assume that no url is allowable.
-        # This prevents false positives when a user erronenously
+        # This prevents false positives when a user erroneously
         # calls can_fetch() before calling read().
         if not self.last_checked:
             return False
index c4d7cc2..ad4d077 100644 (file)
@@ -97,27 +97,35 @@ def _get_filename(loader, mod_name):
     return None
 
 # Helper to get the loader, code and filename for a module
-def _get_module_details(mod_name):
-    loader = get_loader(mod_name)
-    if loader is None:
-        raise ImportError("No module named %s" % mod_name)
-    if loader.is_package(mod_name):
+def _get_module_details(mod_name, error=ImportError):
+    try:
+        loader = get_loader(mod_name)
+        if loader is None:
+            raise error("No module named %s" % mod_name)
+        ispkg = loader.is_package(mod_name)
+    except ImportError as e:
+        raise error(format(e))
+    if ispkg:
         if mod_name == "__main__" or mod_name.endswith(".__main__"):
-            raise ImportError("Cannot use package as __main__ module")
+            raise error("Cannot use package as __main__ module")
+        __import__(mod_name)  # Do not catch exceptions initializing package
         try:
             pkg_main_name = mod_name + ".__main__"
             return _get_module_details(pkg_main_name)
         except ImportError, e:
-            raise ImportError(("%s; %r is a package and cannot " +
+            raise error(("%s; %r is a package and cannot " +
                                "be directly executed") %(e, mod_name))
-    code = loader.get_code(mod_name)
+    try:
+        code = loader.get_code(mod_name)
+    except ImportError as e:
+        raise error(format(e))
     if code is None:
-        raise ImportError("No code object available for %s" % mod_name)
+        raise error("No code object available for %s" % mod_name)
     filename = _get_filename(loader, mod_name)
     return mod_name, loader, code, filename
 
 
-def _get_main_module_details():
+def _get_main_module_details(error=ImportError):
     # Helper that gives a nicer error message when attempting to
     # execute a zipfile or directory by invoking __main__.py
     main_name = "__main__"
@@ -125,10 +133,13 @@ def _get_main_module_details():
         return _get_module_details(main_name)
     except ImportError as exc:
         if main_name in str(exc):
-            raise ImportError("can't find %r module in %r" %
+            raise error("can't find %r module in %r" %
                               (main_name, sys.path[0]))
         raise
 
+class _Error(Exception):
+    """Error that _run_module_as_main() should report without a traceback"""
+
 # This function is the actual implementation of the -m switch and direct
 # execution of zipfiles and directories and is deliberately kept private.
 # This avoids a repeat of the situation where run_module() no longer met the
@@ -148,11 +159,12 @@ def _run_module_as_main(mod_name, alter_argv=True):
     """
     try:
         if alter_argv or mod_name != "__main__": # i.e. -m switch
-            mod_name, loader, code, fname = _get_module_details(mod_name)
+            mod_name, loader, code, fname = _get_module_details(
+                mod_name, _Error)
         else:          # i.e. directory or zipfile execution
-            mod_name, loader, code, fname = _get_main_module_details()
-    except ImportError as exc:
-        msg = "%s: %s" % (sys.executable, str(exc))
+            mod_name, loader, code, fname = _get_main_module_details(_Error)
+    except _Error as exc:
+        msg = "%s: %s" % (sys.executable, exc)
         sys.exit(msg)
     pkg_name = mod_name.rpartition('.')[0]
     main_globals = sys.modules["__main__"].__dict__
index 8388b98..e1651c0 100755 (executable)
@@ -656,6 +656,11 @@ class SMTP:
             self.ehlo_resp = None
             self.esmtp_features = {}
             self.does_esmtp = 0
+        else:
+            # RFC 3207:
+            # 501 Syntax error (no parameters allowed)
+            # 454 TLS not available due to temporary reason
+            raise SMTPResponseException(resp, reply)
         return (resp, reply)
 
     def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
index 614af29..437634c 100644 (file)
@@ -549,7 +549,7 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
     global default timeout setting returned by :func:`getdefaulttimeout`
     is used.  If *source_address* is set it must be a tuple of (host, port)
     for the socket to bind as a source address before making the connection.
-    An host of '' or port 0 tells the OS to use the default.
+    A host of '' or port 0 tells the OS to use the default.
     """
 
     host, port = address
index f4b8428..0e0196a 100644 (file)
@@ -229,7 +229,7 @@ class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
         self.assertEqual(row[0], "a\x00b")
 
     def CheckCustom(self):
-        # A custom factory should receive an str argument
+        # A custom factory should receive a str argument
         self.con.text_factory = lambda x: x
         row = self.con.execute("select value from test").fetchone()
         self.assertIs(type(row[0]), str)
index 72c9277..8b0a715 100644 (file)
@@ -73,7 +73,7 @@ class RegressionTests(unittest.TestCase):
     def CheckStatementFinalizationOnCloseDb(self):
         # pysqlite versions <= 2.3.3 only finalized statements in the statement
         # cache when closing the database. statements that were still
-        # referenced in cursors weren't closed an could provoke "
+        # referenced in cursors weren't closed and could provoke "
         # "OperationalError: Unable to close due to unfinalised statements".
         con = sqlite.connect(":memory:")
         cursors = []
index c29cc16..75f488b 100644 (file)
@@ -721,14 +721,14 @@ def parse(str, flags=0, pattern=None):
     elif tail:
         raise error, "bogus characters at end of regular expression"
 
-    if flags & SRE_FLAG_DEBUG:
-        p.dump()
-
     if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
         # the VERBOSE flag was switched on inside the pattern.  to be
         # on the safe side, we'll parse the whole thing again...
         return parse(str, p.pattern.flags)
 
+    if flags & SRE_FLAG_DEBUG:
+        p.dump()
+
     return p
 
 def parse_template(source, pattern):
index 5df6ed3..6070380 100644 (file)
@@ -141,6 +141,7 @@ from socket import socket, AF_INET, SOCK_STREAM, create_connection
 from socket import SOL_SOCKET, SO_TYPE
 import base64        # for DER-to-PEM translation
 import errno
+import warnings
 
 if _ssl.HAS_TLS_UNIQUE:
     CHANNEL_BINDING_TYPES = ['tls-unique']
@@ -375,12 +376,16 @@ class SSLContext(_SSLContext):
 
     def _load_windows_store_certs(self, storename, purpose):
         certs = bytearray()
-        for cert, encoding, trust in enum_certificates(storename):
-            # CA certs are never PKCS#7 encoded
-            if encoding == "x509_asn":
-                if trust is True or purpose.oid in trust:
-                    certs.extend(cert)
-        self.load_verify_locations(cadata=certs)
+        try:
+            for cert, encoding, trust in enum_certificates(storename):
+                # CA certs are never PKCS#7 encoded
+                if encoding == "x509_asn":
+                    if trust is True or purpose.oid in trust:
+                        certs.extend(cert)
+        except OSError:
+            warnings.warn("unable to enumerate Windows certificate store")
+        if certs:
+            self.load_verify_locations(cadata=certs)
         return certs
 
     def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
@@ -481,13 +486,30 @@ def _create_unverified_context(protocol=PROTOCOL_SSLv23, cert_reqs=None,
 
     return context
 
-# Used by http.client if no context is explicitly passed.
-_create_default_https_context = create_default_context
-
-
 # Backwards compatibility alias, even though it's not a public name.
 _create_stdlib_context = _create_unverified_context
 
+# PEP 493: Verify HTTPS by default, but allow envvar to override that
+_https_verify_envvar = 'PYTHONHTTPSVERIFY'
+
+def _get_https_context_factory():
+    if not sys.flags.ignore_environment:
+        config_setting = os.environ.get(_https_verify_envvar)
+        if config_setting == '0':
+            return _create_unverified_context
+    return create_default_context
+
+_create_default_https_context = _get_https_context_factory()
+
+# PEP 493: "private" API to configure HTTPS defaults without monkeypatching
+def _https_verify_certificates(enable=True):
+    """Verify server HTTPS certificates by default?"""
+    global _create_default_https_context
+    if enable:
+        _create_default_https_context = create_default_context
+    else:
+        _create_default_https_context = _create_unverified_context
+
 
 class SSLSocket(socket):
     """This class implements a subtype of socket.socket that wraps
@@ -607,7 +629,7 @@ class SSLSocket(socket):
             # EAGAIN.
             self.getpeername()
 
-    def read(self, len=0, buffer=None):
+    def read(self, len=1024, buffer=None):
         """Read up to LEN bytes and return them.
         Return zero-length string on EOF."""
 
@@ -618,7 +640,7 @@ class SSLSocket(socket):
             if buffer is not None:
                 v = self._sslobj.read(len, buffer)
             else:
-                v = self._sslobj.read(len or 1024)
+                v = self._sslobj.read(len)
             return v
         except SSLError as x:
             if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
index f9e9104..187566b 100644 (file)
@@ -498,7 +498,6 @@ def _args_from_interpreter_flags():
         'ignore_environment': 'E',
         'verbose': 'v',
         'bytes_warning': 'b',
-        'hash_randomization': 'R',
         'py3k_warning': '3',
     }
     args = []
@@ -506,6 +505,8 @@ def _args_from_interpreter_flags():
         v = getattr(sys.flags, flag)
         if v > 0:
             args.append('-' + opt * v)
+    if getattr(sys.flags, 'hash_randomization') != 0:
+        args.append('-R')
     for opt in sys.warnoptions:
         args.append('-W' + opt)
     return args
@@ -1141,7 +1142,10 @@ class Popen(object):
                 errread, errwrite = self.pipe_cloexec()
                 to_close.update((errread, errwrite))
             elif stderr == STDOUT:
-                errwrite = c2pwrite
+                if c2pwrite is not None:
+                    errwrite = c2pwrite
+                else: # child's stdout is not set, use parent's stdout
+                    errwrite = sys.__stdout__.fileno()
             elif isinstance(stderr, int):
                 errwrite = stderr
             else:
@@ -1312,8 +1316,12 @@ class Popen(object):
                     os.close(errpipe_write)
 
                 # Wait for exec to fail or succeed; possibly raising exception
-                # Exception limited to 1M
                 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
+                pickle_bits = []
+                while data:
+                    pickle_bits.append(data)
+                    data = _eintr_retry_call(os.read, errpipe_read, 1048576)
+                data = "".join(pickle_bits)
             finally:
                 if p2cread is not None and p2cwrite is not None:
                     _close_in_parent(p2cread)
index 66e5393..be68800 100644 (file)
@@ -1844,11 +1844,12 @@ class TarFile(object):
         return [tarinfo.name for tarinfo in self.getmembers()]
 
     def gettarinfo(self, name=None, arcname=None, fileobj=None):
-        """Create a TarInfo object for either the file `name' or the file
-           object `fileobj' (using os.fstat on its file descriptor). You can
-           modify some of the TarInfo's attributes before you add it using
-           addfile(). If given, `arcname' specifies an alternative name for the
-           file in the archive.
+        """Create a TarInfo object from the result of os.stat or equivalent
+           on an existing file. The file is either named by `name', or
+           specified as a file object `fileobj' with a file descriptor. If
+           given, `arcname' specifies an alternative name for the file in the
+           archive, otherwise, the name is taken from the 'name' attribute of
+           'fileobj', or the 'name' argument.
         """
         self._check("aw")
 
@@ -1869,7 +1870,7 @@ class TarFile(object):
         # Now, fill the TarInfo object with
         # information specific for the file.
         tarinfo = self.tarinfo()
-        tarinfo.tarfile = self
+        tarinfo.tarfile = self  # Not needed
 
         # Use os.stat or os.lstat, depending on platform
         # and if symlinks shall be resolved.
@@ -2034,7 +2035,7 @@ class TarFile(object):
     def addfile(self, tarinfo, fileobj=None):
         """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
            given, tarinfo.size bytes are read from it and added to the archive.
-           You can create TarInfo objects using gettarinfo().
+           You can create TarInfo objects directly, or by using gettarinfo().
            On Windows platforms, `fileobj' should always be opened with mode
            'rb' to avoid irritation about the file size.
         """
index 184dfc1..7e3b25a 100644 (file)
@@ -455,8 +455,8 @@ def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
     The file is created as mkstemp() would do it.
 
     Returns an object with a file-like interface; the name of the file
-    is accessible as file.name.  The file will be automatically deleted
-    when it is closed unless the 'delete' argument is set to False.
+    is accessible as its 'name' attribute.  The file will be automatically
+    deleted when it is closed unless the 'delete' argument is set to False.
     """
 
     if dir is None:
@@ -476,7 +476,8 @@ def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
     try:
         file = _os.fdopen(fd, mode, bufsize)
         return _TemporaryFileWrapper(file, name, delete)
-    except:
+    except BaseException:
+        _os.unlink(name)
         _os.close(fd)
         raise
 
diff --git a/Lib/test/buffer_tests.py b/Lib/test/buffer_tests.py
deleted file mode 100644 (file)
index d0d8a56..0000000
+++ /dev/null
@@ -1,206 +0,0 @@
-# Tests that work for both bytes and buffer objects.
-# See PEP 3137.
-
-import struct
-import sys
-
-class MixinBytesBufferCommonTests(object):
-    """Tests that work for both bytes and buffer objects.
-    See PEP 3137.
-    """
-
-    def marshal(self, x):
-        """Convert x into the appropriate type for these tests."""
-        raise RuntimeError('test class must provide a marshal method')
-
-    def test_islower(self):
-        self.assertFalse(self.marshal(b'').islower())
-        self.assertTrue(self.marshal(b'a').islower())
-        self.assertFalse(self.marshal(b'A').islower())
-        self.assertFalse(self.marshal(b'\n').islower())
-        self.assertTrue(self.marshal(b'abc').islower())
-        self.assertFalse(self.marshal(b'aBc').islower())
-        self.assertTrue(self.marshal(b'abc\n').islower())
-        self.assertRaises(TypeError, self.marshal(b'abc').islower, 42)
-
-    def test_isupper(self):
-        self.assertFalse(self.marshal(b'').isupper())
-        self.assertFalse(self.marshal(b'a').isupper())
-        self.assertTrue(self.marshal(b'A').isupper())
-        self.assertFalse(self.marshal(b'\n').isupper())
-        self.assertTrue(self.marshal(b'ABC').isupper())
-        self.assertFalse(self.marshal(b'AbC').isupper())
-        self.assertTrue(self.marshal(b'ABC\n').isupper())
-        self.assertRaises(TypeError, self.marshal(b'abc').isupper, 42)
-
-    def test_istitle(self):
-        self.assertFalse(self.marshal(b'').istitle())
-        self.assertFalse(self.marshal(b'a').istitle())
-        self.assertTrue(self.marshal(b'A').istitle())
-        self.assertFalse(self.marshal(b'\n').istitle())
-        self.assertTrue(self.marshal(b'A Titlecased Line').istitle())
-        self.assertTrue(self.marshal(b'A\nTitlecased Line').istitle())
-        self.assertTrue(self.marshal(b'A Titlecased, Line').istitle())
-        self.assertFalse(self.marshal(b'Not a capitalized String').istitle())
-        self.assertFalse(self.marshal(b'Not\ta Titlecase String').istitle())
-        self.assertFalse(self.marshal(b'Not--a Titlecase String').istitle())
-        self.assertFalse(self.marshal(b'NOT').istitle())
-        self.assertRaises(TypeError, self.marshal(b'abc').istitle, 42)
-
-    def test_isspace(self):
-        self.assertFalse(self.marshal(b'').isspace())
-        self.assertFalse(self.marshal(b'a').isspace())
-        self.assertTrue(self.marshal(b' ').isspace())
-        self.assertTrue(self.marshal(b'\t').isspace())
-        self.assertTrue(self.marshal(b'\r').isspace())
-        self.assertTrue(self.marshal(b'\n').isspace())
-        self.assertTrue(self.marshal(b' \t\r\n').isspace())
-        self.assertFalse(self.marshal(b' \t\r\na').isspace())
-        self.assertRaises(TypeError, self.marshal(b'abc').isspace, 42)
-
-    def test_isalpha(self):
-        self.assertFalse(self.marshal(b'').isalpha())
-        self.assertTrue(self.marshal(b'a').isalpha())
-        self.assertTrue(self.marshal(b'A').isalpha())
-        self.assertFalse(self.marshal(b'\n').isalpha())
-        self.assertTrue(self.marshal(b'abc').isalpha())
-        self.assertFalse(self.marshal(b'aBc123').isalpha())
-        self.assertFalse(self.marshal(b'abc\n').isalpha())
-        self.assertRaises(TypeError, self.marshal(b'abc').isalpha, 42)
-
-    def test_isalnum(self):
-        self.assertFalse(self.marshal(b'').isalnum())
-        self.assertTrue(self.marshal(b'a').isalnum())
-        self.assertTrue(self.marshal(b'A').isalnum())
-        self.assertFalse(self.marshal(b'\n').isalnum())
-        self.assertTrue(self.marshal(b'123abc456').isalnum())
-        self.assertTrue(self.marshal(b'a1b3c').isalnum())
-        self.assertFalse(self.marshal(b'aBc000 ').isalnum())
-        self.assertFalse(self.marshal(b'abc\n').isalnum())
-        self.assertRaises(TypeError, self.marshal(b'abc').isalnum, 42)
-
-    def test_isdigit(self):
-        self.assertFalse(self.marshal(b'').isdigit())
-        self.assertFalse(self.marshal(b'a').isdigit())
-        self.assertTrue(self.marshal(b'0').isdigit())
-        self.assertTrue(self.marshal(b'0123456789').isdigit())
-        self.assertFalse(self.marshal(b'0123456789a').isdigit())
-
-        self.assertRaises(TypeError, self.marshal(b'abc').isdigit, 42)
-
-    def test_lower(self):
-        self.assertEqual(b'hello', self.marshal(b'HeLLo').lower())
-        self.assertEqual(b'hello', self.marshal(b'hello').lower())
-        self.assertRaises(TypeError, self.marshal(b'hello').lower, 42)
-
-    def test_upper(self):
-        self.assertEqual(b'HELLO', self.marshal(b'HeLLo').upper())
-        self.assertEqual(b'HELLO', self.marshal(b'HELLO').upper())
-        self.assertRaises(TypeError, self.marshal(b'hello').upper, 42)
-
-    def test_capitalize(self):
-        self.assertEqual(b' hello ', self.marshal(b' hello ').capitalize())
-        self.assertEqual(b'Hello ', self.marshal(b'Hello ').capitalize())
-        self.assertEqual(b'Hello ', self.marshal(b'hello ').capitalize())
-        self.assertEqual(b'Aaaa', self.marshal(b'aaaa').capitalize())
-        self.assertEqual(b'Aaaa', self.marshal(b'AaAa').capitalize())
-
-        self.assertRaises(TypeError, self.marshal(b'hello').capitalize, 42)
-
-    def test_ljust(self):
-        self.assertEqual(b'abc       ', self.marshal(b'abc').ljust(10))
-        self.assertEqual(b'abc   ', self.marshal(b'abc').ljust(6))
-        self.assertEqual(b'abc', self.marshal(b'abc').ljust(3))
-        self.assertEqual(b'abc', self.marshal(b'abc').ljust(2))
-        self.assertEqual(b'abc*******', self.marshal(b'abc').ljust(10, '*'))
-        self.assertRaises(TypeError, self.marshal(b'abc').ljust)
-
-    def test_rjust(self):
-        self.assertEqual(b'       abc', self.marshal(b'abc').rjust(10))
-        self.assertEqual(b'   abc', self.marshal(b'abc').rjust(6))
-        self.assertEqual(b'abc', self.marshal(b'abc').rjust(3))
-        self.assertEqual(b'abc', self.marshal(b'abc').rjust(2))
-        self.assertEqual(b'*******abc', self.marshal(b'abc').rjust(10, '*'))
-        self.assertRaises(TypeError, self.marshal(b'abc').rjust)
-
-    def test_center(self):
-        self.assertEqual(b'   abc    ', self.marshal(b'abc').center(10))
-        self.assertEqual(b' abc  ', self.marshal(b'abc').center(6))
-        self.assertEqual(b'abc', self.marshal(b'abc').center(3))
-        self.assertEqual(b'abc', self.marshal(b'abc').center(2))
-        self.assertEqual(b'***abc****', self.marshal(b'abc').center(10, '*'))
-        self.assertRaises(TypeError, self.marshal(b'abc').center)
-
-    def test_swapcase(self):
-        self.assertEqual(b'hEllO CoMPuTErS',
-            self.marshal(b'HeLLo cOmpUteRs').swapcase())
-
-        self.assertRaises(TypeError, self.marshal(b'hello').swapcase, 42)
-
-    def test_zfill(self):
-        self.assertEqual(b'123', self.marshal(b'123').zfill(2))
-        self.assertEqual(b'123', self.marshal(b'123').zfill(3))
-        self.assertEqual(b'0123', self.marshal(b'123').zfill(4))
-        self.assertEqual(b'+123', self.marshal(b'+123').zfill(3))
-        self.assertEqual(b'+123', self.marshal(b'+123').zfill(4))
-        self.assertEqual(b'+0123', self.marshal(b'+123').zfill(5))
-        self.assertEqual(b'-123', self.marshal(b'-123').zfill(3))
-        self.assertEqual(b'-123', self.marshal(b'-123').zfill(4))
-        self.assertEqual(b'-0123', self.marshal(b'-123').zfill(5))
-        self.assertEqual(b'000', self.marshal(b'').zfill(3))
-        self.assertEqual(b'34', self.marshal(b'34').zfill(1))
-        self.assertEqual(b'0034', self.marshal(b'34').zfill(4))
-
-        self.assertRaises(TypeError, self.marshal(b'123').zfill)
-
-    def test_expandtabs(self):
-        self.assertEqual(b'abc\rab      def\ng       hi',
-                         self.marshal(b'abc\rab\tdef\ng\thi').expandtabs())
-        self.assertEqual(b'abc\rab      def\ng       hi',
-                         self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(8))
-        self.assertEqual(b'abc\rab  def\ng   hi',
-                         self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(4))
-        self.assertEqual(b'abc\r\nab  def\ng   hi',
-                         self.marshal(b'abc\r\nab\tdef\ng\thi').expandtabs(4))
-        self.assertEqual(b'abc\rab      def\ng       hi',
-                         self.marshal(b'abc\rab\tdef\ng\thi').expandtabs())
-        self.assertEqual(b'abc\rab      def\ng       hi',
-                         self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(8))
-        self.assertEqual(b'abc\r\nab\r\ndef\ng\r\nhi',
-            self.marshal(b'abc\r\nab\r\ndef\ng\r\nhi').expandtabs(4))
-        self.assertEqual(b'  a\n b', self.marshal(b' \ta\n\tb').expandtabs(1))
-
-        self.assertRaises(TypeError, self.marshal(b'hello').expandtabs, 42, 42)
-        # This test is only valid when sizeof(int) == sizeof(void*) == 4.
-        if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
-            self.assertRaises(OverflowError,
-                              self.marshal(b'\ta\n\tb').expandtabs, sys.maxint)
-
-    def test_title(self):
-        self.assertEqual(b' Hello ', self.marshal(b' hello ').title())
-        self.assertEqual(b'Hello ', self.marshal(b'hello ').title())
-        self.assertEqual(b'Hello ', self.marshal(b'Hello ').title())
-        self.assertEqual(b'Format This As Title String',
-                         self.marshal(b'fOrMaT thIs aS titLe String').title())
-        self.assertEqual(b'Format,This-As*Title;String',
-                         self.marshal(b'fOrMaT,thIs-aS*titLe;String').title())
-        self.assertEqual(b'Getint', self.marshal(b'getInt').title())
-        self.assertRaises(TypeError, self.marshal(b'hello').title, 42)
-
-    def test_splitlines(self):
-        self.assertEqual([b'abc', b'def', b'', b'ghi'],
-                         self.marshal(b'abc\ndef\n\rghi').splitlines())
-        self.assertEqual([b'abc', b'def', b'', b'ghi'],
-                         self.marshal(b'abc\ndef\n\r\nghi').splitlines())
-        self.assertEqual([b'abc', b'def', b'ghi'],
-                         self.marshal(b'abc\ndef\r\nghi').splitlines())
-        self.assertEqual([b'abc', b'def', b'ghi'],
-                         self.marshal(b'abc\ndef\r\nghi\n').splitlines())
-        self.assertEqual([b'abc', b'def', b'ghi', b''],
-                         self.marshal(b'abc\ndef\r\nghi\n\r').splitlines())
-        self.assertEqual([b'', b'abc', b'def', b'ghi', b''],
-                         self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines())
-        self.assertEqual([b'\n', b'abc\n', b'def\r\n', b'ghi\n', b'\r'],
-                         self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines(1))
-
-        self.assertRaises(TypeError, self.marshal(b'abc').splitlines, 42, 42)
diff --git a/Lib/test/capath/0e4015b9.0 b/Lib/test/capath/0e4015b9.0
new file mode 100644 (file)
index 0000000..b6d259b
--- /dev/null
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV
+BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u
+IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv
+bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG
+A1UEBhMCWFkxFzAVBgNVBAcMDkNhc3RsZSBBbnRocmF4MSMwIQYDVQQKDBpQeXRo
+b24gU29mdHdhcmUgRm91bmRhdGlvbjEjMCEGA1UEAwwac2VsZi1zaWduZWQucHl0
+aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ
+Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm
+Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv
+EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl
+bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN
+AQEFBQADgYEAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h
+TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515
+C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM=
+-----END CERTIFICATE-----
diff --git a/Lib/test/capath/ce7b8643.0 b/Lib/test/capath/ce7b8643.0
new file mode 100644 (file)
index 0000000..b6d259b
--- /dev/null
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV
+BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u
+IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv
+bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG
+A1UEBhMCWFkxFzAVBgNVBAcMDkNhc3RsZSBBbnRocmF4MSMwIQYDVQQKDBpQeXRo
+b24gU29mdHdhcmUgRm91bmRhdGlvbjEjMCEGA1UEAwwac2VsZi1zaWduZWQucHl0
+aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ
+Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm
+Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv
+EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl
+bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN
+AQEFBQADgYEAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h
+TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515
+C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM=
+-----END CERTIFICATE-----
diff --git a/Lib/test/https_svn_python_org_root.pem b/Lib/test/https_svn_python_org_root.pem
deleted file mode 100644 (file)
index e7dfc82..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290
-IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB
-IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA
-Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO
-BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi
-MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ
-ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC
-CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ
-8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6
-zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y
-fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7
-w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc
-G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k
-epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q
-laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ
-QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU
-fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826
-YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w
-ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY
-gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe
-MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0
-IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy
-dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw
-czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0
-dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl
-aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC
-AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg
-b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB
-ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc
-nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg
-18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c
-gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl
-Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY
-sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T
-SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF
-CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum
-GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk
-zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW
-omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD
------END CERTIFICATE-----
index b8d6d6b..ed606db 100644 (file)
@@ -532,3 +532,14 @@ class CommonTest(seq_tests.CommonTest):
             def __iter__(self):
                 raise KeyboardInterrupt
         self.assertRaises(KeyboardInterrupt, list, F())
+
+    def test_exhausted_iterator(self):
+        a = self.type2test([1, 2, 3])
+        exhit = iter(a)
+        empit = iter(a)
+        for x in exhit:  # exhaust the iterator
+            next(empit)  # not exhausted
+        a.append(9)
+        self.assertEqual(list(exhit), [])
+        self.assertEqual(list(empit), [9])
+        self.assertEqual(a, self.type2test([1, 2, 3, 9]))
index d8346ea..855a9c4 100644 (file)
@@ -6,7 +6,9 @@ import StringIO
 import cStringIO
 import pickletools
 import copy_reg
+import sys
 
+from test import test_support as support
 from test.test_support import TestFailed, verbose, have_unicode, TESTFN
 try:
     from test.test_support import _2G, _1M, precisionbigmemtest
@@ -58,6 +60,21 @@ def run_with_locale(catstr, *locales):
         return inner
     return decorator
 
+def no_tracing(func):
+    """Decorator to temporarily turn off tracing for the duration of a test."""
+    if not hasattr(sys, 'gettrace'):
+        return func
+    else:
+        def wrapper(*args, **kwargs):
+            original_trace = sys.gettrace()
+            try:
+                sys.settrace(None)
+                return func(*args, **kwargs)
+            finally:
+                sys.settrace(original_trace)
+        wrapper.__name__ = func.__name__
+        return wrapper
+
 
 # Return True if opcode code appears in the pickle, else False.
 def opcode_in_pickle(code, pickle):
@@ -74,6 +91,16 @@ def count_opcode(code, pickle):
             n += 1
     return n
 
+class UnseekableIO(StringIO.StringIO):
+    def peek(self, *args):
+        raise NotImplementedError
+
+    def seek(self, *args):
+        raise NotImplementedError
+
+    def tell(self):
+        raise NotImplementedError
+
 # We can't very well test the extension registry without putting known stuff
 # in it, but we have to be careful to restore its original state.  Code
 # should do this:
@@ -473,6 +500,24 @@ class AbstractUnpickleTests(unittest.TestCase):
                 self.assertEqual(getattr(obj, slot, None),
                                  getattr(objcopy, slot, None), msg=msg)
 
+    def check_unpickling_error(self, errors, data):
+        try:
+            try:
+                self.loads(data)
+            except:
+                if support.verbose > 1:
+                    exc_type, exc, tb = sys.exc_info()
+                    print '%-32r - %s: %s' % (data, exc_type.__name__, exc)
+                raise
+        except errors:
+            pass
+        else:
+            try:
+                exc_name = errors.__name__
+            except AttributeError:
+                exc_name = str(errors)
+            raise self.failureException('%s not raised' % exc_name)
+
     def test_load_from_canned_string(self):
         expected = self._testdata
         for canned in DATA0, DATA1, DATA2:
@@ -480,7 +525,7 @@ class AbstractUnpickleTests(unittest.TestCase):
             self.assert_is_copy(expected, got)
 
     def test_garyp(self):
-        self.assertRaises(self.error, self.loads, 'garyp')
+        self.check_unpickling_error(self.error, 'garyp')
 
     def test_maxint64(self):
         maxint64 = (1L << 63) - 1
@@ -490,7 +535,7 @@ class AbstractUnpickleTests(unittest.TestCase):
 
         # Try too with a bogus literal.
         data = 'I' + str(maxint64) + 'JUNK\n.'
-        self.assertRaises(ValueError, self.loads, data)
+        self.check_unpickling_error(ValueError, data)
 
     def test_insecure_strings(self):
         insecure = ["abc", "2 + 2", # not quoted
@@ -511,7 +556,7 @@ class AbstractUnpickleTests(unittest.TestCase):
                     ]
         for s in insecure:
             buf = "S" + s + "\n."
-            self.assertRaises(ValueError, self.loads, buf)
+            self.check_unpickling_error(ValueError, buf)
 
     def test_correctly_quoted_string(self):
         goodpickles = [("S''\n.", ''),
@@ -578,11 +623,6 @@ class AbstractUnpickleTests(unittest.TestCase):
                        'q\x00oq\x01}q\x02b.').replace('X', xname)
             self.assert_is_copy(X(*args), self.loads(pickle2))
 
-    def test_pop_empty_stack(self):
-        # Test issue7455
-        s = '0'
-        self.assertRaises((cPickle.UnpicklingError, IndexError), self.loads, s)
-
     def test_load_str(self):
         # From Python 2: pickle.dumps('a\x00\xa0', protocol=0)
         self.assertEqual(self.loads("S'a\\x00\\xa0'\n."), 'a\x00\xa0')
@@ -607,8 +647,8 @@ class AbstractUnpickleTests(unittest.TestCase):
         self.assertIs(self.loads('I00\n.'), False)
 
     def test_misc_get(self):
-        self.assertRaises(self.error, self.loads, 'g0\np0\n')
-        self.assertRaises(self.error, self.loads, 'h\x00q\x00')
+        self.check_unpickling_error(self.error, 'g0\np0\n')
+        self.check_unpickling_error(self.error, 'h\x00q\x00')
 
     def test_get(self):
         pickled = '((lp100000\ng100000\nt.'
@@ -634,6 +674,148 @@ class AbstractUnpickleTests(unittest.TestCase):
         self.assertEqual(unpickled, ([],)*2)
         self.assertIs(unpickled[0], unpickled[1])
 
+    def test_bad_stack(self):
+        badpickles = [
+            '.',                        # STOP
+            '0',                        # POP
+            '1',                        # POP_MARK
+            '2',                        # DUP
+            # '(2',                     # PyUnpickler doesn't raise
+            'R',                        # REDUCE
+            ')R',
+            'a',                        # APPEND
+            'Na',
+            'b',                        # BUILD
+            'Nb',
+            'd',                        # DICT
+            'e',                        # APPENDS
+            # '(e',                     # PyUnpickler raises AttributeError
+            'i__builtin__\nlist\n',     # INST
+            'l',                        # LIST
+            'o',                        # OBJ
+            '(o',
+            'p1\n',                     # PUT
+            'q\x00',                    # BINPUT
+            'r\x00\x00\x00\x00',        # LONG_BINPUT
+            's',                        # SETITEM
+            'Ns',
+            'NNs',
+            't',                        # TUPLE
+            'u',                        # SETITEMS
+            # '(u',                     # PyUnpickler doesn't raise
+            '}(Nu',
+            '\x81',                     # NEWOBJ
+            ')\x81',
+            '\x85',                     # TUPLE1
+            '\x86',                     # TUPLE2
+            'N\x86',
+            '\x87',                     # TUPLE3
+            'N\x87',
+            'NN\x87',
+        ]
+        for p in badpickles:
+            self.check_unpickling_error(self.bad_stack_errors, p)
+
+    def test_bad_mark(self):
+        badpickles = [
+            # 'N(.',                      # STOP
+            'N(2',                      # DUP
+            'c__builtin__\nlist\n)(R',  # REDUCE
+            'c__builtin__\nlist\n()R',
+            ']N(a',                     # APPEND
+                                        # BUILD
+            'c__builtin__\nValueError\n)R}(b',
+            'c__builtin__\nValueError\n)R(}b',
+            '(Nd',                      # DICT
+            'N(p1\n',                   # PUT
+            'N(q\x00',                  # BINPUT
+            'N(r\x00\x00\x00\x00',      # LONG_BINPUT
+            '}NN(s',                    # SETITEM
+            '}N(Ns',
+            '}(NNs',
+            '}((u',                     # SETITEMS
+                                        # NEWOBJ
+            'c__builtin__\nlist\n)(\x81',
+            'c__builtin__\nlist\n()\x81',
+            'N(\x85',                   # TUPLE1
+            'NN(\x86',                  # TUPLE2
+            'N(N\x86',
+            'NNN(\x87',                 # TUPLE3
+            'NN(N\x87',
+            'N(NN\x87',
+        ]
+        for p in badpickles:
+            self.check_unpickling_error(self.bad_mark_errors, p)
+
+    def test_truncated_data(self):
+        self.check_unpickling_error(EOFError, '')
+        self.check_unpickling_error(EOFError, 'N')
+        badpickles = [
+            'F',                        # FLOAT
+            'F0.0',
+            'F0.00',
+            'G',                        # BINFLOAT
+            'G\x00\x00\x00\x00\x00\x00\x00',
+            'I',                        # INT
+            'I0',
+            'J',                        # BININT
+            'J\x00\x00\x00',
+            'K',                        # BININT1
+            'L',                        # LONG
+            'L0',
+            'L10',
+            'L0L',
+            'L10L',
+            'M',                        # BININT2
+            'M\x00',
+            # 'P',                        # PERSID
+            # 'Pabc',
+            'S',                        # STRING
+            "S'abc'",
+            'T',                        # BINSTRING
+            'T\x03\x00\x00',
+            'T\x03\x00\x00\x00',
+            'T\x03\x00\x00\x00ab',
+            'U',                        # SHORT_BINSTRING
+            'U\x03',
+            'U\x03ab',
+            'V',                        # UNICODE
+            'Vabc',
+            'X',                        # BINUNICODE
+            'X\x03\x00\x00',
+            'X\x03\x00\x00\x00',
+            'X\x03\x00\x00\x00ab',
+            '(c',                       # GLOBAL
+            '(c__builtin__',
+            '(c__builtin__\n',
+            '(c__builtin__\nlist',
+            'Ng',                       # GET
+            'Ng0',
+            '(i',                       # INST
+            '(i__builtin__',
+            '(i__builtin__\n',
+            '(i__builtin__\nlist',
+            'Nh',                       # BINGET
+            'Nj',                       # LONG_BINGET
+            'Nj\x00\x00\x00',
+            'Np',                       # PUT
+            'Np0',
+            'Nq',                       # BINPUT
+            'Nr',                       # LONG_BINPUT
+            'Nr\x00\x00\x00',
+            '\x80',                     # PROTO
+            '\x82',                     # EXT1
+            '\x83',                     # EXT2
+            '\x84\x01',
+            '\x84',                     # EXT4
+            '\x84\x01\x00\x00',
+            '\x8a',                     # LONG1
+            '\x8b',                     # LONG4
+            '\x8b\x00\x00\x00',
+        ]
+        for p in badpickles:
+            self.check_unpickling_error(self.truncated_errors, p)
+
 
 class AbstractPickleTests(unittest.TestCase):
     # Subclass must define self.dumps, self.loads.
@@ -765,6 +947,7 @@ class AbstractPickleTests(unittest.TestCase):
         for proto in protocols:
             s = self.dumps(i, proto)
             x = self.loads(s)
+            self.assertIsInstance(x, C)
             self.assertEqual(dir(x), dir(i))
             self.assertIs(x.attr, x)
 
@@ -777,6 +960,7 @@ class AbstractPickleTests(unittest.TestCase):
         for proto in protocols:
             s = self.dumps(l, proto)
             x = self.loads(s)
+            self.assertIsInstance(x, list)
             self.assertEqual(len(x), 1)
             self.assertEqual(dir(x[0]), dir(i))
             self.assertEqual(x[0].attr.keys(), [1])
@@ -821,7 +1005,9 @@ class AbstractPickleTests(unittest.TestCase):
     if have_unicode:
         def test_unicode(self):
             endcases = [u'', u'<\\u>', u'<\\\u1234>', u'<\n>',
-                        u'<\\>', u'<\\\U00012345>']
+                        u'<\\>', u'<\\\U00012345>',
+                        # surrogates
+                        u'<\udc80>']
             for proto in protocols:
                 for u in endcases:
                     p = self.dumps(u, proto)
@@ -900,6 +1086,7 @@ class AbstractPickleTests(unittest.TestCase):
             s = self.dumps(a, proto)
             b = self.loads(s)
             self.assertEqual(a, b)
+            self.assertIs(a.__class__, b.__class__)
 
     def test_structseq(self):
         import time
@@ -1045,6 +1232,26 @@ class AbstractPickleTests(unittest.TestCase):
                 self.assertEqual(B(x), B(y), detail)
                 self.assertEqual(x.__dict__, y.__dict__, detail)
 
+    def test_newobj_proxies(self):
+        # NEWOBJ should use the __class__ rather than the raw type
+        import weakref
+        classes = myclasses[:]
+        # Cannot create weakproxies to these classes
+        for c in (MyInt, MyLong, MyStr, MyTuple):
+            classes.remove(c)
+        for proto in protocols:
+            for C in classes:
+                B = C.__base__
+                x = C(C.sample)
+                x.foo = 42
+                p = weakref.proxy(x)
+                s = self.dumps(p, proto)
+                y = self.loads(s)
+                self.assertEqual(type(y), type(x))  # rather than type(p)
+                detail = (proto, C, B, x, y, type(y))
+                self.assertEqual(B(x), B(y), detail)
+                self.assertEqual(x.__dict__, y.__dict__, detail)
+
     # Register a type with copy_reg, with extension code extcode.  Pickle
     # an object of that type.  Check that the resulting pickle uses opcode
     # (EXT[124]) under proto 2, and not in proto 1.
@@ -1139,10 +1346,30 @@ class AbstractPickleTests(unittest.TestCase):
                 self.assertTrue(num_setitems >= 2)
 
     def test_simple_newobj(self):
-        x = object.__new__(SimpleNewObj)  # avoid __init__
+        x = SimpleNewObj.__new__(SimpleNewObj, 0xface)  # avoid __init__
+        x.abc = 666
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            if proto < 1:
+                self.assertIn('\nI64206', s)  # INT
+            else:
+                self.assertIn('M\xce\xfa', s)  # BININT2
+            self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2)
+            y = self.loads(s)   # will raise TypeError if __init__ called
+            self.assertEqual(y.abc, 666)
+            self.assertEqual(x.__dict__, y.__dict__)
+
+    def test_complex_newobj(self):
+        x = ComplexNewObj.__new__(ComplexNewObj, 0xface)  # avoid __init__
         x.abc = 666
         for proto in protocols:
             s = self.dumps(x, proto)
+            if proto < 1:
+                self.assertIn('\nI64206', s)  # INT
+            elif proto < 2:
+                self.assertIn('M\xce\xfa', s)  # BININT2
+            else:
+                self.assertIn('U\x04FACE', s)  # SHORT_BINSTRING
             self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2)
             y = self.loads(s)   # will raise TypeError if __init__ called
             self.assertEqual(y.abc, 666)
@@ -1204,6 +1431,13 @@ class AbstractPickleTests(unittest.TestCase):
             y = self.loads(s)
             self.assertEqual(y._reduce_called, 1)
 
+    @no_tracing
+    def test_bad_getattr(self):
+        # Issue #3514: crash when there is an infinite loop in __getattr__
+        x = BadGetattr()
+        for proto in protocols:
+            self.assertRaises(RuntimeError, self.dumps, x, proto)
+
     def test_reduce_bad_iterator(self):
         # Issue4176: crash when 4th and 5th items of __reduce__()
         # are not iterators
@@ -1216,15 +1450,16 @@ class AbstractPickleTests(unittest.TestCase):
                 # 5th item is not an iterator
                 return dict, (), None, None, []
 
-        # Protocol 0 is less strict and also accept iterables.
+        # Protocol 0 in Python implementation is less strict and also accepts
+        # iterables.
         for proto in protocols:
             try:
                 self.dumps(C(), proto)
-            except (AttributeError, pickle.PickleError, cPickle.PickleError):
+            except (AttributeError, pickle.PicklingError, cPickle.PicklingError):
                 pass
             try:
                 self.dumps(D(), proto)
-            except (AttributeError, pickle.PickleError, cPickle.PickleError):
+            except (AttributeError, pickle.PicklingError, cPickle.PicklingError):
                 pass
 
     def test_many_puts_and_gets(self):
@@ -1255,6 +1490,39 @@ class AbstractPickleTests(unittest.TestCase):
             for x_key, y_key in zip(x_keys, y_keys):
                 self.assertIs(x_key, y_key)
 
+    def test_large_pickles(self):
+        # Test the correctness of internal buffering routines when handling
+        # large data.
+        for proto in protocols:
+            data = (1, min, 'xy' * (30 * 1024), len)
+            dumped = self.dumps(data, proto)
+            loaded = self.loads(dumped)
+            self.assertEqual(len(loaded), len(data))
+            self.assertEqual(loaded, data)
+
+    def _check_pickling_with_opcode(self, obj, opcode, proto):
+        pickled = self.dumps(obj, proto)
+        self.assertTrue(opcode_in_pickle(opcode, pickled))
+        unpickled = self.loads(pickled)
+        self.assertEqual(obj, unpickled)
+
+    def test_appends_on_non_lists(self):
+        # Issue #17720
+        obj = REX_six([1, 2, 3])
+        for proto in protocols:
+            if proto == 0:
+                self._check_pickling_with_opcode(obj, pickle.APPEND, proto)
+            else:
+                self._check_pickling_with_opcode(obj, pickle.APPENDS, proto)
+
+    def test_setitems_on_non_dicts(self):
+        obj = REX_seven({1: -1, 2: -2, 3: -3})
+        for proto in protocols:
+            if proto == 0:
+                self._check_pickling_with_opcode(obj, pickle.SETITEM, proto)
+            else:
+                self._check_pickling_with_opcode(obj, pickle.SETITEMS, proto)
+
 
 # Test classes for reduce_ex
 
@@ -1294,6 +1562,39 @@ class REX_five(object):
         return object.__reduce__(self)
     # This one used to fail with infinite recursion
 
+class REX_six(object):
+    """This class is used to check the 4th argument (list iterator) of
+    the reduce protocol.
+    """
+    def __init__(self, items=None):
+        if items is None:
+            items = []
+        self.items = items
+    def __eq__(self, other):
+        return type(self) is type(other) and self.items == other.items
+    def append(self, item):
+        self.items.append(item)
+    def extend(self, items):
+        for item in items:
+            self.append(item)
+    def __reduce__(self):
+        return type(self), (), None, iter(self.items), None
+
+class REX_seven(object):
+    """This class is used to check the 5th argument (dict iterator) of
+    the reduce protocol.
+    """
+    def __init__(self, table=None):
+        if table is None:
+            table = {}
+        self.table = table
+    def __eq__(self, other):
+        return type(self) is type(other) and self.table == other.table
+    def __setitem__(self, key, value):
+        self.table[key] = value
+    def __reduce__(self):
+        return type(self), (), None, None, iter(self.table.items())
+
 # Test classes for newobj
 
 class MyInt(int):
@@ -1332,10 +1633,20 @@ myclasses = [MyInt, MyLong, MyFloat,
 class SlotList(MyList):
     __slots__ = ["foo"]
 
-class SimpleNewObj(object):
-    def __init__(self, a, b, c):
+class SimpleNewObj(int):
+    def __init__(self, *args, **kwargs):
         # raise an error, to make sure this isn't called
         raise TypeError("SimpleNewObj.__init__() didn't expect to get called")
+    def __eq__(self, other):
+        return int(self) == int(other) and self.__dict__ == other.__dict__
+
+class ComplexNewObj(SimpleNewObj):
+    def __getnewargs__(self):
+        return ('%X' % self, 16)
+
+class BadGetattr:
+    def __getattr__(self, key):
+        self.foo
 
 class AbstractPickleModuleTests(unittest.TestCase):
 
@@ -1396,11 +1707,7 @@ class AbstractPickleModuleTests(unittest.TestCase):
         # Test issue4298
         s = '\x58\0\0\0\x54'
         self.assertRaises(EOFError, self.module.loads, s)
-        # Test issue7455
-        s = '0'
-        # XXX Why doesn't pickle raise UnpicklingError?
-        self.assertRaises((IndexError, cPickle.UnpicklingError),
-                          self.module.loads, s)
+
 
 class AbstractPersistentPicklerTests(unittest.TestCase):
 
@@ -1554,6 +1861,46 @@ class AbstractPicklerUnpicklerObjectTests(unittest.TestCase):
         f.seek(0)
         self.assertEqual(unpickler.load(), data2)
 
+    def _check_multiple_unpicklings(self, ioclass, seekable):
+        for proto in protocols:
+            data1 = [(x, str(x)) for x in xrange(2000)] + ["abcde", len]
+            f = ioclass()
+            pickler = self.pickler_class(f, protocol=proto)
+            pickler.dump(data1)
+            pickled = f.getvalue()
+
+            N = 5
+            f = ioclass(pickled * N)
+            unpickler = self.unpickler_class(f)
+            for i in xrange(N):
+                if seekable:
+                    pos = f.tell()
+                self.assertEqual(unpickler.load(), data1)
+                if seekable:
+                    self.assertEqual(f.tell(), pos + len(pickled))
+            self.assertRaises(EOFError, unpickler.load)
+
+    def test_multiple_unpicklings_seekable(self):
+        self._check_multiple_unpicklings(StringIO.StringIO, True)
+
+    def test_multiple_unpicklings_unseekable(self):
+        self._check_multiple_unpicklings(UnseekableIO, False)
+
+    def test_unpickling_buffering_readline(self):
+        # Issue #12687: the unpickler's buffering logic could fail with
+        # text mode opcodes.
+        import io
+        data = list(xrange(10))
+        for proto in protocols:
+            for buf_size in xrange(1, 11):
+                f = io.BufferedRandom(io.BytesIO(), buffer_size=buf_size)
+                pickler = self.pickler_class(f, protocol=proto)
+                pickler.dump(data)
+                f.seek(0)
+                unpickler = self.unpickler_class(f)
+                self.assertEqual(unpickler.load(), data)
+
+
 class BigmemPickleTests(unittest.TestCase):
 
     # Memory requirements: 1 byte per character for input strings, 1 byte
index 0007da6..b6883b5 100755 (executable)
@@ -462,7 +462,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False,
 
     test_times = []
     test_support.use_resources = use_resources
-    save_modules = sys.modules.keys()
+    save_modules = set(sys.modules)
 
     def accumulate_result(test, result):
         ok, test_time = result
index 7f7c70e..6be47bd 100644 (file)
@@ -134,9 +134,9 @@ def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None):
     #    zip_file.close()
     return zip_name, os.path.join(zip_name, name_in_zip)
 
-def make_pkg(pkg_dir):
+def make_pkg(pkg_dir, init_source=''):
     os.mkdir(pkg_dir)
-    make_script(pkg_dir, '__init__', '')
+    make_script(pkg_dir, '__init__', init_source)
 
 def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
                  source, depth=1, compiled=False):
index 9a80073..b6d259b 100644 (file)
@@ -1,5 +1,5 @@
 -----BEGIN CERTIFICATE-----
-MIIChzCCAfCgAwIBAgIJAKGU95wKR8pSMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV
+MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV
 BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u
 IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv
 bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG
@@ -8,9 +8,9 @@ b24gU29mdHdhcmUgRm91bmRhdGlvbjEjMCEGA1UEAwwac2VsZi1zaWduZWQucHl0
 aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ
 Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm
 Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv
-EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjKTAnMCUGA1UdEQQeMByCGnNl
-bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MA0GCSqGSIb3DQEBBQUAA4GBAIOXmdtM
-eG9qzP9TiXW/Gc/zI4cBfdCpC+Y4gOfC9bQUC7hefix4iO3+iZjgy3X/FaRxUUoV
-HKiXcXIaWqTSUWp45cSh0MbwZXudp6JIAptzdAhvvCrPKeC9i9GvxsPD4LtDAL97
-vSaxQBezA7hdxZd90/EeyMgVZgAnTCnvAWX9
+EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl
+bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN
+AQEFBQADgYEAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h
+TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515
+C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM=
 -----END CERTIFICATE-----
index f4673d4..f019e8d 100644 (file)
@@ -4,6 +4,7 @@ Tests common to tuple, list and UserList.UserList
 
 import unittest
 import sys
+from test import test_support as support
 
 # Various iterables
 # This is used for checking the constructor (here and in test_deque.py)
@@ -402,3 +403,7 @@ class CommonTest(unittest.TestCase):
         self.assertEqual(a.index(0, -4*sys.maxint, 4*sys.maxint), 2)
         self.assertRaises(ValueError, a.index, 0, 4*sys.maxint,-4*sys.maxint)
         self.assertRaises(ValueError, a.index, 2, 0, -10)
+
+    def test_free_after_iterating(self):
+        support.check_free_after_iterating(self, iter, self.type2test)
+        support.check_free_after_iterating(self, reversed, self.type2test)
index b2f837b..a4b38a1 100644 (file)
@@ -45,6 +45,9 @@ class CommonTest(unittest.TestCase):
         else:
             return obj
 
+    def test_fixtype(self):
+        self.assertIs(type(self.fixtype("123")), self.type2test)
+
     # check that object.method(*args) returns result
     def checkequal(self, result, object, methodname, *args):
         result = self.fixtype(result)
@@ -346,14 +349,22 @@ class CommonTest(unittest.TestCase):
         self.checkequal(['a'], '  a    ', 'split')
         self.checkequal(['a', 'b'], '  a    b   ', 'split')
         self.checkequal(['a', 'b   '], '  a    b   ', 'split', None, 1)
+        self.checkequal(['a    b   c   '], '  a    b   c   ', 'split', None, 0)
         self.checkequal(['a', 'b   c   '], '  a    b   c   ', 'split', None, 1)
         self.checkequal(['a', 'b', 'c   '], '  a    b   c   ', 'split', None, 2)
+        self.checkequal(['a', 'b', 'c'], '  a    b   c   ', 'split', None, 3)
         self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
         aaa = ' a '*20
         self.checkequal(['a']*20, aaa, 'split')
         self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
         self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
 
+        for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
+                  'arf\fbarf', 'arf\vbarf'):
+            self.checkequal(['arf', 'barf'], b, 'split')
+            self.checkequal(['arf', 'barf'], b, 'split', None)
+            self.checkequal(['arf', 'barf'], b, 'split', None, 2)
+
         # by a char
         self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
         self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
@@ -365,6 +376,8 @@ class CommonTest(unittest.TestCase):
                         sys.maxint-2)
         self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
         self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
+        self.checkequal(['abcd'], 'abcd', 'split', '|')
+        self.checkequal([''], '', 'split', '|')
         self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
         self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
         self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
@@ -404,7 +417,9 @@ class CommonTest(unittest.TestCase):
                         'split', 'BLAH', 18)
 
         # mixed use of str and unicode
-        self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
+        if self.type2test is not bytearray:
+            result = [u'a', u'b', u'c d']
+            self.checkequal(result, 'a b c d', 'split', u' ', 2)
 
         # argument type
         self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
@@ -433,16 +448,25 @@ class CommonTest(unittest.TestCase):
         self.checkequal(['a'], '  a    ', 'rsplit')
         self.checkequal(['a', 'b'], '  a    b   ', 'rsplit')
         self.checkequal(['  a', 'b'], '  a    b   ', 'rsplit', None, 1)
+        self.checkequal(['  a    b   c'], '  a    b   c   ', 'rsplit',
+                        None, 0)
         self.checkequal(['  a    b','c'], '  a    b   c   ', 'rsplit',
                         None, 1)
         self.checkequal(['  a', 'b', 'c'], '  a    b   c   ', 'rsplit',
                         None, 2)
+        self.checkequal(['a', 'b', 'c'], '  a    b   c   ', 'rsplit',
+                        None, 3)
         self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
         aaa = ' a '*20
         self.checkequal(['a']*20, aaa, 'rsplit')
         self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
         self.checkequal([' a  a'] + ['a']*18, aaa, 'rsplit', None, 18)
 
+        for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
+                  'arf\fbarf', 'arf\vbarf'):
+            self.checkequal(['arf', 'barf'], b, 'rsplit')
+            self.checkequal(['arf', 'barf'], b, 'rsplit', None)
+            self.checkequal(['arf', 'barf'], b, 'rsplit', None, 2)
 
         # by a char
         self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
@@ -454,6 +478,8 @@ class CommonTest(unittest.TestCase):
                         sys.maxint-100)
         self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
         self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
+        self.checkequal(['abcd'], 'abcd', 'rsplit', '|')
+        self.checkequal([''], '', 'rsplit', '|')
         self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
         self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
         self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
@@ -494,7 +520,9 @@ class CommonTest(unittest.TestCase):
                         'rsplit', 'BLAH', 18)
 
         # mixed use of str and unicode
-        self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
+        if self.type2test is not bytearray:
+            result = [u'a b', u'c', u'd']
+            self.checkequal(result, 'a b c d', 'rsplit', u' ', 2)
 
         # argument type
         self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
@@ -503,26 +531,36 @@ class CommonTest(unittest.TestCase):
         self.checkraises(ValueError, 'hello', 'rsplit', '')
         self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
 
-    def test_strip(self):
+    def test_strip_whitespace(self):
         self.checkequal('hello', '   hello   ', 'strip')
         self.checkequal('hello   ', '   hello   ', 'lstrip')
         self.checkequal('   hello', '   hello   ', 'rstrip')
         self.checkequal('hello', 'hello', 'strip')
 
+        b = ' \t\n\r\f\vabc \t\n\r\f\v'
+        self.checkequal('abc', b, 'strip')
+        self.checkequal('abc \t\n\r\f\v', b, 'lstrip')
+        self.checkequal(' \t\n\r\f\vabc', b, 'rstrip')
+
         # strip/lstrip/rstrip with None arg
         self.checkequal('hello', '   hello   ', 'strip', None)
         self.checkequal('hello   ', '   hello   ', 'lstrip', None)
         self.checkequal('   hello', '   hello   ', 'rstrip', None)
         self.checkequal('hello', 'hello', 'strip', None)
 
+    def test_strip(self):
         # strip/lstrip/rstrip with str arg
         self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
         self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
         self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
         self.checkequal('hello', 'hello', 'strip', 'xyz')
+        self.checkequal('', 'mississippi', 'strip', 'mississippi')
+
+        # only trims the start and end, does not strip internal characters
+        self.checkequal('mississipp', 'mississippi', 'strip', 'i')
 
         # strip/lstrip/rstrip with unicode arg
-        if test_support.have_unicode:
+        if self.type2test is not bytearray and test_support.have_unicode:
             self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
                  'strip', unicode('xyz', 'ascii'))
             self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
@@ -542,7 +580,11 @@ class CommonTest(unittest.TestCase):
         self.checkequal('abc   ', 'abc', 'ljust', 6)
         self.checkequal('abc', 'abc', 'ljust', 3)
         self.checkequal('abc', 'abc', 'ljust', 2)
-        self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
+        if self.type2test is bytearray:
+            # Special case because bytearray argument is not accepted
+            self.assertEqual(b'abc*******', bytearray(b'abc').ljust(10, '*'))
+        else:
+            self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
         self.checkraises(TypeError, 'abc', 'ljust')
 
     def test_rjust(self):
@@ -550,7 +592,11 @@ class CommonTest(unittest.TestCase):
         self.checkequal('   abc', 'abc', 'rjust', 6)
         self.checkequal('abc', 'abc', 'rjust', 3)
         self.checkequal('abc', 'abc', 'rjust', 2)
-        self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
+        if self.type2test is bytearray:
+            # Special case because bytearray argument is not accepted
+            self.assertEqual(b'*******abc', bytearray(b'abc').rjust(10, '*'))
+        else:
+            self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
         self.checkraises(TypeError, 'abc', 'rjust')
 
     def test_center(self):
@@ -558,7 +604,12 @@ class CommonTest(unittest.TestCase):
         self.checkequal(' abc  ', 'abc', 'center', 6)
         self.checkequal('abc', 'abc', 'center', 3)
         self.checkequal('abc', 'abc', 'center', 2)
-        self.checkequal('***abc****', 'abc', 'center', 10, '*')
+        if self.type2test is bytearray:
+            # Special case because bytearray argument is not accepted
+            result = bytearray(b'abc').center(10, '*')
+            self.assertEqual(b'***abc****', result)
+        else:
+            self.checkequal('***abc****', 'abc', 'center', 10, '*')
         self.checkraises(TypeError, 'abc', 'center')
 
     def test_swapcase(self):
@@ -772,13 +823,10 @@ class CommonTest(unittest.TestCase):
 
         self.checkraises(TypeError, '123', 'zfill')
 
-# XXX alias for py3k forward compatibility
-BaseTest = CommonTest
 
-class MixinStrUnicodeUserStringTest:
-    # additional tests that only work for
-    # stringlike objects, i.e. str, unicode, UserString
-    # (but not the string module)
+class NonStringModuleTest:
+    # additional test cases for all string classes from bytearray to
+    # UserString, but not valid for the "string" module
 
     def test_islower(self):
         self.checkequal(False, '', 'islower')
@@ -875,6 +923,12 @@ class MixinStrUnicodeUserStringTest:
 
         self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
 
+
+class MixinStrUnicodeUserStringTest(NonStringModuleTest):
+    # additional tests that only work for
+    # stringlike objects, i.e. str, unicode, UserString
+    # (but not the string module)
+
     def test_startswith(self):
         self.checkequal(True, 'hello', 'startswith', 'he')
         self.checkequal(True, 'hello', 'startswith', 'hello')
index 9b5914e..576642d 100644 (file)
@@ -39,7 +39,9 @@ if "MSC v.1200" in sys.version:
 known_numerics = {
     'en_US': ('.', ','),
     'de_DE' : (',', '.'),
-    'fr_FR.UTF-8' : (',', ' '),
+    # The French thousands separator may be a breaking or non-breaking space
+    # depending on the platform, so do not test it
+    'fr_FR' : (',', ''),
     'ps_AF.UTF-8' : ('\xd9\xab', '\xd9\xac'),
 }
 
index 915e989..83f6f27 100644 (file)
@@ -548,7 +548,7 @@ class TestOptionalsNargsDefault(ParserTestCase):
 
 
 class TestOptionalsNargs1(ParserTestCase):
-    """Tests specifying the 1 arg for an Optional"""
+    """Tests specifying 1 arg for an Optional"""
 
     argument_signatures = [Sig('-x', nargs=1)]
     failures = ['a', '-x']
@@ -559,7 +559,7 @@ class TestOptionalsNargs1(ParserTestCase):
 
 
 class TestOptionalsNargs3(ParserTestCase):
-    """Tests specifying the 3 args for an Optional"""
+    """Tests specifying 3 args for an Optional"""
 
     argument_signatures = [Sig('-x', nargs=3)]
     failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b']
@@ -593,7 +593,7 @@ class TestOptionalsNargsOptional(ParserTestCase):
 
 
 class TestOptionalsNargsZeroOrMore(ParserTestCase):
-    """Tests specifying an args for an Optional that accepts zero or more"""
+    """Tests specifying args for an Optional that accepts zero or more"""
 
     argument_signatures = [
         Sig('-x', nargs='*'),
@@ -612,7 +612,7 @@ class TestOptionalsNargsZeroOrMore(ParserTestCase):
 
 
 class TestOptionalsNargsOneOrMore(ParserTestCase):
-    """Tests specifying an args for an Optional that accepts one or more"""
+    """Tests specifying args for an Optional that accepts one or more"""
 
     argument_signatures = [
         Sig('-x', nargs='+'),
@@ -1232,7 +1232,7 @@ class TestPrefixCharacterOnlyArguments(ParserTestCase):
 
 
 class TestNargsZeroOrMore(ParserTestCase):
-    """Tests specifying an args for an Optional that accepts zero or more"""
+    """Tests specifying args for an Optional that accepts zero or more"""
 
     argument_signatures = [Sig('-x', nargs='*'), Sig('y', nargs='*')]
     failures = []
index 3f2cee4..6e67dc0 100644 (file)
@@ -137,9 +137,30 @@ class BaseXYTestCase(unittest.TestCase):
         # Non-bytes
         eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\xd3V\xbeo\xf7\x1d')
 
-    def test_b64decode_error(self):
+    def test_b64decode_padding_error(self):
         self.assertRaises(TypeError, base64.b64decode, 'abc')
 
+    def test_b64decode_invalid_chars(self):
+        # issue 1466065: Test some invalid characters.
+        tests = ((b'%3d==', b'\xdd'),
+                 (b'$3d==', b'\xdd'),
+                 (b'[==', b''),
+                 (b'YW]3=', b'am'),
+                 (b'3{d==', b'\xdd'),
+                 (b'3d}==', b'\xdd'),
+                 (b'@@', b''),
+                 (b'!', b''),
+                 (b'YWJj\nYWI=', b'abcab'))
+        for bstr, res in tests:
+            self.assertEqual(base64.b64decode(bstr), res)
+            self.assertEqual(base64.standard_b64decode(bstr), res)
+            self.assertEqual(base64.urlsafe_b64decode(bstr), res)
+
+        # Normal alphabet characters not discarded when alternative given
+        res = b'\xFB\xEF\xBE\xFF\xFF\xFF'
+        self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res)
+        self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res)
+
     def test_b32encode(self):
         eq = self.assertEqual
         eq(base64.b32encode(''), '')
@@ -206,6 +227,10 @@ class BaseXYTestCase(unittest.TestCase):
         eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef')
         # Non-bytes
         eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef')
+        # Non-alphabet characters
+        self.assertRaises(TypeError, base64.b16decode, '0102AG')
+        # Incorrect "padding"
+        self.assertRaises(TypeError, base64.b16decode, '010')
 
 
 \f
index b1ef626..c7949fd 100644 (file)
@@ -56,7 +56,7 @@ class Rat(object):
     den = property(_get_den, None)
 
     def __repr__(self):
-        """Convert a Rat to an string resembling a Rat constructor call."""
+        """Convert a Rat to a string resembling a Rat constructor call."""
         return "Rat(%d, %d)" % (self.__num, self.__den)
 
     def __str__(self):
@@ -78,7 +78,7 @@ class Rat(object):
         raise ValueError, "can't convert %s to int" % repr(self)
 
     def __long__(self):
-        """Convert a Rat to an long; self.den must be 1."""
+        """Convert a Rat to a long; self.den must be 1."""
         if self.__den == 1:
             return long(self.__num)
         raise ValueError, "can't convert %s to long" % repr(self)
index a02c5f7..de80d44 100644 (file)
@@ -4,6 +4,8 @@ For now, tests just new or changed functionality.
 
 """
 
+import copy
+import pickle
 import sys
 import unittest
 from test import test_support
@@ -35,6 +37,18 @@ class BufferTests(unittest.TestCase):
         buf = buffer(data, sys.maxsize, sys.maxsize)
         self.assertEqual(buf[:4096], "")
 
+    def test_copy(self):
+        buf = buffer(b'abc')
+        with self.assertRaises(TypeError):
+            copy.copy(buf)
+
+    # See issue #22995
+    ## def test_pickle(self):
+    ##     buf = buffer(b'abc')
+    ##     for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+    ##         with self.assertRaises(TypeError):
+    ##             pickle.dumps(buf, proto)
+
 
 def test_main():
     with test_support.check_py3k_warnings(("buffer.. not supported",
index 15581d9..c9347e9 100644 (file)
@@ -1682,6 +1682,134 @@ class TestSorted(unittest.TestCase):
         data = 'The quick Brown fox Jumped over The lazy Dog'.split()
         self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
 
+
+class TestType(unittest.TestCase):
+    def test_new_type(self):
+        A = type('A', (), {})
+        self.assertEqual(A.__name__, 'A')
+        self.assertEqual(A.__module__, __name__)
+        self.assertEqual(A.__bases__, (object,))
+        self.assertIs(A.__base__, object)
+        x = A()
+        self.assertIs(type(x), A)
+        self.assertIs(x.__class__, A)
+
+        class B:
+            def ham(self):
+                return 'ham%d' % self
+        C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self})
+        self.assertEqual(C.__name__, 'C')
+        self.assertEqual(C.__module__, __name__)
+        self.assertEqual(C.__bases__, (B, int))
+        self.assertIs(C.__base__, int)
+        self.assertIn('spam', C.__dict__)
+        self.assertNotIn('ham', C.__dict__)
+        x = C(42)
+        self.assertEqual(x, 42)
+        self.assertIs(type(x), C)
+        self.assertIs(x.__class__, C)
+        self.assertEqual(x.ham(), 'ham42')
+        self.assertEqual(x.spam(), 'spam42')
+        self.assertEqual(x.bit_length(), 6)
+
+    def test_type_new_keywords(self):
+        class B:
+            def ham(self):
+                return 'ham%d' % self
+        C = type.__new__(type,
+                         name='C',
+                         bases=(B, int),
+                         dict={'spam': lambda self: 'spam%s' % self})
+        self.assertEqual(C.__name__, 'C')
+        self.assertEqual(C.__module__, __name__)
+        self.assertEqual(C.__bases__, (B, int))
+        self.assertIs(C.__base__, int)
+        self.assertIn('spam', C.__dict__)
+        self.assertNotIn('ham', C.__dict__)
+
+    def test_type_name(self):
+        for name in 'A', '\xc4', 'B.A', '42', '':
+            A = type(name, (), {})
+            self.assertEqual(A.__name__, name)
+            self.assertEqual(A.__module__, __name__)
+        with self.assertRaises(ValueError):
+            type('A\x00B', (), {})
+        with self.assertRaises(TypeError):
+            type(u'A', (), {})
+
+        C = type('C', (), {})
+        for name in 'A', '\xc4', 'B.A', '42', '':
+            C.__name__ = name
+            self.assertEqual(C.__name__, name)
+            self.assertEqual(C.__module__, __name__)
+
+        A = type('C', (), {})
+        with self.assertRaises(ValueError):
+            A.__name__ = 'A\x00B'
+        self.assertEqual(A.__name__, 'C')
+        with self.assertRaises(TypeError):
+            A.__name__ = u'A'
+        self.assertEqual(A.__name__, 'C')
+
+    def test_type_doc(self):
+        tests = ('x', '\xc4', 'x\x00y', 42, None)
+        if have_unicode:
+            tests += (u'\xc4', u'x\x00y')
+        for doc in tests:
+            A = type('A', (), {'__doc__': doc})
+            self.assertEqual(A.__doc__, doc)
+
+        A = type('A', (), {})
+        self.assertEqual(A.__doc__, None)
+        with self.assertRaises(AttributeError):
+            A.__doc__ = 'x'
+
+    def test_bad_args(self):
+        with self.assertRaises(TypeError):
+            type()
+        with self.assertRaises(TypeError):
+            type('A', ())
+        with self.assertRaises(TypeError):
+            type('A', (), {}, ())
+        with self.assertRaises(TypeError):
+            type('A', (), dict={})
+        with self.assertRaises(TypeError):
+            type('A', [], {})
+        with self.assertRaises(TypeError):
+            type('A', (), UserDict.UserDict())
+        with self.assertRaises(TypeError):
+            type('A', (None,), {})
+        with self.assertRaises(TypeError):
+            type('A', (bool,), {})
+        with self.assertRaises(TypeError):
+            type('A', (int, str), {})
+        class B:
+            pass
+        with self.assertRaises(TypeError):
+            type('A', (B,), {})
+
+    def test_bad_slots(self):
+        with self.assertRaises(TypeError):
+            type('A', (long,), {'__slots__': 'x'})
+        with self.assertRaises(TypeError):
+            type('A', (), {'__slots__': ''})
+        with self.assertRaises(TypeError):
+            type('A', (), {'__slots__': '42'})
+        with self.assertRaises(TypeError):
+            type('A', (), {'__slots__': 'x\x00y'})
+        with self.assertRaises(TypeError):
+            type('A', (), {'__slots__': ('__dict__', '__dict__')})
+        with self.assertRaises(TypeError):
+            type('A', (), {'__slots__': ('__weakref__', '__weakref__')})
+
+        class B(object):
+            pass
+        with self.assertRaises(TypeError):
+            type('A', (B,), {'__slots__': '__dict__'})
+        with self.assertRaises(TypeError):
+            type('A', (B,), {'__slots__': '__weakref__'})
+
+
 def _run_unittest(*args):
     with check_py3k_warnings(
             (".+ not supported in 3.x", DeprecationWarning),
@@ -1696,7 +1824,7 @@ def test_main(verbose=None):
                 (".+ not supported in 3.x", DeprecationWarning)):
             run_unittest(TestExecFile)
     numruns += 1
-    test_classes = (BuiltinTest, TestSorted)
+    test_classes = (BuiltinTest, TestSorted, TestType)
 
     _run_unittest(*test_classes)
 
index 02fba38..4a70b33 100644 (file)
@@ -1,8 +1,7 @@
 """Unit tests for the bytes and bytearray types.
 
-XXX This is a mess.  Common tests should be moved to buffer_tests.py,
-which itself ought to be unified with string_tests.py (and the latter
-should be modernized).
+XXX This is a mess.  Common tests should be unified with string_tests.py (and
+the latter should be modernized).
 """
 
 import os
@@ -15,7 +14,6 @@ import tempfile
 import unittest
 import test.test_support
 import test.string_tests
-import test.buffer_tests
 
 
 if sys.flags.bytes_warning:
@@ -338,52 +336,16 @@ class BaseBytesTest(unittest.TestCase):
         self.assertEqual(b.replace(b'i', b'a'), b'massassappa')
         self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi')
 
-    def test_split(self):
-        b = self.type2test(b'mississippi')
-        self.assertEqual(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
-        self.assertEqual(b.split(b'ss'), [b'mi', b'i', b'ippi'])
-        self.assertEqual(b.split(b'w'), [b])
-
-    def test_split_whitespace(self):
-        for b in (b'  arf  barf  ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
-                  b'arf\fbarf', b'arf\vbarf'):
-            b = self.type2test(b)
-            self.assertEqual(b.split(), [b'arf', b'barf'])
-            self.assertEqual(b.split(None), [b'arf', b'barf'])
-            self.assertEqual(b.split(None, 2), [b'arf', b'barf'])
-        for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'):
-            b = self.type2test(b)
-            self.assertEqual(b.split(), [b])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').split(None, 0), [b'a  bb  c  '])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').split(None, 1), [b'a', b'bb  c  '])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').split(None, 2), [b'a', b'bb', b'c  '])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').split(None, 3), [b'a', b'bb', b'c'])
-
     def test_split_string_error(self):
         self.assertRaises(TypeError, self.type2test(b'a b').split, u' ')
 
     def test_split_unicodewhitespace(self):
+        for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'):
+            b = self.type2test(b)
+            self.assertEqual(b.split(), [b])
         b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
         self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f'])
 
-    def test_rsplit(self):
-        b = self.type2test(b'mississippi')
-        self.assertEqual(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
-        self.assertEqual(b.rsplit(b'ss'), [b'mi', b'i', b'ippi'])
-        self.assertEqual(b.rsplit(b'w'), [b])
-
-    def test_rsplit_whitespace(self):
-        for b in (b'  arf  barf  ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
-                  b'arf\fbarf', b'arf\vbarf'):
-            b = self.type2test(b)
-            self.assertEqual(b.rsplit(), [b'arf', b'barf'])
-            self.assertEqual(b.rsplit(None), [b'arf', b'barf'])
-            self.assertEqual(b.rsplit(None, 2), [b'arf', b'barf'])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').rsplit(None, 0), [b'  a  bb  c'])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').rsplit(None, 1), [b'  a  bb', b'c'])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').rsplit(None, 2), [b'  a', b'bb', b'c'])
-        self.assertEqual(self.type2test(b'  a  bb  c  ').rsplit(None, 3), [b'a', b'bb', b'c'])
-
     def test_rsplit_string_error(self):
         self.assertRaises(TypeError, self.type2test(b'a b').rsplit, u' ')
 
@@ -410,37 +372,6 @@ class BaseBytesTest(unittest.TestCase):
                 q = pickle.loads(ps)
                 self.assertEqual(b, q)
 
-    def test_strip(self):
-        b = self.type2test(b'mississippi')
-        self.assertEqual(b.strip(b'i'), b'mississipp')
-        self.assertEqual(b.strip(b'm'), b'ississippi')
-        self.assertEqual(b.strip(b'pi'), b'mississ')
-        self.assertEqual(b.strip(b'im'), b'ssissipp')
-        self.assertEqual(b.strip(b'pim'), b'ssiss')
-        self.assertEqual(b.strip(b), b'')
-
-    def test_lstrip(self):
-        b = self.type2test(b'mississippi')
-        self.assertEqual(b.lstrip(b'i'), b'mississippi')
-        self.assertEqual(b.lstrip(b'm'), b'ississippi')
-        self.assertEqual(b.lstrip(b'pi'), b'mississippi')
-        self.assertEqual(b.lstrip(b'im'), b'ssissippi')
-        self.assertEqual(b.lstrip(b'pim'), b'ssissippi')
-
-    def test_rstrip(self):
-        b = self.type2test(b'mississippi')
-        self.assertEqual(b.rstrip(b'i'), b'mississipp')
-        self.assertEqual(b.rstrip(b'm'), b'mississippi')
-        self.assertEqual(b.rstrip(b'pi'), b'mississ')
-        self.assertEqual(b.rstrip(b'im'), b'mississipp')
-        self.assertEqual(b.rstrip(b'pim'), b'mississ')
-
-    def test_strip_whitespace(self):
-        b = self.type2test(b' \t\n\r\f\vabc \t\n\r\f\v')
-        self.assertEqual(b.strip(), b'abc')
-        self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v')
-        self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc')
-
     def test_strip_bytearray(self):
         self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b')
         self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc')
@@ -518,6 +449,10 @@ class BaseBytesTest(unittest.TestCase):
         self.assertRaisesRegexp(TypeError, r'\bendswith\b', b.endswith,
                                 x, None, None, None)
 
+    def test_free_after_iterating(self):
+        test.test_support.check_free_after_iterating(self, iter, self.type2test)
+        test.test_support.check_free_after_iterating(self, reversed, self.type2test)
+
 
 class ByteArrayTest(BaseBytesTest):
     type2test = bytearray
@@ -788,6 +723,13 @@ class ByteArrayTest(BaseBytesTest):
         b.remove(Indexable(ord('e')))
         self.assertEqual(b, b'')
 
+        # test values outside of the ascii range: (0, 127)
+        c = bytearray([126, 127, 128, 129])
+        c.remove(127)
+        self.assertEqual(c, bytearray([126, 128, 129]))
+        c.remove(129)
+        self.assertEqual(c, bytearray([126, 128]))
+
     def test_pop(self):
         b = bytearray(b'world')
         self.assertEqual(b.pop(), ord('d'))
@@ -896,6 +838,16 @@ class ByteArrayTest(BaseBytesTest):
         # PyByteArray_AS_STRING() C macro.
         self.assertRaises(ValueError, int, bytearray(b''))
 
+    def test_exhausted_iterator(self):
+        a = self.type2test([1, 2, 3])
+        exhit = iter(a)
+        empit = iter(a)
+        for x in exhit:  # exhaust the iterator
+            next(empit)  # not exhausted
+        a.append(9)
+        self.assertEqual(list(exhit), [])
+        self.assertEqual(list(empit), [9])
+        self.assertEqual(a, self.type2test([1, 2, 3, 9]))
 
 class AssortedBytesTest(unittest.TestCase):
     #
@@ -1008,7 +960,7 @@ class AssortedBytesTest(unittest.TestCase):
     # XXX More string methods?  (Those that don't use character properties)
 
     # There are tests in string_tests.py that are more
-    # comprehensive for things like split, partition, etc.
+    # comprehensive for things like partition, etc.
     # Unfortunately they are all bundled with tests that
     # are not appropriate for bytes
 
@@ -1016,8 +968,7 @@ class AssortedBytesTest(unittest.TestCase):
     # the rest that make sense (the code can be cleaned up to use modern
     # unittest methods at the same time).
 
-class BytearrayPEP3137Test(unittest.TestCase,
-                       test.buffer_tests.MixinBytesBufferCommonTests):
+class BytearrayPEP3137Test(unittest.TestCase):
     def marshal(self, x):
         return bytearray(x)
 
@@ -1039,12 +990,10 @@ class BytearrayPEP3137Test(unittest.TestCase,
             self.assertTrue(val is not newval,
                             expr+' returned val on a mutable object')
 
-class FixedStringTest(test.string_tests.BaseTest):
 
-    def fixtype(self, obj):
-        if isinstance(obj, str):
-            return obj.encode("utf-8")
-        return super(FixedStringTest, self).fixtype(obj)
+class ByteArrayAsStringTest(test.string_tests.CommonTest,
+        test.string_tests.NonStringModuleTest):
+    type2test = bytearray
 
     # Currently the bytes containment testing uses a single integer
     # value. This may not be the final design, but until then the
@@ -1062,10 +1011,6 @@ class FixedStringTest(test.string_tests.BaseTest):
         pass
 
 
-class ByteArrayAsStringTest(FixedStringTest):
-    type2test = bytearray
-
-
 class ByteArraySubclass(bytearray):
     pass
 
@@ -1146,7 +1091,6 @@ class ByteArraySubclassTest(unittest.TestCase):
 def test_main():
     #test.test_support.run_unittest(BytesTest)
     #test.test_support.run_unittest(AssortedBytesTest)
-    #test.test_support.run_unittest(BytesAsStringTest)
     test.test_support.run_unittest(
         ByteArrayTest,
         ByteArrayAsStringTest,
index 2029265..944e960 100644 (file)
@@ -16,6 +16,11 @@ except ImportError:
 # Skip this test if the _testcapi module isn't available.
 _testcapi = support.import_module('_testcapi')
 
+class CAPITest(unittest.TestCase):
+
+    def test_buildvalue_N(self):
+        _testcapi.test_buildvalue_N()
+
 
 @unittest.skipUnless(threading, 'Threading required for this test.')
 class TestPendingCalls(unittest.TestCase):
@@ -132,7 +137,7 @@ def test_main():
             except _testcapi.error:
                 raise support.TestFailed, sys.exc_info()[1]
 
-    support.run_unittest(TestPendingCalls, TestThreadState)
+    support.run_unittest(CAPITest, TestPendingCalls, TestThreadState)
 
 if __name__ == "__main__":
     test_main()
index 2cb2c88..5101484 100644 (file)
@@ -110,7 +110,7 @@ class samplecmdclass(cmd.Cmd):
     5  12  19
     6  13
 
-    This is a interactive test, put some commands in the cmdqueue attribute
+    This is an interactive test, put some commands in the cmdqueue attribute
     and let it execute
     This test includes the preloop(), postloop(), default(), emptyline(),
     parseline(), do_help() functions
index 8b05227..cefa1e9 100644 (file)
@@ -1,5 +1,6 @@
 # Tests command line execution of scripts
 
+import contextlib
 import unittest
 import os
 import os.path
@@ -207,18 +208,69 @@ class CmdLineTest(unittest.TestCase):
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
             self._check_import_error(launch_name, msg)
 
+    @contextlib.contextmanager
+    def setup_test_pkg(self, *args):
+        with temp_dir() as script_dir, \
+                test.test_support.change_cwd(script_dir):
+            pkg_dir = os.path.join(script_dir, 'test_pkg')
+            make_pkg(pkg_dir, *args)
+            yield pkg_dir
+
+    def check_dash_m_failure(self, *args):
+        rc, out, err = assert_python_failure('-m', *args)
+        if verbose > 1:
+            print(out)
+        self.assertEqual(rc, 1)
+        return err
+
     def test_dash_m_error_code_is_one(self):
         # If a module is invoked with the -m command line flag
         # and results in an error that the return code to the
         # shell is '1'
-        with temp_dir() as script_dir:
-            pkg_dir = os.path.join(script_dir, 'test_pkg')
-            make_pkg(pkg_dir)
+        with self.setup_test_pkg() as pkg_dir:
             script_name = _make_test_script(pkg_dir, 'other', "if __name__ == '__main__': raise ValueError")
-            rc, out, err = assert_python_failure('-m', 'test_pkg.other', *example_args)
-            if verbose > 1:
-                print(out)
+            err = self.check_dash_m_failure('test_pkg.other', *example_args)
+            self.assertIn(b'ValueError', err)
+
+    def test_dash_m_errors(self):
+        # Exercise error reporting for various invalid package executions
+        tests = (
+            ('__builtin__', br'No code object available'),
+            ('__builtin__.x', br'No module named'),
+            ('__builtin__.x.y', br'No module named'),
+            ('os.path', br'Loader.*cannot handle'),
+            ('importlib', br'No module named.*'
+                br'is a package and cannot be directly executed'),
+            ('importlib.nonexistant', br'No module named'),
+        )
+        for name, regex in tests:
+            rc, _, err = assert_python_failure('-m', name)
             self.assertEqual(rc, 1)
+            self.assertRegexpMatches(err, regex)
+            self.assertNotIn(b'Traceback', err)
+
+    def test_dash_m_init_traceback(self):
+        # These were wrapped in an ImportError and tracebacks were
+        # suppressed; see Issue 14285
+        exceptions = (ImportError, AttributeError, TypeError, ValueError)
+        for exception in exceptions:
+            exception = exception.__name__
+            init = "raise {0}('Exception in __init__.py')".format(exception)
+            with self.setup_test_pkg(init) as pkg_dir:
+                err = self.check_dash_m_failure('test_pkg')
+                self.assertIn(exception.encode('ascii'), err)
+                self.assertIn(b'Exception in __init__.py', err)
+                self.assertIn(b'Traceback', err)
+
+    def test_dash_m_main_traceback(self):
+        # Ensure that an ImportError's traceback is reported
+        with self.setup_test_pkg() as pkg_dir:
+            main = "raise ImportError('Exception in __main__ module')"
+            _make_test_script(pkg_dir, '__main__', main)
+            err = self.check_dash_m_failure('test_pkg')
+            self.assertIn(b'ImportError', err)
+            self.assertIn(b'Exception in __main__ module', err)
+            self.assertIn(b'Traceback', err)
 
 
 def test_main():
index 57d5e06..efc40cf 100644 (file)
@@ -47,7 +47,7 @@ class ReadTest(unittest.TestCase):
         self.assertEqual(r.bytebuffer, "")
         self.assertEqual(r.charbuffer, u"")
 
-        # do the check again, this time using a incremental decoder
+        # do the check again, this time using an incremental decoder
         d = codecs.getincrementaldecoder(self.encoding)()
         result = u""
         for (c, partialresult) in zip(input.encode(self.encoding), partialresults):
diff --git a/Lib/test/test_coding.py b/Lib/test/test_coding.py
deleted file mode 100644 (file)
index 7f5ddb1..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-
-import test.test_support, unittest
-import os
-
-class CodingTest(unittest.TestCase):
-    def test_bad_coding(self):
-        module_name = 'bad_coding'
-        self.verify_bad_module(module_name)
-
-    def test_bad_coding2(self):
-        module_name = 'bad_coding2'
-        self.verify_bad_module(module_name)
-
-    def verify_bad_module(self, module_name):
-        self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
-
-        path = os.path.dirname(__file__)
-        filename = os.path.join(path, module_name + '.py')
-        with open(filename) as fp:
-            text = fp.read()
-        self.assertRaises(SyntaxError, compile, text, filename, 'exec')
-
-    def test_error_from_string(self):
-        # See http://bugs.python.org/issue6289
-        input = u"# coding: ascii\n\N{SNOWMAN}".encode('utf-8')
-        with self.assertRaises(SyntaxError) as c:
-            compile(input, "<string>", "exec")
-        expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \
-                   "ordinal not in range(128)"
-        self.assertTrue(c.exception.args[0].startswith(expected))
-
-
-def test_main():
-    test.test_support.run_unittest(CodingTest)
-
-if __name__ == "__main__":
-    test_main()
index 09b5c54..125a68f 100644 (file)
@@ -1,19 +1,24 @@
-
-import unittest, doctest, operator
-import inspect
-from test import test_support
-from collections import namedtuple, Counter, OrderedDict
-from test import mapping_tests
-import pickle, cPickle, copy
-from random import randrange, shuffle
+import collections
+import copy
+import doctest
 import keyword
+import operator
+import pickle
+import cPickle
+from random import choice, randrange
 import re
+import string
 import sys
+from test import test_support
+import unittest
+
+from collections import namedtuple, Counter, OrderedDict
 from collections import Hashable, Iterable, Iterator
 from collections import Sized, Container, Callable
 from collections import Set, MutableSet
 from collections import Mapping, MutableMapping
 from collections import Sequence, MutableSequence
+
 # Silence deprecation warning
 sets = test_support.import_module('sets', deprecated=True)
 
@@ -178,8 +183,7 @@ class TestNamedTuple(unittest.TestCase):
         self.assertEqual(Dot(1)._fields, ('d',))
 
         n = 5000
-        import string, random
-        names = list(set(''.join([random.choice(string.ascii_letters)
+        names = list(set(''.join([choice(string.ascii_letters)
                                   for j in range(10)]) for i in range(n)))
         n = len(names)
         Big = namedtuple('Big', names)
@@ -556,7 +560,7 @@ class TestCollectionABCs(ABCTestCase):
 
     def test_issue_4920(self):
         # MutableSet.pop() method did not work
-        class MySet(collections.MutableSet):
+        class MySet(MutableSet):
             __slots__=['__s']
             def __init__(self,items=None):
                 if items is None:
@@ -802,7 +806,7 @@ class TestCollectionABCs(ABCTestCase):
             self.assertTrue(issubclass(sample, Mapping))
         self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__',
             '__getitem__')
-        class MyMapping(collections.Mapping):
+        class MyMapping(Mapping):
             def __len__(self):
                 return 0
             def __getitem__(self, i):
@@ -1038,290 +1042,11 @@ class TestCounter(unittest.TestCase):
         self.assertRaises(TypeError, Counter().subtract, {}, {})
         self.assertRaises(TypeError, Counter.subtract)
 
-class TestOrderedDict(unittest.TestCase):
-
-    def test_init(self):
-        with self.assertRaises(TypeError):
-            OrderedDict([('a', 1), ('b', 2)], None)                                 # too many args
-        pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
-        self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs)           # dict input
-        self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs)         # kwds input
-        self.assertEqual(list(OrderedDict(pairs).items()), pairs)                   # pairs input
-        self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)],
-                                          c=3, e=5).items()), pairs)                # mixed input
-
-        # make sure no positional args conflict with possible kwdargs
-        self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)])
-        self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)])
-        self.assertRaises(TypeError, OrderedDict, 42)
-        self.assertRaises(TypeError, OrderedDict, (), ())
-        self.assertRaises(TypeError, OrderedDict.__init__)
-
-        # Make sure that direct calls to __init__ do not clear previous contents
-        d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
-        d.__init__([('e', 5), ('f', 6)], g=7, d=4)
-        self.assertEqual(list(d.items()),
-            [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
-
-    def test_update(self):
-        with self.assertRaises(TypeError):
-            OrderedDict().update([('a', 1), ('b', 2)], None)                        # too many args
-        pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
-        od = OrderedDict()
-        od.update(dict(pairs))
-        self.assertEqual(sorted(od.items()), pairs)                                 # dict input
-        od = OrderedDict()
-        od.update(**dict(pairs))
-        self.assertEqual(sorted(od.items()), pairs)                                 # kwds input
-        od = OrderedDict()
-        od.update(pairs)
-        self.assertEqual(list(od.items()), pairs)                                   # pairs input
-        od = OrderedDict()
-        od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)
-        self.assertEqual(list(od.items()), pairs)                                   # mixed input
-
-        # Issue 9137: Named argument called 'other' or 'self'
-        # shouldn't be treated specially.
-        od = OrderedDict()
-        od.update(self=23)
-        self.assertEqual(list(od.items()), [('self', 23)])
-        od = OrderedDict()
-        od.update(other={})
-        self.assertEqual(list(od.items()), [('other', {})])
-        od = OrderedDict()
-        od.update(red=5, blue=6, other=7, self=8)
-        self.assertEqual(sorted(list(od.items())),
-                         [('blue', 6), ('other', 7), ('red', 5), ('self', 8)])
-
-        # Make sure that direct calls to update do not clear previous contents
-        # add that updates items are not moved to the end
-        d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
-        d.update([('e', 5), ('f', 6)], g=7, d=4)
-        self.assertEqual(list(d.items()),
-            [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
-
-        self.assertRaises(TypeError, OrderedDict().update, 42)
-        self.assertRaises(TypeError, OrderedDict().update, (), ())
-        self.assertRaises(TypeError, OrderedDict.update)
-
-    def test_abc(self):
-        self.assertIsInstance(OrderedDict(), MutableMapping)
-        self.assertTrue(issubclass(OrderedDict, MutableMapping))
-
-    def test_clear(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        shuffle(pairs)
-        od = OrderedDict(pairs)
-        self.assertEqual(len(od), len(pairs))
-        od.clear()
-        self.assertEqual(len(od), 0)
-
-    def test_delitem(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        od = OrderedDict(pairs)
-        del od['a']
-        self.assertNotIn('a', od)
-        with self.assertRaises(KeyError):
-            del od['a']
-        self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
-
-    def test_setitem(self):
-        od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)])
-        od['c'] = 10           # existing element
-        od['f'] = 20           # new element
-        self.assertEqual(list(od.items()),
-                         [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)])
-
-    def test_iterators(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        shuffle(pairs)
-        od = OrderedDict(pairs)
-        self.assertEqual(list(od), [t[0] for t in pairs])
-        self.assertEqual(od.keys()[:], [t[0] for t in pairs])
-        self.assertEqual(od.values()[:], [t[1] for t in pairs])
-        self.assertEqual(od.items()[:], pairs)
-        self.assertEqual(list(od.iterkeys()), [t[0] for t in pairs])
-        self.assertEqual(list(od.itervalues()), [t[1] for t in pairs])
-        self.assertEqual(list(od.iteritems()), pairs)
-        self.assertEqual(list(reversed(od)),
-                         [t[0] for t in reversed(pairs)])
-
-    def test_popitem(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        shuffle(pairs)
-        od = OrderedDict(pairs)
-        while pairs:
-            self.assertEqual(od.popitem(), pairs.pop())
-        with self.assertRaises(KeyError):
-            od.popitem()
-        self.assertEqual(len(od), 0)
-
-    def test_pop(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        shuffle(pairs)
-        od = OrderedDict(pairs)
-        shuffle(pairs)
-        while pairs:
-            k, v = pairs.pop()
-            self.assertEqual(od.pop(k), v)
-        with self.assertRaises(KeyError):
-            od.pop('xyz')
-        self.assertEqual(len(od), 0)
-        self.assertEqual(od.pop(k, 12345), 12345)
-
-        # make sure pop still works when __missing__ is defined
-        class Missing(OrderedDict):
-            def __missing__(self, key):
-                return 0
-        m = Missing(a=1)
-        self.assertEqual(m.pop('b', 5), 5)
-        self.assertEqual(m.pop('a', 6), 1)
-        self.assertEqual(m.pop('a', 6), 6)
-        with self.assertRaises(KeyError):
-            m.pop('a')
-
-    def test_equality(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        shuffle(pairs)
-        od1 = OrderedDict(pairs)
-        od2 = OrderedDict(pairs)
-        self.assertEqual(od1, od2)          # same order implies equality
-        pairs = pairs[2:] + pairs[:2]
-        od2 = OrderedDict(pairs)
-        self.assertNotEqual(od1, od2)       # different order implies inequality
-        # comparison to regular dict is not order sensitive
-        self.assertEqual(od1, dict(od2))
-        self.assertEqual(dict(od2), od1)
-        # different length implied inequality
-        self.assertNotEqual(od1, OrderedDict(pairs[:-1]))
-
-    def test_copying(self):
-        # Check that ordered dicts are copyable, deepcopyable, picklable,
-        # and have a repr/eval round-trip
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        od = OrderedDict(pairs)
-        update_test = OrderedDict()
-        update_test.update(od)
-        for i, dup in enumerate([
-                    od.copy(),
-                    copy.copy(od),
-                    copy.deepcopy(od),
-                    pickle.loads(pickle.dumps(od, 0)),
-                    pickle.loads(pickle.dumps(od, 1)),
-                    pickle.loads(pickle.dumps(od, 2)),
-                    pickle.loads(pickle.dumps(od, -1)),
-                    eval(repr(od)),
-                    update_test,
-                    OrderedDict(od),
-                    ]):
-            self.assertTrue(dup is not od)
-            self.assertEqual(dup, od)
-            self.assertEqual(list(dup.items()), list(od.items()))
-            self.assertEqual(len(dup), len(od))
-            self.assertEqual(type(dup), type(od))
-
-    def test_yaml_linkage(self):
-        # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
-        # In yaml, lists are native but tuples are not.
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        od = OrderedDict(pairs)
-        # yaml.dump(od) -->
-        # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n  - [b, 2]\n'
-        self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))
-
-    def test_reduce_not_too_fat(self):
-        # do not save instance dictionary if not needed
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        od = OrderedDict(pairs)
-        self.assertEqual(len(od.__reduce__()), 2)
-        od.x = 10
-        self.assertEqual(len(od.__reduce__()), 3)
-
-    def test_repr(self):
-        od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])
-        self.assertEqual(repr(od),
-            "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])")
-        self.assertEqual(eval(repr(od)), od)
-        self.assertEqual(repr(OrderedDict()), "OrderedDict()")
-
-    def test_repr_recursive(self):
-        # See issue #9826
-        od = OrderedDict.fromkeys('abc')
-        od['x'] = od
-        self.assertEqual(repr(od),
-            "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])")
-
-    def test_setdefault(self):
-        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
-        shuffle(pairs)
-        od = OrderedDict(pairs)
-        pair_order = list(od.items())
-        self.assertEqual(od.setdefault('a', 10), 3)
-        # make sure order didn't change
-        self.assertEqual(list(od.items()), pair_order)
-        self.assertEqual(od.setdefault('x', 10), 10)
-        # make sure 'x' is added to the end
-        self.assertEqual(list(od.items())[-1], ('x', 10))
-
-        # make sure setdefault still works when __missing__ is defined
-        class Missing(OrderedDict):
-            def __missing__(self, key):
-                return 0
-        self.assertEqual(Missing().setdefault(5, 9), 9)
-
-    def test_reinsert(self):
-        # Given insert a, insert b, delete a, re-insert a,
-        # verify that a is now later than b.
-        od = OrderedDict()
-        od['a'] = 1
-        od['b'] = 2
-        del od['a']
-        od['a'] = 1
-        self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])
-
-    def test_views(self):
-        s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split()
-        od = OrderedDict.fromkeys(s)
-        self.assertEqual(list(od.viewkeys()),  s)
-        self.assertEqual(list(od.viewvalues()),  [None for k in s])
-        self.assertEqual(list(od.viewitems()),  [(k, None) for k in s])
-
-        # See http://bugs.python.org/issue24286
-        self.assertEqual(od.viewkeys(), dict(od).viewkeys())
-        self.assertEqual(od.viewitems(), dict(od).viewitems())
-
-    def test_override_update(self):
-        # Verify that subclasses can override update() without breaking __init__()
-        class MyOD(OrderedDict):
-            def update(self, *args, **kwds):
-                raise Exception()
-        items = [('a', 1), ('c', 3), ('b', 2)]
-        self.assertEqual(list(MyOD(items).items()), items)
-
-class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
-    type2test = OrderedDict
-
-    def test_popitem(self):
-        d = self._empty_mapping()
-        self.assertRaises(KeyError, d.popitem)
-
-class MyOrderedDict(OrderedDict):
-    pass
-
-class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
-    type2test = MyOrderedDict
-
-    def test_popitem(self):
-        d = self._empty_mapping()
-        self.assertRaises(KeyError, d.popitem)
-
-import collections
 
 def test_main(verbose=None):
     NamedTupleDocs = doctest.DocTestSuite(module=collections)
     test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs,
-                    TestCollectionABCs, TestCounter,
-                    TestOrderedDict, GeneralMappingTests, SubclassMappingTests]
+                    TestCollectionABCs, TestCounter]
     test_support.run_unittest(*test_classes)
     test_support.run_doctest(collections, verbose)
 
index 6a6ef0e..e954a0c 100644 (file)
@@ -576,14 +576,15 @@ if 1:
         # objects are accepted, which could be not terminated.
         with self.assertRaisesRegexp(TypeError, "without null bytes"):
             compile(u"123\x00", "<dummy>", "eval")
-        with self.assertRaisesRegexp(TypeError, "without null bytes"):
-            compile(buffer("123\x00"), "<dummy>", "eval")
-        code = compile(buffer("123\x00", 1, 2), "<dummy>", "eval")
-        self.assertEqual(eval(code), 23)
-        code = compile(buffer("1234", 1, 2), "<dummy>", "eval")
-        self.assertEqual(eval(code), 23)
-        code = compile(buffer("$23$", 1, 2), "<dummy>", "eval")
-        self.assertEqual(eval(code), 23)
+        with test_support.check_py3k_warnings():
+            with self.assertRaisesRegexp(TypeError, "without null bytes"):
+                compile(buffer("123\x00"), "<dummy>", "eval")
+            code = compile(buffer("123\x00", 1, 2), "<dummy>", "eval")
+            self.assertEqual(eval(code), 23)
+            code = compile(buffer("1234", 1, 2), "<dummy>", "eval")
+            self.assertEqual(eval(code), 23)
+            code = compile(buffer("$23$", 1, 2), "<dummy>", "eval")
+            self.assertEqual(eval(code), 23)
 
 class TestStackSize(unittest.TestCase):
     # These tests check that the computed stack size for a code object
@@ -622,6 +623,65 @@ class TestStackSize(unittest.TestCase):
         code += "   x and x\n" * self.N
         self.check_stack_size(code)
 
+    def check_constant(self, func, expected):
+        for const in func.__code__.co_consts:
+            if repr(const) == repr(expected):
+                break
+        else:
+            self.fail("unable to find constant %r in %r"
+                      % (expected, func.__code__.co_consts))
+
+    # Merging equal constants is not a strict requirement for the Python
+    # semantics, it's a more an implementation detail.
+    @test_support.cpython_only
+    def test_merge_constants(self):
+        # Issue #25843: compile() must merge constants which are equal
+        # and have the same type.
+
+        def check_same_constant(const):
+            ns = {}
+            code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
+            exec(code, ns)
+            f1 = ns['f1']
+            f2 = ns['f2']
+            self.assertIs(f1.__code__, f2.__code__)
+            self.check_constant(f1, const)
+            self.assertEqual(repr(f1()), repr(const))
+
+        check_same_constant(None)
+        check_same_constant(0)
+        check_same_constant(0.0)
+        check_same_constant(b'abc')
+        check_same_constant('abc')
+
+    def test_dont_merge_constants(self):
+        # Issue #25843: compile() must not merge constants which are equal
+        # but have a different type.
+
+        def check_different_constants(const1, const2):
+            ns = {}
+            exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
+            f1 = ns['f1']
+            f2 = ns['f2']
+            self.assertIsNot(f1.__code__, f2.__code__)
+            self.check_constant(f1, const1)
+            self.check_constant(f2, const2)
+            self.assertEqual(repr(f1()), repr(const1))
+            self.assertEqual(repr(f2()), repr(const2))
+
+        check_different_constants(0, 0.0)
+        check_different_constants(+0.0, -0.0)
+        check_different_constants((0,), (0.0,))
+
+        # check_different_constants() cannot be used because repr(-0j) is
+        # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
+        f1, f2 = lambda: +0.0j, lambda: -0.0j
+        self.assertIsNot(f1.__code__, f2.__code__)
+        self.check_constant(f1, +0.0j)
+        self.check_constant(f2, -0.0j)
+        self.assertEqual(repr(f1()), repr(+0.0j))
+        self.assertEqual(repr(f2()), repr(-0.0j))
+
 
 def test_main():
     test_support.run_unittest(__name__)
index d272d12..a6568d7 100644 (file)
@@ -1760,7 +1760,7 @@ class LWPCookieTests(TestCase):
             key = "%s_after" % cookie.value
             counter[key] = counter[key] + 1
 
-            # a permanent cookie got lost accidently
+            # a permanent cookie got lost accidentally
         self.assertEqual(counter["perm_after"], counter["perm_before"])
             # a session cookie hasn't been cleared
         self.assertEqual(counter["session_after"], 0)
index 6b64f10..d65f6a2 100644 (file)
@@ -82,7 +82,8 @@ class TestCopy(unittest.TestCase):
             pass
         def f():
             pass
-        tests = [None, 42, 2L**100, 3.14, True, False, 1j,
+        tests = [None, Ellipsis,
+                 42, 2L**100, 3.14, True, False, 1j,
                  "hello", u"hello\u1234", f.func_code,
                  NewStyle, xrange(10), Classic, max]
         for x in tests:
@@ -90,15 +91,57 @@ class TestCopy(unittest.TestCase):
 
     def test_copy_list(self):
         x = [1, 2, 3]
-        self.assertEqual(copy.copy(x), x)
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+        x = []
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
 
     def test_copy_tuple(self):
         x = (1, 2, 3)
-        self.assertEqual(copy.copy(x), x)
+        self.assertIs(copy.copy(x), x)
+        x = ()
+        self.assertIs(copy.copy(x), x)
+        x = (1, 2, 3, [])
+        self.assertIs(copy.copy(x), x)
 
     def test_copy_dict(self):
         x = {"foo": 1, "bar": 2}
-        self.assertEqual(copy.copy(x), x)
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+        x = {}
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+
+    def test_copy_set(self):
+        x = {1, 2, 3}
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+        x = set()
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+
+    def test_copy_frozenset(self):
+        x = frozenset({1, 2, 3})
+        self.assertIs(copy.copy(x), x)
+        x = frozenset()
+        self.assertIs(copy.copy(x), x)
+
+    def test_copy_bytearray(self):
+        x = bytearray(b'abc')
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+        x = bytearray()
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        self.assertIsNot(y, x)
 
     def test_copy_inst_vanilla(self):
         class C:
@@ -165,6 +208,9 @@ class TestCopy(unittest.TestCase):
                 return cmp(self.foo, other.foo)
         x = C(42)
         self.assertEqual(copy.copy(x), x)
+        # State with boolean value is false (issue #25718)
+        x = C(0.0)
+        self.assertEqual(copy.copy(x), x)
 
     # The deepcopy() method
 
@@ -395,6 +441,12 @@ class TestCopy(unittest.TestCase):
         x = C([42])
         y = copy.deepcopy(x)
         self.assertEqual(y, x)
+        self.assertIsNot(y, x)
+        self.assertIsNot(y.foo, x.foo)
+        # State with boolean value is false (issue #25718)
+        x = C([])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
         self.assertTrue(y is not x)
         self.assertTrue(y.foo is not x.foo)
 
index 0a1eb43..c9ec788 100644 (file)
@@ -51,6 +51,10 @@ class cPickleTests(AbstractUnpickleTests, AbstractPickleTests,
 
     error = cPickle.BadPickleGet
     module = cPickle
+    bad_stack_errors = (cPickle.UnpicklingError,)
+    bad_mark_errors = (EOFError,)
+    truncated_errors = (cPickle.UnpicklingError, EOFError,
+                        AttributeError, ValueError)
 
 class cPickleUnpicklerTests(AbstractUnpickleTests):
 
@@ -63,6 +67,10 @@ class cPickleUnpicklerTests(AbstractUnpickleTests):
             self.close(f)
 
     error = cPickle.BadPickleGet
+    bad_stack_errors = (cPickle.UnpicklingError,)
+    bad_mark_errors = (EOFError,)
+    truncated_errors = (cPickle.UnpicklingError, EOFError,
+                        AttributeError, ValueError)
 
 class cStringIOCUnpicklerTests(cStringIOMixin, cPickleUnpicklerTests):
     pass
index e2eec70..d456759 100644 (file)
@@ -2,6 +2,7 @@
 # Copyright (C) 2001,2002 Python Software Foundation
 # csv package unit tests
 
+import copy
 import sys
 import os
 import unittest
@@ -10,6 +11,7 @@ import tempfile
 import csv
 import gc
 import io
+import pickle
 from test import test_support
 
 class Test_Csv(unittest.TestCase):
@@ -466,6 +468,18 @@ class TestDialectRegistry(unittest.TestCase):
         self.assertRaises(TypeError, csv.reader, [], quoting = -1)
         self.assertRaises(TypeError, csv.reader, [], quoting = 100)
 
+    # See issue #22995
+    ## def test_copy(self):
+    ##     for name in csv.list_dialects():
+    ##         dialect = csv.get_dialect(name)
+    ##         self.assertRaises(TypeError, copy.copy, dialect)
+
+    ## def test_pickle(self):
+    ##     for name in csv.list_dialects():
+    ##         dialect = csv.get_dialect(name)
+    ##         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+    ##             self.assertRaises(TypeError, pickle.dumps, dialect, proto)
+
 class TestCsvBase(unittest.TestCase):
     def readerAssertEqual(self, input, expected_result):
         fd, name = tempfile.mkstemp()
index fcf9618..c9abfe3 100644 (file)
 # Test script for the curses module
 #
 # This script doesn't actually display anything very coherent. but it
-# does call every method and function.
+# does call (nearly) every method and function.
 #
 # Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(),
 # init_color()
 # Only called, not tested: getmouse(), ungetmouse()
 #
 
-import sys, tempfile, os
+import os
+import sys
+import tempfile
+import unittest
+
+from test.test_support import requires, import_module, verbose, run_unittest
 
 # Optionally test curses module.  This currently requires that the
 # 'curses' resource be given on the regrtest command line using the -u
 # option.  If not available, nothing after this line will be executed.
-
-import unittest
-from test.test_support import requires, import_module
 requires('curses')
+
+# If either of these don't exist, skip the tests.
 curses = import_module('curses')
-curses.panel = import_module('curses.panel')
+import_module('curses.panel')
+import_module('curses.ascii')
 
+def requires_curses_func(name):
+    return unittest.skipUnless(hasattr(curses, name),
+                               'requires curses.%s' % name)
 
-# XXX: if newterm was supported we could use it instead of initscr and not exit
 term = os.environ.get('TERM')
-if not term or term == 'unknown':
-    raise unittest.SkipTest, "$TERM=%r, calling initscr() may cause exit" % term
-
-if sys.platform == "cygwin":
-    raise unittest.SkipTest("cygwin's curses mostly just hangs")
-
-def window_funcs(stdscr):
-    "Test the methods of windows"
-    win = curses.newwin(10,10)
-    win = curses.newwin(5,5, 5,5)
-    win2 = curses.newwin(15,15, 5,5)
-
-    for meth in [stdscr.addch, stdscr.addstr]:
-        for args in [('a'), ('a', curses.A_BOLD),
-                     (4,4, 'a'), (5,5, 'a', curses.A_BOLD)]:
-            meth(*args)
-
-    for meth in [stdscr.box, stdscr.clear, stdscr.clrtobot,
-                 stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch,
-                 stdscr.deleteln, stdscr.erase, stdscr.getbegyx,
-                 stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx,
-                 stdscr.getparyx, stdscr.getyx, stdscr.inch,
-                 stdscr.insertln, stdscr.instr, stdscr.is_wintouched,
-                 win.noutrefresh, stdscr.redrawwin, stdscr.refresh,
-                 stdscr.standout, stdscr.standend, stdscr.syncdown,
-                 stdscr.syncup, stdscr.touchwin, stdscr.untouchwin]:
-        meth()
-
-    stdscr.addnstr('1234', 3)
-    stdscr.addnstr('1234', 3, curses.A_BOLD)
-    stdscr.addnstr(4,4, '1234', 3)
-    stdscr.addnstr(5,5, '1234', 3, curses.A_BOLD)
-
-    stdscr.attron(curses.A_BOLD)
-    stdscr.attroff(curses.A_BOLD)
-    stdscr.attrset(curses.A_BOLD)
-    stdscr.bkgd(' ')
-    stdscr.bkgd(' ', curses.A_REVERSE)
-    stdscr.bkgdset(' ')
-    stdscr.bkgdset(' ', curses.A_REVERSE)
-
-    win.border(65, 66, 67, 68,
-               69, 70, 71, 72)
-    win.border('|', '!', '-', '_',
-               '+', '\\', '#', '/')
-    try:
+
+# If newterm was supported we could use it instead of initscr and not exit
+@unittest.skipIf(not term or term == 'unknown',
+                 "$TERM=%r, calling initscr() may cause exit" % term)
+@unittest.skipIf(sys.platform == "cygwin",
+                 "cygwin's curses mostly just hangs")
+class TestCurses(unittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        if not sys.__stdout__.isatty():
+            # Temporary skip tests on non-tty
+            raise unittest.SkipTest('sys.__stdout__ is not a tty')
+            cls.tmp = tempfile.TemporaryFile()
+            fd = cls.tmp.fileno()
+        else:
+            cls.tmp = None
+            fd = sys.__stdout__.fileno()
+        # testing setupterm() inside initscr/endwin
+        # causes terminal breakage
+        curses.setupterm(fd=fd)
+
+    @classmethod
+    def tearDownClass(cls):
+        if cls.tmp:
+            cls.tmp.close()
+            del cls.tmp
+
+    def setUp(self):
+        if verbose:
+            # just to make the test output a little more readable
+            print()
+        self.stdscr = curses.initscr()
+        curses.savetty()
+
+    def tearDown(self):
+        curses.resetty()
+        curses.endwin()
+
+    def test_window_funcs(self):
+        "Test the methods of windows"
+        stdscr = self.stdscr
+        win = curses.newwin(10,10)
+        win = curses.newwin(5,5, 5,5)
+        win2 = curses.newwin(15,15, 5,5)
+
+        for meth in [stdscr.addch, stdscr.addstr]:
+            for args in [('a'), ('a', curses.A_BOLD),
+                         (4,4, 'a'), (5,5, 'a', curses.A_BOLD)]:
+                meth(*args)
+
+        for meth in [stdscr.box, stdscr.clear, stdscr.clrtobot,
+                     stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch,
+                     stdscr.deleteln, stdscr.erase, stdscr.getbegyx,
+                     stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx,
+                     stdscr.getparyx, stdscr.getyx, stdscr.inch,
+                     stdscr.insertln, stdscr.instr, stdscr.is_wintouched,
+                     win.noutrefresh, stdscr.redrawwin, stdscr.refresh,
+                     stdscr.standout, stdscr.standend, stdscr.syncdown,
+                     stdscr.syncup, stdscr.touchwin, stdscr.untouchwin]:
+            meth()
+
+        stdscr.addnstr('1234', 3)
+        stdscr.addnstr('1234', 3, curses.A_BOLD)
+        stdscr.addnstr(4,4, '1234', 3)
+        stdscr.addnstr(5,5, '1234', 3, curses.A_BOLD)
+
+        stdscr.attron(curses.A_BOLD)
+        stdscr.attroff(curses.A_BOLD)
+        stdscr.attrset(curses.A_BOLD)
+        stdscr.bkgd(' ')
+        stdscr.bkgd(' ', curses.A_REVERSE)
+        stdscr.bkgdset(' ')
+        stdscr.bkgdset(' ', curses.A_REVERSE)
+
         win.border(65, 66, 67, 68,
-                   69, [], 71, 72)
-    except TypeError:
-        pass
-    else:
-        raise RuntimeError, "Expected win.border() to raise TypeError"
-
-    stdscr.clearok(1)
-
-    win4 = stdscr.derwin(2,2)
-    win4 = stdscr.derwin(1,1, 5,5)
-    win4.mvderwin(9,9)
-
-    stdscr.echochar('a')
-    stdscr.echochar('a', curses.A_BOLD)
-    stdscr.hline('-', 5)
-    stdscr.hline('-', 5, curses.A_BOLD)
-    stdscr.hline(1,1,'-', 5)
-    stdscr.hline(1,1,'-', 5, curses.A_BOLD)
-
-    stdscr.idcok(1)
-    stdscr.idlok(1)
-    stdscr.immedok(1)
-    stdscr.insch('c')
-    stdscr.insdelln(1)
-    stdscr.insnstr('abc', 3)
-    stdscr.insnstr('abc', 3, curses.A_BOLD)
-    stdscr.insnstr(5, 5, 'abc', 3)
-    stdscr.insnstr(5, 5, 'abc', 3, curses.A_BOLD)
-
-    stdscr.insstr('def')
-    stdscr.insstr('def', curses.A_BOLD)
-    stdscr.insstr(5, 5, 'def')
-    stdscr.insstr(5, 5, 'def', curses.A_BOLD)
-    stdscr.is_linetouched(0)
-    stdscr.keypad(1)
-    stdscr.leaveok(1)
-    stdscr.move(3,3)
-    win.mvwin(2,2)
-    stdscr.nodelay(1)
-    stdscr.notimeout(1)
-    win2.overlay(win)
-    win2.overwrite(win)
-    win2.overlay(win, 1, 2, 3, 3, 2, 1)
-    win2.overwrite(win, 1, 2, 3, 3, 2, 1)
-    stdscr.redrawln(1,2)
-
-    stdscr.scrollok(1)
-    stdscr.scroll()
-    stdscr.scroll(2)
-    stdscr.scroll(-3)
-
-    stdscr.move(12, 2)
-    stdscr.setscrreg(10,15)
-    win3 = stdscr.subwin(10,10)
-    win3 = stdscr.subwin(10,10, 5,5)
-    stdscr.syncok(1)
-    stdscr.timeout(5)
-    stdscr.touchline(5,5)
-    stdscr.touchline(5,5,0)
-    stdscr.vline('a', 3)
-    stdscr.vline('a', 3, curses.A_STANDOUT)
-    stdscr.chgat(5, 2, 3, curses.A_BLINK)
-    stdscr.chgat(3, curses.A_BOLD)
-    stdscr.chgat(5, 8, curses.A_UNDERLINE)
-    stdscr.chgat(curses.A_BLINK)
-    stdscr.refresh()
-
-    stdscr.vline(1,1, 'a', 3)
-    stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT)
-
-    if hasattr(curses, 'resize'):
-        stdscr.resize()
-    if hasattr(curses, 'enclose'):
-        stdscr.enclose()
-
-
-def module_funcs(stdscr):
-    "Test module-level functions"
-
-    for func in [curses.baudrate, curses.beep, curses.can_change_color,
-                 curses.cbreak, curses.def_prog_mode, curses.doupdate,
-                 curses.filter, curses.flash, curses.flushinp,
-                 curses.has_colors, curses.has_ic, curses.has_il,
-                 curses.isendwin, curses.killchar, curses.longname,
-                 curses.nocbreak, curses.noecho, curses.nonl,
-                 curses.noqiflush, curses.noraw,
-                 curses.reset_prog_mode, curses.termattrs,
-                 curses.termname, curses.erasechar, curses.getsyx]:
-        func()
-
-    # Functions that actually need arguments
-    if curses.tigetstr("cnorm"):
-        curses.curs_set(1)
-    curses.delay_output(1)
-    curses.echo() ; curses.echo(1)
-
-    f = tempfile.TemporaryFile()
-    stdscr.putwin(f)
-    f.seek(0)
-    curses.getwin(f)
-    f.close()
-
-    curses.halfdelay(1)
-    curses.intrflush(1)
-    curses.meta(1)
-    curses.napms(100)
-    curses.newpad(50,50)
-    win = curses.newwin(5,5)
-    win = curses.newwin(5,5, 1,1)
-    curses.nl() ; curses.nl(1)
-    curses.putp('abc')
-    curses.qiflush()
-    curses.raw() ; curses.raw(1)
-    curses.setsyx(5,5)
-    curses.tigetflag('hc')
-    curses.tigetnum('co')
-    curses.tigetstr('cr')
-    curses.tparm('cr')
-    curses.typeahead(sys.__stdin__.fileno())
-    curses.unctrl('a')
-    curses.ungetch('a')
-    curses.use_env(1)
+                   69, 70, 71, 72)
+        win.border('|', '!', '-', '_',
+                   '+', '\\', '#', '/')
+        with self.assertRaises(TypeError,
+                               msg="Expected win.border() to raise TypeError"):
+            win.border(65, 66, 67, 68,
+                       69, [], 71, 72)
+
+        stdscr.clearok(1)
+
+        win4 = stdscr.derwin(2,2)
+        win4 = stdscr.derwin(1,1, 5,5)
+        win4.mvderwin(9,9)
+
+        stdscr.echochar('a')
+        stdscr.echochar('a', curses.A_BOLD)
+        stdscr.hline('-', 5)
+        stdscr.hline('-', 5, curses.A_BOLD)
+        stdscr.hline(1,1,'-', 5)
+        stdscr.hline(1,1,'-', 5, curses.A_BOLD)
+
+        stdscr.idcok(1)
+        stdscr.idlok(1)
+        stdscr.immedok(1)
+        stdscr.insch('c')
+        stdscr.insdelln(1)
+        stdscr.insnstr('abc', 3)
+        stdscr.insnstr('abc', 3, curses.A_BOLD)
+        stdscr.insnstr(5, 5, 'abc', 3)
+        stdscr.insnstr(5, 5, 'abc', 3, curses.A_BOLD)
+
+        stdscr.insstr('def')
+        stdscr.insstr('def', curses.A_BOLD)
+        stdscr.insstr(5, 5, 'def')
+        stdscr.insstr(5, 5, 'def', curses.A_BOLD)
+        stdscr.is_linetouched(0)
+        stdscr.keypad(1)
+        stdscr.leaveok(1)
+        stdscr.move(3,3)
+        win.mvwin(2,2)
+        stdscr.nodelay(1)
+        stdscr.notimeout(1)
+        win2.overlay(win)
+        win2.overwrite(win)
+        win2.overlay(win, 1, 2, 2, 1, 3, 3)
+        win2.overwrite(win, 1, 2, 2, 1, 3, 3)
+        stdscr.redrawln(1,2)
+
+        stdscr.scrollok(1)
+        stdscr.scroll()
+        stdscr.scroll(2)
+        stdscr.scroll(-3)
+
+        stdscr.move(12, 2)
+        stdscr.setscrreg(10,15)
+        win3 = stdscr.subwin(10,10)
+        win3 = stdscr.subwin(10,10, 5,5)
+        stdscr.syncok(1)
+        stdscr.timeout(5)
+        stdscr.touchline(5,5)
+        stdscr.touchline(5,5,0)
+        stdscr.vline('a', 3)
+        stdscr.vline('a', 3, curses.A_STANDOUT)
+        stdscr.chgat(5, 2, 3, curses.A_BLINK)
+        stdscr.chgat(3, curses.A_BOLD)
+        stdscr.chgat(5, 8, curses.A_UNDERLINE)
+        stdscr.chgat(curses.A_BLINK)
+        stdscr.refresh()
+
+        stdscr.vline(1,1, 'a', 3)
+        stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT)
+
+        if hasattr(curses, 'resize'):
+            stdscr.resize()
+        if hasattr(curses, 'enclose'):
+            stdscr.enclose()
+
+
+    def test_module_funcs(self):
+        "Test module-level functions"
+        for func in [curses.baudrate, curses.beep, curses.can_change_color,
+                     curses.cbreak, curses.def_prog_mode, curses.doupdate,
+                     curses.filter, curses.flash, curses.flushinp,
+                     curses.has_colors, curses.has_ic, curses.has_il,
+                     curses.isendwin, curses.killchar, curses.longname,
+                     curses.nocbreak, curses.noecho, curses.nonl,
+                     curses.noqiflush, curses.noraw,
+                     curses.reset_prog_mode, curses.termattrs,
+                     curses.termname, curses.erasechar, curses.getsyx]:
+            func()
+
+        # Functions that actually need arguments
+        if curses.tigetstr("cnorm"):
+            curses.curs_set(1)
+        curses.delay_output(1)
+        curses.echo() ; curses.echo(1)
+
+        with tempfile.TemporaryFile() as f:
+            self.stdscr.putwin(f)
+            f.seek(0)
+            curses.getwin(f)
+
+        curses.halfdelay(1)
+        curses.intrflush(1)
+        curses.meta(1)
+        curses.napms(100)
+        curses.newpad(50,50)
+        win = curses.newwin(5,5)
+        win = curses.newwin(5,5, 1,1)
+        curses.nl() ; curses.nl(1)
+        curses.putp(b'abc')
+        curses.qiflush()
+        curses.raw() ; curses.raw(1)
+        curses.setsyx(5,5)
+        curses.tigetflag('hc')
+        curses.tigetnum('co')
+        curses.tigetstr('cr')
+        curses.tparm(b'cr')
+        curses.typeahead(sys.__stdin__.fileno())
+        curses.unctrl('a')
+        curses.ungetch('a')
+        curses.use_env(1)
 
     # Functions only available on a few platforms
-    if curses.has_colors():
+    def test_colors_funcs(self):
+        if not curses.has_colors():
+            self.skip('requires colors support')
         curses.start_color()
         curses.init_pair(2, 1,1)
         curses.color_content(1)
@@ -206,107 +244,103 @@ def module_funcs(stdscr):
         if hasattr(curses, 'use_default_colors'):
             curses.use_default_colors()
 
-    if hasattr(curses, 'keyname'):
+    @requires_curses_func('keyname')
+    def test_keyname(self):
         curses.keyname(13)
 
-    if hasattr(curses, 'has_key'):
+    @requires_curses_func('has_key')
+    def test_has_key(self):
         curses.has_key(13)
 
-    if hasattr(curses, 'getmouse'):
+    @requires_curses_func('getmouse')
+    def test_getmouse(self):
         (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
-        # availmask indicates that mouse stuff not available.
-        if availmask != 0:
-            curses.mouseinterval(10)
-            # just verify these don't cause errors
-            curses.ungetmouse(0, 0, 0, 0, curses.BUTTON1_PRESSED)
-            m = curses.getmouse()
-
-    if hasattr(curses, 'is_term_resized'):
-        curses.is_term_resized(*stdscr.getmaxyx())
-    if hasattr(curses, 'resizeterm'):
-        curses.resizeterm(*stdscr.getmaxyx())
-    if hasattr(curses, 'resize_term'):
-        curses.resize_term(*stdscr.getmaxyx())
-
-def unit_tests():
-    from curses import ascii
-    for ch, expected in [('a', 'a'), ('A', 'A'),
-                         (';', ';'), (' ', ' '),
-                         ('\x7f', '^?'), ('\n', '^J'), ('\0', '^@'),
-                         # Meta-bit characters
-                         ('\x8a', '!^J'), ('\xc1', '!A'),
-                         ]:
-        if ascii.unctrl(ch) != expected:
-            print 'curses.unctrl fails on character', repr(ch)
-
-
-def test_userptr_without_set(stdscr):
-    w = curses.newwin(10, 10)
-    p = curses.panel.new_panel(w)
-    # try to access userptr() before calling set_userptr() -- segfaults
-    try:
-        p.userptr()
-        raise RuntimeError, 'userptr should fail since not set'
-    except curses.panel.error:
-        pass
-
-def test_userptr_memory_leak(stdscr):
-    w = curses.newwin(10, 10)
-    p = curses.panel.new_panel(w)
-    obj = object()
-    nrefs = sys.getrefcount(obj)
-    for i in range(100):
-        p.set_userptr(obj)
-
-    p.set_userptr(None)
-    if sys.getrefcount(obj) != nrefs:
-        raise RuntimeError, "set_userptr leaked references"
-
-def test_userptr_segfault(stdscr):
-    panel = curses.panel.new_panel(stdscr)
-    class A:
-        def __del__(self):
-            panel.set_userptr(None)
-    panel.set_userptr(A())
-    panel.set_userptr(None)
-
-def test_resize_term(stdscr):
-    if hasattr(curses, 'resizeterm'):
+        if availmask == 0:
+            self.skip('mouse stuff not available')
+        curses.mouseinterval(10)
+        # just verify these don't cause errors
+        curses.ungetmouse(0, 0, 0, 0, curses.BUTTON1_PRESSED)
+        m = curses.getmouse()
+
+    def test_userptr_without_set(self):
+        w = curses.newwin(10, 10)
+        p = curses.panel.new_panel(w)
+        # try to access userptr() before calling set_userptr() -- segfaults
+        with self.assertRaises(curses.panel.error,
+                               msg='userptr should fail since not set'):
+            p.userptr()
+
+    def test_userptr_memory_leak(self):
+        w = curses.newwin(10, 10)
+        p = curses.panel.new_panel(w)
+        obj = object()
+        nrefs = sys.getrefcount(obj)
+        for i in range(100):
+            p.set_userptr(obj)
+
+        p.set_userptr(None)
+        self.assertEqual(sys.getrefcount(obj), nrefs,
+                         "set_userptr leaked references")
+
+    def test_userptr_segfault(self):
+        panel = curses.panel.new_panel(self.stdscr)
+        class A:
+            def __del__(self):
+                panel.set_userptr(None)
+        panel.set_userptr(A())
+        panel.set_userptr(None)
+
+    def test_new_curses_panel(self):
+        panel = curses.panel.new_panel(self.stdscr)
+        self.assertRaises(TypeError, type(panel))
+
+    @requires_curses_func('is_term_resized')
+    def test_is_term_resized(self):
+        curses.is_term_resized(*self.stdscr.getmaxyx())
+
+    @requires_curses_func('resize_term')
+    def test_resize_term(self):
+        curses.resize_term(*self.stdscr.getmaxyx())
+
+    @requires_curses_func('resizeterm')
+    def test_resizeterm(self):
+        stdscr = self.stdscr
         lines, cols = curses.LINES, curses.COLS
-        curses.resizeterm(lines - 1, cols + 1)
-
-        if curses.LINES != lines - 1 or curses.COLS != cols + 1:
-            raise RuntimeError, "Expected resizeterm to update LINES and COLS"
-
-def test_issue6243(stdscr):
-    curses.ungetch(1025)
-    stdscr.getkey()
-
-def main(stdscr):
-    curses.savetty()
-    try:
-        module_funcs(stdscr)
-        window_funcs(stdscr)
-        test_userptr_without_set(stdscr)
-        test_userptr_memory_leak(stdscr)
-        test_userptr_segfault(stdscr)
-        test_resize_term(stdscr)
-        test_issue6243(stdscr)
-    finally:
-        curses.resetty()
+        new_lines = lines - 1
+        new_cols = cols + 1
+        curses.resizeterm(new_lines, new_cols)
 
-if __name__ == '__main__':
-    curses.wrapper(main)
-    unit_tests()
-else:
-    if not sys.__stdout__.isatty():
-        raise unittest.SkipTest("sys.__stdout__ is not a tty")
-    # testing setupterm() inside initscr/endwin
-    # causes terminal breakage
-    curses.setupterm(fd=sys.__stdout__.fileno())
-    try:
-        stdscr = curses.initscr()
-        main(stdscr)
-    finally:
-        curses.endwin()
-    unit_tests()
+        self.assertEqual(curses.LINES, new_lines)
+        self.assertEqual(curses.COLS, new_cols)
+
+    def test_issue6243(self):
+        curses.ungetch(1025)
+        self.stdscr.getkey()
+
+    def test_issue10570(self):
+        b = curses.tparm(curses.tigetstr("cup"), 5, 3)
+        self.assertIs(type(b), bytes)
+
+
+class TestAscii(unittest.TestCase):
+
+    def test_unctrl(self):
+        unctrl = curses.ascii.unctrl
+        self.assertEqual(unctrl('a'), 'a')
+        self.assertEqual(unctrl('A'), 'A')
+        self.assertEqual(unctrl(';'), ';')
+        self.assertEqual(unctrl(' '), ' ')
+        self.assertEqual(unctrl('\x7f'), '^?')
+        self.assertEqual(unctrl('\n'), '^J')
+        self.assertEqual(unctrl('\0'), '^@')
+        # Meta-bit characters
+        self.assertEqual(unctrl('\x8a'), '!^J')
+        self.assertEqual(unctrl('\xc1'), '!A')
+
+
+def test_main():
+    run_unittest(TestCurses, TestAscii)
+
+
+if __name__ == "__main__":
+    unittest.main()
index 19ffbcd..1f7fb77 100644 (file)
@@ -882,7 +882,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
         #self.assertRaises(ValueError, t.strftime, "%#")
 
         #oh well, some systems just ignore those invalid ones.
-        #at least, excercise them to make sure that no crashes
+        #at least, exercise them to make sure that no crashes
         #are generated
         for f in ["%e", "%", "%#"]:
             try:
@@ -1992,7 +1992,7 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
                                          hour_byte + base[1:])
 
 # A mixin for classes with a tzinfo= argument.  Subclasses must define
-# theclass as a class atribute, and theclass(1, 1, 1, tzinfo=whatever)
+# theclass as a class attribute, and theclass(1, 1, 1, tzinfo=whatever)
 # must be legit (which is true for time and datetime).
 class TZInfoBase:
 
index 13ea02f..3e88168 100644 (file)
@@ -523,8 +523,8 @@ class TestBasic(unittest.TestCase):
     @test_support.cpython_only
     def test_sizeof(self):
         BLOCKLEN = 62
-        basesize = test_support.calcobjsize('2P4PlP')
-        blocksize = struct.calcsize('2P%dP' % BLOCKLEN)
+        basesize = test_support.calcobjsize('2P3PlPP')
+        blocksize = struct.calcsize('%dP2P' % BLOCKLEN)
         self.assertEqual(object.__sizeof__(deque()), basesize)
         check = self.check_sizeof
         check(deque(), basesize + blocksize)
@@ -669,6 +669,10 @@ class TestSubclassWithKwargs(unittest.TestCase):
         # SF bug #1486663 -- this used to erroneously raise a TypeError
         SubclassWithKwargs(newarg=1)
 
+    def test_free_after_iterating(self):
+        # For now, bypass tests that require slicing
+        self.skipTest("Exhausted deque iterator doesn't free a deque")
+
 #==============================================================================
 
 libreftest = """
index 25f65c5..9bc114b 100644 (file)
@@ -3723,7 +3723,7 @@ order (MRO) for bases """
         b.a = a
         z = deepcopy(a) # This blew up before
 
-    def test_unintialized_modules(self):
+    def test_uninitialized_modules(self):
         # Testing uninitialized module objects...
         from types import ModuleType as M
         m = M.__new__(M)
@@ -4699,6 +4699,7 @@ order (MRO) for bases """
         for o in gc.get_objects():
             self.assertIsNot(type(o), X)
 
+
 class DictProxyTests(unittest.TestCase):
     def setUp(self):
         class C(object):
@@ -4763,6 +4764,26 @@ class PTypesLongInitTest(unittest.TestCase):
         type.mro(tuple)
 
 
+class PicklingTests(unittest.TestCase):
+
+    def test_issue24097(self):
+        # Slot name is freed inside __getattr__ and is later used.
+        class S(str):  # Not interned
+            pass
+        class A(object):
+            __slotnames__ = [S('spam')]
+            def __getattr__(self, attr):
+                if attr == 'spam':
+                    A.__slotnames__[:] = [S('spam')]
+                    return 42
+                else:
+                    raise AttributeError
+
+        import copy_reg
+        expected = (copy_reg.__newobj__, (A,), ({}, {'spam': 42}), None, None)
+        self.assertEqual(A().__reduce__(2), expected)
+
+
 def test_main():
     deprecations = [(r'complex divmod\(\), // and % are deprecated$',
                      DeprecationWarning)]
@@ -4774,7 +4795,8 @@ def test_main():
     with test_support.check_warnings(*deprecations):
         # Run all local test cases, with PTypesLongInitTest first.
         test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
-                                  ClassPropertiesAndMethods, DictProxyTests)
+                                  ClassPropertiesAndMethods, DictProxyTests,
+                                  PicklingTests)
 
 if __name__ == "__main__":
     test_main()
index 1c63fc0..4474c9b 100644 (file)
@@ -681,6 +681,15 @@ class DictTest(unittest.TestCase):
         self._tracked(MyDict())
 
 
+    def test_free_after_iterating(self):
+        test_support.check_free_after_iterating(self, iter, dict)
+        test_support.check_free_after_iterating(self, lambda d: d.iterkeys(), dict)
+        test_support.check_free_after_iterating(self, lambda d: d.itervalues(), dict)
+        test_support.check_free_after_iterating(self, lambda d: d.iteritems(), dict)
+        test_support.check_free_after_iterating(self, lambda d: iter(d.viewkeys()), dict)
+        test_support.check_free_after_iterating(self, lambda d: iter(d.viewvalues()), dict)
+        test_support.check_free_after_iterating(self, lambda d: iter(d.viewitems()), dict)
+
 from test import mapping_tests
 
 class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
index 71f1af7..b585bdd 100644 (file)
@@ -98,6 +98,7 @@ class DictSetTest(unittest.TestCase):
         self.assertEqual(d1.viewkeys() & set(d1.viewkeys()), {'a', 'b'})
         self.assertEqual(d1.viewkeys() & set(d2.viewkeys()), {'b'})
         self.assertEqual(d1.viewkeys() & set(d3.viewkeys()), set())
+        self.assertEqual(d1.viewkeys() & tuple(d1.viewkeys()), {'a', 'b'})
 
         self.assertEqual(d1.viewkeys() | d1.viewkeys(), {'a', 'b'})
         self.assertEqual(d1.viewkeys() | d2.viewkeys(), {'a', 'b', 'c'})
@@ -106,6 +107,7 @@ class DictSetTest(unittest.TestCase):
         self.assertEqual(d1.viewkeys() | set(d2.viewkeys()), {'a', 'b', 'c'})
         self.assertEqual(d1.viewkeys() | set(d3.viewkeys()),
                          {'a', 'b', 'd', 'e'})
+        self.assertEqual(d1.viewkeys() | (1, 2), {'a', 'b', 1, 2})
 
         self.assertEqual(d1.viewkeys() ^ d1.viewkeys(), set())
         self.assertEqual(d1.viewkeys() ^ d2.viewkeys(), {'a', 'c'})
@@ -114,6 +116,7 @@ class DictSetTest(unittest.TestCase):
         self.assertEqual(d1.viewkeys() ^ set(d2.viewkeys()), {'a', 'c'})
         self.assertEqual(d1.viewkeys() ^ set(d3.viewkeys()),
                          {'a', 'b', 'd', 'e'})
+        self.assertEqual(d1.viewkeys() ^ tuple(d2.keys()), {'a', 'c'})
 
         self.assertEqual(d1.viewkeys() - d1.viewkeys(), set())
         self.assertEqual(d1.viewkeys() - d2.viewkeys(), {'a'})
@@ -121,6 +124,7 @@ class DictSetTest(unittest.TestCase):
         self.assertEqual(d1.viewkeys() - set(d1.viewkeys()), set())
         self.assertEqual(d1.viewkeys() - set(d2.viewkeys()), {'a'})
         self.assertEqual(d1.viewkeys() - set(d3.viewkeys()), {'a', 'b'})
+        self.assertEqual(d1.viewkeys() - (0, 1), {'a', 'b'})
 
     def test_items_set_operations(self):
         d1 = {'a': 1, 'b': 2}
index da5ba4b..1fcbd41 100644 (file)
@@ -12,11 +12,11 @@ def _f(a):
     return 1
 
 dis_f = """\
- %-4d         0 LOAD_FAST                0 (a)
+%3d           0 LOAD_FAST                0 (a)
               3 PRINT_ITEM
               4 PRINT_NEWLINE
 
- %-4d         5 LOAD_CONST               1 (1)
+%3d           5 LOAD_CONST               1 (1)
               8 RETURN_VALUE
 """%(_f.func_code.co_firstlineno + 1,
      _f.func_code.co_firstlineno + 2)
@@ -28,17 +28,17 @@ def bug708901():
         pass
 
 dis_bug708901 = """\
- %-4d         0 SETUP_LOOP              23 (to 26)
+%3d           0 SETUP_LOOP              23 (to 26)
               3 LOAD_GLOBAL              0 (range)
               6 LOAD_CONST               1 (1)
 
- %-4d         9 LOAD_CONST               2 (10)
+%3d           9 LOAD_CONST               2 (10)
              12 CALL_FUNCTION            2
              15 GET_ITER
         >>   16 FOR_ITER                 6 (to 25)
              19 STORE_FAST               0 (res)
 
- %-4d        22 JUMP_ABSOLUTE           16
+%3d          22 JUMP_ABSOLUTE           16
         >>   25 POP_BLOCK
         >>   26 LOAD_CONST               0 (None)
              29 RETURN_VALUE
@@ -53,7 +53,7 @@ def bug1333982(x=[]):
     pass
 
 dis_bug1333982 = """\
- %-4d         0 LOAD_CONST               1 (0)
+%3d           0 LOAD_CONST               1 (0)
               3 POP_JUMP_IF_TRUE        41
               6 LOAD_GLOBAL              0 (AssertionError)
               9 BUILD_LIST               0
@@ -65,12 +65,12 @@ dis_bug1333982 = """\
              25 LIST_APPEND              2
              28 JUMP_ABSOLUTE           16
 
- %-4d   >>   31 LOAD_CONST               2 (1)
+%3d     >>   31 LOAD_CONST               2 (1)
              34 BINARY_ADD
              35 CALL_FUNCTION            1
              38 RAISE_VARARGS            1
 
- %-4d   >>   41 LOAD_CONST               0 (None)
+%3d     >>   41 LOAD_CONST               0 (None)
              44 RETURN_VALUE
 """%(bug1333982.func_code.co_firstlineno + 1,
      bug1333982.func_code.co_firstlineno + 2,
index c1e4c13..7cf7d06 100644 (file)
@@ -322,7 +322,7 @@ containing test:
     >>> test.lineno + e2.lineno
     26
 
-If the docstring contains inconsistant leading whitespace in the
+If the docstring contains inconsistent leading whitespace in the
 expected output of an example, then `DocTest` will raise a ValueError:
 
     >>> docstring = r'''
@@ -951,7 +951,7 @@ the exception is in the output, but this will fail under Python 2:
         HTTPException: message
     TestResults(failed=1, attempted=2)
 
-But in Python 2 the module path is not included, an therefore a test must look
+But in Python 2 the module path is not included, and therefore a test must look
 like the following test to succeed in Python 2. But that test will fail under
 Python 3.
 
@@ -2582,7 +2582,7 @@ Windows line endings first:
     >>> fn = tempfile.mktemp()
     >>> with open(fn, 'wb') as f:
     ...     f.write('Test:\r\n\r\n  >>> x = 1 + 1\r\n\r\nDone.\r\n')
-    >>> doctest.testfile(fn, False)
+    >>> doctest.testfile(fn, module_relative=False, verbose=False)
     TestResults(failed=0, attempted=1)
     >>> os.remove(fn)
 
@@ -2591,7 +2591,7 @@ And now *nix line endings:
     >>> fn = tempfile.mktemp()
     >>> with open(fn, 'wb') as f:
     ...     f.write('Test:\n\n  >>> x = 1 + 1\n\nDone.\n')
-    >>> doctest.testfile(fn, False)
+    >>> doctest.testfile(fn, module_relative=False, verbose=False)
     TestResults(failed=0, attempted=1)
     >>> os.remove(fn)
 
index d9bdd3c..29a8531 100644 (file)
@@ -24,14 +24,14 @@ class LockTests(unittest.TestCase):
 
     def test_initlock(self):
         #Make sure locks start locked
-        self.assertTrue(not self.lock.locked(),
+        self.assertFalse(self.lock.locked(),
                         "Lock object is not initialized unlocked.")
 
     def test_release(self):
         # Test self.lock.release()
         self.lock.acquire()
         self.lock.release()
-        self.assertTrue(not self.lock.locked(),
+        self.assertFalse(self.lock.locked(),
                         "Lock object did not release properly.")
 
     def test_improper_release(self):
@@ -46,7 +46,7 @@ class LockTests(unittest.TestCase):
     def test_cond_acquire_fail(self):
         #Test acquiring locked lock returns False
         self.lock.acquire(0)
-        self.assertTrue(not self.lock.acquire(0),
+        self.assertFalse(self.lock.acquire(0),
                         "Conditional acquiring of a locked lock incorrectly "
                          "succeeded.")
 
@@ -58,9 +58,9 @@ class LockTests(unittest.TestCase):
 
     def test_uncond_acquire_return_val(self):
         #Make sure that an unconditional locking returns True.
-        self.assertTrue(self.lock.acquire(1) is True,
+        self.assertIs(self.lock.acquire(1), True,
                         "Unconditional locking did not return True.")
-        self.assertTrue(self.lock.acquire() is True)
+        self.assertIs(self.lock.acquire(), True)
 
     def test_uncond_acquire_blocking(self):
         #Make sure that unconditional acquiring of a locked lock blocks.
@@ -80,7 +80,7 @@ class LockTests(unittest.TestCase):
         end_time = int(time.time())
         if test_support.verbose:
             print "done"
-        self.assertTrue((end_time - start_time) >= DELAY,
+        self.assertGreaterEqual(end_time - start_time, DELAY,
                         "Blocking by unconditional acquiring failed.")
 
 class MiscTests(unittest.TestCase):
@@ -94,7 +94,7 @@ class MiscTests(unittest.TestCase):
         #Test sanity of _thread.get_ident()
         self.assertIsInstance(_thread.get_ident(), int,
                               "_thread.get_ident() returned a non-integer")
-        self.assertTrue(_thread.get_ident() != 0,
+        self.assertNotEqual(_thread.get_ident(), 0,
                         "_thread.get_ident() returned 0")
 
     def test_LockType(self):
@@ -164,7 +164,7 @@ class ThreadTests(unittest.TestCase):
         time.sleep(DELAY)
         if test_support.verbose:
             print 'done'
-        self.assertTrue(testing_queue.qsize() == thread_count,
+        self.assertEqual(testing_queue.qsize(), thread_count,
                         "Not all %s threads executed properly after %s sec." %
                         (thread_count, DELAY))
 
index b950031..bc8944d 100644 (file)
@@ -5,10 +5,15 @@ import sys
 import unittest
 import pickle, cPickle
 
-from test.test_support import (TESTFN, unlink, run_unittest, captured_output,
+from test.test_support import (TESTFN, unlink, run_unittest, captured_stderr,
                                check_warnings, cpython_only)
 from test.test_pep352 import ignore_deprecation_warnings
 
+class BrokenStrException(Exception):
+    def __str__(self):
+        raise Exception("str() is broken")
+    __repr__ = __str__  # Python 2's PyErr_WriteUnraisable() uses repr()
+
 # XXX This is not really enough, each *operation* should be tested!
 
 class ExceptionTests(unittest.TestCase):
@@ -375,7 +380,7 @@ class ExceptionTests(unittest.TestCase):
         # The test prints an unraisable recursion error when
         # doing "except ValueError", this is because subclass
         # checking has recursion checking too.
-        with captured_output("stderr"):
+        with captured_stderr():
             try:
                 g()
             except RuntimeError:
@@ -448,7 +453,7 @@ class ExceptionTests(unittest.TestCase):
             __metaclass__ = Meta
             pass
 
-        with captured_output("stderr") as stderr:
+        with captured_stderr() as stderr:
             try:
                 raise KeyError()
             except MyException, e:
@@ -460,7 +465,7 @@ class ExceptionTests(unittest.TestCase):
             else:
                 self.fail("Should have raised KeyError")
 
-        with captured_output("stderr") as stderr:
+        with captured_stderr() as stderr:
             def g():
                 try:
                     return g()
@@ -644,6 +649,62 @@ class TestSameStrAndUnicodeMsg(unittest.TestCase):
         self.assertEqual(error5.a, 1)
         self.assertEqual(error5.__doc__, "")
 
+    def test_unraisable(self):
+        # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
+        class BrokenDel:
+            def __del__(self):
+                exc = ValueError("del is broken")
+                # In Python 3, the following line would be in the report:
+                raise exc
+
+        class BrokenRepr(BrokenDel):
+            def __repr__(self):
+                raise AttributeError("repr() is broken")
+
+        class BrokenExceptionDel:
+            def __del__(self):
+                exc = BrokenStrException()
+                # In Python 3, the following line would be in the report:
+                raise exc
+
+        for test_class in (BrokenDel, BrokenRepr, BrokenExceptionDel):
+            obj = test_class()
+            with captured_stderr() as stderr:
+                del obj
+            report = stderr.getvalue()
+            self.assertRegexpMatches(report, "Exception.* ignored")
+            if test_class is BrokenRepr:
+                self.assertIn("<object repr() failed>", report)
+            else:
+                self.assertIn("__del__", report)
+            if test_class is BrokenExceptionDel:
+                self.assertIn("BrokenStrException", report)
+                self.assertIn("<exception repr() failed>", report)
+            else:
+                self.assertIn("ValueError", report)
+                self.assertIn("del is broken", report)
+            self.assertTrue(report.endswith("\n"))
+
+    def test_unhandled(self):
+        # Check for sensible reporting of unhandled exceptions
+        for exc_type in (ValueError, BrokenStrException):
+            try:
+                exc = exc_type("test message")
+                # The following line is included in the traceback report:
+                raise exc
+            except exc_type:
+                with captured_stderr() as stderr:
+                    sys.__excepthook__(*sys.exc_info())
+            report = stderr.getvalue()
+            self.assertIn("test_exceptions.py", report)
+            self.assertIn("raise exc", report)
+            self.assertIn(exc_type.__name__, report)
+            if exc_type is BrokenStrException:
+                self.assertIn("<exception str() failed>", report)
+            else:
+                self.assertIn("test message", report)
+            self.assertTrue(report.endswith("\n"))
+
 
 def test_main():
     run_unittest(ExceptionTests, TestSameStrAndUnicodeMsg)
index 80e09a0..cb2c45e 100644 (file)
@@ -93,7 +93,7 @@ Verify clearing of SF bug #733667
     >>> g(*Nothing())
     Traceback (most recent call last):
       ...
-    TypeError: g() argument after * must be a sequence, not instance
+    TypeError: g() argument after * must be an iterable, not instance
 
     >>> class Nothing:
     ...     def __len__(self): return 5
@@ -102,7 +102,7 @@ Verify clearing of SF bug #733667
     >>> g(*Nothing())
     Traceback (most recent call last):
       ...
-    TypeError: g() argument after * must be a sequence, not instance
+    TypeError: g() argument after * must be an iterable, not instance
 
     >>> class Nothing():
     ...     def __len__(self): return 5
@@ -128,6 +128,17 @@ Verify clearing of SF bug #733667
     >>> g(*Nothing())
     0 (1, 2, 3) {}
 
+Check for issue #4806: Does a TypeError in a generator get propagated with the
+right error message?
+
+    >>> def broken(): raise TypeError("myerror")
+    ...
+
+    >>> g(*(broken() for i in range(1)))
+    Traceback (most recent call last):
+      ...
+    TypeError: myerror
+
 Make sure that the function doesn't stomp the dictionary
 
     >>> d = {'a': 1, 'b': 2, 'c': 3}
@@ -167,17 +178,17 @@ What about willful misconduct?
     >>> h(*h)
     Traceback (most recent call last):
       ...
-    TypeError: h() argument after * must be a sequence, not function
+    TypeError: h() argument after * must be an iterable, not function
 
     >>> dir(*h)
     Traceback (most recent call last):
       ...
-    TypeError: dir() argument after * must be a sequence, not function
+    TypeError: dir() argument after * must be an iterable, not function
 
     >>> None(*h)
     Traceback (most recent call last):
       ...
-    TypeError: NoneType object argument after * must be a sequence, \
+    TypeError: NoneType object argument after * must be an iterable, \
 not function
 
     >>> h(**h)
@@ -271,7 +282,7 @@ the function call setup. See <http://bugs.python.org/issue2016>.
     >>> f(**x)
     1 2
 
-A obscure message:
+An obscure message:
 
     >>> def f(a, b):
     ...    pass
index facc56e..a6f0994 100644 (file)
@@ -5,7 +5,7 @@ Nick Mathewson
 
 import unittest
 from test.test_support import verbose, TESTFN, run_unittest
-from test.test_support import unlink as safe_unlink
+from test.test_support import unlink as safe_unlink, check_warnings
 import sys, re
 from StringIO import StringIO
 from fileinput import FileInput, hook_encoded
@@ -28,6 +28,42 @@ def remove_tempfiles(*names):
     for name in names:
         safe_unlink(name)
 
+class LineReader:
+
+    def __init__(self):
+        self._linesread = []
+
+    @property
+    def linesread(self):
+        try:
+            return self._linesread[:]
+        finally:
+            self._linesread = []
+
+    def openhook(self, filename, mode):
+        self.it = iter(filename.splitlines(True))
+        return self
+
+    def readline(self, size=None):
+        line = next(self.it, '')
+        self._linesread.append(line)
+        return line
+
+    def readlines(self, hint=-1):
+        lines = []
+        size = 0
+        while True:
+            line = self.readline()
+            if not line:
+                return lines
+            lines.append(line)
+            size += len(line)
+            if size >= hint:
+                return lines
+
+    def close(self):
+        pass
+
 class BufferSizesTests(unittest.TestCase):
     def test_buffer_sizes(self):
         # First, run the tests with default and teeny buffer size.
@@ -228,7 +264,7 @@ class FileInputTests(unittest.TestCase):
             f.write('\x80')
         self.addCleanup(safe_unlink, TESTFN)
 
-        fi = FileInput(files=TESTFN, openhook=hook_encoded('ascii'), bufsize=8)
+        fi = FileInput(files=TESTFN, openhook=hook_encoded('ascii'))
         # The most likely failure is a UnicodeDecodeError due to the entire
         # file being read when it shouldn't have been.
         self.assertEqual(fi.readline(), u'A\n')
@@ -239,6 +275,38 @@ class FileInputTests(unittest.TestCase):
             list(fi)
         fi.close()
 
+    def test_readline_buffering(self):
+        src = LineReader()
+        fi = FileInput(files=['line1\nline2', 'line3\n'], openhook=src.openhook)
+        self.assertEqual(src.linesread, [])
+        self.assertEqual(fi.readline(), 'line1\n')
+        self.assertEqual(src.linesread, ['line1\n'])
+        self.assertEqual(fi.readline(), 'line2')
+        self.assertEqual(src.linesread, ['line2'])
+        self.assertEqual(fi.readline(), 'line3\n')
+        self.assertEqual(src.linesread, ['', 'line3\n'])
+        self.assertEqual(fi.readline(), '')
+        self.assertEqual(src.linesread, [''])
+        self.assertEqual(fi.readline(), '')
+        self.assertEqual(src.linesread, [])
+        fi.close()
+
+    def test_iteration_buffering(self):
+        src = LineReader()
+        fi = FileInput(files=['line1\nline2', 'line3\n'], openhook=src.openhook)
+        self.assertEqual(src.linesread, [])
+        self.assertEqual(next(fi), 'line1\n')
+        self.assertEqual(src.linesread, ['line1\n'])
+        self.assertEqual(next(fi), 'line2')
+        self.assertEqual(src.linesread, ['line2'])
+        self.assertEqual(next(fi), 'line3\n')
+        self.assertEqual(src.linesread, ['', 'line3\n'])
+        self.assertRaises(StopIteration, next, fi)
+        self.assertEqual(src.linesread, [''])
+        self.assertRaises(StopIteration, next, fi)
+        self.assertEqual(src.linesread, [])
+        fi.close()
+
 class Test_hook_encoded(unittest.TestCase):
     """Unit tests for fileinput.hook_encoded()"""
 
index 4224306..c917c1e 100644 (file)
@@ -27,6 +27,12 @@ requires_IEEE_754 = unittest.skipUnless(have_getformat and
 test_dir = os.path.dirname(__file__) or os.curdir
 format_testfile = os.path.join(test_dir, 'formatfloat_testcases.txt')
 
+class FloatSubclass(float):
+    pass
+
+class OtherFloatSubclass(float):
+    pass
+
 class GeneralFloatCases(unittest.TestCase):
 
     def test_float(self):
@@ -65,7 +71,8 @@ class GeneralFloatCases(unittest.TestCase):
             factories += [unicode, CustomUnicode]
 
         for f in factories:
-            x = f(" 3.14  ")
+            with test_support.check_py3k_warnings(quiet=True):
+                x = f(" 3.14  ")
             msg = 'x has value %s and type %s' % (x, type(x).__name__)
             try:
                 self.assertEqual(float(x), 3.14, msg=msg)
@@ -73,15 +80,17 @@ class GeneralFloatCases(unittest.TestCase):
                 raise AssertionError('For %s got TypeError: %s' %
                                      (type(x).__name__, err))
             errmsg = "could not convert"
-            with self.assertRaisesRegexp(ValueError, errmsg, msg=msg):
+            with self.assertRaisesRegexp(ValueError, errmsg, msg=msg), \
+                 test_support.check_py3k_warnings(quiet=True):
                 float(f('A' * 0x10))
 
     def test_float_buffer(self):
-        self.assertEqual(float(buffer('12.3', 1, 3)), 2.3)
-        self.assertEqual(float(buffer('12.3\x00', 1, 3)), 2.3)
-        self.assertEqual(float(buffer('12.3 ', 1, 3)), 2.3)
-        self.assertEqual(float(buffer('12.3A', 1, 3)), 2.3)
-        self.assertEqual(float(buffer('12.34', 1, 3)), 2.3)
+        with test_support.check_py3k_warnings():
+            self.assertEqual(float(buffer('12.3', 1, 3)), 2.3)
+            self.assertEqual(float(buffer('12.3\x00', 1, 3)), 2.3)
+            self.assertEqual(float(buffer('12.3 ', 1, 3)), 2.3)
+            self.assertEqual(float(buffer('12.3A', 1, 3)), 2.3)
+            self.assertEqual(float(buffer('12.34', 1, 3)), 2.3)
 
     def check_conversion_to_int(self, x):
         """Check that int(x) has the correct value and type, for a float x."""
@@ -200,6 +209,15 @@ class GeneralFloatCases(unittest.TestCase):
                 return ""
         self.assertRaises(TypeError, time.sleep, Foo5())
 
+        # Issue #24731
+        class F:
+            def __float__(self):
+                return OtherFloatSubclass(42.)
+        self.assertAlmostEqual(float(F()), 42.)
+        self.assertIs(type(float(F())), OtherFloatSubclass)
+        self.assertAlmostEqual(FloatSubclass(F()), 42.)
+        self.assertIs(type(FloatSubclass(F())), FloatSubclass)
+
     def test_is_integer(self):
         self.assertFalse((1.1).is_integer())
         self.assertTrue((1.).is_integer())
index ba3399e..633601c 100644 (file)
@@ -243,6 +243,7 @@ class FormatTest(unittest.TestCase):
 
         fst = IntFails()
         testformat("%x", fst, '0')
+        testformat(u"%x", fst, '0')
 
         # Test exception for unknown format characters
         if verbose:
index 7b3cb96..69176f4 100644 (file)
@@ -1,3 +1,4 @@
+import copy
 import functools
 import sys
 import unittest
@@ -25,6 +26,16 @@ def signature(part):
     """ return the signature of a partial object """
     return (part.func, part.args, part.keywords, part.__dict__)
 
+class MyTuple(tuple):
+    pass
+
+class BadTuple(tuple):
+    def __add__(self, other):
+        return list(self) + list(other)
+
+class MyDict(dict):
+    pass
+
 class TestPartial(unittest.TestCase):
 
     thetype = functools.partial
@@ -146,11 +157,84 @@ class TestPartial(unittest.TestCase):
         self.assertEqual(join(data), '0123456789')
 
     def test_pickle(self):
-        f = self.thetype(signature, 'asdf', bar=True)
-        f.add_something_to__dict__ = True
+        f = self.thetype(signature, ['asdf'], bar=[True])
+        f.attr = []
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             f_copy = pickle.loads(pickle.dumps(f, proto))
-            self.assertEqual(signature(f), signature(f_copy))
+            self.assertEqual(signature(f_copy), signature(f))
+
+    def test_copy(self):
+        f = self.thetype(signature, ['asdf'], bar=[True])
+        f.attr = []
+        f_copy = copy.copy(f)
+        self.assertEqual(signature(f_copy), signature(f))
+        self.assertIs(f_copy.attr, f.attr)
+        self.assertIs(f_copy.args, f.args)
+        self.assertIs(f_copy.keywords, f.keywords)
+
+    def test_deepcopy(self):
+        f = self.thetype(signature, ['asdf'], bar=[True])
+        f.attr = []
+        f_copy = copy.deepcopy(f)
+        self.assertEqual(signature(f_copy), signature(f))
+        self.assertIsNot(f_copy.attr, f.attr)
+        self.assertIsNot(f_copy.args, f.args)
+        self.assertIsNot(f_copy.args[0], f.args[0])
+        self.assertIsNot(f_copy.keywords, f.keywords)
+        self.assertIsNot(f_copy.keywords['bar'], f.keywords['bar'])
+
+    def test_setstate(self):
+        f = self.thetype(signature)
+        f.__setstate__((capture, (1,), dict(a=10), dict(attr=[])))
+        self.assertEqual(signature(f),
+                         (capture, (1,), dict(a=10), dict(attr=[])))
+        self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
+
+        f.__setstate__((capture, (1,), dict(a=10), None))
+        self.assertEqual(signature(f), (capture, (1,), dict(a=10), {}))
+        self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20}))
+
+        f.__setstate__((capture, (1,), None, None))
+        #self.assertEqual(signature(f), (capture, (1,), {}, {}))
+        self.assertEqual(f(2, b=20), ((1, 2), {'b': 20}))
+        self.assertEqual(f(2), ((1, 2), {}))
+        self.assertEqual(f(), ((1,), {}))
+
+        f.__setstate__((capture, (), {}, None))
+        self.assertEqual(signature(f), (capture, (), {}, {}))
+        self.assertEqual(f(2, b=20), ((2,), {'b': 20}))
+        self.assertEqual(f(2), ((2,), {}))
+        self.assertEqual(f(), ((), {}))
+
+    def test_setstate_errors(self):
+        f = self.thetype(signature)
+        self.assertRaises(TypeError, f.__setstate__, (capture, (), {}))
+        self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, {}, None))
+        self.assertRaises(TypeError, f.__setstate__, [capture, (), {}, None])
+        self.assertRaises(TypeError, f.__setstate__, (None, (), {}, None))
+        self.assertRaises(TypeError, f.__setstate__, (capture, None, {}, None))
+        self.assertRaises(TypeError, f.__setstate__, (capture, [], {}, None))
+        self.assertRaises(TypeError, f.__setstate__, (capture, (), [], None))
+
+    def test_setstate_subclasses(self):
+        f = self.thetype(signature)
+        f.__setstate__((capture, MyTuple((1,)), MyDict(a=10), None))
+        s = signature(f)
+        self.assertEqual(s, (capture, (1,), dict(a=10), {}))
+        self.assertIs(type(s[1]), tuple)
+        self.assertIs(type(s[2]), dict)
+        r = f()
+        self.assertEqual(r, ((1,), {'a': 10}))
+        self.assertIs(type(r[0]), tuple)
+        self.assertIs(type(r[1]), dict)
+
+        f.__setstate__((capture, BadTuple((1,)), {}, None))
+        s = signature(f)
+        self.assertEqual(s, (capture, (1,), {}, {}))
+        self.assertIs(type(s[1]), tuple)
+        r = f(2)
+        self.assertEqual(r, ((1, 2), {}))
+        self.assertIs(type(r[0]), tuple)
 
     # Issue 6083: Reference counting bug
     def test_setstate_refcount(self):
@@ -167,7 +251,7 @@ class TestPartial(unittest.TestCase):
                 raise IndexError
 
         f = self.thetype(object)
-        self.assertRaises(SystemError, f.__setstate__, BadSequence())
+        self.assertRaises(TypeError, f.__setstate__, BadSequence())
 
 class PartialSubclass(functools.partial):
     pass
@@ -181,7 +265,14 @@ class TestPythonPartial(TestPartial):
     thetype = PythonPartial
 
     # the python version isn't picklable
-    test_pickle = test_setstate_refcount = None
+    test_pickle = None
+    test_setstate = None
+    test_setstate_errors = None
+    test_setstate_subclasses = None
+    test_setstate_refcount = None
+
+    # the python version isn't deepcopyable
+    test_deepcopy = None
 
     # the python version isn't a type
     test_attributes = None
index 8a56118..f157eae 100644 (file)
@@ -71,6 +71,8 @@ def run_gdb(*args, **env_vars):
     if (gdb_major_version, gdb_minor_version) >= (7, 4):
         base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
     out, err = subprocess.Popen(base_cmd + args,
+        # Redirect stdin to prevent GDB from messing with terminal settings
+        stdin=subprocess.PIPE,
         stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
         ).communicate()
     return out, err
index 27399f7..5e1a3e5 100644 (file)
@@ -1094,7 +1094,7 @@ class Queens:
 
         # For each square, compute a bit vector of the columns and
         # diagonals it covers, and for each row compute a function that
-        # generates the possiblities for the columns in that row.
+        # generates the possibilities for the columns in that row.
         self.rowgenerators = []
         for i in rangen:
             rowuses = [(1L << j) |                  # column ordinal
index aba304a..2b2fa60 100644 (file)
@@ -1,4 +1,6 @@
 import unittest
+import math
+import sys
 from test import test_support
 # Skip this test if the _testcapi module isn't available.
 test_support.import_module('_testcapi')
@@ -42,7 +44,11 @@ VERY_LARGE = 0xFF0000121212121212121242L
 
 from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \
      INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, \
-     SHRT_MIN, SHRT_MAX
+     SHRT_MIN, SHRT_MAX, FLT_MIN, FLT_MAX, DBL_MIN, DBL_MAX
+
+DBL_MAX_EXP = sys.float_info.max_exp
+INF = float('inf')
+NAN = float('nan')
 
 try:
     from _testcapi import getargs_L, getargs_K
@@ -64,6 +70,61 @@ class Int:
     def __int__(self):
         return 99
 
+
+class Float:
+    def __float__(self):
+        return 4.25
+
+class FloatSubclass(float):
+    pass
+
+class FloatSubclass2(float):
+    def __float__(self):
+        return 4.25
+
+class BadFloat:
+    def __float__(self):
+        return 687
+
+class BadFloat2:
+    def __float__(self):
+        return FloatSubclass(4.25)
+
+class BadFloat3(float):
+    def __float__(self):
+        return FloatSubclass(4.25)
+
+
+class Complex:
+    def __complex__(self):
+        return 4.25+0.5j
+
+class ComplexSubclass(complex):
+    pass
+
+class ComplexSubclass2(complex):
+    def __complex__(self):
+        return 4.25+0.5j
+
+class BadComplex:
+    def __complex__(self):
+        return 1.25
+
+class BadComplex2:
+    def __complex__(self):
+        return ComplexSubclass(4.25+0.5j)
+
+class BadComplex3(complex):
+    def __complex__(self):
+        return ComplexSubclass(4.25+0.5j)
+
+
+class TupleSubclass(tuple):
+    pass
+
+class DictSubclass(dict):
+    pass
+
 class Unsigned_TestCase(unittest.TestCase):
     def test_b(self):
         from _testcapi import getargs_b
@@ -267,7 +328,108 @@ class LongLong_TestCase(unittest.TestCase):
         self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))
 
 
+class Float_TestCase(unittest.TestCase):
+    def assertEqualWithSign(self, actual, expected):
+        self.assertEqual(actual, expected)
+        self.assertEqual(math.copysign(1, actual), math.copysign(1, expected))
+
+    def test_f(self):
+        from _testcapi import getargs_f
+        self.assertEqual(getargs_f(4.25), 4.25)
+        self.assertEqual(getargs_f(4), 4.0)
+        self.assertRaises(TypeError, getargs_f, 4.25+0j)
+        self.assertEqual(getargs_f(Float()), 4.25)
+        self.assertEqual(getargs_f(FloatSubclass(7.5)), 7.5)
+        self.assertEqual(getargs_f(FloatSubclass2(7.5)), 7.5)
+        self.assertRaises(TypeError, getargs_f, BadFloat())
+        self.assertEqual(getargs_f(BadFloat2()), 4.25)
+        self.assertEqual(getargs_f(BadFloat3(7.5)), 7.5)
+
+        for x in (FLT_MIN, -FLT_MIN, FLT_MAX, -FLT_MAX, INF, -INF):
+            self.assertEqual(getargs_f(x), x)
+        if FLT_MAX < DBL_MAX:
+            self.assertEqual(getargs_f(DBL_MAX), INF)
+            self.assertEqual(getargs_f(-DBL_MAX), -INF)
+        if FLT_MIN > DBL_MIN:
+            self.assertEqualWithSign(getargs_f(DBL_MIN), 0.0)
+            self.assertEqualWithSign(getargs_f(-DBL_MIN), -0.0)
+        self.assertEqualWithSign(getargs_f(0.0), 0.0)
+        self.assertEqualWithSign(getargs_f(-0.0), -0.0)
+        r = getargs_f(NAN)
+        self.assertNotEqual(r, r)
+
+    def test_d(self):
+        from _testcapi import getargs_d
+        self.assertEqual(getargs_d(4.25), 4.25)
+        self.assertEqual(getargs_d(4), 4.0)
+        self.assertRaises(TypeError, getargs_d, 4.25+0j)
+        self.assertEqual(getargs_d(Float()), 4.25)
+        self.assertEqual(getargs_d(FloatSubclass(7.5)), 7.5)
+        self.assertEqual(getargs_d(FloatSubclass2(7.5)), 7.5)
+        self.assertRaises(TypeError, getargs_d, BadFloat())
+        self.assertEqual(getargs_d(BadFloat2()), 4.25)
+        self.assertEqual(getargs_d(BadFloat3(7.5)), 7.5)
+
+        for x in (DBL_MIN, -DBL_MIN, DBL_MAX, -DBL_MAX, INF, -INF):
+            self.assertEqual(getargs_d(x), x)
+        self.assertRaises(OverflowError, getargs_d, 1<<DBL_MAX_EXP)
+        self.assertRaises(OverflowError, getargs_d, -1<<DBL_MAX_EXP)
+        self.assertEqualWithSign(getargs_d(0.0), 0.0)
+        self.assertEqualWithSign(getargs_d(-0.0), -0.0)
+        r = getargs_d(NAN)
+        self.assertNotEqual(r, r)
+
+    def test_D(self):
+        from _testcapi import getargs_D
+        self.assertEqual(getargs_D(4.25+0.5j), 4.25+0.5j)
+        self.assertEqual(getargs_D(4.25), 4.25+0j)
+        self.assertEqual(getargs_D(4), 4.0+0j)
+        self.assertEqual(getargs_D(Complex()), 4.25+0.5j)
+        self.assertEqual(getargs_D(ComplexSubclass(7.5+0.25j)), 7.5+0.25j)
+        self.assertEqual(getargs_D(ComplexSubclass2(7.5+0.25j)), 7.5+0.25j)
+        self.assertRaises(TypeError, getargs_D, BadComplex())
+        self.assertEqual(getargs_D(BadComplex2()), 4.25+0.5j)
+        self.assertEqual(getargs_D(BadComplex3(7.5+0.25j)), 7.5+0.25j)
+
+        for x in (DBL_MIN, -DBL_MIN, DBL_MAX, -DBL_MAX, INF, -INF):
+            c = complex(x, 1.0)
+            self.assertEqual(getargs_D(c), c)
+            c = complex(1.0, x)
+            self.assertEqual(getargs_D(c), c)
+        self.assertEqualWithSign(getargs_D(complex(0.0, 1.0)).real, 0.0)
+        self.assertEqualWithSign(getargs_D(complex(-0.0, 1.0)).real, -0.0)
+        self.assertEqualWithSign(getargs_D(complex(1.0, 0.0)).imag, 0.0)
+        self.assertEqualWithSign(getargs_D(complex(1.0, -0.0)).imag, -0.0)
+
+
 class Tuple_TestCase(unittest.TestCase):
+    def test_args(self):
+        from _testcapi import get_args
+
+        ret = get_args(1, 2)
+        self.assertEqual(ret, (1, 2))
+        self.assertIs(type(ret), tuple)
+
+        ret = get_args(1, *(2, 3))
+        self.assertEqual(ret, (1, 2, 3))
+        self.assertIs(type(ret), tuple)
+
+        ret = get_args(*[1, 2])
+        self.assertEqual(ret, (1, 2))
+        self.assertIs(type(ret), tuple)
+
+        ret = get_args(*TupleSubclass([1, 2]))
+        self.assertEqual(ret, (1, 2))
+        self.assertIsInstance(ret, tuple)
+
+        ret = get_args()
+        self.assertIn(ret, ((), None))
+        self.assertIn(type(ret), (tuple, type(None)))
+
+        ret = get_args(*())
+        self.assertIn(ret, ((), None))
+        self.assertIn(type(ret), (tuple, type(None)))
+
     def test_tuple(self):
         from _testcapi import getargs_tuple
 
@@ -283,6 +445,29 @@ class Tuple_TestCase(unittest.TestCase):
         self.assertRaises(TypeError, getargs_tuple, 1, seq())
 
 class Keywords_TestCase(unittest.TestCase):
+    def test_kwargs(self):
+        from _testcapi import get_kwargs
+
+        ret = get_kwargs(a=1, b=2)
+        self.assertEqual(ret, {'a': 1, 'b': 2})
+        self.assertIs(type(ret), dict)
+
+        ret = get_kwargs(a=1, **{'b': 2, 'c': 3})
+        self.assertEqual(ret, {'a': 1, 'b': 2, 'c': 3})
+        self.assertIs(type(ret), dict)
+
+        ret = get_kwargs(**DictSubclass({'a': 1, 'b': 2}))
+        self.assertEqual(ret, {'a': 1, 'b': 2})
+        self.assertIsInstance(ret, dict)
+
+        ret = get_kwargs()
+        self.assertIn(ret, ({}, None))
+        self.assertIn(type(ret), (dict, type(None)))
+
+        ret = get_kwargs(**{})
+        self.assertIn(ret, ({}, None))
+        self.assertIn(type(ret), (dict, type(None)))
+
     def test_positional_args(self):
         # using all positional args
         self.assertEqual(
@@ -331,10 +516,329 @@ class Keywords_TestCase(unittest.TestCase):
         else:
             self.fail('TypeError should have been raised')
 
+
+class Bytes_TestCase(unittest.TestCase):
+    def test_c(self):
+        from _testcapi import getargs_c
+        self.assertRaises(TypeError, getargs_c, 'abc')  # len > 1
+        self.assertEqual(getargs_c('a'), 97)
+        if test_support.have_unicode:
+            self.assertRaises(TypeError, getargs_c, u's')
+        self.assertRaises(TypeError, getargs_c, bytearray('a'))
+        self.assertRaises(TypeError, getargs_c, memoryview('a'))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_c, buffer('a'))
+        self.assertRaises(TypeError, getargs_c, 97)
+        self.assertRaises(TypeError, getargs_c, None)
+
+    def test_w(self):
+        from _testcapi import getargs_w
+        self.assertRaises(TypeError, getargs_w, 'abc', 3)
+        self.assertRaises(TypeError, getargs_w, u'abc', 3)
+        self.assertRaises(TypeError, getargs_w, bytearray('bytes'), 3)
+        self.assertRaises(TypeError, getargs_w, memoryview('bytes'), 3)
+        self.assertRaises(TypeError, getargs_w,
+                          memoryview(bytearray('bytes')), 3)
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_w, buffer('bytes'), 3)
+            self.assertRaises(TypeError, getargs_w,
+                              buffer(bytearray('bytes')), 3)
+        self.assertRaises(TypeError, getargs_w, None, 0)
+
+    def test_w_hash(self):
+        from _testcapi import getargs_w_hash
+        self.assertRaises(TypeError, getargs_w_hash, 'abc')
+        self.assertRaises(TypeError, getargs_w_hash, u'abc')
+        self.assertRaises(TypeError, getargs_w_hash, bytearray('bytes'))
+        self.assertRaises(TypeError, getargs_w_hash, memoryview('bytes'))
+        self.assertRaises(TypeError, getargs_w_hash,
+                          memoryview(bytearray('bytes')))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_w_hash, buffer('bytes'))
+            self.assertRaises(TypeError, getargs_w_hash,
+                              buffer(bytearray('bytes')))
+        self.assertRaises(TypeError, getargs_w_hash, None)
+
+    def test_w_star(self):
+        # getargs_w_star() modifies first and last byte
+        from _testcapi import getargs_w_star
+        self.assertRaises(TypeError, getargs_w_star, 'abc')
+        self.assertRaises(TypeError, getargs_w_star, u'abc')
+        self.assertRaises(TypeError, getargs_w_star, memoryview('bytes'))
+        buf = bytearray('bytearray')
+        self.assertEqual(getargs_w_star(buf), '[ytearra]')
+        self.assertEqual(buf, bytearray('[ytearra]'))
+        buf = bytearray(b'memoryview')
+        self.assertEqual(getargs_w_star(memoryview(buf)), '[emoryvie]')
+        self.assertEqual(buf, bytearray('[emoryvie]'))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_w_star, buffer('buffer'))
+            self.assertRaises(TypeError, getargs_w_star,
+                              buffer(bytearray('buffer')))
+        self.assertRaises(TypeError, getargs_w_star, None)
+
+
+class String_TestCase(unittest.TestCase):
+    def test_s(self):
+        from _testcapi import getargs_s
+        self.assertEqual(getargs_s('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_s(u'abc'), 'abc')
+        self.assertRaises(TypeError, getargs_s, 'nul:\0')
+        self.assertRaises(TypeError, getargs_s, u'nul:\0')
+        self.assertRaises(TypeError, getargs_s, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_s, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_s, buffer('buffer'))
+        self.assertRaises(TypeError, getargs_s, None)
+
+    def test_s_star(self):
+        from _testcapi import getargs_s_star
+        self.assertEqual(getargs_s_star('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_s_star(u'abc'), 'abc')
+        self.assertEqual(getargs_s_star('nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_s_star(u'nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_s_star(bytearray('abc\xe9')), 'abc\xe9')
+        self.assertEqual(getargs_s_star(memoryview('abc\xe9')), 'abc\xe9')
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_s_star(buffer('abc\xe9')), 'abc\xe9')
+            self.assertEqual(getargs_s_star(buffer(u'abc\xe9')),
+                             str(buffer(u'abc\xe9')))
+        self.assertRaises(TypeError, getargs_s_star, None)
+
+    def test_s_hash(self):
+        from _testcapi import getargs_s_hash
+        self.assertEqual(getargs_s_hash('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_s_hash(u'abc'), 'abc')
+        self.assertEqual(getargs_s_hash('nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_s_hash(u'nul:\0'), 'nul:\0')
+        self.assertRaises(TypeError, getargs_s_hash, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_s_hash, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_s_hash(buffer('abc\xe9')), 'abc\xe9')
+            self.assertEqual(getargs_s_hash(buffer(u'abc\xe9')),
+                             str(buffer(u'abc\xe9')))
+        self.assertRaises(TypeError, getargs_s_hash, None)
+
+    def test_t_hash(self):
+        from _testcapi import getargs_t_hash
+        self.assertEqual(getargs_t_hash('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_t_hash(u'abc'), 'abc')
+        self.assertEqual(getargs_t_hash('nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_t_hash(u'nul:\0'), 'nul:\0')
+        self.assertRaises(TypeError, getargs_t_hash, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_t_hash, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_t_hash(buffer('abc\xe9')), 'abc\xe9')
+            self.assertEqual(getargs_t_hash(buffer(u'abc')), 'abc')
+        self.assertRaises(TypeError, getargs_t_hash, None)
+
+    def test_z(self):
+        from _testcapi import getargs_z
+        self.assertEqual(getargs_z('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_z(u'abc'), 'abc')
+        self.assertRaises(TypeError, getargs_z, 'nul:\0')
+        self.assertRaises(TypeError, getargs_z, u'nul:\0')
+        self.assertRaises(TypeError, getargs_z, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_z, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_z, buffer('buffer'))
+        self.assertIsNone(getargs_z(None))
+
+    def test_z_star(self):
+        from _testcapi import getargs_z_star
+        self.assertEqual(getargs_z_star('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_z_star(u'abc'), 'abc')
+        self.assertEqual(getargs_z_star('nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_z_star(u'nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_z_star(bytearray('abc\xe9')), 'abc\xe9')
+        self.assertEqual(getargs_z_star(memoryview('abc\xe9')), 'abc\xe9')
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_z_star(buffer('abc\xe9')), 'abc\xe9')
+            self.assertEqual(getargs_z_star(buffer(u'abc\xe9')),
+                             str(buffer(u'abc\xe9')))
+        self.assertIsNone(getargs_z_star(None))
+
+    def test_z_hash(self):
+        from _testcapi import getargs_z_hash
+        self.assertEqual(getargs_z_hash('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_z_hash(u'abc'), 'abc')
+        self.assertEqual(getargs_z_hash('nul:\0'), 'nul:\0')
+        self.assertEqual(getargs_z_hash(u'nul:\0'), 'nul:\0')
+        self.assertRaises(TypeError, getargs_z_hash, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_z_hash, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_z_hash(buffer('abc\xe9')), 'abc\xe9')
+            self.assertEqual(getargs_z_hash(buffer(u'abc\xe9')),
+                             str(buffer(u'abc\xe9')))
+        self.assertIsNone(getargs_z_hash(None))
+
+
+@test_support.requires_unicode
+class Unicode_TestCase(unittest.TestCase):
+    def test_es(self):
+        from _testcapi import getargs_es
+        self.assertEqual(getargs_es('abc'), 'abc')
+        self.assertEqual(getargs_es(u'abc'), 'abc')
+        self.assertEqual(getargs_es('abc', 'ascii'), 'abc')
+        self.assertEqual(getargs_es(u'abc\xe9', 'latin1'), 'abc\xe9')
+        self.assertRaises(UnicodeEncodeError, getargs_es, u'abc\xe9', 'ascii')
+        self.assertRaises(LookupError, getargs_es, u'abc', 'spam')
+        self.assertRaises(TypeError, getargs_es,
+                          bytearray('bytearray'), 'latin1')
+        self.assertRaises(TypeError, getargs_es,
+                          memoryview('memoryview'), 'latin1')
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_es(buffer('abc'), 'ascii'), 'abc')
+            self.assertEqual(getargs_es(buffer(u'abc'), 'ascii'), 'abc')
+        self.assertRaises(TypeError, getargs_es, None, 'latin1')
+        self.assertRaises(TypeError, getargs_es, 'nul:\0', 'latin1')
+        self.assertRaises(TypeError, getargs_es, u'nul:\0', 'latin1')
+
+    def test_et(self):
+        from _testcapi import getargs_et
+        self.assertEqual(getargs_et('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_et(u'abc'), 'abc')
+        self.assertEqual(getargs_et('abc', 'ascii'), 'abc')
+        self.assertEqual(getargs_et('abc\xe9', 'ascii'), 'abc\xe9')
+        self.assertEqual(getargs_et(u'abc\xe9', 'latin1'), 'abc\xe9')
+        self.assertRaises(UnicodeEncodeError, getargs_et, u'abc\xe9', 'ascii')
+        self.assertRaises(LookupError, getargs_et, u'abc', 'spam')
+        self.assertRaises(TypeError, getargs_et,
+                          bytearray('bytearray'), 'latin1')
+        self.assertRaises(TypeError, getargs_et,
+                          memoryview('memoryview'), 'latin1')
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_et(buffer('abc'), 'ascii'), 'abc')
+            self.assertEqual(getargs_et(buffer(u'abc'), 'ascii'), 'abc')
+        self.assertRaises(TypeError, getargs_et, None, 'latin1')
+        self.assertRaises(TypeError, getargs_et, 'nul:\0', 'latin1')
+        self.assertRaises(TypeError, getargs_et, u'nul:\0', 'latin1')
+
+    def test_es_hash(self):
+        from _testcapi import getargs_es_hash
+        self.assertEqual(getargs_es_hash('abc'), 'abc')
+        self.assertEqual(getargs_es_hash(u'abc'), 'abc')
+        self.assertEqual(getargs_es_hash(u'abc\xe9', 'latin1'), 'abc\xe9')
+        self.assertRaises(UnicodeEncodeError, getargs_es_hash, u'abc\xe9', 'ascii')
+        self.assertRaises(LookupError, getargs_es_hash, u'abc', 'spam')
+        self.assertRaises(TypeError, getargs_es_hash,
+                          bytearray('bytearray'), 'latin1')
+        self.assertRaises(TypeError, getargs_es_hash,
+                          memoryview('memoryview'), 'latin1')
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_es_hash(buffer('abc'), 'ascii'), 'abc')
+            self.assertEqual(getargs_es_hash(buffer(u'abc'), 'ascii'), 'abc')
+        self.assertRaises(TypeError, getargs_es_hash, None, 'latin1')
+        self.assertEqual(getargs_es_hash('nul:\0', 'latin1'), 'nul:\0')
+        self.assertEqual(getargs_es_hash(u'nul:\0', 'latin1'), 'nul:\0')
+
+        buf = bytearray('x'*8)
+        self.assertEqual(getargs_es_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9')
+        self.assertEqual(buf, bytearray('abc\xe9\x00xxx'))
+        buf = bytearray('x'*5)
+        self.assertEqual(getargs_es_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9')
+        self.assertEqual(buf, bytearray('abc\xe9\x00'))
+        buf = bytearray('x'*4)
+        self.assertRaises(TypeError, getargs_es_hash, u'abc\xe9', 'latin1', buf)
+        self.assertEqual(buf, bytearray('x'*4))
+        buf = bytearray()
+        self.assertRaises(TypeError, getargs_es_hash, u'abc\xe9', 'latin1', buf)
+
+    def test_et_hash(self):
+        from _testcapi import getargs_et_hash
+        self.assertEqual(getargs_et_hash('abc\xe9'), 'abc\xe9')
+        self.assertEqual(getargs_et_hash(u'abc'), 'abc')
+        self.assertEqual(getargs_et_hash('abc\xe9', 'ascii'), 'abc\xe9')
+        self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1'), 'abc\xe9')
+        self.assertRaises(UnicodeEncodeError, getargs_et_hash,
+                          u'abc\xe9', 'ascii')
+        self.assertRaises(LookupError, getargs_et_hash, u'abc', 'spam')
+        self.assertRaises(TypeError, getargs_et_hash,
+                          bytearray('bytearray'), 'latin1')
+        self.assertRaises(TypeError, getargs_et_hash,
+                          memoryview('memoryview'), 'latin1')
+        with test_support.check_py3k_warnings():
+            self.assertEqual(getargs_et_hash(buffer('abc'), 'ascii'), 'abc')
+            self.assertEqual(getargs_et_hash(buffer(u'abc'), 'ascii'), 'abc')
+        self.assertRaises(TypeError, getargs_et_hash, None, 'latin1')
+        self.assertEqual(getargs_et_hash('nul:\0', 'latin1'), 'nul:\0')
+        self.assertEqual(getargs_et_hash(u'nul:\0', 'latin1'), 'nul:\0')
+
+        buf = bytearray('x'*8)
+        self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9')
+        self.assertEqual(buf, bytearray('abc\xe9\x00xxx'))
+        buf = bytearray('x'*5)
+        self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9')
+        self.assertEqual(buf, bytearray('abc\xe9\x00'))
+        buf = bytearray('x'*4)
+        self.assertRaises(TypeError, getargs_et_hash, u'abc\xe9', 'latin1', buf)
+        self.assertEqual(buf, bytearray('x'*4))
+        buf = bytearray()
+        self.assertRaises(TypeError, getargs_et_hash, u'abc\xe9', 'latin1', buf)
+
+    def test_u(self):
+        from _testcapi import getargs_u
+        self.assertEqual(getargs_u(u'abc\xe9'), u'abc\xe9')
+        self.assertEqual(getargs_u(u'nul:\0'), u'nul:')
+        self.assertRaises(TypeError, getargs_u, 'bytes')
+        self.assertRaises(TypeError, getargs_u, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_u, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_u, buffer('buffer'))
+        self.assertRaises(TypeError, getargs_u, None)
+
+    def test_u_hash(self):
+        from _testcapi import getargs_u_hash
+        self.assertEqual(getargs_u_hash(u'abc\xe9'), u'abc\xe9')
+        self.assertEqual(getargs_u_hash(u'nul:\0'), u'nul:\0')
+        self.assertRaises(TypeError, getargs_u_hash, 'bytes')
+        self.assertRaises(TypeError, getargs_u_hash, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_u_hash, memoryview('memoryview'))
+        with test_support.check_py3k_warnings():
+            self.assertRaises(TypeError, getargs_u_hash, buffer('buffer'))
+        self.assertRaises(TypeError, getargs_u_hash, None)
+
+
 def test_main():
     tests = [Signed_TestCase, Unsigned_TestCase, LongLong_TestCase,
-             Tuple_TestCase, Keywords_TestCase]
+             Tuple_TestCase, Keywords_TestCase,
+             Bytes_TestCase, String_TestCase, Unicode_TestCase]
     test_support.run_unittest(*tests)
 
+class Object_TestCase(unittest.TestCase):
+    def test_S(self):
+        from _testcapi import getargs_S
+        obj = 'str'
+        self.assertIs(getargs_S(obj), obj)
+        self.assertRaises(TypeError, getargs_S, bytearray('bytearray'))
+        if test_support.have_unicode:
+            self.assertRaises(TypeError, getargs_S, u'unicode')
+        self.assertRaises(TypeError, getargs_S, None)
+        self.assertRaises(TypeError, getargs_S, memoryview(obj))
+        self.assertRaises(TypeError, getargs_S, buffer(obj))
+
+    def test_Y(self):
+        from _testcapi import getargs_Y
+        obj = bytearray('bytearray')
+        self.assertIs(getargs_Y(obj), obj)
+        self.assertRaises(TypeError, getargs_Y, 'str')
+        if test_support.have_unicode:
+            self.assertRaises(TypeError, getargs_Y, u'unicode')
+        self.assertRaises(TypeError, getargs_Y, None)
+        self.assertRaises(TypeError, getargs_Y, memoryview(obj))
+        self.assertRaises(TypeError, getargs_Y, buffer(obj))
+
+    @test_support.requires_unicode
+    def test_U(self):
+        from _testcapi import getargs_U
+        obj = u'unicode'
+        self.assertIs(getargs_U(obj), obj)
+        self.assertRaises(TypeError, getargs_U, 'str')
+        self.assertRaises(TypeError, getargs_U, bytearray('bytearray'))
+        self.assertRaises(TypeError, getargs_U, None)
+        self.assertRaises(TypeError, getargs_U, memoryview(obj))
+        self.assertRaises(TypeError, getargs_U, buffer(obj))
+
+
 if __name__ == "__main__":
     test_main()
index 76be461..471ebb4 100644 (file)
@@ -408,7 +408,7 @@ class KDFTests(unittest.TestCase):
 
     pbkdf2_results = {
         "sha1": [
-            # offical test vectors from RFC 6070
+            # official test vectors from RFC 6070
             (unhexlify('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
             (unhexlify('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
             (unhexlify('4b007901b765489abead49d926f721d065a429c1'), None),
index a72f6f7..d3bac0f 100644 (file)
@@ -213,8 +213,8 @@ class HeaderTests(TestCase):
         self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
 
     def test_ipv6host_header(self):
-        # Default host header on IPv6 transaction should wrapped by [] if
-        # its actual IPv6 address
+        # Default host header on IPv6 transaction should be wrapped by [] if
+        # it is an IPv6 address
         expected = 'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
                    'Accept-Encoding: identity\r\n\r\n'
         conn = httplib.HTTPConnection('[2001::]:81')
index c84f48f..1b6339d 100644 (file)
@@ -8,6 +8,7 @@ import os
 import sys
 import re
 import base64
+import ntpath
 import shutil
 import urllib
 import httplib
@@ -177,6 +178,12 @@ class BaseHTTPServerTestCase(BaseTestCase):
             self.send_header('Connection', 'close')
             self.end_headers()
 
+        def do_SEND_ERROR(self):
+            self.send_error(int(self.path[1:]))
+
+        def do_HEAD(self):
+            self.send_error(int(self.path[1:]))
+
     def setUp(self):
         BaseTestCase.setUp(self)
         self.con = httplib.HTTPConnection('localhost', self.PORT)
@@ -275,6 +282,38 @@ class BaseHTTPServerTestCase(BaseTestCase):
         res = self.con.getresponse()
         self.assertEqual(res.status, 999)
 
+    def test_send_error(self):
+        allow_transfer_encoding_codes = (205, 304)
+        for code in (101, 102, 204, 205, 304):
+            self.con.request('SEND_ERROR', '/{}'.format(code))
+            res = self.con.getresponse()
+            self.assertEqual(code, res.status)
+            self.assertEqual(None, res.getheader('Content-Length'))
+            self.assertEqual(None, res.getheader('Content-Type'))
+            if code not in allow_transfer_encoding_codes:
+                self.assertEqual(None, res.getheader('Transfer-Encoding'))
+
+            data = res.read()
+            self.assertEqual(b'', data)
+
+    def test_head_via_send_error(self):
+        allow_transfer_encoding_codes = (205, 304)
+        for code in (101, 200, 204, 205, 304):
+            self.con.request('HEAD', '/{}'.format(code))
+            res = self.con.getresponse()
+            self.assertEqual(code, res.status)
+            if code == 200:
+                self.assertEqual(None, res.getheader('Content-Length'))
+                self.assertIn('text/html', res.getheader('Content-Type'))
+            else:
+                self.assertEqual(None, res.getheader('Content-Length'))
+                self.assertEqual(None, res.getheader('Content-Type'))
+            if code not in allow_transfer_encoding_codes:
+                self.assertEqual(None, res.getheader('Transfer-Encoding'))
+
+            data = res.read()
+            self.assertEqual(b'', data)
+
 
 class SimpleHTTPServerTestCase(BaseTestCase):
     class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
@@ -288,6 +327,7 @@ class SimpleHTTPServerTestCase(BaseTestCase):
         self.data = 'We are the knights who say Ni!'
         self.tempdir = tempfile.mkdtemp(dir=basetempdir)
         self.tempdir_name = os.path.basename(self.tempdir)
+        self.base_url = '/' + self.tempdir_name
         temp = open(os.path.join(self.tempdir, 'test'), 'wb')
         temp.write(self.data)
         temp.close()
@@ -312,39 +352,39 @@ class SimpleHTTPServerTestCase(BaseTestCase):
 
     def test_get(self):
         #constructs the path relative to the root directory of the HTTPServer
-        response = self.request(self.tempdir_name + '/test')
+        response = self.request(self.base_url + '/test')
         self.check_status_and_reason(response, 200, data=self.data)
         # check for trailing "/" which should return 404. See Issue17324
-        response = self.request(self.tempdir_name + '/test/')
+        response = self.request(self.base_url + '/test/')
         self.check_status_and_reason(response, 404)
-        response = self.request(self.tempdir_name + '/')
+        response = self.request(self.base_url + '/')
         self.check_status_and_reason(response, 200)
-        response = self.request(self.tempdir_name)
+        response = self.request(self.base_url)
         self.check_status_and_reason(response, 301)
-        response = self.request(self.tempdir_name + '/?hi=2')
+        response = self.request(self.base_url + '/?hi=2')
         self.check_status_and_reason(response, 200)
-        response = self.request(self.tempdir_name + '?hi=1')
+        response = self.request(self.base_url + '?hi=1')
         self.check_status_and_reason(response, 301)
         self.assertEqual(response.getheader("Location"),
-                         self.tempdir_name + "/?hi=1")
+                         self.base_url + "/?hi=1")
         response = self.request('/ThisDoesNotExist')
         self.check_status_and_reason(response, 404)
         response = self.request('/' + 'ThisDoesNotExist' + '/')
         self.check_status_and_reason(response, 404)
         with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
-            response = self.request('/' + self.tempdir_name + '/')
+            response = self.request(self.base_url + '/')
             self.check_status_and_reason(response, 200)
             # chmod() doesn't work as expected on Windows, and filesystem
             # permissions are ignored by root on Unix.
             if os.name == 'posix' and os.geteuid() != 0:
                 os.chmod(self.tempdir, 0)
-                response = self.request(self.tempdir_name + '/')
+                response = self.request(self.base_url + '/')
                 self.check_status_and_reason(response, 404)
                 os.chmod(self.tempdir, 0755)
 
     def test_head(self):
         response = self.request(
-            self.tempdir_name + '/test', method='HEAD')
+            self.base_url + '/test', method='HEAD')
         self.check_status_and_reason(response, 200)
         self.assertEqual(response.getheader('content-length'),
                          str(len(self.data)))
@@ -360,6 +400,22 @@ class SimpleHTTPServerTestCase(BaseTestCase):
         response = self.request('/', method='GETs')
         self.check_status_and_reason(response, 501)
 
+    def test_path_without_leading_slash(self):
+        response = self.request(self.tempdir_name + '/test')
+        self.check_status_and_reason(response, 200, data=self.data)
+        response = self.request(self.tempdir_name + '/test/')
+        self.check_status_and_reason(response, 404)
+        response = self.request(self.tempdir_name + '/')
+        self.check_status_and_reason(response, 200)
+        response = self.request(self.tempdir_name)
+        self.check_status_and_reason(response, 301)
+        response = self.request(self.tempdir_name + '/?hi=2')
+        self.check_status_and_reason(response, 200)
+        response = self.request(self.tempdir_name + '?hi=1')
+        self.check_status_and_reason(response, 301)
+        self.assertEqual(response.getheader("Location"),
+                         self.tempdir_name + "/?hi=1")
+
 
 cgi_file1 = """\
 #!%s
@@ -587,6 +643,25 @@ class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
         path = self.handler.translate_path('//filename?foo=bar')
         self.assertEqual(path, self.translated)
 
+    def test_windows_colon(self):
+        import SimpleHTTPServer
+        with test_support.swap_attr(SimpleHTTPServer.os, 'path', ntpath):
+            path = self.handler.translate_path('c:c:c:foo/filename')
+            path = path.replace(ntpath.sep, os.sep)
+            self.assertEqual(path, self.translated)
+
+            path = self.handler.translate_path('\\c:../filename')
+            path = path.replace(ntpath.sep, os.sep)
+            self.assertEqual(path, self.translated)
+
+            path = self.handler.translate_path('c:\\c:..\\foo/filename')
+            path = path.replace(ntpath.sep, os.sep)
+            self.assertEqual(path, self.translated)
+
+            path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
+            path = path.replace(ntpath.sep, os.sep)
+            self.assertEqual(path, self.translated)
+
 
 def test_main(verbose=None):
     try:
index 9589bf2..50ad4e7 100644 (file)
@@ -121,7 +121,7 @@ def test_main():
         print 'grey2rgb'
     image = imageop.grey2rgb(greyimage, width, height)
 
-    # Convert a 8-bit deep greyscale image to a 1-bit deep image by
+    # Convert an 8-bit deep greyscale image to a 1-bit deep image by
     # thresholding all the pixels. The resulting image is tightly packed
     # and is probably only useful as an argument to mono2grey.
     if verbose:
index 2ca6cf2..ea5c0e3 100644 (file)
@@ -45,6 +45,9 @@ if have_unicode:
         (unichr(0x200), ValueError),
 ]
 
+class IntSubclass(int):
+    pass
+
 class IntLongCommonTests(object):
 
     """Mixin of test cases to share between both test_int and test_long."""
@@ -348,7 +351,8 @@ class IntTestCases(IntLongCommonTests, unittest.TestCase):
             factories += [unicode, CustomUnicode]
 
         for f in factories:
-            x = f('100')
+            with test_support.check_py3k_warnings(quiet=True):
+                x = f('100')
             msg = 'x has value %s and type %s' % (x, type(x).__name__)
             try:
                 self.assertEqual(int(x), 100, msg=msg)
@@ -362,15 +366,17 @@ class IntTestCases(IntLongCommonTests, unittest.TestCase):
                 with self.assertRaisesRegexp(TypeError, errmsg, msg=msg):
                     int(x, 2)
             errmsg = 'invalid literal'
-            with self.assertRaisesRegexp(ValueError, errmsg, msg=msg):
+            with self.assertRaisesRegexp(ValueError, errmsg, msg=msg), \
+                 test_support.check_py3k_warnings(quiet=True):
                 int(f('A' * 0x10))
 
     def test_int_buffer(self):
-        self.assertEqual(int(buffer('123', 1, 2)), 23)
-        self.assertEqual(int(buffer('123\x00', 1, 2)), 23)
-        self.assertEqual(int(buffer('123 ', 1, 2)), 23)
-        self.assertEqual(int(buffer('123A', 1, 2)), 23)
-        self.assertEqual(int(buffer('1234', 1, 2)), 23)
+        with test_support.check_py3k_warnings():
+            self.assertEqual(int(buffer('123', 1, 2)), 23)
+            self.assertEqual(int(buffer('123\x00', 1, 2)), 23)
+            self.assertEqual(int(buffer('123 ', 1, 2)), 23)
+            self.assertEqual(int(buffer('123A', 1, 2)), 23)
+            self.assertEqual(int(buffer('1234', 1, 2)), 23)
 
     def test_error_on_string_float_for_x(self):
         self.assertRaises(ValueError, int, '1.2')
@@ -477,6 +483,18 @@ class IntTestCases(IntLongCommonTests, unittest.TestCase):
                     self.fail("Failed to raise TypeError with %s" %
                               ((base, trunc_result_base),))
 
+                class TruncReturnsIntSubclass(base):
+                    def __trunc__(self):
+                        return True
+                good_int = TruncReturnsIntSubclass()
+                n = int(good_int)
+                self.assertEqual(n, 1)
+                self.assertIs(type(n), bool)
+                n = IntSubclass(good_int)
+                self.assertEqual(n, 1)
+                self.assertIs(type(n), IntSubclass)
+
+
 def test_main():
     run_unittest(IntTestCases)
 
index 34760c9..e26ffba 100644 (file)
@@ -54,6 +54,9 @@ except ImportError:
 __metaclass__ = type
 bytes = support.py3k_bytes
 
+def byteslike(*pos, **kw):
+    return memoryview(bytearray(*pos, **kw))
+
 def _default_chunk_size():
     """Get the default TextIOWrapper chunk size"""
     with io.open(__file__, "r", encoding="latin1") as f:
@@ -273,7 +276,9 @@ class IOTest(unittest.TestCase):
         self.assertEqual(f.tell(), 6)
         self.assertEqual(f.seek(-1, 1), 5)
         self.assertEqual(f.tell(), 5)
-        self.assertEqual(f.write(bytearray(b" world\n\n\n")), 9)
+        buffer = bytearray(b" world\n\n\n")
+        self.assertEqual(f.write(buffer), 9)
+        buffer[:] = b"*" * 9  # Overwrite our copy of the data
         self.assertEqual(f.seek(0), 0)
         self.assertEqual(f.write(b"h"), 1)
         self.assertEqual(f.seek(-1, 2), 13)
@@ -286,20 +291,21 @@ class IOTest(unittest.TestCase):
     def read_ops(self, f, buffered=False):
         data = f.read(5)
         self.assertEqual(data, b"hello")
-        data = bytearray(data)
+        data = byteslike(data)
         self.assertEqual(f.readinto(data), 5)
-        self.assertEqual(data, b" worl")
+        self.assertEqual(data.tobytes(), b" worl")
+        data = bytearray(5)
         self.assertEqual(f.readinto(data), 2)
         self.assertEqual(len(data), 5)
         self.assertEqual(data[:2], b"d\n")
         self.assertEqual(f.seek(0), 0)
         self.assertEqual(f.read(20), b"hello world\n")
         self.assertEqual(f.read(1), b"")
-        self.assertEqual(f.readinto(bytearray(b"x")), 0)
+        self.assertEqual(f.readinto(byteslike(b"x")), 0)
         self.assertEqual(f.seek(-6, 2), 6)
         self.assertEqual(f.read(5), b"world")
         self.assertEqual(f.read(0), b"")
-        self.assertEqual(f.readinto(bytearray()), 0)
+        self.assertEqual(f.readinto(byteslike()), 0)
         self.assertEqual(f.seek(-6, 1), 5)
         self.assertEqual(f.read(5), b" worl")
         self.assertEqual(f.tell(), 10)
@@ -649,6 +655,16 @@ class IOTest(unittest.TestCase):
             support.gc_collect()
         self.assertEqual(recorded, [])
 
+    def test_buffered_readinto_mixin(self):
+        # Test the implementation provided by BufferedIOBase
+        class Stream(self.BufferedIOBase):
+            def read(self, size):
+                return b"12345"
+        stream = Stream()
+        buffer = byteslike(5)
+        self.assertEqual(stream.readinto(buffer), 5)
+        self.assertEqual(buffer.tobytes(), b"12345")
+
 
 class CIOTest(IOTest):
 
@@ -693,12 +709,6 @@ class CommonBufferedTests:
 
         self.assertEqual(42, bufio.fileno())
 
-    @unittest.skip('test having existential crisis')
-    def test_no_fileno(self):
-        # XXX will we always have fileno() function? If so, kill
-        # this test. Else, write it.
-        pass
-
     def test_invalid_args(self):
         rawio = self.MockRawIO()
         bufio = self.tp(rawio)
@@ -1117,6 +1127,11 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests):
         bufio = self.tp(writer, 8)
         bufio.write(b"abc")
         self.assertFalse(writer._write_stack)
+        buffer = bytearray(b"def")
+        bufio.write(buffer)
+        buffer[:] = b"***"  # Overwrite our copy of the data
+        bufio.flush()
+        self.assertEqual(b"".join(writer._write_stack), b"abcdef")
 
     def test_write_overflow(self):
         writer = self.MockRawIO()
@@ -1446,9 +1461,9 @@ class BufferedRWPairTest(unittest.TestCase):
     def test_readinto(self):
         pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO())
 
-        data = bytearray(5)
+        data = byteslike(5)
         self.assertEqual(pair.readinto(data), 5)
-        self.assertEqual(data, b"abcde")
+        self.assertEqual(data.tobytes(), b"abcde")
 
     def test_write(self):
         w = self.MockRawIO()
@@ -1456,7 +1471,9 @@ class BufferedRWPairTest(unittest.TestCase):
 
         pair.write(b"abc")
         pair.flush()
-        pair.write(b"def")
+        buffer = bytearray(b"def")
+        pair.write(buffer)
+        buffer[:] = b"***"  # Overwrite our copy of the data
         pair.flush()
         self.assertEqual(w._write_stack, [b"abc", b"def"])
 
index bd1b32d..cc20865 100644 (file)
@@ -2,7 +2,8 @@
 
 import unittest
 from test.test_support import run_unittest, TESTFN, unlink, have_unicode, \
-                              check_py3k_warnings, cpython_only
+                              check_py3k_warnings, cpython_only, \
+                              check_free_after_iterating
 
 # Test result of triple loop (too big to inline)
 TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2),
@@ -121,6 +122,17 @@ class TestCase(unittest.TestCase):
     def test_seq_class_iter(self):
         self.check_iterator(iter(SequenceClass(10)), range(10))
 
+    def test_mutating_seq_class_exhausted_iter(self):
+        a = SequenceClass(5)
+        exhit = iter(a)
+        empit = iter(a)
+        for x in exhit:  # exhaust the iterator
+            next(empit)  # not exhausted
+        a.n = 7
+        self.assertEqual(list(exhit), [])
+        self.assertEqual(list(empit), [5, 6])
+        self.assertEqual(list(a), [0, 1, 2, 3, 4, 5, 6])
+
     # Test a new_style class with __iter__ but no next() method
     def test_new_style_iter_class(self):
         class IterClass(object):
@@ -921,6 +933,9 @@ class TestCase(unittest.TestCase):
         lst.extend(gen())
         self.assertEqual(len(lst), 760)
 
+    def test_free_after_iterating(self):
+        check_free_after_iterating(self, iter, SequenceClass, (0,))
+
 
 def test_main():
     run_unittest(TestCase)
index 753aa17..8b5f051 100644 (file)
@@ -1525,6 +1525,11 @@ Samuele
 ...     "Returns the nth item or a default value"
 ...     return next(islice(iterable, n, None), default)
 
+>>> def all_equal(iterable):
+...     "Returns True if all the elements are equal to each other"
+...     g = groupby(iterable)
+...     return next(g, True) and not next(g, False)
+
 >>> def quantify(iterable, pred=bool):
 ...     "Count how many times the predicate is true"
 ...     return sum(imap(pred, iterable))
@@ -1623,6 +1628,9 @@ perform as purported.
 >>> nth('abcde', 9) is None
 True
 
+>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
+[True, True, True, False, False]
+
 >>> quantify(xrange(99), lambda x: x%2==0)
 50
 
index 719175b..563ddb1 100644 (file)
@@ -493,6 +493,16 @@ class TestMiscellaneous(unittest.TestCase):
         # longer accept unicode strings.
         self.assertEqual(locale.normalize(u'en_US'), 'en_US.ISO8859-1')
 
+    def test_setlocale_unicode(self):
+        oldlocale = locale.getlocale()
+        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
+
+        user_locale = locale.setlocale(locale.LC_CTYPE, '')
+        unicode_locale = user_locale.decode('utf-8')
+
+        user_locale2 = locale.setlocale(locale.LC_CTYPE, unicode_locale)
+        self.assertEqual(user_locale, user_locale2)
+
 
 def test_main():
     tests = [
index ffa4774..b65d24c 100644 (file)
@@ -79,6 +79,12 @@ if test_support.have_unicode:
         (unichr(0x200), ValueError),
 ]
 
+class LongSubclass(long):
+    pass
+
+class OtherLongSubclass(long):
+    pass
+
 class LongTest(test_int.IntLongCommonTests, unittest.TestCase):
 
     ntype = long
@@ -539,6 +545,17 @@ class LongTest(test_int.IntLongCommonTests, unittest.TestCase):
                     self.fail("Failed to raise TypeError with %s" %
                               ((base, trunc_result_base),))
 
+                class TruncReturnsLongSubclass(base):
+                    def __long__(self):
+                        return OtherLongSubclass(42L)
+                good_int = TruncReturnsLongSubclass()
+                n = long(good_int)
+                self.assertEqual(n, 42L)
+                self.assertIs(type(n), OtherLongSubclass)
+                n = LongSubclass(good_int)
+                self.assertEqual(n, 42L)
+                self.assertIs(type(n), LongSubclass)
+
     def test_misc(self):
 
         # check the extremes in int<->long conversion
index 0eb9961..2c18ad7 100644 (file)
@@ -396,6 +396,7 @@ class MemoryTestMixin:
 
 
 class PyBytesIOTest(MemoryTestMixin, MemorySeekTestMixin, unittest.TestCase):
+    # Test _pyio.BytesIO; class also inherited for testing C implementation
 
     UnsupportedOperation = pyio.UnsupportedOperation
 
index f14bafd..4407af8 100644 (file)
@@ -10,6 +10,8 @@ import weakref
 import array
 from test import test_support
 import io
+import copy
+import pickle
 
 
 class AbstractMemoryTests:
@@ -354,6 +356,20 @@ class BytesMemorySliceSliceTest(unittest.TestCase,
     #pass
 
 
+class OtherTest(unittest.TestCase):
+    def test_copy(self):
+        m = memoryview(b'abc')
+        with self.assertRaises(TypeError):
+            copy.copy(m)
+
+    # See issue #22995
+    ## def test_pickle(self):
+    ##     m = memoryview(b'abc')
+    ##     for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+    ##         with self.assertRaises(TypeError):
+    ##             pickle.dumps(m, proto)
+
+
 def test_main():
     test_support.run_unittest(__name__)
 
index a962ddc..b6d88d2 100644 (file)
@@ -1,5 +1,6 @@
 # test for xml.dom.minidom
 
+import copy
 import pickle
 from StringIO import StringIO
 from test.test_support import verbose, run_unittest, findfile
@@ -14,7 +15,13 @@ from xml.dom.minidom import getDOMImplementation
 
 
 tstfile = findfile("test.xml", subdir="xmltestdata")
-
+sample = ("<?xml version='1.0' encoding='us-ascii'?>\n"
+          "<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'"
+          " 'http://xml.python.org/system' [\n"
+          "  <!ELEMENT e EMPTY>\n"
+          "  <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
+          "]><doc attr='value'> text\n"
+          "<?pi sample?> <!-- comment --> <e/> </doc>")
 
 # The tests of DocumentType importing use these helpers to construct
 # the documents to work with, since not all DOM builders actually
@@ -1377,52 +1384,54 @@ class MinidomTest(unittest.TestCase):
         self.confirm(e.isSameNode(doc.getElementById("w"))
                 and a2.isId)
 
+    def assert_recursive_equal(self, doc, doc2):
+        stack = [(doc, doc2)]
+        while stack:
+            n1, n2 = stack.pop()
+            self.assertEqual(n1.nodeType, n2.nodeType)
+            self.assertEqual(len(n1.childNodes), len(n2.childNodes))
+            self.assertEqual(n1.nodeName, n2.nodeName)
+            self.assertFalse(n1.isSameNode(n2))
+            self.assertFalse(n2.isSameNode(n1))
+            if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
+                len(n1.entities)
+                len(n2.entities)
+                len(n1.notations)
+                len(n2.notations)
+                self.assertEqual(len(n1.entities), len(n2.entities))
+                self.assertEqual(len(n1.notations), len(n2.notations))
+                for i in range(len(n1.notations)):
+                    # XXX this loop body doesn't seem to be executed?
+                    no1 = n1.notations.item(i)
+                    no2 = n1.notations.item(i)
+                    self.assertEqual(no1.name, no2.name)
+                    self.assertEqual(no1.publicId, no2.publicId)
+                    self.assertEqual(no1.systemId, no2.systemId)
+                    stack.append((no1, no2))
+                for i in range(len(n1.entities)):
+                    e1 = n1.entities.item(i)
+                    e2 = n2.entities.item(i)
+                    self.assertEqual(e1.notationName, e2.notationName)
+                    self.assertEqual(e1.publicId, e2.publicId)
+                    self.assertEqual(e1.systemId, e2.systemId)
+                    stack.append((e1, e2))
+            if n1.nodeType != Node.DOCUMENT_NODE:
+                self.assertTrue(n1.ownerDocument.isSameNode(doc))
+                self.assertTrue(n2.ownerDocument.isSameNode(doc2))
+            for i in range(len(n1.childNodes)):
+                stack.append((n1.childNodes[i], n2.childNodes[i]))
+
     def testPickledDocument(self):
-        doc = parseString("<?xml version='1.0' encoding='us-ascii'?>\n"
-                    "<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'"
-                    " 'http://xml.python.org/system' [\n"
-                    "  <!ELEMENT e EMPTY>\n"
-                    "  <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
-                    "]><doc attr='value'> text\n"
-                    "<?pi sample?> <!-- comment --> <e/> </doc>")
-        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+        doc = parseString(sample)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             s = pickle.dumps(doc, proto)
             doc2 = pickle.loads(s)
-            stack = [(doc, doc2)]
-            while stack:
-                n1, n2 = stack.pop()
-                self.confirm(n1.nodeType == n2.nodeType
-                        and len(n1.childNodes) == len(n2.childNodes)
-                        and n1.nodeName == n2.nodeName
-                        and not n1.isSameNode(n2)
-                        and not n2.isSameNode(n1))
-                if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
-                    len(n1.entities)
-                    len(n2.entities)
-                    len(n1.notations)
-                    len(n2.notations)
-                    self.confirm(len(n1.entities) == len(n2.entities)
-                            and len(n1.notations) == len(n2.notations))
-                    for i in range(len(n1.notations)):
-                        # XXX this loop body doesn't seem to be executed?
-                        no1 = n1.notations.item(i)
-                        no2 = n1.notations.item(i)
-                        self.confirm(no1.name == no2.name
-                                and no1.publicId == no2.publicId
-                                and no1.systemId == no2.systemId)
-                        stack.append((no1, no2))
-                    for i in range(len(n1.entities)):
-                        e1 = n1.entities.item(i)
-                        e2 = n2.entities.item(i)
-                        self.confirm(e1.notationName == e2.notationName
-                                and e1.publicId == e2.publicId
-                                and e1.systemId == e2.systemId)
-                        stack.append((e1, e2))
-                if n1.nodeType != Node.DOCUMENT_NODE:
-                    self.confirm(n1.ownerDocument.isSameNode(doc)
-                            and n2.ownerDocument.isSameNode(doc2))
-                for i in range(len(n1.childNodes)):
-                    stack.append((n1.childNodes[i], n2.childNodes[i]))
+            self.assert_recursive_equal(doc, doc2)
+
+    def testDeepcopiedDocument(self):
+        doc = parseString(sample)
+        doc2 = copy.deepcopy(doc)
+        self.assert_recursive_equal(doc, doc2)
 
     def testSerializeCommentNodeWithDoubleHyphen(self):
         doc = create_doc_without_doctype()
index e71d1e0..497ee5c 100644 (file)
@@ -278,6 +278,19 @@ class ModuleFinderTest(unittest.TestCase):
         def test_relative_imports_3(self):
             self._do_test(relative_import_test_3)
 
+    def test_extended_opargs(self):
+        extended_opargs_test = [
+            "a",
+            ["a", "b"],
+            [], [],
+            """\
+a.py
+                                %r
+                                import b
+b.py
+""" % range(2**16)]  # 2**16 constants
+        self._do_test(extended_opargs_test)
+
 def test_main():
     distutils.log.set_threshold(distutils.log.WARN)
     test_support.run_unittest(ModuleFinderTest)
index 69c381e..c70106d 100644 (file)
@@ -4,7 +4,7 @@ import os
 
 # From SF bug #422121:  Insecurities in dict comparison.
 
-# Safety of code doing comparisons has been an historical Python weak spot.
+# Safety of code doing comparisons has been a historical Python weak spot.
 # The problem is that comparison of structures written in C *naturally*
 # wants to hold on to things like the size of the container, or "the
 # biggest" containee so far, across a traversal of the container; but
index 81a8020..0864461 100644 (file)
@@ -371,6 +371,9 @@ class OperatorTestCase(unittest.TestCase):
         a.name = 'arthur'
         f = operator.attrgetter('name')
         self.assertEqual(f(a), 'arthur')
+        self.assertRaises(TypeError, f)
+        self.assertRaises(TypeError, f, a, 'dent')
+        self.assertRaises(TypeError, f, a, surname='dent')
         f = operator.attrgetter('rank')
         self.assertRaises(AttributeError, f, a)
         f = operator.attrgetter(2)
@@ -414,6 +417,9 @@ class OperatorTestCase(unittest.TestCase):
         a = 'ABCDE'
         f = operator.itemgetter(2)
         self.assertEqual(f(a), 'C')
+        self.assertRaises(TypeError, f)
+        self.assertRaises(TypeError, f, a, 3)
+        self.assertRaises(TypeError, f, a, size=3)
         f = operator.itemgetter(10)
         self.assertRaises(IndexError, f, a)
 
@@ -456,6 +462,9 @@ class OperatorTestCase(unittest.TestCase):
         self.assertRaises(IndexError, f, a)
         f = operator.methodcaller('foo', 1, 2)
         self.assertEqual(f(a), 3)
+        self.assertRaises(TypeError, f)
+        self.assertRaises(TypeError, f, a, 3)
+        self.assertRaises(TypeError, f, a, spam=3)
         f = operator.methodcaller('bar')
         self.assertEqual(f(a), 42)
         self.assertRaises(TypeError, f, a, a)
diff --git a/Lib/test/test_ordered_dict.py b/Lib/test/test_ordered_dict.py
new file mode 100644 (file)
index 0000000..85e4841
--- /dev/null
@@ -0,0 +1,302 @@
+import copy
+import pickle
+from random import shuffle
+import unittest
+from collections import OrderedDict
+from collections import MutableMapping
+from test import mapping_tests, test_support
+
+
+class TestOrderedDict(unittest.TestCase):
+
+    def test_init(self):
+        with self.assertRaises(TypeError):
+            OrderedDict([('a', 1), ('b', 2)], None)                                 # too many args
+        pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
+        self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs)           # dict input
+        self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs)         # kwds input
+        self.assertEqual(list(OrderedDict(pairs).items()), pairs)                   # pairs input
+        self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)],
+                                          c=3, e=5).items()), pairs)                # mixed input
+
+        # make sure no positional args conflict with possible kwdargs
+        self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)])
+        self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)])
+        self.assertRaises(TypeError, OrderedDict, 42)
+        self.assertRaises(TypeError, OrderedDict, (), ())
+        self.assertRaises(TypeError, OrderedDict.__init__)
+
+        # Make sure that direct calls to __init__ do not clear previous contents
+        d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
+        d.__init__([('e', 5), ('f', 6)], g=7, d=4)
+        self.assertEqual(list(d.items()),
+            [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
+
+    def test_update(self):
+        with self.assertRaises(TypeError):
+            OrderedDict().update([('a', 1), ('b', 2)], None)                        # too many args
+        pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
+        od = OrderedDict()
+        od.update(dict(pairs))
+        self.assertEqual(sorted(od.items()), pairs)                                 # dict input
+        od = OrderedDict()
+        od.update(**dict(pairs))
+        self.assertEqual(sorted(od.items()), pairs)                                 # kwds input
+        od = OrderedDict()
+        od.update(pairs)
+        self.assertEqual(list(od.items()), pairs)                                   # pairs input
+        od = OrderedDict()
+        od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)
+        self.assertEqual(list(od.items()), pairs)                                   # mixed input
+
+        # Issue 9137: Named argument called 'other' or 'self'
+        # shouldn't be treated specially.
+        od = OrderedDict()
+        od.update(self=23)
+        self.assertEqual(list(od.items()), [('self', 23)])
+        od = OrderedDict()
+        od.update(other={})
+        self.assertEqual(list(od.items()), [('other', {})])
+        od = OrderedDict()
+        od.update(red=5, blue=6, other=7, self=8)
+        self.assertEqual(sorted(list(od.items())),
+                         [('blue', 6), ('other', 7), ('red', 5), ('self', 8)])
+
+        # Make sure that direct calls to update do not clear previous contents
+        # add that updates items are not moved to the end
+        d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
+        d.update([('e', 5), ('f', 6)], g=7, d=4)
+        self.assertEqual(list(d.items()),
+            [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
+
+        self.assertRaises(TypeError, OrderedDict().update, 42)
+        self.assertRaises(TypeError, OrderedDict().update, (), ())
+        self.assertRaises(TypeError, OrderedDict.update)
+
+    def test_abc(self):
+        self.assertIsInstance(OrderedDict(), MutableMapping)
+        self.assertTrue(issubclass(OrderedDict, MutableMapping))
+
+    def test_clear(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        shuffle(pairs)
+        od = OrderedDict(pairs)
+        self.assertEqual(len(od), len(pairs))
+        od.clear()
+        self.assertEqual(len(od), 0)
+
+    def test_delitem(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        od = OrderedDict(pairs)
+        del od['a']
+        self.assertNotIn('a', od)
+        with self.assertRaises(KeyError):
+            del od['a']
+        self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
+
+    def test_setitem(self):
+        od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)])
+        od['c'] = 10           # existing element
+        od['f'] = 20           # new element
+        self.assertEqual(list(od.items()),
+                         [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)])
+
+    def test_iterators(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        shuffle(pairs)
+        od = OrderedDict(pairs)
+        self.assertEqual(list(od), [t[0] for t in pairs])
+        self.assertEqual(od.keys()[:], [t[0] for t in pairs])
+        self.assertEqual(od.values()[:], [t[1] for t in pairs])
+        self.assertEqual(od.items()[:], pairs)
+        self.assertEqual(list(od.iterkeys()), [t[0] for t in pairs])
+        self.assertEqual(list(od.itervalues()), [t[1] for t in pairs])
+        self.assertEqual(list(od.iteritems()), pairs)
+        self.assertEqual(list(reversed(od)),
+                         [t[0] for t in reversed(pairs)])
+
+    def test_popitem(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        shuffle(pairs)
+        od = OrderedDict(pairs)
+        while pairs:
+            self.assertEqual(od.popitem(), pairs.pop())
+        with self.assertRaises(KeyError):
+            od.popitem()
+        self.assertEqual(len(od), 0)
+
+    def test_pop(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        shuffle(pairs)
+        od = OrderedDict(pairs)
+        shuffle(pairs)
+        while pairs:
+            k, v = pairs.pop()
+            self.assertEqual(od.pop(k), v)
+        with self.assertRaises(KeyError):
+            od.pop('xyz')
+        self.assertEqual(len(od), 0)
+        self.assertEqual(od.pop(k, 12345), 12345)
+
+        # make sure pop still works when __missing__ is defined
+        class Missing(OrderedDict):
+            def __missing__(self, key):
+                return 0
+        m = Missing(a=1)
+        self.assertEqual(m.pop('b', 5), 5)
+        self.assertEqual(m.pop('a', 6), 1)
+        self.assertEqual(m.pop('a', 6), 6)
+        with self.assertRaises(KeyError):
+            m.pop('a')
+
+    def test_equality(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        shuffle(pairs)
+        od1 = OrderedDict(pairs)
+        od2 = OrderedDict(pairs)
+        self.assertEqual(od1, od2)          # same order implies equality
+        pairs = pairs[2:] + pairs[:2]
+        od2 = OrderedDict(pairs)
+        self.assertNotEqual(od1, od2)       # different order implies inequality
+        # comparison to regular dict is not order sensitive
+        self.assertEqual(od1, dict(od2))
+        self.assertEqual(dict(od2), od1)
+        # different length implied inequality
+        self.assertNotEqual(od1, OrderedDict(pairs[:-1]))
+
+    def test_copying(self):
+        # Check that ordered dicts are copyable, deepcopyable, picklable,
+        # and have a repr/eval round-trip
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        od = OrderedDict(pairs)
+        update_test = OrderedDict()
+        update_test.update(od)
+        for i, dup in enumerate([
+                    od.copy(),
+                    copy.copy(od),
+                    copy.deepcopy(od),
+                    pickle.loads(pickle.dumps(od, 0)),
+                    pickle.loads(pickle.dumps(od, 1)),
+                    pickle.loads(pickle.dumps(od, 2)),
+                    pickle.loads(pickle.dumps(od, -1)),
+                    eval(repr(od)),
+                    update_test,
+                    OrderedDict(od),
+                    ]):
+            self.assertTrue(dup is not od)
+            self.assertEqual(dup, od)
+            self.assertEqual(list(dup.items()), list(od.items()))
+            self.assertEqual(len(dup), len(od))
+            self.assertEqual(type(dup), type(od))
+
+    def test_yaml_linkage(self):
+        # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
+        # In yaml, lists are native but tuples are not.
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        od = OrderedDict(pairs)
+        # yaml.dump(od) -->
+        # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n  - [b, 2]\n'
+        self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))
+
+    def test_reduce_not_too_fat(self):
+        # do not save instance dictionary if not needed
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        od = OrderedDict(pairs)
+        self.assertEqual(len(od.__reduce__()), 2)
+        od.x = 10
+        self.assertEqual(len(od.__reduce__()), 3)
+
+    def test_repr(self):
+        od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])
+        self.assertEqual(repr(od),
+            "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])")
+        self.assertEqual(eval(repr(od)), od)
+        self.assertEqual(repr(OrderedDict()), "OrderedDict()")
+
+    def test_repr_recursive(self):
+        # See issue #9826
+        od = OrderedDict.fromkeys('abc')
+        od['x'] = od
+        self.assertEqual(repr(od),
+            "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])")
+
+    def test_setdefault(self):
+        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
+        shuffle(pairs)
+        od = OrderedDict(pairs)
+        pair_order = list(od.items())
+        self.assertEqual(od.setdefault('a', 10), 3)
+        # make sure order didn't change
+        self.assertEqual(list(od.items()), pair_order)
+        self.assertEqual(od.setdefault('x', 10), 10)
+        # make sure 'x' is added to the end
+        self.assertEqual(list(od.items())[-1], ('x', 10))
+
+        # make sure setdefault still works when __missing__ is defined
+        class Missing(OrderedDict):
+            def __missing__(self, key):
+                return 0
+        self.assertEqual(Missing().setdefault(5, 9), 9)
+
+    def test_reinsert(self):
+        # Given insert a, insert b, delete a, re-insert a,
+        # verify that a is now later than b.
+        od = OrderedDict()
+        od['a'] = 1
+        od['b'] = 2
+        del od['a']
+        od['a'] = 1
+        self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])
+
+    def test_views(self):
+        s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split()
+        od = OrderedDict.fromkeys(s)
+        self.assertEqual(list(od.viewkeys()),  s)
+        self.assertEqual(list(od.viewvalues()),  [None for k in s])
+        self.assertEqual(list(od.viewitems()),  [(k, None) for k in s])
+
+        # See http://bugs.python.org/issue24286
+        self.assertEqual(od.viewkeys(), dict(od).viewkeys())
+        self.assertEqual(od.viewitems(), dict(od).viewitems())
+
+    def test_override_update(self):
+        # Verify that subclasses can override update() without breaking __init__()
+        class MyOD(OrderedDict):
+            def update(self, *args, **kwds):
+                raise Exception()
+        items = [('a', 1), ('c', 3), ('b', 2)]
+        self.assertEqual(list(MyOD(items).items()), items)
+
+    def test_free_after_iterating(self):
+        test_support.check_free_after_iterating(self, iter, OrderedDict)
+        test_support.check_free_after_iterating(self, lambda d: d.iterkeys(), OrderedDict)
+        test_support.check_free_after_iterating(self, lambda d: d.itervalues(), OrderedDict)
+        test_support.check_free_after_iterating(self, lambda d: d.iteritems(), OrderedDict)
+        test_support.check_free_after_iterating(self, lambda d: iter(d.viewkeys()), OrderedDict)
+        test_support.check_free_after_iterating(self, lambda d: iter(d.viewvalues()), OrderedDict)
+        test_support.check_free_after_iterating(self, lambda d: iter(d.viewitems()), OrderedDict)
+
+class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
+    type2test = OrderedDict
+
+    def test_popitem(self):
+        d = self._empty_mapping()
+        self.assertRaises(KeyError, d.popitem)
+
+class MyOrderedDict(OrderedDict):
+    pass
+
+class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
+    type2test = MyOrderedDict
+
+    def test_popitem(self):
+        d = self._empty_mapping()
+        self.assertRaises(KeyError, d.popitem)
+
+
+def test_main(verbose=None):
+    test_classes = [TestOrderedDict, GeneralMappingTests, SubclassMappingTests]
+    test_support.run_unittest(*test_classes)
+
+if __name__ == "__main__":
+    test_main(verbose=True)
diff --git a/Lib/test/test_pep263.py b/Lib/test/test_pep263.py
deleted file mode 100644 (file)
index a3abc3c..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-# -*- coding: koi8-r -*-
-
-import unittest
-from test import test_support
-
-class PEP263Test(unittest.TestCase):
-
-    def test_pep263(self):
-        self.assertEqual(
-            u"ðÉÔÏÎ".encode("utf-8"),
-            '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
-        )
-        self.assertEqual(
-            u"\ð".encode("utf-8"),
-            '\\\xd0\x9f'
-        )
-
-    def test_compilestring(self):
-        # see #1882
-        c = compile("\n# coding: utf-8\nu = u'\xc3\xb3'\n", "dummy", "exec")
-        d = {}
-        exec c in d
-        self.assertEqual(d['u'], u'\xf3')
-
-
-    def test_issue3297(self):
-        c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec")
-        d = {}
-        exec(c, d)
-        self.assertEqual(d['a'], d['b'])
-        self.assertEqual(len(d['a']), len(d['b']))
-
-    def test_issue7820(self):
-        # Ensure that check_bom() restores all bytes in the right order if
-        # check_bom() fails in pydebug mode: a buffer starts with the first
-        # byte of a valid BOM, but next bytes are different
-
-        # one byte in common with the UTF-16-LE BOM
-        self.assertRaises(SyntaxError, eval, '\xff\x20')
-
-        # two bytes in common with the UTF-8 BOM
-        self.assertRaises(SyntaxError, eval, '\xef\xbb\x20')
-
-    def test_error_message(self):
-        compile('# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
-        compile('\xef\xbb\xbf\n', 'dummy', 'exec')
-        compile('\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
-        with self.assertRaisesRegexp(SyntaxError, 'fake'):
-            compile('# -*- coding: fake -*-\n', 'dummy', 'exec')
-        with self.assertRaisesRegexp(SyntaxError, 'iso-8859-15'):
-            compile('\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
-                    'dummy', 'exec')
-        with self.assertRaisesRegexp(SyntaxError, 'BOM'):
-            compile('\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
-                    'dummy', 'exec')
-        with self.assertRaisesRegexp(SyntaxError, 'fake'):
-            compile('\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
-        with self.assertRaisesRegexp(SyntaxError, 'BOM'):
-            compile('\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
-
-    def test_non_unicode_codec(self):
-        with self.assertRaisesRegexp(SyntaxError,
-                                     'codec did not return a unicode'):
-            from test import bad_coding3
-
-
-def test_main():
-    test_support.run_unittest(PEP263Test)
-
-if __name__=="__main__":
-    test_main()
diff --git a/Lib/test/test_pep292.py b/Lib/test/test_pep292.py
deleted file mode 100644 (file)
index 133cab7..0000000
+++ /dev/null
@@ -1,234 +0,0 @@
-# Copyright (C) 2004 Python Software Foundation
-# Author: barry@python.org (Barry Warsaw)
-# License: http://www.opensource.org/licenses/PythonSoftFoundation.php
-
-import unittest
-from string import Template
-
-
-class Bag:
-    pass
-
-class Mapping:
-    def __getitem__(self, name):
-        obj = self
-        for part in name.split('.'):
-            try:
-                obj = getattr(obj, part)
-            except AttributeError:
-                raise KeyError(name)
-        return obj
-
-
-class TestTemplate(unittest.TestCase):
-    def test_regular_templates(self):
-        s = Template('$who likes to eat a bag of $what worth $$100')
-        self.assertEqual(s.substitute(dict(who='tim', what='ham')),
-                         'tim likes to eat a bag of ham worth $100')
-        self.assertRaises(KeyError, s.substitute, dict(who='tim'))
-        self.assertRaises(TypeError, Template.substitute)
-
-    def test_regular_templates_with_braces(self):
-        s = Template('$who likes ${what} for ${meal}')
-        d = dict(who='tim', what='ham', meal='dinner')
-        self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
-        self.assertRaises(KeyError, s.substitute,
-                          dict(who='tim', what='ham'))
-
-    def test_escapes(self):
-        eq = self.assertEqual
-        s = Template('$who likes to eat a bag of $$what worth $$100')
-        eq(s.substitute(dict(who='tim', what='ham')),
-           'tim likes to eat a bag of $what worth $100')
-        s = Template('$who likes $$')
-        eq(s.substitute(dict(who='tim', what='ham')), 'tim likes $')
-
-    def test_percents(self):
-        eq = self.assertEqual
-        s = Template('%(foo)s $foo ${foo}')
-        d = dict(foo='baz')
-        eq(s.substitute(d), '%(foo)s baz baz')
-        eq(s.safe_substitute(d), '%(foo)s baz baz')
-
-    def test_stringification(self):
-        eq = self.assertEqual
-        s = Template('tim has eaten $count bags of ham today')
-        d = dict(count=7)
-        eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
-        eq(s.safe_substitute(d), 'tim has eaten 7 bags of ham today')
-        s = Template('tim has eaten ${count} bags of ham today')
-        eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
-
-    def test_tupleargs(self):
-        eq = self.assertEqual
-        s = Template('$who ate ${meal}')
-        d = dict(who=('tim', 'fred'), meal=('ham', 'kung pao'))
-        eq(s.substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
-        eq(s.safe_substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
-
-    def test_SafeTemplate(self):
-        eq = self.assertEqual
-        s = Template('$who likes ${what} for ${meal}')
-        eq(s.safe_substitute(dict(who='tim')), 'tim likes ${what} for ${meal}')
-        eq(s.safe_substitute(dict(what='ham')), '$who likes ham for ${meal}')
-        eq(s.safe_substitute(dict(what='ham', meal='dinner')),
-           '$who likes ham for dinner')
-        eq(s.safe_substitute(dict(who='tim', what='ham')),
-           'tim likes ham for ${meal}')
-        eq(s.safe_substitute(dict(who='tim', what='ham', meal='dinner')),
-           'tim likes ham for dinner')
-
-    def test_invalid_placeholders(self):
-        raises = self.assertRaises
-        s = Template('$who likes $')
-        raises(ValueError, s.substitute, dict(who='tim'))
-        s = Template('$who likes ${what)')
-        raises(ValueError, s.substitute, dict(who='tim'))
-        s = Template('$who likes $100')
-        raises(ValueError, s.substitute, dict(who='tim'))
-
-    def test_idpattern_override(self):
-        class PathPattern(Template):
-            idpattern = r'[_a-z][._a-z0-9]*'
-        m = Mapping()
-        m.bag = Bag()
-        m.bag.foo = Bag()
-        m.bag.foo.who = 'tim'
-        m.bag.what = 'ham'
-        s = PathPattern('$bag.foo.who likes to eat a bag of $bag.what')
-        self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
-
-    def test_pattern_override(self):
-        class MyPattern(Template):
-            pattern = r"""
-            (?P<escaped>@{2})                   |
-            @(?P<named>[_a-z][._a-z0-9]*)       |
-            @{(?P<braced>[_a-z][._a-z0-9]*)}    |
-            (?P<invalid>@)
-            """
-        m = Mapping()
-        m.bag = Bag()
-        m.bag.foo = Bag()
-        m.bag.foo.who = 'tim'
-        m.bag.what = 'ham'
-        s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what')
-        self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
-
-        class BadPattern(Template):
-            pattern = r"""
-            (?P<badname>.*)                     |
-            (?P<escaped>@{2})                   |
-            @(?P<named>[_a-z][._a-z0-9]*)       |
-            @{(?P<braced>[_a-z][._a-z0-9]*)}    |
-            (?P<invalid>@)                      |
-            """
-        s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
-        self.assertRaises(ValueError, s.substitute, {})
-        self.assertRaises(ValueError, s.safe_substitute, {})
-
-    def test_braced_override(self):
-        class MyTemplate(Template):
-            pattern = r"""
-            \$(?:
-              (?P<escaped>$)                     |
-              (?P<named>[_a-z][_a-z0-9]*)        |
-              @@(?P<braced>[_a-z][_a-z0-9]*)@@   |
-              (?P<invalid>)                      |
-           )
-           """
-
-        tmpl = 'PyCon in $@@location@@'
-        t = MyTemplate(tmpl)
-        self.assertRaises(KeyError, t.substitute, {})
-        val = t.substitute({'location': 'Cleveland'})
-        self.assertEqual(val, 'PyCon in Cleveland')
-
-    def test_braced_override_safe(self):
-        class MyTemplate(Template):
-            pattern = r"""
-            \$(?:
-              (?P<escaped>$)                     |
-              (?P<named>[_a-z][_a-z0-9]*)        |
-              @@(?P<braced>[_a-z][_a-z0-9]*)@@   |
-              (?P<invalid>)                      |
-           )
-           """
-
-        tmpl = 'PyCon in $@@location@@'
-        t = MyTemplate(tmpl)
-        self.assertEqual(t.safe_substitute(), tmpl)
-        val = t.safe_substitute({'location': 'Cleveland'})
-        self.assertEqual(val, 'PyCon in Cleveland')
-
-    def test_unicode_values(self):
-        s = Template('$who likes $what')
-        d = dict(who=u't\xffm', what=u'f\xfe\fed')
-        self.assertEqual(s.substitute(d), u't\xffm likes f\xfe\x0ced')
-
-    def test_keyword_arguments(self):
-        eq = self.assertEqual
-        s = Template('$who likes $what')
-        eq(s.substitute(who='tim', what='ham'), 'tim likes ham')
-        eq(s.substitute(dict(who='tim'), what='ham'), 'tim likes ham')
-        eq(s.substitute(dict(who='fred', what='kung pao'),
-                        who='tim', what='ham'),
-           'tim likes ham')
-        s = Template('the mapping is $mapping')
-        eq(s.substitute(dict(foo='none'), mapping='bozo'),
-           'the mapping is bozo')
-        eq(s.substitute(dict(mapping='one'), mapping='two'),
-           'the mapping is two')
-
-        s = Template('the self is $self')
-        eq(s.substitute(self='bozo'), 'the self is bozo')
-
-    def test_keyword_arguments_safe(self):
-        eq = self.assertEqual
-        raises = self.assertRaises
-        s = Template('$who likes $what')
-        eq(s.safe_substitute(who='tim', what='ham'), 'tim likes ham')
-        eq(s.safe_substitute(dict(who='tim'), what='ham'), 'tim likes ham')
-        eq(s.safe_substitute(dict(who='fred', what='kung pao'),
-                        who='tim', what='ham'),
-           'tim likes ham')
-        s = Template('the mapping is $mapping')
-        eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
-           'the mapping is bozo')
-        eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
-           'the mapping is two')
-        d = dict(mapping='one')
-        raises(TypeError, s.substitute, d, {})
-        raises(TypeError, s.safe_substitute, d, {})
-
-        s = Template('the self is $self')
-        eq(s.safe_substitute(self='bozo'), 'the self is bozo')
-
-    def test_delimiter_override(self):
-        eq = self.assertEqual
-        raises = self.assertRaises
-        class AmpersandTemplate(Template):
-            delimiter = '&'
-        s = AmpersandTemplate('this &gift is for &{who} &&')
-        eq(s.substitute(gift='bud', who='you'), 'this bud is for you &')
-        raises(KeyError, s.substitute)
-        eq(s.safe_substitute(gift='bud', who='you'), 'this bud is for you &')
-        eq(s.safe_substitute(), 'this &gift is for &{who} &')
-        s = AmpersandTemplate('this &gift is for &{who} &')
-        raises(ValueError, s.substitute, dict(gift='bud', who='you'))
-        eq(s.safe_substitute(), 'this &gift is for &{who} &')
-
-        class PieDelims(Template):
-            delimiter = '@'
-        s = PieDelims('@who likes to eat a bag of @{what} worth $100')
-        self.assertEqual(s.substitute(dict(who='tim', what='ham')),
-                         'tim likes to eat a bag of ham worth $100')
-
-
-def test_main():
-    from test import test_support
-    test_classes = [TestTemplate,]
-    test_support.run_unittest(*test_classes)
-
-
-if __name__ == '__main__':
-    test_main()
index 2db7589..bb43656 100644 (file)
@@ -1,4 +1,5 @@
 import pickle
+import struct
 from cStringIO import StringIO
 
 from test import test_support
@@ -23,17 +24,30 @@ class PickleTests(AbstractUnpickleTests, AbstractPickleTests,
 
     module = pickle
     error = KeyError
+    bad_stack_errors = (IndexError,)
+    bad_mark_errors = (IndexError, pickle.UnpicklingError,
+                       TypeError, AttributeError, EOFError)
+    truncated_errors = (pickle.UnpicklingError, EOFError,
+                        AttributeError, ValueError,
+                        struct.error, IndexError, ImportError,
+                        TypeError, KeyError)
 
 class UnpicklerTests(AbstractUnpickleTests):
 
     error = KeyError
+    bad_stack_errors = (IndexError,)
+    bad_mark_errors = (IndexError, pickle.UnpicklingError,
+                       TypeError, AttributeError, EOFError)
+    truncated_errors = (pickle.UnpicklingError, EOFError,
+                        AttributeError, ValueError,
+                        struct.error, IndexError, ImportError,
+                        TypeError, KeyError)
 
     def loads(self, buf):
         f = StringIO(buf)
         u = pickle.Unpickler(f)
         return u.load()
 
-
 class PicklerTests(AbstractPickleTests):
 
     def dumps(self, arg, proto=0, fast=0):
index 331995f..f754550 100644 (file)
@@ -67,6 +67,22 @@ class PlatformTest(unittest.TestCase):
              ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
             ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
              ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
+            ('2.4.3 (truncation, date, t) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')),
+            ('2.4.3 (truncation, date, ) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
+            ('2.4.3 (truncation, date,) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
+            ('2.4.3 (truncation, date) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
+            ('2.4.3 (truncation, d) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', 'd', 'GCC')),
+            ('2.4.3 (truncation, ) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
+            ('2.4.3 (truncation,) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
+            ('2.4.3 (truncation) \n[GCC]',
+             ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
             ):
             # branch and revision are not "parsed", but fetched
             # from sys.subversion.  Ignore them
index 686b6b9..fbb18fd 100644 (file)
@@ -198,6 +198,12 @@ class PosixPathTest(unittest.TestCase):
 
     def test_expanduser(self):
         self.assertEqual(posixpath.expanduser("foo"), "foo")
+        with test_support.EnvironmentVarGuard() as env:
+            for home in '/', '', '//', '///':
+                env['HOME'] = home
+                self.assertEqual(posixpath.expanduser("~"), "/")
+                self.assertEqual(posixpath.expanduser("~/"), "/")
+                self.assertEqual(posixpath.expanduser("~/foo"), "/foo")
         try:
             import pwd
         except ImportError:
@@ -214,9 +220,12 @@ class PosixPathTest(unittest.TestCase):
             self.assertIsInstance(posixpath.expanduser("~foo/"), basestring)
 
             with test_support.EnvironmentVarGuard() as env:
-                env['HOME'] = '/'
-                self.assertEqual(posixpath.expanduser("~"), "/")
-                self.assertEqual(posixpath.expanduser("~/foo"), "/foo")
+                # expanduser should fall back to using the password database
+                del env['HOME']
+                home = pwd.getpwuid(os.getuid()).pw_dir
+                # $HOME can end with a trailing /, so strip it (see #17809)
+                home = home.rstrip("/") or '/'
+                self.assertEqual(posixpath.expanduser("~"), home)
 
     def test_normpath(self):
         self.assertEqual(posixpath.normpath(""), ".")
index b726347..e8d9e66 100644 (file)
@@ -107,7 +107,7 @@ class TestPrint(unittest.TestCase):
         self.assertRaises(AttributeError, print, '', file='')
 
     def test_mixed_args(self):
-        # If an unicode arg is passed, sep and end should be unicode, too.
+        # If a unicode arg is passed, sep and end should be unicode, too.
         class Recorder(object):
 
             def __init__(self, must_be_unicode):
index c969d27..99f0480 100644 (file)
@@ -81,6 +81,27 @@ class TestRlcompleter(unittest.TestCase):
 def test_main():
     support.run_unittest(TestRlcompleter)
 
+    def test_duplicate_globals(self):
+        namespace = {
+            'False': None,  # Keyword vs builtin vs namespace
+            'assert': None,  # Keyword vs namespace
+            'try': lambda: None,  # Keyword vs callable
+            'memoryview': None,  # Callable builtin vs non-callable
+            'Ellipsis': lambda: None,  # Non-callable builtin vs callable
+        }
+        completer = rlcompleter.Completer(namespace)
+        self.assertEqual(completer.complete('False', 0), 'False')
+        self.assertIsNone(completer.complete('False', 1))  # No duplicates
+        self.assertEqual(completer.complete('assert', 0), 'assert')
+        self.assertIsNone(completer.complete('assert', 1))
+        self.assertEqual(completer.complete('try', 0), 'try')
+        self.assertIsNone(completer.complete('try', 1))
+        # No opening bracket "(" because we overrode the built-in class
+        self.assertEqual(completer.complete('memoryview', 0), 'memoryview')
+        self.assertIsNone(completer.complete('memoryview', 1))
+        self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(')
+        self.assertIsNone(completer.complete('Ellipsis', 1))
+
 
 if __name__ == '__main__':
     test_main()
index 76858d5..7f9fefa 100644 (file)
@@ -270,6 +270,30 @@ from ..uncle.cousin import nephew
             if verbose: print "Testing package depth:", depth
             self._check_package(depth)
 
+    def test_run_package_init_exceptions(self):
+        # These were previously wrapped in an ImportError; see Issue 14285
+        exceptions = (ImportError, AttributeError, TypeError, ValueError)
+        for exception in exceptions:
+            name = exception.__name__
+            source = "raise {0}('{0} in __init__.py.')".format(name)
+
+            result = self._make_pkg("", 1, "__main__")
+            pkg_dir, _, mod_name = result
+            mod_name = mod_name.replace(".__main__", "")
+            try:
+                init = os.path.join(pkg_dir, "__runpy_pkg__", "__init__.py")
+                with open(init, "wt") as mod_file:
+                    mod_file.write(source)
+                try:
+                    run_module(mod_name)
+                except exception as err:
+                    msg = "cannot be directly executed"
+                    self.assertNotIn(msg, format(err))
+                else:
+                    self.fail("Nothing raised; expected {}".format(name))
+            finally:
+                self._del_pkg(pkg_dir, 1, mod_name)
+
     def test_explicit_relative_import(self):
         for depth in range(2, 5):
             if verbose: print "Testing relative imports at depth:", depth
index d9ea098..62b36bd 100644 (file)
@@ -340,6 +340,9 @@ class TestJointOps(unittest.TestCase):
         gc.collect()
         self.assertTrue(ref() is None, "Cycle was not collected")
 
+    def test_free_after_iterating(self):
+        test_support.check_free_after_iterating(self, iter, self.thetype)
+
 class TestSet(TestJointOps):
     thetype = set
 
@@ -1737,7 +1740,7 @@ class TestGraphs(unittest.TestCase):
 
         # http://en.wikipedia.org/wiki/Cuboctahedron
         # 8 triangular faces and 6 square faces
-        # 12 indentical vertices each connecting a triangle and square
+        # 12 identical vertices each connecting a triangle and square
 
         g = cube(3)
         cuboctahedron = linegraph(g)            # V( --> {V1, V2, V3, V4}
index 0898449..78c4809 100644 (file)
@@ -26,8 +26,13 @@ else:
 
 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
     # need to add user site directory for tests
-    os.makedirs(site.USER_SITE)
-    site.addsitedir(site.USER_SITE)
+    try:
+        os.makedirs(site.USER_SITE)
+        site.addsitedir(site.USER_SITE)
+    except OSError as exc:
+        raise unittest.SkipTest('unable to create user site directory (%r): %s'
+                                % (site.USER_SITE, exc))
+
 
 class HelperFunctionsTests(unittest.TestCase):
     """Tests for helper functions.
index 68518d7..262ee12 100644 (file)
@@ -1,8 +1,10 @@
 # tests for slice objects; in particular the indices method.
 
 import unittest
-from test import test_support
+import weakref
+
 from cPickle import loads, dumps
+from test import test_support
 
 import sys
 
@@ -128,6 +130,15 @@ class SliceTest(unittest.TestCase):
             self.assertEqual(s.indices(15), t.indices(15))
             self.assertNotEqual(id(s), id(t))
 
+    def test_cycle(self):
+        class myobj(): pass
+        o = myobj()
+        o.s = slice(o)
+        w = weakref.ref(o)
+        o = None
+        test_support.gc_collect()
+        self.assertIsNone(w())
+
 def test_main():
     test_support.run_unittest(SliceTest)
 
index 0ce80b9..fe79b82 100644 (file)
@@ -86,7 +86,7 @@ class ThreadableTest:
         clientTearDown ()
 
     Any new test functions within the class must then define
-    tests in pairs, where the test name is preceeded with a
+    tests in pairs, where the test name is preceded with a
     '_' to indicate the client portion of the test. Ex:
 
         def testFoo(self):
@@ -708,7 +708,7 @@ class GeneralModuleTests(unittest.TestCase):
                 pass
 
     def check_sendall_interrupted(self, with_timeout):
-        # socketpair() is not stricly required, but it makes things easier.
+        # socketpair() is not strictly required, but it makes things easier.
         if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
             self.skipTest("signal.alarm and socket.socketpair required for this test")
         # Our signal handlers clobber the C errno by calling a math function
@@ -827,7 +827,7 @@ class BasicTCPTest(SocketConnectedTest):
         self.serv_conn.sendall(big_chunk)
 
     @unittest.skipUnless(hasattr(socket, 'fromfd'),
-                         'socket.fromfd not availble')
+                         'socket.fromfd not available')
     def testFromFd(self):
         # Testing fromfd()
         fd = self.cli_conn.fileno()
@@ -1755,7 +1755,7 @@ class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
         self.conn, self.connaddr = self.srv.accept()
 
     def clientSetUp(self):
-        # The is a hittable race between serverExplicitReady() and the
+        # There is a hittable race between serverExplicitReady() and the
         # accept() call; sleep a little while to avoid it, otherwise
         # we could get an exception
         time.sleep(0.1)
index 714ca4a..d645d20 100644 (file)
@@ -175,6 +175,8 @@ class SocketServerTest(unittest.TestCase):
 
     def dgram_examine(self, proto, addr):
         s = socket.socket(proto, socket.SOCK_DGRAM)
+        if HAVE_UNIX_SOCKETS and proto == socket.AF_UNIX:
+            s.bind(self.pickaddr(proto))
         s.sendto(TEST_STR, addr)
         buf = data = receive(s, 100)
         while data and '\n' not in buf:
@@ -269,27 +271,24 @@ class SocketServerTest(unittest.TestCase):
             # Make sure select was called again:
             self.assertGreater(mock_select.called, 1)
 
-    # Alas, on Linux (at least) recvfrom() doesn't return a meaningful
-    # client address so this cannot work:
-
-    # @requires_unix_sockets
-    # def test_UnixDatagramServer(self):
-    #     self.run_server(SocketServer.UnixDatagramServer,
-    #                     SocketServer.DatagramRequestHandler,
-    #                     self.dgram_examine)
-    #
-    # @requires_unix_sockets
-    # def test_ThreadingUnixDatagramServer(self):
-    #     self.run_server(SocketServer.ThreadingUnixDatagramServer,
-    #                     SocketServer.DatagramRequestHandler,
-    #                     self.dgram_examine)
-    #
-    # @requires_unix_sockets
-    # @requires_forking
-    # def test_ForkingUnixDatagramServer(self):
-    #     self.run_server(SocketServer.ForkingUnixDatagramServer,
-    #                     SocketServer.DatagramRequestHandler,
-    #                     self.dgram_examine)
+    @requires_unix_sockets
+    def test_UnixDatagramServer(self):
+        self.run_server(SocketServer.UnixDatagramServer,
+                        SocketServer.DatagramRequestHandler,
+                        self.dgram_examine)
+
+    @requires_unix_sockets
+    def test_ThreadingUnixDatagramServer(self):
+        self.run_server(SocketServer.ThreadingUnixDatagramServer,
+                        SocketServer.DatagramRequestHandler,
+                        self.dgram_examine)
+
+    @requires_unix_sockets
+    @requires_forking
+    def test_ForkingUnixDatagramServer(self):
+        self.run_server(ForkingUnixDatagramServer,
+                        SocketServer.DatagramRequestHandler,
+                        self.dgram_examine)
 
     @reap_threads
     def test_shutdown(self):
@@ -327,6 +326,30 @@ class SocketServerTest(unittest.TestCase):
                                        SocketServer.StreamRequestHandler)
 
 
+class MiscTestCase(unittest.TestCase):
+
+    def test_shutdown_request_called_if_verify_request_false(self):
+        # Issue #26309: BaseServer should call shutdown_request even if
+        # verify_request is False
+
+        class MyServer(SocketServer.TCPServer):
+            def verify_request(self, request, client_address):
+                return False
+
+            shutdown_called = 0
+            def shutdown_request(self, request):
+                self.shutdown_called += 1
+                SocketServer.TCPServer.shutdown_request(self, request)
+
+        server = MyServer((HOST, 0), SocketServer.StreamRequestHandler)
+        s = socket.socket(server.address_family, socket.SOCK_STREAM)
+        s.connect(server.server_address)
+        s.close()
+        server.handle_request()
+        self.assertEqual(server.shutdown_called, 1)
+        server.server_close()
+
+
 def test_main():
     if imp.lock_held():
         # If the import lock is held, the threads will hang
diff --git a/Lib/test/test_source_encoding.py b/Lib/test/test_source_encoding.py
new file mode 100644 (file)
index 0000000..46f0040
--- /dev/null
@@ -0,0 +1,169 @@
+# -*- coding: koi8-r -*-
+
+import unittest
+from test.test_support import run_unittest, rmtree, captured_stdout
+import script_helper
+import os
+import tempfile
+
+class MiscSourceEncodingTest(unittest.TestCase):
+
+    def test_pep263(self):
+        self.assertEqual(
+            u"ðÉÔÏÎ".encode("utf-8"),
+            '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
+        )
+        self.assertEqual(
+            u"\ð".encode("utf-8"),
+            '\\\xd0\x9f'
+        )
+
+    def test_compilestring(self):
+        # see #1882
+        c = compile("\n# coding: utf-8\nu = u'\xc3\xb3'\n", "dummy", "exec")
+        d = {}
+        exec c in d
+        self.assertEqual(d['u'], u'\xf3')
+
+    def test_issue3297(self):
+        c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec")
+        d = {}
+        exec(c, d)
+        self.assertEqual(d['a'], d['b'])
+        self.assertEqual(len(d['a']), len(d['b']))
+
+    def test_issue7820(self):
+        # Ensure that check_bom() restores all bytes in the right order if
+        # check_bom() fails in pydebug mode: a buffer starts with the first
+        # byte of a valid BOM, but next bytes are different
+
+        # one byte in common with the UTF-16-LE BOM
+        self.assertRaises(SyntaxError, eval, '\xff\x20')
+
+        # two bytes in common with the UTF-8 BOM
+        self.assertRaises(SyntaxError, eval, '\xef\xbb\x20')
+
+    def test_error_message(self):
+        compile('# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
+        compile('\xef\xbb\xbf\n', 'dummy', 'exec')
+        compile('\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
+        with self.assertRaisesRegexp(SyntaxError, 'fake'):
+            compile('# -*- coding: fake -*-\n', 'dummy', 'exec')
+        with self.assertRaisesRegexp(SyntaxError, 'iso-8859-15'):
+            compile('\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
+                    'dummy', 'exec')
+        with self.assertRaisesRegexp(SyntaxError, 'BOM'):
+            compile('\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n',
+                    'dummy', 'exec')
+        with self.assertRaisesRegexp(SyntaxError, 'fake'):
+            compile('\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
+        with self.assertRaisesRegexp(SyntaxError, 'BOM'):
+            compile('\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
+
+    def test_non_unicode_codec(self):
+        with self.assertRaisesRegexp(SyntaxError,
+                                     'codec did not return a unicode'):
+            from test import bad_coding3
+
+
+    def test_bad_coding(self):
+        module_name = 'bad_coding'
+        self.verify_bad_module(module_name)
+
+    def test_bad_coding2(self):
+        module_name = 'bad_coding2'
+        self.verify_bad_module(module_name)
+
+    def verify_bad_module(self, module_name):
+        self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
+
+        path = os.path.dirname(__file__)
+        filename = os.path.join(path, module_name + '.py')
+        with open(filename) as fp:
+            text = fp.read()
+        self.assertRaises(SyntaxError, compile, text, filename, 'exec')
+
+    def test_error_from_string(self):
+        # See http://bugs.python.org/issue6289
+        input = u"# coding: ascii\n\N{SNOWMAN}".encode('utf-8')
+        with self.assertRaises(SyntaxError) as c:
+            compile(input, "<string>", "exec")
+        expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \
+                   "ordinal not in range(128)"
+        self.assertTrue(c.exception.args[0].startswith(expected))
+
+
+class AbstractSourceEncodingTest:
+
+    def test_first_coding_line(self):
+        src = ('#coding:iso8859-15\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xc3\u20ac'")
+
+    def test_second_coding_line(self):
+        src = ('#\n'
+               '#coding:iso8859-15\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xc3\u20ac'")
+
+    def test_double_coding_line(self):
+        # If the first line matches the second line is ignored.
+        src = ('#coding:iso8859-15\n'
+               '#coding:latin1\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xc3\u20ac'")
+
+    def test_double_coding_same_line(self):
+        src = ('#coding:iso8859-15 coding:latin1\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xc3\u20ac'")
+
+    def test_first_non_utf8_coding_line(self):
+        src = ('#coding:iso-8859-15 \xa4\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xc3\u20ac'")
+
+    def test_second_non_utf8_coding_line(self):
+        src = ('\n'
+               '#coding:iso-8859-15 \xa4\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xc3\u20ac'")
+
+    def test_utf8_bom(self):
+        src = ('\xef\xbb\xbfprint(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xe4'")
+
+    def test_utf8_bom_and_utf8_coding_line(self):
+        src = ('\xef\xbb\xbf#coding:utf-8\n'
+               'print(repr(u"\xc3\xa4"))\n')
+        self.check_script_output(src, r"u'\xe4'")
+
+
+class BytesSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase):
+
+    def check_script_output(self, src, expected):
+        with captured_stdout() as stdout:
+            exec(src)
+        out = stdout.getvalue().encode('latin1')
+        self.assertEqual(out.rstrip(), expected)
+
+
+class FileSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase):
+
+    def check_script_output(self, src, expected):
+        tmpd = tempfile.mkdtemp()
+        try:
+            fn = os.path.join(tmpd, 'test.py')
+            with open(fn, 'wb') as fp:
+                fp.write(src)
+            rc, out, err = script_helper.assert_python_ok(fn)
+        finally:
+            rmtree(tmpd)
+        self.assertEqual(out.rstrip(), expected)
+
+
+def test_main():
+    run_unittest(MiscSourceEncodingTest, BytesSourceEncodingTest, FileSourceEncodingTest)
+
+if __name__ == "__main__":
+    test_main()
index 27572c3..659d0df 100644 (file)
@@ -4,6 +4,7 @@
 import sys
 import unittest
 from test import test_support as support
+from test.script_helper import assert_python_ok
 import asyncore
 import socket
 import select
@@ -57,11 +58,12 @@ SIGNED_CERTFILE = data_file("keycert3.pem")
 SIGNED_CERTFILE2 = data_file("keycert4.pem")
 SIGNING_CA = data_file("pycacert.pem")
 
-SVN_PYTHON_ORG_ROOT_CERT = data_file("https_svn_python_org_root.pem")
+REMOTE_HOST = "self-signed.pythontest.net"
+REMOTE_ROOT_CERT = data_file("selfsigned_pythontestdotnet.pem")
 
 EMPTYCERT = data_file("nullcert.pem")
 BADCERT = data_file("badcert.pem")
-WRONGCERT = data_file("XXXnonexisting.pem")
+NONEXISTINGCERT = data_file("XXXnonexisting.pem")
 BADKEY = data_file("badkey.pem")
 NOKIACERT = data_file("nokia.pem")
 NULLBYTECERT = data_file("nullbytecert.pem")
@@ -244,7 +246,7 @@ class BasicSocketTests(unittest.TestCase):
         self.assertEqual(p['subjectAltName'], san)
 
     def test_DER_to_PEM(self):
-        with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
+        with open(CAFILE_CACERT, 'r') as f:
             pem = f.read()
         d1 = ssl.PEM_cert_to_DER_cert(pem)
         p2 = ssl.DER_cert_to_PEM_cert(d1)
@@ -333,17 +335,42 @@ class BasicSocketTests(unittest.TestCase):
                                     s.connect, (HOST, 8080))
         with self.assertRaises(IOError) as cm:
             with closing(socket.socket()) as sock:
-                ssl.wrap_socket(sock, certfile=WRONGCERT)
+                ssl.wrap_socket(sock, certfile=NONEXISTINGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         with self.assertRaises(IOError) as cm:
             with closing(socket.socket()) as sock:
-                ssl.wrap_socket(sock, certfile=CERTFILE, keyfile=WRONGCERT)
+                ssl.wrap_socket(sock,
+                    certfile=CERTFILE, keyfile=NONEXISTINGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         with self.assertRaises(IOError) as cm:
             with closing(socket.socket()) as sock:
-                ssl.wrap_socket(sock, certfile=WRONGCERT, keyfile=WRONGCERT)
+                ssl.wrap_socket(sock,
+                    certfile=NONEXISTINGCERT, keyfile=NONEXISTINGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
 
+    def bad_cert_test(self, certfile):
+        """Check that trying to use the given client certificate fails"""
+        certfile = os.path.join(os.path.dirname(__file__) or os.curdir,
+                                   certfile)
+        sock = socket.socket()
+        self.addCleanup(sock.close)
+        with self.assertRaises(ssl.SSLError):
+            ssl.wrap_socket(sock,
+                            certfile=certfile,
+                            ssl_version=ssl.PROTOCOL_TLSv1)
+
+    def test_empty_cert(self):
+        """Wrapping with an empty cert file"""
+        self.bad_cert_test("nullcert.pem")
+
+    def test_malformed_cert(self):
+        """Wrapping with a badly formatted certificate (syntax error)"""
+        self.bad_cert_test("badcert.pem")
+
+    def test_malformed_key(self):
+        """Wrapping with a badly formatted key (syntax error)"""
+        self.bad_cert_test("badkey.pem")
+
     def test_match_hostname(self):
         def ok(cert, hostname):
             ssl.match_hostname(cert, hostname)
@@ -772,7 +799,7 @@ class ContextTests(unittest.TestCase):
         ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE)
         self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE)
         with self.assertRaises(IOError) as cm:
-            ctx.load_cert_chain(WRONGCERT)
+            ctx.load_cert_chain(NONEXISTINGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
             ctx.load_cert_chain(BADCERT)
@@ -792,7 +819,7 @@ class ContextTests(unittest.TestCase):
         # Mismatching key and cert
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"):
-            ctx.load_cert_chain(SVN_PYTHON_ORG_ROOT_CERT, ONLYKEY)
+            ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY)
         # Password protected key and cert
         ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD)
         ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode())
@@ -858,7 +885,7 @@ class ContextTests(unittest.TestCase):
         self.assertRaises(TypeError, ctx.load_verify_locations)
         self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None)
         with self.assertRaises(IOError) as cm:
-            ctx.load_verify_locations(WRONGCERT)
+            ctx.load_verify_locations(NONEXISTINGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         with self.assertRaises(IOError):
             ctx.load_verify_locations(u'')
@@ -936,7 +963,7 @@ class ContextTests(unittest.TestCase):
         self.assertRaises(TypeError, ctx.load_dh_params)
         self.assertRaises(TypeError, ctx.load_dh_params, None)
         with self.assertRaises(IOError) as cm:
-            ctx.load_dh_params(WRONGCERT)
+            ctx.load_dh_params(NONEXISTINGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         with self.assertRaises(ssl.SSLError) as cm:
             ctx.load_dh_params(CERTFILE)
@@ -1013,7 +1040,7 @@ class ContextTests(unittest.TestCase):
         ctx.load_verify_locations(CERTFILE)
         self.assertEqual(ctx.cert_store_stats(),
             {'x509_ca': 0, 'crl': 0, 'x509': 1})
-        ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT)
+        ctx.load_verify_locations(CAFILE_CACERT)
         self.assertEqual(ctx.cert_store_stats(),
             {'x509_ca': 1, 'crl': 0, 'x509': 2})
 
@@ -1023,8 +1050,8 @@ class ContextTests(unittest.TestCase):
         # CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE
         ctx.load_verify_locations(CERTFILE)
         self.assertEqual(ctx.get_ca_certs(), [])
-        # but SVN_PYTHON_ORG_ROOT_CERT is a CA cert
-        ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT)
+        # but CAFILE_CACERT is a CA cert
+        ctx.load_verify_locations(CAFILE_CACERT)
         self.assertEqual(ctx.get_ca_certs(),
             [{'issuer': ((('organizationName', 'Root CA'),),
                          (('organizationalUnitName', 'http://www.cacert.org'),),
@@ -1040,7 +1067,7 @@ class ContextTests(unittest.TestCase):
                           (('emailAddress', 'support@cacert.org'),)),
               'version': 3}])
 
-        with open(SVN_PYTHON_ORG_ROOT_CERT) as f:
+        with open(CAFILE_CACERT) as f:
             pem = f.read()
         der = ssl.PEM_cert_to_DER_cert(pem)
         self.assertEqual(ctx.get_ca_certs(True), [der])
@@ -1148,6 +1175,57 @@ class ContextTests(unittest.TestCase):
         self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
         self.assertEqual(ctx.options & ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv2)
 
+    def test__https_verify_certificates(self):
+        # Unit test to check the contect factory mapping
+        # The factories themselves are tested above
+        # This test will fail by design if run under PYTHONHTTPSVERIFY=0
+        # (as will various test_httplib tests)
+
+        # Uses a fresh SSL module to avoid affecting the real one
+        local_ssl = support.import_fresh_module("ssl")
+        # Certificate verification is enabled by default
+        self.assertIs(local_ssl._create_default_https_context,
+                      local_ssl.create_default_context)
+        # Turn default verification off
+        local_ssl._https_verify_certificates(enable=False)
+        self.assertIs(local_ssl._create_default_https_context,
+                      local_ssl._create_unverified_context)
+        # And back on
+        local_ssl._https_verify_certificates(enable=True)
+        self.assertIs(local_ssl._create_default_https_context,
+                      local_ssl.create_default_context)
+        # The default behaviour is to enable
+        local_ssl._https_verify_certificates(enable=False)
+        local_ssl._https_verify_certificates()
+        self.assertIs(local_ssl._create_default_https_context,
+                      local_ssl.create_default_context)
+
+    def test__https_verify_envvar(self):
+        # Unit test to check the PYTHONHTTPSVERIFY handling
+        # Need to use a subprocess so it can still be run under -E
+        https_is_verified = """import ssl, sys; \
+            status = "Error: _create_default_https_context does not verify certs" \
+                       if ssl._create_default_https_context is \
+                          ssl._create_unverified_context \
+                     else None; \
+            sys.exit(status)"""
+        https_is_not_verified = """import ssl, sys; \
+            status = "Error: _create_default_https_context verifies certs" \
+                       if ssl._create_default_https_context is \
+                          ssl.create_default_context \
+                     else None; \
+            sys.exit(status)"""
+        extra_env = {}
+        # Omitting it leaves verification on
+        assert_python_ok("-c", https_is_verified, **extra_env)
+        # Setting it to zero turns verification off
+        extra_env[ssl._https_verify_envvar] = "0"
+        assert_python_ok("-c", https_is_not_verified, **extra_env)
+        # Any other value should also leave it on
+        for setting in ("", "1", "enabled", "foo"):
+            extra_env[ssl._https_verify_envvar] = setting
+            assert_python_ok("-c", https_is_verified, **extra_env)
+
     def test_check_hostname(self):
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         self.assertFalse(ctx.check_hostname)
@@ -1215,11 +1293,11 @@ class SSLErrorTests(unittest.TestCase):
 class NetworkedTests(unittest.TestCase):
 
     def test_connect(self):
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_NONE)
             try:
-                s.connect(("svn.python.org", 443))
+                s.connect((REMOTE_HOST, 443))
                 self.assertEqual({}, s.getpeercert())
             finally:
                 s.close()
@@ -1228,27 +1306,27 @@ class NetworkedTests(unittest.TestCase):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED)
             self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
-                                   s.connect, ("svn.python.org", 443))
+                                   s.connect, (REMOTE_HOST, 443))
             s.close()
 
             # this should succeed because we specify the root cert
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED,
-                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
+                                ca_certs=REMOTE_ROOT_CERT)
             try:
-                s.connect(("svn.python.org", 443))
+                s.connect((REMOTE_HOST, 443))
                 self.assertTrue(s.getpeercert())
             finally:
                 s.close()
 
     def test_connect_ex(self):
         # Issue #11326: check connect_ex() implementation
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED,
-                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
+                                ca_certs=REMOTE_ROOT_CERT)
             try:
-                self.assertEqual(0, s.connect_ex(("svn.python.org", 443)))
+                self.assertEqual(0, s.connect_ex((REMOTE_HOST, 443)))
                 self.assertTrue(s.getpeercert())
             finally:
                 s.close()
@@ -1256,14 +1334,14 @@ class NetworkedTests(unittest.TestCase):
     def test_non_blocking_connect_ex(self):
         # Issue #11326: non-blocking connect_ex() should allow handshake
         # to proceed after the socket gets ready.
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED,
-                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT,
+                                ca_certs=REMOTE_ROOT_CERT,
                                 do_handshake_on_connect=False)
             try:
                 s.setblocking(False)
-                rc = s.connect_ex(('svn.python.org', 443))
+                rc = s.connect_ex((REMOTE_HOST, 443))
                 # EWOULDBLOCK under Windows, EINPROGRESS elsewhere
                 self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK))
                 # Wait for connect to finish
@@ -1285,58 +1363,62 @@ class NetworkedTests(unittest.TestCase):
     def test_timeout_connect_ex(self):
         # Issue #12065: on a timeout, connect_ex() should return the original
         # errno (mimicking the behaviour of non-SSL sockets).
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED,
-                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT,
+                                ca_certs=REMOTE_ROOT_CERT,
                                 do_handshake_on_connect=False)
             try:
                 s.settimeout(0.0000001)
-                rc = s.connect_ex(('svn.python.org', 443))
+                rc = s.connect_ex((REMOTE_HOST, 443))
                 if rc == 0:
-                    self.skipTest("svn.python.org responded too quickly")
+                    self.skipTest("REMOTE_HOST responded too quickly")
                 self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK))
             finally:
                 s.close()
 
     def test_connect_ex_error(self):
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED,
-                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
+                                ca_certs=REMOTE_ROOT_CERT)
             try:
-                rc = s.connect_ex(("svn.python.org", 444))
+                rc = s.connect_ex((REMOTE_HOST, 444))
                 # Issue #19919: Windows machines or VMs hosted on Windows
                 # machines sometimes return EWOULDBLOCK.
-                self.assertIn(rc, (errno.ECONNREFUSED, errno.EWOULDBLOCK))
+                errors = (
+                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
+                    errno.EWOULDBLOCK,
+                )
+                self.assertIn(rc, errors)
             finally:
                 s.close()
 
     def test_connect_with_context(self):
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             # Same as test_connect, but with a separately created context
             ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
-            s.connect(("svn.python.org", 443))
+            s.connect((REMOTE_HOST, 443))
             try:
                 self.assertEqual({}, s.getpeercert())
             finally:
                 s.close()
             # Same with a server hostname
             s = ctx.wrap_socket(socket.socket(socket.AF_INET),
-                                server_hostname="svn.python.org")
-            s.connect(("svn.python.org", 443))
+                                server_hostname=REMOTE_HOST)
+            s.connect((REMOTE_HOST, 443))
             s.close()
             # This should fail because we have no verification certs
             ctx.verify_mode = ssl.CERT_REQUIRED
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
             self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
-                                    s.connect, ("svn.python.org", 443))
+                                    s.connect, (REMOTE_HOST, 443))
             s.close()
             # This should succeed because we specify the root cert
-            ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT)
+            ctx.load_verify_locations(REMOTE_ROOT_CERT)
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
-            s.connect(("svn.python.org", 443))
+            s.connect((REMOTE_HOST, 443))
             try:
                 cert = s.getpeercert()
                 self.assertTrue(cert)
@@ -1349,12 +1431,12 @@ class NetworkedTests(unittest.TestCase):
         # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must
         # contain both versions of each certificate (same content, different
         # filename) for this test to be portable across OpenSSL releases.
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
             ctx.verify_mode = ssl.CERT_REQUIRED
             ctx.load_verify_locations(capath=CAPATH)
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
-            s.connect(("svn.python.org", 443))
+            s.connect((REMOTE_HOST, 443))
             try:
                 cert = s.getpeercert()
                 self.assertTrue(cert)
@@ -1365,7 +1447,7 @@ class NetworkedTests(unittest.TestCase):
             ctx.verify_mode = ssl.CERT_REQUIRED
             ctx.load_verify_locations(capath=BYTES_CAPATH)
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
-            s.connect(("svn.python.org", 443))
+            s.connect((REMOTE_HOST, 443))
             try:
                 cert = s.getpeercert()
                 self.assertTrue(cert)
@@ -1373,15 +1455,15 @@ class NetworkedTests(unittest.TestCase):
                 s.close()
 
     def test_connect_cadata(self):
-        with open(CAFILE_CACERT) as f:
+        with open(REMOTE_ROOT_CERT) as f:
             pem = f.read().decode('ascii')
         der = ssl.PEM_cert_to_DER_cert(pem)
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
             ctx.verify_mode = ssl.CERT_REQUIRED
             ctx.load_verify_locations(cadata=pem)
             with closing(ctx.wrap_socket(socket.socket(socket.AF_INET))) as s:
-                s.connect(("svn.python.org", 443))
+                s.connect((REMOTE_HOST, 443))
                 cert = s.getpeercert()
                 self.assertTrue(cert)
 
@@ -1390,7 +1472,7 @@ class NetworkedTests(unittest.TestCase):
             ctx.verify_mode = ssl.CERT_REQUIRED
             ctx.load_verify_locations(cadata=der)
             with closing(ctx.wrap_socket(socket.socket(socket.AF_INET))) as s:
-                s.connect(("svn.python.org", 443))
+                s.connect((REMOTE_HOST, 443))
                 cert = s.getpeercert()
                 self.assertTrue(cert)
 
@@ -1399,9 +1481,9 @@ class NetworkedTests(unittest.TestCase):
         # Issue #5238: creating a file-like object with makefile() shouldn't
         # delay closing the underlying "real socket" (here tested with its
         # file descriptor, hence skipping the test under Windows).
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             ss = ssl.wrap_socket(socket.socket(socket.AF_INET))
-            ss.connect(("svn.python.org", 443))
+            ss.connect((REMOTE_HOST, 443))
             fd = ss.fileno()
             f = ss.makefile()
             f.close()
@@ -1415,9 +1497,9 @@ class NetworkedTests(unittest.TestCase):
             self.assertEqual(e.exception.errno, errno.EBADF)
 
     def test_non_blocking_handshake(self):
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             s = socket.socket(socket.AF_INET)
-            s.connect(("svn.python.org", 443))
+            s.connect((REMOTE_HOST, 443))
             s.setblocking(False)
             s = ssl.wrap_socket(s,
                                 cert_reqs=ssl.CERT_NONE,
@@ -1460,12 +1542,12 @@ class NetworkedTests(unittest.TestCase):
                 if support.verbose:
                     sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem))
 
-        _test_get_server_certificate('svn.python.org', 443, SVN_PYTHON_ORG_ROOT_CERT)
+        _test_get_server_certificate(REMOTE_HOST, 443, REMOTE_ROOT_CERT)
         if support.IPV6_ENABLED:
             _test_get_server_certificate('ipv6.google.com', 443)
 
     def test_ciphers(self):
-        remote = ("svn.python.org", 443)
+        remote = (REMOTE_HOST, 443)
         with support.transient_internet(remote[0]):
             with closing(ssl.wrap_socket(socket.socket(socket.AF_INET),
                                          cert_reqs=ssl.CERT_NONE, ciphers="ALL")) as s:
@@ -1510,13 +1592,13 @@ class NetworkedTests(unittest.TestCase):
 
     def test_get_ca_certs_capath(self):
         # capath certs are loaded on request
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
             ctx.verify_mode = ssl.CERT_REQUIRED
             ctx.load_verify_locations(capath=CAPATH)
             self.assertEqual(ctx.get_ca_certs(), [])
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
-            s.connect(("svn.python.org", 443))
+            s.connect((REMOTE_HOST, 443))
             try:
                 cert = s.getpeercert()
                 self.assertTrue(cert)
@@ -1527,12 +1609,12 @@ class NetworkedTests(unittest.TestCase):
     @needs_sni
     def test_context_setget(self):
         # Check that the context of a connected socket can be replaced.
-        with support.transient_internet("svn.python.org"):
+        with support.transient_internet(REMOTE_HOST):
             ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
             ctx2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
             s = socket.socket(socket.AF_INET)
             with closing(ctx1.wrap_socket(s)) as ss:
-                ss.connect(("svn.python.org", 443))
+                ss.connect((REMOTE_HOST, 443))
                 self.assertIs(ss.context, ctx1)
                 self.assertIs(ss._sslobj.context, ctx1)
                 ss.context = ctx2
@@ -1866,36 +1948,6 @@ else:
             self.active = False
             self.server.close()
 
-    def bad_cert_test(certfile):
-        """
-        Launch a server with CERT_REQUIRED, and check that trying to
-        connect to it with the given client certificate fails.
-        """
-        server = ThreadedEchoServer(CERTFILE,
-                                    certreqs=ssl.CERT_REQUIRED,
-                                    cacerts=CERTFILE, chatty=False,
-                                    connectionchatty=False)
-        with server:
-            try:
-                with closing(socket.socket()) as sock:
-                    s = ssl.wrap_socket(sock,
-                                        certfile=certfile,
-                                        ssl_version=ssl.PROTOCOL_TLSv1)
-                    s.connect((HOST, server.port))
-            except ssl.SSLError as x:
-                if support.verbose:
-                    sys.stdout.write("\nSSLError is %s\n" % x.args[1])
-            except OSError as x:
-                if support.verbose:
-                    sys.stdout.write("\nOSError is %s\n" % x.args[1])
-            except OSError as x:
-                if x.errno != errno.ENOENT:
-                    raise
-                if support.verbose:
-                    sys.stdout.write("\OSError is %s\n" % str(x))
-            else:
-                raise AssertionError("Use of invalid cert should have failed!")
-
     def server_params_test(client_context, server_context, indata=b"FOO\n",
                            chatty=True, connectionchatty=False, sni_name=None):
         """
@@ -2134,22 +2186,38 @@ else:
                                                 "check_hostname requires server_hostname"):
                         context.wrap_socket(s)
 
-        def test_empty_cert(self):
-            """Connecting with an empty cert file"""
-            bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
-                                      "nullcert.pem"))
-        def test_malformed_cert(self):
-            """Connecting with a badly formatted certificate (syntax error)"""
-            bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
-                                       "badcert.pem"))
-        def test_nonexisting_cert(self):
-            """Connecting with a non-existing cert file"""
-            bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
-                                       "wrongcert.pem"))
-        def test_malformed_key(self):
-            """Connecting with a badly formatted key (syntax error)"""
-            bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
-                                       "badkey.pem"))
+        def test_wrong_cert(self):
+            """Connecting when the server rejects the client's certificate
+
+            Launch a server with CERT_REQUIRED, and check that trying to
+            connect to it with a wrong client certificate fails.
+            """
+            certfile = os.path.join(os.path.dirname(__file__) or os.curdir,
+                                       "wrongcert.pem")
+            server = ThreadedEchoServer(CERTFILE,
+                                        certreqs=ssl.CERT_REQUIRED,
+                                        cacerts=CERTFILE, chatty=False,
+                                        connectionchatty=False)
+            with server, \
+                    closing(socket.socket()) as sock, \
+                    closing(ssl.wrap_socket(sock,
+                                        certfile=certfile,
+                                        ssl_version=ssl.PROTOCOL_TLSv1)) as s:
+                try:
+                    # Expect either an SSL error about the server rejecting
+                    # the connection, or a low-level connection reset (which
+                    # sometimes happens on Windows)
+                    s.connect((HOST, server.port))
+                except ssl.SSLError as e:
+                    if support.verbose:
+                        sys.stdout.write("\nSSLError is %r\n" % e)
+                except socket.error as e:
+                    if e.errno != errno.ECONNRESET:
+                        raise
+                    if support.verbose:
+                        sys.stdout.write("\nsocket.error is %r\n" % e)
+                else:
+                    self.fail("Use of invalid cert should have failed!")
 
         def test_rude_shutdown(self):
             """A brutal shutdown of an SSL server should raise an OSError
@@ -2554,7 +2622,25 @@ else:
                         # consume data
                         s.read()
 
+                data = b"data"
+
+                # read(-1, buffer) is supported, even though read(-1) is not
+                s.send(data)
+                buffer = bytearray(len(data))
+                self.assertEqual(s.read(-1, buffer), len(data))
+                self.assertEqual(buffer, data)
+
+                # recv/read(0) should return no data
+                s.send(data)
+                self.assertEqual(s.recv(0), b"")
+                self.assertEqual(s.read(0), b"")
+                self.assertEqual(s.read(), data)
+
                 s.write(b"over\n")
+
+                self.assertRaises(ValueError, s.recv, -1)
+                self.assertRaises(ValueError, s.read, -1)
+
                 s.close()
 
         def test_handshake_timeout(self):
@@ -3026,7 +3112,7 @@ def test_main(verbose=False):
             pass
 
     for filename in [
-        CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE,
+        CERTFILE, REMOTE_ROOT_CERT, BYTES_CERTFILE,
         ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
         SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
         BADCERT, BADKEY, EMPTYCERT]:
index 9dce8fd..3c22f3f 100644 (file)
@@ -5,7 +5,7 @@
 #
 # A possible improvement would be to have empty.vbs do something that
 # we can detect here, to make sure that not only the os.startfile()
-# call succeeded, but also the the script actually has run.
+# call succeeded, but also the script actually has run.
 
 import unittest
 from test import test_support
index 774c634..5bb9f48 100644 (file)
@@ -4,6 +4,9 @@ import sys
 from test import test_support, string_tests
 
 
+class StrSubclass(str):
+    pass
+
 class StrTest(
     string_tests.CommonTest,
     string_tests.MixinStrUnicodeUserStringTest,
@@ -107,6 +110,9 @@ class StrTest(
         self.assertEqual(str(Foo6("bar")), "foos")
         self.assertEqual(str(Foo7("bar")), "foos")
         self.assertEqual(str(Foo8("foo")), "foofoo")
+        self.assertIs(type(str(Foo8("foo"))), Foo8)
+        self.assertEqual(StrSubclass(Foo8("foo")), "foofoo")
+        self.assertIs(type(StrSubclass(Foo8("foo"))), StrSubclass)
         self.assertEqual(str(Foo9("foo")), "string")
         self.assertEqual(unicode(Foo9("foo")), u"not unicode")
 
index fdb3253..94d2b67 100644 (file)
@@ -1,4 +1,6 @@
-import unittest, string
+import unittest
+import string
+from string import Template
 from test import test_support, string_tests
 from UserList import UserList
 
@@ -59,8 +61,6 @@ class StringTest(
             self.fail('exception not raised')
 
 
-
-
 class ModuleTest(unittest.TestCase):
 
     def test_attrs(self):
@@ -219,8 +219,229 @@ class BytesAliasTest(unittest.TestCase):
         self.assertTrue(type(b""), str)
         self.assertTrue(type(br""), str)
 
+
+# Template tests (formerly housed in test_pep292.py)
+
+class Bag:
+    pass
+
+class Mapping:
+    def __getitem__(self, name):
+        obj = self
+        for part in name.split('.'):
+            try:
+                obj = getattr(obj, part)
+            except AttributeError:
+                raise KeyError(name)
+        return obj
+
+
+class TestTemplate(unittest.TestCase):
+    def test_regular_templates(self):
+        s = Template('$who likes to eat a bag of $what worth $$100')
+        self.assertEqual(s.substitute(dict(who='tim', what='ham')),
+                         'tim likes to eat a bag of ham worth $100')
+        self.assertRaises(KeyError, s.substitute, dict(who='tim'))
+        self.assertRaises(TypeError, Template.substitute)
+
+    def test_regular_templates_with_braces(self):
+        s = Template('$who likes ${what} for ${meal}')
+        d = dict(who='tim', what='ham', meal='dinner')
+        self.assertEqual(s.substitute(d), 'tim likes ham for dinner')
+        self.assertRaises(KeyError, s.substitute,
+                          dict(who='tim', what='ham'))
+
+    def test_escapes(self):
+        eq = self.assertEqual
+        s = Template('$who likes to eat a bag of $$what worth $$100')
+        eq(s.substitute(dict(who='tim', what='ham')),
+           'tim likes to eat a bag of $what worth $100')
+        s = Template('$who likes $$')
+        eq(s.substitute(dict(who='tim', what='ham')), 'tim likes $')
+
+    def test_percents(self):
+        eq = self.assertEqual
+        s = Template('%(foo)s $foo ${foo}')
+        d = dict(foo='baz')
+        eq(s.substitute(d), '%(foo)s baz baz')
+        eq(s.safe_substitute(d), '%(foo)s baz baz')
+
+    def test_stringification(self):
+        eq = self.assertEqual
+        s = Template('tim has eaten $count bags of ham today')
+        d = dict(count=7)
+        eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
+        eq(s.safe_substitute(d), 'tim has eaten 7 bags of ham today')
+        s = Template('tim has eaten ${count} bags of ham today')
+        eq(s.substitute(d), 'tim has eaten 7 bags of ham today')
+
+    def test_tupleargs(self):
+        eq = self.assertEqual
+        s = Template('$who ate ${meal}')
+        d = dict(who=('tim', 'fred'), meal=('ham', 'kung pao'))
+        eq(s.substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
+        eq(s.safe_substitute(d), "('tim', 'fred') ate ('ham', 'kung pao')")
+
+    def test_SafeTemplate(self):
+        eq = self.assertEqual
+        s = Template('$who likes ${what} for ${meal}')
+        eq(s.safe_substitute(dict(who='tim')), 'tim likes ${what} for ${meal}')
+        eq(s.safe_substitute(dict(what='ham')), '$who likes ham for ${meal}')
+        eq(s.safe_substitute(dict(what='ham', meal='dinner')),
+           '$who likes ham for dinner')
+        eq(s.safe_substitute(dict(who='tim', what='ham')),
+           'tim likes ham for ${meal}')
+        eq(s.safe_substitute(dict(who='tim', what='ham', meal='dinner')),
+           'tim likes ham for dinner')
+
+    def test_invalid_placeholders(self):
+        raises = self.assertRaises
+        s = Template('$who likes $')
+        raises(ValueError, s.substitute, dict(who='tim'))
+        s = Template('$who likes ${what)')
+        raises(ValueError, s.substitute, dict(who='tim'))
+        s = Template('$who likes $100')
+        raises(ValueError, s.substitute, dict(who='tim'))
+
+    def test_idpattern_override(self):
+        class PathPattern(Template):
+            idpattern = r'[_a-z][._a-z0-9]*'
+        m = Mapping()
+        m.bag = Bag()
+        m.bag.foo = Bag()
+        m.bag.foo.who = 'tim'
+        m.bag.what = 'ham'
+        s = PathPattern('$bag.foo.who likes to eat a bag of $bag.what')
+        self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
+
+    def test_pattern_override(self):
+        class MyPattern(Template):
+            pattern = r"""
+            (?P<escaped>@{2})                   |
+            @(?P<named>[_a-z][._a-z0-9]*)       |
+            @{(?P<braced>[_a-z][._a-z0-9]*)}    |
+            (?P<invalid>@)
+            """
+        m = Mapping()
+        m.bag = Bag()
+        m.bag.foo = Bag()
+        m.bag.foo.who = 'tim'
+        m.bag.what = 'ham'
+        s = MyPattern('@bag.foo.who likes to eat a bag of @bag.what')
+        self.assertEqual(s.substitute(m), 'tim likes to eat a bag of ham')
+
+        class BadPattern(Template):
+            pattern = r"""
+            (?P<badname>.*)                     |
+            (?P<escaped>@{2})                   |
+            @(?P<named>[_a-z][._a-z0-9]*)       |
+            @{(?P<braced>[_a-z][._a-z0-9]*)}    |
+            (?P<invalid>@)                      |
+            """
+        s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
+        self.assertRaises(ValueError, s.substitute, {})
+        self.assertRaises(ValueError, s.safe_substitute, {})
+
+    def test_braced_override(self):
+        class MyTemplate(Template):
+            pattern = r"""
+            \$(?:
+              (?P<escaped>$)                     |
+              (?P<named>[_a-z][_a-z0-9]*)        |
+              @@(?P<braced>[_a-z][_a-z0-9]*)@@   |
+              (?P<invalid>)                      |
+           )
+           """
+
+        tmpl = 'PyCon in $@@location@@'
+        t = MyTemplate(tmpl)
+        self.assertRaises(KeyError, t.substitute, {})
+        val = t.substitute({'location': 'Cleveland'})
+        self.assertEqual(val, 'PyCon in Cleveland')
+
+    def test_braced_override_safe(self):
+        class MyTemplate(Template):
+            pattern = r"""
+            \$(?:
+              (?P<escaped>$)                     |
+              (?P<named>[_a-z][_a-z0-9]*)        |
+              @@(?P<braced>[_a-z][_a-z0-9]*)@@   |
+              (?P<invalid>)                      |
+           )
+           """
+
+        tmpl = 'PyCon in $@@location@@'
+        t = MyTemplate(tmpl)
+        self.assertEqual(t.safe_substitute(), tmpl)
+        val = t.safe_substitute({'location': 'Cleveland'})
+        self.assertEqual(val, 'PyCon in Cleveland')
+
+    def test_unicode_values(self):
+        s = Template('$who likes $what')
+        d = dict(who=u't\xffm', what=u'f\xfe\fed')
+        self.assertEqual(s.substitute(d), u't\xffm likes f\xfe\x0ced')
+
+    def test_keyword_arguments(self):
+        eq = self.assertEqual
+        s = Template('$who likes $what')
+        eq(s.substitute(who='tim', what='ham'), 'tim likes ham')
+        eq(s.substitute(dict(who='tim'), what='ham'), 'tim likes ham')
+        eq(s.substitute(dict(who='fred', what='kung pao'),
+                        who='tim', what='ham'),
+           'tim likes ham')
+        s = Template('the mapping is $mapping')
+        eq(s.substitute(dict(foo='none'), mapping='bozo'),
+           'the mapping is bozo')
+        eq(s.substitute(dict(mapping='one'), mapping='two'),
+           'the mapping is two')
+
+        s = Template('the self is $self')
+        eq(s.substitute(self='bozo'), 'the self is bozo')
+
+    def test_keyword_arguments_safe(self):
+        eq = self.assertEqual
+        raises = self.assertRaises
+        s = Template('$who likes $what')
+        eq(s.safe_substitute(who='tim', what='ham'), 'tim likes ham')
+        eq(s.safe_substitute(dict(who='tim'), what='ham'), 'tim likes ham')
+        eq(s.safe_substitute(dict(who='fred', what='kung pao'),
+                        who='tim', what='ham'),
+           'tim likes ham')
+        s = Template('the mapping is $mapping')
+        eq(s.safe_substitute(dict(foo='none'), mapping='bozo'),
+           'the mapping is bozo')
+        eq(s.safe_substitute(dict(mapping='one'), mapping='two'),
+           'the mapping is two')
+        d = dict(mapping='one')
+        raises(TypeError, s.substitute, d, {})
+        raises(TypeError, s.safe_substitute, d, {})
+
+        s = Template('the self is $self')
+        eq(s.safe_substitute(self='bozo'), 'the self is bozo')
+
+    def test_delimiter_override(self):
+        eq = self.assertEqual
+        raises = self.assertRaises
+        class AmpersandTemplate(Template):
+            delimiter = '&'
+        s = AmpersandTemplate('this &gift is for &{who} &&')
+        eq(s.substitute(gift='bud', who='you'), 'this bud is for you &')
+        raises(KeyError, s.substitute)
+        eq(s.safe_substitute(gift='bud', who='you'), 'this bud is for you &')
+        eq(s.safe_substitute(), 'this &gift is for &{who} &')
+        s = AmpersandTemplate('this &gift is for &{who} &')
+        raises(ValueError, s.substitute, dict(gift='bud', who='you'))
+        eq(s.safe_substitute(), 'this &gift is for &{who} &')
+
+        class PieDelims(Template):
+            delimiter = '@'
+        s = PieDelims('@who likes to eat a bag of @{what} worth $100')
+        self.assertEqual(s.substitute(dict(who='tim', what='ham')),
+                         'tim likes to eat a bag of ham worth $100')
+
+
 def test_main():
-    test_support.run_unittest(StringTest, ModuleTest, BytesAliasTest)
+    test_support.run_unittest(StringTest, ModuleTest, BytesAliasTest, TestTemplate)
 
-if __name__ == "__main__":
+if __name__ == '__main__':
     test_main()
index 7a47f9e..3d24941 100644 (file)
@@ -4,8 +4,9 @@ import unittest
 import time
 import locale
 import re
+import os
 import sys
-from test import test_support
+from test import test_support as support
 from datetime import date as datetime_date
 
 import _strptime
@@ -189,7 +190,7 @@ class TimeRETests(unittest.TestCase):
 
     def test_whitespace_substitution(self):
         # When pattern contains whitespace, make sure it is taken into account
-        # so as to not allow to subpatterns to end up next to each other and
+        # so as to not allow subpatterns to end up next to each other and
         # "steal" characters from each other.
         pattern = self.time_re.pattern('%j %H')
         self.assertFalse(re.match(pattern, "180"))
@@ -314,9 +315,10 @@ class StrptimeTests(unittest.TestCase):
         tz_name = time.tzname[0]
         if tz_name.upper() in ("UTC", "GMT"):
             self.skipTest('need non-UTC/GMT timezone')
-        try:
-            original_tzname = time.tzname
-            original_daylight = time.daylight
+
+        with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
+             support.swap_attr(time, 'daylight', 1), \
+             support.swap_attr(time, 'tzset', lambda: None):
             time.tzname = (tz_name, tz_name)
             time.daylight = 1
             tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
@@ -324,9 +326,6 @@ class StrptimeTests(unittest.TestCase):
                     "%s lead to a timezone value of %s instead of -1 when "
                     "time.daylight set to %s and passing in %s" %
                     (time.tzname, tz_value, time.daylight, tz_name))
-        finally:
-            time.tzname = original_tzname
-            time.daylight = original_daylight
 
     def test_date_time(self):
         # Test %c directive
@@ -487,14 +486,14 @@ class CalculationTests(unittest.TestCase):
     def test_week_0(self):
         def check(value, format, *expected):
             self.assertEqual(_strptime._strptime_time(value, format)[:-1], expected)
-        check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, -3)
+        check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, 362)
         check('2015 0 0', '%Y %W %w', 2015, 1, 4, 0, 0, 0, 6, 4)
-        check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, -2)
-        check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, -2)
-        check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, -1)
-        check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, -1)
-        check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 0)
-        check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 0)
+        check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, 363)
+        check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, 363)
+        check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, 364)
+        check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, 364)
+        check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 365)
+        check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 365)
         check('2015 0 4', '%Y %U %w', 2015, 1, 1, 0, 0, 0, 3, 1)
         check('2015 0 4', '%Y %W %w', 2015, 1, 1, 0, 0, 0, 3, 1)
         check('2015 0 5', '%Y %U %w', 2015, 1, 2, 0, 0, 0, 4, 2)
@@ -502,6 +501,20 @@ class CalculationTests(unittest.TestCase):
         check('2015 0 6', '%Y %U %w', 2015, 1, 3, 0, 0, 0, 5, 3)
         check('2015 0 6', '%Y %W %w', 2015, 1, 3, 0, 0, 0, 5, 3)
 
+        check('2009 0 0', '%Y %U %w', 2008, 12, 28, 0, 0, 0, 6, 363)
+        check('2009 0 0', '%Y %W %w', 2009, 1, 4, 0, 0, 0, 6, 4)
+        check('2009 0 1', '%Y %U %w', 2008, 12, 29, 0, 0, 0, 0, 364)
+        check('2009 0 1', '%Y %W %w', 2008, 12, 29, 0, 0, 0, 0, 364)
+        check('2009 0 2', '%Y %U %w', 2008, 12, 30, 0, 0, 0, 1, 365)
+        check('2009 0 2', '%Y %W %w', 2008, 12, 30, 0, 0, 0, 1, 365)
+        check('2009 0 3', '%Y %U %w', 2008, 12, 31, 0, 0, 0, 2, 366)
+        check('2009 0 3', '%Y %W %w', 2008, 12, 31, 0, 0, 0, 2, 366)
+        check('2009 0 4', '%Y %U %w', 2009, 1, 1, 0, 0, 0, 3, 1)
+        check('2009 0 4', '%Y %W %w', 2009, 1, 1, 0, 0, 0, 3, 1)
+        check('2009 0 5', '%Y %U %w', 2009, 1, 2, 0, 0, 0, 4, 2)
+        check('2009 0 5', '%Y %W %w', 2009, 1, 2, 0, 0, 0, 4, 2)
+        check('2009 0 6', '%Y %U %w', 2009, 1, 3, 0, 0, 0, 5, 3)
+        check('2009 0 6', '%Y %W %w', 2009, 1, 3, 0, 0, 0, 5, 3)
 
 class CacheTests(unittest.TestCase):
     """Test that caching works properly."""
@@ -538,7 +551,7 @@ class CacheTests(unittest.TestCase):
         _strptime._strptime_time("10", "%d")
         self.assertIsNot(locale_time_id, _strptime._TimeRE_cache.locale_time)
 
-    def test_TimeRE_recreation(self):
+    def test_TimeRE_recreation_locale(self):
         # The TimeRE instance should be recreated upon changing the locale.
         locale_info = locale.getlocale(locale.LC_TIME)
         try:
@@ -567,9 +580,36 @@ class CacheTests(unittest.TestCase):
         finally:
             locale.setlocale(locale.LC_TIME, locale_info)
 
+    @support.run_with_tz('STD-1DST')
+    def test_TimeRE_recreation_timezone(self):
+        # The TimeRE instance should be recreated upon changing the timezone.
+        oldtzname = time.tzname
+        tm = _strptime._strptime_time(time.tzname[0], '%Z')
+        self.assertEqual(tm.tm_isdst, 0)
+        tm = _strptime._strptime_time(time.tzname[1], '%Z')
+        self.assertEqual(tm.tm_isdst, 1)
+        # Get id of current cache object.
+        first_time_re = _strptime._TimeRE_cache
+        # Change the timezone and force a recreation of the cache.
+        os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'
+        time.tzset()
+        tm = _strptime._strptime_time(time.tzname[0], '%Z')
+        self.assertEqual(tm.tm_isdst, 0)
+        tm = _strptime._strptime_time(time.tzname[1], '%Z')
+        self.assertEqual(tm.tm_isdst, 1)
+        # Get the new cache object's id.
+        second_time_re = _strptime._TimeRE_cache
+        # They should not be equal.
+        self.assertIsNot(first_time_re, second_time_re)
+        # Make sure old names no longer accepted.
+        with self.assertRaises(ValueError):
+            _strptime._strptime_time(oldtzname[0], '%Z')
+        with self.assertRaises(ValueError):
+            _strptime._strptime_time(oldtzname[1], '%Z')
+
 
 def test_main():
-    test_support.run_unittest(
+    support.run_unittest(
         getlang_Tests,
         LocaleTime_Tests,
         TimeRETests,
index 06de108..ab92112 100644 (file)
@@ -285,6 +285,27 @@ class ProcessTestCase(BaseTestCase):
         tf.seek(0)
         self.assertStderrEqual(tf.read(), "strawberry")
 
+    def test_stderr_redirect_with_no_stdout_redirect(self):
+        # test stderr=STDOUT while stdout=None (not set)
+
+        # - grandchild prints to stderr
+        # - child redirects grandchild's stderr to its stdout
+        # - the parent should get grandchild's stderr in child's stdout
+        p = subprocess.Popen([sys.executable, "-c",
+                              'import sys, subprocess;'
+                              'rc = subprocess.call([sys.executable, "-c",'
+                              '    "import sys;"'
+                              '    "sys.stderr.write(\'42\')"],'
+                              '    stderr=subprocess.STDOUT);'
+                              'sys.exit(rc)'],
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.PIPE)
+        stdout, stderr = p.communicate()
+        #NOTE: stdout should get stderr from grandchild
+        self.assertStderrEqual(stdout, b'42')
+        self.assertStderrEqual(stderr, b'') # should be empty
+        self.assertEqual(p.returncode, 0)
+
     def test_stdout_stderr_pipe(self):
         # capture stdout and stderr to the same pipe
         p = subprocess.Popen([sys.executable, "-c",
index 7ce1c73..85f9965 100644 (file)
@@ -40,7 +40,7 @@ __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
            "threading_cleanup", "reap_threads", "start_threads", "cpython_only",
            "check_impl_detail", "get_attribute", "py3k_bytes",
            "import_fresh_module", "threading_cleanup", "reap_children",
-           "strip_python_stderr", "IPV6_ENABLED"]
+           "strip_python_stderr", "IPV6_ENABLED", "run_with_tz"]
 
 class Error(Exception):
     """Base class for regression test exceptions."""
@@ -1226,6 +1226,39 @@ def run_with_locale(catstr, *locales):
     return decorator
 
 #=======================================================================
+# Decorator for running a function in a specific timezone, correctly
+# resetting it afterwards.
+
+def run_with_tz(tz):
+    def decorator(func):
+        def inner(*args, **kwds):
+            try:
+                tzset = time.tzset
+            except AttributeError:
+                raise unittest.SkipTest("tzset required")
+            if 'TZ' in os.environ:
+                orig_tz = os.environ['TZ']
+            else:
+                orig_tz = None
+            os.environ['TZ'] = tz
+            tzset()
+
+            # now run the function, resetting the tz on exceptions
+            try:
+                return func(*args, **kwds)
+            finally:
+                if orig_tz is None:
+                    del os.environ['TZ']
+                else:
+                    os.environ['TZ'] = orig_tz
+                time.tzset()
+
+        inner.__name__ = func.__name__
+        inner.__doc__ = func.__doc__
+        return inner
+    return decorator
+
+#=======================================================================
 # Big-memory-test support. Separate from 'resources' because memory use should be configurable.
 
 # Some handy shorthands. Note that these are used for byte-limits as well
@@ -1626,3 +1659,21 @@ def strip_python_stderr(stderr):
     """
     stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
     return stderr
+
+
+def check_free_after_iterating(test, iter, cls, args=()):
+    class A(cls):
+        def __del__(self):
+            done[0] = True
+            try:
+                next(it)
+            except StopIteration:
+                pass
+
+    done = [False]
+    it = iter(A(*args))
+    # Issue 26494: Shouldn't crash
+    test.assertRaises(StopIteration, next, it)
+    # The sequence should be deallocated just after the end of iterating
+    gc_collect()
+    test.assertTrue(done[0])
index ab35ba4..95bd26e 100644 (file)
@@ -1,9 +1,12 @@
 # -*- coding: iso-8859-1 -*-
 import unittest, test.test_support
 from test.script_helper import assert_python_ok, assert_python_failure
-import sys, os, cStringIO
-import struct
+import cStringIO
+import gc
 import operator
+import os
+import struct
+import sys
 
 class SysModuleTest(unittest.TestCase):
 
@@ -412,7 +415,10 @@ class SysModuleTest(unittest.TestCase):
     def test_43581(self):
         # Can't use sys.stdout, as this is a cStringIO object when
         # the test runs under regrtest.
-        self.assertTrue(sys.__stdout__.encoding == sys.__stderr__.encoding)
+        if not (os.environ.get('PYTHONIOENCODING') or
+                (sys.__stdout__.isatty() and sys.__stderr__.isatty())):
+            self.skipTest('stdout/stderr encoding is not set')
+        self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding)
 
     def test_sys_flags(self):
         self.assertTrue(sys.flags)
@@ -457,7 +463,7 @@ class SysModuleTest(unittest.TestCase):
         self.assertEqual(os.path.abspath(sys.executable), sys.executable)
 
         # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
-        # has been set to an non existent program name and Python is unable to
+        # has been set to a non existent program name and Python is unable to
         # retrieve the real program name
         import subprocess
         # For a normal installation, it should work without 'cwd'
@@ -478,11 +484,6 @@ class SizeofTest(unittest.TestCase):
         self.longdigit = sys.long_info.sizeof_digit
         import _testcapi
         self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
-        self.file = open(test.test_support.TESTFN, 'wb')
-
-    def tearDown(self):
-        self.file.close()
-        test.test_support.unlink(test.test_support.TESTFN)
 
     check_sizeof = test.test_support.check_sizeof
 
@@ -526,6 +527,7 @@ class SizeofTest(unittest.TestCase):
 
     def test_objecttypes(self):
         # check all types defined in Objects/
+        calcsize = struct.calcsize
         size = test.test_support.calcobjsize
         vsize = test.test_support.calcvobjsize
         check = self.check_sizeof
@@ -589,9 +591,17 @@ class SizeofTest(unittest.TestCase):
         # method-wrapper (descriptor object)
         check({}.__iter__, size('2P'))
         # dict
-        check({}, size('3P2P' + 8*'P2P'))
+        check({}, size('3P2P') + 8*calcsize('P2P'))
         x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
-        check(x, size('3P2P' + 8*'P2P') + 16*struct.calcsize('P2P'))
+        check(x, size('3P2P') + 8*calcsize('P2P') + 16*calcsize('P2P'))
+        # dictionary-keyview
+        check({}.viewkeys(), size('P'))
+        # dictionary-valueview
+        check({}.viewvalues(), size('P'))
+        # dictionary-itemview
+        check({}.viewitems(), size('P'))
+        # dictionary iterator
+        check(iter({}), size('P2PPP'))
         # dictionary-keyiterator
         check({}.iterkeys(), size('P2PPP'))
         # dictionary-valueiterator
@@ -607,7 +617,12 @@ class SizeofTest(unittest.TestCase):
         # enumerate
         check(enumerate([]), size('l3P'))
         # file
-        check(self.file, size('4P2i4P3i3P3i'))
+        f = file(test.test_support.TESTFN, 'wb')
+        try:
+            check(f, size('4P2i4P3i3P3i'))
+        finally:
+            f.close()
+            test.test_support.unlink(test.test_support.TESTFN)
         # float
         check(float(0), size('d'))
         # sys.floatinfo
@@ -704,16 +719,16 @@ class SizeofTest(unittest.TestCase):
                 check(set(sample), s)
                 check(frozenset(sample), s)
             else:
-                check(set(sample), s + newsize*struct.calcsize('lP'))
-                check(frozenset(sample), s + newsize*struct.calcsize('lP'))
+                check(set(sample), s + newsize*calcsize('lP'))
+                check(frozenset(sample), s + newsize*calcsize('lP'))
         # setiterator
         check(iter(set()), size('P3P'))
         # slice
         check(slice(1), size('3P'))
         # str
         vh = test.test_support._vheader
-        check('', struct.calcsize(vh + 'lic'))
-        check('abc', struct.calcsize(vh + 'lic') + 3)
+        check('', calcsize(vh + 'lic'))
+        check('abc', calcsize(vh + 'lic') + 3)
         # super
         check(super(int), size('3P'))
         # tuple
@@ -722,9 +737,12 @@ class SizeofTest(unittest.TestCase):
         # tupleiterator
         check(iter(()), size('lP'))
         # type
-        # (PyTypeObject + PyNumberMethods +  PyMappingMethods +
-        #  PySequenceMethods + PyBufferProcs)
-        s = vsize('P2P15Pl4PP9PP11PI') + struct.calcsize('41P 10P 3P 6P')
+        s = vsize('P2P15Pl4PP9PP11PI'   # PyTypeObject
+                  '39P'                 # PyNumberMethods
+                  '3P'                  # PyMappingMethods
+                  '10P'                 # PySequenceMethods
+                  '6P'                  # PyBufferProcs
+                  '2P')
         class newstyleclass(object):
             pass
         check(newstyleclass, s)
@@ -751,6 +769,32 @@ class SizeofTest(unittest.TestCase):
         check(xrange(1), size('3l'))
         check(xrange(66000), size('3l'))
 
+    def check_slots(self, obj, base, extra):
+        expected = sys.getsizeof(base) + struct.calcsize(extra)
+        if gc.is_tracked(obj) and not gc.is_tracked(base):
+            expected += self.gc_headsize
+        self.assertEqual(sys.getsizeof(obj), expected)
+
+    def test_slots(self):
+        # check all subclassable types defined in Objects/ that allow
+        # non-empty __slots__
+        check = self.check_slots
+        class BA(bytearray):
+            __slots__ = 'a', 'b', 'c'
+        check(BA(), bytearray(), '3P')
+        class D(dict):
+            __slots__ = 'a', 'b', 'c'
+        check(D(x=[]), {'x': []}, '3P')
+        class L(list):
+            __slots__ = 'a', 'b', 'c'
+        check(L(), [], '3P')
+        class S(set):
+            __slots__ = 'a', 'b', 'c'
+        check(S(), set(), '3P')
+        class FS(frozenset):
+            __slots__ = 'a', 'b', 'c'
+        check(FS(), frozenset(), '3P')
+
     def test_pythontypes(self):
         # check all types defined in Python/
         size = test.test_support.calcobjsize
@@ -761,7 +805,12 @@ class SizeofTest(unittest.TestCase):
         check(_ast.AST(), size(''))
         # imp.NullImporter
         import imp
-        check(imp.NullImporter(self.file.name), size(''))
+        f = open(test.test_support.TESTFN, 'wb')
+        try:
+            check(imp.NullImporter(f.name), size(''))
+        finally:
+            f.close()
+            test.test_support.unlink(test.test_support.TESTFN)
         try:
             raise TypeError
         except TypeError:
index e82559f..18b013d 100644 (file)
@@ -165,7 +165,7 @@ class ProfileHookTestCase(TestCaseBase):
                               (1, 'return', g_ident),
                               ])
 
-    def test_exception_propogation(self):
+    def test_exception_propagation(self):
         def f(p):
             1./0
         def g(p):
index 1eea786..cc9a581 100644 (file)
@@ -386,6 +386,15 @@ class TraceTestCase(unittest.TestCase):
              (257, 'line'),
              (257, 'return')])
 
+    def test_17_none_f_trace(self):
+        # Issue 20041: fix TypeError when f_trace is set to None.
+        def func():
+            sys._getframe().f_trace = None
+            lineno = 2
+        self.run_and_compare(func,
+            [(0, 'call'),
+             (1, 'line')])
+
 
 class RaisingTraceFuncTestCase(unittest.TestCase):
     def trace(self, frame, event, arg):
index 7f7b2b4..3f9e996 100644 (file)
@@ -1,5 +1,3 @@
-# -*- coding: iso-8859-15 -*-
-
 import sys
 import os
 import shutil
@@ -62,9 +60,10 @@ class UstarReadTest(ReadTest):
         self.tar.extract("ustar/regtype", TEMPDIR)
         tarinfo = self.tar.getmember("ustar/regtype")
         fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
+        with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1:
+            lines1 = fobj1.readlines()
         fobj2 = self.tar.extractfile(tarinfo)
 
-        lines1 = fobj1.readlines()
         lines2 = fobj2.readlines()
         self.assertTrue(lines1 == lines2,
                 "fileobj.readlines() failed")
@@ -77,18 +76,17 @@ class UstarReadTest(ReadTest):
     def test_fileobj_iter(self):
         self.tar.extract("ustar/regtype", TEMPDIR)
         tarinfo = self.tar.getmember("ustar/regtype")
-        fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
+        with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1:
+            lines1 = fobj1.readlines()
         fobj2 = self.tar.extractfile(tarinfo)
-        lines1 = fobj1.readlines()
         lines2 = [line for line in fobj2]
         self.assertTrue(lines1 == lines2,
                      "fileobj.__iter__() failed")
 
     def test_fileobj_seek(self):
         self.tar.extract("ustar/regtype", TEMPDIR)
-        fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
-        data = fobj.read()
-        fobj.close()
+        with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
+            data = fobj.read()
 
         tarinfo = self.tar.getmember("ustar/regtype")
         fobj = self.tar.extractfile(tarinfo)
@@ -240,19 +238,24 @@ class CommonReadTest(ReadTest):
         # This test checks if tarfile.open() is able to open an empty tar
         # archive successfully. Note that an empty tar archive is not the
         # same as an empty file!
-        tarfile.open(tmpname, self.mode.replace("r", "w")).close()
+        with tarfile.open(tmpname, self.mode.replace("r", "w")):
+            pass
         try:
             tar = tarfile.open(tmpname, self.mode)
             tar.getnames()
         except tarfile.ReadError:
             self.fail("tarfile.open() failed on empty archive")
-        self.assertListEqual(tar.getmembers(), [])
+        else:
+            self.assertListEqual(tar.getmembers(), [])
+        finally:
+            tar.close()
 
     def test_null_tarfile(self):
         # Test for issue6123: Allow opening empty archives.
         # This test guarantees that tarfile.open() does not treat an empty
         # file as an empty tar archive.
-        open(tmpname, "wb").close()
+        with open(tmpname, "wb"):
+            pass
         self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
         self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
 
@@ -276,15 +279,16 @@ class CommonReadTest(ReadTest):
         for char in ('\0', 'a'):
             # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
             # are ignored correctly.
-            fobj = _open(tmpname, "wb")
-            fobj.write(char * 1024)
-            fobj.write(tarfile.TarInfo("foo").tobuf())
-            fobj.close()
+            with _open(tmpname, "wb") as fobj:
+                fobj.write(char * 1024)
+                fobj.write(tarfile.TarInfo("foo").tobuf())
 
             tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
-            self.assertListEqual(tar.getnames(), ["foo"],
+            try:
+                self.assertListEqual(tar.getnames(), ["foo"],
                     "ignore_zeros=True should have skipped the %r-blocks" % char)
-            tar.close()
+            finally:
+                tar.close()
 
     def test_premature_end_of_archive(self):
         for size in (512, 600, 1024, 1200):
@@ -315,19 +319,21 @@ class MiscReadTest(CommonReadTest):
     taropen = tarfile.TarFile.taropen
 
     def test_no_name_argument(self):
-        fobj = open(self.tarname, "rb")
-        tar = tarfile.open(fileobj=fobj, mode=self.mode)
-        self.assertEqual(tar.name, os.path.abspath(fobj.name))
+        with open(self.tarname, "rb") as fobj:
+            tar = tarfile.open(fileobj=fobj, mode=self.mode)
+            self.assertEqual(tar.name, os.path.abspath(fobj.name))
 
     def test_no_name_attribute(self):
-        data = open(self.tarname, "rb").read()
+        with open(self.tarname, "rb") as fobj:
+            data = fobj.read()
         fobj = StringIO.StringIO(data)
         self.assertRaises(AttributeError, getattr, fobj, "name")
         tar = tarfile.open(fileobj=fobj, mode=self.mode)
         self.assertEqual(tar.name, None)
 
     def test_empty_name_attribute(self):
-        data = open(self.tarname, "rb").read()
+        with open(self.tarname, "rb") as fobj:
+            data = fobj.read()
         fobj = StringIO.StringIO(data)
         fobj.name = ""
         tar = tarfile.open(fileobj=fobj, mode=self.mode)
@@ -348,12 +354,14 @@ class MiscReadTest(CommonReadTest):
         # Skip the first member and store values from the second member
         # of the testtar.
         tar = tarfile.open(self.tarname, mode=self.mode)
-        tar.next()
-        t = tar.next()
-        name = t.name
-        offset = t.offset
-        data = tar.extractfile(t).read()
-        tar.close()
+        try:
+            tar.next()
+            t = tar.next()
+            name = t.name
+            offset = t.offset
+            data = tar.extractfile(t).read()
+        finally:
+            tar.close()
 
         # Open the testtar and seek to the offset of the second member.
         if self.mode.endswith(":gz"):
@@ -363,26 +371,30 @@ class MiscReadTest(CommonReadTest):
         else:
             _open = open
         fobj = _open(self.tarname, "rb")
-        fobj.seek(offset)
-
-        # Test if the tarfile starts with the second member.
-        tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
-        t = tar.next()
-        self.assertEqual(t.name, name)
-        # Read to the end of fileobj and test if seeking back to the
-        # beginning works.
-        tar.getmembers()
-        self.assertEqual(tar.extractfile(t).read(), data,
-                "seek back did not work")
-        tar.close()
+        try:
+            fobj.seek(offset)
+
+            # Test if the tarfile starts with the second member.
+            tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
+            t = tar.next()
+            self.assertEqual(t.name, name)
+            # Read to the end of fileobj and test if seeking back to the
+            # beginning works.
+            tar.getmembers()
+            self.assertEqual(tar.extractfile(t).read(), data,
+                    "seek back did not work")
+            tar.close()
+        finally:
+            fobj.close()
 
     def test_fail_comp(self):
         # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
         if self.mode == "r:":
             self.skipTest('needs a gz or bz2 mode')
         self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
-        fobj = open(tarname, "rb")
-        self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
+        with open(tarname, "rb") as fobj:
+            self.assertRaises(tarfile.ReadError, tarfile.open,
+                              fileobj=fobj, mode=self.mode)
 
     def test_v7_dirtype(self):
         # Test old style dirtype member (bug #1336623):
@@ -436,22 +448,25 @@ class MiscReadTest(CommonReadTest):
         # Test if extractall() correctly restores directory permissions
         # and times (see issue1735).
         tar = tarfile.open(tarname, encoding="iso8859-1")
-        directories = [t for t in tar if t.isdir()]
-        tar.extractall(TEMPDIR, directories)
-        for tarinfo in directories:
-            path = os.path.join(TEMPDIR, tarinfo.name)
-            if sys.platform != "win32":
-                # Win32 has no support for fine grained permissions.
-                self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
-            self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
-        tar.close()
+        try:
+            directories = [t for t in tar if t.isdir()]
+            tar.extractall(TEMPDIR, directories)
+            for tarinfo in directories:
+                path = os.path.join(TEMPDIR, tarinfo.name)
+                if sys.platform != "win32":
+                    # Win32 has no support for fine grained permissions.
+                    self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
+                self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
+        finally:
+            tar.close()
 
     def test_init_close_fobj(self):
         # Issue #7341: Close the internal file object in the TarFile
         # constructor in case of an error. For the test we rely on
         # the fact that opening an empty file raises a ReadError.
         empty = os.path.join(TEMPDIR, "empty")
-        open(empty, "wb").write("")
+        with open(empty, "wb") as fobj:
+            fobj.write("")
 
         try:
             tar = object.__new__(tarfile.TarFile)
@@ -462,7 +477,7 @@ class MiscReadTest(CommonReadTest):
             else:
                 self.fail("ReadError not raised")
         finally:
-            os.remove(empty)
+            support.unlink(empty)
 
     def test_parallel_iteration(self):
         # Issue #16601: Restarting iteration over tarfile continued
@@ -491,42 +506,47 @@ class StreamReadTest(CommonReadTest):
 
     def test_compare_members(self):
         tar1 = tarfile.open(tarname, encoding="iso8859-1")
-        tar2 = self.tar
-
-        while True:
-            t1 = tar1.next()
-            t2 = tar2.next()
-            if t1 is None:
-                break
-            self.assertTrue(t2 is not None, "stream.next() failed.")
-
-            if t2.islnk() or t2.issym():
-                self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
-                continue
-
-            v1 = tar1.extractfile(t1)
-            v2 = tar2.extractfile(t2)
-            if v1 is None:
-                continue
-            self.assertTrue(v2 is not None, "stream.extractfile() failed")
-            self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
-
-        tar1.close()
+        try:
+            tar2 = self.tar
+
+            while True:
+                t1 = tar1.next()
+                t2 = tar2.next()
+                if t1 is None:
+                    break
+                self.assertTrue(t2 is not None, "stream.next() failed.")
+
+                if t2.islnk() or t2.issym():
+                    self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
+                    continue
+
+                v1 = tar1.extractfile(t1)
+                v2 = tar2.extractfile(t2)
+                if v1 is None:
+                    continue
+                self.assertTrue(v2 is not None, "stream.extractfile() failed")
+                self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
+        finally:
+            tar1.close()
 
 
 class DetectReadTest(unittest.TestCase):
 
     def _testfunc_file(self, name, mode):
         try:
-            tarfile.open(name, mode)
+            tar = tarfile.open(name, mode)
         except tarfile.ReadError:
             self.fail()
+        else:
+            tar.close()
 
     def _testfunc_fileobj(self, name, mode):
         try:
-            tarfile.open(name, mode, fileobj=open(name, "rb"))
+            tar = tarfile.open(name, mode, fileobj=open(name, "rb"))
         except tarfile.ReadError:
             self.fail()
+        else:
+            tar.close()
 
     def _test_modes(self, testfunc):
         testfunc(tarname, "r")
@@ -640,7 +660,7 @@ class MemberReadTest(ReadTest):
         self._test_member(tarinfo, size=86016, chksum=md5_sparse)
 
     def test_find_umlauts(self):
-        tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
+        tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
         self._test_member(tarinfo, size=7011, chksum=md5_regtype)
 
     def test_find_ustar_longname(self):
@@ -653,7 +673,7 @@ class MemberReadTest(ReadTest):
 
     def test_find_pax_umlauts(self):
         self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
-        tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
+        tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
         self._test_member(tarinfo, size=7011, chksum=md5_regtype)
 
 
@@ -717,33 +737,39 @@ class PaxReadTest(LongnameTest):
 
     def test_pax_global_headers(self):
         tar = tarfile.open(tarname, encoding="iso8859-1")
+        try:
 
-        tarinfo = tar.getmember("pax/regtype1")
-        self.assertEqual(tarinfo.uname, "foo")
-        self.assertEqual(tarinfo.gname, "bar")
-        self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
+            tarinfo = tar.getmember("pax/regtype1")
+            self.assertEqual(tarinfo.uname, "foo")
+            self.assertEqual(tarinfo.gname, "bar")
+            self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
 
-        tarinfo = tar.getmember("pax/regtype2")
-        self.assertEqual(tarinfo.uname, "")
-        self.assertEqual(tarinfo.gname, "bar")
-        self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
+            tarinfo = tar.getmember("pax/regtype2")
+            self.assertEqual(tarinfo.uname, "")
+            self.assertEqual(tarinfo.gname, "bar")
+            self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
 
-        tarinfo = tar.getmember("pax/regtype3")
-        self.assertEqual(tarinfo.uname, "tarfile")
-        self.assertEqual(tarinfo.gname, "tarfile")
-        self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
+            tarinfo = tar.getmember("pax/regtype3")
+            self.assertEqual(tarinfo.uname, "tarfile")
+            self.assertEqual(tarinfo.gname, "tarfile")
+            self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
+        finally:
+            tar.close()
 
     def test_pax_number_fields(self):
         # All following number fields are read from the pax header.
         tar = tarfile.open(tarname, encoding="iso8859-1")
-        tarinfo = tar.getmember("pax/regtype4")
-        self.assertEqual(tarinfo.size, 7011)
-        self.assertEqual(tarinfo.uid, 123)
-        self.assertEqual(tarinfo.gid, 123)
-        self.assertEqual(tarinfo.mtime, 1041808783.0)
-        self.assertEqual(type(tarinfo.mtime), float)
-        self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
-        self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
+        try:
+            tarinfo = tar.getmember("pax/regtype4")
+            self.assertEqual(tarinfo.size, 7011)
+            self.assertEqual(tarinfo.uid, 123)
+            self.assertEqual(tarinfo.gid, 123)
+            self.assertEqual(tarinfo.mtime, 1041808783.0)
+            self.assertEqual(type(tarinfo.mtime), float)
+            self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
+            self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
+        finally:
+            tar.close()
 
 
 class WriteTestBase(unittest.TestCase):
@@ -775,52 +801,60 @@ class WriteTest(WriteTestBase):
         # a trailing '\0'.
         name = "0123456789" * 10
         tar = tarfile.open(tmpname, self.mode)
-        t = tarfile.TarInfo(name)
-        tar.addfile(t)
-        tar.close()
+        try:
+            t = tarfile.TarInfo(name)
+            tar.addfile(t)
+        finally:
+            tar.close()
 
         tar = tarfile.open(tmpname)
-        self.assertTrue(tar.getnames()[0] == name,
-                "failed to store 100 char filename")
-        tar.close()
+        try:
+            self.assertTrue(tar.getnames()[0] == name,
+                    "failed to store 100 char filename")
+        finally:
+            tar.close()
 
     def test_tar_size(self):
         # Test for bug #1013882.
         tar = tarfile.open(tmpname, self.mode)
-        path = os.path.join(TEMPDIR, "file")
-        fobj = open(path, "wb")
-        fobj.write("aaa")
-        fobj.close()
-        tar.add(path)
-        tar.close()
+        try:
+            path = os.path.join(TEMPDIR, "file")
+            with open(path, "wb") as fobj:
+                fobj.write("aaa")
+            tar.add(path)
+        finally:
+            tar.close()
         self.assertTrue(os.path.getsize(tmpname) > 0,
                 "tarfile is empty")
 
     # The test_*_size tests test for bug #1167128.
     def test_file_size(self):
         tar = tarfile.open(tmpname, self.mode)
+        try:
 
-        path = os.path.join(TEMPDIR, "file")
-        fobj = open(path, "wb")
-        fobj.close()
-        tarinfo = tar.gettarinfo(path)
-        self.assertEqual(tarinfo.size, 0)
-
-        fobj = open(path, "wb")
-        fobj.write("aaa")
-        fobj.close()
-        tarinfo = tar.gettarinfo(path)
-        self.assertEqual(tarinfo.size, 3)
+            path = os.path.join(TEMPDIR, "file")
+            with open(path, "wb"):
+                pass
+            tarinfo = tar.gettarinfo(path)
+            self.assertEqual(tarinfo.size, 0)
 
-        tar.close()
+            with open(path, "wb") as fobj:
+                fobj.write("aaa")
+            tarinfo = tar.gettarinfo(path)
+            self.assertEqual(tarinfo.size, 3)
+        finally:
+            tar.close()
 
     def test_directory_size(self):
         path = os.path.join(TEMPDIR, "directory")
         os.mkdir(path)
         try:
             tar = tarfile.open(tmpname, self.mode)
-            tarinfo = tar.gettarinfo(path)
-            self.assertEqual(tarinfo.size, 0)
+            try:
+                tarinfo = tar.gettarinfo(path)
+                self.assertEqual(tarinfo.size, 0)
+            finally:
+                tar.close()
         finally:
             os.rmdir(path)
 
@@ -828,16 +862,18 @@ class WriteTest(WriteTestBase):
         if hasattr(os, "link"):
             link = os.path.join(TEMPDIR, "link")
             target = os.path.join(TEMPDIR, "link_target")
-            fobj = open(target, "wb")
-            fobj.write("aaa")
-            fobj.close()
+            with open(target, "wb") as fobj:
+                fobj.write("aaa")
             os.link(target, link)
             try:
                 tar = tarfile.open(tmpname, self.mode)
-                # Record the link target in the inodes list.
-                tar.gettarinfo(target)
-                tarinfo = tar.gettarinfo(link)
-                self.assertEqual(tarinfo.size, 0)
+                try:
+                    # Record the link target in the inodes list.
+                    tar.gettarinfo(target)
+                    tarinfo = tar.gettarinfo(link)
+                    self.assertEqual(tarinfo.size, 0)
+                finally:
+                    tar.close()
             finally:
                 os.remove(target)
                 os.remove(link)
@@ -848,26 +884,30 @@ class WriteTest(WriteTestBase):
             os.symlink("link_target", path)
             try:
                 tar = tarfile.open(tmpname, self.mode)
-                tarinfo = tar.gettarinfo(path)
-                self.assertEqual(tarinfo.size, 0)
+                try:
+                    tarinfo = tar.gettarinfo(path)
+                    self.assertEqual(tarinfo.size, 0)
+                finally:
+                    tar.close()
             finally:
                 os.remove(path)
 
     def test_add_self(self):
         # Test for #1257255.
         dstname = os.path.abspath(tmpname)
-
         tar = tarfile.open(tmpname, self.mode)
-        self.assertTrue(tar.name == dstname, "archive name must be absolute")
-
-        tar.add(dstname)
-        self.assertTrue(tar.getnames() == [], "added the archive to itself")
-
-        cwd = os.getcwd()
-        os.chdir(TEMPDIR)
-        tar.add(dstname)
-        os.chdir(cwd)
-        self.assertTrue(tar.getnames() == [], "added the archive to itself")
+        try:
+            self.assertTrue(tar.name == dstname, "archive name must be absolute")
+            tar.add(dstname)
+            self.assertTrue(tar.getnames() == [], "added the archive to itself")
+
+            cwd = os.getcwd()
+            os.chdir(TEMPDIR)
+            tar.add(dstname)
+            os.chdir(cwd)
+            self.assertTrue(tar.getnames() == [], "added the archive to itself")
+        finally:
+            tar.close()
 
     def test_exclude(self):
         tempdir = os.path.join(TEMPDIR, "exclude")
@@ -880,14 +920,19 @@ class WriteTest(WriteTestBase):
             exclude = os.path.isfile
 
             tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
-            with test_support.check_warnings(("use the filter argument",
-                                              DeprecationWarning)):
-                tar.add(tempdir, arcname="empty_dir", exclude=exclude)
-            tar.close()
+            try:
+                with test_support.check_warnings(("use the filter argument",
+                                                DeprecationWarning)):
+                    tar.add(tempdir, arcname="empty_dir", exclude=exclude)
+            finally:
+                tar.close()
 
             tar = tarfile.open(tmpname, "r")
-            self.assertEqual(len(tar.getmembers()), 1)
-            self.assertEqual(tar.getnames()[0], "empty_dir")
+            try:
+                self.assertEqual(len(tar.getmembers()), 1)
+                self.assertEqual(tar.getnames()[0], "empty_dir")
+            finally:
+                tar.close()
         finally:
             shutil.rmtree(tempdir)
 
@@ -907,15 +952,19 @@ class WriteTest(WriteTestBase):
                 return tarinfo
 
             tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
-            tar.add(tempdir, arcname="empty_dir", filter=filter)
-            tar.close()
+            try:
+                tar.add(tempdir, arcname="empty_dir", filter=filter)
+            finally:
+                tar.close()
 
             tar = tarfile.open(tmpname, "r")
-            for tarinfo in tar:
-                self.assertEqual(tarinfo.uid, 123)
-                self.assertEqual(tarinfo.uname, "foo")
-            self.assertEqual(len(tar.getmembers()), 3)
-            tar.close()
+            try:
+                for tarinfo in tar:
+                    self.assertEqual(tarinfo.uid, 123)
+                    self.assertEqual(tarinfo.uname, "foo")
+                self.assertEqual(len(tar.getmembers()), 3)
+            finally:
+                tar.close()
         finally:
             shutil.rmtree(tempdir)
 
@@ -933,12 +982,16 @@ class WriteTest(WriteTestBase):
             os.mkdir(foo)
 
         tar = tarfile.open(tmpname, self.mode)
-        tar.add(foo, arcname=path)
-        tar.close()
+        try:
+            tar.add(foo, arcname=path)
+        finally:
+            tar.close()
 
         tar = tarfile.open(tmpname, "r")
-        t = tar.next()
-        tar.close()
+        try:
+            t = tar.next()
+        finally:
+            tar.close()
 
         if not dir:
             os.remove(foo)
@@ -974,16 +1027,18 @@ class WriteTest(WriteTestBase):
     def test_cwd(self):
         # Test adding the current working directory.
         with support.change_cwd(TEMPDIR):
-            open("foo", "w").close()
-
             tar = tarfile.open(tmpname, self.mode)
-            tar.add(".")
-            tar.close()
+            try:
+                tar.add(".")
+            finally:
+                tar.close()
 
             tar = tarfile.open(tmpname, "r")
-            for t in tar:
-                self.assertTrue(t.name == "." or t.name.startswith("./"))
-            tar.close()
+            try:
+                for t in tar:
+                    self.assertTrue(t.name == "." or t.name.startswith("./"))
+            finally:
+                tar.close()
 
     @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
     def test_extractall_symlinks(self):
@@ -1100,19 +1155,18 @@ class StreamWriteTest(WriteTestBase):
         tar.close()
 
         if self.mode.endswith("gz"):
-            fobj = gzip.GzipFile(tmpname)
-            data = fobj.read()
-            fobj.close()
+            with gzip.GzipFile(tmpname) as fobj:
+                data = fobj.read()
         elif self.mode.endswith("bz2"):
             dec = bz2.BZ2Decompressor()
-            data = open(tmpname, "rb").read()
+            with open(tmpname, "rb") as fobj:
+                data = fobj.read()
             data = dec.decompress(data)
             self.assertTrue(len(dec.unused_data) == 0,
                     "found trailing data")
         else:
-            fobj = open(tmpname, "rb")
-            data = fobj.read()
-            fobj.close()
+            with open(tmpname, "rb") as fobj:
+                data = fobj.read()
 
         self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
                          "incorrect zero padding")
@@ -1173,23 +1227,27 @@ class GNUWriteTest(unittest.TestCase):
             tarinfo.type = tarfile.LNKTYPE
 
         tar = tarfile.open(tmpname, "w")
-        tar.format = tarfile.GNU_FORMAT
-        tar.addfile(tarinfo)
-
-        v1 = self._calc_size(name, link)
-        v2 = tar.offset
-        self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
+        try:
+            tar.format = tarfile.GNU_FORMAT
+            tar.addfile(tarinfo)
 
-        tar.close()
+            v1 = self._calc_size(name, link)
+            v2 = tar.offset
+            self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
+        finally:
+            tar.close()
 
         tar = tarfile.open(tmpname)
-        member = tar.next()
-        self.assertIsNotNone(member,
-                "unable to read longname member")
-        self.assertEqual(tarinfo.name, member.name,
-                "unable to read longname member")
-        self.assertEqual(tarinfo.linkname, member.linkname,
-                "unable to read longname member")
+        try:
+            member = tar.next()
+            self.assertIsNotNone(member,
+                    "unable to read longname member")
+            self.assertEqual(tarinfo.name, member.name,
+                    "unable to read longname member")
+            self.assertEqual(tarinfo.linkname, member.linkname,
+                    "unable to read longname member")
+        finally:
+            tar.close()
 
     def test_longname_1023(self):
         self._test(("longnam/" * 127) + "longnam")
@@ -1229,9 +1287,8 @@ class HardlinkTest(unittest.TestCase):
         self.foo = os.path.join(TEMPDIR, "foo")
         self.bar = os.path.join(TEMPDIR, "bar")
 
-        fobj = open(self.foo, "wb")
-        fobj.write("foo")
-        fobj.close()
+        with open(self.foo, "wb") as fobj:
+            fobj.write("foo")
 
         os.link(self.foo, self.bar)
 
@@ -1240,8 +1297,8 @@ class HardlinkTest(unittest.TestCase):
 
     def tearDown(self):
         self.tar.close()
-        os.remove(self.foo)
-        os.remove(self.bar)
+        support.unlink(self.foo)
+        support.unlink(self.bar)
 
     def test_add_twice(self):
         # The same name will be added as a REGTYPE every
@@ -1272,44 +1329,54 @@ class PaxWriteTest(GNUWriteTest):
             tarinfo.type = tarfile.LNKTYPE
 
         tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
-        tar.addfile(tarinfo)
-        tar.close()
+        try:
+            tar.addfile(tarinfo)
+        finally:
+            tar.close()
 
         tar = tarfile.open(tmpname)
-        if link:
-            l = tar.getmembers()[0].linkname
-            self.assertTrue(link == l, "PAX longlink creation failed")
-        else:
-            n = tar.getmembers()[0].name
-            self.assertTrue(name == n, "PAX longname creation failed")
+        try:
+            if link:
+                l = tar.getmembers()[0].linkname
+                self.assertTrue(link == l, "PAX longlink creation failed")
+            else:
+                n = tar.getmembers()[0].name
+                self.assertTrue(name == n, "PAX longname creation failed")
+        finally:
+            tar.close()
 
     def test_pax_global_header(self):
         pax_headers = {
                 u"foo": u"bar",
                 u"uid": u"0",
                 u"mtime": u"1.23",
-                u"test": u"äöü",
-                u"äöü": u"test"}
+                u"test": u"\xe4\xf6\xfc",
+                u"\xe4\xf6\xfc": u"test"}
 
         tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
                 pax_headers=pax_headers)
-        tar.addfile(tarfile.TarInfo("test"))
-        tar.close()
+        try:
+            tar.addfile(tarfile.TarInfo("test"))
+        finally:
+            tar.close()
 
         # Test if the global header was written correctly.
         tar = tarfile.open(tmpname, encoding="iso8859-1")
-        self.assertEqual(tar.pax_headers, pax_headers)
-        self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
-
-        # Test if all the fields are unicode.
-        for key, val in tar.pax_headers.iteritems():
-            self.assertTrue(type(key) is unicode)
-            self.assertTrue(type(val) is unicode)
-            if key in tarfile.PAX_NUMBER_FIELDS:
-                try:
-                    tarfile.PAX_NUMBER_FIELDS[key](val)
-                except (TypeError, ValueError):
-                    self.fail("unable to convert pax header field")
+        try:
+            self.assertEqual(tar.pax_headers, pax_headers)
+            self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
+
+            # Test if all the fields are unicode.
+            for key, val in tar.pax_headers.iteritems():
+                self.assertTrue(type(key) is unicode)
+                self.assertTrue(type(val) is unicode)
+                if key in tarfile.PAX_NUMBER_FIELDS:
+                    try:
+                        tarfile.PAX_NUMBER_FIELDS[key](val)
+                    except (TypeError, ValueError):
+                        self.fail("unable to convert pax header field")
+        finally:
+            tar.close()
 
     def test_pax_extended_header(self):
         # The fields from the pax header have priority over the
@@ -1317,18 +1384,23 @@ class PaxWriteTest(GNUWriteTest):
         pax_headers = {u"path": u"foo", u"uid": u"123"}
 
         tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
-        t = tarfile.TarInfo()
-        t.name = u"äöü"     # non-ASCII
-        t.uid = 8**8        # too large
-        t.pax_headers = pax_headers
-        tar.addfile(t)
-        tar.close()
+        try:
+            t = tarfile.TarInfo()
+            t.name = u"\xe4\xf6\xfc"     # non-ASCII
+            t.uid = 8**8        # too large
+            t.pax_headers = pax_headers
+            tar.addfile(t)
+        finally:
+            tar.close()
 
         tar = tarfile.open(tmpname, encoding="iso8859-1")
-        t = tar.getmembers()[0]
-        self.assertEqual(t.pax_headers, pax_headers)
-        self.assertEqual(t.name, "foo")
-        self.assertEqual(t.uid, 123)
+        try:
+            t = tar.getmembers()[0]
+            self.assertEqual(t.pax_headers, pax_headers)
+            self.assertEqual(t.name, "foo")
+            self.assertEqual(t.uid, 123)
+        finally:
+            tar.close()
 
 
 class UstarUnicodeTest(unittest.TestCase):
@@ -1347,57 +1419,68 @@ class UstarUnicodeTest(unittest.TestCase):
 
     def _test_unicode_filename(self, encoding):
         tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
-        name = u"äöü"
-        tar.addfile(tarfile.TarInfo(name))
-        tar.close()
+        try:
+            name = u"\xe4\xf6\xfc"
+            tar.addfile(tarfile.TarInfo(name))
+        finally:
+            tar.close()
 
         tar = tarfile.open(tmpname, encoding=encoding)
-        self.assertTrue(type(tar.getnames()[0]) is not unicode)
-        self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
-        tar.close()
+        try:
+            self.assertTrue(type(tar.getnames()[0]) is not unicode)
+            self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
+        finally:
+            tar.close()
 
     def test_unicode_filename_error(self):
         tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
-        tarinfo = tarfile.TarInfo()
+        try:
+            tarinfo = tarfile.TarInfo()
 
-        tarinfo.name = "äöü"
-        if self.format == tarfile.PAX_FORMAT:
-            self.assertRaises(UnicodeError, tar.addfile, tarinfo)
-        else:
-            tar.addfile(tarinfo)
+            tarinfo.name = "\xe4\xf6\xfc"
+            if self.format == tarfile.PAX_FORMAT:
+                self.assertRaises(UnicodeError, tar.addfile, tarinfo)
+            else:
+                tar.addfile(tarinfo)
 
-        tarinfo.name = u"äöü"
-        self.assertRaises(UnicodeError, tar.addfile, tarinfo)
+            tarinfo.name = u"\xe4\xf6\xfc"
+            self.assertRaises(UnicodeError, tar.addfile, tarinfo)
 
-        tarinfo.name = "foo"
-        tarinfo.uname = u"äöü"
-        self.assertRaises(UnicodeError, tar.addfile, tarinfo)
+            tarinfo.name = "foo"
+            tarinfo.uname = u"\xe4\xf6\xfc"
+            self.assertRaises(UnicodeError, tar.addfile, tarinfo)
+        finally:
+            tar.close()
 
     def test_unicode_argument(self):
         tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
-        for t in tar:
-            self.assertTrue(type(t.name) is str)
-            self.assertTrue(type(t.linkname) is str)
-            self.assertTrue(type(t.uname) is str)
-            self.assertTrue(type(t.gname) is str)
-        tar.close()
+        try:
+            for t in tar:
+                self.assertTrue(type(t.name) is str)
+                self.assertTrue(type(t.linkname) is str)
+                self.assertTrue(type(t.uname) is str)
+                self.assertTrue(type(t.gname) is str)
+        finally:
+            tar.close()
 
     def test_uname_unicode(self):
-        for name in (u"äöü", "äöü"):
+        for name in (u"\xe4\xf6\xfc", "\xe4\xf6\xfc"):
             t = tarfile.TarInfo("foo")
             t.uname = name
             t.gname = name
 
             fobj = StringIO.StringIO()
             tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
-            tar.addfile(t)
-            tar.close()
+            try:
+                tar.addfile(t)
+            finally:
+                tar.close()
             fobj.seek(0)
 
             tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
             t = tar.getmember("foo")
-            self.assertEqual(t.uname, "äöü")
-            self.assertEqual(t.gname, "äöü")
+            self.assertEqual(t.uname, "\xe4\xf6\xfc")
+            self.assertEqual(t.gname, "\xe4\xf6\xfc")
 
 
 class GNUUnicodeTest(UstarUnicodeTest):
@@ -1419,9 +1502,9 @@ class PaxUnicodeTest(UstarUnicodeTest):
     def test_error_handlers(self):
         # Test if the unicode error handlers work correctly for characters
         # that cannot be expressed in a given encoding.
-        self._create_unicode_name(u"äöü")
+        self._create_unicode_name(u"\xe4\xf6\xfc")
 
-        for handler, name in (("utf-8", u"äöü".encode("utf8")),
+        for handler, name in (("utf-8", u"\xe4\xf6\xfc".encode("utf8")),
                     ("replace", "???"), ("ignore", "")):
             tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
                     errors=handler)
@@ -1433,11 +1516,11 @@ class PaxUnicodeTest(UstarUnicodeTest):
     def test_error_handler_utf8(self):
         # Create a pathname that has one component representable using
         # iso8859-1 and the other only in iso8859-15.
-        self._create_unicode_name(u"äöü/¤")
+        self._create_unicode_name(u"\xe4\xf6\xfc/\u20ac")
 
         tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
                 errors="utf-8")
-        self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
+        self.assertEqual(tar.getnames()[0], "\xe4\xf6\xfc/" + u"\u20ac".encode("utf8"))
 
 
 class AppendTest(unittest.TestCase):
@@ -1449,22 +1532,20 @@ class AppendTest(unittest.TestCase):
             os.remove(self.tarname)
 
     def _add_testfile(self, fileobj=None):
-        tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
-        tar.addfile(tarfile.TarInfo("bar"))
-        tar.close()
+        with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
+            tar.addfile(tarfile.TarInfo("bar"))
 
     def _create_testtar(self, mode="w:"):
-        src = tarfile.open(tarname, encoding="iso8859-1")
-        t = src.getmember("ustar/regtype")
-        t.name = "foo"
-        f = src.extractfile(t)
-        tar = tarfile.open(self.tarname, mode)
-        tar.addfile(t, f)
-        tar.close()
+        with tarfile.open(tarname, encoding="iso8859-1") as src:
+            t = src.getmember("ustar/regtype")
+            t.name = "foo"
+            f = src.extractfile(t)
+            with tarfile.open(self.tarname, mode) as tar:
+                tar.addfile(t, f)
 
     def _test(self, names=["bar"], fileobj=None):
-        tar = tarfile.open(self.tarname, fileobj=fileobj)
-        self.assertEqual(tar.getnames(), names)
+        with tarfile.open(self.tarname, fileobj=fileobj) as tar:
+            self.assertEqual(tar.getnames(), names)
 
     def test_non_existing(self):
         self._add_testfile()
@@ -1483,7 +1564,8 @@ class AppendTest(unittest.TestCase):
 
     def test_fileobj(self):
         self._create_testtar()
-        data = open(self.tarname).read()
+        with open(self.tarname) as fobj:
+            data = fobj.read()
         fobj = StringIO.StringIO(data)
         self._add_testfile(fobj)
         fobj.seek(0)
@@ -1507,7 +1589,8 @@ class AppendTest(unittest.TestCase):
     # Append mode is supposed to fail if the tarfile to append to
     # does not end with a zero block.
     def _test_error(self, data):
-        open(self.tarname, "wb").write(data)
+        with open(self.tarname, "wb") as fobj:
+            fobj.write(data)
         self.assertRaises(tarfile.ReadError, self._add_testfile)
 
     def test_null(self):
@@ -1643,15 +1726,14 @@ class ContextManagerTest(unittest.TestCase):
     def test_fileobj(self):
         # Test that __exit__() did not close the external file
         # object.
-        fobj = open(tmpname, "wb")
-        try:
-            with tarfile.open(fileobj=fobj, mode="w") as tar:
-                raise Exception
-        except:
-            pass
-        self.assertFalse(fobj.closed, "external file object was closed")
-        self.assertTrue(tar.closed, "context manager failed")
-        fobj.close()
+        with open(tmpname, "wb") as fobj:
+            try:
+                with tarfile.open(fileobj=fobj, mode="w") as tar:
+                    raise Exception
+            except:
+                pass
+            self.assertFalse(fobj.closed, "external file object was closed")
+            self.assertTrue(tar.closed, "context manager failed")
 
 
 class LinkEmulationTest(ReadTest):
@@ -1739,6 +1821,7 @@ class Bz2PartialReadTest(unittest.TestCase):
 
 
 def test_main():
+    support.unlink(TEMPDIR)
     os.makedirs(TEMPDIR)
 
     tests = [
@@ -1768,15 +1851,14 @@ def test_main():
     else:
         tests.append(LinkEmulationTest)
 
-    fobj = open(tarname, "rb")
-    data = fobj.read()
-    fobj.close()
+    with open(tarname, "rb") as fobj:
+        data = fobj.read()
 
     if gzip:
         # Create testtar.tar.gz and add gzip-specific tests.
-        tar = gzip.open(gzipname, "wb")
-        tar.write(data)
-        tar.close()
+        support.unlink(gzipname)
+        with gzip.open(gzipname, "wb") as tar:
+            tar.write(data)
 
         tests += [
             GzipMiscReadTest,
@@ -1789,9 +1871,12 @@ def test_main():
 
     if bz2:
         # Create testtar.tar.bz2 and add bz2-specific tests.
+        support.unlink(bz2name)
         tar = bz2.BZ2File(bz2name, "wb")
-        tar.write(data)
-        tar.close()
+        try:
+            tar.write(data)
+        finally:
+            tar.close()
 
         tests += [
             Bz2MiscReadTest,
index 6c122d7..1534e14 100644 (file)
@@ -248,8 +248,8 @@ class ReadTests(TestCase):
         func = getattr(telnet, func_name)
         self.assertRaises(EOFError, func)
 
-    # read_eager and read_very_eager make the same gaurantees
-    # (they behave differently but we only test the gaurantees)
+    # read_eager and read_very_eager make the same guarantees
+    # (they behave differently but we only test the guarantees)
     def test_read_very_eager_A(self):
         self._test_read_any_eager_A('read_very_eager')
     def test_read_very_eager_B(self):
index 3d0ac57..078e4a9 100644 (file)
@@ -827,6 +827,13 @@ class test_NamedTemporaryFile(TC):
             os.close = old_close
             os.fdopen = old_fdopen
 
+    def test_bad_mode(self):
+        dir = tempfile.mkdtemp()
+        self.addCleanup(support.rmtree, dir)
+        with self.assertRaises(TypeError):
+            tempfile.NamedTemporaryFile(mode=(), dir=dir)
+        self.assertEqual(os.listdir(dir), [])
+
     # How to test the mode and bufsize parameters?
 
 test_classes.append(test_NamedTemporaryFile)
index b056039..b466138 100644 (file)
@@ -233,7 +233,12 @@ class TestForkInThread(unittest.TestCase):
             if pid == 0: # child
                 os.close(self.read_fd)
                 os.write(self.write_fd, "OK")
-                sys.exit(0)
+                # Exiting the thread normally in the child process can leave
+                # any additional threads (such as the one started by
+                # importing _tkinter) still running, and this can prevent
+                # the half-zombie child process from being cleaned up. See
+                # Issue #26456.
+                os._exit(0)
             else: # parent
                 os.close(self.write_fd)
 
index 44f2c57..ac14e66 100644 (file)
@@ -51,7 +51,7 @@ class TestThread(threading.Thread):
                 self.nrunning.inc()
                 if verbose:
                     print self.nrunning.get(), 'tasks are running'
-                self.testcase.assertTrue(self.nrunning.get() <= 3)
+                self.testcase.assertLessEqual(self.nrunning.get(), 3)
 
             time.sleep(delay)
             if verbose:
@@ -59,7 +59,7 @@ class TestThread(threading.Thread):
 
             with self.mutex:
                 self.nrunning.dec()
-                self.testcase.assertTrue(self.nrunning.get() >= 0)
+                self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
                 if verbose:
                     print '%s is finished. %d tasks are running' % (
                         self.name, self.nrunning.get())
@@ -92,25 +92,25 @@ class ThreadTests(BaseTestCase):
         for i in range(NUMTASKS):
             t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
             threads.append(t)
-            self.assertEqual(t.ident, None)
-            self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
+            self.assertIsNone(t.ident)
+            self.assertRegexpMatches(repr(t), r'^<TestThread\(.*, initial\)>$')
             t.start()
 
         if verbose:
             print 'waiting for all tasks to complete'
         for t in threads:
             t.join(NUMTASKS)
-            self.assertTrue(not t.is_alive())
+            self.assertFalse(t.is_alive())
             self.assertNotEqual(t.ident, 0)
-            self.assertFalse(t.ident is None)
-            self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
+            self.assertIsNotNone(t.ident)
+            self.assertRegexpMatches(repr(t), r'^<TestThread\(.*, \w+ -?\d+\)>$')
         if verbose:
             print 'all tasks done'
         self.assertEqual(numrunning.get(), 0)
 
     def test_ident_of_no_threading_threads(self):
         # The ident still must work for the main thread and dummy threads.
-        self.assertFalse(threading.currentThread().ident is None)
+        self.assertIsNotNone(threading.currentThread().ident)
         def f():
             ident.append(threading.currentThread().ident)
             done.set()
@@ -118,7 +118,7 @@ class ThreadTests(BaseTestCase):
         ident = []
         thread.start_new_thread(f, ())
         done.wait()
-        self.assertFalse(ident[0] is None)
+        self.assertIsNotNone(ident[0])
         # Kill the "immortal" _DummyThread
         del threading._active[ident[0]]
 
@@ -236,7 +236,7 @@ class ThreadTests(BaseTestCase):
         self.assertTrue(ret)
         if verbose:
             print "    verifying worker hasn't exited"
-        self.assertTrue(not t.finished)
+        self.assertFalse(t.finished)
         if verbose:
             print "    attempting to raise asynch exception in worker"
         result = set_async_exc(ctypes.c_long(t.id), exception)
@@ -876,7 +876,7 @@ class EventTests(lock_tests.EventTests):
     eventtype = staticmethod(threading.Event)
 
 class ConditionAsRLockTests(lock_tests.RLockTests):
-    # An Condition uses an RLock by default and exports its API.
+    # Condition uses an RLock by default and exports its API.
     locktype = staticmethod(threading.Condition)
 
 class ConditionTests(lock_tests.ConditionTests):
index b161315..e53400c 100644 (file)
@@ -196,7 +196,7 @@ class ThreadLocalTest(unittest.TestCase, BaseLocalTest):
         wr = weakref.ref(x)
         del x
         gc.collect()
-        self.assertIs(wr(), None)
+        self.assertIsNone(wr())
 
 class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest):
     _local = _threading_local.local
diff --git a/Lib/test/test_turtle.py b/Lib/test/test_turtle.py
new file mode 100644 (file)
index 0000000..8f8434c
--- /dev/null
@@ -0,0 +1,435 @@
+import pickle
+import unittest
+from test import test_support as support
+
+turtle = support.import_module('turtle')
+Vec2D = turtle.Vec2D
+
+test_config = """\
+width = 0.75
+height = 0.8
+canvwidth = 500
+canvheight = 200
+leftright = 100
+topbottom = 100
+mode = world
+colormode = 255
+delay = 100
+undobuffersize = 10000
+shape = circle
+pencolor  = red
+fillcolor  = blue
+resizemode  = auto
+visible  = None
+language = english
+exampleturtle = turtle
+examplescreen = screen
+title = Python Turtle Graphics
+using_IDLE = ''
+"""
+
+test_config_two = """\
+# Comments!
+# Testing comments!
+pencolor  = red
+fillcolor  = blue
+visible  = False
+language = english
+# Some more
+# comments
+using_IDLE = False
+"""
+
+invalid_test_config = """
+pencolor = red
+fillcolor: blue
+visible = False
+"""
+
+
+class TurtleConfigTest(unittest.TestCase):
+
+    def get_cfg_file(self, cfg_str):
+        self.addCleanup(support.unlink, support.TESTFN)
+        with open(support.TESTFN, 'w') as f:
+            f.write(cfg_str)
+        return support.TESTFN
+
+    def test_config_dict(self):
+
+        cfg_name = self.get_cfg_file(test_config)
+        parsed_cfg = turtle.config_dict(cfg_name)
+
+        expected = {
+            'width' : 0.75,
+            'height' : 0.8,
+            'canvwidth' : 500,
+            'canvheight': 200,
+            'leftright': 100,
+            'topbottom': 100,
+            'mode': 'world',
+            'colormode': 255,
+            'delay': 100,
+            'undobuffersize': 10000,
+            'shape': 'circle',
+            'pencolor' : 'red',
+            'fillcolor' : 'blue',
+            'resizemode' : 'auto',
+            'visible' : None,
+            'language': 'english',
+            'exampleturtle': 'turtle',
+            'examplescreen': 'screen',
+            'title': 'Python Turtle Graphics',
+            'using_IDLE': '',
+        }
+
+        self.assertEqual(parsed_cfg, expected)
+
+    def test_partial_config_dict_with_commments(self):
+
+        cfg_name = self.get_cfg_file(test_config_two)
+        parsed_cfg = turtle.config_dict(cfg_name)
+
+        expected = {
+            'pencolor': 'red',
+            'fillcolor': 'blue',
+            'visible': False,
+            'language': 'english',
+            'using_IDLE': False,
+        }
+
+        self.assertEqual(parsed_cfg, expected)
+
+    def test_config_dict_invalid(self):
+
+        cfg_name = self.get_cfg_file(invalid_test_config)
+
+        with support.captured_stdout() as stdout:
+            parsed_cfg = turtle.config_dict(cfg_name)
+
+        err_msg = stdout.getvalue()
+
+        self.assertIn('Bad line in config-file ', err_msg)
+        self.assertIn('fillcolor: blue', err_msg)
+
+        self.assertEqual(parsed_cfg, {
+            'pencolor': 'red',
+            'visible': False,
+        })
+
+
+class VectorComparisonMixin:
+
+    def assertVectorsAlmostEqual(self, vec1, vec2):
+        if len(vec1) != len(vec2):
+            self.fail("Tuples are not of equal size")
+        for idx, (i, j) in enumerate(zip(vec1, vec2)):
+            self.assertAlmostEqual(
+                i, j, msg='values at index {} do not match'.format(idx))
+
+
+class TestVec2D(VectorComparisonMixin, unittest.TestCase):
+
+    def test_constructor(self):
+        vec = Vec2D(0.5, 2)
+        self.assertEqual(vec[0], 0.5)
+        self.assertEqual(vec[1], 2)
+        self.assertIsInstance(vec, Vec2D)
+
+        self.assertRaises(TypeError, Vec2D)
+        self.assertRaises(TypeError, Vec2D, 0)
+        self.assertRaises(TypeError, Vec2D, (0, 1))
+        self.assertRaises(TypeError, Vec2D, vec)
+        self.assertRaises(TypeError, Vec2D, 0, 1, 2)
+
+    def test_repr(self):
+        vec = Vec2D(0.567, 1.234)
+        self.assertEqual(repr(vec), '(0.57,1.23)')
+
+    def test_equality(self):
+        vec1 = Vec2D(0, 1)
+        vec2 = Vec2D(0.0, 1)
+        vec3 = Vec2D(42, 1)
+        self.assertEqual(vec1, vec2)
+        self.assertEqual(vec1, tuple(vec1))
+        self.assertEqual(tuple(vec1), vec1)
+        self.assertNotEqual(vec1, vec3)
+        self.assertNotEqual(vec2, vec3)
+
+    def test_pickling(self):
+        vec = Vec2D(0.5, 2)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(vec, protocol=proto)
+            unpickled = pickle.loads(pickled)
+            self.assertEqual(unpickled, vec)
+            self.assertIsInstance(unpickled, Vec2D)
+
+    def _assert_arithmetic_cases(self, test_cases, lambda_operator):
+        for test_case in test_cases:
+            ((first, second), expected) = test_case
+
+            op1 = Vec2D(*first)
+            op2 = Vec2D(*second)
+
+            result = lambda_operator(op1, op2)
+
+            expected = Vec2D(*expected)
+
+            self.assertVectorsAlmostEqual(result, expected)
+
+    def test_vector_addition(self):
+
+        test_cases = [
+            (((0, 0), (1, 1)), (1.0, 1.0)),
+            (((-1, 0), (2, 2)), (1, 2)),
+            (((1.5, 0), (1, 1)), (2.5, 1)),
+        ]
+
+        self._assert_arithmetic_cases(test_cases, lambda x, y: x + y)
+
+    def test_vector_subtraction(self):
+
+        test_cases = [
+            (((0, 0), (1, 1)), (-1, -1)),
+            (((10.625, 0.125), (10, 0)), (0.625, 0.125)),
+        ]
+
+        self._assert_arithmetic_cases(test_cases, lambda x, y: x - y)
+
+    def test_vector_multiply(self):
+
+        vec1 = Vec2D(10, 10)
+        vec2 = Vec2D(0.5, 3)
+        answer = vec1 * vec2
+        expected = 35
+        self.assertAlmostEqual(answer, expected)
+
+        vec = Vec2D(0.5, 3)
+        answer = vec * 10
+        expected = Vec2D(5, 30)
+        self.assertVectorsAlmostEqual(answer, expected)
+
+    def test_vector_negative(self):
+        vec = Vec2D(10, -10)
+        expected = (-10, 10)
+        self.assertVectorsAlmostEqual(-vec, expected)
+
+    def test_distance(self):
+        vec = Vec2D(6, 8)
+        expected = 10
+        self.assertEqual(abs(vec), expected)
+
+        vec = Vec2D(0, 0)
+        expected = 0
+        self.assertEqual(abs(vec), expected)
+
+        vec = Vec2D(2.5, 6)
+        expected = 6.5
+        self.assertEqual(abs(vec), expected)
+
+    def test_rotate(self):
+
+        cases = [
+            (((0, 0), 0), (0, 0)),
+            (((0, 1), 90), (-1, 0)),
+            (((0, 1), -90), (1, 0)),
+            (((1, 0), 180), (-1, 0)),
+            (((1, 0), 360), (1, 0)),
+        ]
+
+        for case in cases:
+            (vec, rot), expected = case
+            vec = Vec2D(*vec)
+            got = vec.rotate(rot)
+            self.assertVectorsAlmostEqual(got, expected)
+
+
+class TestTNavigator(VectorComparisonMixin, unittest.TestCase):
+
+    def setUp(self):
+        self.nav = turtle.TNavigator()
+
+    def test_goto(self):
+        self.nav.goto(100, -100)
+        self.assertAlmostEqual(self.nav.xcor(), 100)
+        self.assertAlmostEqual(self.nav.ycor(), -100)
+
+    def test_pos(self):
+        self.assertEqual(self.nav.pos(), self.nav._position)
+        self.nav.goto(100, -100)
+        self.assertEqual(self.nav.pos(), self.nav._position)
+
+    def test_left(self):
+        self.assertEqual(self.nav._orient, (1.0, 0))
+        self.nav.left(90)
+        self.assertVectorsAlmostEqual(self.nav._orient, (0.0, 1.0))
+
+    def test_right(self):
+        self.assertEqual(self.nav._orient, (1.0, 0))
+        self.nav.right(90)
+        self.assertVectorsAlmostEqual(self.nav._orient, (0, -1.0))
+
+    def test_reset(self):
+        self.nav.goto(100, -100)
+        self.assertAlmostEqual(self.nav.xcor(), 100)
+        self.assertAlmostEqual(self.nav.ycor(), -100)
+        self.nav.reset()
+        self.assertAlmostEqual(self.nav.xcor(), 0)
+        self.assertAlmostEqual(self.nav.ycor(), 0)
+
+    def test_forward(self):
+        self.nav.forward(150)
+        expected = Vec2D(150, 0)
+        self.assertVectorsAlmostEqual(self.nav.position(), expected)
+
+        self.nav.reset()
+        self.nav.left(90)
+        self.nav.forward(150)
+        expected = Vec2D(0, 150)
+        self.assertVectorsAlmostEqual(self.nav.position(), expected)
+
+        self.assertRaises(TypeError, self.nav.forward, 'skldjfldsk')
+
+    def test_backwards(self):
+        self.nav.back(200)
+        expected = Vec2D(-200, 0)
+        self.assertVectorsAlmostEqual(self.nav.position(), expected)
+
+        self.nav.reset()
+        self.nav.right(90)
+        self.nav.back(200)
+        expected = Vec2D(0, 200)
+        self.assertVectorsAlmostEqual(self.nav.position(), expected)
+
+    def test_distance(self):
+        self.nav.forward(100)
+        expected = 100
+        self.assertAlmostEqual(self.nav.distance(Vec2D(0,0)), expected)
+
+    def test_radians_and_degrees(self):
+        self.nav.left(90)
+        self.assertAlmostEqual(self.nav.heading(), 90)
+        self.nav.radians()
+        self.assertAlmostEqual(self.nav.heading(), 1.57079633)
+        self.nav.degrees()
+        self.assertAlmostEqual(self.nav.heading(), 90)
+
+    def test_towards(self):
+
+        coordinates = [
+            # coordinates, expected
+            ((100, 0), 0.0),
+            ((100, 100), 45.0),
+            ((0, 100), 90.0),
+            ((-100, 100), 135.0),
+            ((-100, 0), 180.0),
+            ((-100, -100), 225.0),
+            ((0, -100), 270.0),
+            ((100, -100), 315.0),
+        ]
+
+        for (x, y), expected in coordinates:
+            self.assertEqual(self.nav.towards(x, y), expected)
+            self.assertEqual(self.nav.towards((x, y)), expected)
+            self.assertEqual(self.nav.towards(Vec2D(x, y)), expected)
+
+    def test_heading(self):
+
+        self.nav.left(90)
+        self.assertAlmostEqual(self.nav.heading(), 90)
+        self.nav.left(45)
+        self.assertAlmostEqual(self.nav.heading(), 135)
+        self.nav.right(1.6)
+        self.assertAlmostEqual(self.nav.heading(), 133.4)
+        self.assertRaises(TypeError, self.nav.right, 'sdkfjdsf')
+        self.nav.reset()
+
+        rotations = [10, 20, 170, 300]
+        result = sum(rotations) % 360
+        for num in rotations:
+            self.nav.left(num)
+        self.assertEqual(self.nav.heading(), result)
+        self.nav.reset()
+
+        result = (360-sum(rotations)) % 360
+        for num in rotations:
+            self.nav.right(num)
+        self.assertEqual(self.nav.heading(), result)
+        self.nav.reset()
+
+        rotations = [10, 20, -170, 300, -210, 34.3, -50.2, -10, -29.98, 500]
+        sum_so_far = 0
+        for num in rotations:
+            if num < 0:
+                self.nav.right(abs(num))
+            else:
+                self.nav.left(num)
+            sum_so_far += num
+            self.assertAlmostEqual(self.nav.heading(), sum_so_far % 360)
+
+    def test_setheading(self):
+        self.nav.setheading(102.32)
+        self.assertAlmostEqual(self.nav.heading(), 102.32)
+        self.nav.setheading(-123.23)
+        self.assertAlmostEqual(self.nav.heading(), (-123.23) % 360)
+        self.nav.setheading(-1000.34)
+        self.assertAlmostEqual(self.nav.heading(), (-1000.34) % 360)
+        self.nav.setheading(300000)
+        self.assertAlmostEqual(self.nav.heading(), 300000%360)
+
+    def test_positions(self):
+        self.nav.forward(100)
+        self.nav.left(90)
+        self.nav.forward(-200)
+        self.assertVectorsAlmostEqual(self.nav.pos(), (100.0, -200.0))
+
+    def test_setx_and_sety(self):
+        self.nav.setx(-1023.2334)
+        self.nav.sety(193323.234)
+        self.assertVectorsAlmostEqual(self.nav.pos(), (-1023.2334, 193323.234))
+
+    def test_home(self):
+        self.nav.left(30)
+        self.nav.forward(-100000)
+        self.nav.home()
+        self.assertVectorsAlmostEqual(self.nav.pos(), (0,0))
+        self.assertAlmostEqual(self.nav.heading(), 0)
+
+    def test_distance_method(self):
+        self.assertAlmostEqual(self.nav.distance(30, 40), 50)
+        vec = Vec2D(0.22, .001)
+        self.assertAlmostEqual(self.nav.distance(vec), 0.22000227271553355)
+        another_turtle = turtle.TNavigator()
+        another_turtle.left(90)
+        another_turtle.forward(10000)
+        self.assertAlmostEqual(self.nav.distance(another_turtle), 10000)
+
+
+class TestTPen(unittest.TestCase):
+
+    def test_pendown_and_penup(self):
+
+        tpen = turtle.TPen()
+
+        self.assertTrue(tpen.isdown())
+        tpen.penup()
+        self.assertFalse(tpen.isdown())
+        tpen.pendown()
+        self.assertTrue(tpen.isdown())
+
+    def test_showturtle_hideturtle_and_isvisible(self):
+
+        tpen = turtle.TPen()
+
+        self.assertTrue(tpen.isvisible())
+        tpen.hideturtle()
+        self.assertFalse(tpen.isvisible())
+        tpen.showturtle()
+        self.assertTrue(tpen.isvisible())
+
+
+def test_main():
+    support.run_unittest(TurtleConfigTest, TestVec2D, TestTNavigator, TestTPen)
+
+if __name__ == '__main__':
+    test_main()
index be8f89b..93224e1 100644 (file)
@@ -33,6 +33,9 @@ def search_function(encoding):
         return None
 codecs.register(search_function)
 
+class UnicodeSubclass(unicode):
+    pass
+
 class UnicodeTest(
     string_tests.CommonTest,
     string_tests.MixinStrUnicodeUserStringTest,
@@ -685,9 +688,6 @@ class UnicodeTest(
             u'unicode remains unicode'
         )
 
-        class UnicodeSubclass(unicode):
-            pass
-
         self.assertEqual(
             unicode(UnicodeSubclass('unicode subclass becomes unicode')),
             u'unicode subclass becomes unicode'
@@ -1037,10 +1037,12 @@ class UnicodeTest(
         self.assertEqual(unicode('Andr\202 x','ascii','ignore'), u"Andr x")
         self.assertEqual(unicode('Andr\202 x','ascii','replace'), u'Andr\uFFFD x')
         self.assertEqual(unicode('\202 x', 'ascii', 'replace'), u'\uFFFD x')
-        self.assertEqual(u'abcde'.decode('ascii', 'ignore'),
-                         u'abcde'.decode('ascii', errors='ignore'))
-        self.assertEqual(u'abcde'.decode('ascii', 'replace'),
-                         u'abcde'.decode(encoding='ascii', errors='replace'))
+        with test_support.check_py3k_warnings():
+            self.assertEqual(u'abcde'.decode('ascii', 'ignore'),
+                             u'abcde'.decode('ascii', errors='ignore'))
+        with test_support.check_py3k_warnings():
+            self.assertEqual(u'abcde'.decode('ascii', 'replace'),
+                             u'abcde'.decode(encoding='ascii', errors='replace'))
 
         # Error handling (unknown character names)
         self.assertEqual("\\N{foo}xx".decode("unicode-escape", "ignore"), u"xx")
@@ -1269,6 +1271,9 @@ class UnicodeTest(
         self.assertEqual(unicode(Foo6("bar")), u"foou")
         self.assertEqual(unicode(Foo7("bar")), u"foou")
         self.assertEqual(unicode(Foo8("foo")), u"foofoo")
+        self.assertIs(type(unicode(Foo8("foo"))), Foo8)
+        self.assertEqual(UnicodeSubclass(Foo8("foo")), u"foofoo")
+        self.assertIs(type(UnicodeSubclass(Foo8("foo"))), UnicodeSubclass)
         self.assertEqual(str(Foo9("foo")), "string")
         self.assertEqual(unicode(Foo9("foo")), u"not unicode")
 
@@ -1852,6 +1857,11 @@ class UnicodeTest(
                     unicode_encodedecimal(u"123" + s, "xmlcharrefreplace"),
                     '123' + exp)
 
+    def test_free_after_iterating(self):
+        test_support.check_free_after_iterating(self, iter, unicode)
+        test_support.check_free_after_iterating(self, reversed, unicode)
+
+
 def test_main():
     test_support.run_unittest(__name__)
 
index adffb57..434d533 100644 (file)
@@ -1,13 +1,14 @@
 """Regresssion tests for urllib"""
 
+import collections
 import urllib
 import httplib
+import io
 import unittest
 import os
 import sys
 import mimetools
 import tempfile
-import StringIO
 
 from test import test_support
 from base64 import b64encode
@@ -21,37 +22,43 @@ def hexescape(char):
     return "%" + hex_repr
 
 
-class FakeHTTPMixin(object):
-    def fakehttp(self, fakedata):
-        class FakeSocket(StringIO.StringIO):
+def fakehttp(fakedata):
+    class FakeSocket(io.BytesIO):
+
+        def sendall(self, data):
+            FakeHTTPConnection.buf = data
 
-            def sendall(self, data):
-                FakeHTTPConnection.buf = data
+        def makefile(self, *args, **kwds):
+            return self
 
-            def makefile(self, *args, **kwds):
-                return self
+        def read(self, amt=None):
+            if self.closed:
+                return b""
+            return io.BytesIO.read(self, amt)
 
-            def read(self, amt=None):
-                if self.closed:
-                    return ""
-                return StringIO.StringIO.read(self, amt)
+        def readline(self, length=None):
+            if self.closed:
+                return b""
+            return io.BytesIO.readline(self, length)
 
-            def readline(self, length=None):
-                if self.closed:
-                    return ""
-                return StringIO.StringIO.readline(self, length)
+    class FakeHTTPConnection(httplib.HTTPConnection):
 
-        class FakeHTTPConnection(httplib.HTTPConnection):
+        # buffer to store data for verification in urlopen tests.
+        buf = ""
 
-            # buffer to store data for verification in urlopen tests.
-            buf = ""
+        def connect(self):
+            self.sock = FakeSocket(self.fakedata)
+            self.__class__.fakesock = self.sock
+    FakeHTTPConnection.fakedata = fakedata
 
-            def connect(self):
-                self.sock = FakeSocket(fakedata)
+    return FakeHTTPConnection
 
+
+class FakeHTTPMixin(object):
+    def fakehttp(self, fakedata):
         assert httplib.HTTP._connection_class == httplib.HTTPConnection
 
-        httplib.HTTP._connection_class = FakeHTTPConnection
+        httplib.HTTP._connection_class = fakehttp(fakedata)
 
     def unfakehttp(self):
         httplib.HTTP._connection_class = httplib.HTTPConnection
@@ -158,8 +165,59 @@ class ProxyTests(unittest.TestCase):
         # getproxies_environment use lowered case truncated (no '_proxy') keys
         self.assertEqual('localhost', proxies['no'])
         # List of no_proxies with space.
-        self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com')
+        self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234')
         self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com'))
+        self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888'))
+        self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234'))
+
+    def test_proxy_bypass_environment_host_match(self):
+        bypass = urllib.proxy_bypass_environment
+        self.env.set('NO_PROXY',
+            'localhost, anotherdomain.com, newdomain.com:1234')
+        self.assertTrue(bypass('localhost'))
+        self.assertTrue(bypass('LocalHost'))                 # MixedCase
+        self.assertTrue(bypass('LOCALHOST'))                 # UPPERCASE
+        self.assertTrue(bypass('newdomain.com:1234'))
+        self.assertTrue(bypass('anotherdomain.com:8888'))
+        self.assertTrue(bypass('www.newdomain.com:1234'))
+        self.assertFalse(bypass('prelocalhost'))
+        self.assertFalse(bypass('newdomain.com'))            # no port
+        self.assertFalse(bypass('newdomain.com:1235'))       # wrong port
+
+class ProxyTests_withOrderedEnv(unittest.TestCase):
+
+    def setUp(self):
+        # We need to test conditions, where variable order _is_ significant
+        self._saved_env = os.environ
+        # Monkey patch os.environ, start with empty fake environment
+        os.environ = collections.OrderedDict()
+
+    def tearDown(self):
+        os.environ = self._saved_env
+
+    def test_getproxies_environment_prefer_lowercase(self):
+        # Test lowercase preference with removal
+        os.environ['no_proxy'] = ''
+        os.environ['No_Proxy'] = 'localhost'
+        self.assertFalse(urllib.proxy_bypass_environment('localhost'))
+        self.assertFalse(urllib.proxy_bypass_environment('arbitrary'))
+        os.environ['http_proxy'] = ''
+        os.environ['HTTP_PROXY'] = 'http://somewhere:3128'
+        proxies = urllib.getproxies_environment()
+        self.assertEqual({}, proxies)
+        # Test lowercase preference of proxy bypass and correct matching including ports
+        os.environ['no_proxy'] = 'localhost, noproxy.com, my.proxy:1234'
+        os.environ['No_Proxy'] = 'xyz.com'
+        self.assertTrue(urllib.proxy_bypass_environment('localhost'))
+        self.assertTrue(urllib.proxy_bypass_environment('noproxy.com:5678'))
+        self.assertTrue(urllib.proxy_bypass_environment('my.proxy:1234'))
+        self.assertFalse(urllib.proxy_bypass_environment('my.proxy'))
+        self.assertFalse(urllib.proxy_bypass_environment('arbitrary'))
+        # Test lowercase preference with replacement
+        os.environ['http_proxy'] = 'http://somewhere:3128'
+        os.environ['Http_Proxy'] = 'http://somewhereelse:3128'
+        proxies = urllib.getproxies_environment()
+        self.assertEqual('http://somewhere:3128', proxies['http'])
 
 
 class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin):
@@ -209,10 +267,26 @@ Connection: close
 Content-Type: text/html; charset=iso-8859-1
 """)
         try:
-            self.assertRaises(IOError, urllib.urlopen, "http://python.org/")
+            msg = "Redirection to url 'file:"
+            with self.assertRaisesRegexp(IOError, msg):
+                urllib.urlopen("http://python.org/")
         finally:
             self.unfakehttp()
 
+    def test_redirect_limit_independent(self):
+        # Ticket #12923: make sure independent requests each use their
+        # own retry limit.
+        for i in range(urllib.FancyURLopener().maxtries):
+            self.fakehttp(b'''HTTP/1.1 302 Found
+Location: file://guidocomputer.athome.com:/python/license
+Connection: close
+''')
+            try:
+                self.assertRaises(IOError, urllib.urlopen,
+                    "http://something")
+            finally:
+                self.unfakehttp()
+
     def test_empty_socket(self):
         # urlopen() raises IOError if the underlying socket does not send any
         # data. (#1680230)
@@ -1014,6 +1088,8 @@ def test_main():
             Pathname_Tests,
             Utility_Tests,
             URLopener_Tests,
+            ProxyTests,
+            ProxyTests_withOrderedEnv,
             #FTPWrapperTests,
         )
 
index 32ffd0a..6d24d5d 100644 (file)
@@ -1,12 +1,14 @@
 import unittest
 from test import test_support
+from test import test_urllib
 
 import os
 import socket
 import StringIO
 
 import urllib2
-from urllib2 import Request, OpenerDirector
+from urllib2 import Request, OpenerDirector, AbstractDigestAuthHandler
+import httplib
 
 try:
     import ssl
@@ -418,7 +420,7 @@ class MockHTTPHandler(urllib2.BaseHandler):
         self._count = 0
         self.requests = []
     def http_open(self, req):
-        import mimetools, httplib, copy
+        import mimetools, copy
         from StringIO import StringIO
         self.requests.append(copy.deepcopy(req))
         if self._count == 0:
@@ -1036,6 +1038,22 @@ class HandlerTests(unittest.TestCase):
         fp = o.open('http://www.example.com')
         self.assertEqual(fp.geturl(), redirected_url.strip())
 
+    def test_redirect_no_path(self):
+        # Issue 14132: Relative redirect strips original path
+        real_class = httplib.HTTPConnection
+        response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
+        httplib.HTTPConnection = test_urllib.fakehttp(response1)
+        self.addCleanup(setattr, httplib, "HTTPConnection", real_class)
+        urls = iter(("/path", "/path?query"))
+        def request(conn, method, url, *pos, **kw):
+            self.assertEqual(url, next(urls))
+            real_class.request(conn, method, url, *pos, **kw)
+            # Change response for subsequent connection
+            conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
+        httplib.HTTPConnection.request = request
+        fp = urllib2.urlopen("http://python.org/path")
+        self.assertEqual(fp.geturl(), "http://python.org/path?query")
+
     def test_proxy(self):
         o = OpenerDirector()
         ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
@@ -1290,6 +1308,16 @@ class MiscTests(unittest.TestCase):
         else:
             self.assertTrue(False)
 
+    def test_unsupported_algorithm(self):
+        handler = AbstractDigestAuthHandler()
+        with self.assertRaises(ValueError) as exc:
+            handler.get_algorithm_impls('invalid')
+        self.assertEqual(
+            str(exc.exception),
+            "Unsupported digest authentication algorithm 'invalid'"
+        )
+
+
 class RequestTests(unittest.TestCase):
 
     def setUp(self):
@@ -1350,6 +1378,11 @@ class RequestTests(unittest.TestCase):
         req = Request(url)
         self.assertEqual(req.get_full_url(), url)
 
+    def test_private_attributes(self):
+        self.assertFalse(hasattr(self.get, '_Request__r_xxx'))
+        # Issue #6500: infinite recursion
+        self.assertFalse(hasattr(self.get, '_Request__r_method'))
+
     def test_HTTPError_interface(self):
         """
         Issue 13211 reveals that HTTPError didn't implement the URLError
index 7c4b1f7..a4b4d92 100644 (file)
@@ -111,7 +111,7 @@ class urlopenNetworkTests(unittest.TestCase):
 
     def test_getcode(self):
         # test getcode() with the fancy opener to get 404 error codes
-        URL = "http://www.example.com/XXXinvalidXXX"
+        URL = "http://www.pythontest.net/XXXinvalidXXX"
         open_url = urllib.FancyURLopener().open(URL)
         try:
             code = open_url.getcode()
index b3ad7cd..4e1ded7 100644 (file)
@@ -22,6 +22,49 @@ parse_qsl_test_cases = [
     ("&a=b", [('a', 'b')]),
     ("a=a+b&b=b+c", [('a', 'a b'), ('b', 'b c')]),
     ("a=1&a=2", [('a', '1'), ('a', '2')]),
+    (";", []),
+    (";;", []),
+    (";a=b", [('a', 'b')]),
+    ("a=a+b;b=b+c", [('a', 'a b'), ('b', 'b c')]),
+    ("a=1;a=2", [('a', '1'), ('a', '2')]),
+    (b";", []),
+    (b";;", []),
+    (b";a=b", [(b'a', b'b')]),
+    (b"a=a+b;b=b+c", [(b'a', b'a b'), (b'b', b'b c')]),
+    (b"a=1;a=2", [(b'a', b'1'), (b'a', b'2')]),
+]
+
+parse_qs_test_cases = [
+    ("", {}),
+    ("&", {}),
+    ("&&", {}),
+    ("=", {'': ['']}),
+    ("=a", {'': ['a']}),
+    ("a", {'a': ['']}),
+    ("a=", {'a': ['']}),
+    ("&a=b", {'a': ['b']}),
+    ("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}),
+    ("a=1&a=2", {'a': ['1', '2']}),
+    (b"", {}),
+    (b"&", {}),
+    (b"&&", {}),
+    (b"=", {b'': [b'']}),
+    (b"=a", {b'': [b'a']}),
+    (b"a", {b'a': [b'']}),
+    (b"a=", {b'a': [b'']}),
+    (b"&a=b", {b'a': [b'b']}),
+    (b"a=a+b&b=b+c", {b'a': [b'a b'], b'b': [b'b c']}),
+    (b"a=1&a=2", {b'a': [b'1', b'2']}),
+    (";", {}),
+    (";;", {}),
+    (";a=b", {'a': ['b']}),
+    ("a=a+b;b=b+c", {'a': ['a b'], 'b': ['b c']}),
+    ("a=1;a=2", {'a': ['1', '2']}),
+    (b";", {}),
+    (b";;", {}),
+    (b";a=b", {b'a': [b'b']}),
+    (b"a=a+b;b=b+c", {b'a': [b'a b'], b'b': [b'b c']}),
+    (b"a=1;a=2", {b'a': [b'1', b'2']}),
 ]
 
 class UrlParseTestCase(unittest.TestCase):
@@ -86,6 +129,15 @@ class UrlParseTestCase(unittest.TestCase):
             self.assertEqual(result, expect_without_blanks,
                     "Error parsing %r" % orig)
 
+    def test_qs(self):
+        for orig, expect in parse_qs_test_cases:
+            result = urlparse.parse_qs(orig, keep_blank_values=True)
+            self.assertEqual(result, expect, "Error parsing %r" % orig)
+            expect_without_blanks = dict(
+                    [(v, expect[v]) for v in expect if len(expect[v][0])])
+            result = urlparse.parse_qs(orig, keep_blank_values=False)
+            self.assertEqual(result, expect_without_blanks,
+                    "Error parsing %r" % orig)
 
     def test_roundtrips(self):
         testcases = [
index 11dc294..bc7e398 100644 (file)
@@ -553,10 +553,13 @@ class _WarningsTests(BaseTest):
         globals_dict = globals()
         oldfile = globals_dict['__file__']
         try:
-            with original_warnings.catch_warnings(module=self.module) as w:
+            with original_warnings.catch_warnings(module=self.module, record=True) as w:
                 self.module.filterwarnings("always", category=UserWarning)
                 globals_dict['__file__'] = None
                 self.module.warn('test', UserWarning)
+            self.assertEqual(len(w), 1)
+            self.assertEqual(w[0].category, UserWarning)
+            self.assertEqual(str(w[0].message), 'test')
         finally:
             globals_dict['__file__'] = oldfile
 
index b7f985c..4073d49 100644 (file)
@@ -116,6 +116,10 @@ class ReferencesTestCase(TestBase):
         ref1 = weakref.ref(c, callback)
         del c
 
+    def test_constructor_kwargs(self):
+        c = C()
+        self.assertRaises(TypeError, weakref.ref, c, callback=None)
+
     def test_proxy_ref(self):
         o = C()
         o.bar = 1
index 4208fe7..c94a4dc 100644 (file)
@@ -159,7 +159,7 @@ class PlaySoundTest(unittest.TestCase):
             )
 
     def test_alias_fallback(self):
-        # In the absense of the ability to tell if a sound was actually
+        # In the absence of the ability to tell if a sound was actually
         # played, this test has two acceptable outcomes: success (no error,
         # sound was theoretically played; although as issue #19987 shows
         # a box without a soundcard can "succeed") or RuntimeError.  Any
index 474a4b4..98410c5 100644 (file)
@@ -30,6 +30,38 @@ class MiscTests(unittest.TestCase):
         finally:
             data = None
 
+    def test_del_attribute(self):
+        element = cET.Element('tag')
+
+        element.tag = 'TAG'
+        with self.assertRaises(AttributeError):
+            del element.tag
+        self.assertEqual(element.tag, 'TAG')
+
+        with self.assertRaises(AttributeError):
+            del element.text
+        self.assertIsNone(element.text)
+        element.text = 'TEXT'
+        with self.assertRaises(AttributeError):
+            del element.text
+        self.assertEqual(element.text, 'TEXT')
+
+        with self.assertRaises(AttributeError):
+            del element.tail
+        self.assertIsNone(element.tail)
+        element.tail = 'TAIL'
+        with self.assertRaises(AttributeError):
+            del element.tail
+        self.assertEqual(element.tail, 'TAIL')
+
+        with self.assertRaises(AttributeError):
+            del element.attrib
+        self.assertEqual(element.attrib, {})
+        element.attrib = {'A': 'B', 'C': 'D'}
+        with self.assertRaises(AttributeError):
+            del element.attrib
+        self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'})
+
 
 def test_main():
     from test import test_xml_etree, test_xml_etree_c
index 2bb3978..97d9e8f 100644 (file)
@@ -23,13 +23,6 @@ try:
 except ImportError:
     gzip = None
 
-try:
-    unicode
-except NameError:
-    have_unicode = False
-else:
-    have_unicode = True
-
 alist = [{'astring': 'foo@bar.baz.spam',
           'afloat': 7283.43,
           'anint': 2**20,
@@ -37,8 +30,6 @@ alist = [{'astring': 'foo@bar.baz.spam',
           'anotherlist': ['.zyx.41'],
           'abase64': xmlrpclib.Binary("my dog has fleas"),
           'boolean': xmlrpclib.False,
-          'unicode': u'\u4000\u6000\u8000',
-          u'ukey\u4000': 'regular value',
           'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
           'datetime2': xmlrpclib.DateTime(
                         (2005, 02, 10, 11, 41, 23, 0, 1, -1)),
@@ -46,6 +37,12 @@ alist = [{'astring': 'foo@bar.baz.spam',
                         datetime.datetime(2005, 02, 10, 11, 41, 23)),
           }]
 
+if test_support.have_unicode:
+    alist[0].update({
+          'unicode': test_support.u(r'\u4000\u6000\u8000'),
+          test_support.u(r'ukey\u4000'): 'regular value',
+    })
+
 class XMLRPCTestCase(unittest.TestCase):
 
     def test_dump_load(self):
@@ -150,6 +147,25 @@ class XMLRPCTestCase(unittest.TestCase):
                          xmlrpclib.loads(strg)[0][0])
         self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
 
+    @test_support.requires_unicode
+    def test_dump_encoding(self):
+        value = {test_support.u(r'key\u20ac\xa4'):
+                 test_support.u(r'value\u20ac\xa4')}
+        strg = xmlrpclib.dumps((value,), encoding='iso-8859-15')
+        strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg
+        self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
+
+        strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
+                               methodresponse=True)
+        self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
+
+        methodname = test_support.u(r'method\u20ac\xa4')
+        strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
+                               methodname=methodname)
+        self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
+        self.assertEqual(xmlrpclib.loads(strg)[1], methodname)
+
+    @test_support.requires_unicode
     def test_default_encoding_issues(self):
         # SF bug #1115989: wrong decoding in '_stringify'
         utf8 = """<?xml version='1.0' encoding='iso-8859-1'?>
@@ -182,7 +198,7 @@ class XMLRPCTestCase(unittest.TestCase):
                 temp_sys.setdefaultencoding(old_encoding)
 
         items = d.items()
-        if have_unicode:
+        if test_support.have_unicode:
             self.assertEqual(s, u"abc \x95")
             self.assertIsInstance(s, unicode)
             self.assertEqual(items, [(u"def \x96", u"ghi \x97")])
@@ -192,6 +208,20 @@ class XMLRPCTestCase(unittest.TestCase):
             self.assertEqual(s, "abc \xc2\x95")
             self.assertEqual(items, [("def \xc2\x96", "ghi \xc2\x97")])
 
+    def test_loads_unsupported(self):
+        ResponseError = xmlrpclib.ResponseError
+        data = '<params><param><value><spam/></value></param></params>'
+        self.assertRaises(ResponseError, xmlrpclib.loads, data)
+        data = ('<params><param><value><array>'
+                '<value><spam/></value>'
+                '</array></value></param></params>')
+        self.assertRaises(ResponseError, xmlrpclib.loads, data)
+        data = ('<params><param><value><struct>'
+                '<member><name>a</name><value><spam/></value></member>'
+                '<member><name>b</name><value><spam/></value></member>'
+                '</struct></value></param></params>')
+        self.assertRaises(ResponseError, xmlrpclib.loads, data)
+
 
 class HelperTestCase(unittest.TestCase):
     def test_escape(self):
@@ -282,7 +312,7 @@ ADDR = PORT = URL = None
 # The evt is set twice.  First when the server is ready to serve.
 # Second when the server has been shutdown.  The user must clear
 # the event after it has been set the first time to catch the second set.
-def http_server(evt, numrequests, requestHandler=None):
+def http_server(evt, numrequests, requestHandler=None, encoding=None):
     class TestInstanceClass:
         def div(self, x, y):
             return x // y
@@ -306,6 +336,7 @@ def http_server(evt, numrequests, requestHandler=None):
     if not requestHandler:
         requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
     serv = MyXMLRPCServer(("localhost", 0), requestHandler,
+                          encoding=encoding,
                           logRequests=False, bind_and_activate=False)
     try:
         serv.socket.settimeout(3)
@@ -322,6 +353,7 @@ def http_server(evt, numrequests, requestHandler=None):
         serv.register_multicall_functions()
         serv.register_function(pow)
         serv.register_function(lambda x,y: x+y, 'add')
+        serv.register_function(lambda x: x, test_support.u(r't\xea\u0161t'))
         serv.register_function(my_function)
         serv.register_instance(TestInstanceClass())
         evt.set()
@@ -463,9 +495,10 @@ class SimpleServerTestCase(BaseServerTestCase):
                 # protocol error; provide additional information in test output
                 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
 
+    @test_support.requires_unicode
     def test_nonascii(self):
-        start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'
-        end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n'
+        start_string = test_support.u(r'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t')
+        end_string = test_support.u(r'h\N{LATIN SMALL LETTER O WITH HORN}n')
 
         try:
             p = xmlrpclib.ServerProxy(URL)
@@ -477,10 +510,38 @@ class SimpleServerTestCase(BaseServerTestCase):
                 # protocol error; provide additional information in test output
                 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
 
+    @test_support.requires_unicode
     def test_unicode_host(self):
         server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
         self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
 
+    @test_support.requires_unicode
+    def test_client_encoding(self):
+        start_string = unichr(0x20ac)
+        end_string = unichr(0xa4)
+
+        try:
+            p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
+            self.assertEqual(p.add(start_string, end_string),
+                             start_string + end_string)
+        except (xmlrpclib.ProtocolError, socket.error) as e:
+            # ignore failures due to non-blocking socket unavailable errors.
+            if not is_unavailable_exception(e):
+                # protocol error; provide additional information in test output
+                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
+
+    @test_support.requires_unicode
+    def test_nonascii_methodname(self):
+        try:
+            p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
+            m = getattr(p, 't\xea\xa8t')
+            self.assertEqual(m(42), 42)
+        except (xmlrpclib.ProtocolError, socket.error) as e:
+            # ignore failures due to non-blocking socket unavailable errors.
+            if not is_unavailable_exception(e):
+                # protocol error; provide additional information in test output
+                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
+
     # [ch] The test 404 is causing lots of false alarms.
     def XXXtest_404(self):
         # send POST with httplib, it should return 404 header and
@@ -498,6 +559,7 @@ class SimpleServerTestCase(BaseServerTestCase):
             p = xmlrpclib.ServerProxy(URL)
             meth = p.system.listMethods()
             expected_methods = set(['pow', 'div', 'my_function', 'add',
+                                    test_support.u(r't\xea\u0161t'),
                                     'system.listMethods', 'system.methodHelp',
                                     'system.methodSignature', 'system.multicall'])
             self.assertEqual(set(meth), expected_methods)
@@ -600,6 +662,27 @@ class SimpleServerTestCase(BaseServerTestCase):
         conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
         conn.close()
 
+class SimpleServerEncodingTestCase(BaseServerTestCase):
+    @staticmethod
+    def threadFunc(evt, numrequests, requestHandler=None, encoding=None):
+        http_server(evt, numrequests, requestHandler, 'iso-8859-15')
+
+    @test_support.requires_unicode
+    def test_server_encoding(self):
+        start_string = unichr(0x20ac)
+        end_string = unichr(0xa4)
+
+        try:
+            p = xmlrpclib.ServerProxy(URL)
+            self.assertEqual(p.add(start_string, end_string),
+                             start_string + end_string)
+        except (xmlrpclib.ProtocolError, socket.error) as e:
+            # ignore failures due to non-blocking socket unavailable errors.
+            if not is_unavailable_exception(e):
+                # protocol error; provide additional information in test output
+                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
+
+
 class MultiPathServerTestCase(BaseServerTestCase):
     threadFunc = staticmethod(http_multi_server)
     request_count = 2
@@ -1032,6 +1115,7 @@ def test_main():
     xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
          BinaryTestCase, FaultTestCase, TransportSubclassTestCase]
     xmlrpc_tests.append(SimpleServerTestCase)
+    xmlrpc_tests.append(SimpleServerEncodingTestCase)
     xmlrpc_tests.append(KeepaliveServerTestCase1)
     xmlrpc_tests.append(KeepaliveServerTestCase2)
     xmlrpc_tests.append(GzipServerTestCase)
index 01750c1..4000b30 100644 (file)
@@ -184,7 +184,7 @@ class TestsWithSourceFile(unittest.TestCase):
         for f in (TESTFN2, TemporaryFile(), StringIO()):
             self.zip_random_open_test(f, zipfile.ZIP_STORED)
 
-    def test_univeral_readaheads(self):
+    def test_universal_readaheads(self):
         f = StringIO()
 
         data = 'a\r\n' * 16 * 1024
@@ -1456,11 +1456,12 @@ class TestsWithMultipleOpens(unittest.TestCase):
         # multiple open() calls can be made without interfering with each other.
         self.make_test_archive(TESTFN2)
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
-            with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
+            with zipf.open('ones') as zopen1:
                 data1 = zopen1.read(500)
-                data2 = zopen2.read(500)
-                data1 += zopen1.read()
-                data2 += zopen2.read()
+                with zipf.open('twos') as zopen2:
+                    data2 = zopen2.read(500)
+                    data1 += zopen1.read()
+                    data2 += zopen2.read()
             self.assertEqual(data1, self.data1)
             self.assertEqual(data2, self.data2)
 
index a87baaa..151baf2 100644 (file)
@@ -79,15 +79,19 @@ class TestsWithSourceFile(unittest.TestCase):
     def testStored(self):
         # Try the temp file first.  If we do TESTFN2 first, then it hogs
         # gigabytes of disk space for the duration of the test.
-        for f in TemporaryFile(), TESTFN2:
+        with TemporaryFile() as f:
             self.zipTest(f, zipfile.ZIP_STORED)
+            self.assertFalse(f.closed)
+        self.zipTest(TESTFN2, zipfile.ZIP_STORED)
 
-    if zlib:
-        def testDeflated(self):
-            # Try the temp file first.  If we do TESTFN2 first, then it hogs
-            # gigabytes of disk space for the duration of the test.
-            for f in TemporaryFile(), TESTFN2:
-                self.zipTest(f, zipfile.ZIP_DEFLATED)
+    @unittest.skipUnless(zlib, "requires zlib")
+    def testDeflated(self):
+        # Try the temp file first.  If we do TESTFN2 first, then it hogs
+        # gigabytes of disk space for the duration of the test.
+        with TemporaryFile() as f:
+            self.zipTest(f, zipfile.ZIP_DEFLATED)
+            self.assertFalse(f.closed)
+        self.zipTest(TESTFN2, zipfile.ZIP_DEFLATED)
 
     def tearDown(self):
         for fname in TESTFN, TESTFN2:
index c8fc985..96cc3a7 100644 (file)
@@ -150,7 +150,7 @@ class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
         self.assertEqual(zlib.decompress(x), data)
 
     def test_incomplete_stream(self):
-        # An useful error message is given
+        # A useful error message is given
         x = zlib.compress(HAMLET_SCENE)
         self.assertRaisesRegexp(zlib.error,
             "Error -5 while decompressing data: incomplete or truncated stream",
@@ -527,6 +527,47 @@ class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
         decompress = lambda s: d.decompress(s) + d.flush()
         self.check_big_decompress_buffer(size, decompress)
 
+    def test_wbits(self):
+        co = zlib.compressobj(1, zlib.DEFLATED, 15)
+        zlib15 = co.compress(HAMLET_SCENE) + co.flush()
+        self.assertEqual(zlib.decompress(zlib15, 15), HAMLET_SCENE)
+        self.assertEqual(zlib.decompress(zlib15, 32 + 15), HAMLET_SCENE)
+        with self.assertRaisesRegexp(zlib.error, 'invalid window size'):
+            zlib.decompress(zlib15, 14)
+        dco = zlib.decompressobj(32 + 15)
+        self.assertEqual(dco.decompress(zlib15), HAMLET_SCENE)
+        dco = zlib.decompressobj(14)
+        with self.assertRaisesRegexp(zlib.error, 'invalid window size'):
+            dco.decompress(zlib15)
+
+        co = zlib.compressobj(1, zlib.DEFLATED, 9)
+        zlib9 = co.compress(HAMLET_SCENE) + co.flush()
+        self.assertEqual(zlib.decompress(zlib9, 9), HAMLET_SCENE)
+        self.assertEqual(zlib.decompress(zlib9, 15), HAMLET_SCENE)
+        self.assertEqual(zlib.decompress(zlib9, 32 + 9), HAMLET_SCENE)
+        dco = zlib.decompressobj(32 + 9)
+        self.assertEqual(dco.decompress(zlib9), HAMLET_SCENE)
+
+        co = zlib.compressobj(1, zlib.DEFLATED, -15)
+        deflate15 = co.compress(HAMLET_SCENE) + co.flush()
+        self.assertEqual(zlib.decompress(deflate15, -15), HAMLET_SCENE)
+        dco = zlib.decompressobj(-15)
+        self.assertEqual(dco.decompress(deflate15), HAMLET_SCENE)
+
+        co = zlib.compressobj(1, zlib.DEFLATED, -9)
+        deflate9 = co.compress(HAMLET_SCENE) + co.flush()
+        self.assertEqual(zlib.decompress(deflate9, -9), HAMLET_SCENE)
+        self.assertEqual(zlib.decompress(deflate9, -15), HAMLET_SCENE)
+        dco = zlib.decompressobj(-9)
+        self.assertEqual(dco.decompress(deflate9), HAMLET_SCENE)
+
+        co = zlib.compressobj(1, zlib.DEFLATED, 16 + 15)
+        gzip = co.compress(HAMLET_SCENE) + co.flush()
+        self.assertEqual(zlib.decompress(gzip, 16 + 15), HAMLET_SCENE)
+        self.assertEqual(zlib.decompress(gzip, 32 + 15), HAMLET_SCENE)
+        dco = zlib.decompressobj(32 + 15)
+        self.assertEqual(dco.decompress(gzip), HAMLET_SCENE)
+
 
 def genblock(seed, length, step=1024, generator=random):
     """length-byte stream of random data from a seed (in step-byte blocks)."""
index 644fe5b..0c23c96 100644 (file)
@@ -689,7 +689,7 @@ class TestCase(object):
 
                 if item1 != item2:
                     differing += ('\nFirst differing element %d:\n%s\n%s\n' %
-                                 (i, item1, item2))
+                                 (i, safe_repr(item1), safe_repr(item2)))
                     break
             else:
                 if (len1 == len2 and seq_type is None and
@@ -702,7 +702,7 @@ class TestCase(object):
                              'elements.\n' % (seq_type_name, len1 - len2))
                 try:
                     differing += ('First extra element %d:\n%s\n' %
-                                  (len2, seq1[len2]))
+                                  (len2, safe_repr(seq1[len2])))
                 except (TypeError, IndexError, NotImplementedError):
                     differing += ('Unable to index element %d '
                                   'of first %s\n' % (len2, seq_type_name))
@@ -711,7 +711,7 @@ class TestCase(object):
                              'elements.\n' % (seq_type_name, len2 - len1))
                 try:
                     differing += ('First extra element %d:\n%s\n' %
-                                  (len1, seq2[len1]))
+                                  (len1, safe_repr(seq2[len1])))
                 except (TypeError, IndexError, NotImplementedError):
                     differing += ('Unable to index element %d '
                                   'of second %s\n' % (len1, seq_type_name))
index 2cc17d7..8af972f 100644 (file)
@@ -132,7 +132,7 @@ class TestResult(object):
         self.skipped.append((test, reason))
 
     def addExpectedFailure(self, test, err):
-        """Called when an expected failure/error occured."""
+        """Called when an expected failure/error occurred."""
         self.expectedFailures.append(
             (test, self._exc_info_to_string(err, test)))
 
index ccb0574..139fab9 100644 (file)
@@ -629,18 +629,20 @@ class FancyURLopener(URLopener):
     def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
         """Error 302 -- relocated (temporarily)."""
         self.tries += 1
-        if self.maxtries and self.tries >= self.maxtries:
-            if hasattr(self, "http_error_500"):
-                meth = self.http_error_500
-            else:
-                meth = self.http_error_default
+        try:
+            if self.maxtries and self.tries >= self.maxtries:
+                if hasattr(self, "http_error_500"):
+                    meth = self.http_error_500
+                else:
+                    meth = self.http_error_default
+                return meth(url, fp, 500,
+                            "Internal Server Error: Redirect Recursion",
+                            headers)
+            result = self.redirect_internal(url, fp, errcode, errmsg,
+                                            headers, data)
+            return result
+        finally:
             self.tries = 0
-            return meth(url, fp, 500,
-                        "Internal Server Error: Redirect Recursion", headers)
-        result = self.redirect_internal(url, fp, errcode, errmsg, headers,
-                                        data)
-        self.tries = 0
-        return result
 
     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
         if 'location' in headers:
@@ -930,13 +932,7 @@ class ftpwrapper:
         return (ftpobj, retrlen)
 
     def endtransfer(self):
-        if not self.busy:
-            return
         self.busy = 0
-        try:
-            self.ftp.voidresp()
-        except ftperrors():
-            pass
 
     def close(self):
         self.keepalive = False
@@ -1377,25 +1373,42 @@ def getproxies_environment():
     """Return a dictionary of scheme -> proxy server URL mappings.
 
     Scan the environment for variables named <scheme>_proxy;
-    this seems to be the standard convention.  If you need a
-    different way, you can pass a proxies dictionary to the
-    [Fancy]URLopener constructor.
+    this seems to be the standard convention.  In order to prefer lowercase
+    variables, we process the environment in two passes, first matches any
+    and second matches only lower case proxies.
 
+    If you need a different way, you can pass a proxies dictionary to the
+    [Fancy]URLopener constructor.
     """
     proxies = {}
     for name, value in os.environ.items():
         name = name.lower()
         if value and name[-6:] == '_proxy':
             proxies[name[:-6]] = value
+
+    for name, value in os.environ.items():
+        if name[-6:] == '_proxy':
+            name = name.lower()
+            if value:
+                proxies[name[:-6]] = value
+            else:
+                proxies.pop(name[:-6], None)
+
     return proxies
 
-def proxy_bypass_environment(host):
+def proxy_bypass_environment(host, proxies=None):
     """Test if proxies should not be used for a particular host.
 
-    Checks the environment for a variable named no_proxy, which should
-    be a list of DNS suffixes separated by commas, or '*' for all hosts.
+    Checks the proxies dict for the value of no_proxy, which should be a
+    list of comma separated DNS suffixes, or '*' for all hosts.
     """
-    no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
+    if proxies is None:
+        proxies = getproxies_environment()
+    # don't bypass, if no_proxy isn't specified
+    try:
+        no_proxy = proxies['no']
+    except KeyError:
+        return 0
     # '*' is special case for always bypass
     if no_proxy == '*':
         return 1
@@ -1404,8 +1417,12 @@ def proxy_bypass_environment(host):
     # check if the host ends with any of the DNS suffixes
     no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
     for name in no_proxy_list:
-        if name and (hostonly.endswith(name) or host.endswith(name)):
-            return 1
+        if name:
+            name = re.escape(name)
+            pattern = r'(.+\.)?%s$' % name
+            if (re.match(pattern, hostonly, re.I)
+                    or re.match(pattern, host, re.I)):
+                return 1
     # otherwise, don't bypass
     return 0
 
@@ -1481,8 +1498,14 @@ if sys.platform == 'darwin':
         return _get_proxies()
 
     def proxy_bypass(host):
-        if getproxies_environment():
-            return proxy_bypass_environment(host)
+        """Return True, if a host should be bypassed.
+
+        Checks proxy settings gathered from the environment, if specified, or
+        from the MacOSX framework SystemConfiguration.
+        """
+        proxies = getproxies_environment()
+        if proxies:
+            return proxy_bypass_environment(host, proxies)
         else:
             return proxy_bypass_macosx_sysconf(host)
 
@@ -1598,14 +1621,14 @@ elif os.name == 'nt':
         return 0
 
     def proxy_bypass(host):
-        """Return a dictionary of scheme -> proxy server URL mappings.
+        """Return True, if the host should be bypassed.
 
-        Returns settings gathered from the environment, if specified,
+        Checks proxy settings gathered from the environment, if specified,
         or the registry.
-
         """
-        if getproxies_environment():
-            return proxy_bypass_environment(host)
+        proxies = getproxies_environment()
+        if proxies:
+            return proxy_bypass_environment(host, proxies)
         else:
             return proxy_bypass_registry(host)
 
index 9277b1d..8b634ad 100644 (file)
@@ -248,11 +248,9 @@ class Request:
         # methods getting called in a non-standard order.  this may be
         # too complicated and/or unnecessary.
         # XXX should the __r_XXX attributes be public?
-        if attr[:12] == '_Request__r_':
-            name = attr[12:]
-            if hasattr(Request, 'get_' + name):
-                getattr(self, 'get_' + name)()
-                return getattr(self, attr)
+        if attr in ('_Request__r_type', '_Request__r_host'):
+            getattr(self, 'get_' + attr[12:])()
+            return self.__dict__[attr]
         raise AttributeError, attr
 
     def get_method(self):
@@ -611,7 +609,7 @@ class HTTPRedirectHandler(BaseHandler):
 
         # fix a possible malformed URL
         urlparts = urlparse.urlparse(newurl)
-        if not urlparts.path:
+        if not urlparts.path and urlparts.netloc:
             urlparts = list(urlparts)
             urlparts[2] = "/"
         newurl = urlparse.urlunparse(urlparts)
@@ -1073,6 +1071,9 @@ class AbstractDigestAuthHandler:
         elif algorithm == 'SHA':
             H = lambda x: hashlib.sha1(x).hexdigest()
         # XXX MD5-sess
+        else:
+            raise ValueError("Unsupported digest authentication "
+                             "algorithm %r" % algorithm.lower())
         KD = lambda s, d: H("%s:%s" % (s, d))
         return H, KD
 
index 6c8c60c..5a95e84 100644 (file)
@@ -59,7 +59,7 @@ class Headers:
         Return None if the header is missing instead of raising an exception.
 
         Note that if the header appeared multiple times, the first exactly which
-        occurrance gets returned is undefined.  Use getall() to get all
+        occurrence gets returned is undefined.  Use getall() to get all
         the values matching a header field name.
         """
         return self.get(name)
index de4cb4f..266a7f4 100644 (file)
@@ -65,10 +65,10 @@ class NodeList(list):
     length = property(_get_length, _set_length,
                       doc="The number of nodes in the NodeList.")
 
-    def __getstate__(self):
-        return list(self)
-
+    # For backward compatibility
     def __setstate__(self, state):
+        if state is None:
+            state = []
         self[:] = state
 
 
index 9f3e75d..cf6402f 100644 (file)
@@ -574,7 +574,7 @@ PI = ProcessingInstruction
 # @param text A string containing the QName value, in the form {uri}local,
 #     or, if the tag argument is given, the URI part of a QName.
 # @param tag Optional tag.  If given, the first argument is interpreted as
-#     an URI, and this argument is interpreted as a local name.
+#     a URI, and this argument is interpreted as a local name.
 # @return An opaque object, representing the QName.
 
 class QName(object):
@@ -1198,9 +1198,14 @@ def iterparse(source, events=None, parser=None):
     if not hasattr(source, "read"):
         source = open(source, "rb")
         close_source = True
-    if not parser:
-        parser = XMLParser(target=TreeBuilder())
-    return _IterParseIterator(source, events, parser, close_source)
+    try:
+        if not parser:
+            parser = XMLParser(target=TreeBuilder())
+        return _IterParseIterator(source, events, parser, close_source)
+    except:
+        if close_source:
+            source.close()
+        raise
 
 class _IterParseIterator(object):
 
@@ -1252,34 +1257,40 @@ class _IterParseIterator(object):
                 raise ValueError("unknown event %r" % event)
 
     def next(self):
-        while 1:
-            try:
-                item = self._events[self._index]
-                self._index += 1
-                return item
-            except IndexError:
-                pass
-            if self._error:
-                e = self._error
-                self._error = None
-                raise e
-            if self._parser is None:
-                self.root = self._root
-                if self._close_file:
-                    self._file.close()
-                raise StopIteration
-            # load event buffer
-            del self._events[:]
-            self._index = 0
-            data = self._file.read(16384)
-            if data:
+        try:
+            while 1:
                 try:
-                    self._parser.feed(data)
-                except SyntaxError as exc:
-                    self._error = exc
-            else:
-                self._root = self._parser.close()
-                self._parser = None
+                    item = self._events[self._index]
+                    self._index += 1
+                    return item
+                except IndexError:
+                    pass
+                if self._error:
+                    e = self._error
+                    self._error = None
+                    raise e
+                if self._parser is None:
+                    self.root = self._root
+                    break
+                # load event buffer
+                del self._events[:]
+                self._index = 0
+                data = self._file.read(16384)
+                if data:
+                    try:
+                        self._parser.feed(data)
+                    except SyntaxError as exc:
+                        self._error = exc
+                else:
+                    self._root = self._parser.close()
+                    self._parser = None
+        except:
+            if self._close_file:
+                self._file.close()
+            raise
+        if self._close_file:
+            self._file.close()
+        raise StopIteration
 
     def __iter__(self):
         return self
index db185a6..e072f71 100644 (file)
@@ -358,7 +358,7 @@ del modules, mod_dict
 # tuple.
 #
 # @param value The time, given as an ISO 8601 string, a time
-#              tuple, or a integer time value.
+#              tuple, or an integer time value.
 
 def _strftime(value):
     if datetime:
@@ -393,7 +393,7 @@ class DateTime:
         elif datetime and isinstance(other, datetime.datetime):
             s = self.value
             o = other.strftime("%Y%m%dT%H:%M:%S")
-        elif isinstance(other, (str, unicode)):
+        elif isinstance(other, basestring):
             s = self.value
             o = other
         elif hasattr(other, "timetuple"):
@@ -703,9 +703,8 @@ class Marshaller:
 
     if unicode:
         def dump_unicode(self, value, write, escape=escape):
-            value = value.encode(self.encoding)
             write("<value><string>")
-            write(escape(value))
+            write(escape(value).encode(self.encoding, 'xmlcharrefreplace'))
             write("</string></value>\n")
         dispatch[UnicodeType] = dump_unicode
 
@@ -732,12 +731,13 @@ class Marshaller:
         write("<value><struct>\n")
         for k, v in value.items():
             write("<member>\n")
-            if type(k) is not StringType:
-                if unicode and type(k) is UnicodeType:
-                    k = k.encode(self.encoding)
-                else:
-                    raise TypeError, "dictionary key must be string"
-            write("<name>%s</name>\n" % escape(k))
+            if type(k) is StringType:
+                k = escape(k)
+            elif unicode and type(k) is UnicodeType:
+                k = escape(k).encode(self.encoding, 'xmlcharrefreplace')
+            else:
+                raise TypeError, "dictionary key must be string"
+            write("<name>%s</name>\n" % k)
             dump(v, write)
             write("</member>\n")
         write("</struct></value>\n")
@@ -784,6 +784,7 @@ class Unmarshaller:
         self._stack = []
         self._marks = []
         self._data = []
+        self._value = False
         self._methodname = None
         self._encoding = "utf-8"
         self.append = self._stack.append
@@ -814,6 +815,8 @@ class Unmarshaller:
         if tag == "array" or tag == "struct":
             self._marks.append(len(self._stack))
         self._data = []
+        if self._value and tag not in self.dispatch:
+            raise ResponseError("unknown tag %r" % tag)
         self._value = (tag == "value")
 
     def data(self, text):
@@ -1099,7 +1102,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None,
     if methodname:
         # a method call
         if not isinstance(methodname, StringType):
-            methodname = methodname.encode(encoding)
+            methodname = methodname.encode(encoding, 'xmlcharrefreplace')
         data = (
             xmlheader,
             "<methodCall>\n"
@@ -1560,7 +1563,7 @@ class ServerProxy:
                  allow_none=0, use_datetime=0, context=None):
         # establish a "logical" server connection
 
-        if isinstance(uri, unicode):
+        if unicode and isinstance(uri, unicode):
             uri = uri.encode('ISO-8859-1')
 
         # get the url
@@ -1616,7 +1619,7 @@ class ServerProxy:
         # magic method dispatcher
         return _Method(self.__request, name)
 
-    # note: to call a remote object with an non-standard name, use
+    # note: to call a remote object with a non-standard name, use
     # result getattr(server, "strange-python-name")(args)
 
     def __call__(self, attr):
index 74c9cfb..553d64e 100755 (executable)
@@ -206,7 +206,7 @@ def library_recipes():
 
     LT_10_5 = bool(getDeptargetTuple() < (10, 5))
 
-    if getDeptargetTuple() < (10, 6):
+    if not (10, 5) < getDeptargetTuple() < (10, 10):
         # The OpenSSL libs shipped with OS X 10.5 and earlier are
         # hopelessly out-of-date and do not include Apple's tie-in to
         # the root certificates in the user and system keychains via TEA
@@ -226,7 +226,8 @@ def library_recipes():
         # now more obvious with cert checking enabled by default in the
         # standard library.
         #
-        # For builds with 10.6+ SDKs, continue to use the deprecated but
+        # For builds with 10.6 through 10.9 SDKs,
+        # continue to use the deprecated but
         # less out-of-date Apple 0.9.8 libs for now.  While they are less
         # secure than using an up-to-date 1.0.1 version, doing so
         # avoids the big problems of forcing users to have to manage
@@ -234,12 +235,16 @@ def library_recipes():
         # APIs for cert validation from keychains if validation using the
         # standard OpenSSL locations (/System/Library/OpenSSL, normally empty)
         # fails.
+        #
+        # Since Apple removed the header files for the deprecated system
+        # OpenSSL as of the Xcode 7 release (for OS X 10.10+), we do not
+        # have much choice but to build our own copy here, too.
 
         result.extend([
           dict(
-              name="OpenSSL 1.0.2d",
-              url="https://www.openssl.org/source/openssl-1.0.2d.tar.gz",
-              checksum='38dd619b2e77cbac69b99f52a053d25a',
+              name="OpenSSL 1.0.2h",
+              url="https://www.openssl.org/source/openssl-1.0.2h.tar.gz",
+              checksum='9392e65072ce4b614c1392eefc1f23d0',
               patches=[
                   "openssl_sdk_makedepend.patch",
                    ],
index 86a0f2f..96a8841 100644 (file)
@@ -1,18 +1,17 @@
 # HG changeset patch
-# Parent  25a9af415e8c3faf591c360d5f0e361d049b2b43
+# Parent  d377390f787c0739a3e89f669def72d7167e5108
 # openssl_sdk_makedepend.patch
 #
-#      using openssl 1.0.2d
+#      using openssl 1.0.2f
 #
 # - support building with an OS X SDK
-# - allow "make depend" to use compilers with names other than "gcc"
 
 diff Configure
 
 diff --git a/Configure b/Configure
 --- a/Configure
 +++ b/Configure
-@@ -617,12 +617,12 @@
+@@ -638,12 +638,12 @@
  
  ##### MacOS X (a.k.a. Rhapsody or Darwin) setup
  "rhapsody-ppc-cc","cc:-O3 -DB_ENDIAN::(unknown):MACOSX_RHAPSODY::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}::",
@@ -31,24 +30,13 @@ diff --git a/Configure b/Configure
  "debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
  # iPhoneOS/iOS
  "iphoneos-cross","llvm-gcc:-O3 -isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fomit-frame-pointer -fno-common::-D_REENTRANT:iOS:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
-@@ -1685,7 +1685,7 @@
+@@ -1717,8 +1717,7 @@
                s/^CC=.*$/CC= $cc/;
                s/^AR=\s*ar/AR= $ar/;
                s/^RANLIB=.*/RANLIB= $ranlib/;
 -              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $cc eq "gcc";
-+              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/;
+-              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $ecc eq "gcc" || $ecc eq "clang";
++              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/
                }
        s/^CFLAG=.*$/CFLAG= $cflags/;
        s/^DEPFLAG=.*$/DEPFLAG=$depflags/;
-diff --git a/util/domd b/util/domd
---- a/util/domd
-+++ b/util/domd
-@@ -14,7 +14,7 @@
- cp Makefile Makefile.save
- # fake the presence of Kerberos
- touch $TOP/krb5.h
--if expr "$MAKEDEPEND" : '.*gcc$' > /dev/null; then
-+if true ; then  # was: if expr "$MAKEDEPEND" : '.*gcc$' > /dev/null; then
-     args=""
-     while [ $# -gt 0 ]; do
-       if [ "$1" != "--" ]; then args="$args $1"; fi
index fff4d5b..20982a4 100644 (file)
@@ -54,7 +54,7 @@ Thanks to the many outside volunteers who have worked under Guido's direction to
 \b0 \
 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation.\
 \
-2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee.\
+2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee.\
 \
 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python.\
 \
index a66b8c7..64d9169 100755 (executable)
@@ -58,7 +58,7 @@ case "${BSH}" in
        fi
        echo "" >> "${RC}"
        echo "# Setting PATH for Python ${PYVER}" >> "${RC}"
-       echo "# The orginal version is saved in .cshrc.pysave" >> "${RC}"
+       echo "# The original version is saved in .cshrc.pysave" >> "${RC}"
        echo "set path=(${PYTHON_ROOT}/bin "'$path'")" >> "${RC}"
        if [ `id -ur` = 0 ]; then
                chown "${USER}" "${RC}"
@@ -90,7 +90,7 @@ if [ -f "${PR}" ]; then
 fi
 echo "" >> "${PR}"
 echo "# Setting PATH for Python ${PYVER}" >> "${PR}"
-echo "# The orginal version is saved in `basename ${PR}`.pysave" >> "${PR}"
+echo "# The original version is saved in `basename ${PR}`.pysave" >> "${PR}"
 echo 'PATH="'"${PYTHON_ROOT}/bin"':${PATH}"' >> "${PR}"
 echo 'export PATH' >> "${PR}"
 if [ `id -ur` = 0 ]; then
index a2b0910..17aefc1 100644 (file)
@@ -20,7 +20,7 @@ class Special_Events_Events:
     }
 
     def mount(self, _object, _attributes={}, **_arguments):
-        """mount: Mounts an Disk Copy image as a disk volume
+        """mount: Mounts a Disk Copy image as a disk volume
         Required argument: a reference to the disk image to be mounted
         Keyword argument access_mode: the access mode for mounted volume (default is "any", i.e. best possible)
         Keyword argument checksum_verification: Verify the checksum before mounting?
index 6efcba1..5e91509 100644 (file)
@@ -36,7 +36,7 @@
        <key>CFBundleExecutable</key>
        <string>IDLE</string>
        <key>CFBundleGetInfoString</key>
-       <string>%VERSION%, © 2001-2015 Python Software Foundation</string>
+       <string>%VERSION%, © 2001-2016 Python Software Foundation</string>
        <key>CFBundleIconFile</key>
        <string>IDLE.icns</string>
        <key>CFBundleIdentifier</key>
index 6ae360c..98590ab 100644 (file)
@@ -7,6 +7,7 @@ CFLAGS=$(BASECFLAGS) $(OPT)
 LDFLAGS=@LDFLAGS@
 srcdir=         @srcdir@
 VERSION=       @VERSION@
+LIBDEST=$(prefix)/lib/python$(VERSION)
 UNIVERSALSDK=@UNIVERSALSDK@
 builddir=      ../..
 PYTHONFRAMEWORK=@PYTHONFRAMEWORK@
@@ -28,13 +29,28 @@ PYTHONAPPSDIR=@FRAMEWORKINSTALLAPPSPREFIX@/$(PYTHONFRAMEWORK) $(VERSION)
 
 all: IDLE.app
 
-install: IDLE.app $(srcdir)/config-main.def $(srcdir)/config-extensions.def
+install: IDLE.app
        test -d "$(DESTDIR)$(PYTHONAPPSDIR)" || mkdir -p "$(DESTDIR)$(PYTHONAPPSDIR)"
        -test -d "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" && rm -r "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app"
        /bin/cp -PR IDLE.app "$(DESTDIR)$(PYTHONAPPSDIR)"
        touch "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app"
-       /bin/cp $(srcdir)/config-main.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-main.def"
-       /bin/cp $(srcdir)/config-extensions.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-extensions.def"
+       if [ -f "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def" ]; then \
+               /bin/cp -p "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def" \
+                       "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def~" ; \
+               sed -e 's!name= IDLE Classic Windows!name= IDLE Classic OSX!g' \
+                       < "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def~" \
+                       > "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def" ; \
+               rm "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def~" ; \
+       fi
+       if [ -f "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def" ]; then \
+               /bin/cp -p "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def" \
+                       "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def~" ; \
+               sed -e 's!zoom-height=<Alt-Key-2>!zoom-height=<Option-Key-0>!g' \
+                       -e 's!<Alt-Key-!<Option-Key-!g' \
+                       < "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def~" \
+                       > "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def" ; \
+               rm "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def~" ; \
+       fi
 
 clean:
        rm -rf IDLE.app
diff --git a/Mac/IDLE/config-extensions.def b/Mac/IDLE/config-extensions.def
deleted file mode 100644 (file)
index 1791b9c..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-# config-extensions.def
-#
-# IDLE reads several config files to determine user preferences.  This
-# file is the default configuration file for IDLE extensions settings.
-#
-# Each extension must have at least one section, named after the extension
-# module. This section must contain an 'enable' item (=1 to enable the
-# extension, =0 to disable it), it may contain 'enable_editor' or 'enable_shell'
-# items, to apply it only to editor/shell windows, and may also contain any
-# other general configuration items for the extension.
-#
-# Each extension must define at least one section named ExtensionName_bindings
-# or ExtensionName_cfgBindings. If present, ExtensionName_bindings defines
-# virtual event bindings for the extension that are not user re-configurable.
-# If present, ExtensionName_cfgBindings defines virtual event bindings for the
-# extension that may be sensibly re-configured.
-#
-# If there are no keybindings for a menus' virtual events, include lines like
-# <<toggle-code-context>>=   (See [CodeContext], below.)
-#
-# Currently it is necessary to manually modify this file to change extension
-# key bindings and default values. To customize, create
-# ~/.idlerc/config-extensions.cfg and append the appropriate customized
-# section(s).  Those sections will override the defaults in this file.
-#
-# Note: If a keybinding is already in use when the extension is
-# loaded, the extension's virtual event's keybinding will be set to ''.
-#
-# See config-keys.def for notes on specifying keys and extend.txt for
-# information on creating IDLE extensions.
-
-[FormatParagraph]
-enable=1
-[FormatParagraph_cfgBindings]
-format-paragraph=<Option-Key-q>
-
-[AutoExpand]
-enable=1
-[AutoExpand_cfgBindings]
-expand-word=<Option-Key-slash>
-
-[ZoomHeight]
-enable=1
-[ZoomHeight_cfgBindings]
-zoom-height=<Option-Key-0>
-
-[ScriptBinding]
-enable=1
-[ScriptBinding_cfgBindings]
-run-module=<Key-F5>
-check-module=<Option-Key-x>
-
-[CallTips]
-enable=1
-[CallTips_cfgBindings]
-force-open-calltip=<Control-Key-backslash>
-[CallTips_bindings]
-try-open-calltip=<KeyRelease-parenleft>
-refresh-calltip=<KeyRelease-parenright> <KeyRelease-0>
-
-[ParenMatch]
-enable=1
-style= expression
-flash-delay= 500
-bell= 1
-[ParenMatch_cfgBindings]
-flash-paren=<Control-Key-0>
-[ParenMatch_bindings]
-paren-closed=<KeyRelease-parenright> <KeyRelease-bracketright> <KeyRelease-braceright>
-
-[AutoComplete]
-enable=1
-popupwait=2000
-[AutoComplete_cfgBindings]
-force-open-completions=<Control-Key-space>
-[AutoComplete_bindings]
-autocomplete=<Key-Tab>
-try-open-completions=<KeyRelease-period> <KeyRelease-slash> <KeyRelease-backslash>
-
-[CodeContext]
-enable=1
-enable_shell=0
-numlines=3
-visible=0
-bgcolor=LightGray
-fgcolor=Black
-[CodeContext_bindings]
-toggle-code-context=
-
-[RstripExtension]
-enable=1
-enable_shell=0
-enable_editor=1
diff --git a/Mac/IDLE/config-main.def b/Mac/IDLE/config-main.def
deleted file mode 100644 (file)
index 4691a85..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-# IDLE reads several config files to determine user preferences.  This
-# file is the default config file for general idle settings.
-#
-# When IDLE starts, it will look in
-# the following two sets of files, in order:
-#
-#     default configuration
-#     ---------------------
-#     config-main.def         the default general config file
-#     config-extensions.def   the default extension config file
-#     config-highlight.def    the default highlighting config file
-#     config-keys.def         the default keybinding config file
-#
-#     user configuration
-#     -------------------
-#     ~/.idlerc/config-main.cfg            the user general config file
-#     ~/.idlerc/config-extensions.cfg      the user extension config file
-#     ~/.idlerc/config-highlight.cfg       the user highlighting config file
-#     ~/.idlerc/config-keys.cfg            the user keybinding config file
-#
-# On Windows2000 and Windows XP the .idlerc directory is at
-#     Documents and Settings\<username>\.idlerc
-#
-# On Windows98 it is at c:\.idlerc
-#
-# Any options the user saves through the config dialog will be saved to
-# the relevant user config file. Reverting any general setting to the
-# default causes that entry to be wiped from the user file and re-read
-# from the default file. User highlighting themes or keybinding sets are
-# retained unless specifically deleted within the config dialog. Choosing
-# one of the default themes or keysets just applies the relevant settings
-# from the default file.
-#
-# Additional help sources are listed in the [HelpFiles] section and must be
-# viewable by a web browser (or the Windows Help viewer in the case of .chm
-# files). These sources will be listed on the Help menu.  The pattern is
-# <sequence_number = menu item;/path/to/help/source>
-# You can't use a semi-colon in a menu item or path.  The path will be platform
-# specific because of path separators, drive specs etc.
-#
-# It is best to use the Configuration GUI to set up additional help sources!
-# Example:
-#1 = My Extra Help Source;/usr/share/doc/foo/index.html
-#2 = Another Help Source;/path/to/another.pdf
-
-[General]
-editor-on-startup= 0
-autosave= 0
-print-command-posix=lpr %s
-print-command-win=start /min notepad /p %s
-delete-exitfunc= 1
-
-[EditorWindow]
-width= 80
-height= 40
-font= courier
-font-size= 10
-font-bold= 0
-encoding= none
-
-[FormatParagraph]
-paragraph=70
-
-[Indent]
-use-spaces= 1
-num-spaces= 4
-
-[Theme]
-default= 1
-name= IDLE Classic
-
-[Keys]
-default= 1
-name= IDLE Classic OSX
-
-[History]
-cyclic=1
-
-[HelpFiles]
index 4d17bf7..3a47cd0 100644 (file)
@@ -229,7 +229,7 @@ ici_ICEditPreferences(iciobject *self, PyObject *args)
 
 
 static char ici_ICParseURL__doc__[] =
-"(hint, data, selStart, selEnd, handle)->selStart, selEnd; Find an URL, return in handle"
+"(hint, data, selStart, selEnd, handle)->selStart, selEnd; Find a URL, return in handle"
 ;
 
 static PyObject *
@@ -253,7 +253,7 @@ ici_ICParseURL(iciobject *self, PyObject *args)
 
 
 static char ici_ICLaunchURL__doc__[] =
-"(hint, data, selStart, selEnd)->None; Find an URL and launch the correct app"
+"(hint, data, selStart, selEnd)->None; Find a URL and launch the correct app"
 ;
 
 static PyObject *
index 42846ea..6c4bfe8 100644 (file)
@@ -40,7 +40,7 @@
        <key>CFBundleExecutable</key>
        <string>PythonLauncher</string>
        <key>CFBundleGetInfoString</key>
-       <string>%VERSION%, © 2001-2015 Python Software Foundation</string>
+       <string>%VERSION%, © 2001-2016 Python Software Foundation</string>
        <key>CFBundleIconFile</key>
        <string>PythonLauncher.icns</string>
        <key>CFBundleIdentifier</key>
index 04c02a3..ec2cd27 100644 (file)
@@ -46,12 +46,15 @@ OS X specific arguments to configure
   The optional argument specifies which OS X SDK should be used to perform the
   build. This defaults to ``/Developer/SDKs/MacOSX.10.4u.sdk``.  When building
   on OS X 10.5 or later, you can specify ``/`` to use the installed system
-  headers rather than an SDK.
+  headers rather than an SDK.  As of OS X 10.9, you should install the optional
+  system headers from the Command Line Tools component using ``xcode-select``::
+
+     $ sudo xcode-select --install
 
   See the section _`Building and using a universal binary of Python on Mac OS X`
   for more information.
 
-* ``--with-univeral-archs=VALUE``
+* ``--with-universal-archs=VALUE``
 
   Specify the kind of universal binary that should be created. This option is 
   only valid when ``--enable-universalsdk`` is specified.
@@ -122,7 +125,7 @@ values are available:
 
 To build a universal binary that includes a 64-bit architecture, you must build
 on a system running OS X 10.5 or later.  The ``all`` and ``64-bit`` flavors can
-only be built with an 10.5 SDK because ``ppc64`` support was only included with
+only be built with a 10.5 SDK because ``ppc64`` support was only included with
 OS X 10.5.  Although legacy ``ppc`` support was included with Xcode 3 on OS X
 10.6, it was removed in Xcode 4, versions of which were released on OS X 10.6
 and which is the standard for OS X 10.7.  To summarize, the
index cb7e8d7..a0bb971 100644 (file)
@@ -20,7 +20,7 @@
        <key>CFBundleExecutable</key>
        <string>Python</string>
        <key>CFBundleGetInfoString</key>
-       <string>%version%, (c) 2001-2015 Python Software Foundation.</string>
+       <string>%version%, (c) 2001-2016 Python Software Foundation.</string>
        <key>CFBundleHelpBookFolder</key>
        <array>
                <string>Documentation</string>
@@ -37,7 +37,7 @@
        <key>CFBundleInfoDictionaryVersion</key>
        <string>6.0</string>
        <key>CFBundleLongVersionString</key>
-       <string>%version%, (c) 2001-2015 Python Software Foundation.</string>
+       <string>%version%, (c) 2001-2016 Python Software Foundation.</string>
        <key>CFBundleName</key>
        <string>Python</string>
        <key>CFBundlePackageType</key>
@@ -55,7 +55,7 @@
        <key>NSAppleScriptEnabled</key>
        <true/>
        <key>NSHumanReadableCopyright</key>
-       <string>(c) 2001-2015 Python Software Foundation.</string>
+       <string>(c) 2001-2016 Python Software Foundation.</string>
        <key>NSHighResolutionCapable</key>
        <true/>
 </dict>
index a97cc1f..fcba7d9 100644 (file)
@@ -17,9 +17,9 @@
        <key>CFBundlePackageType</key>
        <string>FMWK</string>
        <key>CFBundleShortVersionString</key>
-       <string>%VERSION%, (c) 2001-2015 Python Software Foundation.</string>
+       <string>%VERSION%, (c) 2001-2016 Python Software Foundation.</string>
        <key>CFBundleLongVersionString</key>
-       <string>%VERSION%, (c) 2001-2015 Python Software Foundation.</string>
+       <string>%VERSION%, (c) 2001-2016 Python Software Foundation.</string>
        <key>CFBundleSignature</key>
        <string>????</string>
        <key>CFBundleVersion</key>
index ee73edd..dffc0b9 100644 (file)
@@ -200,6 +200,7 @@ UNICODE_OBJS=   @UNICODE_OBJS@
 PYTHON=                python$(EXE)
 BUILDPYTHON=   python$(BUILDEXE)
 
+cross_compiling=@cross_compiling@
 PYTHON_FOR_BUILD=@PYTHON_FOR_BUILD@
 _PYTHON_HOST_PLATFORM=@_PYTHON_HOST_PLATFORM@
 HOST_GNU_TYPE=  @host@
@@ -209,7 +210,14 @@ TCLTK_INCLUDES=    @TCLTK_INCLUDES@
 TCLTK_LIBS=    @TCLTK_LIBS@
 
 # The task to run while instrument when building the profile-opt target
-PROFILE_TASK=-m test.regrtest --pgo
+# We exclude unittests with -x that take a rediculious amount of time to
+# run in the instrumented training build or do not provide much value.
+PROFILE_TASK=-m test.regrtest --pgo -x test_asyncore test_gdb test_multiprocessing test_subprocess
+
+# report files for gcov / lcov coverage report
+COVERAGE_INFO= $(abs_builddir)/coverage.info
+COVERAGE_REPORT=$(abs_builddir)/lcov-report
+COVERAGE_REPORT_OPTIONS=--no-branch-coverage --title "CPython lcov report"
 
 # === Definitions added by makesetup ===
 
@@ -426,7 +434,7 @@ build_all:  $(BUILDPYTHON) oldsharedmods sharedmods gdbhooks
 
 # Compile a binary with profile guided optimization.
 profile-opt:
-       @if [ $(LLVM_PROF_ERR) == yes ]; then \
+       @if [ $(LLVM_PROF_ERR) = yes ]; then \
                echo "Error: Cannot perform PGO build because llvm-profdata was not found in PATH" ;\
                echo "Please add it to PATH and run ./configure again" ;\
                exit 1;\
@@ -445,7 +453,7 @@ profile-opt:
        $(MAKE) profile-removal
 
 build_all_generate_profile:
-       $(MAKE) all CFLAGS="$(CFLAGS) $(PGO_PROF_GEN_FLAG)" LDFLAGS="$(LDFLAGS) $(PGO_PROF_GEN_FLAG)" LIBS="$(LIBS)"
+       $(MAKE) all CFLAGS="$(CFLAGS) $(PGO_PROF_GEN_FLAG) @LTOFLAGS@" LDFLAGS="$(LDFLAGS) $(PGO_PROF_GEN_FLAG) @LTOFLAGS@" LIBS="$(LIBS)"
 
 run_profile_task:
        : # FIXME: can't run for a cross build
@@ -455,13 +463,48 @@ build_all_merge_profile:
        $(LLVM_PROF_MERGER)
 
 build_all_use_profile:
-       $(MAKE) all CFLAGS="$(CFLAGS) $(PGO_PROF_USE_FLAG)"
+       $(MAKE) all CFLAGS="$(CFLAGS) $(PGO_PROF_USE_FLAG) @LTOFLAGS@" LDFLAGS="$(LDFLAGS) @LTOFLAGS@"
 
+# Compile and run with gcov
+.PHONY=coverage coverage-lcov coverage-report
 coverage:
        @echo "Building with support for coverage checking:"
-       $(MAKE) clean
+       $(MAKE) clean profile-removal
        $(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov"
 
+coverage-lcov:
+       @echo "Creating Coverage HTML report with LCOV:"
+       @rm -f $(COVERAGE_INFO)
+       @rm -rf $(COVERAGE_REPORT)
+       @lcov --capture --directory $(abs_builddir) \
+           --base-directory $(realpath $(abs_builddir)) \
+           --path $(realpath $(abs_srcdir)) \
+           --output-file $(COVERAGE_INFO)
+       : # remove 3rd party modules and system headers
+       @lcov --remove $(COVERAGE_INFO) \
+           '*/Modules/_ctypes/libffi*/*' \
+           '*/Modules/expat/*' \
+           '*/Modules/zlib/*' \
+           '*/Include/*' \
+           '/usr/include/*' \
+           '/usr/local/include/*' \
+           --output-file $(COVERAGE_INFO)
+       @genhtml $(COVERAGE_INFO) --output-directory $(COVERAGE_REPORT) \
+           $(COVERAGE_REPORT_OPTIONS)
+       @echo
+       @echo "lcov report at $(COVERAGE_REPORT)/index.html"
+       @echo
+
+coverage-report:
+       : # force rebuilding of parser
+       @touch $(GRAMMAR_INPUT)
+       : # build with coverage info
+       $(MAKE) coverage
+       : # run tests, ignore failures
+       $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) || true
+       : # build lcov report
+       $(MAKE) coverage-lcov
+
 
 # Build the interpreter
 $(BUILDPYTHON):        Modules/python.o $(LIBRARY) $(LDLIBRARY)
@@ -488,11 +531,15 @@ pybuilddir.txt: $(BUILDPYTHON)
                exit 1 ; \
        fi
 
+# This is shared by the math and cmath modules
+Modules/_math.o: Modules/_math.c Modules/_math.h
+       $(CC) -c $(CCSHARED) $(PY_CFLAGS) -o $@ $<
+
 # Build the shared modules
 # Under GNU make, MAKEFLAGS are sorted and normalized; the 's' for
 # -s, --silent or --quiet is always the first char.
 # Under BSD make, MAKEFLAGS might be " -s -v x=y".
-sharedmods: $(BUILDPYTHON) pybuilddir.txt
+sharedmods: $(BUILDPYTHON) pybuilddir.txt Modules/_math.o
        @case "$$MAKEFLAGS" in \
            *\ -s*|s*) quiet="-q";; \
            *) quiet="";; \
@@ -633,13 +680,22 @@ Modules/grpmodule.o: $(srcdir)/Modules/grpmodule.c $(srcdir)/Modules/posixmodule
 
 Modules/pwdmodule.o: $(srcdir)/Modules/pwdmodule.c $(srcdir)/Modules/posixmodule.h
 
-$(GRAMMAR_H): $(GRAMMAR_INPUT) $(PGENSRCS)
-               @$(MKDIR_P) Include
-               $(MAKE) $(PGEN)
-               $(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
-$(GRAMMAR_C): $(GRAMMAR_H) $(GRAMMAR_INPUT) $(PGENSRCS)
-               $(MAKE) $(GRAMMAR_H)
-               touch $(GRAMMAR_C)
+$(GRAMMAR_H): $(GRAMMAR_INPUT) $(PGEN)
+       @$(MKDIR_P) Include
+       # Avoid copying the file onto itself for an in-tree build
+       if test "$(cross_compiling)" != "yes"; then \
+               $(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C); \
+       else \
+               cp $(srcdir)/Include/graminit.h $(GRAMMAR_H).tmp; \
+               mv $(GRAMMAR_H).tmp $(GRAMMAR_H); \
+       fi
+$(GRAMMAR_C): $(GRAMMAR_H)
+       if test "$(cross_compiling)" != "yes"; then \
+               touch $(GRAMMAR_C); \
+       else \
+               cp $(srcdir)/Python/graminit.c $(GRAMMAR_C).tmp; \
+               mv $(GRAMMAR_C).tmp $(GRAMMAR_C); \
+       fi
 
 $(PGEN):       $(PGENOBJS)
                $(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
@@ -914,6 +970,10 @@ $(DESTSHARED):
 #  $(PYTHON) -> python2 -> python$(VERSION))
 # Also create equivalent chains for other installed files
 bininstall:    altbininstall
+       if test ! -d $(DESTDIR)$(LIBPC); then \
+               echo "Creating directory $(LIBPC)"; \
+               $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$(LIBPC); \
+       fi
        -if test -f $(DESTDIR)$(BINDIR)/$(PYTHON) -o -h $(DESTDIR)$(BINDIR)/$(PYTHON); \
        then rm -f $(DESTDIR)$(BINDIR)/$(PYTHON); \
        else true; \
@@ -1218,7 +1278,7 @@ sharedinstall: sharedmods
 # the Makefile in Mac
 #
 #
-# This target is here for backward compatiblity, previous versions of Python
+# This target is here for backward compatibility, previous versions of Python
 # hadn't integrated framework installation in the normal install process.
 frameworkinstall: install
 
@@ -1350,6 +1410,7 @@ clean: pycremoval
 profile-removal:
        find . -name '*.gc??' -exec rm -f {} ';'
        find . -name '*.profclang?' -exec rm -f {} ';'
+       find . -name '*.dyn' -exec rm -f {} ';'
 
 clobber: clean profile-removal
        -rm -f $(BUILDPYTHON) $(PGEN) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \
index c1f6481..ee3a465 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -45,8 +45,8 @@ Ross Andrus
 Juancarlo Añez
 Chris Angelico
 Jérémy Anger
-Ankur Ankan
 Jon Anglin
+Ankur Ankan
 Heidi Annexstad
 Ramchandra Apte
 Éric Araujo
@@ -163,8 +163,8 @@ Monty Brandenberg
 Georg Brandl
 Christopher Brannon
 Terrence Brannon
-Germán M. Bravo
 Sven Brauch
+Germán M. Bravo
 Erik Bray
 Brian Brazil
 Demian Brecht
@@ -336,6 +336,7 @@ Humberto Diogenes
 Yves Dionne
 Daniel Dittmar
 Josip Djolonga
+Walter Dörwald
 Jaromir Dolecek
 Ismail Donmez
 Robert Donohue
@@ -362,7 +363,6 @@ Gary Duzan
 Eugene Dvurechenski
 Josip Dzolonga
 Maxim Dzumanenko
-Walter Dörwald
 Hans Eckardt
 Rodolpho Eckhardt
 Ulrich Eckhardt
@@ -466,6 +466,7 @@ Matthieu Gautier
 Stephen M. Gava
 Xavier de Gaye
 Harry Henry Gebel
+Tamás Bence Gedai
 Marius Gedminas
 Thomas Gellekum
 Gabriel Genellina
@@ -617,6 +618,7 @@ Catalin Iacob
 Mihai Ibanescu
 Ali Ikinci
 Aaron Iles
+Thomas Ilsche
 Lars Immisch
 Bobby Impollonia
 Meador Inge
@@ -650,6 +652,7 @@ Philip Jenvey
 MunSic Jeong
 Chris Jerdonek
 Dmitry Jeremov
+Joe Jevnik
 Jim Jewett
 Pedro Diaz Jimenez
 Orjan Johansen
@@ -727,15 +730,18 @@ Pat Knight
 Jeff Knupp
 Kubilay Kocak
 Greg Kochanski
+Manvisha Kodali
 Damon Kohler
 Marko Kohtala
 Vajrasky Kok
 Guido Kollerie
 Jacek Konieczny
-Марк Коренберг
 Arkady Koplyarov
 Peter A. Koren
+Марк Коренберг
 Vlad Korolev
+Anna Koroliuk
+Susumu Koshiba
 Joseph Koshy
 Daniel Kozan
 Jerzy Kozera
@@ -826,7 +832,9 @@ Everett Lipman
 Mirko Liss
 Nick Lockwood
 Stephanie Lockwood
+Martin von Löwis
 Hugo Lopes Tavares
+Guillermo López-Anglada
 Anne Lord
 Tom Loredo
 Justin Love
@@ -843,8 +851,6 @@ Mark Lutz
 Taras Lyapun
 Jim Lynch
 Mikael Lyngvig
-Martin von Löwis
-Guillermo López-Anglada
 Jeff MacDonald
 John Machin
 Andrew I MacIntyre
@@ -869,9 +875,9 @@ Sven Marnach
 Alex Martelli
 Anthony Martin
 Owen Martin
+Sidney San Martín
 Westley Martínez
 Sébastien Martini
-Sidney San Martín
 Roger Masse
 Nick Mathewson
 Simon Mathieu
@@ -906,15 +912,15 @@ Lucas Prado Melo
 Ezio Melotti
 Doug Mennella
 Brian Merrell
+Alexis Métaireau
 Luke Mewburn
 Carl Meyer
 Mike Meyer
 Piotr Meyer
-Alexis Métaireau
 Steven Miale
-Trent Mick
 Jason Michalski
 Franck Michea
+Trent Mick
 Tom Middleton
 Thomas Miedema
 Stan Mihai
@@ -1013,11 +1019,13 @@ Oleg Oshmyan
 Denis S. Otkidach
 Peter Otten
 Michael Otteneder
-R. M. Oudkerk
+Richard Oudkerk
 Russel Owen
 Joonas Paalasmaa
 Martin Packman
 Shriphani Palakodety
+Julien Palard
+Aviv Palivoda
 Ondrej Palkovsky
 Mike Pall
 Todd R. Palmer
@@ -1030,6 +1038,7 @@ M. Papillon
 Peter Parente
 Alexandre Parenteau
 Dan Parisien
+HyeSoo Park
 William Park
 Heikki Partanen
 Harri Pasanen
@@ -1071,8 +1080,8 @@ Anand B. Pillai
 François Pinard
 Tom Pinckney
 Zach Pincus
-Zero Piraeus
 Michael Piotrowski
+Zero Piraeus
 Antoine Pitrou
 Jean-François Piéronne
 Oleg Plakhotnyuk
@@ -1093,6 +1102,7 @@ Florian Preinstorfer
 Amrit Prem
 Paul Prescod
 Donovan Preston
+Eric Price
 Paul Price
 Iuliia Proskurnia
 Dorian Pula
@@ -1100,15 +1110,16 @@ Jyrki Pulliainen
 Steve Purcell
 Eduardo Pérez
 Fernando Pérez
+Kevin Jing Qiu
 Pierre Quentel
 Brian Quinlan
-Kevin Jing Qiu
 Anders Qvist
 Thomas Rachel
 Ram Rachum
 Jérôme Radix
 Burton Radons
 Jeff Ramnani
+Varpu Rantala
 Brodie Rao
 Senko Rasic
 Antti Rasinen
@@ -1152,6 +1163,7 @@ Carl Robben
 Mark Roberts
 Andy Robinson
 Jim Robinson
+Daniel Rocco
 Mark Roddy
 Kevin Rodgers
 Sean Rodman
@@ -1209,7 +1221,6 @@ Ty Sarna
 Hugh Sasse
 Bob Savage
 Ben Sayer
-sbt
 Luca Sbardella
 Marco Scataglini
 Andrew Schaaf
@@ -1225,6 +1236,7 @@ Ralf Schmitt
 Michael Schneider
 Peter Schneider-Kamp
 Arvin Schnell
+Nofar Schnider
 Scott Schram
 Robin Schreiber
 Chad J. Schroeder
@@ -1248,8 +1260,8 @@ Pete Sevander
 Denis Severson
 Ian Seyer
 Daniel Shahaf
-Ha Shao
 Mark Shannon
+Ha Shao
 Richard Shapiro
 Varun Sharma
 Vlad Shcherbina
@@ -1280,6 +1292,7 @@ Ng Pheng Siong
 George Sipe
 J. Sipprell
 Kragen Sitaker
+Ville Skyttä
 Michael Sloan
 Nick Sloan
 Václav Šmilauer
@@ -1418,6 +1431,7 @@ Dmitry Vasiliev
 Sebastian Ortiz Vasquez
 Alexandre Vassalotti
 Nadeem Vawda
+Sye van der Veen
 Frank Vercruesse
 Mike Verdone
 Jaap Vermeulen
@@ -1436,6 +1450,7 @@ Alex Volkov
 Guido Vranken
 Martijn Vries
 Sjoerd de Vries
+Jonas Wagner
 Niki W. Waibel
 Wojtek Walczak
 Charles Waldman
@@ -1445,10 +1460,10 @@ Kevin Walzer
 Rodrigo Steinmuller Wanderley
 Dingyuan Wang
 Ke Wang
+Liang-Bo Wang
 Greg Ward
 Tom Wardill
 Zachary Ware
-Jonas Wagner
 Barry Warsaw
 Steve Waterbury
 Bob Watson
@@ -1483,6 +1498,7 @@ Sue Williams
 Carol Willing
 Steven Willis
 Frank Willison
+Alex Willmer
 Geoff Wilson
 Greg V. Wilson
 J Derek Wilson
index 41317e5..fa0c623 100644 (file)
@@ -1845,7 +1845,7 @@ Library
 
 - Patch #1110248: SYNC_FLUSH the zlib buffer for GZipFile.flush.
 
-- Patch #1107973: Allow to iterate over the lines of a tarfile.ExFileObject.
+- Patch #1107973: Allow iterating over the lines of a tarfile.ExFileObject.
 
 - Patch #1104111: Alter setup.py --help and --help-commands.
 
@@ -2822,7 +2822,7 @@ Library
   same as when the argument is omitted).
   [SF bug 658254, patch 663482]
 
-- nntplib does now allow to ignore a .netrc file.
+- nntplib does now allow ignoring a .netrc file.
 
 - urllib2 now recognizes Basic authentication even if other authentication
   schemes are offered.
@@ -3096,7 +3096,7 @@ Core and builtins
   would not be removed while allocating a new weakref object.  Since
   GC could be invoked at that time, however, that assumption was
   invalid.  In a truly obscure case of GC being triggered during
-  creation for a new weakref object for an referent which already
+  creation for a new weakref object for a referent which already
   has a weakref without a callback which is only referenced from
   cyclic trash, a memory error can occur.  This consistently created a
   segfault in a debug build, but provided less predictable behavior in
@@ -3134,7 +3134,7 @@ Core and builtins
 - When method objects have an attribute that can be satisfied either
   by the function object or by the method object, the function
   object's attribute usually wins.  Christian Tismer pointed out that
-  that this is really a mistake, because this only happens for special
+  this is really a mistake, because this only happens for special
   methods (like __reduce__) where the method object's version is
   really more appropriate than the function's attribute.  So from now
   on, all method attributes will have precedence over function
@@ -3240,7 +3240,7 @@ Extension modules
 
 - fcntl.ioctl now warns if the mutate flag is not specified.
 
-- nt now properly allows to refer to UNC roots, e.g. in nt.stat().
+- nt now properly allows referring to UNC roots, e.g. in nt.stat().
 
 - the weakref module now supports additional objects:  array.array,
   sre.pattern_objects, file objects, and sockets.
@@ -5148,7 +5148,7 @@ Core and builtins
 - All standard iterators now ensure that, once StopIteration has been
   raised, all future calls to next() on the same iterator will also
   raise StopIteration.  There used to be various counterexamples to
-  this behavior, which could caused confusion or subtle program
+  this behavior, which could have caused confusion or subtle program
   breakage, without any benefits.  (Note that this is still an
   iterator's responsibility; the iterator framework does not enforce
   this.)
@@ -5798,7 +5798,7 @@ C API
 - New functions PyErr_SetExcFromWindowsErr() and
   PyErr_SetExcFromWindowsErrWithFilename(). Similar to
   PyErr_SetFromWindowsErrWithFilename() and
-  PyErr_SetFromWindowsErr(), but they allow to specify
+  PyErr_SetFromWindowsErr(), but they allow specifying
   the exception type to raise. Available on Windows.
 
 - Py_FatalError() is now declared as taking a const char* argument.  It
@@ -6678,8 +6678,8 @@ Type/class unification and new-style classes
 - property() now takes 4 keyword arguments:  fget, fset, fdel and doc.
   These map to read-only attributes 'fget', 'fset', 'fdel', and '__doc__'
   in the constructed property object.  fget, fset and fdel weren't
-  discoverable from Python in 2.2a3.  __doc__ is new, and allows to
-  associate a docstring with a property.
+  discoverable from Python in 2.2a3.  __doc__ is new, and allows
+  associating a docstring with a property.
 
 - Comparison overloading is now more completely implemented.  For
   example, a str subclass instance can properly be compared to a str
@@ -7094,7 +7094,7 @@ Tests
 -----
 
 - regrtest.py now knows which tests are expected to be skipped on some
-  platforms, allowing to give clearer test result output.  regrtest
+  platforms, allowing clearer test result output to be given.  regrtest
   also has optional --use/-u switch to run normally disabled tests
   which require network access or consume significant disk resources.
 
@@ -7825,7 +7825,7 @@ Standard library
 
 - xml.dom.minidom offers a toprettyxml method. A number of DOM
   conformance issues have been resolved. In particular, Element now
-  has an hasAttributes method, and the handling of namespaces was
+  has a hasAttributes method, and the handling of namespaces was
   improved.
 
 - Ka-Ping Yee contributed two new modules: inspect.py, a module for
@@ -8024,7 +8024,7 @@ Core language, builtins, and interpreter
 
 - There is a new Unicode companion to the PyObject_Str() API
   called PyObject_Unicode(). It behaves in the same way as the
-  former, but assures that the returned value is an Unicode object
+  former, but assures that the returned value is a Unicode object
   (applying the usual coercion if necessary).
 
 - The comparison operators support "rich comparison overloading" (PEP
@@ -9315,7 +9315,7 @@ list of all new modules is included below.
 
 Probably the most pervasive change is the addition of Unicode support.
 We've added a new fundamental datatype, the Unicode string, a new
-build-in function unicode(), an numerous C APIs to deal with Unicode
+built-in function unicode(), a numerous C APIs to deal with Unicode
 and encodings.  See the file Misc/unicode.txt for details, or
 http://starship.python.net/crew/lemburg/unicode-proposal.txt.
 
@@ -10009,7 +10009,7 @@ Fri Mar 26 22:36:00 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>
 
        * Tools/scripts/dutree.py:
        During display, if EPIPE is raised, it's probably because a pager was
-       killed.  Discard the error in that case, but propogate it otherwise.
+       killed.  Discard the error in that case, but propagate it otherwise.
 
 Fri Mar 26 16:20:45 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>
 
@@ -10800,7 +10800,7 @@ real list objects.
 - The uu module now deals better with trailing garbage generated by
 some broke uuencoders.
 
-- The telnet module now has an my_interact() method which uses threads
+- The telnet module now has a my_interact() method which uses threads
 instead of select.  The interact() method uses this by default on
 Windows (where the single-threaded version doesn't work).
 
@@ -11857,7 +11857,7 @@ PyEval_CallMethod().
 - New macros to access object members for PyFunction, PyCFunction
 objects.
 
-- New APIs PyImport_AppendInittab() an PyImport_ExtendInittab() to
+- New APIs PyImport_AppendInittab() and PyImport_ExtendInittab() to
 dynamically add one or many entries to the table of built-in modules.
 
 - New macro Py_InitModule3(name, methods, doc) which calls
@@ -12831,7 +12831,7 @@ the first class with an applicable hook wins.  Makes more sense.
 - Changed the checks made in Py_Initialize() and Py_Finalize().  It is
 now legal to call these more than once.  The first call to
 Py_Initialize() initializes, the first call to Py_Finalize()
-finalizes.  There's also a new API, Py_IsInitalized() which checks
+finalizes.  There's also a new API, Py_IsInitialized() which checks
 whether we are already initialized (in case you want to leave things
 as they were).
 
@@ -15887,7 +15887,7 @@ the first time it is imported.
 python parser.  Corresponding standard library modules token and symbol
 defines the numeric values of tokens and non-terminal symbols.
 
-* The posix module has aquired new functions setuid(), setgid(),
+* The posix module has acquired new functions setuid(), setgid(),
 execve(), and exec() has been renamed to execv().
 
 * The array module is extended with 8-byte object swaps, the 'i'
@@ -15901,7 +15901,7 @@ module can't be decoded by the new version.
 * For select.select(), a timeout (4th) argument of None means the same
 as leaving the timeout argument out.
 
-* Module strop (and hence standard library module string) has aquired
+* Module strop (and hence standard library module string) has acquired
 a new function: rindex().  Thanks to Amrit Prem!
 
 * Module regex defines a new function symcomp() which uses an extended
@@ -16267,7 +16267,7 @@ a string it is returned unchanged, otherwise it returns `x`.
 * repr(x) returns the same as `x`.  (Some users found it easier to
 have this as a function.)
 
-* round(x) returns the floating point number x rounded to an whole
+* round(x) returns the floating point number x rounded to a whole
 number, represented as a floating point number.  round(x, n) returns x
 rounded to n digits.
 
@@ -17047,7 +17047,7 @@ New features in 0.9.6:
   to give more useful results for negative operands
 - Changed/added range checks for long/plain integer shifts
 - Options found after "-c command" are now passed to the command in sys.argv
-  (note subtle incompatiblity with "python -c command -- -options"!)
+  (note subtle incompatibility with "python -c command -- -options"!)
 - Module stdwin is better protected against touching objects after they've
   been closed; menus can now also be closed explicitly
 - Stdwin now uses its own exception (stdwin.error)
index 5b9793b..4ab3a70 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -2,6 +2,416 @@
 Python News
 +++++++++++
 
+What's New in Python 2.7.12?
+============================
+
+*Release date: 2016-06-25*
+
+Build
+-----
+
+- Issue #26930: Update Windows builds to use OpenSSL 1.0.2h.
+
+IDLE
+----
+
+- Issue #27365: Fix about dialog.
+
+
+What's New in Python 2.7.12 release candidate 1?
+================================================
+
+*Release date: 2016-06-12*
+
+Core and Builtins
+-----------------
+
+- Issue #20041: Fixed TypeError when frame.f_trace is set to None.
+  Patch by Xavier de Gaye.
+
+- Issue #25702: A --with-lto configure option has been added that will
+  enable link time optimizations at build time during a make profile-opt.
+  Some compilers and toolchains are known to not produce stable code when
+  using LTO, be sure to test things thoroughly before relying on it.
+  It can provide a few % speed up over profile-opt alone.
+
+- Issue #26168: Fixed possible refleaks in failing Py_BuildValue() with the "N"
+  format unit.
+
+- Issue #27039: Fixed bytearray.remove() for values greater than 127.  Patch by
+  Joe Jevnik.
+
+- Issue #4806: Avoid masking the original TypeError exception when using star
+  (*) unpacking and the exception was raised from a generator.  Based on
+  patch by Hagen Fürstenau.
+
+- Issue #26659: Make the builtin slice type support cycle collection.
+
+- Issue #26718: super.__init__ no longer leaks memory if called multiple times.
+  NOTE: A direct call of super.__init__ is not endorsed!
+
+- Issue #13410: Fixed a bug in PyUnicode_Format where it failed to properly
+  ignore errors from a __int__() method.
+
+- Issue #26494: Fixed crash on iterating exhausting iterators.
+  Affected classes are generic sequence iterators, iterators of bytearray,
+  list, tuple, set, frozenset, dict, OrderedDict and corresponding views.
+
+- Issue #26581: If coding cookie is specified multiple times on a line in
+  Python source code file, only the first one is taken to account.
+
+- Issue #22836: Ensure exception reports from PyErr_Display() and
+  PyErr_WriteUnraisable() are sensible even when formatting them produces
+  secondary errors.  This affects the reports produced by
+  sys.__excepthook__() and when __del__() raises an exception.
+
+- Issue #22847: Improve method cache efficiency.
+
+- Issue #25843: When compiling code, don't merge constants if they are equal
+  but have a different types. For example, ``f1, f2 = lambda: 1, lambda: 1.0``
+  is now correctly compiled to two different functions: ``f1()`` returns ``1``
+  (``int``) and ``f2()`` returns ``1.0`` (``int``), even if ``1`` and ``1.0``
+  are equal.
+
+- Issue #22995: [UPDATE] Remove the one of the pickleability tests in
+  _PyObject_GetState() due to regressions observed in Cython-based projects.
+
+- Issue #25961: Disallowed null characters in the type name.
+
+- Issue #22995: Instances of extension types with a state that aren't
+  subclasses of list or dict and haven't implemented any pickle-related
+  methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__,
+  or __getstate__), can no longer be pickled.  Including memoryview.
+
+- Issue #20440: Massive replacing unsafe attribute setting code with special
+  macro Py_SETREF.
+
+- Issue #25421: __sizeof__ methods of builtin types now use dynamic basic size.
+  This allows sys.getsize() to work correctly with their subclasses with
+  __slots__ defined.
+
+- Issue #19543: Added Py3k warning for decoding unicode.
+
+- Issue #24097: Fixed crash in object.__reduce__() if slot name is freed inside
+  __getattr__.
+
+- Issue #24731: Fixed crash on converting objects with special methods
+  __str__, __trunc__, and __float__ returning instances of subclasses of
+  str, long, and float to subclasses of str, long, and float correspondingly.
+
+- Issue #26478: Fix semantic bugs when using binary operators with dictionary
+  views and tuples.
+
+- Issue #26171: Fix possible integer overflow and heap corruption in
+  zipimporter.get_data().
+
+Library
+-------
+
+- Issue #26556: Update expat to 2.1.1, fixes CVE-2015-1283.
+
+- Fix TLS stripping vulnerability in smptlib, CVE-2016-0772.  Reported by Team
+  Oststrom
+
+- Issue #7356: ctypes.util: Make parsing of ldconfig output independent of the
+  locale.
+
+- Issue #25738: Stop BaseHTTPServer.BaseHTTPRequestHandler.send_error() from
+  sending a message body for 205 Reset Content.  Also, don't send the
+  Content-Type header field in responses that don't have a body.  Based on
+  patch by Susumu Koshiba.
+
+- Issue #21313: Fix the "platform" module to tolerate when sys.version
+  contains truncated build information.
+
+- Issue #27211: Fix possible memory corruption in io.IOBase.readline().
+
+- Issue #27114: Fix SSLContext._load_windows_store_certs fails with
+  PermissionError
+
+- Issue #14132: Fix urllib.request redirect handling when the target only has
+  a query string.  Fix by Ján Janech.
+
+- Removed the requirements for the ctypes and modulefinder modules to be
+  compatible with earlier Python versions.
+
+- Issue #22274: In the subprocess module, allow stderr to be redirected to
+  stdout even when stdout is not redirected.  Patch by Akira Li.
+
+- Issue #12045: Avoid duplicate execution of command in ctypes.util._get_soname().
+  Patch by Sijin Joseph.
+
+- Issue #26960: Backported #16270 from Python 3 to Python 2, to prevent urllib
+  from hanging when retrieving certain FTP files.
+
+- Issue #25745: Fixed leaking a userptr in curses panel destructor.
+
+- Issue #17765: weakref.ref() no longer silently ignores keyword arguments.
+  Patch by Georg Brandl.
+
+- Issue #26873: xmlrpclib now raises ResponseError on unsupported type tags
+  instead of silently return incorrect result.
+
+- Issue #24114: Fix an uninitialized variable in `ctypes.util`.
+
+  The bug only occurs on SunOS when the ctypes implementation searches
+  for the `crle` program.  Patch by Xiang Zhang.  Tested on SunOS by
+  Kees Bos.
+
+- Issue #26864: In urllib, change the proxy bypass host checking against
+  no_proxy to be case-insensitive, and to not match unrelated host names that
+  happen to have a bypassed hostname as a suffix.  Patch by Xiang Zhang.
+
+- Issue #26804: urllib will prefer lower_case proxy environment variables over
+  UPPER_CASE or Mixed_Case ones. Patch contributed by Hans-Peter Jansen.
+
+- Issue #26837: assertSequenceEqual() now correctly outputs non-stringified
+  differing items.  This affects assertListEqual() and assertTupleEqual().
+
+- Issue #26822: itemgetter, attrgetter and methodcaller objects no longer
+  silently ignore keyword arguments.
+
+- Issue #26657: Fix directory traversal vulnerability with SimpleHTTPServer
+  on Windows.  This fixes a regression that was introduced in 2.7.7.  Based
+  on patch by Philipp Hagemeister.
+
+- Issue #19377: Add .svg to mimetypes.types_map.
+
+- Issue #13952: Add .csv to mimetypes.types_map.  Patch by Geoff Wilson.
+
+- Issue #16329: Add .webm to mimetypes.types_map.  Patch by Giampaolo Rodola'.
+
+- Issue #23735: Handle terminal resizing with Readline 6.3+ by installing our
+  own SIGWINCH handler.  Patch by Eric Price.
+
+- Issue #26644: Raise ValueError rather than SystemError when a negative
+  length is passed to SSLSocket.recv() or read().
+
+- Issue #23804: Fix SSL recv(0) and read(0) methods to return zero bytes
+  instead of up to 1024.
+
+- Issue #24266: Ctrl+C during Readline history search now cancels the search
+  mode when compiled with Readline 7.
+
+- Issue #23857: Implement PEP 493, adding a Python-2-only ssl module API and
+  environment variable to configure the default handling of SSL/TLS certificates
+  for HTTPS connections.
+
+- Issue #26313: ssl.py _load_windows_store_certs fails if windows cert store
+  is empty. Patch by Baji.
+
+- Issue #26513: Fixes platform module detection of Windows Server
+
+- Issue #23718: Fixed parsing time in week 0 before Jan 1.  Original patch by
+  Tamás Bence Gedai.
+
+- Issue #26177: Fixed the keys() method for Canvas and Scrollbar widgets.
+
+- Issue #15068: Got rid of excessive buffering in the fileinput module.
+  The bufsize parameter is no longer used.
+
+- Issue #2202: Fix UnboundLocalError in
+  AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by Mathieu Dupuy.
+
+- Issue #26475: Fixed debugging output for regular expressions with the (?x)
+  flag.
+
+- Issue #26385: Remove the file if the internal fdopen() call in
+  NamedTemporaryFile() fails.  Based on patch by Silent Ghost.
+
+- Issue #26309: In the "socketserver" module, shut down the request (closing
+  the connected socket) when verify_request() returns false.  Based on patch
+  by Aviv Palivoda.
+
+- Issue #25939: On Windows open the cert store readonly in ssl.enum_certificates.
+
+- Issue #24303: Fix random EEXIST upon multiprocessing semaphores creation with
+  Linux PID namespaces enabled.
+
+- Issue #25698: Importing module if the stack is too deep no longer replaces
+  imported module with the empty one.
+
+- Issue #12923: Reset FancyURLopener's redirect counter even if there is an
+  exception.  Based on patches by Brian Brazil and Daniel Rocco.
+
+- Issue #25945: Fixed a crash when unpickle the functools.partial object with
+  wrong state.  Fixed a leak in failed functools.partial constructor.
+  "args" and "keywords" attributes of functools.partial have now always types
+  tuple and dict correspondingly.
+
+- Issue #19883: Fixed possible integer overflows in zipimport.
+
+- Issue #26147: xmlrpclib now works with unicode not encodable with used
+  non-UTF-8 encoding.
+
+- Issue #16620: Fixed AttributeError in msilib.Directory.glob().
+
+- Issue #21847: Fixed xmlrpclib on Unicode-disabled builds.
+
+- Issue #6500: Fixed infinite recursion in urllib2.Request.__getattr__().
+
+- Issue #26083: Workaround a subprocess bug that raises an incorrect
+  "ValueError: insecure string pickle" exception instead of the actual
+  exception on some platforms such as Mac OS X when an exception raised
+  in the forked child process prior to the exec() was large enough that
+  it overflowed the internal errpipe_read pipe buffer.
+
+- Issue #24103: Fixed possible use after free in ElementTree.iterparse().
+
+- Issue #20954: _args_from_interpreter_flags used by multiprocessing and some
+  tests no longer behaves incorrectly in the presence of the PYTHONHASHSEED
+  environment variable.
+
+- Issue #14285: When executing a package with the "python -m package" option,
+  and package initialization raises ImportError, a proper traceback is now
+  reported.
+
+- Issue #6478: _strptime's regexp cache now is reset after changing timezone
+  with time.tzset().
+
+- Issue #25718: Fixed copying object with state with boolean value is false.
+
+- Issue #25742: :func:`locale.setlocale` now accepts a Unicode string for
+  its second parameter.
+
+- Issue #10131: Fixed deep copying of minidom documents.  Based on patch
+  by Marian Ganisin.
+
+- Issue #25725: Fixed a reference leak in cPickle.loads() when unpickling
+  invalid data including tuple instructions.
+
+- Issue #25663: In the Readline completer, avoid listing duplicate global
+  names, and search the global namespace before searching builtins.
+
+- Issue #25688: Fixed file leak in ElementTree.iterparse() raising an error.
+
+- Issue #23914: Fixed SystemError raised by CPickle unpickler on broken data.
+
+- Issue #25924: Avoid unnecessary serialization of getaddrinfo(3) calls on
+  OS X versions 10.5 or higher.  Original patch by A. Jesse Jiryu Davis.
+
+- Issue #26406: Avoid unnecessary serialization of getaddrinfo(3) calls on
+  current versions of OpenBSD and NetBSD.  Patch by A. Jesse Jiryu Davis.
+
+IDLE
+----
+
+- Issue #5124: Paste with text selected now replaces the selection on X11.
+  This matches how paste works on Windows, Mac, most modern Linux apps,
+  and ttk widgets.  Original patch by Serhiy Storchaka.
+
+- Issue #24759: Make clear in idlelib.idle_test.__init__ that the directory
+  is a private implementation of test.test_idle and tool for maintainers.
+
+- Issue #26673: When tk reports font size as 0, change to size 10.
+  Such fonts on Linux prevented the configuration dialog from opening.
+
+- Issue #27044: Add ConfigDialog.remove_var_callbacks to stop memory leaks.
+
+- In the 'IDLE-console differences' section of the IDLE doc, clarify
+  how running with IDLE affects sys.modules and the standard streams.
+
+- Issue #25507: fix incorrect change in IOBinding that prevented printing.
+  Change also prevented saving shell window with non-ascii characters.
+  Augment IOBinding htest to include all major IOBinding functions.
+
+- Issue #25905: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION
+  MARK in README.txt and open this and NEWS.txt with 'ascii'.
+  Re-encode CREDITS.txt to utf-8 and open it with 'utf-8'.
+
+- Issue #26417: Prevent spurious errors and incorrect defaults when
+  installing IDLE 2.7 on OS X: default configuration settings are
+  no longer installed from OS X specific copies.
+
+Documentation
+-------------
+
+- Issue #26736: Used HTTPS for external links in the documentation if possible.
+
+- Issue #6953: Rework the Readline module documentation to group related
+  functions together, and add more details such as what underlying Readline
+  functions and variables are accessed.
+
+- Issue #26014: Guide users to the newer packaging documentation as was done
+  for Python 3.x.  In particular, the top-level 2.7 documentation page now
+  links to the newer installer and distributions pages rather than the
+  legacy install and Distutils pages; these are still linked to in the
+  library/distutils doc page.
+
+Tests
+-----
+
+- Issue #21916: Added tests for the turtle module.  Patch by ingrid,
+  Gregory Loyse and Jelle Zijlstra.
+
+- Issue #25940: Changed test_ssl to use self-signed.pythontest.net.  This
+  avoids relying on svn.python.org, which recently changed root certificate.
+
+- Issue #25616: Tests for OrderedDict are extracted from test_collections
+  into separate file test_ordered_dict.
+
+Build
+-----
+
+- Issue #22359: Avoid incorrect recursive $(MAKE), and disable the rules for
+  running pgen when cross-compiling.  The pgen output is normally saved with
+  the source code anyway, and is still regenerated when doing a native build.
+  Patch by Jonas Wagner and Xavier de Gaye.
+
+- Issue #19450: Update Windows builds to use SQLite 3.8.11.0.
+
+- Issue #27229: Fix the cross-compiling pgen rule for in-tree builds.  Patch
+  by Xavier de Gaye.
+
+- Issue #17603: Avoid error about nonexistant fileblocks.o file by using a
+  lower-level check for st_blocks in struct stat.
+
+- Issue #26465: Update Windows builds to use OpenSSL 1.0.2g.
+
+- Issue #24421: Compile Modules/_math.c once, before building extensions.
+  Previously it could fail to compile properly if the math and cmath builds
+  were concurrent.
+
+- Issue #25824: Fixes sys.winver to not include any architecture suffix.
+
+- Issue #25348: Added ``--pgo`` and ``--pgo-job`` arguments to
+  ``PCbuild\build.bat`` for building with Profile-Guided Optimization.  The
+  old ``PCbuild\build_pgo.bat`` script is now deprecated, and simply calls
+  ``PCbuild\build.bat --pgo %*``.
+
+- Issue #25827: Add support for building with ICC to ``configure``, including
+  a new ``--with-icc`` flag.
+
+- Issue #25696: Fix installation of Python on UNIX with make -j9.
+
+- Issue #26930: Update OS X 10.5+ 32-bit-only installer to build
+  and link with OpenSSL 1.0.2h.
+
+- Issue #26268: Update Windows builds to use OpenSSL 1.0.2f.
+
+- Issue #25136: Support Apple Xcode 7's new textual SDK stub libraries.
+
+Tools/Demos
+-----------
+
+- Issue #26799: Fix python-gdb.py: don't get C types once when the Python code
+  is loaded, but get C types on demand. The C types can change if
+  python-gdb.py is loaded before the Python executable. Patch written by Thomas
+  Ilsche.
+
+C API
+-----
+
+- Issue #26476: Fixed compilation error when use PyErr_BadInternalCall() in C++.
+  Patch by Jeroen Demeyer.
+
+Misc
+----
+
+- Issue #17500, and https://github.com/python/pythondotorg/issues/945: Remove
+  unused and outdated icons.
+
+
 What's New in Python 2.7.11?
 ============================
 
@@ -242,7 +652,7 @@ Library
 IDLE
 ----
 
-- Issue 15348: Stop the debugger engine (normally in a user process)
+- Issue #15348: Stop the debugger engine (normally in a user process)
   before closing the debugger window (running in the IDLE process).
   This prevents the RuntimeErrors that were being caught and ignored.
 
@@ -339,7 +749,7 @@ IDLE
 - Issue #23672: Allow Idle to edit and run files with astral chars in name.
   Patch by Mohd Sanad Zaki Rizvi.
 
-- Issue 24745: Idle editor default font. Switch from Courier to
+- Issue #24745: Idle editor default font. Switch from Courier to
   platform-sensitive TkFixedFont.  This should not affect current customized
   font selections.  If there is a problem, edit $HOME/.idlerc/config-main.cfg
   and remove 'fontxxx' entries from [Editor Window].  Patch by Mark Roseman.
@@ -491,8 +901,8 @@ Library
 - Issue #21802: The reader in BufferedRWPair now is closed even when closing
   writer failed in BufferedRWPair.close().
 
-- Issue #23671: string.Template now allows to specify the "self" parameter as
-  keyword argument.  string.Formatter now allows to specify the "self" and
+- Issue #23671: string.Template now allows specifying the "self" parameter as
+  a keyword argument.  string.Formatter now allows specifying the "self" and
   the "format_string" parameters as keyword arguments.
 
 - Issue #21560: An attempt to write a data of wrong type no longer cause
@@ -613,7 +1023,7 @@ Library
 - Issue #23016: A warning no longer produces an AttributeError when sys.stderr
   is None.
 
-- Issue #21032. Fixed socket leak if HTTPConnection.getresponse() fails.
+- Issue #21032: Fixed socket leak if HTTPConnection.getresponse() fails.
   Original patch by Martin Panter.
 
 - Issue #22609: Constructors and update methods of mapping classes in the
@@ -1027,7 +1437,7 @@ IDLE
   move version to end.
 
 - Issue #14105: Idle debugger breakpoints no longer disappear
-  when inseting or deleting lines.
+  when inserting or deleting lines.
 
 Extension Modules
 -----------------
@@ -2002,8 +2412,8 @@ Library
   with port None or "0" and flags AI_NUMERICSERV.
 
 - Issue #18080: When building a C extension module on OS X, if the compiler
-  is overriden with the CC environment variable, use the new compiler as
-  the default for linking if LDSHARED is not also overriden.  This restores
+  is overridden with the CC environment variable, use the new compiler as
+  the default for linking if LDSHARED is not also overridden.  This restores
   Distutils behavior introduced in 2.7.3 and inadvertently dropped in 2.7.4.
 
 - Issue #18071: C extension module builds on OS X could fail with TypeError
@@ -2170,7 +2580,7 @@ Library
 - Issue #16601: Restarting iteration over tarfile no more continues from where
   it left off.  Patch by Michael Birtwell.
 
-- Issue 16584: in filecomp._cmp, catch IOError as well as os.error.
+- Issue #16584: in filecomp._cmp, catch IOError as well as os.error.
   Patch by Till Maas.
 
 - Issue #17926: Fix dbm.__contains__ on 64-bit big-endian machines.
@@ -2340,7 +2750,7 @@ Tests
 Documentation
 -------------
 
-- Issue 17538: Document XML vulnerabilties
+- Issue #17538: Document XML vulnerabilties
 
 
 What's New in Python 2.7.4 release candidate 1
@@ -2647,7 +3057,7 @@ Library
 
 - Issue #17073: Fix some integer overflows in sqlite3 module.
 
-- Issue #6083: Fix multiple segmentation faults occured when PyArg_ParseTuple
+- Issue #6083: Fix multiple segmentation faults occurred when PyArg_ParseTuple
   parses nested mutating sequence.
 
 - Issue #5289: Fix ctypes.util.find_library on Solaris.
@@ -2794,7 +3204,7 @@ Library
 - Issue #16152: fix tokenize to ignore whitespace at the end of the code when
   no newline is found.  Patch by Ned Batchelder.
 
-- Issue #16230: Fix a crash in select.select() when one the lists changes
+- Issue #16230: Fix a crash in select.select() when one of the lists changes
   size while iterated on.  Patch by Serhiy Storchaka.
 
 - Issue #16228: Fix a crash in the json module where a list changes size
@@ -3924,7 +4334,7 @@ Extension Modules
 IDLE
 ----
 
-- Issue #964437 Make IDLE help window non-modal.
+- Issue #964437: Make IDLE help window non-modal.
   Patch by Guilherme Polo and Roger Serwy.
 
 - Issue #13933: IDLE auto-complete did not work with some imported
@@ -4397,7 +4807,7 @@ Library
 
 - Subclasses of collections.OrderedDict now work correctly with __missing__.
 
-- Issue #10753 - Characters ';', '=' and ',' in the PATH_INFO environment
+- Issue #10753: Characters ';', '=' and ',' in the PATH_INFO environment
   variable won't be quoted when the URI is constructed by the wsgiref.util 's
   request_uri method. According to RFC 3986, these characters can be a part of
   params in PATH component of URI and need not be quoted.
@@ -4527,7 +4937,7 @@ IDLE
 - Issue #4676: <Home> toggle failing on Tk 8.5, causing IDLE exits and
   strange selection behavior.  Improve selection extension behaviour.
 
-- Issue #3851 <Home> toggle non-functional when NumLock set on Windows.
+- Issue #3851: <Home> toggle non-functional when NumLock set on Windows.
 
 Build
 -----
@@ -4956,10 +5366,10 @@ Library
 
 - Issue #6869: Fix a refcount problem in the _ctypes extension.
 
-- Issue5504 - ctypes should now work with systems where mmap can't be
+- Issue #5504: ctypes should now work with systems where mmap can't be
   PROT_WRITE and PROT_EXEC.
 
-- Fix Issue8280 - urllib2's Request method will remove fragements in the url.
+- Issue #8280: urllib2's Request method will remove fragements in the url.
   This is how it is supposed to work, wget and curl do the same.  Previous
   behavior was wrong.
 
@@ -5125,7 +5535,7 @@ Extension Modules
 
 - Issue #7900: The getgroups(2) system call on MacOSX behaves rather oddly
   compared to other unix systems. In particular, os.getgroups() does
-  not reflect any changes made using os.setgroups() but basicly always
+  not reflect any changes made using os.setgroups() but basically always
   returns the same information as the id command.
 
   os.getgroups() can now return more than 16 groups on MacOSX.
@@ -5311,7 +5721,7 @@ Library
 Documentation
 -------------
 
-- Issues #8909: Added the size of the bitmap used in the installer created by
+- Issue #8909: Added the size of the bitmap used in the installer created by
   distutils' bdist_wininst. Patch by Anatoly Techtonik.
 
 Misc
@@ -5383,7 +5793,7 @@ Library
   unittest.TestCase.assertSequenceEqual are no longer included in failure
   reports.
 
-- Issue #8899: time.struct_time now has class and atribute docstrings.
+- Issue #8899: time.struct_time now has class and attribute docstrings.
 
 - Issue #4487: email now accepts as charset aliases all codec aliases
   accepted by the codecs module.
@@ -5742,7 +6152,7 @@ Core and Builtins
 - Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in case it
   is set.
 
-- Issue #1583863: An unicode subclass can now override the __unicode__ method
+- Issue #1583863: A unicode subclass can now override the __unicode__ method
 
 - Issue #6474: Make error message from passing an inadequate number of keyword
   arguments to a function correct.
@@ -5857,9 +6267,6 @@ Library
 
 - Issue #8140: Extend compileall to compile single files.  Add -i option.
 
-- Issue #7356: ctypes.util: Make parsing of ldconfig output independent of the
-  locale.
-
 - Issue #7774: Set sys.executable to an empty string if ``argv[0]`` has been set
   to an non existent program name and Python is unable to retrieve the real
   program name.
@@ -6247,7 +6654,7 @@ Library
   when the release file is empty.
 
 - Issue #7748: Since unicode values are supported for some metadata options in
-  Distutils, the DistributionMetadata get_* methods will now return an utf-8
+  Distutils, the DistributionMetadata get_* methods will now return a utf-8
   encoded string for them.  This ensures that the upload and register commands
   send the correct values to PyPI without any error.
 
@@ -7734,7 +8141,7 @@ Library
   backported to help facilitate transitions from 2.7 to 3.1.
 
 - Issue #1885: distutils: When running sdist with --formats=tar,gztar the tar
-  file was overriden by the gztar one.
+  file was overridden by the gztar one.
 
 - Issue #4863: distutils.mwerkscompiler has been removed.
 
@@ -8023,7 +8430,7 @@ Build
   installed.
 
 - Issue #5809: Specifying both --enable-framework and --enable-shared is an
-  error. Configure now explicity tells you about this.
+  error. Configure now explicitly tells you about this.
 
 - Issue #3585: Add pkg-config support.  It creates a python-2.7.pc file and a
   python.pc symlink in the $(LIBDIR)/pkgconfig directory.  Patch by Clinton Roy.
@@ -8623,7 +9030,7 @@ Library
 - Silence the DeprecationWarning raised when importing mimetools in
   BaseHTTPServer, cgi (and rfc822), httplib.
 
-- Issue #2776: fixed small issue when handling an URL with double slash
+- Issue #2776: fixed small issue when handling a URL with double slash
   after a 302 response in the case of not going through a proxy.
 
 - Issue #2676: in the email package, content-type parsing was hanging on
@@ -9955,7 +10362,7 @@ Core and builtins
   ``object.__reduce_ex__()`` is called with an object that is faking
   its type.
 
-- Patch #1680015: Don't modify __slots__ tuple if it contains an
+- Patch #1680015: Don't modify __slots__ tuple if it contains a
   unicode name.
 
 - Patch #1444529: the builtin compile() now accepts keyword arguments.
@@ -10277,7 +10684,7 @@ Library
 - Doctest now returns results as a named tuple for readability:
       (0, 7) --> TestResults(failed=0, attempted=7)
 
-- Issue #846388:q re.match is interruptible now, which is particularly
+- Issue #846388: re.match is interruptible now, which is particularly
   good for long regular expression matches.
 
 - Patch #1137: allow setting buffer_size attribute on pyexpat Parser
index d878424..3e603fc 100644 (file)
@@ -1053,7 +1053,7 @@ type(obj)           types.StringType: print 'It is a string'NB: it is
                     recommanded to use the following form:if isinstance(x,
                     types.StringType): etc...
 unichr(code)        code.
-unicode(string[,    Creates a Unicode string from a 8-bit string, using
+unicode(string[,    Creates a Unicode string from an 8-bit string, using
 encoding[, error    thegiven encoding name and error treatment ('strict',
 ]]])                'ignore',or 'replace'}.
                     Without arguments, returns a dictionary correspondingto the
index 054fbb5..eacbc8d 100644 (file)
@@ -1,4 +1,4 @@
-.TH PYTHON "1" "$Date$"
+.TH PYTHON "1"
 
 .\" To view this file while editing, run it through groff:
 .\"   groff -Tascii -man python.man | less
index 408efc3..ed17d39 100644 (file)
@@ -1607,9 +1607,8 @@ DB_associate(DBObject* self, PyObject* args, PyObject* kwargs)
     }
 
     /* Save a reference to the callback in the secondary DB. */
-    Py_XDECREF(secondaryDB->associateCallback);
     Py_XINCREF(callback);
-    secondaryDB->associateCallback = callback;
+    Py_XSETREF(secondaryDB->associateCallback, callback);
     secondaryDB->primaryDBType = _DB_get_type(self);
 
     /* PyEval_InitThreads is called here due to a quirk in python 1.5
@@ -2498,9 +2497,8 @@ static PyObject*
 DB_set_private(DBObject* self, PyObject* private_obj)
 {
     /* We can set the private field even if db is closed */
-    Py_DECREF(self->private_obj);
     Py_INCREF(private_obj);
-    self->private_obj = private_obj;
+    Py_SETREF(self->private_obj, private_obj);
     RETURN_NONE();
 }
 
@@ -3688,7 +3686,7 @@ _DB_has_key(DBObject* self, PyObject* keyobj, PyObject* txnobj)
     /*
     ** DB_BUFFER_SMALL is only used if we use "get".
     ** We can drop it when we only use "exists",
-    ** when we drop suport for Berkeley DB < 4.6.
+    ** when we drop support for Berkeley DB < 4.6.
     */
     if (err == DB_BUFFER_SMALL || err == 0) {
         Py_INCREF(Py_True);
@@ -6998,9 +6996,8 @@ static PyObject*
 DBEnv_set_private(DBEnvObject* self, PyObject* private_obj)
 {
     /* We can set the private field even if dbenv is closed */
-    Py_DECREF(self->private_obj);
     Py_INCREF(private_obj);
-    self->private_obj = private_obj;
+    Py_SETREF(self->private_obj, private_obj);
     RETURN_NONE();
 }
 
@@ -7253,9 +7250,8 @@ DBEnv_set_event_notify(DBEnvObject* self, PyObject* notifyFunc)
             return NULL;
     }
 
-    Py_XDECREF(self->event_notifyCallback);
     Py_INCREF(notifyFunc);
-    self->event_notifyCallback = notifyFunc;
+    Py_XSETREF(self->event_notifyCallback, notifyFunc);
 
     /* This is to workaround a problem with un-initialized threads (see
        comment in DB_associate) */
@@ -7413,9 +7409,8 @@ DBEnv_rep_set_transport(DBEnvObject* self, PyObject* args)
     MYDB_END_ALLOW_THREADS;
     RETURN_IF_ERR();
 
-    Py_DECREF(self->rep_transport);
     Py_INCREF(rep_transport);
-    self->rep_transport = rep_transport;
+    Py_SETREF(self->rep_transport, rep_transport);
     RETURN_NONE();
 }
 
index aaac660..1dd4b99 100644 (file)
@@ -3,8 +3,6 @@
 
 /* collections module implementation of a deque() datatype
    Written and maintained by Raymond D. Hettinger <python@rcn.com>
-   Copyright (c) 2004 Python Software Foundation.
-   All rights reserved.
 */
 
 /* The block length may be set to any number over 1.  Larger numbers
@@ -1103,7 +1101,7 @@ deque_sizeof(dequeobject *deque, void *unused)
     Py_ssize_t res;
     Py_ssize_t blocks;
 
-    res = sizeof(dequeobject);
+    res = _PyObject_SIZE(Py_TYPE(deque));
     blocks = (deque->leftindex + deque->len + BLOCKLEN - 1) / BLOCKLEN;
     assert(deque->leftindex + deque->len - 1 ==
            (blocks - 1) * BLOCKLEN + deque->rightindex);
index 884e051..af46658 100644 (file)
@@ -276,9 +276,8 @@ _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
             return -1;
         }
         else {
-            Py_XDECREF(*target);
             Py_INCREF(src);
-            *target = src;
+            Py_XSETREF(*target, src);
         }
     }
     return 0;
@@ -718,7 +717,7 @@ parse_process_char(ReaderObj *self, char c)
         break;
 
     case QUOTE_IN_QUOTED_FIELD:
-        /* doublequote - seen a quote in an quoted field */
+        /* doublequote - seen a quote in a quoted field */
         if (dialect->quoting != QUOTE_NONE &&
             c == dialect->quotechar) {
             /* save "" as " */
@@ -770,8 +769,7 @@ parse_process_char(ReaderObj *self, char c)
 static int
 parse_reset(ReaderObj *self)
 {
-    Py_XDECREF(self->fields);
-    self->fields = PyList_New(0);
+    Py_XSETREF(self->fields, PyList_New(0));
     if (self->fields == NULL)
         return -1;
     self->field_len = 0;
index 96ffa9d..86208e2 100644 (file)
@@ -1,5 +1,6 @@
 /*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
+  This file contains remnant Python 2.3 compatibility code that is no longer
+  strictly required.
  *****************************************************************/
 
 
@@ -54,7 +55,7 @@ from_address(addr)
 
 from_param(obj)
     - typecheck and convert a Python object into a C function call parameter
-      the result may be an instance of the type, or an integer or tuple
+      The result may be an instance of the type, or an integer or tuple
       (typecode, value[, obj])
 
 instance methods/properties
@@ -424,8 +425,7 @@ StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isSt
         Py_DECREF((PyObject *)dict);
         return NULL;
     }
-    Py_DECREF(result->tp_dict);
-    result->tp_dict = (PyObject *)dict;
+    Py_SETREF(result->tp_dict, (PyObject *)dict);
     dict->format = _ctypes_alloc_format_string(NULL, "B");
     if (dict->format == NULL) {
         Py_DECREF(result);
@@ -903,8 +903,7 @@ PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
         return -1;
     }
     Py_INCREF(proto);
-    Py_XDECREF(stgdict->proto);
-    stgdict->proto = proto;
+    Py_XSETREF(stgdict->proto, proto);
     return 0;
 }
 
@@ -994,8 +993,7 @@ PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         Py_DECREF((PyObject *)stgdict);
         return NULL;
     }
-    Py_DECREF(result->tp_dict);
-    result->tp_dict = (PyObject *)stgdict;
+    Py_SETREF(result->tp_dict, (PyObject *)stgdict);
 
     return (PyObject *)result;
 }
@@ -1460,8 +1458,7 @@ PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         Py_DECREF((PyObject *)stgdict);
         return NULL;
     }
-    Py_DECREF(result->tp_dict);
-    result->tp_dict = (PyObject *)stgdict;
+    Py_SETREF(result->tp_dict, (PyObject *)stgdict);
 
     /* Special case for character arrays.
        A permanent annoyance: char arrays are also strings!
@@ -1884,8 +1881,7 @@ static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject
         Py_DECREF((PyObject *)stgdict);
         return NULL;
     }
-    Py_DECREF(result->tp_dict);
-    result->tp_dict = (PyObject *)stgdict;
+    Py_SETREF(result->tp_dict, (PyObject *)stgdict);
 
     return (PyObject *)result;
 }
@@ -2393,8 +2389,7 @@ PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         Py_DECREF((PyObject *)stgdict);
         return NULL;
     }
-    Py_DECREF(result->tp_dict);
-    result->tp_dict = (PyObject *)stgdict;
+    Py_SETREF(result->tp_dict, (PyObject *)stgdict);
 
     if (-1 == make_funcptrtype_dict(stgdict)) {
         Py_DECREF(result);
@@ -2536,8 +2531,7 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
     }
     ob = PyCData_GetContainer(target);
     if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
-        Py_XDECREF(ob->b_objects);
-        ob->b_objects = keep; /* refcount consumed */
+        Py_XSETREF(ob->b_objects, keep); /* refcount consumed */
         return 0;
     }
     key = unique_key(target, index);
@@ -3059,9 +3053,8 @@ PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob)
                         "the errcheck attribute must be callable");
         return -1;
     }
-    Py_XDECREF(self->errcheck);
     Py_XINCREF(ob);
-    self->errcheck = ob;
+    Py_XSETREF(self->errcheck, ob);
     return 0;
 }
 
@@ -3089,11 +3082,9 @@ PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob)
                         "restype must be a type, a callable, or None");
         return -1;
     }
-    Py_XDECREF(self->checker);
-    Py_XDECREF(self->restype);
     Py_INCREF(ob);
-    self->restype = ob;
-    self->checker = PyObject_GetAttrString(ob, "_check_retval_");
+    Py_XSETREF(self->restype, ob);
+    Py_XSETREF(self->checker, PyObject_GetAttrString(ob, "_check_retval_"));
     if (self->checker == NULL)
         PyErr_Clear();
     return 0;
@@ -3130,11 +3121,9 @@ PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob)
         converters = converters_from_argtypes(ob);
         if (!converters)
             return -1;
-        Py_XDECREF(self->converters);
-        self->converters = converters;
-        Py_XDECREF(self->argtypes);
+        Py_XSETREF(self->converters, converters);
         Py_INCREF(ob);
-        self->argtypes = ob;
+        Py_XSETREF(self->argtypes, ob);
     }
     return 0;
 }
@@ -3509,7 +3498,7 @@ PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         return NULL;
     }
 
-    /* XXX XXX This would allow to pass additional options.  For COM
+    /* XXX XXX This would allow passing additional options.  For COM
        method *implementations*, we would probably want different
        behaviour than in 'normal' callback functions: return a HRESULT if
        an exception occurs in the callback, and print the traceback not
@@ -3911,7 +3900,7 @@ PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds)
             return NULL;
         }
         /* there should be more checks? No, in Python */
-        /* First arg is an pointer to an interface instance */
+        /* First arg is a pointer to an interface instance */
         if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
             PyErr_SetString(PyExc_ValueError,
                             "NULL COM pointer access");
index a52f650..57628b8 100644 (file)
@@ -1,12 +1,7 @@
-/*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
- *****************************************************************/
-
-
 #include <Python.h>
 
 /*
-  Backwards compatibility:
+  Backwards compatibility, no longer strictly required:
   Python2.2 used LONG_LONG instead of PY_LONG_LONG
 */
 #if defined(HAVE_LONG_LONG) && !defined(PY_LONG_LONG)
index 47dbe05..b1e85ce 100644 (file)
@@ -1,5 +1,6 @@
 /*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
+  This file contains remnant Python 2.3 compatibility code that is no longer
+  strictly required.
  *****************************************************************/
 
 #include "Python.h"
index 7007b7c..280a315 100644 (file)
@@ -1,5 +1,6 @@
 /*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
+  This file contains remnant Python 2.3 compatibility code that is no longer
+  strictly required.
  *****************************************************************/
 
 
index 85b5ad2..0585ed2 100644 (file)
@@ -1,5 +1,6 @@
 /*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
+  This file contains remnant Python 2.3 compatibility code that is no longer
+  strictly required.
  *****************************************************************/
 
 #include "Python.h"
index b88cf4f..a61ce5f 100644 (file)
@@ -1,5 +1,6 @@
 /*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
+  This file contains remnant Python 2.3 compatibility code that is no longer
+  strictly required.
  *****************************************************************/
 
 #if defined (__SVR4) && defined (__sun)
index d8bf904..54cdde9 100644 (file)
@@ -1,7 +1,3 @@
-/*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
- *****************************************************************/
-
 #ifndef _CTYPES_DLFCN_H_
 #define _CTYPES_DLFCN_H_
 
index 4bc6b22..d9cc77b 100644 (file)
@@ -1121,7 +1121,7 @@ m4_defun([_LT_DARWIN_LINKER_FEATURES],
 # If we don't find anything, use the default library path according
 # to the aix ld manual.
 # Store the results from the different compilers for each TAGNAME.
-# Allow to override them for all tags through lt_cv_aix_libpath.
+# Allow overriding them for all tags through lt_cv_aix_libpath.
 m4_defun([_LT_SYS_MODULE_PATH_AIX],
 [m4_require([_LT_DECL_SED])dnl
 if test set = "${lt_cv_aix_libpath+set}"; then
index b98d43b..248c6a6 100644 (file)
@@ -1,7 +1,3 @@
-/*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
- *****************************************************************/
-
 #include <Python.h>
 #include <ffi.h>
 #ifdef MS_WIN32
index 17b9760..31528af 100644 (file)
@@ -1,7 +1,3 @@
-/*****************************************************************
-  This file should be kept compatible with Python 2.3, see PEP 291.
- *****************************************************************/
-
 #include "Python.h"
 #include <ffi.h>
 #ifdef MS_WIN32
@@ -449,6 +445,7 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
             Py_DECREF(pair);
             PyErr_Format(PyExc_TypeError,
 #if (PY_VERSION_HEX < 0x02050000)
+                         /* Compatibility no longer strictly required */
                          "second item in _fields_ tuple (index %d) must be a C type",
 #else
                          "second item in _fields_ tuple (index %zd) must be a C type",
index bdd5cf0..bc89447 100644 (file)
@@ -191,6 +191,11 @@ PyCursesPanel_New(PANEL *pan, PyCursesWindowObject *wo)
 static void
 PyCursesPanel_Dealloc(PyCursesPanelObject *po)
 {
+    PyObject *obj = (PyObject *) panel_userptr(po->pan);
+    if (obj) {
+        (void)set_panel_userptr(po->pan, NULL);
+        Py_DECREF(obj);
+    }
     (void)del_panel(po->pan);
     if (po->wo != NULL) {
         Py_DECREF(po->wo);
@@ -283,9 +288,8 @@ PyCursesPanel_replace_panel(PyCursesPanelObject *self, PyObject *args)
         PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
         return NULL;
     }
-    Py_DECREF(po->wo);
-    po->wo = temp;
-    Py_INCREF(po->wo);
+    Py_INCREF(temp);
+    Py_SETREF(po->wo, temp);
     Py_INCREF(Py_None);
     return Py_None;
 }
index 837164c..6f628a5 100644 (file)
@@ -337,9 +337,9 @@ element_new(PyObject* tag, PyObject* attrib)
 }
 
 LOCAL(int)
-element_resize(ElementObject* self, int extra)
+element_resize(ElementObject* self, Py_ssize_t extra)
 {
-    int size;
+    Py_ssize_t size;
     PyObject* *children;
 
     /* make sure self->children can hold the given number of extra
@@ -359,6 +359,13 @@ element_resize(ElementObject* self, int extra)
          * be safe.
          */
         size = size ? size : 1;
+        if ((size_t)size > PY_SSIZE_T_MAX/sizeof(PyObject*))
+            goto nomemory;
+        if (size > INT_MAX) {
+            PyErr_SetString(PyExc_OverflowError,
+                            "too many children");
+            return -1;
+        }
         if (self->extra->children != self->extra->_children) {
             /* Coverity CID #182 size_error: Allocating 1 bytes to pointer
              * "children", which needs at least 4 bytes. Although it's a 
@@ -1253,18 +1260,19 @@ element_set(ElementObject* self, PyObject* args)
 }
 
 static int
-element_setitem(PyObject* self_, Py_ssize_t index, PyObject* item)
+element_setitem(PyObject* self_, Py_ssize_t index_, PyObject* item)
 {
     ElementObject* self = (ElementObject*) self_;
-    int i;
+    int i, index;
     PyObject* old;
 
-    if (!self->extra || index < 0 || index >= self->extra->length) {
+    if (!self->extra || index_ < 0 || index_ >= self->extra->length) {
         PyErr_SetString(
             PyExc_IndexError,
             "child assignment index out of range");
         return -1;
     }
+    index = (int)index_;
 
     old = self->extra->children[index];
 
@@ -1373,6 +1381,7 @@ element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
                 &start, &stop, &step, &slicelen) < 0) {
             return -1;
         }
+        assert(slicelen <= self->extra->length);
 
         if (value == NULL)
             newlen = 0;
@@ -1390,15 +1399,17 @@ element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
 
         if (step !=  1 && newlen != slicelen)
         {
+            Py_XDECREF(seq);
             PyErr_Format(PyExc_ValueError,
 #if (PY_VERSION_HEX < 0x02050000)
                 "attempt to assign sequence of size %d "
                 "to extended slice of size %d",
+                (int)newlen, (int)slicelen
 #else
                 "attempt to assign sequence of size %zd "
                 "to extended slice of size %zd",
-#endif
                 newlen, slicelen
+#endif
                 );
             return -1;
         }
@@ -1407,12 +1418,12 @@ element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
         /* Resize before creating the recycle bin, to prevent refleaks. */
         if (newlen > slicelen) {
             if (element_resize(self, newlen - slicelen) < 0) {
-                if (seq) {
-                    Py_DECREF(seq);
-                }
+                Py_XDECREF(seq);
                 return -1;
             }
         }
+        assert(newlen - slicelen <= INT_MAX - self->extra->length);
+        assert(newlen - slicelen >= -self->extra->length);
 
         if (slicelen > 0) {
             /* to avoid recursive calls to this method (via decref), move
@@ -1420,9 +1431,7 @@ element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
                we're done modifying the element */
             recycle = PyList_New(slicelen);
             if (!recycle) {
-                if (seq) {
-                    Py_DECREF(seq);
-                }
+                Py_XDECREF(seq);
                 return -1;
             }
             for (cur = start, i = 0; i < slicelen;
@@ -1448,11 +1457,9 @@ element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
             self->extra->children[cur] = element;
         }
 
-        self->extra->length += newlen - slicelen;
+        self->extra->length += (int)(newlen - slicelen);
 
-        if (seq) {
-            Py_DECREF(seq);
-        }
+        Py_XDECREF(seq);
 
         /* discard the recycle bin, and everything in it */
         Py_XDECREF(recycle);
@@ -1566,9 +1573,8 @@ element_setattr(ElementObject* self, const char* name, PyObject* value)
     }
 
     if (strcmp(name, "tag") == 0) {
-        Py_DECREF(self->tag);
-        self->tag = value;
-        Py_INCREF(self->tag);
+        Py_INCREF(value);
+        Py_SETREF(self->tag, value);
     } else if (strcmp(name, "text") == 0) {
         Py_DECREF(JOIN_OBJ(self->text));
         self->text = value;
@@ -1580,9 +1586,8 @@ element_setattr(ElementObject* self, const char* name, PyObject* value)
     } else if (strcmp(name, "attrib") == 0) {
         if (!self->extra)
             element_new_extra(self, NULL);
-        Py_DECREF(self->extra->attrib);
-        self->extra->attrib = value;
-        Py_INCREF(self->extra->attrib);
+        Py_INCREF(value);
+        Py_SETREF(self->extra->attrib, value);
     } else {
         PyErr_SetString(PyExc_AttributeError, name);
         return -1;
@@ -1713,6 +1718,23 @@ treebuilder_dealloc(TreeBuilderObject* self)
     PyObject_Del(self);
 }
 
+LOCAL(int)
+treebuilder_append_event(TreeBuilderObject *self, PyObject *action,
+                         PyObject *node)
+{
+    if (action != NULL) {
+        PyObject *res = PyTuple_Pack(2, action, node);
+        if (res == NULL)
+            return -1;
+        if (PyList_Append(self->events, res) < 0) {
+            Py_DECREF(res);
+            return -1;
+        }
+        Py_DECREF(res);
+    }
+    return 0;
+}
+
 /* -------------------------------------------------------------------- */
 /* handlers */
 
@@ -1776,26 +1798,14 @@ treebuilder_handle_start(TreeBuilderObject* self, PyObject* tag,
     }
     self->index++;
 
-    Py_DECREF(this);
     Py_INCREF(node);
-    self->this = (ElementObject*) node;
+    Py_SETREF(self->this, (ElementObject*) node);
 
-    Py_DECREF(self->last);
     Py_INCREF(node);
-    self->last = (ElementObject*) node;
-
-    if (self->start_event_obj) {
-        PyObject* res;
-        PyObject* action = self->start_event_obj;
-        res = PyTuple_New(2);
-        if (res) {
-            Py_INCREF(action); PyTuple_SET_ITEM(res, 0, (PyObject*) action);
-            Py_INCREF(node);   PyTuple_SET_ITEM(res, 1, (PyObject*) node);
-            PyList_Append(self->events, res);
-            Py_DECREF(res);
-        } else
-            PyErr_Clear(); /* FIXME: propagate error */
-    }
+    Py_SETREF(self->last, (ElementObject*) node);
+
+    if (treebuilder_append_event(self, self->start_event_obj, node) < 0)
+        goto error;
 
     return node;
 
@@ -1843,7 +1853,7 @@ treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
 LOCAL(PyObject*)
 treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag)
 {
-    PyObject* item;
+    ElementObject *item;
 
     if (self->data) {
         if (self->this == self->last) {
@@ -1868,73 +1878,20 @@ treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag)
         return NULL;
     }
 
+    item = self->last;
+    self->last = self->this;
     self->index--;
+    self->this = (ElementObject *) PyList_GET_ITEM(self->stack, self->index);
+    Py_INCREF(self->this);
+    Py_DECREF(item);
 
-    item = PyList_GET_ITEM(self->stack, self->index);
-    Py_INCREF(item);
-
-    Py_DECREF(self->last);
-
-    self->last = (ElementObject*) self->this;
-    self->this = (ElementObject*) item;
-
-    if (self->end_event_obj) {
-        PyObject* res;
-        PyObject* action = self->end_event_obj;
-        PyObject* node = (PyObject*) self->last;
-        res = PyTuple_New(2);
-        if (res) {
-            Py_INCREF(action); PyTuple_SET_ITEM(res, 0, (PyObject*) action);
-            Py_INCREF(node);   PyTuple_SET_ITEM(res, 1, (PyObject*) node);
-            PyList_Append(self->events, res);
-            Py_DECREF(res);
-        } else
-            PyErr_Clear(); /* FIXME: propagate error */
-    }
+    if (treebuilder_append_event(self, self->end_event_obj, (PyObject*)self->last) < 0)
+        return NULL;
 
     Py_INCREF(self->last);
     return (PyObject*) self->last;
 }
 
-LOCAL(void)
-treebuilder_handle_namespace(TreeBuilderObject* self, int start,
-                             PyObject *prefix, PyObject *uri)
-{
-    PyObject* res;
-    PyObject* action;
-    PyObject* parcel;
-
-    if (!self->events)
-        return;
-
-    if (start) {
-        if (!self->start_ns_event_obj)
-            return;
-        action = self->start_ns_event_obj;
-        parcel = Py_BuildValue("OO", prefix, uri);
-        if (!parcel)
-            return;
-        Py_INCREF(action);
-    } else {
-        if (!self->end_ns_event_obj)
-            return;
-        action = self->end_ns_event_obj;
-        Py_INCREF(action);
-        parcel = Py_None;
-        Py_INCREF(parcel);
-    }
-
-    res = PyTuple_New(2);
-
-    if (res) {
-        PyTuple_SET_ITEM(res, 0, action);
-        PyTuple_SET_ITEM(res, 1, parcel);
-        PyList_Append(self->events, res);
-        Py_DECREF(res);
-    } else
-        PyErr_Clear(); /* FIXME: propagate error */
-}
-
 /* -------------------------------------------------------------------- */
 /* methods (in alphabetical order) */
 
@@ -2147,7 +2104,7 @@ makeuniversal(XMLParserObject* self, const char* string)
         /* decode universal name */
 #if defined(Py_USING_UNICODE)
         /* inline makestring, to avoid duplicating the source string if
-           it's not an utf-8 string */
+           it's not a utf-8 string */
         p = PyString_AS_STRING(tag);
         if (checkstring(p, size)) {
             value = PyUnicode_DecodeUTF8(p, size, "strict");
@@ -2263,8 +2220,10 @@ expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
     /* attributes */
     if (attrib_in[0]) {
         attrib = PyDict_New();
-        if (!attrib)
+        if (!attrib) {
+            Py_DECREF(tag);
             return;
+        }
         while (attrib_in[0] && attrib_in[1]) {
             PyObject* key = makeuniversal(self, attrib_in[0]);
             PyObject* value = makestring(attrib_in[1], strlen(attrib_in[1]));
@@ -2272,6 +2231,7 @@ expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
                 Py_XDECREF(value);
                 Py_XDECREF(key);
                 Py_DECREF(attrib);
+                Py_DECREF(tag);
                 return;
             }
             ok = PyDict_SetItem(attrib, key, value);
@@ -2279,6 +2239,7 @@ expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
             Py_DECREF(key);
             if (ok < 0) {
                 Py_DECREF(attrib);
+                Py_DECREF(tag);
                 return;
             }
             attrib_in += 2;
@@ -2296,8 +2257,10 @@ expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
         if (attrib == Py_None) {
             Py_DECREF(attrib);
             attrib = PyDict_New();
-            if (!attrib)
+            if (!attrib) {
+                Py_DECREF(tag);
                 return;
+            }
         }
         res = PyObject_CallFunction(self->handle_start, "OO", tag, attrib);
     } else
@@ -2360,8 +2323,16 @@ static void
 expat_start_ns_handler(XMLParserObject* self, const XML_Char* prefix,
                        const XML_Char *uri)
 {
-    PyObject* sprefix = NULL;
-    PyObject* suri = NULL;
+    TreeBuilderObject *target = (TreeBuilderObject*) self->target;
+    PyObject *parcel;
+    PyObject *sprefix = NULL;
+    PyObject *suri = NULL;
+
+    if (PyErr_Occurred())
+        return;
+
+    if (!target->events || !target->start_ns_event_obj)
+        return;
 
     if (uri)
         suri = makestring(uri, strlen(uri));
@@ -2379,20 +2350,27 @@ expat_start_ns_handler(XMLParserObject* self, const XML_Char* prefix,
         return;
     }
 
-    treebuilder_handle_namespace(
-        (TreeBuilderObject*) self->target, 1, sprefix, suri
-        );
-
+    parcel = PyTuple_Pack(2, sprefix, suri);
     Py_DECREF(sprefix);
     Py_DECREF(suri);
+    if (!parcel)
+        return;
+    treebuilder_append_event(target, target->start_ns_event_obj, parcel);
+    Py_DECREF(parcel);
 }
 
 static void
 expat_end_ns_handler(XMLParserObject* self, const XML_Char* prefix_in)
 {
-    treebuilder_handle_namespace(
-        (TreeBuilderObject*) self->target, 0, NULL, NULL
-        );
+    TreeBuilderObject *target = (TreeBuilderObject*) self->target;
+
+    if (PyErr_Occurred())
+        return;
+
+    if (!target->events)
+        return;
+
+    treebuilder_append_event(target, target->end_ns_event_obj, Py_None);
 }
 
 static void
@@ -2708,8 +2686,14 @@ xmlparser_parse(XMLParserObject* self, PyObject* args)
             break;
         }
 
+        if (PyString_GET_SIZE(buffer) > INT_MAX) {
+            Py_DECREF(buffer);
+            Py_DECREF(reader);
+            PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
+            return NULL;
+        }
         res = expat_parse(
-            self, PyString_AS_STRING(buffer), PyString_GET_SIZE(buffer), 0
+            self, PyString_AS_STRING(buffer), (int)PyString_GET_SIZE(buffer), 0
             );
 
         Py_DECREF(buffer);
@@ -2760,8 +2744,7 @@ xmlparser_setevents(XMLParserObject* self, PyObject* args)
     target = (TreeBuilderObject*) self->target;
 
     Py_INCREF(events);
-    Py_XDECREF(target->events);
-    target->events = events;
+    Py_XSETREF(target->events, events);
 
     /* clear out existing events */
     Py_CLEAR(target->start_event_obj);
@@ -2783,33 +2766,28 @@ xmlparser_setevents(XMLParserObject* self, PyObject* args)
         char* event;
         if (!PyString_Check(item))
             goto error;
+        Py_INCREF(item);
         event = PyString_AS_STRING(item);
         if (strcmp(event, "start") == 0) {
-            Py_INCREF(item);
-            target->start_event_obj = item;
+            Py_XSETREF(target->start_event_obj, item);
         } else if (strcmp(event, "end") == 0) {
-            Py_INCREF(item);
-            Py_XDECREF(target->end_event_obj);
-            target->end_event_obj = item;
+            Py_XSETREF(target->end_event_obj, item);
         } else if (strcmp(event, "start-ns") == 0) {
-            Py_INCREF(item);
-            Py_XDECREF(target->start_ns_event_obj);
-            target->start_ns_event_obj = item;
+            Py_XSETREF(target->start_ns_event_obj, item);
             EXPAT(SetNamespaceDeclHandler)(
                 self->parser,
                 (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
                 (XML_EndNamespaceDeclHandler) expat_end_ns_handler
                 );
         } else if (strcmp(event, "end-ns") == 0) {
-            Py_INCREF(item);
-            Py_XDECREF(target->end_ns_event_obj);
-            target->end_ns_event_obj = item;
+            Py_XSETREF(target->end_ns_event_obj, item);
             EXPAT(SetNamespaceDeclHandler)(
                 self->parser,
                 (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
                 (XML_EndNamespaceDeclHandler) expat_end_ns_handler
                 );
         } else {
+            Py_DECREF(item);
             PyErr_Format(
                 PyExc_ValueError,
                 "unknown event '%s'", event
index 2ba92ba..e0781a9 100644 (file)
@@ -128,7 +128,6 @@ partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
     Py_INCREF(func);
     pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
     if (pto->args == NULL) {
-        pto->kw = NULL;
         Py_DECREF(pto);
         return NULL;
     }
@@ -138,10 +137,6 @@ partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
         return NULL;
     }
 
-
-    pto->weakreflist = NULL;
-    pto->dict = NULL;
-
     return (PyObject *)pto;
 }
 
@@ -162,11 +157,11 @@ static PyObject *
 partial_call(partialobject *pto, PyObject *args, PyObject *kw)
 {
     PyObject *ret;
-    PyObject *argappl = NULL, *kwappl = NULL;
+    PyObject *argappl, *kwappl;
 
     assert (PyCallable_Check(pto->fn));
     assert (PyTuple_Check(pto->args));
-    assert (pto->kw == Py_None  ||  PyDict_Check(pto->kw));
+    assert (PyDict_Check(pto->kw));
 
     if (PyTuple_GET_SIZE(pto->args) == 0) {
         argappl = args;
@@ -178,11 +173,12 @@ partial_call(partialobject *pto, PyObject *args, PyObject *kw)
         argappl = PySequence_Concat(pto->args, args);
         if (argappl == NULL)
             return NULL;
+        assert(PyTuple_Check(argappl));
     }
 
-    if (pto->kw == Py_None) {
+    if (PyDict_Size(pto->kw) == 0) {
         kwappl = kw;
-        Py_XINCREF(kw);
+        Py_XINCREF(kwappl);
     } else {
         kwappl = PyDict_Copy(pto->kw);
         if (kwappl == NULL) {
@@ -289,25 +285,45 @@ PyObject *
 partial_setstate(partialobject *pto, PyObject *state)
 {
     PyObject *fn, *fnargs, *kw, *dict;
-    if (!PyArg_ParseTuple(state, "OOOO",
-                          &fn, &fnargs, &kw, &dict))
+
+    if (!PyTuple_Check(state) ||
+        !PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) ||
+        !PyCallable_Check(fn) ||
+        !PyTuple_Check(fnargs) ||
+        (kw != Py_None && !PyDict_Check(kw)))
+    {
+        PyErr_SetString(PyExc_TypeError, "invalid partial state");
         return NULL;
-    Py_XDECREF(pto->fn);
-    Py_XDECREF(pto->args);
-    Py_XDECREF(pto->kw);
-    Py_XDECREF(pto->dict);
-    pto->fn = fn;
-    pto->args = fnargs;
-    pto->kw = kw;
-    if (dict != Py_None) {
-      pto->dict = dict;
-      Py_INCREF(dict);
-    } else {
-      pto->dict = NULL;
     }
+
+    if(!PyTuple_CheckExact(fnargs))
+        fnargs = PySequence_Tuple(fnargs);
+    else
+        Py_INCREF(fnargs);
+    if (fnargs == NULL)
+        return NULL;
+
+    if (kw == Py_None)
+        kw = PyDict_New();
+    else if(!PyDict_CheckExact(kw))
+        kw = PyDict_Copy(kw);
+    else
+        Py_INCREF(kw);
+    if (kw == NULL) {
+        Py_DECREF(fnargs);
+        return NULL;
+    }
+
     Py_INCREF(fn);
-    Py_INCREF(fnargs);
-    Py_INCREF(kw);
+    if (dict == Py_None)
+        dict = NULL;
+    else
+        Py_INCREF(dict);
+
+    Py_SETREF(pto->fn, fn);
+    Py_SETREF(pto->args, fnargs);
+    Py_SETREF(pto->kw, kw);
+    Py_XSETREF(pto->dict, dict);
     Py_RETURN_NONE;
 }
 
index be301a6..5b0ef69 100644 (file)
@@ -619,7 +619,7 @@ representation for a tournament.  The numbers below are `k', not a[k]:\n\
 \n\
 \n\
 In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'.  In\n\
-an usual binary tournament we see in sports, each cell is the winner\n\
+a usual binary tournament we see in sports, each cell is the winner\n\
 over the two cells it tops, and we can trace the winner down the tree\n\
 to see all opponents s/he had.  However, in many computer applications\n\
 of such tournaments, we do not need to trace the history of a winner.\n\
index b4632ed..5bef746 100644 (file)
@@ -125,8 +125,7 @@ bufferediobase_read1(PyObject *self, PyObject *args)
 PyDoc_STRVAR(bufferediobase_write_doc,
     "Write the given buffer to the IO stream.\n"
     "\n"
-    "Returns the number of bytes written, which is never less than\n"
-    "len(b).\n"
+    "Returns the number of bytes written, which is always len(b).\n"
     "\n"
     "Raises BlockingIOError if the buffer is full and the\n"
     "underlying raw stream cannot accept more data at the moment.\n");
@@ -391,7 +390,7 @@ buffered_sizeof(buffered *self, void *unused)
 {
     Py_ssize_t res;
 
-    res = sizeof(buffered);
+    res = _PyObject_SIZE(Py_TYPE(self));
     if (self->buffer)
         res += self->buffer_size;
     return PyLong_FromSsize_t(res);
@@ -1028,8 +1027,7 @@ found:
         Py_CLEAR(res);
         goto end;
     }
-    Py_CLEAR(res);
-    res = _PyBytes_Join(_PyIO_empty_bytes, chunks);
+    Py_XSETREF(res, _PyBytes_Join(_PyIO_empty_bytes, chunks));
 
 end:
     LEAVE_BUFFERED(self)
@@ -1264,9 +1262,8 @@ bufferedreader_init(buffered *self, PyObject *args, PyObject *kwds)
     if (_PyIOBase_check_readable(raw, Py_True) == NULL)
         return -1;
 
-    Py_CLEAR(self->raw);
     Py_INCREF(raw);
-    self->raw = raw;
+    Py_XSETREF(self->raw, raw);
     self->buffer_size = buffer_size;
     self->readable = 1;
     self->writable = 0;
@@ -1687,9 +1684,8 @@ bufferedwriter_init(buffered *self, PyObject *args, PyObject *kwds)
     if (_PyIOBase_check_writable(raw, Py_True) == NULL)
         return -1;
 
-    Py_CLEAR(self->raw);
     Py_INCREF(raw);
-    self->raw = raw;
+    Py_XSETREF(self->raw, raw);
     self->readable = 0;
     self->writable = 1;
 
@@ -2344,9 +2340,8 @@ bufferedrandom_init(buffered *self, PyObject *args, PyObject *kwds)
     if (_PyIOBase_check_writable(raw, Py_True) == NULL)
         return -1;
 
-    Py_CLEAR(self->raw);
     Py_INCREF(raw);
-    self->raw = raw;
+    Py_XSETREF(self->raw, raw);
     self->buffer_size = buffer_size;
     self->readable = 1;
     self->writable = 1;
index f643e91..1335ae8 100644 (file)
@@ -392,10 +392,10 @@ bytesio_readlines(bytesio *self, PyObject *args)
 }
 
 PyDoc_STRVAR(readinto_doc,
-"readinto(bytearray) -> int.  Read up to len(b) bytes into b.\n"
+"readinto(b) -> int.  Read up to len(b) bytes into b.\n"
 "\n"
 "Returns number of bytes read (0 for EOF), or None if the object\n"
-"is set not to block as has no data to read.");
+"is set not to block and has no data to read.");
 
 static PyObject *
 bytesio_readinto(bytesio *self, PyObject *args)
@@ -809,7 +809,7 @@ bytesio_sizeof(bytesio *self, void *unused)
 {
     Py_ssize_t res;
 
-    res = sizeof(bytesio);
+    res = _PyObject_SIZE(Py_TYPE(self));
     if (self->buf)
         res += self->buf_size;
     return PyLong_FromSsize_t(res);
index 098aef4..74b2305 100644 (file)
@@ -969,7 +969,7 @@ PyDoc_STRVAR(readall_doc,
 "or None if no data is available.  On end-of-file, returns ''.");
 
 PyDoc_STRVAR(write_doc,
-"write(b: bytes) -> int.  Write bytes b to file, return number written.\n"
+"write(b) -> int.  Write array of bytes b, return number written.\n"
 "\n"
 "Only makes one system call, so not all of the data may be written.\n"
 "The number of bytes actually written is returned.  In non-blocking mode,\n"
index ab6911d..710ada4 100644 (file)
@@ -38,8 +38,10 @@ PyDoc_STRVAR(iobase_doc,
     "may raise a IOError when operations they do not support are called.\n"
     "\n"
     "The basic type used for binary data read from or written to a file is\n"
-    "bytes. bytearrays are accepted too, and in some cases (such as\n"
-    "readinto) needed. Text I/O classes work with str data.\n"
+    "the bytes type. Method arguments may also be bytearray or memoryview\n"
+    "of arrays of bytes. In some cases, such as readinto, a writable\n"
+    "object such as bytearray is required. Text I/O classes work with\n"
+    "unicode data.\n"
     "\n"
     "Note that calling any method (except additional calls to close(),\n"
     "which are ignored) on a closed stream should raise a ValueError.\n"
@@ -529,7 +531,10 @@ iobase_readline(PyObject *self, PyObject *args)
         }
 
         old_size = PyByteArray_GET_SIZE(buffer);
-        PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
+        if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
+            Py_DECREF(b);
+            goto fail;
+        }
         memcpy(PyByteArray_AS_STRING(buffer) + old_size,
                PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
 
index 59a3905..83bb7ac 100644 (file)
@@ -736,8 +736,8 @@ stringio_setstate(stringio *self, PyObject *state)
     Py_DECREF(initarg);
 
     /* Restore the buffer state. Even if __init__ did initialize the buffer,
-       we have to initialize it again since __init__ may translates the
-       newlines in the inital_value string. We clearly do not want that
+       we have to initialize it again since __init__ may translate the
+       newlines in the initial_value string. We clearly do not want that
        because the string value in the state tuple has already been translated
        once by __init__. So we do not take any chance and replace object's
        buffer completely. */
index 9981d4c..38bb0d8 100644 (file)
@@ -966,8 +966,7 @@ textiowrapper_init(textio *self, PyObject *args, PyObject *kwds)
                 "Oi", self->decoder, (int)self->readtranslate);
             if (incrementalDecoder == NULL)
                 goto error;
-            Py_CLEAR(self->decoder);
-            self->decoder = incrementalDecoder;
+            Py_XSETREF(self->decoder, incrementalDecoder);
         }
     }
 
@@ -1347,8 +1346,7 @@ textiowrapper_write(textio *self, PyObject *args)
 static void
 textiowrapper_set_decoded_chars(textio *self, PyObject *chars)
 {
-    Py_CLEAR(self->decoded_chars);
-    self->decoded_chars = chars;
+    Py_XSETREF(self->decoded_chars, chars);
     self->decoded_chars_used = 0;
 }
 
@@ -1477,8 +1475,7 @@ textiowrapper_read_chunk(textio *self)
             goto fail;
         }
         Py_DECREF(dec_buffer);
-        Py_CLEAR(self->snapshot);
-        self->snapshot = Py_BuildValue("NN", dec_flags, next_input);
+        Py_XSETREF(self->snapshot, Py_BuildValue("NN", dec_flags, next_input));
     }
     Py_DECREF(input_chunk);
 
@@ -1578,8 +1575,7 @@ textiowrapper_read(textio *self, PyObject *args)
         if (chunks != NULL) {
             if (result != NULL && PyList_Append(chunks, result) < 0)
                 goto fail;
-            Py_CLEAR(result);
-            result = PyUnicode_Join(_PyIO_empty_str, chunks);
+            Py_XSETREF(result, PyUnicode_Join(_PyIO_empty_str, chunks));
             if (result == NULL)
                 goto fail;
             Py_CLEAR(chunks);
@@ -1836,8 +1832,7 @@ _textiowrapper_readline(textio *self, Py_ssize_t limit)
     if (chunks != NULL) {
         if (line != NULL && PyList_Append(chunks, line) < 0)
             goto error;
-        Py_CLEAR(line);
-        line = PyUnicode_Join(_PyIO_empty_str, chunks);
+        Py_XSETREF(line, PyUnicode_Join(_PyIO_empty_str, chunks));
         if (line == NULL)
             goto error;
         Py_DECREF(chunks);
index 5dac038..fede6b1 100644 (file)
@@ -1717,8 +1717,7 @@ scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
     }
     else if (PyUnicode_Check(s->encoding)) {
         PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
-        Py_DECREF(s->encoding);
-        s->encoding = tmp;
+        Py_SETREF(s->encoding, tmp);
     }
     if (s->encoding == NULL)
         goto bail;
index b9e8f34..fc42754 100644 (file)
@@ -429,7 +429,7 @@ semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     int kind, maxvalue, value;
     PyObject *result;
     static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
-    static int counter = 0;
+    int try = 0;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
                                      &kind, &value, &maxvalue))
@@ -440,10 +440,18 @@ semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         return NULL;
     }
 
-    PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%d", (long)getpid(), counter++);
+    /* Create a semaphore with a unique name. The bytes returned by
+     * _PyOS_URandom() are treated as unsigned long to ensure that the filename
+     * is valid (no special characters). */
+    do {
+        unsigned long suffix;
+        _PyOS_URandom((char *)&suffix, sizeof(suffix));
+        PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%lu", (long)getpid(),
+                      suffix);
+        SEM_CLEAR_ERROR();
+        handle = SEM_CREATE(buffer, value, maxvalue);
+    } while ((handle == SEM_FAILED) && (errno == EEXIST) && (++try < 100));
 
-    SEM_CLEAR_ERROR();
-    handle = SEM_CREATE(buffer, value, maxvalue);
     /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
     if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
         goto failure;
index 79a7a00..6b0e3c6 100644 (file)
@@ -228,8 +228,8 @@ void pysqlite_flush_statement_cache(pysqlite_Connection* self)
         node = node->next;
     }
 
-    Py_DECREF(self->statement_cache);
-    self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
+    Py_SETREF(self->statement_cache,
+              (pysqlite_Cache *)PyObject_CallFunction((PyObject *)&pysqlite_CacheType, "O", self));
     Py_DECREF(self);
     self->statement_cache->decref_factory = 0;
 }
@@ -346,9 +346,8 @@ PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args,
     _pysqlite_drop_unused_cursor_references(self);
 
     if (cursor && self->row_factory != Py_None) {
-        Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
         Py_INCREF(self->row_factory);
-        ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
+        Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
     }
 
     return cursor;
@@ -816,8 +815,7 @@ static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self
         }
     }
 
-    Py_DECREF(self->statements);
-    self->statements = new_list;
+    Py_SETREF(self->statements, new_list);
 }
 
 static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
@@ -848,8 +846,7 @@ static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
         }
     }
 
-    Py_DECREF(self->cursors);
-    self->cursors = new_list;
+    Py_SETREF(self->cursors, new_list);
 }
 
 PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
index 3b84484..f2b48ff 100644 (file)
@@ -172,8 +172,7 @@ int pysqlite_build_row_cast_map(pysqlite_Cursor* self)
         return 0;
     }
 
-    Py_XDECREF(self->row_cast_map);
-    self->row_cast_map = PyList_New(0);
+    Py_XSETREF(self->row_cast_map, PyList_New(0));
 
     for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
         converter = NULL;
@@ -544,9 +543,8 @@ PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject*
     }
 
     /* reset description and rowcount */
-    Py_DECREF(self->description);
     Py_INCREF(Py_None);
-    self->description = Py_None;
+    Py_SETREF(self->description, Py_None);
     self->rowcount = -1L;
 
     func_args = PyTuple_New(1);
@@ -560,10 +558,10 @@ PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject*
 
     if (self->statement) {
         (void)pysqlite_statement_reset(self->statement);
-        Py_DECREF(self->statement);
     }
 
-    self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args);
+    Py_XSETREF(self->statement,
+              (pysqlite_Statement *)pysqlite_cache_get(self->connection->statement_cache, func_args));
     Py_DECREF(func_args);
 
     if (!self->statement) {
@@ -571,8 +569,8 @@ PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject*
     }
 
     if (self->statement->in_use) {
-        Py_DECREF(self->statement);
-        self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
+        Py_SETREF(self->statement,
+                  PyObject_New(pysqlite_Statement, &pysqlite_StatementType));
         if (!self->statement) {
             goto error;
         }
@@ -683,8 +681,7 @@ PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject*
                 numcols = sqlite3_column_count(self->statement->st);
                 Py_END_ALLOW_THREADS
 
-                Py_DECREF(self->description);
-                self->description = PyTuple_New(numcols);
+                Py_SETREF(self->description, PyTuple_New(numcols));
                 if (!self->description) {
                     goto error;
                 }
index 8ef8c2c..829fb6b 100644 (file)
@@ -2054,8 +2054,7 @@ deepcopy(PyObject** object, PyObject* memo)
     if (!copy)
         return 0;
 
-    Py_DECREF(*object);
-    *object = copy;
+    Py_SETREF(*object, copy);
 
     return 1; /* success */
 }
index 89f2aaa..f291352 100644 (file)
@@ -1467,8 +1467,7 @@ static int PySSL_set_context(PySSLSocket *self, PyObject *value,
         return -1;
 #else
         Py_INCREF(value);
-        Py_DECREF(self->ctx);
-        self->ctx = (PySSLContext *) value;
+        Py_SETREF(self->ctx, (PySSLContext *)value);
         SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
 #endif
     } else {
@@ -1696,6 +1695,10 @@ static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
         goto error;
 
     if ((buf.buf == NULL) && (buf.obj == NULL)) {
+        if (len < 0) {
+            PyErr_SetString(PyExc_ValueError, "size should not be negative");
+            goto error;
+        }
         dest = PyBytes_FromStringAndSize(NULL, len);
         if (dest == NULL)
             goto error;
@@ -2610,7 +2613,9 @@ load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
     }
     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
+    Py_XDECREF(keyfile_bytes);
     PyMem_Free(pw_info.password);
+    PyMem_Free(certfile_bytes);
     Py_RETURN_NONE;
 
 error:
@@ -3654,7 +3659,9 @@ PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
     if (result == NULL) {
         return NULL;
     }
-    hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
+    hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
+                            CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
+                            store_name);
     if (hStore == NULL) {
         Py_DECREF(result);
         return PyErr_SetFromWindowsErr(GetLastError());
@@ -3742,7 +3749,9 @@ PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
     if (result == NULL) {
         return NULL;
     }
-    hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
+    hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
+                            CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
+                            store_name);
     if (hStore == NULL) {
         Py_DECREF(result);
         return PyErr_SetFromWindowsErr(GetLastError());
index bca7a2e..50fb138 100644 (file)
@@ -1377,15 +1377,13 @@ s_init(PyObject *self, PyObject *args, PyObject *kwds)
 
     if (PyString_Check(o_format)) {
         Py_INCREF(o_format);
-        Py_CLEAR(soself->s_format);
-        soself->s_format = o_format;
+        Py_XSETREF(soself->s_format, o_format);
     }
     else if (PyUnicode_Check(o_format)) {
         PyObject *str = PyUnicode_AsEncodedString(o_format, "ascii", NULL);
         if (str == NULL)
             return -1;
-        Py_CLEAR(soself->s_format);
-        soself->s_format = str;
+        Py_XSETREF(soself->s_format, str);
     }
     else {
         PyErr_Format(PyExc_TypeError,
@@ -1737,7 +1735,7 @@ s_sizeof(PyStructObject *self, void *unused)
 {
     Py_ssize_t size;
 
-    size = sizeof(PyStructObject) + sizeof(formatcode) * (self->s_len + 1);
+    size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode) * (self->s_len + 1);
     return PyLong_FromSsize_t(size);
 }
 
index 5896e48..69f59fc 100644 (file)
@@ -930,6 +930,120 @@ test_L_code(PyObject *self)
 
 #endif  /* ifdef HAVE_LONG_LONG */
 
+static PyObject *
+return_none(void *unused)
+{
+    Py_RETURN_NONE;
+}
+
+static PyObject *
+raise_error(void *unused)
+{
+    PyErr_SetNone(PyExc_ValueError);
+    return NULL;
+}
+
+static int
+test_buildvalue_N_error(const char *fmt)
+{
+    PyObject *arg, *res;
+
+    arg = PyList_New(0);
+    if (arg == NULL) {
+        return -1;
+    }
+
+    Py_INCREF(arg);
+    res = Py_BuildValue(fmt, return_none, NULL, arg);
+    if (res == NULL) {
+        return -1;
+    }
+    Py_DECREF(res);
+    if (Py_REFCNT(arg) != 1) {
+        PyErr_Format(TestError, "test_buildvalue_N: "
+                     "arg was not decrefed in successful "
+                     "Py_BuildValue(\"%s\")", fmt);
+        return -1;
+    }
+
+    Py_INCREF(arg);
+    res = Py_BuildValue(fmt, raise_error, NULL, arg);
+    if (res != NULL || !PyErr_Occurred()) {
+        PyErr_Format(TestError, "test_buildvalue_N: "
+                     "Py_BuildValue(\"%s\") didn't complain", fmt);
+        return -1;
+    }
+    PyErr_Clear();
+    if (Py_REFCNT(arg) != 1) {
+        PyErr_Format(TestError, "test_buildvalue_N: "
+                     "arg was not decrefed in failed "
+                     "Py_BuildValue(\"%s\")", fmt);
+        return -1;
+    }
+    Py_DECREF(arg);
+    return 0;
+}
+
+static PyObject *
+test_buildvalue_N(PyObject *self, PyObject *noargs)
+{
+    PyObject *arg, *res;
+
+    arg = PyList_New(0);
+    if (arg == NULL) {
+        return NULL;
+    }
+    Py_INCREF(arg);
+    res = Py_BuildValue("N", arg);
+    if (res == NULL) {
+        return NULL;
+    }
+    if (res != arg) {
+        return raiseTestError("test_buildvalue_N",
+                              "Py_BuildValue(\"N\") returned wrong result");
+    }
+    if (Py_REFCNT(arg) != 2) {
+        return raiseTestError("test_buildvalue_N",
+                              "arg was not decrefed in Py_BuildValue(\"N\")");
+    }
+    Py_DECREF(res);
+    Py_DECREF(arg);
+
+    if (test_buildvalue_N_error("O&N") < 0)
+        return NULL;
+    if (test_buildvalue_N_error("(O&N)") < 0)
+        return NULL;
+    if (test_buildvalue_N_error("[O&N]") < 0)
+        return NULL;
+    if (test_buildvalue_N_error("{O&N}") < 0)
+        return NULL;
+    if (test_buildvalue_N_error("{()O&(())N}") < 0)
+        return NULL;
+
+    Py_RETURN_NONE;
+}
+
+
+static PyObject *
+get_args(PyObject *self, PyObject *args)
+{
+    if (args == NULL) {
+        args = Py_None;
+    }
+    Py_INCREF(args);
+    return args;
+}
+
+static PyObject *
+get_kwargs(PyObject *self, PyObject *args, PyObject *kwargs)
+{
+    if (kwargs == NULL) {
+        kwargs = Py_None;
+    }
+    Py_INCREF(kwargs);
+    return kwargs;
+}
+
 /* Test tuple argument processing */
 static PyObject *
 getargs_tuple(PyObject *self, PyObject *args)
@@ -1115,6 +1229,326 @@ test_k_code(PyObject *self)
     return Py_None;
 }
 
+static PyObject *
+getargs_f(PyObject *self, PyObject *args)
+{
+    float f;
+    if (!PyArg_ParseTuple(args, "f", &f))
+        return NULL;
+    return PyFloat_FromDouble(f);
+}
+
+static PyObject *
+getargs_d(PyObject *self, PyObject *args)
+{
+    double d;
+    if (!PyArg_ParseTuple(args, "d", &d))
+        return NULL;
+    return PyFloat_FromDouble(d);
+}
+
+static PyObject *
+getargs_D(PyObject *self, PyObject *args)
+{
+    Py_complex cval;
+    if (!PyArg_ParseTuple(args, "D", &cval))
+        return NULL;
+    return PyComplex_FromCComplex(cval);
+}
+
+static PyObject *
+getargs_S(PyObject *self, PyObject *args)
+{
+    PyObject *obj;
+    if (!PyArg_ParseTuple(args, "S", &obj))
+        return NULL;
+    Py_INCREF(obj);
+    return obj;
+}
+
+static PyObject *
+getargs_Y(PyObject *self, PyObject *args)
+{
+    PyObject *obj;
+    if (!PyArg_ParseTuple(args, "Y", &obj))
+        return NULL;
+    Py_INCREF(obj);
+    return obj;
+}
+
+#ifdef Py_USING_UNICODE
+static PyObject *
+getargs_U(PyObject *self, PyObject *args)
+{
+    PyObject *obj;
+    if (!PyArg_ParseTuple(args, "U", &obj))
+        return NULL;
+    Py_INCREF(obj);
+    return obj;
+}
+#endif
+
+static PyObject *
+getargs_c(PyObject *self, PyObject *args)
+{
+    char c;
+    if (!PyArg_ParseTuple(args, "c", &c))
+        return NULL;
+    return PyInt_FromLong((unsigned char)c);
+}
+
+static PyObject *
+getargs_s(PyObject *self, PyObject *args)
+{
+    const char *str;
+    if (!PyArg_ParseTuple(args, "s", &str))
+        return NULL;
+    return PyBytes_FromString(str);
+}
+
+static PyObject *
+getargs_s_star(PyObject *self, PyObject *args)
+{
+    Py_buffer buffer;
+    PyObject *bytes;
+    if (!PyArg_ParseTuple(args, "s*", &buffer))
+        return NULL;
+    bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
+    PyBuffer_Release(&buffer);
+    return bytes;
+}
+
+static PyObject *
+getargs_s_hash(PyObject *self, PyObject *args)
+{
+    const char *str;
+    int size;
+    if (!PyArg_ParseTuple(args, "s#", &str, &size))
+        return NULL;
+    return PyBytes_FromStringAndSize(str, size);
+}
+
+static PyObject *
+getargs_t_hash(PyObject *self, PyObject *args)
+{
+    const char *str;
+    int size;
+    if (!PyArg_ParseTuple(args, "t#", &str, &size))
+        return NULL;
+    return PyBytes_FromStringAndSize(str, size);
+}
+
+static PyObject *
+getargs_z(PyObject *self, PyObject *args)
+{
+    const char *str;
+    if (!PyArg_ParseTuple(args, "z", &str))
+        return NULL;
+    if (str != NULL)
+        return PyBytes_FromString(str);
+    else
+        Py_RETURN_NONE;
+}
+
+static PyObject *
+getargs_z_star(PyObject *self, PyObject *args)
+{
+    Py_buffer buffer;
+    PyObject *bytes;
+    if (!PyArg_ParseTuple(args, "z*", &buffer))
+        return NULL;
+    if (buffer.buf != NULL)
+        bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
+    else {
+        Py_INCREF(Py_None);
+        bytes = Py_None;
+    }
+    PyBuffer_Release(&buffer);
+    return bytes;
+}
+
+static PyObject *
+getargs_z_hash(PyObject *self, PyObject *args)
+{
+    const char *str;
+    int size;
+    if (!PyArg_ParseTuple(args, "z#", &str, &size))
+        return NULL;
+    if (str != NULL)
+        return PyBytes_FromStringAndSize(str, size);
+    else
+        Py_RETURN_NONE;
+}
+
+static PyObject *
+getargs_w(PyObject *self, PyObject *args)
+{
+    char *str;
+    Py_ssize_t size;
+
+    if (!PyArg_ParseTuple(args, "wn", &str, &size))
+        return NULL;
+
+    if (2 <= size) {
+        str[0] = '[';
+        str[size-1] = ']';
+    }
+
+    return PyBytes_FromStringAndSize(str, size);
+}
+
+static PyObject *
+getargs_w_hash(PyObject *self, PyObject *args)
+{
+    char *str;
+    int size;
+
+    if (!PyArg_ParseTuple(args, "w#", &str, &size))
+        return NULL;
+
+    if (2 <= size) {
+        str[0] = '[';
+        str[size-1] = ']';
+    }
+
+    return PyBytes_FromStringAndSize(str, size);
+}
+
+static PyObject *
+getargs_w_star(PyObject *self, PyObject *args)
+{
+    Py_buffer buffer;
+    PyObject *result;
+    char *str;
+
+    if (!PyArg_ParseTuple(args, "w*", &buffer))
+        return NULL;
+
+    if (2 <= buffer.len) {
+        str = buffer.buf;
+        str[0] = '[';
+        str[buffer.len-1] = ']';
+    }
+
+    result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
+    PyBuffer_Release(&buffer);
+    return result;
+}
+
+#ifdef Py_USING_UNICODE
+
+static int
+_ustrlen(const Py_UNICODE *u)
+{
+    int i = 0;
+    const Py_UNICODE *v = u;
+    while (*v != 0) { i++; v++; }
+    return i;
+}
+
+static PyObject *
+getargs_u(PyObject *self, PyObject *args)
+{
+    const Py_UNICODE *str;
+    int size;
+    if (!PyArg_ParseTuple(args, "u", &str))
+        return NULL;
+    size = _ustrlen(str);
+    return PyUnicode_FromUnicode(str, size);
+}
+
+static PyObject *
+getargs_u_hash(PyObject *self, PyObject *args)
+{
+    const Py_UNICODE *str;
+    int size;
+    if (!PyArg_ParseTuple(args, "u#", &str, &size))
+        return NULL;
+    return PyUnicode_FromUnicode(str, size);
+}
+
+#endif
+
+static PyObject *
+getargs_es(PyObject *self, PyObject *args)
+{
+    PyObject *arg, *result;
+    const char *encoding = NULL;
+    char *str;
+
+    if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
+        return NULL;
+    if (!PyArg_Parse(arg, "es", encoding, &str))
+        return NULL;
+    result = PyBytes_FromString(str);
+    PyMem_Free(str);
+    return result;
+}
+
+static PyObject *
+getargs_et(PyObject *self, PyObject *args)
+{
+    PyObject *arg, *result;
+    const char *encoding = NULL;
+    char *str;
+
+    if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding))
+        return NULL;
+    if (!PyArg_Parse(arg, "et", encoding, &str))
+        return NULL;
+    result = PyBytes_FromString(str);
+    PyMem_Free(str);
+    return result;
+}
+
+static PyObject *
+getargs_es_hash(PyObject *self, PyObject *args)
+{
+    PyObject *arg, *result;
+    const char *encoding = NULL;
+    PyByteArrayObject *buffer = NULL;
+    char *str = NULL;
+    int size;
+
+    if (!PyArg_ParseTuple(args, "O|sO!",
+                          &arg, &encoding, &PyByteArray_Type, &buffer))
+        return NULL;
+    if (buffer != NULL) {
+        str = PyByteArray_AS_STRING(buffer);
+        size = PyByteArray_GET_SIZE(buffer);
+    }
+    if (!PyArg_Parse(arg, "es#", encoding, &str, &size))
+        return NULL;
+    result = PyBytes_FromStringAndSize(str, size);
+    if (buffer == NULL)
+        PyMem_Free(str);
+    return result;
+}
+
+static PyObject *
+getargs_et_hash(PyObject *self, PyObject *args)
+{
+    PyObject *arg, *result;
+    const char *encoding = NULL;
+    PyByteArrayObject *buffer = NULL;
+    char *str = NULL;
+    int size;
+
+    if (!PyArg_ParseTuple(args, "O|sO!",
+                          &arg, &encoding, &PyByteArray_Type, &buffer))
+        return NULL;
+    if (buffer != NULL) {
+        str = PyByteArray_AS_STRING(buffer);
+        size = PyByteArray_GET_SIZE(buffer);
+    }
+    if (!PyArg_Parse(arg, "et#", encoding, &str, &size))
+        return NULL;
+    result = PyBytes_FromStringAndSize(str, size);
+    if (buffer == NULL)
+        PyMem_Free(str);
+    return result;
+}
+
 #ifdef Py_USING_UNICODE
 
 static volatile int x;
@@ -1335,7 +1769,12 @@ test_long_numbits(PyObject *self)
 static PyObject *
 test_null_strings(PyObject *self)
 {
-    PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Unicode(NULL);
+    PyObject *o1 = PyObject_Str(NULL);
+#ifdef Py_USING_UNICODE
+    PyObject *o2 = PyObject_Unicode(NULL);
+#else
+    PyObject *o2 = PyObject_Str(NULL);
+#endif
     PyObject *tuple = PyTuple_Pack(2, o1, o2);
     Py_XDECREF(o1);
     Py_XDECREF(o2);
@@ -1385,6 +1824,7 @@ set_errno(PyObject *self, PyObject *args)
     Py_RETURN_NONE;
 }
 
+#ifdef Py_USING_UNICODE
 static int test_run_counter = 0;
 
 static PyObject *
@@ -1407,6 +1847,7 @@ test_datetime_capi(PyObject *self, PyObject *args) {
     else
         return NULL;
 }
+#endif
 
 
 #ifdef WITH_THREAD
@@ -2045,7 +2486,9 @@ static PyMethodDef TestMethods[] = {
     {"raise_exception",         raise_exception,                 METH_VARARGS},
     {"set_errno",               set_errno,                       METH_VARARGS},
     {"test_config",             (PyCFunction)test_config,        METH_NOARGS},
+#ifdef Py_USING_UNICODE
     {"test_datetime_capi",  test_datetime_capi,              METH_NOARGS},
+#endif
     {"test_list_api",           (PyCFunction)test_list_api,      METH_NOARGS},
     {"test_dict_iteration",     (PyCFunction)test_dict_iteration,METH_NOARGS},
     {"test_lazy_hash_inheritance",      (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
@@ -2057,12 +2500,17 @@ static PyMethodDef TestMethods[] = {
      METH_NOARGS},
     {"test_long_numbits",       (PyCFunction)test_long_numbits,  METH_NOARGS},
     {"test_k_code",             (PyCFunction)test_k_code,        METH_NOARGS},
+#ifdef Py_USING_UNICODE
     {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
+#endif
     {"test_null_strings",       (PyCFunction)test_null_strings,  METH_NOARGS},
     {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
     {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
      PyDoc_STR("This is a pretty normal docstring.")},
 
+    {"test_buildvalue_N",       test_buildvalue_N,               METH_NOARGS},
+    {"get_args", get_args, METH_VARARGS},
+    {"get_kwargs", (PyCFunction)get_kwargs, METH_VARARGS|METH_KEYWORDS},
     {"getargs_tuple",           getargs_tuple,                   METH_VARARGS},
     {"getargs_keywords", (PyCFunction)getargs_keywords,
       METH_VARARGS|METH_KEYWORDS},
@@ -2082,12 +2530,39 @@ static PyMethodDef TestMethods[] = {
     {"test_long_long_and_overflow",
         (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
     {"test_L_code",             (PyCFunction)test_L_code,        METH_NOARGS},
+#endif
+    {"getargs_f",               getargs_f,                       METH_VARARGS},
+    {"getargs_d",               getargs_d,                       METH_VARARGS},
+    {"getargs_D",               getargs_D,                       METH_VARARGS},
+    {"getargs_S",               getargs_S,                       METH_VARARGS},
+    {"getargs_Y",               getargs_Y,                       METH_VARARGS},
+#ifdef Py_USING_UNICODE
+    {"getargs_U",               getargs_U,                       METH_VARARGS},
+#endif
+    {"getargs_c",               getargs_c,                       METH_VARARGS},
+    {"getargs_s",               getargs_s,                       METH_VARARGS},
+    {"getargs_s_star",          getargs_s_star,                  METH_VARARGS},
+    {"getargs_s_hash",          getargs_s_hash,                  METH_VARARGS},
+    {"getargs_t_hash",          getargs_t_hash,                  METH_VARARGS},
+    {"getargs_z",               getargs_z,                       METH_VARARGS},
+    {"getargs_z_star",          getargs_z_star,                  METH_VARARGS},
+    {"getargs_z_hash",          getargs_z_hash,                  METH_VARARGS},
+    {"getargs_w",               getargs_w,                       METH_VARARGS},
+    {"getargs_w_star",          getargs_w_star,                  METH_VARARGS},
+    {"getargs_w_hash",          getargs_w_hash,                  METH_VARARGS},
+#ifdef Py_USING_UNICODE
+    {"getargs_u",               getargs_u,                       METH_VARARGS},
+    {"getargs_u_hash",          getargs_u_hash,                  METH_VARARGS},
+#endif
+    {"getargs_es",              getargs_es,                      METH_VARARGS},
+    {"getargs_et",              getargs_et,                      METH_VARARGS},
+    {"getargs_es_hash",         getargs_es_hash,                 METH_VARARGS},
+    {"getargs_et_hash",         getargs_et_hash,                 METH_VARARGS},
+#ifdef Py_USING_UNICODE
     {"codec_incrementalencoder",
      (PyCFunction)codec_incrementalencoder,      METH_VARARGS},
     {"codec_incrementaldecoder",
      (PyCFunction)codec_incrementaldecoder,      METH_VARARGS},
-#endif
-#ifdef Py_USING_UNICODE
     {"test_u_code",             (PyCFunction)test_u_code,        METH_NOARGS},
     {"test_widechar",           (PyCFunction)test_widechar,      METH_NOARGS},
     {"unicode_encodedecimal",   unicode_encodedecimal,           METH_VARARGS},
index 1d1f0d3..f147115 100644 (file)
@@ -1541,7 +1541,7 @@ static PyObject *
 array_sizeof(arrayobject *self, PyObject *unused)
 {
     Py_ssize_t res;
-    res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize;
+    res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
     return PyLong_FromSsize_t(res);
 }
 
index 4d3b679..e829e4d 100644 (file)
@@ -55,7 +55,7 @@ fbound(double val, double minval, double maxval)
  */
 #define BIAS 0x84   /* define the add-in bias for 16 bit samples */
 #define CLIP 32635
-#define SIGN_BIT        (0x80)          /* Sign bit for a A-law byte. */
+#define SIGN_BIT        (0x80)          /* Sign bit for an A-law byte. */
 #define QUANT_MASK      (0xf)           /* Quantization field mask. */
 #define SEG_SHIFT       (4)             /* Left shift for segment number. */
 #define SEG_MASK        (0x70)          /* Segment field mask. */
@@ -229,8 +229,8 @@ static PyInt16 _st_alaw2linear16[256] = {
 };
 
 /*
- * linear2alaw() accepts an 13-bit signed integer and encodes it as A-law data
- * stored in a unsigned char.  This function should only be called with
+ * linear2alaw() accepts a 13-bit signed integer and encodes it as A-law data
+ * stored in an unsigned char.  This function should only be called with
  * the data shifted such that it only contains information in the lower
  * 13-bits.
  *
index ae749ee..fe417c5 100644 (file)
@@ -1953,9 +1953,8 @@ BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args)
             self->running = 0;
             input_left += bzs->avail_in;
             if (input_left != 0) {
-                Py_DECREF(self->unused_data);
-                self->unused_data =
-                    PyString_FromStringAndSize(bzs->next_in, input_left);
+                Py_SETREF(self->unused_data,
+                          PyString_FromStringAndSize(bzs->next_in, input_left));
                 if (self->unused_data == NULL)
                     goto error;
             }
index 0e93723..88f4f23 100644 (file)
@@ -689,8 +689,7 @@ read_other(Unpicklerobject *self, char **s, Py_ssize_t  n)
     }
     if (! str) return -1;
 
-    Py_XDECREF(self->last_string);
-    self->last_string = str;
+    Py_XSETREF(self->last_string, str);
 
     if (! (*s = PyString_AsString(str))) return -1;
 
@@ -716,8 +715,7 @@ readline_other(Unpicklerobject *self, char **s)
     if ((str_size = PyString_Size(str)) < 0)
         return -1;
 
-    Py_XDECREF(self->last_string);
-    self->last_string = str;
+    Py_XSETREF(self->last_string, str);
 
     if (! (*s = PyString_AsString(str)))
         return -1;
@@ -3228,9 +3226,8 @@ Pickler_set_pers_func(Picklerobject *p, PyObject *v)
                         "attribute deletion is not supported");
         return -1;
     }
-    Py_XDECREF(p->pers_func);
     Py_INCREF(v);
-    p->pers_func = v;
+    Py_XSETREF(p->pers_func, v);
     return 0;
 }
 
@@ -3242,9 +3239,8 @@ Pickler_set_inst_pers_func(Picklerobject *p, PyObject *v)
                         "attribute deletion is not supported");
         return -1;
     }
-    Py_XDECREF(p->inst_pers_func);
     Py_INCREF(v);
-    p->inst_pers_func = v;
+    Py_XSETREF(p->inst_pers_func, v);
     return 0;
 }
 
@@ -3270,9 +3266,8 @@ Pickler_set_memo(Picklerobject *p, PyObject *v)
         PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
         return -1;
     }
-    Py_XDECREF(p->memo);
     Py_INCREF(v);
-    p->memo = v;
+    Py_XSETREF(p->memo, v);
     return 0;
 }
 
@@ -3449,7 +3444,7 @@ load_bool(Unpicklerobject *self, PyObject *boolean)
 
 /* s contains x bytes of a little-endian integer.  Return its value as a
  * C int.  Obscure:  when x is 1 or 2, this is an unsigned little-endian
- * int, but when x is 4 it's a signed one.  This is an historical source
+ * int, but when x is 4 it's a signed one.  This is a historical source
  * of x-platform bugs.
  */
 static long
@@ -3798,35 +3793,26 @@ load_binunicode(Unpicklerobject *self)
 
 
 static int
-load_tuple(Unpicklerobject *self)
+load_counted_tuple(Unpicklerobject *self, int len)
 {
     PyObject *tup;
-    Py_ssize_t i;
 
-    if ((i = marker(self)) < 0) return -1;
-    if (!( tup=Pdata_popTuple(self->stack, i)))  return -1;
+    if (self->stack->length < len)
+        return stackUnderflow();
+
+    if (!(tup = Pdata_popTuple(self->stack, self->stack->length - len)))
+        return -1;
     PDATA_PUSH(self->stack, tup, -1);
     return 0;
 }
 
 static int
-load_counted_tuple(Unpicklerobject *self, int len)
+load_tuple(Unpicklerobject *self)
 {
-    PyObject *tup = PyTuple_New(len);
-
-    if (tup == NULL)
-        return -1;
-
-    while (--len >= 0) {
-        PyObject *element;
+    Py_ssize_t i;
 
-        PDATA_POP(self->stack, element);
-        if (element == NULL)
-            return -1;
-        PyTuple_SET_ITEM(tup, len, element);
-    }
-    PDATA_PUSH(self->stack, tup, -1);
-    return 0;
+    if ((i = marker(self)) < 0) return -1;
+    return load_counted_tuple(self, self->stack->length - i);
 }
 
 static int
@@ -3945,6 +3931,10 @@ load_obj(Unpicklerobject *self)
     Py_ssize_t i;
 
     if ((i = marker(self)) < 0) return -1;
+
+    if (self->stack->length - i < 1)
+        return stackUnderflow();
+
     if (!( tup=Pdata_popTuple(self->stack, i+1)))  return -1;
     PDATA_POP(self->stack, class);
     if (class) {
@@ -3974,7 +3964,10 @@ load_inst(Unpicklerobject *self)
     if (!module_name)  return -1;
 
     if ((len = self->readline_func(self, &s)) >= 0) {
-        if (len < 2) return bad_readline();
+        if (len < 2) {
+            Py_DECREF(module_name);
+            return bad_readline();
+        }
         if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
             class = find_class(module_name, class_name,
                                self->find_class);
@@ -4496,6 +4489,8 @@ do_append(Unpicklerobject *self, Py_ssize_t  x)
 static int
 load_append(Unpicklerobject *self)
 {
+    if (self->stack->length - 1 <= 0)
+        return stackUnderflow();
     return do_append(self, self->stack->length - 1);
 }
 
@@ -4503,7 +4498,10 @@ load_append(Unpicklerobject *self)
 static int
 load_appends(Unpicklerobject *self)
 {
-    return do_append(self, marker(self));
+    Py_ssize_t i = marker(self);
+    if (i < 0)
+        return -1;
+    return do_append(self, i);
 }
 
 
@@ -4515,6 +4513,14 @@ do_setitems(Unpicklerobject *self, Py_ssize_t x)
 
     if (!( (len=self->stack->length) >= x
            && x > 0 ))  return stackUnderflow();
+    if (len == x)  /* nothing to do */
+        return 0;
+    if ((len - x) % 2 != 0) {
+        /* Currupt or hostile pickle -- we never write one like this. */
+        PyErr_SetString(UnpicklingError,
+                        "odd number of items for SETITEMS");
+        return -1;
+    }
 
     dict=self->stack->data[x-1];
 
@@ -4542,7 +4548,10 @@ load_setitem(Unpicklerobject *self)
 static int
 load_setitems(Unpicklerobject *self)
 {
-    return do_setitems(self, marker(self));
+    Py_ssize_t i = marker(self);
+    if (i < 0)
+        return -1;
+    return do_setitems(self, i);
 }
 
 
@@ -5653,16 +5662,14 @@ Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value)
 {
 
     if (!strcmp(name, "persistent_load")) {
-        Py_XDECREF(self->pers_func);
-        self->pers_func = value;
         Py_XINCREF(value);
+        Py_XSETREF(self->pers_func, value);
         return 0;
     }
 
     if (!strcmp(name, "find_global")) {
-        Py_XDECREF(self->find_class);
-        self->find_class = value;
         Py_XINCREF(value);
+        Py_XSETREF(self->find_class, value);
         return 0;
     }
 
@@ -5678,9 +5685,8 @@ Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value)
                             "memo must be a dictionary");
             return -1;
         }
-        Py_XDECREF(self->memo);
-        self->memo = value;
         Py_INCREF(value);
+        Py_XSETREF(self->memo, value);
         return 0;
     }
 
index 9ee9b0b..ddb2996 100644 (file)
@@ -628,12 +628,10 @@ CD_addcallback(cdparserobject *self, PyObject *args)
     CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
                   (void *) self);
 #endif
-    Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
     Py_INCREF(func);
-    self->ob_cdcallbacks[type].ob_cdcallback = func;
-    Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+    Py_XSETREF(self->ob_cdcallbacks[type].ob_cdcallback, func);
     Py_INCREF(funcarg);
-    self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg;
+    Py_XSETREF(self->ob_cdcallbacks[type].ob_cdcallbackarg, funcarg);
 
 /*
     if (type == cd_audio) {
index 399e9dc..ac2892d 100644 (file)
@@ -325,22 +325,26 @@ find_pairencmap(ucs2_t body, ucs2_t modifier,
     min = 0;
     max = haystacksize;
 
-    for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
+    for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) {
         if (value < haystack[pos].uniseq) {
-            if (max == pos) break;
-            else max = pos;
+            if (max != pos) {
+                max = pos;
+                continue;
+            }
         }
         else if (value > haystack[pos].uniseq) {
-            if (min == pos) break;
-            else min = pos;
+            if (min != pos) {
+                min = pos;
+                continue;
+            }
         }
-        else
-            break;
+        break;
+    }
 
-        if (value == haystack[pos].uniseq)
-            return haystack[pos].code;
-        else
-            return DBCINV;
+    if (value == haystack[pos].uniseq) {
+        return haystack[pos].code;
+    }
+    return DBCINV;
 }
 #endif
 
index f733fa1..e7fd349 100644 (file)
@@ -197,7 +197,7 @@ days_in_month(int year, int month)
         return _days_in_month[month];
 }
 
-/* year, month -> number of days in year preceeding first day of month */
+/* year, month -> number of days in year preceding first day of month */
 static int
 days_before_month(int year, int month)
 {
index 06b5de0..e8eefdd 100644 (file)
@@ -1040,7 +1040,7 @@ XML_GetFeatureList(void);
 */
 #define XML_MAJOR_VERSION 2
 #define XML_MINOR_VERSION 1
-#define XML_MICRO_VERSION 0
+#define XML_MICRO_VERSION 1
 
 #ifdef __cplusplus
 }
index f35aa36..6a61508 100644 (file)
@@ -1550,7 +1550,7 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
   else if (bufferPtr == bufferEnd) {
     const char *end;
     int nLeftOver;
-    enum XML_Error result;
+    enum XML_Status result;
     parseEndByteIndex += len;
     positionPtr = s;
     ps_finalBuffer = (XML_Bool)isFinal;
@@ -1678,6 +1678,10 @@ XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
 void * XMLCALL
 XML_GetBuffer(XML_Parser parser, int len)
 {
+  if (len < 0) {
+    errorCode = XML_ERROR_NO_MEMORY;
+    return NULL;
+  }
   switch (ps_parsing) {
   case XML_SUSPENDED:
     errorCode = XML_ERROR_SUSPENDED;
@@ -1689,10 +1693,16 @@ XML_GetBuffer(XML_Parser parser, int len)
   }
 
   if (len > bufferLim - bufferEnd) {
-    /* FIXME avoid integer overflow */
+#ifdef XML_CONTEXT_BYTES
+    int keep;
+#endif
     int neededSize = len + (int)(bufferEnd - bufferPtr);
+    if (neededSize < 0) {
+      errorCode = XML_ERROR_NO_MEMORY;
+      return NULL;
+    }
 #ifdef XML_CONTEXT_BYTES
-    int keep = (int)(bufferPtr - buffer);
+    keep = (int)(bufferPtr - buffer);
 
     if (keep > XML_CONTEXT_BYTES)
       keep = XML_CONTEXT_BYTES;
@@ -1719,7 +1729,11 @@ XML_GetBuffer(XML_Parser parser, int len)
         bufferSize = INIT_BUFFER_SIZE;
       do {
         bufferSize *= 2;
-      } while (bufferSize < neededSize);
+      } while (bufferSize < neededSize && bufferSize > 0);
+      if (bufferSize <= 0) {
+        errorCode = XML_ERROR_NO_MEMORY;
+        return NULL;
+      }
       newBuf = (char *)MALLOC(bufferSize);
       if (newBuf == 0) {
         errorCode = XML_ERROR_NO_MEMORY;
@@ -2911,6 +2925,8 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
         unsigned long uriHash = hash_secret_salt;
         ((XML_Char *)s)[-1] = 0;  /* clear flag */
         id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
+        if (!id || !id->prefix)
+          return XML_ERROR_NO_MEMORY;
         b = id->prefix->binding;
         if (!b)
           return XML_ERROR_UNBOUND_PREFIX;
@@ -5475,6 +5491,8 @@ getAttributeId(XML_Parser parser, const ENCODING *enc,
             return NULL;
           id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
                                         sizeof(PREFIX));
+          if (!id->prefix)
+            return NULL;
           if (id->prefix->name == poolStart(&dtd->pool))
             poolFinish(&dtd->pool);
           else
index b9cd7a4..bf09dfc 100644 (file)
@@ -1584,7 +1584,7 @@ initScan(const ENCODING * const *encodingTable,
       if (ptr[0] == '\0') {
         /* 0 isn't a legal data character. Furthermore a document
            entity can only start with ASCII characters.  So the only
-           way this can fail to be big-endian UTF-16 is if it is an
+           way this can fail to be big-endian UTF-16 if it it's an
            external parsed general entity that's labelled as
            UTF-16LE.
         */
index 9d054d0..99db7e7 100644 (file)
  *    without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR GAI_ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON GAI_ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN GAI_ANY WAY
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
index de96d47..b239159 100644 (file)
 #endif
 
 
-#ifndef VERSION
-#define VERSION "2.1"
-#endif
-
-#ifndef VPATH
-#define VPATH "."
-#endif
-
-#ifndef PREFIX
-#  ifdef __VMS
-#    define PREFIX ""
-#  else
-#    define PREFIX "/usr/local"
-#  endif
-#endif
-
-#ifndef EXEC_PREFIX
-#define EXEC_PREFIX PREFIX
-#endif
-
-#ifndef PYTHONPATH
-#define PYTHONPATH PREFIX "/lib/python" VERSION ":" \
-              EXEC_PREFIX "/lib/python" VERSION "/lib-dynload"
+#if !defined(PREFIX) || !defined(EXEC_PREFIX) || !defined(VERSION) || !defined(VPATH)
+#error "PREFIX, EXEC_PREFIX, VERSION, and VPATH must be constant defined"
 #endif
 
 #ifndef LANDMARK
index c3cf1c0..68285b8 100644 (file)
@@ -4,8 +4,6 @@
 
 /* Itertools module written and maintained
    by Raymond D. Hettinger <python@rcn.com>
-   Copyright (c) 2003 Python Software Foundation.
-   All rights reserved.
 */
 
 
@@ -494,8 +492,7 @@ tee_next(teeobject *to)
         link = teedataobject_jumplink(to->dataobj);
         if (link == NULL)
             return NULL;
-        Py_DECREF(to->dataobj);
-        to->dataobj = (teedataobject *)link;
+        Py_SETREF(to->dataobj, (teedataobject *)link);
         to->index = 0;
     }
     value = teedataobject_getitem(to->dataobj, to->index);
index 39251d2..c18ff10 100644 (file)
@@ -12,7 +12,7 @@
 #
 #   ARGUMENTS:      Same as for "ld". The following arguments are processed
 #                   or supplied by this script (those marked with an asterisk
-#                   can be overriden from command line):
+#                   can be overridden from command line):
 #
 #                       Argument                     Default value
 #                   (*) -o [OutputFileName]          -o shr.o
@@ -85,7 +85,7 @@ if test ! -n "$*"; then
 fi
 
 # Default import file for Python
-# Can be overriden by providing a -bI: argument.
+# Can be overridden by providing a -bI: argument.
 impfile="./python.exp"
 
 # Parse arguments
@@ -156,7 +156,7 @@ if test -z "$expfile"; then
 fi
 
 # Default entry symbol for Python modules = init[modulename]
-# Can be overriden by providing a -e argument.
+# Can be overridden by providing a -e argument.
 if test -z "$entry"; then
   entry=init`echo $filename | sed "s/module.*//"`
 fi
index 670e52d..01ed36b 100644 (file)
@@ -379,9 +379,8 @@ m_lgamma(double x)
    Implementations of the error function erf(x) and the complementary error
    function erfc(x).
 
-   Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
-   Cambridge University Press), we use a series approximation for erf for
-   small x, and a continued fraction approximation for erfc(x) for larger x;
+   Method: we use a series approximation for erf for small x, and a continued
+   fraction approximation for erfc(x) for larger x;
    combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
    this gives us erf(x) and erfc(x) for all x.
 
index 8fdf7f7..1ebccdf 100644 (file)
@@ -655,7 +655,7 @@ mmap__sizeof__method(mmap_object *self, void *unused)
 {
     Py_ssize_t res;
 
-    res = sizeof(mmap_object);
+    res = _PyObject_SIZE(Py_TYPE(self));
     if (self->tagname)
         res += strlen(self->tagname) + 1;
     return PyLong_FromSsize_t(res);
index 375592c..ae060b8 100644 (file)
@@ -511,6 +511,8 @@ itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw)
     PyObject *obj, *result;
     Py_ssize_t i, nitems=ig->nitems;
 
+    if (kw != NULL && !_PyArg_NoKeywords("itemgetter", kw))
+        return NULL;
     if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
         return NULL;
     if (nitems == 1)
@@ -691,6 +693,8 @@ attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw)
     PyObject *obj, *result;
     Py_ssize_t i, nattrs=ag->nattrs;
 
+    if (kw != NULL && !_PyArg_NoKeywords("attrgetter", kw))
+        return NULL;
     if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
         return NULL;
     if (ag->nattrs == 1)
@@ -838,6 +842,8 @@ methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw)
 {
     PyObject *method, *obj, *result;
 
+    if (kw != NULL && !_PyArg_NoKeywords("methodcaller", kw))
+        return NULL;
     if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
         return NULL;
     method = PyObject_GetAttr(obj, mc->name);
index eb2d600..2434c67 100644 (file)
@@ -720,7 +720,7 @@ parser_sizeof(PyST_Object *st, void *unused)
 {
     Py_ssize_t res;
 
-    res = sizeof(PyST_Object) + _PyNode_SizeOf(st->st_node);
+    res = _PyObject_SIZE(Py_TYPE(st)) + _PyNode_SizeOf(st->st_node);
     return PyLong_FromSsize_t(res);
 }
 
index 2739b8b..d83642a 100644 (file)
@@ -3,7 +3,7 @@
 #include "Python.h"
 
 #ifdef __FreeBSD__
-#include <floatingpoint.h>
+#include <fenv.h>
 #endif
 
 int
@@ -15,10 +15,7 @@ main(int argc, char **argv)
         * exceptions by default.  Here we disable them.
         */
 #ifdef __FreeBSD__
-       fp_except_t m;
-
-       m = fpgetmask();
-       fpsetmask(m & ~FP_X_OFL);
+       fedisableexcept(FE_OVERFLOW);
 #endif
        return Py_Main(argc, argv);
 }
index 1e98ffb..1600cd3 100644 (file)
@@ -96,7 +96,7 @@ parse_and_bind(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_parse_and_bind,
 "parse_and_bind(string) -> None\n\
-Parse and execute single line of a readline init file.");
+Execute the init line provided in the string argument.");
 
 
 /* Exported function to parse a readline init file */
@@ -115,7 +115,7 @@ read_init_file(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_read_init_file,
 "read_init_file([filename]) -> None\n\
-Parse a readline initialization file.\n\
+Execute a readline initialization file.\n\
 The default filename is the last filename used.");
 
 
@@ -176,7 +176,7 @@ set_history_length(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(set_history_length_doc,
 "set_history_length(length) -> None\n\
-set the maximal number of items which will be written to\n\
+set the maximal number of lines which will be written to\n\
 the history file. A negative length is used to inhibit\n\
 history truncation.");
 
@@ -191,7 +191,7 @@ get_history_length(PyObject *self, PyObject *noarg)
 
 PyDoc_STRVAR(get_history_length_doc,
 "get_history_length() -> int\n\
-return the maximum number of items that will be written to\n\
+return the maximum number of lines that will be written to\n\
 the history file.");
 
 
@@ -269,7 +269,7 @@ set_startup_hook(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_set_startup_hook,
 "set_startup_hook([function]) -> None\n\
-Set or remove the startup_hook function.\n\
+Set or remove the function invoked by the rl_startup_hook callback.\n\
 The function is called with no arguments just\n\
 before readline prints the first prompt.");
 
@@ -286,7 +286,7 @@ set_pre_input_hook(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_set_pre_input_hook,
 "set_pre_input_hook([function]) -> None\n\
-Set or remove the pre_input_hook function.\n\
+Set or remove the function invoked by the rl_pre_input_hook callback.\n\
 The function is called with no arguments after the first prompt\n\
 has been printed and just before readline starts reading input\n\
 characters.");
@@ -325,7 +325,7 @@ get_begidx(PyObject *self, PyObject *noarg)
 
 PyDoc_STRVAR(doc_get_begidx,
 "get_begidx() -> int\n\
-get the beginning index of the readline tab-completion scope");
+get the beginning index of the completion scope");
 
 
 /* Get the ending index for the scope of the tab-completion */
@@ -339,7 +339,7 @@ get_endidx(PyObject *self, PyObject *noarg)
 
 PyDoc_STRVAR(doc_get_endidx,
 "get_endidx() -> int\n\
-get the ending index of the readline tab-completion scope");
+get the ending index of the completion scope");
 
 
 /* Set the tab-completion word-delimiters that readline uses */
@@ -368,7 +368,7 @@ set_completer_delims(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_set_completer_delims,
 "set_completer_delims(string) -> None\n\
-set the readline word delimiters for tab-completion");
+set the word delimiters for completion");
 
 /* _py_free_history_entry: Utility function to free a history entry. */
 
@@ -408,7 +408,7 @@ py_remove_history(PyObject *self, PyObject *args)
     int entry_number;
     HIST_ENTRY *entry;
 
-    if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
+    if (!PyArg_ParseTuple(args, "i:remove_history_item", &entry_number))
         return NULL;
     if (entry_number < 0) {
         PyErr_SetString(PyExc_ValueError,
@@ -438,7 +438,7 @@ py_replace_history(PyObject *self, PyObject *args)
     char *line;
     HIST_ENTRY *old_entry;
 
-    if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
+    if (!PyArg_ParseTuple(args, "is:replace_history_item", &entry_number,
                           &line)) {
         return NULL;
     }
@@ -479,7 +479,7 @@ py_add_history(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_add_history,
 "add_history(string) -> None\n\
-add a line to the history buffer");
+add an item to the history buffer");
 
 
 /* Get the tab-completion word-delimiters that readline uses */
@@ -492,7 +492,7 @@ get_completer_delims(PyObject *self, PyObject *noarg)
 
 PyDoc_STRVAR(doc_get_completer_delims,
 "get_completer_delims() -> string\n\
-get the readline word delimiters for tab-completion");
+get the word delimiters for completion");
 
 
 /* Set the completer function */
@@ -553,7 +553,7 @@ get_history_item(PyObject *self, PyObject *args)
     int idx = 0;
     HIST_ENTRY *hist_ent;
 
-    if (!PyArg_ParseTuple(args, "i:index", &idx))
+    if (!PyArg_ParseTuple(args, "i:get_history_item", &idx))
         return NULL;
 #ifdef  __APPLE__
     if (using_libedit_emulation) {
@@ -645,7 +645,7 @@ insert_text(PyObject *self, PyObject *args)
 
 PyDoc_STRVAR(doc_insert_text,
 "insert_text(string) -> None\n\
-Insert text into the command line.");
+Insert text into the line buffer at the cursor position.");
 
 
 /* Redisplay the line buffer */
@@ -817,6 +817,26 @@ on_completion_display_matches_hook(char **matches,
 }
 
 
+#ifdef HAVE_RL_RESIZE_TERMINAL
+static volatile sig_atomic_t sigwinch_received;
+static PyOS_sighandler_t sigwinch_ohandler;
+
+static void
+readline_sigwinch_handler(int signum)
+{
+    sigwinch_received = 1;
+    if (sigwinch_ohandler &&
+            sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
+        sigwinch_ohandler(signum);
+
+#ifndef HAVE_SIGACTION
+    /* If the handler was installed with signal() rather than sigaction(),
+    we need to reinstall it. */
+    PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
+#endif
+}
+#endif
+
 /* C function to call the Python completer. */
 
 static char *
@@ -918,6 +938,10 @@ setup_readline(void)
     /* Bind both ESC-TAB and ESC-ESC to the completion function */
     rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
     rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
+#ifdef HAVE_RL_RESIZE_TERMINAL
+    /* Set up signal handler for window resize */
+    sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
+#endif
     /* Set our hook functions */
     rl_startup_hook = on_startup_hook;
 #ifdef HAVE_RL_PRE_INPUT_HOOK
@@ -936,7 +960,7 @@ setup_readline(void)
 
 #ifndef __APPLE__
     if (!isatty(STDOUT_FILENO)) {
-        /* Issue #19884: stdout is no a terminal. Disable meta modifier
+        /* Issue #19884: stdout is not a terminal. Disable meta modifier
            keys to not write the ANSI sequence "\033[1034h" into stdout. On
            terminals supporting 8 bit characters like TERM=xterm-256color
            (which is now the default Fedora since Fedora 18), the meta key is
@@ -1003,6 +1027,13 @@ readline_until_enter_or_signal(char *prompt, int *signal)
             struct timeval *timeoutp = NULL;
             if (PyOS_InputHook)
                 timeoutp = &timeout;
+#ifdef HAVE_RL_RESIZE_TERMINAL
+            /* Update readline's view of the window size after SIGWINCH */
+            if (sigwinch_received) {
+                sigwinch_received = 0;
+                rl_resize_terminal();
+            }
+#endif
             FD_SET(fileno(rl_instream), &selectset);
             /* select resets selectset if no input was available */
             has_input = select(fileno(rl_instream) + 1, &selectset,
@@ -1024,6 +1055,9 @@ readline_until_enter_or_signal(char *prompt, int *signal)
 #endif
             if (s < 0) {
                 rl_free_line_state();
+#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
+                rl_callback_sigcleanup();
+#endif
                 rl_cleanup_after_signal();
                 rl_callback_handler_remove();
                 *signal = 1;
index 2ce8d92..8f18faa 100644 (file)
@@ -101,7 +101,7 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
  * algorithms in a highly modular and flexible manner.
  *
  * The library is free for all purposes without any express
- * gurantee it works.
+ * guarantee it works.
  *
  * Tom St Denis, tomstdenis@iahu.ca, http://libtomcrypt.org
  */
index d7b3699..abc9021 100644 (file)
@@ -111,7 +111,7 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
  * algorithms in a highly modular and flexible manner.
  *
  * The library is free for all purposes without any express
- * gurantee it works.
+ * guarantee it works.
  *
  * Tom St Denis, tomstdenis@iahu.ca, http://libtomcrypt.org
  */
index 184b3a9..c0e17f3 100644 (file)
@@ -621,8 +621,7 @@ initsignal(void)
     if (Handlers[SIGINT].func == DefaultHandler) {
         /* Install default int handler */
         Py_INCREF(IntHandler);
-        Py_DECREF(Handlers[SIGINT].func);
-        Handlers[SIGINT].func = IntHandler;
+        Py_SETREF(Handlers[SIGINT].func, IntHandler);
         old_siginthandler = PyOS_setsig(SIGINT, signal_handler);
     }
 
index ced9343..cd6df92 100644 (file)
@@ -82,6 +82,11 @@ Local naming conventions:
 */
 
 #ifdef __APPLE__
+#include <AvailabilityMacros.h>
+/* for getaddrinfo thread safety test on old versions of OS X */
+#ifndef MAC_OS_X_VERSION_10_5
+#define MAC_OS_X_VERSION_10_5 1050
+#endif
   /*
    * inet_aton is not available on OSX 10.3, yet we want to use a binary
    * that was build on 10.4 or later to work on that release, weak linking
@@ -178,15 +183,32 @@ shutdown(how) -- shut down traffic in one or both directions\n\
 # define USE_GETHOSTBYNAME_LOCK
 #endif
 
-/* To use __FreeBSD_version */
+/* To use __FreeBSD_version, __OpenBSD__, and __NetBSD_Version__ */
 #ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 /* On systems on which getaddrinfo() is believed to not be thread-safe,
-   (this includes the getaddrinfo emulation) protect access with a lock. */
-#if defined(WITH_THREAD) && (defined(__APPLE__) || \
+   (this includes the getaddrinfo emulation) protect access with a lock.
+
+   getaddrinfo is thread-safe on Mac OS X 10.5 and later. Originally it was
+   a mix of code including an unsafe implementation from an old BSD's
+   libresolv. In 10.5 Apple reimplemented it as a safe IPC call to the
+   mDNSResponder process. 10.5 is the first be UNIX '03 certified, which
+   includes the requirement that getaddrinfo be thread-safe. See issue #25924.
+
+   It's thread-safe in OpenBSD starting with 5.4, released Nov 2013:
+   http://www.openbsd.org/plus54.html
+
+   It's thread-safe in NetBSD starting with 4.0, released Dec 2007:
+
+http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/net/getaddrinfo.c.diff?r1=1.82&r2=1.83
+*/
+#if defined(WITH_THREAD) && ( \
+    (defined(__APPLE__) && \
+        MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) || \
     (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
-    defined(__OpenBSD__) || defined(__NetBSD__) || \
+    (defined(__OpenBSD__) && OpenBSD+0 < 201311) || \
+    (defined(__NetBSD__) && __NetBSD_Version__+0 < 400000000) || \
     defined(__VMS) || !defined(HAVE_GETADDRINFO))
 #define USE_GETADDRINFO_LOCK
 #endif
index 7240cb4..ee44cab 100644 (file)
@@ -44,8 +44,8 @@ static PyObject *ZipImportError;
 static PyObject *zip_directory_cache = NULL;
 
 /* forward decls */
-static PyObject *read_directory(char *archive);
-static PyObject *get_data(char *archive, PyObject *toc_entry);
+static PyObject *read_directory(const char *archive);
+static PyObject *get_data(const char *archive, PyObject *toc_entry);
 static PyObject *get_module_code(ZipImporter *self, char *fullname,
                                  int *p_ispackage, char **p_modpath);
 
@@ -644,23 +644,43 @@ static PyTypeObject ZipImporter_Type = {
 
 /* implementation */
 
-/* Given a buffer, return the long that is represented by the first
+/* Given a buffer, return the unsigned int that is represented by the first
    4 bytes, encoded as little endian. This partially reimplements
    marshal.c:r_long() */
-static long
-get_long(unsigned char *buf) {
-    long x;
+static unsigned int
+get_uint32(const unsigned char *buf)
+{
+    unsigned int x;
     x =  buf[0];
-    x |= (long)buf[1] <<  8;
-    x |= (long)buf[2] << 16;
-    x |= (long)buf[3] << 24;
-#if SIZEOF_LONG > 4
-    /* Sign extension for 64-bit machines */
-    x |= -(x & 0x80000000L);
-#endif
+    x |= (unsigned int)buf[1] <<  8;
+    x |= (unsigned int)buf[2] << 16;
+    x |= (unsigned int)buf[3] << 24;
+    return x;
+}
+
+/* Given a buffer, return the unsigned int that is represented by the first
+   2 bytes, encoded as little endian. This partially reimplements
+   marshal.c:r_short() */
+static unsigned short
+get_uint16(const unsigned char *buf)
+{
+    unsigned short x;
+    x =  buf[0];
+    x |= (unsigned short)buf[1] <<  8;
     return x;
 }
 
+static void
+set_file_error(const char *archive, int eof)
+{
+    if (eof) {
+        PyErr_SetString(PyExc_EOFError, "EOF read where not expected");
+    }
+    else {
+        PyErr_SetFromErrnoWithFilename(PyExc_IOError, archive);
+    }
+}
+
 /*
    read_directory(archive) -> files dict (new reference)
 
@@ -683,18 +703,20 @@ get_long(unsigned char *buf) {
    data_size and file_offset are 0.
 */
 static PyObject *
-read_directory(char *archive)
+read_directory(const char *archive)
 {
     PyObject *files = NULL;
     FILE *fp;
-    long compress, crc, data_size, file_size, file_offset, date, time;
-    long header_offset, name_size, header_size, header_position;
-    long i, l, count;
+    unsigned short compress, time, date, name_size;
+    unsigned int crc, data_size, file_size, header_size, header_offset;
+    unsigned long file_offset, header_position;
+    unsigned long arc_offset;  /* Absolute offset to start of the zip-archive. */
+    unsigned int count, i;
+    unsigned char buffer[46];
     size_t length;
     char path[MAXPATHLEN + 5];
     char name[MAXPATHLEN + 5];
-    char *p, endof_central_dir[22];
-    long arc_offset; /* offset from beginning of file to start of zip-archive */
+    const char *errmsg = NULL;
 
     if (strlen(archive) > MAXPATHLEN) {
         PyErr_SetString(PyExc_OverflowError,
@@ -711,98 +733,145 @@ read_directory(char *archive)
     }
 
     if (fseek(fp, -22, SEEK_END) == -1) {
-        fclose(fp);
-        PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);
-        return NULL;
+        goto file_error;
     }
-    header_position = ftell(fp);
-    if (fread(endof_central_dir, 1, 22, fp) != 22) {
-        fclose(fp);
-        PyErr_Format(ZipImportError, "can't read Zip file: "
-                     "'%.200s'", archive);
-        return NULL;
+    header_position = (unsigned long)ftell(fp);
+    if (header_position == (unsigned long)-1) {
+        goto file_error;
+    }
+    assert(header_position <= (unsigned long)LONG_MAX);
+    if (fread(buffer, 1, 22, fp) != 22) {
+        goto file_error;
     }
-    if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
+    if (get_uint32(buffer) != 0x06054B50u) {
         /* Bad: End of Central Dir signature */
-        fclose(fp);
-        PyErr_Format(ZipImportError, "not a Zip file: "
-                     "'%.200s'", archive);
-        return NULL;
+        errmsg = "not a Zip file";
+        goto invalid_header;
     }
 
-    header_size = get_long((unsigned char *)endof_central_dir + 12);
-    header_offset = get_long((unsigned char *)endof_central_dir + 16);
-    arc_offset = header_position - header_offset - header_size;
-    header_offset += arc_offset;
+    header_size = get_uint32(buffer + 12);
+    header_offset = get_uint32(buffer + 16);
+    if (header_position < header_size) {
+        errmsg = "bad central directory size";
+        goto invalid_header;
+    }
+    if (header_position < header_offset) {
+        errmsg = "bad central directory offset";
+        goto invalid_header;
+    }
+    if (header_position - header_size < header_offset) {
+        errmsg = "bad central directory size or offset";
+        goto invalid_header;
+    }
+    header_position -= header_size;
+    arc_offset = header_position - header_offset;
 
     files = PyDict_New();
-    if (files == NULL)
+    if (files == NULL) {
         goto error;
+    }
 
     length = (long)strlen(path);
     path[length] = SEP;
 
     /* Start of Central Directory */
     count = 0;
+    if (fseek(fp, (long)header_position, 0) == -1) {
+        goto file_error;
+    }
     for (;;) {
         PyObject *t;
+        size_t n;
         int err;
 
-        if (fseek(fp, header_offset, 0) == -1)  /* Start of file header */
-            goto fseek_error;
-        l = PyMarshal_ReadLongFromFile(fp);
-        if (l != 0x02014B50)
+        n = fread(buffer, 1, 46, fp);
+        if (n < 4) {
+            goto eof_error;
+        }
+        /* Start of file header */
+        if (get_uint32(buffer) != 0x02014B50u) {
             break;              /* Bad: Central Dir File Header */
-        if (fseek(fp, header_offset + 10, 0) == -1)
-            goto fseek_error;
-        compress = PyMarshal_ReadShortFromFile(fp);
-        time = PyMarshal_ReadShortFromFile(fp);
-        date = PyMarshal_ReadShortFromFile(fp);
-        crc = PyMarshal_ReadLongFromFile(fp);
-        data_size = PyMarshal_ReadLongFromFile(fp);
-        file_size = PyMarshal_ReadLongFromFile(fp);
-        name_size = PyMarshal_ReadShortFromFile(fp);
-        header_size = 46 + name_size +
-           PyMarshal_ReadShortFromFile(fp) +
-           PyMarshal_ReadShortFromFile(fp);
-        if (fseek(fp, header_offset + 42, 0) == -1)
-            goto fseek_error;
-        file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
-        if (name_size > MAXPATHLEN)
-            name_size = MAXPATHLEN;
+        }
+        if (n != 46) {
+            goto eof_error;
+        }
+        compress = get_uint16(buffer + 10);
+        time = get_uint16(buffer + 12);
+        date = get_uint16(buffer + 14);
+        crc = get_uint32(buffer + 16);
+        data_size = get_uint32(buffer + 20);
+        file_size = get_uint32(buffer + 24);
+        name_size = get_uint16(buffer + 28);
+        header_size = (unsigned int)name_size +
+           get_uint16(buffer + 30) /* extra field */ +
+           get_uint16(buffer + 32) /* comment */;
+
+        file_offset = get_uint32(buffer + 42);
+        if (file_offset > header_offset) {
+            errmsg = "bad local header offset";
+            goto invalid_header;
+        }
+        file_offset += arc_offset;
 
-        p = name;
-        for (i = 0; i < name_size; i++) {
-            *p = (char)getc(fp);
-            if (*p == '/')
-                *p = SEP;
-            p++;
+        if (name_size > MAXPATHLEN) {
+            name_size = MAXPATHLEN;
+        }
+        if (fread(name, 1, name_size, fp) != name_size) {
+            goto file_error;
+        }
+        name[name_size] = '\0';  /* Add terminating null byte */
+        if (SEP != '/') {
+            for (i = 0; i < name_size; i++) {
+                if (name[i] == '/') {
+                    name[i] = SEP;
+                }
+            }
+        }
+        /* Skip the rest of the header.
+         * On Windows, calling fseek to skip over the fields we don't use is
+         * slower than reading the data because fseek flushes stdio's
+         * internal buffers.  See issue #8745. */
+        assert(header_size <= 3*0xFFFFu);
+        for (i = name_size; i < header_size; i++) {
+            if (getc(fp) == EOF) {
+                goto file_error;
+            }
         }
-        *p = 0;         /* Add terminating null byte */
-        header_offset += header_size;
 
         strncpy(path + length + 1, name, MAXPATHLEN - length - 1);
 
-        t = Py_BuildValue("siiiiiii", path, compress, data_size,
+        t = Py_BuildValue("sHIIkHHI", path, compress, data_size,
                           file_size, file_offset, time, date, crc);
-        if (t == NULL)
+        if (t == NULL) {
             goto error;
+        }
         err = PyDict_SetItemString(files, name, t);
         Py_DECREF(t);
-        if (err != 0)
+        if (err != 0) {
             goto error;
+        }
         count++;
     }
     fclose(fp);
-    if (Py_VerboseFlag)
-        PySys_WriteStderr("# zipimport: found %ld names in %s\n",
-            count, archive);
+    if (Py_VerboseFlag) {
+        PySys_WriteStderr("# zipimport: found %u names in %.200s\n",
+                           count, archive);
+    }
     return files;
-fseek_error:
-    fclose(fp);
-    Py_XDECREF(files);
-    PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);
-    return NULL;
+
+eof_error:
+    set_file_error(archive, !ferror(fp));
+    goto error;
+
+file_error:
+    PyErr_Format(ZipImportError, "can't read Zip file: %.200s", archive);
+    goto error;
+
+invalid_header:
+    assert(errmsg != NULL);
+    PyErr_Format(ZipImportError, "%s: %.200s", errmsg, archive);
+    goto error;
+
 error:
     fclose(fp);
     Py_XDECREF(files);
@@ -844,23 +913,28 @@ get_decompress_func(void)
 /* Given a path to a Zip file and a toc_entry, return the (uncompressed)
    data as a new reference. */
 static PyObject *
-get_data(char *archive, PyObject *toc_entry)
+get_data(const char *archive, PyObject *toc_entry)
 {
-    PyObject *raw_data, *data = NULL, *decompress;
+    PyObject *raw_data = NULL, *data, *decompress;
     char *buf;
     FILE *fp;
-    int err;
-    Py_ssize_t bytes_read = 0;
-    long l;
-    char *datapath;
-    long compress, data_size, file_size, file_offset;
-    long time, date, crc;
-
-    if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,
+    const char *datapath;
+    unsigned short compress, time, date;
+    unsigned int crc;
+    Py_ssize_t data_size, file_size;
+    long file_offset, header_size;
+    unsigned char buffer[30];
+    const char *errmsg = NULL;
+
+    if (!PyArg_ParseTuple(toc_entry, "sHnnlHHI", &datapath, &compress,
                           &data_size, &file_size, &file_offset, &time,
                           &date, &crc)) {
         return NULL;
     }
+    if (data_size < 0) {
+        PyErr_Format(ZipImportError, "negative data size");
+        return NULL;
+    }
 
     fp = fopen(archive, "rb");
     if (!fp) {
@@ -871,54 +945,51 @@ get_data(char *archive, PyObject *toc_entry)
 
     /* Check to make sure the local file header is correct */
     if (fseek(fp, file_offset, 0) == -1) {
-        fclose(fp);
-        PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);
-        return NULL;
+        goto file_error;
     }
-
-    l = PyMarshal_ReadLongFromFile(fp);
-    if (l != 0x04034B50) {
+    if (fread(buffer, 1, 30, fp) != 30) {
+        goto eof_error;
+    }
+    if (get_uint32(buffer) != 0x04034B50u) {
         /* Bad: Local File Header */
-        PyErr_Format(ZipImportError,
-                     "bad local file header in %s",
-                     archive);
-        fclose(fp);
-        return NULL;
+        errmsg = "bad local file header";
+        goto invalid_header;
     }
-    if (fseek(fp, file_offset + 26, 0) == -1) {
+
+    header_size = (unsigned int)30 +
+        get_uint16(buffer + 26) /* file name */ +
+        get_uint16(buffer + 28) /* extra field */;
+    if (file_offset > LONG_MAX - header_size) {
+        errmsg = "bad local file header size";
+        goto invalid_header;
+    }
+    file_offset += header_size;  /* Start of file data */
+
+    if (data_size > LONG_MAX - 1) {
         fclose(fp);
-        PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);
+        PyErr_NoMemory();
         return NULL;
     }
-
-    l = 30 + PyMarshal_ReadShortFromFile(fp) +
-        PyMarshal_ReadShortFromFile(fp);        /* local header size */
-    file_offset += l;           /* Start of file data */
-
     raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?
                                           data_size : data_size + 1);
+
     if (raw_data == NULL) {
-        fclose(fp);
-        return NULL;
+        goto error;
     }
     buf = PyString_AsString(raw_data);
 
-    err = fseek(fp, file_offset, 0);
-    if (err == 0) {
-        bytes_read = fread(buf, 1, data_size, fp);
-    } else {
-        fclose(fp);
-        PyErr_Format(ZipImportError, "can't read Zip file: %s", archive);
-        return NULL;
+    if (fseek(fp, file_offset, 0) == -1) {
+        goto file_error;
     }
-    fclose(fp);
-    if (err || bytes_read != data_size) {
+    if (fread(buf, 1, data_size, fp) != (size_t)data_size) {
         PyErr_SetString(PyExc_IOError,
                         "zipimport: can't read data");
-        Py_DECREF(raw_data);
-        return NULL;
+        goto error;
     }
 
+    fclose(fp);
+    fp = NULL;
+
     if (compress != 0) {
         buf[data_size] = 'Z';  /* saw this in zipfile.py */
         data_size++;
@@ -938,9 +1009,28 @@ get_data(char *archive, PyObject *toc_entry)
     }
     data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
     Py_DECREF(decompress);
-error:
     Py_DECREF(raw_data);
     return data;
+
+eof_error:
+    set_file_error(archive, !ferror(fp));
+    goto error;
+
+file_error:
+    PyErr_Format(ZipImportError, "can't read Zip file: %.200s", archive);
+    goto error;
+
+invalid_header:
+    assert(errmsg != NULL);
+    PyErr_Format(ZipImportError, "%s: %.200s", errmsg, archive);
+    goto error;
+
+error:
+    if (fp != NULL) {
+        fclose(fp);
+    }
+    Py_XDECREF(raw_data);
+    return NULL;
 }
 
 /* Lenient date/time comparison function. The precision of the mtime
@@ -962,38 +1052,40 @@ eq_mtime(time_t t1, time_t t2)
    to .py if available and we don't want to mask other errors).
    Returns a new reference. */
 static PyObject *
-unmarshal_code(char *pathname, PyObject *data, time_t mtime)
+unmarshal_code(const char *pathname, PyObject *data, time_t mtime)
 {
     PyObject *code;
-    char *buf = PyString_AsString(data);
+    unsigned char *buf = (unsigned char *)PyString_AsString(data);
     Py_ssize_t size = PyString_Size(data);
 
-    if (size <= 9) {
+    if (size < 8) {
         PyErr_SetString(ZipImportError,
                         "bad pyc data");
         return NULL;
     }
 
-    if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
-        if (Py_VerboseFlag)
+    if (get_uint32(buf) != (unsigned int)PyImport_GetMagicNumber()) {
+        if (Py_VerboseFlag) {
             PySys_WriteStderr("# %s has bad magic\n",
                               pathname);
+        }
         Py_INCREF(Py_None);
         return Py_None;  /* signal caller to try alternative */
     }
 
-    if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
-                                mtime)) {
-        if (Py_VerboseFlag)
+    if (mtime != 0 && !eq_mtime(get_uint32(buf + 4), mtime)) {
+        if (Py_VerboseFlag) {
             PySys_WriteStderr("# %s has bad mtime\n",
                               pathname);
+        }
         Py_INCREF(Py_None);
         return Py_None;  /* signal caller to try alternative */
     }
 
-    code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
-    if (code == NULL)
+    code = PyMarshal_ReadObjectFromString((char *)buf + 8, size - 8);
+    if (code == NULL) {
         return NULL;
+    }
     if (!PyCode_Check(code)) {
         Py_DECREF(code);
         PyErr_Format(PyExc_TypeError,
index 519af94..153a86c 100644 (file)
@@ -101,12 +101,12 @@ zlib_error(z_stream zst, int err, char *msg)
 PyDoc_STRVAR(compressobj__doc__,
 "compressobj([level]) -- Return a compressor object.\n"
 "\n"
-"Optional arg level is the compression level, in 0-9.");
+"Optional arg level is the compression level, in 0-9 or -1.");
 
 PyDoc_STRVAR(decompressobj__doc__,
 "decompressobj([wbits]) -- Return a decompressor object.\n"
 "\n"
-"Optional arg wbits is the window buffer size.");
+"Optional arg wbits indicates the window buffer size and container format.");
 
 static compobject *
 newcompobject(PyTypeObject *type)
@@ -208,8 +208,8 @@ PyZlib_compress(PyObject *self, PyObject *args)
 PyDoc_STRVAR(decompress__doc__,
 "decompress(string[, wbits[, bufsize]]) -- Return decompressed string.\n"
 "\n"
-"Optional arg wbits is the window buffer size.  Optional arg bufsize is\n"
-"the initial output buffer size.");
+"Optional arg wbits indicates the window buffer size and container format.\n"
+"Optional arg bufsize is the initial output buffer size.");
 
 static PyObject *
 PyZlib_decompress(PyObject *self, PyObject *args)
@@ -491,8 +491,7 @@ save_unconsumed_input(compobject *self, int err)
                       PyString_AS_STRING(self->unused_data), old_size);
             Py_MEMCPY(PyString_AS_STRING(new_data) + old_size,
                       self->zst.next_in, self->zst.avail_in);
-            Py_DECREF(self->unused_data);
-            self->unused_data = new_data;
+            Py_SETREF(self->unused_data, new_data);
             self->zst.avail_in = 0;
         }
     }
@@ -504,8 +503,7 @@ save_unconsumed_input(compobject *self, int err)
                 (char *)self->zst.next_in, self->zst.avail_in);
         if (new_data == NULL)
             return -1;
-        Py_DECREF(self->unconsumed_tail);
-        self->unconsumed_tail = new_data;
+        Py_SETREF(self->unconsumed_tail, new_data);
     }
     return 0;
 }
@@ -733,11 +731,9 @@ PyZlib_copy(compobject *self)
     }
 
     Py_INCREF(self->unused_data);
+    Py_XSETREF(retval->unused_data, self->unused_data);
     Py_INCREF(self->unconsumed_tail);
-    Py_XDECREF(retval->unused_data);
-    Py_XDECREF(retval->unconsumed_tail);
-    retval->unused_data = self->unused_data;
-    retval->unconsumed_tail = self->unconsumed_tail;
+    Py_XSETREF(retval->unconsumed_tail, self->unconsumed_tail);
 
     /* Mark it as being initialized */
     retval->is_initialised = 1;
@@ -784,11 +780,9 @@ PyZlib_uncopy(compobject *self)
     }
 
     Py_INCREF(self->unused_data);
+    Py_XSETREF(retval->unused_data, self->unused_data);
     Py_INCREF(self->unconsumed_tail);
-    Py_XDECREF(retval->unused_data);
-    Py_XDECREF(retval->unconsumed_tail);
-    retval->unused_data = self->unused_data;
-    retval->unconsumed_tail = self->unconsumed_tail;
+    Py_XSETREF(retval->unconsumed_tail, self->unconsumed_tail);
 
     /* Mark it as being initialized */
     retval->is_initialised = 1;
@@ -1045,7 +1039,7 @@ PyDoc_STRVAR(zlib_module_documentation,
 "decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string.\n"
 "decompressobj([wbits]) -- Return a decompressor object.\n"
 "\n"
-"'wbits' is window buffer size.\n"
+"'wbits' is window buffer size and container format.\n"
 "Compressor objects support compress() and flush() methods; decompressor\n"
 "objects support decompress() and flush().");
 
index 5276da5..a90bdeb 100644 (file)
@@ -2395,23 +2395,21 @@ static PyObject *
 bytearray_remove(PyByteArrayObject *self, PyObject *arg)
 {
     int value;
-    Py_ssize_t where, n = Py_SIZE(self);
+    Py_ssize_t n = Py_SIZE(self);
+    char *where;
 
     if (! _getbytevalue(arg, &value))
         return NULL;
 
-    for (where = 0; where < n; where++) {
-        if (self->ob_bytes[where] == value)
-            break;
-    }
-    if (where == n) {
+    where = memchr(self->ob_bytes, value, n);
+    if (!where) {
         PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
         return NULL;
     }
     if (!_canresize(self))
         return NULL;
 
-    memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
+    memmove(where, where + 1, self->ob_bytes + n - where);
     if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
         return NULL;
 
@@ -2780,7 +2778,7 @@ bytearray_sizeof(PyByteArrayObject *self)
 {
     Py_ssize_t res;
 
-    res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
+    res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char);
     return PyInt_FromSsize_t(res);
 }
 
@@ -2883,7 +2881,7 @@ bytearray(string, encoding[, errors]) -> bytearray.\n\
 bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray.\n\
 bytearray(memory_view) -> bytearray.\n\
 \n\
-Construct an mutable bytearray object from:\n\
+Construct a mutable bytearray object from:\n\
   - an iterable yielding integers in range(256)\n\
   - a text string encoded using the specified encoding\n\
   - a bytes or a bytearray object\n\
@@ -2982,8 +2980,8 @@ bytearrayiter_next(bytesiterobject *it)
         return item;
     }
 
-    Py_DECREF(seq);
     it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
index d0f6cda..c206684 100644 (file)
@@ -116,8 +116,8 @@ PyTypeObject PyCell_Type = {
     "cell",
     sizeof(PyCellObject),
     0,
-    (destructor)cell_dealloc,               /* tp_dealloc */
-    0,                                      /* tp_print */
+    (destructor)cell_dealloc,                   /* tp_dealloc */
+    0,                                          /* tp_print */
     0,                                          /* tp_getattr */
     0,                                          /* tp_setattr */
     (cmpfunc)cell_compare,                      /* tp_compare */
@@ -131,7 +131,7 @@ PyTypeObject PyCell_Type = {
     PyObject_GenericGetAttr,                    /* tp_getattro */
     0,                                          /* tp_setattro */
     0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
     0,                                          /* tp_doc */
     (traverseproc)cell_traverse,                /* tp_traverse */
     (inquiry)cell_clear,                        /* tp_clear */
index 9879df5..c104098 100644 (file)
@@ -376,11 +376,140 @@ code_compare(PyCodeObject *co, PyCodeObject *cp)
         return 0;
 }
 
+PyObject*
+_PyCode_ConstantKey(PyObject *op)
+{
+    PyObject *key;
+
+    /* Py_None is a singleton */
+    if (op == Py_None
+       || PyInt_CheckExact(op)
+       || PyLong_CheckExact(op)
+       || PyBool_Check(op)
+       || PyBytes_CheckExact(op)
+#ifdef Py_USING_UNICODE
+       || PyUnicode_CheckExact(op)
+#endif
+          /* code_richcompare() uses _PyCode_ConstantKey() internally */
+       || PyCode_Check(op)) {
+        key = PyTuple_Pack(2, Py_TYPE(op), op);
+    }
+    else if (PyFloat_CheckExact(op)) {
+        double d = PyFloat_AS_DOUBLE(op);
+        /* all we need is to make the tuple different in either the 0.0
+         * or -0.0 case from all others, just to avoid the "coercion".
+         */
+        if (d == 0.0 && copysign(1.0, d) < 0.0)
+            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
+        else
+            key = PyTuple_Pack(2, Py_TYPE(op), op);
+    }
+#ifndef WITHOUT_COMPLEX
+    else if (PyComplex_CheckExact(op)) {
+        Py_complex z;
+        int real_negzero, imag_negzero;
+        /* For the complex case we must make complex(x, 0.)
+           different from complex(x, -0.) and complex(0., y)
+           different from complex(-0., y), for any x and y.
+           All four complex zeros must be distinguished.*/
+        z = PyComplex_AsCComplex(op);
+        real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
+        imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
+        /* use True, False and None singleton as tags for the real and imag
+         * sign, to make tuples different */
+        if (real_negzero && imag_negzero) {
+            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
+        }
+        else if (imag_negzero) {
+            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
+        }
+        else if (real_negzero) {
+            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
+        }
+        else {
+            key = PyTuple_Pack(2, Py_TYPE(op), op);
+        }
+    }
+#endif
+    else if (PyTuple_CheckExact(op)) {
+        Py_ssize_t i, len;
+        PyObject *tuple;
+
+        len = PyTuple_GET_SIZE(op);
+        tuple = PyTuple_New(len);
+        if (tuple == NULL)
+            return NULL;
+
+        for (i=0; i < len; i++) {
+            PyObject *item, *item_key;
+
+            item = PyTuple_GET_ITEM(op, i);
+            item_key = _PyCode_ConstantKey(item);
+            if (item_key == NULL) {
+                Py_DECREF(tuple);
+                return NULL;
+            }
+
+            PyTuple_SET_ITEM(tuple, i, item_key);
+        }
+
+        key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
+        Py_DECREF(tuple);
+    }
+    else if (PyFrozenSet_CheckExact(op)) {
+        Py_ssize_t pos = 0;
+        PyObject *item;
+        long hash;
+        Py_ssize_t i, len;
+        PyObject *tuple, *set;
+
+        len = PySet_GET_SIZE(op);
+        tuple = PyTuple_New(len);
+        if (tuple == NULL)
+            return NULL;
+
+        i = 0;
+        while (_PySet_NextEntry(op, &pos, &item, &hash)) {
+            PyObject *item_key;
+
+            item_key = _PyCode_ConstantKey(item);
+            if (item_key == NULL) {
+                Py_DECREF(tuple);
+                return NULL;
+            }
+
+            assert(i < len);
+            PyTuple_SET_ITEM(tuple, i, item_key);
+            i++;
+        }
+        set = PyFrozenSet_New(tuple);
+        Py_DECREF(tuple);
+        if (set == NULL)
+            return NULL;
+
+        key = PyTuple_Pack(3, Py_TYPE(op), op, set);
+        Py_DECREF(set);
+        return key;
+    }
+    else {
+        /* for other types, use the object identifier as a unique identifier
+         * to ensure that they are seen as unequal. */
+        PyObject *obj_id = PyLong_FromVoidPtr(op);
+        if (obj_id == NULL)
+            return NULL;
+
+        key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
+        Py_DECREF(obj_id);
+    }
+    return key;
+}
+
 static PyObject *
 code_richcompare(PyObject *self, PyObject *other, int op)
 {
     PyCodeObject *co, *cp;
     int eq;
+    PyObject *consts1, *consts2;
     PyObject *res;
 
     if ((op != Py_EQ && op != Py_NE) ||
@@ -413,8 +542,21 @@ code_richcompare(PyObject *self, PyObject *other, int op)
     if (!eq) goto unequal;
     eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
     if (eq <= 0) goto unequal;
-    eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ);
+
+    /* compare constants */
+    consts1 = _PyCode_ConstantKey(co->co_consts);
+    if (!consts1)
+        return NULL;
+    consts2 = _PyCode_ConstantKey(cp->co_consts);
+    if (!consts2) {
+        Py_DECREF(consts1);
+        return NULL;
+    }
+    eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
+    Py_DECREF(consts1);
+    Py_DECREF(consts2);
     if (eq <= 0) goto unequal;
+
     eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
     if (eq <= 0) goto unequal;
     eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
index 886a451..8d6e6e3 100644 (file)
@@ -1332,8 +1332,7 @@ property_init(PyObject *self, PyObject *args, PyObject *kwds)
         PyObject *get_doc = PyObject_GetAttrString(get, "__doc__");
         if (get_doc) {
             if (Py_TYPE(self) == &PyProperty_Type) {
-                Py_XDECREF(prop->prop_doc);
-                prop->prop_doc = get_doc;
+                Py_XSETREF(prop->prop_doc, get_doc);
             }
             else {
                 /* If this is a property subclass, put __doc__
index 50afa3f..e3e4765 100644 (file)
@@ -749,6 +749,36 @@ PyDict_GetItem(PyObject *op, PyObject *key)
     return ep->me_value;
 }
 
+/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
+   This returns NULL *with* an exception set if an exception occurred.
+   It returns NULL *without* an exception set if the key wasn't present.
+*/
+PyObject *
+_PyDict_GetItemWithError(PyObject *op, PyObject *key)
+{
+    long hash;
+    PyDictObject *mp = (PyDictObject *)op;
+    PyDictEntry *ep;
+    if (!PyDict_Check(op)) {
+        PyErr_BadInternalCall();
+        return NULL;
+    }
+    if (!PyString_CheckExact(key) ||
+        (hash = ((PyStringObject *) key)->ob_shash) == -1)
+    {
+        hash = PyObject_Hash(key);
+        if (hash == -1) {
+            return NULL;
+        }
+    }
+
+    ep = (mp->ma_lookup)(mp, key, hash);
+    if (ep == NULL) {
+        return NULL;
+    }
+    return ep->me_value;
+}
+
 static int
 dict_set_item_by_hash_or_entry(register PyObject *op, PyObject *key,
                                long hash, PyDictEntry *ep, PyObject *value)
@@ -2152,7 +2182,7 @@ dict_sizeof(PyDictObject *mp)
 {
     Py_ssize_t res;
 
-    res = sizeof(PyDictObject);
+    res = _PyObject_SIZE(Py_TYPE(mp));
     if (mp->ma_table != mp->ma_smalltable)
         res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry);
     return PyInt_FromSsize_t(res);
@@ -2556,8 +2586,8 @@ static PyObject *dictiter_iternextkey(dictiterobject *di)
     return key;
 
 fail:
-    Py_DECREF(d);
     di->di_dict = NULL;
+    Py_DECREF(d);
     return NULL;
 }
 
@@ -2628,8 +2658,8 @@ static PyObject *dictiter_iternextvalue(dictiterobject *di)
     return value;
 
 fail:
-    Py_DECREF(d);
     di->di_dict = NULL;
+    Py_DECREF(d);
     return NULL;
 }
 
@@ -2714,8 +2744,8 @@ static PyObject *dictiter_iternextitem(dictiterobject *di)
     return result;
 
 fail:
-    Py_DECREF(d);
     di->di_dict = NULL;
+    Py_DECREF(d);
     return NULL;
 }
 
@@ -2968,7 +2998,8 @@ dictviews_sub(PyObject* self, PyObject *other)
     if (result == NULL)
         return NULL;
 
-    tmp = PyObject_CallMethod(result, "difference_update", "O", other);
+
+    tmp = PyObject_CallMethod(result, "difference_update", "(O)", other);
     if (tmp == NULL) {
         Py_DECREF(result);
         return NULL;
@@ -2986,7 +3017,7 @@ dictviews_and(PyObject* self, PyObject *other)
     if (result == NULL)
         return NULL;
 
-    tmp = PyObject_CallMethod(result, "intersection_update", "O", other);
+    tmp = PyObject_CallMethod(result, "intersection_update", "(O)", other);
     if (tmp == NULL) {
         Py_DECREF(result);
         return NULL;
@@ -3004,7 +3035,7 @@ dictviews_or(PyObject* self, PyObject *other)
     if (result == NULL)
         return NULL;
 
-    tmp = PyObject_CallMethod(result, "update", "O", other);
+    tmp = PyObject_CallMethod(result, "update", "(O)", other);
     if (tmp == NULL) {
         Py_DECREF(result);
         return NULL;
@@ -3022,8 +3053,7 @@ dictviews_xor(PyObject* self, PyObject *other)
     if (result == NULL)
         return NULL;
 
-    tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O",
-                              other);
+    tmp = PyObject_CallMethod(result, "symmetric_difference_update", "(O)", other);
     if (tmp == NULL) {
         Py_DECREF(result);
         return NULL;
index e165528..3fc0e13 100644 (file)
@@ -58,14 +58,12 @@ BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
     if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
         return -1;
 
-    Py_DECREF(self->args);
-    self->args = args;
-    Py_INCREF(self->args);
+    Py_INCREF(args);
+    Py_SETREF(self->args, args);
 
     if (PyTuple_GET_SIZE(self->args) == 1) {
-        Py_CLEAR(self->message);
-        self->message = PyTuple_GET_ITEM(self->args, 0);
-        Py_INCREF(self->message);
+        Py_INCREF(PyTuple_GET_ITEM(self->args, 0));
+        Py_XSETREF(self->message, PyTuple_GET_ITEM(self->args, 0));
     }
     return 0;
 }
@@ -280,9 +278,8 @@ BaseException_set_dict(PyBaseExceptionObject *self, PyObject *val)
         PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary");
         return -1;
     }
-    Py_CLEAR(self->dict);
     Py_INCREF(val);
-    self->dict = val;
+    Py_XSETREF(self->dict, val);
     return 0;
 }
 
@@ -308,8 +305,7 @@ BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
     seq = PySequence_Tuple(val);
     if (!seq)
         return -1;
-    Py_CLEAR(self->args);
-    self->args = seq;
+    Py_XSETREF(self->args, seq);
     return 0;
 }
 
@@ -521,12 +517,14 @@ SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
 
     if (size == 0)
         return 0;
-    Py_CLEAR(self->code);
-    if (size == 1)
-        self->code = PyTuple_GET_ITEM(args, 0);
-    else if (size > 1)
-        self->code = args;
-    Py_INCREF(self->code);
+    if (size == 1) {
+        Py_INCREF(PyTuple_GET_ITEM(args, 0));
+        Py_XSETREF(self->code, PyTuple_GET_ITEM(args, 0));
+    }
+    else { /* size > 1 */
+        Py_INCREF(args);
+        Py_XSETREF(self->code, args);
+    }
     return 0;
 }
 
@@ -609,26 +607,22 @@ EnvironmentError_init(PyEnvironmentErrorObject *self, PyObject *args,
                            &myerrno, &strerror, &filename)) {
         return -1;
     }
-    Py_CLEAR(self->myerrno);       /* replacing */
-    self->myerrno = myerrno;
-    Py_INCREF(self->myerrno);
+    Py_INCREF(myerrno);
+    Py_XSETREF(self->myerrno, myerrno);
 
-    Py_CLEAR(self->strerror);      /* replacing */
-    self->strerror = strerror;
-    Py_INCREF(self->strerror);
+    Py_INCREF(strerror);
+    Py_XSETREF(self->strerror, strerror);
 
     /* self->filename will remain Py_None otherwise */
     if (filename != NULL) {
-        Py_CLEAR(self->filename);      /* replacing */
-        self->filename = filename;
-        Py_INCREF(self->filename);
+        Py_INCREF(filename);
+        Py_XSETREF(self->filename, filename);
 
         subslice = PyTuple_GetSlice(args, 0, 2);
         if (!subslice)
             return -1;
 
-        Py_DECREF(self->args);  /* replacing args */
-        self->args = subslice;
+        Py_SETREF(self->args, subslice);
     }
     return 0;
 }
@@ -879,8 +873,7 @@ WindowsError_init(PyWindowsErrorObject *self, PyObject *args, PyObject *kwds)
         return -1;
     posix_errno = winerror_to_errno(errcode);
 
-    Py_CLEAR(self->winerror);
-    self->winerror = self->myerrno;
+    Py_XSETREF(self->winerror, self->myerrno);
 
     o_errcode = PyInt_FromLong(posix_errno);
     if (!o_errcode)
@@ -1065,9 +1058,8 @@ SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
         return -1;
 
     if (lenargs >= 1) {
-        Py_CLEAR(self->msg);
-        self->msg = PyTuple_GET_ITEM(args, 0);
-        Py_INCREF(self->msg);
+        Py_INCREF(PyTuple_GET_ITEM(args, 0));
+        Py_XSETREF(self->msg, PyTuple_GET_ITEM(args, 0));
     }
     if (lenargs == 2) {
         info = PyTuple_GET_ITEM(args, 1);
@@ -1082,21 +1074,17 @@ SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
             return -1;
         }
 
-        Py_CLEAR(self->filename);
-        self->filename = PyTuple_GET_ITEM(info, 0);
-        Py_INCREF(self->filename);
+        Py_INCREF(PyTuple_GET_ITEM(info, 0));
+        Py_XSETREF(self->filename, PyTuple_GET_ITEM(info, 0));
 
-        Py_CLEAR(self->lineno);
-        self->lineno = PyTuple_GET_ITEM(info, 1);
-        Py_INCREF(self->lineno);
+        Py_INCREF(PyTuple_GET_ITEM(info, 1));
+        Py_XSETREF(self->lineno, PyTuple_GET_ITEM(info, 1));
 
-        Py_CLEAR(self->offset);
-        self->offset = PyTuple_GET_ITEM(info, 2);
-        Py_INCREF(self->offset);
+        Py_INCREF(PyTuple_GET_ITEM(info, 2));
+        Py_XSETREF(self->offset, PyTuple_GET_ITEM(info, 2));
 
-        Py_CLEAR(self->text);
-        self->text = PyTuple_GET_ITEM(info, 3);
-        Py_INCREF(self->text);
+        Py_INCREF(PyTuple_GET_ITEM(info, 3));
+        Py_XSETREF(self->text, PyTuple_GET_ITEM(info, 3));
 
         Py_DECREF(info);
     }
@@ -1329,8 +1317,7 @@ set_string(PyObject **attr, const char *value)
     PyObject *obj = PyString_FromString(value);
     if (!obj)
         return -1;
-    Py_CLEAR(*attr);
-    *attr = obj;
+    Py_XSETREF(*attr, obj);
     return 0;
 }
 
index 55e074b..b29da8a 100644 (file)
@@ -574,10 +574,8 @@ PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
         oerrors = Py_None;
         Py_INCREF(Py_None);
     }
-    Py_DECREF(file->f_encoding);
-    file->f_encoding = str;
-    Py_DECREF(file->f_errors);
-    file->f_errors = oerrors;
+    Py_SETREF(file->f_encoding, str);
+    Py_SETREF(file->f_errors, oerrors);
     return 1;
 }
 
@@ -837,7 +835,7 @@ file_truncate(PyFileObject *f, PyObject *args)
     if (initialpos == -1)
         goto onioerror;
 
-    /* Set newsize to current postion if newsizeobj NULL, else to the
+    /* Set newsize to current position if newsizeobj NULL, else to the
      * specified value.
      */
     if (newsizeobj != NULL) {
index 1143fab..82cb28d 100644 (file)
@@ -407,7 +407,7 @@ float_str(PyFloatObject *v)
  * may lose info from fractional bits.  Converting the integer to a double
  * also has two failure modes:  (1) a long int may trigger overflow (too
  * large to fit in the dynamic range of a C double); (2) even a C long may have
- * more bits than fit in a C double (e.g., on a 64-bit box long may have
+ * more bits than fit in a C double (e.g., on a 64-bit box long may have
  * 63 bits of precision, but a C double probably has only 53), and then
  * we can falsely claim equality when low-order integer bits are lost by
  * coercion to double.  So this part is painful too.
@@ -1839,7 +1839,7 @@ float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     tmp = float_new(&PyFloat_Type, args, kwds);
     if (tmp == NULL)
         return NULL;
-    assert(PyFloat_CheckExact(tmp));
+    assert(PyFloat_Check(tmp));
     newobj = type->tp_alloc(type, 0);
     if (newobj == NULL) {
         Py_DECREF(tmp);
index f9e4a0e..2c8fb01 100644 (file)
@@ -364,15 +364,13 @@ frame_gettrace(PyFrameObject *f, void *closure)
 static int
 frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
 {
-    PyObject* old_value;
-
     /* We rely on f_lineno being accurate when f_trace is set. */
     f->f_lineno = PyFrame_GetLineNumber(f);
 
-    old_value = f->f_trace;
+    if (v == Py_None)
+        v = NULL;
     Py_XINCREF(v);
-    f->f_trace = v;
-    Py_XDECREF(old_value);
+    Py_XSETREF(f->f_trace, v);
 
     return 0;
 }
@@ -859,8 +857,7 @@ dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
             }
         } else if (values[j] != value) {
             Py_XINCREF(value);
-            Py_XDECREF(values[j]);
-            values[j] = value;
+            Py_XSETREF(values[j], value);
         }
         Py_XDECREF(value);
     }
index 51b6c9d..0e76a44 100644 (file)
@@ -116,8 +116,7 @@ PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
         PyErr_SetString(PyExc_SystemError, "non-tuple default args");
         return -1;
     }
-    Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
-    ((PyFunctionObject *) op) -> func_defaults = defaults;
+    Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
     return 0;
 }
 
@@ -149,8 +148,7 @@ PyFunction_SetClosure(PyObject *op, PyObject *closure)
                      closure->ob_type->tp_name);
         return -1;
     }
-    Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
-    ((PyFunctionObject *) op) -> func_closure = closure;
+    Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
     return 0;
 }
 
@@ -430,8 +428,7 @@ func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
 
     if (name != Py_None) {
         Py_INCREF(name);
-        Py_DECREF(newfunc->func_name);
-        newfunc->func_name = name;
+        Py_SETREF(newfunc->func_name, name);
     }
     if (defaults != Py_None) {
         Py_INCREF(defaults);
index 9c90abe..346d2d9 100644 (file)
@@ -69,8 +69,8 @@ iter_iternext(PyObject *iterator)
         PyErr_ExceptionMatches(PyExc_StopIteration))
     {
         PyErr_Clear();
-        Py_DECREF(seq);
         it->it_seq = NULL;
+        Py_DECREF(seq);
     }
     return NULL;
 }
index 1f43ba2..c414620 100644 (file)
@@ -2469,7 +2469,7 @@ list_sizeof(PyListObject *self)
 {
     Py_ssize_t res;
 
-    res = sizeof(PyListObject) + self->allocated * sizeof(void*);
+    res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
     return PyInt_FromSsize_t(res);
 }
 
@@ -2915,8 +2915,8 @@ listiter_next(listiterobject *it)
         return item;
     }
 
-    Py_DECREF(seq);
     it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
@@ -3018,9 +3018,17 @@ static PyObject *
 listreviter_next(listreviterobject *it)
 {
     PyObject *item;
-    Py_ssize_t index = it->it_index;
-    PyListObject *seq = it->it_seq;
+    Py_ssize_t index;
+    PyListObject *seq;
+
+    assert(it != NULL);
+    seq = it->it_seq;
+    if (seq == NULL) {
+        return NULL;
+    }
+    assert(PyList_Check(seq));
 
+    index = it->it_index;
     if (index>=0 && index < PyList_GET_SIZE(seq)) {
         item = PyList_GET_ITEM(seq, index);
         it->it_index--;
@@ -3028,10 +3036,8 @@ listreviter_next(listreviterobject *it)
         return item;
     }
     it->it_index = -1;
-    if (seq != NULL) {
-        it->it_seq = NULL;
-        Py_DECREF(seq);
-    }
+    it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
index 405be2e..6427f42 100644 (file)
@@ -4068,7 +4068,7 @@ long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
     if (tmp == NULL)
         return NULL;
-    assert(PyLong_CheckExact(tmp));
+    assert(PyLong_Check(tmp));
     n = Py_SIZE(tmp);
     if (n < 0)
         n = -n;
index 14f4e9f..7a28218 100644 (file)
@@ -2358,7 +2358,7 @@ PyMem_Free(void *p)
 
 /* These methods are used to control infinite recursion in repr, str, print,
    etc.  Container objects that may recursively contain themselves,
-   e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
+   e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
    Py_ReprLeave() to avoid infinite recursion.
 
    Py_ReprEnter() returns 0 the first time it is called for a particular
index 8a58d65..b3ca643 100644 (file)
@@ -2,9 +2,6 @@
 /* set object implementation
    Written and maintained by Raymond D. Hettinger <python@rcn.com>
    Derived from Lib/sets.py and Objects/dictobject.c.
-
-   Copyright (c) 2003-2007 Python Software Foundation.
-   All rights reserved.
 */
 
 #include "Python.h"
@@ -787,7 +784,7 @@ frozenset_hash(PyObject *self)
     hash *= PySet_GET_SIZE(self) + 1;
     while (set_next(so, &pos, &entry)) {
         /* Work to increase the bit dispersion for closely spaced hash
-           values.  The is important because some use cases have many
+           values.  This is important because some use cases have many
            combinations of a small number of elements with nearby
            hashes so that many distinct combinations collapse to only
            a handful of distinct hash values. */
@@ -874,8 +871,8 @@ static PyObject *setiter_iternext(setiterobject *si)
     return key;
 
 fail:
-    Py_DECREF(so);
     si->si_set = NULL;
+    Py_DECREF(so);
     return NULL;
 }
 
@@ -1985,7 +1982,7 @@ set_sizeof(PySetObject *so)
 {
     Py_ssize_t res;
 
-    res = sizeof(PySetObject);
+    res = _PyObject_SIZE(Py_TYPE(so));
     if (so->table != so->smalltable)
         res = res + (so->mask + 1) * sizeof(setentry);
     return PyInt_FromSsize_t(res);
index 767a50a..3c996f9 100644 (file)
@@ -60,7 +60,7 @@ PyObject _Py_EllipsisObject = {
 PyObject *
 PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
 {
-    PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type);
+    PySliceObject *obj = PyObject_GC_New(PySliceObject, &PySlice_Type);
 
     if (obj == NULL)
         return NULL;
@@ -76,6 +76,7 @@ PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
     obj->start = start;
     obj->stop = stop;
 
+    _PyObject_GC_TRACK(obj);
     return (PyObject *) obj;
 }
 
@@ -219,10 +220,11 @@ Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).");
 static void
 slice_dealloc(PySliceObject *r)
 {
+    _PyObject_GC_UNTRACK(r);
     Py_DECREF(r->step);
     Py_DECREF(r->start);
     Py_DECREF(r->stop);
-    PyObject_Del(r);
+    PyObject_GC_Del(r);
 }
 
 static PyObject *
@@ -320,6 +322,15 @@ slice_hash(PySliceObject *v)
     return -1L;
 }
 
+static int
+slice_traverse(PySliceObject *v, visitproc visit, void *arg)
+{
+    Py_VISIT(v->start);
+    Py_VISIT(v->stop);
+    Py_VISIT(v->step);
+    return 0;
+}
+
 PyTypeObject PySlice_Type = {
     PyVarObject_HEAD_INIT(&PyType_Type, 0)
     "slice",                    /* Name of this type */
@@ -340,9 +351,9 @@ PyTypeObject PySlice_Type = {
     PyObject_GenericGetAttr,                    /* tp_getattro */
     0,                                          /* tp_setattro */
     0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
     slice_doc,                                  /* tp_doc */
-    0,                                          /* tp_traverse */
+    (traverseproc)slice_traverse,               /* tp_traverse */
     0,                                          /* tp_clear */
     0,                                          /* tp_richcompare */
     0,                                          /* tp_weaklistoffset */
index b75755e..1ac6277 100644 (file)
@@ -995,7 +995,7 @@ format_float_internal(PyObject *value,
     if (precision < 0)
         precision = default_precision;
 
-    /* Cast "type", because if we're in unicode we need to pass a
+    /* Cast "type", because if we're in unicode we need to pass an
        8-bit char. This is safe, because we've restricted what "type"
        can be. */
     buf = PyOS_double_to_string(val, (char)type, precision, flags,
@@ -1175,7 +1175,7 @@ format_complex_internal(PyObject *value,
     if (precision < 0)
         precision = default_precision;
 
-    /* Cast "type", because if we're in unicode we need to pass a
+    /* Cast "type", because if we're in unicode we need to pass an
        8-bit char. This is safe, because we've restricted what "type"
        can be. */
     re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
index 965e1ad..2bd1839 100644 (file)
@@ -1310,7 +1310,7 @@ static PyTypeObject PyFieldNameIter_Type = {
     0};
 
 /* unicode_formatter_field_name_split is used to implement
-   string.Formatter.vformat.  it takes an PEP 3101 "field name", and
+   string.Formatter.vformat.  it takes a PEP 3101 "field name", and
    returns a tuple of (first, rest): "first", the part before the
    first '.' or '['; and "rest", an iterator for the rest of the field
    name.  it's a wrapper around stringlib/string_format.h's
index c1e12a7..f2db6da 100644 (file)
@@ -35,7 +35,7 @@ static PyObject *interned;
    For PyString_FromString(), the parameter `str' points to a null-terminated
    string containing exactly `size' bytes.
 
-   For PyString_FromStringAndSize(), the parameter the parameter `str' is
+   For PyString_FromStringAndSize(), the parameter `str' is
    either NULL or else points to a string containing at least `size' bytes.
    For PyString_FromStringAndSize(), the string in the `str' parameter does
    not have to be null-terminated.  (Therefore it is safe to construct a
@@ -1627,7 +1627,7 @@ string_join(PyStringObject *self, PyObject *orig)
 #ifdef Py_USING_UNICODE
             if (PyUnicode_Check(item)) {
                 /* Defer to Unicode join.
-                 * CAUTION:  There's no gurantee that the
+                 * CAUTION:  There's no guarantee that the
                  * original sequence can be iterated over
                  * again, so we must pass seq here.
                  */
@@ -3719,7 +3719,7 @@ str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     tmp = string_new(&PyString_Type, args, kwds);
     if (tmp == NULL)
         return NULL;
-    assert(PyString_CheckExact(tmp));
+    assert(PyString_Check(tmp));
     n = PyString_GET_SIZE(tmp);
     pnew = type->tp_alloc(type, n);
     if (pnew != NULL) {
@@ -3865,8 +3865,7 @@ PyString_Concat(register PyObject **pv, register PyObject *w)
         return;
     }
     v = string_concat((PyStringObject *) *pv, w);
-    Py_DECREF(*pv);
-    *pv = v;
+    Py_SETREF(*pv, v);
 }
 
 void
@@ -4751,8 +4750,7 @@ PyString_InternInPlace(PyObject **p)
     t = PyDict_GetItem(interned, (PyObject *)s);
     if (t) {
         Py_INCREF(t);
-        Py_DECREF(*p);
-        *p = t;
+        Py_SETREF(*p, t);
         return;
     }
 
index 5d72806..550719f 100644 (file)
@@ -966,8 +966,8 @@ tupleiter_next(tupleiterobject *it)
         return item;
     }
 
-    Py_DECREF(seq);
     it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
index 720a84e..cae5118 100644 (file)
    MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
    strings are used as attribute names. */
 #define MCACHE_MAX_ATTR_SIZE    100
-#define MCACHE_SIZE_EXP         10
+#define MCACHE_SIZE_EXP         12
 #define MCACHE_HASH(version, name_hash)                                 \
-        (((unsigned int)(version) * (unsigned int)(name_hash))          \
-         >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
+        (((unsigned int)(version) ^ (unsigned int)(name_hash))          \
+         & ((1 << MCACHE_SIZE_EXP) - 1))
+
 #define MCACHE_HASH_METHOD(type, name)                                  \
         MCACHE_HASH((type)->tp_version_tag,                     \
                     ((PyStringObject *)(name))->ob_shash)
@@ -33,12 +34,32 @@ struct method_cache_entry {
 static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
 static unsigned int next_version_tag = 0;
 
+#define MCACHE_STATS 0
+
+#if MCACHE_STATS
+static size_t method_cache_hits = 0;
+static size_t method_cache_misses = 0;
+static size_t method_cache_collisions = 0;
+#endif
+
 unsigned int
 PyType_ClearCache(void)
 {
     Py_ssize_t i;
     unsigned int cur_version_tag = next_version_tag - 1;
 
+#if MCACHE_STATS
+    size_t total = method_cache_hits + method_cache_collisions + method_cache_misses;
+    fprintf(stderr, "-- Method cache hits        = %zd (%d%%)\n",
+            method_cache_hits, (int) (100.0 * method_cache_hits / total));
+    fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n",
+            method_cache_misses, (int) (100.0 * method_cache_misses / total));
+    fprintf(stderr, "-- Method cache collisions  = %zd (%d%%)\n",
+            method_cache_collisions, (int) (100.0 * method_cache_collisions / total));
+    fprintf(stderr, "-- Method cache size        = %zd KB\n",
+            sizeof(method_cache) / 1024);
+#endif
+
     for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
         method_cache[i].version = 0;
         Py_CLEAR(method_cache[i].name);
@@ -166,9 +187,8 @@ assign_version_tag(PyTypeObject *type)
            are borrowed reference */
         for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
             method_cache[i].value = NULL;
-            Py_XDECREF(method_cache[i].name);
-            method_cache[i].name = Py_None;
             Py_INCREF(Py_None);
+            Py_XSETREF(method_cache[i].name, Py_None);
         }
         /* mark all version tags as invalid */
         PyType_Modified(&PyBaseObject_Type);
@@ -245,8 +265,8 @@ type_set_name(PyTypeObject *type, PyObject *value, void *context)
     }
     if (strlen(PyString_AS_STRING(value))
         != (size_t)PyString_GET_SIZE(value)) {
-        PyErr_Format(PyExc_ValueError,
-                     "__name__ must not contain null bytes");
+        PyErr_SetString(PyExc_ValueError,
+                        "type name must not contain null characters");
         return -1;
     }
 
@@ -2072,8 +2092,8 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
     PyTypeObject *type, *base, *tmptype, *winner;
     PyHeapTypeObject *et;
     PyMemberDef *mp;
-    Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
-    int j, may_add_dict, may_add_weak;
+    Py_ssize_t i, nbases, nslots, slotoffset;
+    int j, may_add_dict, may_add_weak, add_dict, add_weak;
 
     assert(args != NULL && PyTuple_Check(args));
     assert(kwds == NULL || PyDict_Check(kwds));
@@ -2343,6 +2363,18 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
     type->tp_as_mapping = &et->as_mapping;
     type->tp_as_buffer = &et->as_buffer;
     type->tp_name = PyString_AS_STRING(name);
+    if (!type->tp_name) {
+        Py_DECREF(bases);
+        Py_DECREF(type);
+        return NULL;
+    }
+    if (strlen(type->tp_name) != (size_t)PyString_GET_SIZE(name)) {
+        PyErr_SetString(PyExc_ValueError,
+                        "type name must not contain null characters");
+        Py_DECREF(bases);
+        Py_DECREF(type);
+        return NULL;
+    }
 
     /* Set tp_base and tp_bases */
     type->tp_bases = bases;
@@ -2363,8 +2395,10 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
             tmp = PyDict_GetItemString(tmp, "__name__");
             if (tmp != NULL) {
                 if (PyDict_SetItemString(dict, "__module__",
-                                         tmp) < 0)
+                                         tmp) < 0) {
+                    Py_DECREF(type);
                     return NULL;
+                }
             }
         }
     }
@@ -2396,7 +2430,11 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
             Py_DECREF(type);
             return NULL;
         }
-        PyDict_SetItemString(dict, "__new__", tmp);
+        if (PyDict_SetItemString(dict, "__new__", tmp) < 0) {
+            Py_DECREF(tmp);
+            Py_DECREF(type);
+            return NULL;
+        }
         Py_DECREF(tmp);
     }
 
@@ -2492,8 +2530,12 @@ _PyType_Lookup(PyTypeObject *type, PyObject *name)
         /* fast path */
         h = MCACHE_HASH_METHOD(type, name);
         if (method_cache[h].version == type->tp_version_tag &&
-            method_cache[h].name == name)
+            method_cache[h].name == name) {
+#if MCACHE_STATS
+            method_cache_hits++;
+#endif
             return method_cache[h].value;
+        }
     }
 
     /* Look in tp_dict of types in MRO */
@@ -2527,6 +2569,13 @@ _PyType_Lookup(PyTypeObject *type, PyObject *name)
         method_cache[h].version = type->tp_version_tag;
         method_cache[h].value = res;  /* borrowed */
         Py_INCREF(name);
+        assert(((PyStringObject *)(name))->ob_shash != -1);
+#if MCACHE_STATS
+        if (method_cache[h].name != Py_None && method_cache[h].name != name)
+            method_cache_collisions++;
+        else
+            method_cache_misses++;
+#endif
         Py_DECREF(method_cache[h].name);
         method_cache[h].name = name;
     }
@@ -3209,6 +3258,7 @@ reduce_2(PyObject *obj)
     PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
     PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
     Py_ssize_t i, n;
+    int required_state = 0;
 
     cls = PyObject_GetAttrString(obj, "__class__");
     if (cls == NULL)
@@ -3216,7 +3266,7 @@ reduce_2(PyObject *obj)
 
     if (PyType_Check(cls) && ((PyTypeObject *)cls)->tp_new == NULL) {
         PyErr_Format(PyExc_TypeError,
-                     "can't pickle %s objects",
+                     "can't pickle %.200s objects",
                      ((PyTypeObject *)cls)->tp_name);
         return NULL;
     }
@@ -3225,7 +3275,9 @@ reduce_2(PyObject *obj)
     if (getnewargs != NULL) {
         args = PyObject_CallObject(getnewargs, NULL);
         Py_DECREF(getnewargs);
-        if (args != NULL && !PyTuple_Check(args)) {
+        if (args == NULL)
+            goto end;
+        if (!PyTuple_Check(args)) {
             PyErr_Format(PyExc_TypeError,
                 "__getnewargs__ should return a tuple, "
                 "not '%.200s'", Py_TYPE(args)->tp_name);
@@ -3234,10 +3286,8 @@ reduce_2(PyObject *obj)
     }
     else {
         PyErr_Clear();
-        args = PyTuple_New(0);
+        required_state = !PyList_Check(obj) && !PyDict_Check(obj);
     }
-    if (args == NULL)
-        goto end;
 
     getstate = PyObject_GetAttrString(obj, "__getstate__");
     if (getstate != NULL) {
@@ -3248,6 +3298,14 @@ reduce_2(PyObject *obj)
     }
     else {
         PyErr_Clear();
+
+        if (required_state && obj->ob_type->tp_itemsize) {
+            PyErr_Format(PyExc_TypeError,
+                         "can't pickle %.200s objects",
+                         Py_TYPE(obj)->tp_name);
+            goto end;
+        }
+
         state = PyObject_GetAttrString(obj, "__dict__");
         if (state == NULL) {
             PyErr_Clear();
@@ -3257,8 +3315,9 @@ reduce_2(PyObject *obj)
         names = slotnames(cls);
         if (names == NULL)
             goto end;
+        assert(names == Py_None || PyList_Check(names));
+
         if (names != Py_None) {
-            assert(PyList_Check(names));
             slots = PyDict_New();
             if (slots == NULL)
                 goto end;
@@ -3269,12 +3328,16 @@ reduce_2(PyObject *obj)
             for (i = 0; i < PyList_GET_SIZE(names); i++) {
                 PyObject *name, *value;
                 name = PyList_GET_ITEM(names, i);
+                Py_INCREF(name);
                 value = PyObject_GetAttr(obj, name);
-                if (value == NULL)
+                if (value == NULL) {
+                    Py_DECREF(name);
                     PyErr_Clear();
+                }
                 else {
                     int err = PyDict_SetItem(slots, name,
                                              value);
+                    Py_DECREF(name);
                     Py_DECREF(value);
                     if (err)
                         goto end;
@@ -3316,7 +3379,7 @@ reduce_2(PyObject *obj)
     if (newobj == NULL)
         goto end;
 
-    n = PyTuple_GET_SIZE(args);
+    n = args ? PyTuple_GET_SIZE(args) : 0;
     args2 = PyTuple_New(n+1);
     if (args2 == NULL)
         goto end;
@@ -6682,9 +6745,9 @@ super_init(PyObject *self, PyObject *args, PyObject *kwds)
         Py_INCREF(obj);
     }
     Py_INCREF(type);
-    su->type = type;
-    su->obj = obj;
-    su->obj_type = obj_type;
+    Py_XSETREF(su->type, type);
+    Py_XSETREF(su->obj, obj);
+    Py_XSETREF(su->obj_type, obj_type);
     return 0;
 }
 
index 9368a3a..0b81a3c 100644 (file)
@@ -436,8 +436,7 @@ int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
             return -1;
         Py_UNICODE_COPY(w->str, v->str,
                         length < v->length ? length : v->length);
-        Py_DECREF(*unicode);
-        *unicode = w;
+        Py_SETREF(*unicode, w);
         return 0;
     }
 
@@ -1288,6 +1287,9 @@ PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
         goto onError;
     }
 
+    if (PyErr_WarnPy3k("decoding Unicode is not supported in 3.x", 1) < 0)
+        goto onError;
+
     if (encoding == NULL)
         encoding = PyUnicode_GetDefaultEncoding();
 
@@ -8630,7 +8632,10 @@ PyObject *PyUnicode_Format(PyObject *format,
                     }
                     else {
                         iobj = PyNumber_Int(v);
-                        if (iobj==NULL) iobj = PyNumber_Long(v);
+                        if (iobj==NULL) {
+                            PyErr_Clear();
+                            iobj = PyNumber_Long(v);
+                        }
                     }
                     if (iobj!=NULL) {
                         if (PyInt_Check(iobj)) {
index e1f4bc4..c8b982f 100644 (file)
@@ -271,7 +271,6 @@ static int
 parse_weakref_init_args(char *funcname, PyObject *args, PyObject *kwargs,
                         PyObject **obp, PyObject **callbackp)
 {
-    /* XXX Should check that kwargs == NULL or is empty. */
     return PyArg_UnpackTuple(args, funcname, 1, 2, obp, callbackp);
 }
 
@@ -334,6 +333,9 @@ weakref___init__(PyObject *self, PyObject *args, PyObject *kwargs)
 {
     PyObject *tmp;
 
+    if (!_PyArg_NoKeywords("ref()", kwargs))
+        return -1;
+
     if (parse_weakref_init_args("__init__", args, kwargs, &tmp, &tmp))
         return 0;
     else
index 5625f9d..4901251 100644 (file)
@@ -82,7 +82,7 @@
        />\r
        <UserMacro\r
                Name="opensslDir"\r
-               Value="$(externalsDir)\openssl-1.0.2d"\r
+               Value="$(externalsDir)\openssl-1.0.2h"\r
        />\r
        <UserMacro\r
                Name="tcltkDir"\r
index 92d5c8a..3345af9 100644 (file)
@@ -132,7 +132,7 @@ _ssl
 \r
     Get the source code through\r
 \r
-    svn export http://svn.python.org/projects/external/openssl-1.0.2d\r
+    svn export http://svn.python.org/projects/external/openssl-1.0.2h\r
 \r
     ** NOTE: if you use the PCbuild\get_externals.bat approach for\r
     obtaining external sources then you don't need to manually get the source\r
@@ -145,11 +145,10 @@ _ssl
         http://www.nasm.us/\r
     and add NASM to your PATH.\r
 \r
-    You can also install ActivePerl from\r
+    You will also need ActivePerl from\r
         http://www.activestate.com/activeperl/\r
-    if you like to use the official sources instead of the files from\r
-    python's subversion repository. The svn version contains pre-build\r
-    makefiles and assembly files.\r
+    in order to create the necessary makefiles and .asm files for building\r
+    OpenSSL.\r
 \r
     The build process makes sure that no patented algorithms are included.\r
     For now RC5, MDC2 and IDEA are excluded from the build. You may have\r
index f757aa5..e139cce 100644 (file)
@@ -301,7 +301,7 @@ PyDoc_STRVAR(SetValueEx_doc,
 "  REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references\n"
 "                   to environment variables (for example, %PATH%).\n"
 "  REG_LINK -- A Unicode symbolic link.\n"
-"  REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by\n"
+"  REG_MULTI_SZ -- A sequence of null-terminated strings, terminated by\n"
 "                  two null characters.  Note that Python handles this\n"
 "                  termination automatically.\n"
 "  REG_NONE -- No defined value type.\n"
diff --git a/PC/icons/baselogo.svg b/PC/icons/baselogo.svg
deleted file mode 100644 (file)
index fff6b17..0000000
+++ /dev/null
@@ -1,609 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<svg version="1.0" width="744.09448" height="1052.3622" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
-  <defs>
-    <linearGradient id="pyYellowGradient">
-      <stop  offset="0" style="stop-color:#ffc130;stop-opacity:1"/>
-      <stop  offset="1" style="stop-color:#ffea5b;stop-opacity:1"/>
-    </linearGradient>
-    <linearGradient id="pyBlueGradient">
-      <stop style="stop-color:#426684;stop-opacity:1" offset="0"/>
-      <stop style="stop-color:#357cb5;stop-opacity:1" offset="1"/>
-    </linearGradient>
-    <linearGradient id="pyYellow" xlink:href="#pyYellowGradient" x1="1108.9739" y1="3365.6448" x2="949.80927" y2="3144.1941" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.317715,0,0,0.317715,-172.579,-583.027)"/>
-    <linearGradient id="pyBlue" xlink:href="#pyBlueGradient" x1="607.27795" y1="1841.619" x2="472.67371" y2="1660.6002" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0.317715,0,0,0.317715,-71.39343,-151.2348)"/>
-  </defs>
-
-  <g
-     id="layer1">
-    <path
-       d="M 88.126188,110.89374 C 88.126188,99.932569 97.021954,91.036422 107.98312,91.023301 L 147.69781,91.023301 C 158.65898,91.036435 167.55475,99.932569 167.55475,110.88023 L 167.55475,148.11929 C 167.55475,159.08046 158.65898,167.97661 147.69781,167.97661 L 107.98312,167.97661 C 94.281853,167.97661 83.161955,179.0965 83.161955,192.79777 L 83.161955,210.17955 L 68.268873,210.16643 C 57.307706,210.17955 48.411559,201.27028 48.411559,190.30911 L 48.411559,150.59472 C 48.411559,139.64668 57.307706,130.73741 68.268873,130.73741 L 127.84044,130.75054 L 127.84044,125.78631 L 88.126061,125.78631 L 88.126061,110.89361 L 88.126188,110.89374 z M 105.49443,100.96489 C 109.61173,100.96489 112.94774,104.3009 112.94774,108.40504 C 112.94774,112.52196 109.61173,115.85797 105.49443,115.85797 C 101.39066,115.85797 98.041501,112.52196 98.041501,108.40504 C 98.041501,104.3009 101.39063,100.96489 105.49443,100.96489 z "
-       style="fill:#426684;fill-rule:evenodd"
-       id="path6" />
-    <g
-       transform="matrix(0.317715,0,0,0.317715,-71.39343,-151.2348)"
-       style="fill-rule:evenodd"
-       id="_19410248">
-   <g
-   id="g9">
-    <path
-   d="M 1102.42,902.293 C 1160.3365,901.33394 1186.6279,955.8347 1187.0861,1017.668 C 1187.0861,1072.1676 1159.8369,1123.293 1101.4196,1125.21 C 1077.5861,1125.21 1057.1283,1117.9179 1037.17,1105.7513 L 1037.17,1231.8353 L 1002.1279,1219.168 L 1002.6287,939.293 C 1002.1279,939.293 1029.8779,902.7934 1101.9204,901.793 L 1102.42,902.29379 L 1102.42,902.293 z M 1093.6279,1099.917 C 1140.3783,1097.0009 1146.2118,1051.2509 1146.2118,1015.2095 C 1146.2118,980.1674 1140.3783,927.5835 1096.087,925.6678 C 1065.9205,923.70953 1041.5449,937.8343 1036.7118,942.7087 L 1036.7118,1081.4177 C 1048.3787,1088.7098 1071.7527,1101.376 1093.6279,1099.9173 L 1093.6279,1099.917 z "
-   style="fill:#6a6a6a"
-   id="_19410568" />
-
-    <path
-   d="M 1261,1051.25 L 1261,901.791 L 1224.9587,913.9587 L 1224.9587,1061.9577 C 1224.9587,1101.3746 1261.4996,1124.249 1293.6244,1124.249 C 1335.4579,1124.249 1359.3327,1112.5833 1370.0405,1107.7077 C 1370.4988,1113.0416 1370.0405,1111.5829 1370.0405,1116.9581 C 1370.0405,1132.5416 1369.5409,1159.2912 1362.2488,1172.9164 C 1347.6244,1200.6664 1308.7071,1204.5416 1281.4579,1208.4581 L 1287.2902,1230.8329 C 1323.2902,1229.875 1373.9158,1216.2498 1391.9162,1182.1668 C 1402.1658,1162.7081 1403.6245,1125.2081 1403.6245,1100.4168 L 1403.6245,907.16579 L 1368.0828,907.16579 L 1368.0828,1080.9168 C 1356.4159,1088.7085 1335.0001,1099.4164 1315.9997,1099.916 C 1284.3745,1100.4168 1261.0005,1083.3747 1261.0005,1050.7491 L 1261.0005,1051.2499 L 1261,1051.25 z "
-   style="fill:#6a6a6a"
-   id="_19412384" />
-
-    <path
-   d="M 1463.29,930.043 L 1463.29,1069.751 C 1463.29,1106.2506 1491.5396,1127.6675 1538.7483,1123.2927 L 1538.7483,1104.7931 C 1513.9144,1103.7927 1498.8318,1097.0014 1498.8318,1068.7506 L 1498.8318,930.0436 L 1538.7483,930.0436 L 1538.7483,907.168 L 1498.8318,907.168 L 1498.8318,835.1267 L 1463.2901,847.7928 L 1463.2901,907.168 L 1438.957,907.168 L 1438.957,930.0436 L 1463.2901,930.0436 L 1463.29,930.043 z "
-   style="fill:#6a6a6a"
-   id="_19413104" />
-
-    <path
-   d="M 1754.5,1120.33 L 1754.5,971.914 C 1754.5,934.9136 1729.1665,905.7061 1691.2083,905.7061 C 1662.5004,905.7061 1638.1674,914.95531 1616.7504,930.4974 L 1616.7504,781.0804 L 1581.2087,792.2879 L 1581.2087,1120.3299 L 1616.7504,1120.3299 L 1616.7504,955.8309 C 1634.7504,943.1636 1655.2083,930.0392 1677.5831,930.0392 C 1706.2922,930.0392 1718.4587,958.2475 1718.4587,983.0801 L 1718.4587,1120.3301 L 1754.5,1120.3301 L 1754.5,1120.33 z "
-   style="fill:#6a6a6a"
-   id="_19415136" />
-
-    <path
-   d="M 1786.29,1009.88 C 1786.29,1068.7544 1817.4569,1124.254 1883.1652,1124.755 C 1949.3731,1124.2542 1981.4991,1068.7542 1981.4991,1009.88 C 1980.9983,952.4217 1944.9983,902.297 1883.6648,901.796 C 1822.8321,902.29679 1786.29,952.4216 1786.29,1009.88 L 1786.29,1009.88 z M 1824.7491,1009.88 C 1824.7491,971.4221 1834.4979,929.0879 1883.1652,926.1304 C 1928.9152,928.58827 1942.5404,971.4221 1942.5404,1009.88 C 1942.5404,1050.7544 1933.7896,1101.38 1884.1231,1102.8387 C 1838.3731,1102.3379 1825.2487,1050.7544 1825.2487,1009.88 L 1824.7491,1009.88 L 1824.7491,1009.88 z "
-   style="fill:#6a6a6a"
-   id="_19416104" />
-
-    <path
-   d="M 2184.04,1120.33 L 2184.04,957.288 C 2184.04,928.5801 2161.1644,910.0805 2135.3727,904.2471 C 2110.0392,898.41364 2086.207,903.24671 2068.7066,908.1223 C 2046.2893,913.95576 2030.2475,924.2054 2012.2062,937.3298 L 2012.2062,1120.3298 L 2047.7479,1120.3298 L 2047.7479,941.7058 C 2058.9566,933.91407 2076.9566,925.6641 2095.957,925.1633 C 2127.0814,924.66369 2148.4983,942.705 2148.4983,975.2881 L 2148.4983,1120.3301 L 2184.04,1120.3301 L 2184.04,1120.33 z "
-   style="fill:#6a6a6a"
-   id="_19416592" />
-
-   </g>
-
-  </g>
-    <path
-       d="M 167.55462,230.0232 C 167.55462,240.98437 158.65885,249.88051 147.69769,249.89364 L 107.98299,249.89364 C 97.021827,249.88051 88.126061,240.98437 88.126061,230.0367 L 88.126061,192.79765 C 88.126061,181.83648 97.021827,172.94071 107.98299,172.94071 L 147.69769,172.94071 C 161.39896,172.94071 172.51923,161.82043 172.51923,148.11916 L 172.51923,130.73739 L 187.41193,130.75052 C 198.3731,130.73739 207.26925,139.64667 207.26925,150.60784 L 207.26925,190.3222 C 207.26925,201.27025 198.3731,210.17952 187.41193,210.17952 L 127.84037,210.16639 L 127.84037,215.13063 L 167.55475,215.13063 L 167.55475,230.02333 L 167.55462,230.0232 z M 150.17323,239.95205 C 146.06946,239.95205 142.73345,236.61604 142.73345,232.51227 C 142.73345,228.39497 146.06946,225.05897 150.17323,225.05897 C 154.29015,225.05897 157.62615,228.39497 157.62615,232.51227 C 157.62615,236.61604 154.29015,239.95205 150.17323,239.95205 z "
-       style="fill:#d3aa3f;fill-rule:evenodd"
-       id="path17" />
-    <g
-       transform="matrix(0.317715,0,0,0.317715,-71.39343,-151.2348)"
-       style="fill-rule:evenodd"
-       id="g1699">
-      <polygon
-         points="335.222,626.069 334.291,620.493 334.291,615.508 338.458,615.508 338.458,620.493 337.486,626.069 335.222,626.069 "
-         style="fill:#000000;fill-rule:nonzero"
-         id="_19419944" />
-      <path
-         d="M 341.798,634.527 C 341.798,630.52779 342.90942,627.56204 345.13816,625.6392 C 346.99249,624.04117 349.25666,623.23566 351.9295,623.23566 C 354.90233,623.23566 357.33186,624.20889 359.21454,626.16007 C 361.10312,628.10416 362.04092,630.79117 362.04092,634.22227 C 362.04092,637.00613 361.62399,639.19471 360.79013,640.78447 C 359.95745,642.38132 358.7421,643.61793 357.15233,644.49904 C 355.5543,645.38132 353.81808,645.81951 351.9295,645.81951 C 348.90942,645.81951 346.46454,644.85337 344.59604,642.90927 C 342.72872,640.97226 341.79801,638.18014 341.79801,634.52699 L 341.798,634.527 z M 345.56217,634.527 C 345.56217,637.29787 346.16571,639.36834 347.37398,640.74314 C 348.58225,642.12503 350.10351,642.81243 351.92949,642.81243 C 353.74957,642.81243 355.26256,642.11794 356.47083,640.73605 C 357.67319,639.35416 358.27674,637.24235 358.27674,634.41007 C 358.27674,631.73605 357.6732,629.7081 356.45784,628.3333 C 355.24249,626.9585 353.7354,626.2711 351.92949,626.2711 C 350.10351,626.2711 348.58225,626.9585 347.37398,628.32622 C 346.16571,629.69394 345.56217,631.76323 345.56217,634.52701 L 345.56217,634.527 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path21" />
-      <path
-         d="M 366.298,645.333 L 366.298,623.7295 L 369.58973,623.7295 L 369.58973,626.99997 C 370.42949,625.4728 371.20784,624.45824 371.92241,623.9728 C 372.63107,623.48619 373.41532,623.23579 374.27044,623.23579 C 375.50587,623.23579 376.75666,623.63264 378.03343,624.41689 L 376.76965,627.81965 C 375.88146,627.28461 374.985,627.02123 374.08973,627.02123 C 373.28422,627.02123 372.56847,627.26453 371.92949,627.74288 C 371.29051,628.2295 370.83933,628.89564 370.56886,629.74957 C 370.15902,631.04878 369.95823,632.47201 369.95823,634.02044 L 369.95823,645.33304 L 366.29799,645.33304 L 366.298,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path23" />
-      <path
-         d="M 380.228,619.722 L 380.228,615.50783 L 383.89414,615.50783 L 383.89414,619.722 L 380.228,619.722 z M 380.228,645.333 L 380.228,623.7295 L 383.89414,623.7295 L 383.89414,645.333 L 380.228,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path25" />
-      <path
-         d="M 388.796,647.125 L 392.3582,647.65295 C 392.50466,648.75019 392.92041,649.54862 393.59481,650.05531 C 394.50426,650.72854 395.74678,651.0687 397.31646,651.0687 C 399.01843,651.0687 400.32355,650.72855 401.24717,650.05531 C 402.17079,649.375 402.78851,648.42303 403.11449,647.20767 C 403.30937,646.45767 403.39323,644.89625 403.37906,642.50688 C 401.78221,644.38838 399.78851,645.33326 397.40032,645.33326 C 394.42749,645.33326 392.12906,644.26436 390.50386,642.1183 C 388.87984,639.97932 388.06016,637.40334 388.06016,634.41043 C 388.06016,632.34704 388.43457,630.44429 389.17748,628.70216 C 389.92748,626.95885 391.01173,625.61122 392.42787,624.66043 C 393.84401,623.71555 395.51055,623.23602 397.42039,623.23602 C 399.96921,623.23602 402.07393,624.27067 403.7263,626.33405 L 403.7263,623.72972 L 407.1078,623.72972 L 407.1078,642.40292 C 407.1078,645.76434 406.76055,648.15253 406.08024,649.55568 C 405.39283,650.95765 404.30977,652.06907 402.82394,652.88166 C 401.33693,653.69426 399.51095,654.1041 397.33772,654.1041 C 394.76055,654.1041 392.67827,653.52064 391.09441,652.36079 C 389.50465,651.20095 388.74047,649.45764 388.79598,647.12496 L 388.796,647.125 z M 391.82317,634.1459 C 391.82317,636.97936 392.38656,639.04866 393.51805,640.34787 C 394.64364,641.65299 396.0527,642.29905 397.74758,642.29905 C 399.42711,642.29905 400.83734,641.65299 401.97593,640.36086 C 403.11451,639.06283 403.68499,637.03488 403.68499,634.26401 C 403.68499,631.61834 403.10153,629.62582 401.92751,628.28527 C 400.75349,626.94472 399.33735,626.27149 397.68499,626.27149 C 396.05979,626.27149 394.6779,626.93054 393.53223,628.25692 C 392.39365,629.57621 391.82317,631.54157 391.82317,634.1459 L 391.82317,634.1459 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path27" />
-      <path
-         d="M 412.657,619.722 L 412.657,615.50783 L 416.32314,615.50783 L 416.32314,619.722 L 412.657,619.722 z M 412.657,645.333 L 412.657,623.7295 L 416.32314,623.7295 L 416.32314,645.333 L 412.657,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path29" />
-      <path
-         d="M 421.899,645.333 L 421.899,623.7295 L 425.19073,623.7295 L 425.19073,626.79919 C 426.78167,624.42399 429.07301,623.2358 432.06593,623.2358 C 433.37105,623.2358 434.56514,623.47202 435.65648,623.93737 C 436.75372,624.40982 437.56514,625.02045 438.10727,625.78462 C 438.65648,626.5417 439.03089,627.44407 439.25294,628.4858 C 439.38522,629.16729 439.45491,630.3543 439.45491,632.04919 L 439.45491,645.33309 L 435.78759,645.33309 L 435.78759,632.18739 C 435.78759,630.70156 435.6494,629.58306 435.36475,628.84015 C 435.08011,628.10432 434.57223,627.51377 433.85058,627.07676 C 433.12184,626.63266 432.27381,626.40943 431.29467,626.40943 C 429.73207,626.40943 428.3927,626.91022 427.25294,627.89644 C 426.12144,628.88857 425.55924,630.76416 425.55924,633.53502 L 425.55924,645.33302 L 421.899,645.33302 L 421.899,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path31" />
-      <path
-         d="M 459.17,642.666 C 457.80819,643.81876 456.50307,644.63135 455.25346,645.11088 C 453.99559,645.58332 452.64913,645.81954 451.21173,645.81954 C 448.83653,645.81954 447.01764,645.24316 445.73968,644.08332 C 444.46881,642.92348 443.82984,641.43765 443.82984,639.63883 C 443.82984,638.57584 444.06606,637.61088 444.55149,636.73568 C 445.03102,635.86048 445.66291,635.16009 446.44125,634.63214 C 447.22551,634.10419 448.1007,633.70143 449.07983,633.43096 C 449.7944,633.24317 450.87865,633.05537 452.32904,632.88175 C 455.2877,632.52742 457.46802,632.11049 458.86408,631.61797 C 458.87826,631.11836 458.88534,630.79828 458.88534,630.666 C 458.88534,629.17309 458.5381,628.11836 457.84361,627.51364 C 456.9129,626.68096 455.51684,626.27112 453.67668,626.27112 C 451.95463,626.27112 450.68377,626.56994 449.85699,627.17348 C 449.03731,627.77821 448.43376,628.8471 448.03809,630.38135 L 444.46171,629.88883 C 444.7877,628.36166 445.32274,627.11796 446.06565,626.18017 C 446.80857,625.23647 447.89163,624.50655 449.30187,623.99986 C 450.71093,623.49317 452.34321,623.23569 454.20463,623.23569 C 456.05187,623.23569 457.54479,623.45892 458.69754,623.88884 C 459.8503,624.32703 460.69715,624.86797 461.24636,625.52821 C 461.78731,626.18726 462.1629,627.01404 462.38494,628.02034 C 462.50305,628.64632 462.56565,629.77073 462.56565,631.39593 L 462.56565,636.27743 C 462.56565,639.68727 462.64124,641.84042 462.80187,642.7357 C 462.95423,643.63806 463.26723,644.50617 463.72549,645.33294 L 459.89872,645.33294 C 459.52432,644.57585 459.27392,643.68766 459.16998,642.66601 L 459.17,642.666 z M 458.86409,634.48569 C 457.53063,635.0349 455.53811,635.49317 452.88535,635.87467 C 451.37826,636.08963 450.30818,636.33294 449.69047,636.60341 C 449.06567,636.87506 448.57905,637.27073 448.24598,637.79869 C 447.90583,638.31956 447.7322,638.89593 447.7322,639.53491 C 447.7322,640.51404 448.1078,641.32664 448.84362,641.97861 C 449.57945,642.62467 450.66252,642.95066 452.08693,642.95066 C 453.49599,642.95066 454.75268,642.64593 455.84992,642.02704 C 456.94716,641.40932 457.75976,640.56247 458.27354,639.49239 C 458.66921,638.66679 458.8641,637.44435 458.8641,635.83333 L 458.8641,634.48569 L 458.86409,634.48569 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path33" />
-      <polygon
-         points="468.163,645.333 468.163,615.508 471.822,615.508 471.822,645.333 468.163,645.333 "
-         style="fill:#000000;fill-rule:nonzero"
-         id="polygon35" />
-      <polygon
-         points="477.516,626.069 476.585,620.493 476.585,615.508 480.752,615.508 480.752,620.493 479.78,626.069 477.516,626.069 "
-         style="fill:#000000;fill-rule:nonzero"
-         id="polygon37" />
-      <polygon
-         points="496.954,645.333 496.954,615.508 500.613,615.508 500.613,645.333 496.954,645.333 "
-         style="fill:#000000;fill-rule:nonzero"
-         id="polygon39" />
-      <path
-         d="M 504.925,634.527 C 504.925,630.52779 506.03642,627.56204 508.26516,625.6392 C 510.11949,624.04117 512.38366,623.23566 515.0565,623.23566 C 518.02933,623.23566 520.45886,624.20889 522.34154,626.16007 C 524.23012,628.10416 525.16792,630.79117 525.16792,634.22227 C 525.16792,637.00613 524.75099,639.19471 523.91713,640.78447 C 523.08445,642.38132 521.8691,643.61793 520.27933,644.49904 C 518.6813,645.38132 516.94508,645.81951 515.0565,645.81951 C 512.03642,645.81951 509.59154,644.85337 507.72304,642.90927 C 505.85572,640.97226 504.92501,638.18014 504.92501,634.52699 L 504.925,634.527 z M 508.68917,634.527 C 508.68917,637.29787 509.29271,639.36834 510.50098,640.74314 C 511.70925,642.12503 513.23051,642.81243 515.05649,642.81243 C 516.87657,642.81243 518.38956,642.11794 519.59783,640.73605 C 520.80019,639.35416 521.40374,637.24235 521.40374,634.41007 C 521.40374,631.73605 520.8002,629.7081 519.58484,628.3333 C 518.36949,626.9585 516.8624,626.2711 515.05649,626.2711 C 513.23051,626.2711 511.70925,626.9585 510.50098,628.32622 C 509.29271,629.69394 508.68917,631.76323 508.68917,634.52701 L 508.68917,634.527 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path41" />
-      <path
-         d="M 528.793,647.125 L 532.3552,647.65295 C 532.50166,648.75019 532.9174,649.54862 533.59181,650.05531 C 534.50126,650.72854 535.74378,651.0687 537.31346,651.0687 C 539.01543,651.0687 540.32055,650.72855 541.24417,650.05531 C 542.16779,649.375 542.78551,648.42303 543.11149,647.20767 C 543.30637,646.45767 543.39023,644.89625 543.37606,642.50688 C 541.77921,644.38838 539.78551,645.33326 537.39732,645.33326 C 534.42449,645.33326 532.12606,644.26436 530.50086,642.1183 C 528.87684,639.97932 528.05716,637.40334 528.05716,634.41043 C 528.05716,632.34704 528.43157,630.44429 529.17448,628.70216 C 529.92448,626.95885 531.00873,625.61122 532.42487,624.66043 C 533.84101,623.71555 535.50755,623.23602 537.41739,623.23602 C 539.96621,623.23602 542.07093,624.27067 543.7233,626.33405 L 543.7233,623.72972 L 547.1048,623.72972 L 547.1048,642.40292 C 547.1048,645.76434 546.75755,648.15253 546.07724,649.55568 C 545.38983,650.95765 544.30677,652.06907 542.82094,652.88166 C 541.33393,653.69426 539.50795,654.1041 537.33472,654.1041 C 534.75755,654.1041 532.67527,653.52064 531.09141,652.36079 C 529.50165,651.20095 528.73747,649.45764 528.79298,647.12496 L 528.793,647.125 z M 531.82017,634.1459 C 531.82017,636.97936 532.38356,639.04866 533.51505,640.34787 C 534.64064,641.65299 536.0497,642.29905 537.74458,642.29905 C 539.42411,642.29905 540.83434,641.65299 541.97293,640.36086 C 543.11151,639.06283 543.68199,637.03488 543.68199,634.26401 C 543.68199,631.61834 543.09852,629.62582 541.92451,628.28527 C 540.75049,626.94472 539.33435,626.27149 537.68199,626.27149 C 536.05679,626.27149 534.6749,626.93054 533.52923,628.25692 C 532.39065,629.57621 531.82017,631.54157 531.82017,634.1459 L 531.82017,634.1459 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path43" />
-      <path
-         d="M 551.271,634.527 C 551.271,630.52779 552.38242,627.56204 554.61116,625.6392 C 556.46549,624.04117 558.72966,623.23566 561.4025,623.23566 C 564.37533,623.23566 566.80486,624.20889 568.68754,626.16007 C 570.57612,628.10416 571.51392,630.79117 571.51392,634.22227 C 571.51392,637.00613 571.09699,639.19471 570.26313,640.78447 C 569.43045,642.38132 568.2151,643.61793 566.62533,644.49904 C 565.0273,645.38132 563.29108,645.81951 561.4025,645.81951 C 558.38242,645.81951 555.93754,644.85337 554.06904,642.90927 C 552.20172,640.97226 551.27101,638.18014 551.27101,634.52699 L 551.271,634.527 z M 555.03517,634.527 C 555.03517,637.29787 555.63871,639.36834 556.84698,640.74314 C 558.05525,642.12503 559.57651,642.81243 561.40249,642.81243 C 563.22257,642.81243 564.73556,642.11794 565.94383,640.73605 C 567.14619,639.35416 567.74974,637.24235 567.74974,634.41007 C 567.74974,631.73605 567.1462,629.7081 565.93084,628.3333 C 564.71549,626.9585 563.2084,626.2711 561.40249,626.2711 C 559.57651,626.2711 558.05525,626.9585 556.84698,628.32622 C 555.63871,629.69394 555.03517,631.76323 555.03517,634.52701 L 555.03517,634.527 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path45" />
-      <path
-         d="M 588.256,645.333 L 588.256,626.5759 L 585.02687,626.5759 L 585.02687,623.72944 L 588.256,623.72944 L 588.256,621.43101 C 588.256,619.97944 588.38828,618.89636 588.64458,618.19479 C 588.99891,617.24282 589.61781,616.47274 590.506,615.88219 C 591.39537,615.29164 592.63789,614.99991 594.24183,614.99991 C 595.27057,614.99991 596.40915,615.11802 597.65876,615.36841 L 597.11073,618.56329 C 596.35364,618.42392 595.63081,618.35424 594.95049,618.35424 C 593.83907,618.35424 593.05482,618.59046 592.59655,619.06998 C 592.1312,619.54242 591.90206,620.43061 591.90206,621.73573 L 591.90206,623.72943 L 596.11033,623.72943 L 596.11033,626.57589 L 591.90206,626.57589 L 591.90206,645.33299 L 588.256,645.33299 L 588.256,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path47" />
-      <path
-         d="M 598.923,645.333 L 598.923,623.7295 L 602.21473,623.7295 L 602.21473,626.99997 C 603.05449,625.4728 603.83284,624.45824 604.54741,623.9728 C 605.25607,623.48619 606.04032,623.23579 606.89544,623.23579 C 608.13087,623.23579 609.38166,623.63264 610.65843,624.41689 L 609.39465,627.81965 C 608.50646,627.28461 607.61,627.02123 606.71473,627.02123 C 605.90922,627.02123 605.19347,627.26453 604.55449,627.74288 C 603.91551,628.2295 603.46433,628.89564 603.19386,629.74957 C 602.78402,631.04878 602.58323,632.47201 602.58323,634.02044 L 602.58323,645.33304 L 598.92299,645.33304 L 598.923,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path49" />
-      <path
-         d="M 611.471,634.527 C 611.471,630.52779 612.58242,627.56204 614.81116,625.6392 C 616.66549,624.04117 618.92966,623.23566 621.6025,623.23566 C 624.57533,623.23566 627.00486,624.20889 628.88754,626.16007 C 630.77612,628.10416 631.71392,630.79117 631.71392,634.22227 C 631.71392,637.00613 631.29699,639.19471 630.46313,640.78447 C 629.63045,642.38132 628.4151,643.61793 626.82533,644.49904 C 625.2273,645.38132 623.49108,645.81951 621.6025,645.81951 C 618.58242,645.81951 616.13754,644.85337 614.26904,642.90927 C 612.40172,640.97226 611.47101,638.18014 611.47101,634.52699 L 611.471,634.527 z M 615.23517,634.527 C 615.23517,637.29787 615.83871,639.36834 617.04698,640.74314 C 618.25525,642.12503 619.77651,642.81243 621.60249,642.81243 C 623.42257,642.81243 624.93556,642.11794 626.14383,640.73605 C 627.34619,639.35416 627.94974,637.24235 627.94974,634.41007 C 627.94974,631.73605 627.3462,629.7081 626.13084,628.3333 C 624.91549,626.9585 623.4084,626.2711 621.60249,626.2711 C 619.77651,626.2711 618.25525,626.9585 617.04698,628.32622 C 615.83871,629.69394 615.23517,631.76323 615.23517,634.52701 L 615.23517,634.527 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path51" />
-      <path
-         d="M 636.012,645.333 L 636.012,623.7295 L 639.28365,623.7295 L 639.28365,626.75667 C 639.96396,625.70195 640.86633,624.84683 641.99192,624.20903 C 643.11633,623.56297 644.40137,623.2358 645.83877,623.2358 C 647.43562,623.2358 648.74783,623.57005 649.76948,624.23619 C 650.79704,624.90351 651.51869,625.82595 651.93562,627.02123 C 653.65058,624.50076 655.87342,623.2358 658.60885,623.2358 C 660.75491,623.2358 662.40019,623.83344 663.55294,625.02045 C 664.7057,626.20864 665.28207,628.03462 665.28207,630.49958 L 665.28207,645.33308 L 661.64427,645.33308 L 661.64427,631.72208 C 661.64427,630.25751 661.52616,629.20161 661.28994,628.55554 C 661.04663,627.91657 660.61553,627.3957 659.99781,627.00003 C 659.37301,626.61145 658.63718,626.40948 657.79624,626.40948 C 656.27616,626.40948 655.01829,626.91735 654.01199,627.93074 C 653.0116,628.93822 652.5049,630.55515 652.5049,632.77798 L 652.5049,645.33308 L 648.84584,645.33308 L 648.84584,631.29918 C 648.84584,629.6669 648.54702,628.44446 647.94938,627.63186 C 647.35293,626.81926 646.37969,626.40942 645.01907,626.40942 C 643.99151,626.40942 643.03954,626.68107 642.16553,627.22911 C 641.29034,627.77123 640.65136,628.56257 640.26277,629.60431 C 639.86592,630.65313 639.67222,632.16022 639.67222,634.12439 L 639.67222,645.33309 L 636.01198,645.33309 L 636.012,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path53" />
-      <path
-         d="M 685.671,645.333 L 682.27533,645.333 L 682.27533,615.5078 L 685.93439,615.5078 L 685.93439,626.146 C 687.48282,624.20899 689.45526,623.23576 691.85053,623.23576 C 693.18399,623.23576 694.44187,623.50741 695.62888,624.04127 C 696.81589,624.57631 697.78794,625.3334 698.55919,626.29836 C 699.32336,627.27041 699.92691,628.43734 700.35801,629.81214 C 700.79502,631.18104 701.01116,632.6456 701.01116,634.20112 C 701.01116,637.90978 700.09344,640.77041 698.26037,642.79128 C 696.43439,644.81215 694.23281,645.81963 691.671,645.81963 C 689.12218,645.81963 687.12257,644.75664 685.671,642.62475 L 685.671,645.33302 L 685.671,645.333 z M 685.62848,634.3676 C 685.62848,636.95776 685.98281,638.82626 686.68439,639.97902 C 687.83715,641.8676 689.39974,642.81248 691.3651,642.81248 C 692.96904,642.81248 694.35093,642.11799 695.51786,640.72193 C 696.68479,639.33295 697.26707,637.26366 697.26707,634.50697 C 697.26707,631.68768 696.70487,629.60421 695.58754,628.26366 C 694.46904,626.92311 693.11549,626.24988 691.53163,626.24988 C 689.92769,626.24988 688.5458,626.94437 687.37887,628.33334 C 686.21194,629.72232 685.62848,631.7361 685.62848,634.36759 L 685.62848,634.3676 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path55" />
-      <path
-         d="M 720.254,638.375 L 724.03825,638.84035 C 723.44061,641.05492 722.33746,642.76988 720.72644,643.99232 C 719.10833,645.20767 717.04494,645.81949 714.53864,645.81949 C 711.37919,645.81949 708.87171,644.84627 707.02447,642.90217 C 705.17014,640.95808 704.24652,638.22855 704.24652,634.71477 C 704.24652,631.07579 705.18431,628.2565 707.05282,626.24981 C 708.92723,624.24312 711.35085,623.23564 714.33668,623.23564 C 717.22566,623.23564 719.58668,624.22186 721.41385,626.18721 C 723.24692,628.15256 724.16346,630.92343 724.16346,634.48564 C 724.16346,634.70769 724.15637,635.03486 724.1422,635.46478 L 708.032,635.46478 C 708.16428,637.83998 708.83751,639.65887 710.04578,640.91675 C 711.25405,642.18053 712.75405,642.81242 714.55995,642.81242 C 715.89932,642.81242 717.04499,642.45809 717.99696,641.74943 C 718.94775,641.04785 719.69775,639.92345 720.25405,638.37502 L 720.254,638.375 z M 708.2327,632.45177 L 720.2953,632.45177 C 720.13585,630.63878 719.6705,629.27106 718.91341,628.36752 C 717.74648,626.95846 716.23349,626.2498 714.37916,626.2498 C 712.69845,626.2498 711.28113,626.81201 710.13546,627.9376 C 708.98979,629.06201 708.3579,630.5691 708.2327,632.45177 L 708.2327,632.45177 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path57" />
-      <path
-         d="M 736.636,642.056 L 737.16277,645.29222 C 736.13521,645.50718 735.21159,645.6182 734.39899,645.6182 C 733.06671,645.6182 732.03797,645.41033 731.30214,644.98631 C 730.5734,644.56939 730.05962,644.01427 729.7608,643.32686 C 729.46198,642.64655 729.30962,641.20206 729.30962,639.00757 L 729.30962,626.57647 L 726.62143,626.57647 L 726.62143,623.73001 L 729.30962,623.73001 L 729.30962,618.37607 L 732.9545,616.18158 L 732.9545,623.73001 L 736.636,623.73001 L 736.636,626.57647 L 732.9545,626.57647 L 732.9545,639.20837 C 732.9545,640.25719 733.0171,640.92451 733.1423,641.22215 C 733.27458,641.52097 733.48245,641.75719 733.77419,641.9379 C 734.06592,642.11152 734.48285,642.20129 735.02498,642.20129 C 735.43364,642.20129 735.96868,642.15286 736.636,642.05601 L 736.636,642.056 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path59" />
-      <path
-         d="M 754.316,642.666 C 752.95419,643.81876 751.64907,644.63135 750.39946,645.11088 C 749.14159,645.58332 747.79513,645.81954 746.35773,645.81954 C 743.98253,645.81954 742.16364,645.24316 740.88568,644.08332 C 739.61481,642.92348 738.97584,641.43765 738.97584,639.63883 C 738.97584,638.57584 739.21206,637.61088 739.69749,636.73568 C 740.17702,635.86048 740.80891,635.16009 741.58725,634.63214 C 742.37151,634.10419 743.2467,633.70143 744.22583,633.43096 C 744.9404,633.24317 746.02465,633.05537 747.47504,632.88175 C 750.4337,632.52742 752.61402,632.11049 754.01008,631.61797 C 754.02426,631.11836 754.03134,630.79828 754.03134,630.666 C 754.03134,629.17309 753.6841,628.11836 752.98961,627.51364 C 752.0589,626.68096 750.66284,626.27112 748.82268,626.27112 C 747.10063,626.27112 745.82977,626.56994 745.00299,627.17348 C 744.18331,627.77821 743.57976,628.8471 743.18409,630.38135 L 739.60771,629.88883 C 739.9337,628.36166 740.46874,627.11796 741.21165,626.18017 C 741.95457,625.23647 743.03763,624.50655 744.44787,623.99986 C 745.85693,623.49317 747.48921,623.23569 749.35063,623.23569 C 751.19787,623.23569 752.69079,623.45892 753.84354,623.88884 C 754.9963,624.32703 755.84315,624.86797 756.39236,625.52821 C 756.93331,626.18726 757.3089,627.01404 757.53094,628.02034 C 757.64905,628.64632 757.71165,629.77073 757.71165,631.39593 L 757.71165,636.27743 C 757.71165,639.68727 757.78724,641.84042 757.94787,642.7357 C 758.10023,643.63806 758.41323,644.50617 758.87149,645.33294 L 755.04472,645.33294 C 754.67032,644.57585 754.41992,643.68766 754.31598,642.66601 L 754.316,642.666 z M 754.01009,634.48569 C 752.67663,635.0349 750.68411,635.49317 748.03135,635.87467 C 746.52426,636.08963 745.45418,636.33294 744.83647,636.60341 C 744.21167,636.87506 743.72505,637.27073 743.39198,637.79869 C 743.05183,638.31956 742.8782,638.89593 742.8782,639.53491 C 742.8782,640.51404 743.25379,641.32664 743.98962,641.97861 C 744.72545,642.62467 745.80852,642.95066 747.23293,642.95066 C 748.64199,642.95066 749.89868,642.64593 750.99592,642.02704 C 752.09316,641.40932 752.90576,640.56247 753.41954,639.49239 C 753.81521,638.66679 754.01009,637.44435 754.01009,635.83333 L 754.01009,634.48569 L 754.01009,634.48569 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path61" />
-      <polygon
-         points="764.426,645.333 764.426,641.159 768.6,641.159 768.6,645.333 764.426,645.333 "
-         style="fill:#000000;fill-rule:nonzero"
-         id="polygon63" />
-      <path
-         d="M 774.967,653.61 L 774.967,623.7293 L 778.30007,623.7293 L 778.30007,626.53442 C 779.0855,625.43718 779.97369,624.61159 780.967,624.06237 C 781.95322,623.51434 783.1544,623.2356 784.56464,623.2356 C 786.41188,623.2356 788.03708,623.71513 789.44614,624.66001 C 790.86228,625.61079 791.92527,626.95135 792.64102,628.68048 C 793.36267,630.40961 793.72409,632.30528 793.72409,634.36749 C 793.72409,636.57615 793.32842,638.56867 792.53,640.34032 C 791.73748,642.11079 790.58472,643.46434 789.07173,644.40922 C 787.55756,645.34701 785.96661,645.81946 784.30008,645.81946 C 783.07882,645.81946 781.98748,645.56198 781.01543,645.0482 C 780.04338,644.53442 779.25204,643.88127 778.62724,643.09702 L 778.62724,653.61002 L 774.967,653.61002 L 774.967,653.61 z M 778.27999,634.6521 C 778.27999,637.43005 778.84219,639.48517 779.96779,640.81864 C 781.0922,642.14502 782.45992,642.81234 784.05795,642.81234 C 785.68197,642.81234 787.07803,642.12494 788.23787,640.74305 C 789.39771,639.36825 789.98118,637.23636 789.98118,634.34738 C 789.98118,631.58951 789.41189,629.53439 788.27921,628.15958 C 787.14771,626.79186 785.79299,626.10446 784.22449,626.10446 C 782.66189,626.10446 781.28,626.8332 780.07882,628.29186 C 778.87646,629.74934 778.28,631.87532 778.28,634.6521 L 778.27999,634.6521 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path65" />
-      <path
-         d="M 797.974,653.653 L 797.56416,650.21481 C 798.36967,650.43095 799.06416,650.54198 799.6618,650.54198 C 800.47439,650.54198 801.12637,650.40261 801.61298,650.13213 C 802.1055,649.86048 802.50235,649.48607 802.81416,648.99237 C 803.05038,648.63214 803.41888,647.72268 803.93266,646.27111 C 804.00234,646.06206 804.11337,645.77033 804.25864,645.37465 L 796.06415,623.72975 L 800.00903,623.72975 L 804.50903,636.23645 C 805.08541,637.82621 805.61336,639.49275 806.07163,641.24315 C 806.49447,639.56244 806.99525,637.92425 807.57872,636.31912 L 812.19565,623.72973 L 815.85589,623.72973 L 807.64014,645.70173 C 806.75904,648.07574 806.07164,649.70803 805.58502,650.60448 C 804.93187,651.81275 804.18896,652.69385 803.34919,653.25724 C 802.50234,653.81945 801.50195,654.10409 800.33502,654.10409 C 799.62636,654.10409 798.84211,653.95055 797.974,653.65291 L 797.974,653.653 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path67" />
-      <path
-         d="M 826.967,642.056 L 827.49377,645.29222 C 826.46621,645.50718 825.54259,645.6182 824.72999,645.6182 C 823.39771,645.6182 822.36897,645.41033 821.63314,644.98631 C 820.9044,644.56939 820.39062,644.01427 820.0918,643.32686 C 819.79298,642.64655 819.64062,641.20206 819.64062,639.00757 L 819.64062,626.57647 L 816.95243,626.57647 L 816.95243,623.73001 L 819.64062,623.73001 L 819.64062,618.37607 L 823.2855,616.18158 L 823.2855,623.73001 L 826.967,623.73001 L 826.967,626.57647 L 823.2855,626.57647 L 823.2855,639.20837 C 823.2855,640.25719 823.3481,640.92451 823.4733,641.22215 C 823.60558,641.52097 823.81345,641.75719 824.10519,641.9379 C 824.39692,642.11152 824.81385,642.20129 825.35598,642.20129 C 825.76464,642.20129 826.29968,642.15286 826.967,642.05601 L 826.967,642.056 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path69" />
-      <path
-         d="M 830.549,645.333 L 830.549,615.5078 L 834.20924,615.5078 L 834.20924,626.2086 C 835.91711,624.22907 838.07735,623.23577 840.6805,623.23577 C 842.27853,623.23577 843.66751,623.55585 844.84743,624.18774 C 846.02853,624.81254 846.87538,625.68774 847.38208,626.79916 C 847.88877,627.9094 848.14625,629.52751 848.14625,631.63932 L 848.14625,645.33302 L 844.48011,645.33302 L 844.48011,631.63932 C 844.48011,629.81215 844.08326,628.47869 843.29192,627.64601 C 842.50058,626.81215 841.37499,626.38932 839.9246,626.38932 C 838.84035,626.38932 837.81988,626.67396 836.862,627.23617 C 835.90295,627.79837 835.22263,628.56255 834.81987,629.52751 C 834.41003,630.48656 834.20924,631.81885 834.20924,633.51373 L 834.20924,645.33303 L 830.549,645.33303 L 830.549,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path71" />
-      <path
-         d="M 852.354,634.527 C 852.354,630.52779 853.46542,627.56204 855.69416,625.6392 C 857.54849,624.04117 859.81266,623.23566 862.4855,623.23566 C 865.45833,623.23566 867.88786,624.20889 869.77054,626.16007 C 871.65912,628.10416 872.59692,630.79117 872.59692,634.22227 C 872.59692,637.00613 872.17999,639.19471 871.34613,640.78447 C 870.51345,642.38132 869.2981,643.61793 867.70833,644.49904 C 866.1103,645.38132 864.37408,645.81951 862.4855,645.81951 C 859.46542,645.81951 857.02054,644.85337 855.15204,642.90927 C 853.28472,640.97226 852.35401,638.18014 852.35401,634.52699 L 852.354,634.527 z M 856.11817,634.527 C 856.11817,637.29787 856.72171,639.36834 857.92998,640.74314 C 859.13825,642.12503 860.65951,642.81243 862.48549,642.81243 C 864.30557,642.81243 865.81856,642.11794 867.02683,640.73605 C 868.22919,639.35416 868.83274,637.24235 868.83274,634.41007 C 868.83274,631.73605 868.2292,629.7081 867.01384,628.3333 C 865.79849,626.9585 864.2914,626.2711 862.48549,626.2711 C 860.65951,626.2711 859.13825,626.9585 857.92998,628.32622 C 856.72171,629.69394 856.11817,631.76323 856.11817,634.52701 L 856.11817,634.527 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path73" />
-      <path
-         d="M 876.895,645.333 L 876.895,623.7295 L 880.18673,623.7295 L 880.18673,626.79919 C 881.77767,624.42399 884.06901,623.2358 887.06193,623.2358 C 888.36705,623.2358 889.56114,623.47202 890.65248,623.93737 C 891.74972,624.40982 892.56114,625.02045 893.10327,625.78462 C 893.65248,626.5417 894.02689,627.44407 894.24894,628.4858 C 894.38122,629.16729 894.45091,630.3543 894.45091,632.04919 L 894.45091,645.33309 L 890.78359,645.33309 L 890.78359,632.18739 C 890.78359,630.70156 890.6454,629.58306 890.36075,628.84015 C 890.07611,628.10432 889.56823,627.51377 888.84658,627.07676 C 888.11784,626.63266 887.26981,626.40943 886.29067,626.40943 C 884.72807,626.40943 883.3887,626.91022 882.24894,627.89644 C 881.11744,628.88857 880.55524,630.76416 880.55524,633.53502 L 880.55524,645.33302 L 876.895,645.33302 L 876.895,645.333 z "
-         style="fill:#000000;fill-rule:nonzero"
-         id="path75" />
-    </g>
-    <g
-       transform="matrix(0.317715,0,0,0.317715,-71.39343,-151.2348)"
-       style="fill-rule:evenodd"
-       id="_19428312">
-   <path
-   d="M 341.207,1443.54 L 332.98535,1421.9365 L 336.85346,1421.9365 L 341.49165,1434.8731 C 341.99244,1436.2692 342.4507,1437.7207 342.87354,1439.2278 C 343.2007,1438.0892 343.65189,1436.7203 344.23535,1435.1164 L 349.04007,1421.9365 L 352.80424,1421.9365 L 344.62393,1443.54 L 341.207,1443.54 L 341.207,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="_19439224" />
-
-   <path
-   d="M 370.825,1436.58 L 374.60925,1437.0454 C 374.01161,1439.2599 372.90846,1440.9749 371.29744,1442.1973 C 369.67933,1443.4127 367.61594,1444.0245 365.10964,1444.0245 C 361.95019,1444.0245 359.44271,1443.0513 357.59547,1441.1072 C 355.74114,1439.1631 354.81752,1436.4336 354.81752,1432.9198 C 354.81752,1429.2808 355.75532,1426.4615 357.62382,1424.4548 C 359.49823,1422.4481 361.92185,1421.4406 364.90768,1421.4406 C 367.79666,1421.4406 370.15768,1422.4269 371.98485,1424.3922 C 373.81792,1426.3576 374.73446,1429.1284 374.73446,1432.6906 C 374.73446,1432.9127 374.72737,1433.2399 374.7132,1433.6698 L 358.603,1433.6698 C 358.73528,1436.045 359.40851,1437.8639 360.61678,1439.1217 C 361.82505,1440.3855 363.32505,1441.0174 365.13095,1441.0174 C 366.47032,1441.0174 367.61599,1440.6631 368.56796,1439.9544 C 369.51875,1439.2529 370.26875,1438.1284 370.82505,1436.58 L 370.825,1436.58 z M 358.8037,1430.6568 L 370.8663,1430.6568 C 370.70685,1428.8438 370.2415,1427.4761 369.48441,1426.5725 C 368.31748,1425.1635 366.80449,1424.4548 364.95016,1424.4548 C 363.26945,1424.4548 361.85213,1425.017 360.70646,1426.1426 C 359.56079,1427.267 358.9289,1428.7741 358.8037,1430.6568 L 358.8037,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path79" />
-
-   <path
-   d="M 379.172,1443.54 L 379.172,1421.9365 L 382.46373,1421.9365 L 382.46373,1425.207 C 383.30349,1423.6798 384.08184,1422.6652 384.79641,1422.1798 C 385.50507,1421.6932 386.28932,1421.4428 387.14444,1421.4428 C 388.37987,1421.4428 389.63066,1421.8396 390.90743,1422.6239 L 389.64365,1426.0267 C 388.75546,1425.4916 387.859,1425.2282 386.96373,1425.2282 C 386.15822,1425.2282 385.44247,1425.4715 384.80349,1425.9499 C 384.16451,1426.4365 383.71333,1427.1026 383.44286,1427.9566 C 383.03302,1429.2558 382.83223,1430.679 382.83223,1432.2274 L 382.83223,1443.54 L 379.17199,1443.54 L 379.172,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path81" />
-
-   <path
-   d="M 391.623,1437.09 L 395.24072,1436.5207 C 395.44151,1437.9723 396.01198,1439.0825 396.94151,1439.8609 C 397.86513,1440.6309 399.16434,1441.0207 400.83797,1441.0207 C 402.51868,1441.0207 403.76828,1440.6735 404.58088,1439.9931 C 405.39348,1439.3057 405.80332,1438.4991 405.80332,1437.5825 C 405.80332,1436.7498 405.4419,1436.1038 404.71907,1435.6242 C 404.21946,1435.2983 402.96986,1434.8884 400.97616,1434.3888 C 398.29624,1433.7085 396.42773,1433.125 395.39309,1432.6242 C 394.35844,1432.1317 393.56711,1431.4443 393.03207,1430.5691 C 392.49821,1429.6939 392.22656,1428.729 392.22656,1427.6731 C 392.22656,1426.7081 392.4486,1425.8199 392.89388,1425.0002 C 393.33089,1424.1735 393.93561,1423.4931 394.69152,1422.951 C 395.26199,1422.5353 396.03916,1422.1739 397.01829,1421.8821 C 398.00451,1421.5904 399.06042,1421.4439 400.18483,1421.4439 C 401.87971,1421.4439 403.36554,1421.6943 404.65058,1422.1809 C 405.93444,1422.6664 406.87932,1423.3266 407.48995,1424.1593 C 408.10176,1425.0002 408.51869,1426.1105 408.74782,1427.5065 L 405.17144,1428.0002 C 405.00491,1426.8888 404.53247,1426.0207 403.75412,1425.3959 C 402.97696,1424.7711 401.87262,1424.4581 400.4494,1424.4581 C 398.76869,1424.4581 397.56751,1424.7357 396.85176,1425.292 C 396.13011,1425.8471 395.76869,1426.5002 395.76869,1427.2432 C 395.76869,1427.7215 395.92105,1428.1455 396.21987,1428.5282 C 396.51869,1428.9239 396.98405,1429.2428 397.62302,1429.5073 C 397.99034,1429.6384 399.06751,1429.9514 400.85806,1430.4369 C 403.44822,1431.1313 405.25412,1431.6947 406.2746,1432.1388 C 407.30334,1432.5758 408.10885,1433.2219 408.69232,1434.0617 C 409.27461,1434.9026 409.56634,1435.9443 409.56634,1437.1939 C 409.56634,1438.4164 409.2061,1439.562 408.49744,1440.6451 C 407.78169,1441.7223 406.75413,1442.555 405.41358,1443.1455 C 404.07421,1443.7361 402.55295,1444.0278 400.85807,1444.0278 C 398.04587,1444.0278 395.90689,1443.4443 394.43524,1442.2774 C 392.96241,1441.1105 392.02579,1439.3813 391.62304,1437.09 L 391.623,1437.09 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path83" />
-
-   <path
-   d="M 413.934,1417.93 L 413.934,1413.7158 L 417.60014,1413.7158 L 417.60014,1417.93 L 413.934,1417.93 z M 413.934,1443.541 L 413.934,1421.9375 L 417.60014,1421.9375 L 417.60014,1443.541 L 413.934,1443.541 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path85" />
-
-   <path
-   d="M 421.808,1432.74 C 421.808,1428.7408 422.91942,1425.775 425.14816,1423.8522 C 427.00249,1422.2542 429.26666,1421.4487 431.9395,1421.4487 C 434.91233,1421.4487 437.34186,1422.4219 439.22454,1424.3731 C 441.11312,1426.3172 442.05092,1429.0042 442.05092,1432.4353 C 442.05092,1435.2191 441.63399,1437.4077 440.80013,1438.9975 C 439.96745,1440.5943 438.7521,1441.8309 437.16233,1442.712 C 435.5643,1443.5943 433.82808,1444.0325 431.9395,1444.0325 C 428.91942,1444.0325 426.47454,1443.0664 424.60604,1441.1223 C 422.73872,1439.1853 421.80801,1436.3931 421.80801,1432.74 L 421.808,1432.74 z M 425.57217,1432.74 C 425.57217,1435.5109 426.17571,1437.5813 427.38398,1438.9561 C 428.59225,1440.338 430.11351,1441.0254 431.93949,1441.0254 C 433.75957,1441.0254 435.27256,1440.3309 436.48083,1438.949 C 437.68319,1437.5672 438.28674,1435.4554 438.28674,1432.6231 C 438.28674,1429.949 437.6832,1427.9211 436.46784,1426.5463 C 435.25249,1425.1715 433.7454,1424.4841 431.93949,1424.4841 C 430.11351,1424.4841 428.59225,1425.1715 427.38398,1426.5392 C 426.17571,1427.9069 425.57217,1429.9762 425.57217,1432.74 L 425.57217,1432.74 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path87" />
-
-   <path
-   d="M 446.349,1443.54 L 446.349,1421.9365 L 449.64073,1421.9365 L 449.64073,1425.0062 C 451.23167,1422.631 453.52301,1421.4428 456.51593,1421.4428 C 457.82105,1421.4428 459.01514,1421.679 460.10648,1422.1444 C 461.20372,1422.6168 462.01514,1423.2274 462.55727,1423.9916 C 463.10648,1424.7487 463.48089,1425.6511 463.70294,1426.6928 C 463.83522,1427.3743 463.90491,1428.5613 463.90491,1430.2562 L 463.90491,1443.5401 L 460.23759,1443.5401 L 460.23759,1430.3944 C 460.23759,1428.9086 460.0994,1427.7901 459.81475,1427.0471 C 459.53011,1426.3113 459.02223,1425.7208 458.30058,1425.2838 C 457.57184,1424.8397 456.72381,1424.6164 455.74467,1424.6164 C 454.18207,1424.6164 452.8427,1425.1172 451.70294,1426.1034 C 450.57144,1427.0956 450.00924,1428.9712 450.00924,1431.742 L 450.00924,1443.54 L 446.349,1443.54 L 446.349,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path89" />
-
-   <path
-   d="M 481.113,1417.93 L 481.113,1413.7158 L 484.77914,1413.7158 L 484.77914,1417.93 L 481.113,1417.93 z M 481.113,1443.541 L 481.113,1421.9375 L 484.77914,1421.9375 L 484.77914,1443.541 L 481.113,1443.541 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path91" />
-
-   <path
-   d="M 490.355,1443.54 L 490.355,1421.9365 L 493.64673,1421.9365 L 493.64673,1425.0062 C 495.23767,1422.631 497.52901,1421.4428 500.52193,1421.4428 C 501.82705,1421.4428 503.02114,1421.679 504.11248,1422.1444 C 505.20972,1422.6168 506.02114,1423.2274 506.56327,1423.9916 C 507.11248,1424.7487 507.48689,1425.6511 507.70894,1426.6928 C 507.84122,1427.3743 507.91091,1428.5613 507.91091,1430.2562 L 507.91091,1443.5401 L 504.24359,1443.5401 L 504.24359,1430.3944 C 504.24359,1428.9086 504.1054,1427.7901 503.82075,1427.0471 C 503.53611,1426.3113 503.02823,1425.7208 502.30658,1425.2838 C 501.57784,1424.8397 500.72981,1424.6164 499.75067,1424.6164 C 498.18807,1424.6164 496.8487,1425.1172 495.70894,1426.1034 C 494.57744,1427.0956 494.01524,1428.9712 494.01524,1431.742 L 494.01524,1443.54 L 490.355,1443.54 L 490.355,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path93" />
-
-   <path
-   d="M 539.264,1443.54 L 539.264,1440.3664 C 537.5762,1442.8113 535.29195,1444.0266 532.40298,1444.0266 C 531.13211,1444.0266 529.93684,1443.7833 528.83369,1443.2967 C 527.72936,1442.8113 526.90967,1442.1924 526.37463,1441.4565 C 525.83368,1440.7136 525.45809,1439.8113 525.24313,1438.7412 C 525.09667,1438.0195 525.02108,1436.8809 525.02108,1435.3184 L 525.02108,1421.9365 L 528.68014,1421.9365 L 528.68014,1433.9152 C 528.68014,1435.8321 528.75691,1437.1159 528.90219,1437.7833 C 529.13841,1438.7482 529.62502,1439.4982 530.36794,1440.0533 C 531.11794,1440.6026 532.04156,1440.873 533.13881,1440.873 C 534.23605,1440.873 535.26361,1440.5955 536.22857,1440.0333 C 537.19353,1439.4711 537.87503,1438.6998 538.2707,1437.7348 C 538.67346,1436.7628 538.87424,1435.3526 538.87424,1433.5124 L 538.87424,1421.9364 L 542.53448,1421.9364 L 542.53448,1443.5399 L 539.26401,1443.5399 L 539.264,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path95" />
-
-   <path
-   d="M 546.813,1437.09 L 550.43072,1436.5207 C 550.63151,1437.9723 551.20198,1439.0825 552.13151,1439.8609 C 553.05513,1440.6309 554.35434,1441.0207 556.02797,1441.0207 C 557.70868,1441.0207 558.95828,1440.6735 559.77088,1439.9931 C 560.58348,1439.3057 560.99332,1438.4991 560.99332,1437.5825 C 560.99332,1436.7498 560.6319,1436.1038 559.90907,1435.6242 C 559.40946,1435.2983 558.15986,1434.8884 556.16616,1434.3888 C 553.48624,1433.7085 551.61773,1433.125 550.58309,1432.6242 C 549.54844,1432.1317 548.75711,1431.4443 548.22207,1430.5691 C 547.68821,1429.6939 547.41656,1428.729 547.41656,1427.6731 C 547.41656,1426.7081 547.6386,1425.8199 548.08388,1425.0002 C 548.52089,1424.1735 549.12561,1423.4931 549.88152,1422.951 C 550.45199,1422.5353 551.22916,1422.1739 552.20829,1421.8821 C 553.19451,1421.5904 554.25042,1421.4439 555.37483,1421.4439 C 557.06971,1421.4439 558.55554,1421.6943 559.84058,1422.1809 C 561.12444,1422.6664 562.06932,1423.3266 562.67995,1424.1593 C 563.29176,1425.0002 563.70869,1426.1105 563.93782,1427.5065 L 560.36144,1428.0002 C 560.19491,1426.8888 559.72247,1426.0207 558.94412,1425.3959 C 558.16696,1424.7711 557.06262,1424.4581 555.6394,1424.4581 C 553.95869,1424.4581 552.75751,1424.7357 552.04176,1425.292 C 551.32011,1425.8471 550.95869,1426.5002 550.95869,1427.2432 C 550.95869,1427.7215 551.11105,1428.1455 551.40987,1428.5282 C 551.70869,1428.9239 552.17405,1429.2428 552.81302,1429.5073 C 553.18035,1429.6384 554.25751,1429.9514 556.04806,1430.4369 C 558.63822,1431.1313 560.44412,1431.6947 561.4646,1432.1388 C 562.49334,1432.5758 563.29885,1433.2219 563.88232,1434.0617 C 564.46461,1434.9026 564.75634,1435.9443 564.75634,1437.1939 C 564.75634,1438.4164 564.3961,1439.562 563.68744,1440.6451 C 562.97169,1441.7223 561.94413,1442.555 560.60358,1443.1455 C 559.26421,1443.7361 557.74295,1444.0278 556.04807,1444.0278 C 553.23587,1444.0278 551.09689,1443.4443 549.62524,1442.2774 C 548.15241,1441.1105 547.21579,1439.3813 546.81304,1437.09 L 546.813,1437.09 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path97" />
-
-   <path
-   d="M 583.894,1436.58 L 587.67825,1437.0454 C 587.08061,1439.2599 585.97746,1440.9749 584.36644,1442.1973 C 582.74833,1443.4127 580.68494,1444.0245 578.17864,1444.0245 C 575.01919,1444.0245 572.51171,1443.0513 570.66447,1441.1072 C 568.81014,1439.1631 567.88652,1436.4336 567.88652,1432.9198 C 567.88652,1429.2808 568.82431,1426.4615 570.69282,1424.4548 C 572.56723,1422.4481 574.99085,1421.4406 577.97668,1421.4406 C 580.86566,1421.4406 583.22668,1422.4269 585.05385,1424.3922 C 586.88692,1426.3576 587.80346,1429.1284 587.80346,1432.6906 C 587.80346,1432.9127 587.79637,1433.2399 587.7822,1433.6698 L 571.672,1433.6698 C 571.80428,1436.045 572.47751,1437.8639 573.68578,1439.1217 C 574.89405,1440.3855 576.39405,1441.0174 578.19995,1441.0174 C 579.53932,1441.0174 580.68499,1440.6631 581.63696,1439.9544 C 582.58775,1439.2529 583.33775,1438.1284 583.89405,1436.58 L 583.894,1436.58 z M 571.8727,1430.6568 L 583.9353,1430.6568 C 583.77585,1428.8438 583.3105,1427.4761 582.55341,1426.5725 C 581.38648,1425.1635 579.87349,1424.4548 578.01916,1424.4548 C 576.33845,1424.4548 574.92113,1425.017 573.77546,1426.1426 C 572.62979,1427.267 571.9979,1428.7741 571.8727,1430.6568 L 571.8727,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path99" />
-
-   <path
-   d="M 602.491,1432.74 C 602.491,1428.7408 603.60242,1425.775 605.83116,1423.8522 C 607.68549,1422.2542 609.94966,1421.4487 612.6225,1421.4487 C 615.59533,1421.4487 618.02486,1422.4219 619.90754,1424.3731 C 621.79612,1426.3172 622.73392,1429.0042 622.73392,1432.4353 C 622.73392,1435.2191 622.31699,1437.4077 621.48313,1438.9975 C 620.65045,1440.5943 619.4351,1441.8309 617.84533,1442.712 C 616.2473,1443.5943 614.51108,1444.0325 612.6225,1444.0325 C 609.60242,1444.0325 607.15754,1443.0664 605.28904,1441.1223 C 603.42172,1439.1853 602.49101,1436.3931 602.49101,1432.74 L 602.491,1432.74 z M 606.25517,1432.74 C 606.25517,1435.5109 606.85871,1437.5813 608.06698,1438.9561 C 609.27525,1440.338 610.79651,1441.0254 612.62249,1441.0254 C 614.44257,1441.0254 615.95556,1440.3309 617.16383,1438.949 C 618.36619,1437.5672 618.96974,1435.4554 618.96974,1432.6231 C 618.96974,1429.949 618.3662,1427.9211 617.15084,1426.5463 C 615.93549,1425.1715 614.4284,1424.4841 612.62249,1424.4841 C 610.79651,1424.4841 609.27525,1425.1715 608.06698,1426.5392 C 606.85871,1427.9069 606.25517,1429.9762 606.25517,1432.74 L 606.25517,1432.74 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path101" />
-
-   <path
-   d="M 627.032,1443.54 L 627.032,1421.9365 L 630.32373,1421.9365 L 630.32373,1425.0062 C 631.91467,1422.631 634.20601,1421.4428 637.19893,1421.4428 C 638.50405,1421.4428 639.69814,1421.679 640.78948,1422.1444 C 641.88672,1422.6168 642.69814,1423.2274 643.24027,1423.9916 C 643.78948,1424.7487 644.16389,1425.6511 644.38594,1426.6928 C 644.51822,1427.3743 644.58791,1428.5613 644.58791,1430.2562 L 644.58791,1443.5401 L 640.92059,1443.5401 L 640.92059,1430.3944 C 640.92059,1428.9086 640.7824,1427.7901 640.49775,1427.0471 C 640.21311,1426.3113 639.70523,1425.7208 638.98358,1425.2838 C 638.25484,1424.8397 637.40681,1424.6164 636.42767,1424.6164 C 634.86507,1424.6164 633.5257,1425.1172 632.38594,1426.1034 C 631.25444,1427.0956 630.69224,1428.9712 630.69224,1431.742 L 630.69224,1443.54 L 627.032,1443.54 L 627.032,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path103" />
-
-   <path
-   d="M 988.517,1440.88 C 987.15519,1442.0328 985.85007,1442.8454 984.60046,1443.3249 C 983.34259,1443.7973 981.99613,1444.0335 980.55873,1444.0335 C 978.18353,1444.0335 976.36464,1443.4572 975.08668,1442.2973 C 973.81581,1441.1375 973.17684,1439.6517 973.17684,1437.8528 C 973.17684,1436.7898 973.41306,1435.8249 973.89849,1434.9497 C 974.37802,1434.0745 975.00991,1433.3741 975.78825,1432.8461 C 976.57251,1432.3182 977.4477,1431.9154 978.42683,1431.645 C 979.1414,1431.4572 980.22565,1431.2694 981.67604,1431.0957 C 984.6347,1430.7414 986.81502,1430.3245 988.21108,1429.832 C 988.22526,1429.3324 988.23234,1429.0123 988.23234,1428.88 C 988.23234,1427.3871 987.8851,1426.3324 987.19061,1425.7276 C 986.2599,1424.895 984.86384,1424.4851 983.02368,1424.4851 C 981.30163,1424.4851 980.03077,1424.7839 979.20399,1425.3875 C 978.38431,1425.9922 977.78076,1427.0611 977.38509,1428.5954 L 973.80871,1428.1028 C 974.1347,1426.5757 974.66974,1425.332 975.41265,1424.3942 C 976.15557,1423.4505 977.23863,1422.7206 978.64887,1422.2139 C 980.05793,1421.7072 981.69021,1421.4497 983.55163,1421.4497 C 985.39887,1421.4497 986.89179,1421.6729 988.04454,1422.1028 C 989.1973,1422.541 990.04415,1423.082 990.59336,1423.7422 C 991.13431,1424.4013 991.5099,1425.228 991.73194,1426.2343 C 991.85005,1426.8603 991.91265,1427.9847 991.91265,1429.6099 L 991.91265,1434.4914 C 991.91265,1437.9013 991.98824,1440.0544 992.14887,1440.9497 C 992.30123,1441.8521 992.61423,1442.7202 993.07249,1443.5469 L 989.24572,1443.5469 C 988.87132,1442.7899 988.62092,1441.9017 988.51698,1440.88 L 988.517,1440.88 z M 988.21109,1432.6997 C 986.87763,1433.2489 984.88511,1433.7072 982.23235,1434.0887 C 980.72526,1434.3036 979.65518,1434.5469 979.03747,1434.8174 C 978.41267,1435.0891 977.92605,1435.4847 977.59298,1436.0127 C 977.25283,1436.5336 977.0792,1437.1099 977.0792,1437.7489 C 977.0792,1438.728 977.45479,1439.5406 978.19062,1440.1926 C 978.92645,1440.8387 980.00952,1441.1647 981.43393,1441.1647 C 982.84299,1441.1647 984.09968,1440.8599 985.19692,1440.241 C 986.29416,1439.6233 987.10676,1438.7765 987.62054,1437.7064 C 988.01621,1436.8808 988.21109,1435.6584 988.21109,1434.0473 L 988.21109,1432.6997 L 988.21109,1432.6997 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path105" />
-
-   <path
-   d="M 1011.61,1443.54 L 1011.61,1440.8105 C 1010.2423,1442.9565 1008.2285,1444.0266 1005.5687,1444.0266 C 1003.8466,1444.0266 1002.2628,1443.5542 1000.8183,1442.6022 C 999.37378,1441.6585 998.25646,1440.3321 997.45803,1438.6231 C 996.66551,1436.9223 996.26984,1434.9711 996.26984,1432.7553 C 996.26984,1430.6022 996.63126,1428.6439 997.34701,1426.8876 C 998.06866,1425.1302 999.14465,1423.7837 1000.5821,1422.853 C 1002.0206,1421.9152 1003.6317,1421.4427 1005.4092,1421.4427 C 1006.7073,1421.4427 1007.8671,1421.7215 1008.8805,1422.2695 C 1009.9021,1422.8187 1010.7277,1423.5333 1011.3667,1424.4156 L 1011.3667,1413.7148 L 1015.0057,1413.7148 L 1015.0057,1443.54 L 1011.61,1443.54 L 1011.61,1443.54 z M 1000.034,1432.7554 C 1000.034,1435.5263 1000.6175,1437.5956 1001.7844,1438.9633 C 1002.9501,1440.3322 1004.3261,1441.0196 1005.9159,1441.0196 C 1007.5127,1441.0196 1008.8746,1440.3593 1009.9919,1439.0542 C 1011.1104,1437.7479 1011.6726,1435.7483 1011.6726,1433.0613 C 1011.6726,1430.1027 1011.1033,1427.9365 1009.9647,1426.5546 C 1008.8249,1425.1656 1007.423,1424.4782 1005.7494,1424.4782 C 1004.1242,1424.4782 1002.7635,1425.1444 1001.6734,1426.4708 C 1000.582,1427.7971 1000.034,1429.8948 1000.034,1432.7554 L 1000.034,1432.7554 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path107" />
-
-   <path
-   d="M 1020.78,1417.93 L 1020.78,1413.7158 L 1024.4461,1413.7158 L 1024.4461,1417.93 L 1020.78,1417.93 z M 1020.78,1443.541 L 1020.78,1421.9375 L 1024.4461,1421.9375 L 1024.4461,1443.541 L 1020.78,1443.541 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path109" />
-
-   <path
-   d="M 1044.81,1436.58 L 1048.5942,1437.0454 C 1047.9966,1439.2599 1046.8935,1440.9749 1045.2824,1442.1973 C 1043.6643,1443.4127 1041.6009,1444.0245 1039.0946,1444.0245 C 1035.9352,1444.0245 1033.4277,1443.0513 1031.5805,1441.1072 C 1029.7261,1439.1631 1028.8025,1436.4336 1028.8025,1432.9198 C 1028.8025,1429.2808 1029.7403,1426.4615 1031.6088,1424.4548 C 1033.4832,1422.4481 1035.9069,1421.4406 1038.8927,1421.4406 C 1041.7817,1421.4406 1044.1427,1422.4269 1045.9699,1424.3922 C 1047.8029,1426.3576 1048.7195,1429.1284 1048.7195,1432.6906 C 1048.7195,1432.9127 1048.7124,1433.2399 1048.6982,1433.6698 L 1032.588,1433.6698 C 1032.7203,1436.045 1033.3935,1437.8639 1034.6018,1439.1217 C 1035.8101,1440.3855 1037.3101,1441.0174 1039.116,1441.0174 C 1040.4553,1441.0174 1041.601,1440.6631 1042.553,1439.9544 C 1043.5037,1439.2529 1044.2538,1438.1284 1044.8101,1436.58 L 1044.81,1436.58 z M 1032.7887,1430.6568 L 1044.8513,1430.6568 C 1044.6919,1428.8438 1044.2265,1427.4761 1043.4694,1426.5725 C 1042.3025,1425.1635 1040.7895,1424.4548 1038.9352,1424.4548 C 1037.2544,1424.4548 1035.8371,1425.017 1034.6915,1426.1426 C 1033.5458,1427.267 1032.9139,1428.7741 1032.7887,1430.6568 L 1032.7887,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path111" />
-
-   <path
-   d="M 1053.19,1443.54 L 1053.19,1421.9365 L 1056.4817,1421.9365 L 1056.4817,1425.0062 C 1058.0727,1422.631 1060.364,1421.4428 1063.3569,1421.4428 C 1064.662,1421.4428 1065.8561,1421.679 1066.9475,1422.1444 C 1068.0447,1422.6168 1068.8561,1423.2274 1069.3983,1423.9916 C 1069.9475,1424.7487 1070.3219,1425.6511 1070.5439,1426.6928 C 1070.6762,1427.3743 1070.7459,1428.5613 1070.7459,1430.2562 L 1070.7459,1443.5401 L 1067.0786,1443.5401 L 1067.0786,1430.3944 C 1067.0786,1428.9086 1066.9404,1427.7901 1066.6558,1427.0471 C 1066.3711,1426.3113 1065.8632,1425.7208 1065.1416,1425.2838 C 1064.4128,1424.8397 1063.5648,1424.6164 1062.5857,1424.6164 C 1061.0231,1424.6164 1059.6837,1425.1172 1058.5439,1426.1034 C 1057.4124,1427.0956 1056.8502,1428.9712 1056.8502,1431.742 L 1056.8502,1443.54 L 1053.19,1443.54 L 1053.19,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path113" />
-
-   <path
-   d="M 1084.36,1440.26 L 1084.8868,1443.4962 C 1083.8592,1443.7112 1082.9356,1443.8222 1082.123,1443.8222 C 1080.7907,1443.8222 1079.762,1443.6143 1079.0261,1443.1903 C 1078.2974,1442.7734 1077.7836,1442.2183 1077.4848,1441.5309 C 1077.186,1440.8505 1077.0336,1439.4061 1077.0336,1437.2116 L 1077.0336,1424.7805 L 1074.3454,1424.7805 L 1074.3454,1421.934 L 1077.0336,1421.934 L 1077.0336,1416.5801 L 1080.6785,1414.3856 L 1080.6785,1421.934 L 1084.36,1421.934 L 1084.36,1424.7805 L 1080.6785,1424.7805 L 1080.6785,1437.4124 C 1080.6785,1438.4612 1080.7411,1439.1285 1080.8663,1439.4262 C 1080.9986,1439.725 1081.2065,1439.9612 1081.4982,1440.1419 C 1081.7899,1440.3155 1082.2068,1440.4053 1082.749,1440.4053 C 1083.1576,1440.4053 1083.6927,1440.3569 1084.36,1440.26 L 1084.36,1440.26 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path115" />
-
-   <polygon
-   points="1098.09,1434.59 1098.09,1430.91 1109.35,1430.91 1109.35,1434.59 1098.09,1434.59 "
-   style="fill:#000000;fill-rule:nonzero"
-   id="polygon117" />
-
-   <path
-   d="M 1138.98,1443.54 L 1138.98,1440.8105 C 1137.6123,1442.9565 1135.5985,1444.0266 1132.9387,1444.0266 C 1131.2166,1444.0266 1129.6328,1443.5542 1128.1883,1442.6022 C 1126.7438,1441.6585 1125.6265,1440.3321 1124.828,1438.6231 C 1124.0355,1436.9223 1123.6398,1434.9711 1123.6398,1432.7553 C 1123.6398,1430.6022 1124.0013,1428.6439 1124.717,1426.8876 C 1125.4387,1425.1302 1126.5147,1423.7837 1127.9521,1422.853 C 1129.3906,1421.9152 1131.0017,1421.4427 1132.7792,1421.4427 C 1134.0773,1421.4427 1135.2371,1421.7215 1136.2505,1422.2695 C 1137.2721,1422.8187 1138.0977,1423.5333 1138.7367,1424.4156 L 1138.7367,1413.7148 L 1142.3757,1413.7148 L 1142.3757,1443.54 L 1138.98,1443.54 L 1138.98,1443.54 z M 1127.404,1432.7554 C 1127.404,1435.5263 1127.9875,1437.5956 1129.1544,1438.9633 C 1130.3201,1440.3322 1131.6961,1441.0196 1133.2859,1441.0196 C 1134.8827,1441.0196 1136.2445,1440.3593 1137.3619,1439.0542 C 1138.4804,1437.7479 1139.0426,1435.7483 1139.0426,1433.0613 C 1139.0426,1430.1027 1138.4733,1427.9365 1137.3347,1426.5546 C 1136.195,1425.1656 1134.793,1424.4782 1133.1194,1424.4782 C 1131.4942,1424.4782 1130.1335,1425.1444 1129.0434,1426.4708 C 1127.952,1427.7971 1127.404,1429.8948 1127.404,1432.7554 L 1127.404,1432.7554 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path119" />
-
-   <path
-   d="M 1148.16,1417.93 L 1148.16,1413.7158 L 1151.8261,1413.7158 L 1151.8261,1417.93 L 1148.16,1417.93 z M 1148.16,1443.541 L 1148.16,1421.9375 L 1151.8261,1421.9375 L 1151.8261,1443.541 L 1148.16,1443.541 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path121" />
-
-   <path
-   d="M 1158.27,1443.54 L 1158.27,1424.7829 L 1155.0409,1424.7829 L 1155.0409,1421.9364 L 1158.27,1421.9364 L 1158.27,1419.638 C 1158.27,1418.1864 1158.4023,1417.1034 1158.6586,1416.4018 C 1159.0129,1415.4498 1159.6318,1414.6797 1160.52,1414.0892 C 1161.4094,1413.4986 1162.6519,1413.2069 1164.2558,1413.2069 C 1165.2846,1413.2069 1166.4232,1413.325 1167.6728,1413.5754 L 1167.1247,1416.7703 C 1166.3676,1416.6309 1165.6448,1416.5612 1164.9645,1416.5612 C 1163.8531,1416.5612 1163.0688,1416.7975 1162.6106,1417.277 C 1162.1452,1417.7494 1161.9161,1418.6376 1161.9161,1419.9427 L 1161.9161,1421.9364 L 1166.1243,1421.9364 L 1166.1243,1424.7829 L 1161.9161,1424.7829 L 1161.9161,1443.54 L 1158.27,1443.54 L 1158.27,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path123" />
-
-   <path
-   d="M 1169.09,1443.54 L 1169.09,1424.7829 L 1165.8609,1424.7829 L 1165.8609,1421.9364 L 1169.09,1421.9364 L 1169.09,1419.638 C 1169.09,1418.1864 1169.2223,1417.1034 1169.4786,1416.4018 C 1169.8329,1415.4498 1170.4518,1414.6797 1171.34,1414.0892 C 1172.2294,1413.4986 1173.4719,1413.2069 1175.0758,1413.2069 C 1176.1046,1413.2069 1177.2432,1413.325 1178.4928,1413.5754 L 1177.9447,1416.7703 C 1177.1876,1416.6309 1176.4648,1416.5612 1175.7845,1416.5612 C 1174.6731,1416.5612 1173.8888,1416.7975 1173.4306,1417.277 C 1172.9652,1417.7494 1172.7361,1418.6376 1172.7361,1419.9427 L 1172.7361,1421.9364 L 1176.9443,1421.9364 L 1176.9443,1424.7829 L 1172.7361,1424.7829 L 1172.7361,1443.54 L 1169.09,1443.54 L 1169.09,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path125" />
-
-   <path
-   d="M 1194.59,1436.58 L 1198.3742,1437.0454 C 1197.7766,1439.2599 1196.6735,1440.9749 1195.0624,1442.1973 C 1193.4443,1443.4127 1191.3809,1444.0245 1188.8746,1444.0245 C 1185.7152,1444.0245 1183.2077,1443.0513 1181.3605,1441.1072 C 1179.5061,1439.1631 1178.5825,1436.4336 1178.5825,1432.9198 C 1178.5825,1429.2808 1179.5203,1426.4615 1181.3888,1424.4548 C 1183.2632,1422.4481 1185.6869,1421.4406 1188.6727,1421.4406 C 1191.5617,1421.4406 1193.9227,1422.4269 1195.7499,1424.3922 C 1197.5829,1426.3576 1198.4995,1429.1284 1198.4995,1432.6906 C 1198.4995,1432.9127 1198.4924,1433.2399 1198.4782,1433.6698 L 1182.368,1433.6698 C 1182.5003,1436.045 1183.1735,1437.8639 1184.3818,1439.1217 C 1185.5901,1440.3855 1187.0901,1441.0174 1188.896,1441.0174 C 1190.2353,1441.0174 1191.381,1440.6631 1192.333,1439.9544 C 1193.2837,1439.2529 1194.0338,1438.1284 1194.5901,1436.58 L 1194.59,1436.58 z M 1182.5687,1430.6568 L 1194.6313,1430.6568 C 1194.4719,1428.8438 1194.0065,1427.4761 1193.2494,1426.5725 C 1192.0825,1425.1635 1190.5695,1424.4548 1188.7152,1424.4548 C 1187.0344,1424.4548 1185.6171,1425.017 1184.4715,1426.1426 C 1183.3258,1427.267 1182.6939,1428.7741 1182.5687,1430.6568 L 1182.5687,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path127" />
-
-   <path
-   d="M 1202.93,1443.54 L 1202.93,1421.9365 L 1206.2217,1421.9365 L 1206.2217,1425.207 C 1207.0615,1423.6798 1207.8398,1422.6652 1208.5544,1422.1798 C 1209.2631,1421.6932 1210.0473,1421.4428 1210.9024,1421.4428 C 1212.1379,1421.4428 1213.3887,1421.8396 1214.6654,1422.6239 L 1213.4017,1426.0267 C 1212.5135,1425.4916 1211.617,1425.2282 1210.7217,1425.2282 C 1209.9162,1425.2282 1209.2005,1425.4715 1208.5615,1425.9499 C 1207.9225,1426.4365 1207.4713,1427.1026 1207.2009,1427.9566 C 1206.791,1429.2558 1206.5902,1430.679 1206.5902,1432.2274 L 1206.5902,1443.54 L 1202.93,1443.54 L 1202.93,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path129" />
-
-   <path
-   d="M 1231.63,1436.58 L 1235.4143,1437.0454 C 1234.8166,1439.2599 1233.7135,1440.9749 1232.1024,1442.1973 C 1230.4843,1443.4127 1228.4209,1444.0245 1225.9146,1444.0245 C 1222.7552,1444.0245 1220.2477,1443.0513 1218.4005,1441.1072 C 1216.5461,1439.1631 1215.6225,1436.4336 1215.6225,1432.9198 C 1215.6225,1429.2808 1216.5603,1426.4615 1218.4288,1424.4548 C 1220.3032,1422.4481 1222.7269,1421.4406 1225.7127,1421.4406 C 1228.6017,1421.4406 1230.9627,1422.4269 1232.7899,1424.3922 C 1234.6229,1426.3576 1235.5395,1429.1284 1235.5395,1432.6906 C 1235.5395,1432.9127 1235.5324,1433.2399 1235.5182,1433.6698 L 1219.408,1433.6698 C 1219.5403,1436.045 1220.2135,1437.8639 1221.4218,1439.1217 C 1222.6301,1440.3855 1224.1301,1441.0174 1225.936,1441.0174 C 1227.2753,1441.0174 1228.421,1440.6631 1229.373,1439.9544 C 1230.3237,1439.2529 1231.0738,1438.1284 1231.6301,1436.58 L 1231.63,1436.58 z M 1219.6087,1430.6568 L 1231.6713,1430.6568 C 1231.5119,1428.8438 1231.0465,1427.4761 1230.2894,1426.5725 C 1229.1225,1425.1635 1227.6095,1424.4548 1225.7552,1424.4548 C 1224.0744,1424.4548 1222.6571,1425.017 1221.5115,1426.1426 C 1220.3658,1427.267 1219.7339,1428.7741 1219.6087,1430.6568 L 1219.6087,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path131" />
-
-   <path
-   d="M 1240.02,1443.54 L 1240.02,1421.9365 L 1243.3117,1421.9365 L 1243.3117,1425.0062 C 1244.9027,1422.631 1247.194,1421.4428 1250.1869,1421.4428 C 1251.492,1421.4428 1252.6861,1421.679 1253.7775,1422.1444 C 1254.8747,1422.6168 1255.6861,1423.2274 1256.2283,1423.9916 C 1256.7775,1424.7487 1257.1519,1425.6511 1257.3739,1426.6928 C 1257.5062,1427.3743 1257.5759,1428.5613 1257.5759,1430.2562 L 1257.5759,1443.5401 L 1253.9086,1443.5401 L 1253.9086,1430.3944 C 1253.9086,1428.9086 1253.7704,1427.7901 1253.4858,1427.0471 C 1253.2011,1426.3113 1252.6932,1425.7208 1251.9716,1425.2838 C 1251.2428,1424.8397 1250.3948,1424.6164 1249.4157,1424.6164 C 1247.8531,1424.6164 1246.5137,1425.1172 1245.3739,1426.1034 C 1244.2424,1427.0956 1243.6802,1428.9712 1243.6802,1431.742 L 1243.6802,1443.54 L 1240.02,1443.54 L 1240.02,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path133" />
-
-   <path
-   d="M 1271.19,1440.26 L 1271.7168,1443.4962 C 1270.6892,1443.7112 1269.7656,1443.8222 1268.953,1443.8222 C 1267.6207,1443.8222 1266.592,1443.6143 1265.8561,1443.1903 C 1265.1274,1442.7734 1264.6136,1442.2183 1264.3148,1441.5309 C 1264.016,1440.8505 1263.8636,1439.4061 1263.8636,1437.2116 L 1263.8636,1424.7805 L 1261.1754,1424.7805 L 1261.1754,1421.934 L 1263.8636,1421.934 L 1263.8636,1416.5801 L 1267.5085,1414.3856 L 1267.5085,1421.934 L 1271.19,1421.934 L 1271.19,1424.7805 L 1267.5085,1424.7805 L 1267.5085,1437.4124 C 1267.5085,1438.4612 1267.5711,1439.1285 1267.6963,1439.4262 C 1267.8286,1439.725 1268.0365,1439.9612 1268.3282,1440.1419 C 1268.6199,1440.3155 1269.0368,1440.4053 1269.579,1440.4053 C 1269.9876,1440.4053 1270.5227,1440.3569 1271.19,1440.26 L 1271.19,1440.26 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path135" />
-
-   <path
-   d="M 1300.45,1435.63 L 1304.0465,1436.1024 C 1303.6579,1438.5816 1302.6504,1440.5257 1301.0264,1441.9288 C 1299.4083,1443.332 1297.4146,1444.0335 1295.0536,1444.0335 C 1292.1032,1444.0335 1289.7209,1443.0674 1287.9291,1441.1375 C 1286.1303,1439.2064 1285.228,1436.4355 1285.228,1432.8249 C 1285.228,1430.4922 1285.6165,1428.4501 1286.3878,1426.6997 C 1287.165,1424.9505 1288.339,1423.6371 1289.9217,1422.7631 C 1291.4984,1421.8879 1293.2205,1421.4497 1295.0748,1421.4497 C 1297.4217,1421.4497 1299.3457,1422.0473 1300.8315,1423.2343 C 1302.3244,1424.4225 1303.2835,1426.1032 1303.7063,1428.2906 L 1300.1441,1428.8387 C 1299.8039,1427.3871 1299.2063,1426.2969 1298.3453,1425.5611 C 1297.4843,1424.8324 1296.4425,1424.4639 1295.2201,1424.4639 C 1293.3728,1424.4639 1291.8728,1425.1241 1290.7201,1426.4505 C 1289.5673,1427.7698 1288.991,1429.8603 1288.991,1432.7209 C 1288.991,1435.6229 1289.5472,1437.7347 1290.6646,1439.054 C 1291.776,1440.3662 1293.2276,1441.0265 1295.0193,1441.0265 C 1296.4567,1441.0265 1297.6508,1440.5812 1298.6158,1439.7001 C 1299.5819,1438.8178 1300.1925,1437.4642 1300.45,1435.63 L 1300.45,1435.63 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path137" />
-
-   <path
-   d="M 1321.34,1443.54 L 1321.34,1440.3664 C 1319.6522,1442.8113 1317.3679,1444.0266 1314.479,1444.0266 C 1313.2081,1444.0266 1312.0128,1443.7833 1310.9097,1443.2967 C 1309.8054,1442.8113 1308.9857,1442.1924 1308.4506,1441.4565 C 1307.9097,1440.7136 1307.5341,1439.8113 1307.3191,1438.7412 C 1307.1727,1438.0195 1307.0971,1436.8809 1307.0971,1435.3184 L 1307.0971,1421.9365 L 1310.7561,1421.9365 L 1310.7561,1433.9152 C 1310.7561,1435.8321 1310.8329,1437.1159 1310.9782,1437.7833 C 1311.2144,1438.7482 1311.701,1439.4982 1312.4439,1440.0533 C 1313.1939,1440.6026 1314.1176,1440.873 1315.2148,1440.873 C 1316.3121,1440.873 1317.3396,1440.5955 1318.3046,1440.0333 C 1319.2695,1439.4711 1319.951,1438.6998 1320.3467,1437.7348 C 1320.7495,1436.7628 1320.9502,1435.3526 1320.9502,1433.5124 L 1320.9502,1421.9364 L 1324.6105,1421.9364 L 1324.6105,1443.5399 L 1321.34,1443.5399 L 1321.34,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path139" />
-
-   <path
-   d="M 1330.31,1443.54 L 1330.31,1421.9365 L 1333.6017,1421.9365 L 1333.6017,1425.207 C 1334.4415,1423.6798 1335.2198,1422.6652 1335.9344,1422.1798 C 1336.6431,1421.6932 1337.4273,1421.4428 1338.2824,1421.4428 C 1339.5179,1421.4428 1340.7687,1421.8396 1342.0454,1422.6239 L 1340.7816,1426.0267 C 1339.8935,1425.4916 1338.997,1425.2282 1338.1017,1425.2282 C 1337.2962,1425.2282 1336.5805,1425.4715 1335.9415,1425.9499 C 1335.3025,1426.4365 1334.8513,1427.1026 1334.5809,1427.9566 C 1334.171,1429.2558 1333.9702,1430.679 1333.9702,1432.2274 L 1333.9702,1443.54 L 1330.31,1443.54 L 1330.31,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path141" />
-
-   <path
-   d="M 1350.23,1443.54 L 1342.0084,1421.9365 L 1345.8765,1421.9365 L 1350.5146,1434.8731 C 1351.0154,1436.2692 1351.4737,1437.7207 1351.8965,1439.2278 C 1352.2237,1438.0892 1352.6749,1436.7203 1353.2584,1435.1164 L 1358.0631,1421.9365 L 1361.8272,1421.9365 L 1353.6469,1443.54 L 1350.23,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path143" />
-
-   <path
-   d="M 1379.85,1436.58 L 1383.6342,1437.0454 C 1383.0366,1439.2599 1381.9335,1440.9749 1380.3224,1442.1973 C 1378.7043,1443.4127 1376.6409,1444.0245 1374.1346,1444.0245 C 1370.9752,1444.0245 1368.4677,1443.0513 1366.6205,1441.1072 C 1364.7661,1439.1631 1363.8425,1436.4336 1363.8425,1432.9198 C 1363.8425,1429.2808 1364.7803,1426.4615 1366.6488,1424.4548 C 1368.5232,1422.4481 1370.9469,1421.4406 1373.9327,1421.4406 C 1376.8217,1421.4406 1379.1827,1422.4269 1381.0099,1424.3922 C 1382.8429,1426.3576 1383.7595,1429.1284 1383.7595,1432.6906 C 1383.7595,1432.9127 1383.7524,1433.2399 1383.7382,1433.6698 L 1367.628,1433.6698 C 1367.7603,1436.045 1368.4335,1437.8639 1369.6418,1439.1217 C 1370.8501,1440.3855 1372.3501,1441.0174 1374.156,1441.0174 C 1375.4953,1441.0174 1376.641,1440.6631 1377.593,1439.9544 C 1378.5437,1439.2529 1379.2938,1438.1284 1379.8501,1436.58 L 1379.85,1436.58 z M 1367.8287,1430.6568 L 1379.8913,1430.6568 C 1379.7319,1428.8438 1379.2665,1427.4761 1378.5094,1426.5725 C 1377.3425,1425.1635 1375.8295,1424.4548 1373.9752,1424.4548 C 1372.2944,1424.4548 1370.8771,1425.017 1369.7315,1426.1426 C 1368.5858,1427.267 1367.9539,1428.7741 1367.8287,1430.6568 L 1367.8287,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path145" />
-
-   <path
-   d="M 1386.77,1437.09 L 1390.3877,1436.5207 C 1390.5885,1437.9723 1391.159,1439.0825 1392.0885,1439.8609 C 1393.0121,1440.6309 1394.3113,1441.0207 1395.985,1441.0207 C 1397.6657,1441.0207 1398.9153,1440.6735 1399.7279,1439.9931 C 1400.5405,1439.3057 1400.9503,1438.4991 1400.9503,1437.5825 C 1400.9503,1436.7498 1400.5889,1436.1038 1399.8661,1435.6242 C 1399.3665,1435.2983 1398.1169,1434.8884 1396.1232,1434.3888 C 1393.4432,1433.7085 1391.5747,1433.125 1390.5401,1432.6242 C 1389.5054,1432.1317 1388.7141,1431.4443 1388.1791,1430.5691 C 1387.6452,1429.6939 1387.3736,1428.729 1387.3736,1427.6731 C 1387.3736,1426.7081 1387.5956,1425.8199 1388.0409,1425.0002 C 1388.4779,1424.1735 1389.0826,1423.4931 1389.8385,1422.951 C 1390.409,1422.5353 1391.1862,1422.1739 1392.1653,1421.8821 C 1393.1515,1421.5904 1394.2074,1421.4439 1395.3318,1421.4439 C 1397.0267,1421.4439 1398.5125,1421.6943 1399.7976,1422.1809 C 1401.0814,1422.6664 1402.0263,1423.3266 1402.637,1424.1593 C 1403.2488,1425.0002 1403.6657,1426.1105 1403.8948,1427.5065 L 1400.3184,1428.0002 C 1400.1519,1426.8888 1399.6795,1426.0207 1398.9011,1425.3959 C 1398.124,1424.7711 1397.0196,1424.4581 1395.5964,1424.4581 C 1393.9157,1424.4581 1392.7145,1424.7357 1391.9988,1425.292 C 1391.2771,1425.8471 1390.9157,1426.5002 1390.9157,1427.2432 C 1390.9157,1427.7215 1391.0681,1428.1455 1391.3669,1428.5282 C 1391.6657,1428.9239 1392.131,1429.2428 1392.77,1429.5073 C 1393.1373,1429.6384 1394.2145,1429.9514 1396.0051,1430.4369 C 1398.5952,1431.1313 1400.4011,1431.6947 1401.4216,1432.1388 C 1402.4503,1432.5758 1403.2559,1433.2219 1403.8393,1434.0617 C 1404.4216,1434.9026 1404.7133,1435.9443 1404.7133,1437.1939 C 1404.7133,1438.4164 1404.3531,1439.562 1403.6444,1440.6451 C 1402.9287,1441.7223 1401.9011,1442.555 1400.5606,1443.1455 C 1399.2212,1443.7361 1397.6999,1444.0278 1396.0051,1444.0278 C 1393.1929,1444.0278 1391.0539,1443.4443 1389.5822,1442.2774 C 1388.1094,1441.1105 1387.1728,1439.3813 1386.77,1437.09 L 1386.77,1437.09 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path147" />
-
-   <path
-   d="M 1410.02,1443.54 L 1410.02,1439.366 L 1414.1928,1439.366 L 1414.1928,1443.54 C 1414.1928,1445.0742 1413.9224,1446.3109 1413.3802,1447.2558 C 1412.8322,1448.1924 1411.9712,1448.9223 1410.7972,1449.4432 L 1409.7767,1447.8735 C 1410.548,1447.5333 1411.1172,1447.0325 1411.4846,1446.3806 C 1411.8531,1445.7203 1412.0539,1444.7766 1412.0964,1443.54 L 1410.02,1443.54 L 1410.02,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path149" />
-
-   <path
-   d="M 1430.75,1437.09 L 1434.3677,1436.5207 C 1434.5685,1437.9723 1435.139,1439.0825 1436.0685,1439.8609 C 1436.9921,1440.6309 1438.2913,1441.0207 1439.965,1441.0207 C 1441.6457,1441.0207 1442.8953,1440.6735 1443.7079,1439.9931 C 1444.5205,1439.3057 1444.9303,1438.4991 1444.9303,1437.5825 C 1444.9303,1436.7498 1444.5689,1436.1038 1443.8461,1435.6242 C 1443.3465,1435.2983 1442.0969,1434.8884 1440.1032,1434.3888 C 1437.4232,1433.7085 1435.5547,1433.125 1434.5201,1432.6242 C 1433.4854,1432.1317 1432.6941,1431.4443 1432.1591,1430.5691 C 1431.6252,1429.6939 1431.3536,1428.729 1431.3536,1427.6731 C 1431.3536,1426.7081 1431.5756,1425.8199 1432.0209,1425.0002 C 1432.4579,1424.1735 1433.0626,1423.4931 1433.8185,1422.951 C 1434.389,1422.5353 1435.1662,1422.1739 1436.1453,1421.8821 C 1437.1315,1421.5904 1438.1874,1421.4439 1439.3118,1421.4439 C 1441.0067,1421.4439 1442.4925,1421.6943 1443.7776,1422.1809 C 1445.0614,1422.6664 1446.0063,1423.3266 1446.617,1424.1593 C 1447.2288,1425.0002 1447.6457,1426.1105 1447.8748,1427.5065 L 1444.2984,1428.0002 C 1444.1319,1426.8888 1443.6595,1426.0207 1442.8811,1425.3959 C 1442.104,1424.7711 1440.9996,1424.4581 1439.5764,1424.4581 C 1437.8957,1424.4581 1436.6945,1424.7357 1435.9788,1425.292 C 1435.2571,1425.8471 1434.8957,1426.5002 1434.8957,1427.2432 C 1434.8957,1427.7215 1435.0481,1428.1455 1435.3469,1428.5282 C 1435.6457,1428.9239 1436.111,1429.2428 1436.75,1429.5073 C 1437.1173,1429.6384 1438.1945,1429.9514 1439.9851,1430.4369 C 1442.5752,1431.1313 1444.3811,1431.6947 1445.4016,1432.1388 C 1446.4303,1432.5758 1447.2359,1433.2219 1447.8193,1434.0617 C 1448.4016,1434.9026 1448.6933,1435.9443 1448.6933,1437.1939 C 1448.6933,1438.4164 1448.3331,1439.562 1447.6244,1440.6451 C 1446.9087,1441.7223 1445.8811,1442.555 1444.5406,1443.1455 C 1443.2012,1443.7361 1441.6799,1444.0278 1439.9851,1444.0278 C 1437.1729,1444.0278 1435.0339,1443.4443 1433.5622,1442.2774 C 1432.0894,1441.1105 1431.1528,1439.3813 1430.75,1437.09 L 1430.75,1437.09 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path151" />
-
-   <path
-   d="M 1453.05,1451.82 L 1453.05,1421.9393 L 1456.3831,1421.9393 L 1456.3831,1424.7444 C 1457.1685,1423.6472 1458.0567,1422.8216 1459.05,1422.2724 C 1460.0362,1421.7243 1461.2374,1421.4456 1462.6476,1421.4456 C 1464.4949,1421.4456 1466.1201,1421.9251 1467.5291,1422.87 C 1468.9453,1423.8208 1470.0083,1425.1613 1470.724,1426.8905 C 1471.4457,1428.6196 1471.8071,1430.5153 1471.8071,1432.5775 C 1471.8071,1434.7861 1471.4114,1436.7787 1470.613,1438.5503 C 1469.8205,1440.3208 1468.6677,1441.6743 1467.1547,1442.6192 C 1465.6406,1443.557 1464.0496,1444.0295 1462.3831,1444.0295 C 1461.1618,1444.0295 1460.0705,1443.772 1459.0984,1443.2582 C 1458.1264,1442.7444 1457.335,1442.0913 1456.7102,1441.307 L 1456.7102,1451.82 L 1453.05,1451.82 L 1453.05,1451.82 z M 1456.363,1432.8621 C 1456.363,1435.64 1456.9252,1437.6952 1458.0508,1439.0286 C 1459.1752,1440.355 1460.5429,1441.0223 1462.1409,1441.0223 C 1463.765,1441.0223 1465.161,1440.3349 1466.3209,1438.953 C 1467.4807,1437.5782 1468.0642,1435.4464 1468.0642,1432.5574 C 1468.0642,1429.7995 1467.4949,1427.7444 1466.3622,1426.3696 C 1465.2307,1425.0019 1463.876,1424.3145 1462.3075,1424.3145 C 1460.7449,1424.3145 1459.363,1425.0432 1458.1618,1426.5019 C 1456.9595,1427.9593 1456.363,1430.0853 1456.363,1432.8621 L 1456.363,1432.8621 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path153" />
-
-   <path
-   d="M 1490.32,1440.88 C 1488.9582,1442.0328 1487.6531,1442.8454 1486.4035,1443.3249 C 1485.1456,1443.7973 1483.7991,1444.0335 1482.3617,1444.0335 C 1479.9865,1444.0335 1478.1676,1443.4572 1476.8897,1442.2973 C 1475.6188,1441.1375 1474.9798,1439.6517 1474.9798,1437.8528 C 1474.9798,1436.7898 1475.2161,1435.8249 1475.7015,1434.9497 C 1476.181,1434.0745 1476.8129,1433.3741 1477.5913,1432.8461 C 1478.3755,1432.3182 1479.2507,1431.9154 1480.2298,1431.645 C 1480.9444,1431.4572 1482.0287,1431.2694 1483.479,1431.0957 C 1486.4377,1430.7414 1488.618,1430.3245 1490.0141,1429.832 C 1490.0283,1429.3324 1490.0353,1429.0123 1490.0353,1428.88 C 1490.0353,1427.3871 1489.6881,1426.3324 1488.9936,1425.7276 C 1488.0629,1424.895 1486.6668,1424.4851 1484.8267,1424.4851 C 1483.1046,1424.4851 1481.8338,1424.7839 1481.007,1425.3875 C 1480.1873,1425.9922 1479.5838,1427.0611 1479.1881,1428.5954 L 1475.6117,1428.1028 C 1475.9377,1426.5757 1476.4727,1425.332 1477.2157,1424.3942 C 1477.9586,1423.4505 1479.0416,1422.7206 1480.4519,1422.2139 C 1481.8609,1421.7072 1483.4932,1421.4497 1485.3546,1421.4497 C 1487.2019,1421.4497 1488.6948,1421.6729 1489.8475,1422.1028 C 1491.0003,1422.541 1491.8472,1423.082 1492.3964,1423.7422 C 1492.9373,1424.4013 1493.3129,1425.228 1493.5349,1426.2343 C 1493.6531,1426.8603 1493.7157,1427.9847 1493.7157,1429.6099 L 1493.7157,1434.4914 C 1493.7157,1437.9013 1493.7912,1440.0544 1493.9519,1440.9497 C 1494.1042,1441.8521 1494.4172,1442.7202 1494.8755,1443.5469 L 1491.0487,1443.5469 C 1490.6743,1442.7899 1490.4239,1441.9017 1490.32,1440.88 L 1490.32,1440.88 z M 1490.0141,1432.6997 C 1488.6806,1433.2489 1486.6881,1433.7072 1484.0354,1434.0887 C 1482.5283,1434.3036 1481.4582,1434.5469 1480.8405,1434.8174 C 1480.2157,1435.0891 1479.7291,1435.4847 1479.396,1436.0127 C 1479.0558,1436.5336 1478.8822,1437.1099 1478.8822,1437.7489 C 1478.8822,1438.728 1479.2578,1439.5406 1479.9936,1440.1926 C 1480.7295,1440.8387 1481.8125,1441.1647 1483.2369,1441.1647 C 1484.646,1441.1647 1485.9027,1440.8599 1486.9999,1440.241 C 1488.0972,1439.6233 1488.9098,1438.7765 1489.4235,1437.7064 C 1489.8192,1436.8808 1490.0141,1435.6584 1490.0141,1434.0473 L 1490.0141,1432.6997 L 1490.0141,1432.6997 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path155" />
-
-   <path
-   d="M 1513.49,1435.63 L 1517.0865,1436.1024 C 1516.6979,1438.5816 1515.6904,1440.5257 1514.0664,1441.9288 C 1512.4483,1443.332 1510.4546,1444.0335 1508.0936,1444.0335 C 1505.1432,1444.0335 1502.7609,1443.0674 1500.9691,1441.1375 C 1499.1703,1439.2064 1498.268,1436.4355 1498.268,1432.8249 C 1498.268,1430.4922 1498.6565,1428.4501 1499.4278,1426.6997 C 1500.205,1424.9505 1501.379,1423.6371 1502.9617,1422.7631 C 1504.5384,1421.8879 1506.2605,1421.4497 1508.1148,1421.4497 C 1510.4617,1421.4497 1512.3857,1422.0473 1513.8715,1423.2343 C 1515.3644,1424.4225 1516.3235,1426.1032 1516.7463,1428.2906 L 1513.1841,1428.8387 C 1512.8439,1427.3871 1512.2463,1426.2969 1511.3853,1425.5611 C 1510.5243,1424.8324 1509.4825,1424.4639 1508.2601,1424.4639 C 1506.4128,1424.4639 1504.9128,1425.1241 1503.7601,1426.4505 C 1502.6073,1427.7698 1502.031,1429.8603 1502.031,1432.7209 C 1502.031,1435.6229 1502.5872,1437.7347 1503.7046,1439.054 C 1504.816,1440.3662 1506.2676,1441.0265 1508.0593,1441.0265 C 1509.4967,1441.0265 1510.6908,1440.5812 1511.6558,1439.7001 C 1512.6219,1438.8178 1513.2325,1437.4642 1513.49,1435.63 L 1513.49,1435.63 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path157" />
-
-   <path
-   d="M 1520.24,1417.93 L 1520.24,1413.7158 L 1523.9061,1413.7158 L 1523.9061,1417.93 L 1520.24,1417.93 z M 1520.24,1443.541 L 1520.24,1421.9375 L 1523.9061,1421.9375 L 1523.9061,1443.541 L 1520.24,1443.541 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path159" />
-
-   <path
-   d="M 1529.49,1443.54 L 1529.49,1421.9365 L 1532.7817,1421.9365 L 1532.7817,1425.0062 C 1534.3727,1422.631 1536.664,1421.4428 1539.6569,1421.4428 C 1540.962,1421.4428 1542.1561,1421.679 1543.2475,1422.1444 C 1544.3447,1422.6168 1545.1561,1423.2274 1545.6983,1423.9916 C 1546.2475,1424.7487 1546.6219,1425.6511 1546.8439,1426.6928 C 1546.9762,1427.3743 1547.0459,1428.5613 1547.0459,1430.2562 L 1547.0459,1443.5401 L 1543.3786,1443.5401 L 1543.3786,1430.3944 C 1543.3786,1428.9086 1543.2404,1427.7901 1542.9558,1427.0471 C 1542.6711,1426.3113 1542.1632,1425.7208 1541.4416,1425.2838 C 1540.7128,1424.8397 1539.8648,1424.6164 1538.8857,1424.6164 C 1537.3231,1424.6164 1535.9837,1425.1172 1534.8439,1426.1034 C 1533.7124,1427.0956 1533.1502,1428.9712 1533.1502,1431.742 L 1533.1502,1443.54 L 1529.49,1443.54 L 1529.49,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path161" />
-
-   <path
-   d="M 1551.99,1445.33 L 1555.5522,1445.858 C 1555.6987,1446.9552 1556.1144,1447.7536 1556.7888,1448.2603 C 1557.6983,1448.9335 1558.9408,1449.2737 1560.5105,1449.2737 C 1562.2124,1449.2737 1563.5176,1448.9335 1564.4412,1448.2603 C 1565.3648,1447.58 1565.9825,1446.628 1566.3085,1445.4127 C 1566.5034,1444.6627 1566.5872,1443.1013 1566.5731,1440.7119 C 1564.9762,1442.5934 1562.9825,1443.5383 1560.5943,1443.5383 C 1557.6215,1443.5383 1555.3231,1442.4694 1553.6979,1440.3233 C 1552.0738,1438.1843 1551.2542,1435.6083 1551.2542,1432.6154 C 1551.2542,1430.552 1551.6286,1428.6493 1552.3715,1426.9072 C 1553.1215,1425.1639 1554.2057,1423.8162 1555.6219,1422.8654 C 1557.038,1421.9206 1558.7045,1421.441 1560.6144,1421.441 C 1563.1632,1421.441 1565.2679,1422.4757 1566.9203,1424.5391 L 1566.9203,1421.9347 L 1570.3018,1421.9347 L 1570.3018,1440.6079 C 1570.3018,1443.9693 1569.9546,1446.3575 1569.2742,1447.7607 C 1568.5868,1449.1627 1567.5038,1450.2741 1566.0179,1451.0867 C 1564.5309,1451.8993 1562.7049,1452.3091 1560.5317,1452.3091 C 1557.9545,1452.3091 1555.8723,1451.7256 1554.2884,1450.5658 C 1552.6986,1449.406 1551.9345,1447.6626 1551.99,1445.33 L 1551.99,1445.33 z M 1555.0172,1432.3509 C 1555.0172,1435.1844 1555.5806,1437.2537 1556.7121,1438.5529 C 1557.8376,1439.858 1559.2467,1440.5041 1560.9416,1440.5041 C 1562.6211,1440.5041 1564.0313,1439.858 1565.1699,1438.5659 C 1566.3085,1437.2678 1566.879,1435.2399 1566.879,1432.469 C 1566.879,1429.8233 1566.2955,1427.8308 1565.1215,1426.4903 C 1563.9475,1425.1497 1562.5314,1424.4765 1560.879,1424.4765 C 1559.2538,1424.4765 1557.8719,1425.1355 1556.7262,1426.4619 C 1555.5877,1427.7812 1555.0172,1429.7466 1555.0172,1432.3509 L 1555.0172,1432.3509 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path163" />
-
-   <path
-   d="M 1576.78,1443.54 L 1576.78,1439.366 L 1580.9528,1439.366 L 1580.9528,1443.54 C 1580.9528,1445.0742 1580.6824,1446.3109 1580.1402,1447.2558 C 1579.5922,1448.1924 1578.7312,1448.9223 1577.5572,1449.4432 L 1576.5367,1447.8735 C 1577.308,1447.5333 1577.8772,1447.0325 1578.2446,1446.3806 C 1578.6131,1445.7203 1578.8139,1444.7766 1578.8564,1443.54 L 1576.78,1443.54 L 1576.78,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path165" />
-
-   <path
-   d="M 669.775,1440.26 L 670.30177,1443.4962 C 669.27421,1443.7112 668.35059,1443.8222 667.53799,1443.8222 C 666.20571,1443.8222 665.17697,1443.6143 664.44114,1443.1903 C 663.7124,1442.7734 663.19862,1442.2183 662.8998,1441.5309 C 662.60098,1440.8505 662.44862,1439.4061 662.44862,1437.2116 L 662.44862,1424.7805 L 659.76043,1424.7805 L 659.76043,1421.934 L 662.44862,1421.934 L 662.44862,1416.5801 L 666.0935,1414.3856 L 666.0935,1421.934 L 669.775,1421.934 L 669.775,1424.7805 L 666.0935,1424.7805 L 666.0935,1437.4124 C 666.0935,1438.4612 666.1561,1439.1285 666.2813,1439.4262 C 666.41358,1439.725 666.62145,1439.9612 666.91319,1440.1419 C 667.20492,1440.3155 667.62185,1440.4053 668.16398,1440.4053 C 668.57264,1440.4053 669.10768,1440.3569 669.775,1440.26 L 669.775,1440.26 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path167" />
-
-   <path
-   d="M 673.357,1443.54 L 673.357,1413.7148 L 677.01724,1413.7148 L 677.01724,1424.4156 C 678.72511,1422.4361 680.88535,1421.4428 683.4885,1421.4428 C 685.08653,1421.4428 686.47551,1421.7628 687.65543,1422.3947 C 688.83653,1423.0195 689.68338,1423.8947 690.19008,1425.0062 C 690.69677,1426.1164 690.95425,1427.7345 690.95425,1429.8463 L 690.95425,1443.54 L 687.28811,1443.54 L 687.28811,1429.8463 C 687.28811,1428.0191 686.89126,1426.6857 686.09992,1425.853 C 685.30858,1425.0192 684.18299,1424.5963 682.7326,1424.5963 C 681.64835,1424.5963 680.62788,1424.881 679.67,1425.4432 C 678.71095,1426.0054 678.03063,1426.7695 677.62787,1427.7345 C 677.21803,1428.6936 677.01724,1430.0258 677.01724,1431.7207 L 677.01724,1443.54 L 673.357,1443.54 L 673.357,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path169" />
-
-   <path
-   d="M 711.315,1436.58 L 715.09925,1437.0454 C 714.50161,1439.2599 713.39846,1440.9749 711.78744,1442.1973 C 710.16933,1443.4127 708.10594,1444.0245 705.59964,1444.0245 C 702.44019,1444.0245 699.93271,1443.0513 698.08547,1441.1072 C 696.23114,1439.1631 695.30752,1436.4336 695.30752,1432.9198 C 695.30752,1429.2808 696.24532,1426.4615 698.11382,1424.4548 C 699.98823,1422.4481 702.41185,1421.4406 705.39768,1421.4406 C 708.28666,1421.4406 710.64768,1422.4269 712.47485,1424.3922 C 714.30792,1426.3576 715.22446,1429.1284 715.22446,1432.6906 C 715.22446,1432.9127 715.21737,1433.2399 715.2032,1433.6698 L 699.093,1433.6698 C 699.22528,1436.045 699.89851,1437.8639 701.10678,1439.1217 C 702.31505,1440.3855 703.81505,1441.0174 705.62095,1441.0174 C 706.96032,1441.0174 708.10599,1440.6631 709.05796,1439.9544 C 710.00875,1439.2529 710.75875,1438.1284 711.31505,1436.58 L 711.315,1436.58 z M 699.2937,1430.6568 L 711.3563,1430.6568 C 711.19685,1428.8438 710.7315,1427.4761 709.97441,1426.5725 C 708.80748,1425.1635 707.29449,1424.4548 705.44016,1424.4548 C 703.75945,1424.4548 702.34213,1425.017 701.19646,1426.1426 C 700.05079,1427.267 699.4189,1428.7741 699.2937,1430.6568 L 699.2937,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path171" />
-
-   <path
-   d="M 735.266,1443.54 L 728.65537,1421.9365 L 732.43962,1421.9365 L 735.87781,1434.4078 L 737.15458,1439.0472 C 737.21009,1438.811 737.58568,1437.3251 738.27308,1434.5885 L 741.71009,1421.9365 L 745.47426,1421.9365 L 748.71048,1434.4633 L 749.79355,1438.596 L 751.03016,1434.422 L 754.73055,1421.9366 L 758.29394,1421.9366 L 751.53685,1443.5401 L 747.73842,1443.5401 L 744.30023,1430.6023 L 743.46047,1426.9149 L 739.09275,1443.5401 L 735.26598,1443.5401 L 735.266,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path173" />
-
-   <path
-   d="M 776.154,1436.58 L 779.93825,1437.0454 C 779.34061,1439.2599 778.23746,1440.9749 776.62644,1442.1973 C 775.00833,1443.4127 772.94494,1444.0245 770.43864,1444.0245 C 767.27919,1444.0245 764.77171,1443.0513 762.92447,1441.1072 C 761.07014,1439.1631 760.14652,1436.4336 760.14652,1432.9198 C 760.14652,1429.2808 761.08431,1426.4615 762.95282,1424.4548 C 764.82723,1422.4481 767.25085,1421.4406 770.23668,1421.4406 C 773.12566,1421.4406 775.48668,1422.4269 777.31385,1424.3922 C 779.14692,1426.3576 780.06346,1429.1284 780.06346,1432.6906 C 780.06346,1432.9127 780.05637,1433.2399 780.0422,1433.6698 L 763.932,1433.6698 C 764.06428,1436.045 764.73751,1437.8639 765.94578,1439.1217 C 767.15405,1440.3855 768.65405,1441.0174 770.45995,1441.0174 C 771.79932,1441.0174 772.94499,1440.6631 773.89696,1439.9544 C 774.84775,1439.2529 775.59775,1438.1284 776.15405,1436.58 L 776.154,1436.58 z M 764.1327,1430.6568 L 776.1953,1430.6568 C 776.03585,1428.8438 775.5705,1427.4761 774.81341,1426.5725 C 773.64648,1425.1635 772.13349,1424.4548 770.27916,1424.4548 C 768.59845,1424.4548 767.18113,1425.017 766.03546,1426.1426 C 764.88979,1427.267 764.2579,1428.7741 764.1327,1430.6568 L 764.1327,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path175" />
-
-   <path
-   d="M 787.918,1443.54 L 784.52233,1443.54 L 784.52233,1413.7148 L 788.18139,1413.7148 L 788.18139,1424.353 C 789.72982,1422.416 791.70226,1421.4428 794.09753,1421.4428 C 795.43099,1421.4428 796.68887,1421.7144 797.87588,1422.2483 C 799.06289,1422.7833 800.03494,1423.5404 800.80619,1424.5054 C 801.57036,1425.4774 802.17391,1426.6443 802.60501,1428.0191 C 803.04202,1429.388 803.25816,1430.8526 803.25816,1432.4081 C 803.25816,1436.1168 802.34044,1438.9774 800.50737,1440.9983 C 798.68139,1443.0192 796.47981,1444.0266 793.918,1444.0266 C 791.36918,1444.0266 789.36957,1442.9636 787.918,1440.8318 L 787.918,1443.54 L 787.918,1443.54 z M 787.87548,1432.5746 C 787.87548,1435.1648 788.22981,1437.0333 788.93139,1438.186 C 790.08415,1440.0746 791.64674,1441.0195 793.6121,1441.0195 C 795.21604,1441.0195 796.59793,1440.325 797.76486,1438.9289 C 798.93179,1437.54 799.51407,1435.4707 799.51407,1432.714 C 799.51407,1429.8947 798.95187,1427.8112 797.83454,1426.4707 C 796.71604,1425.1301 795.36249,1424.4569 793.77863,1424.4569 C 792.17469,1424.4569 790.7928,1425.1514 789.62587,1426.5403 C 788.45894,1427.9293 787.87548,1429.9431 787.87548,1432.5746 L 787.87548,1432.5746 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path177" />
-
-   <path
-   d="M 817.827,1437.09 L 821.44472,1436.5207 C 821.64551,1437.9723 822.21598,1439.0825 823.14551,1439.8609 C 824.06913,1440.6309 825.36834,1441.0207 827.04197,1441.0207 C 828.72268,1441.0207 829.97228,1440.6735 830.78488,1439.9931 C 831.59748,1439.3057 832.00732,1438.4991 832.00732,1437.5825 C 832.00732,1436.7498 831.6459,1436.1038 830.92307,1435.6242 C 830.42346,1435.2983 829.17386,1434.8884 827.18016,1434.3888 C 824.50024,1433.7085 822.63173,1433.125 821.59709,1432.6242 C 820.56244,1432.1317 819.77111,1431.4443 819.23607,1430.5691 C 818.70221,1429.6939 818.43056,1428.729 818.43056,1427.6731 C 818.43056,1426.7081 818.6526,1425.8199 819.09788,1425.0002 C 819.53489,1424.1735 820.13961,1423.4931 820.89552,1422.951 C 821.46599,1422.5353 822.24316,1422.1739 823.22229,1421.8821 C 824.20851,1421.5904 825.26442,1421.4439 826.38883,1421.4439 C 828.08371,1421.4439 829.56954,1421.6943 830.85458,1422.1809 C 832.13844,1422.6664 833.08332,1423.3266 833.69395,1424.1593 C 834.30576,1425.0002 834.72269,1426.1105 834.95182,1427.5065 L 831.37544,1428.0002 C 831.20891,1426.8888 830.73647,1426.0207 829.95812,1425.3959 C 829.18096,1424.7711 828.07662,1424.4581 826.6534,1424.4581 C 824.97269,1424.4581 823.77151,1424.7357 823.05576,1425.292 C 822.33411,1425.8471 821.97269,1426.5002 821.97269,1427.2432 C 821.97269,1427.7215 822.12505,1428.1455 822.42387,1428.5282 C 822.72269,1428.9239 823.18805,1429.2428 823.82702,1429.5073 C 824.19435,1429.6384 825.27151,1429.9514 827.06206,1430.4369 C 829.65222,1431.1313 831.45812,1431.6947 832.4786,1432.1388 C 833.50734,1432.5758 834.31285,1433.2219 834.89632,1434.0617 C 835.47861,1434.9026 835.77034,1435.9443 835.77034,1437.1939 C 835.77034,1438.4164 835.4101,1439.562 834.70144,1440.6451 C 833.98569,1441.7223 832.95813,1442.555 831.61758,1443.1455 C 830.27821,1443.7361 828.75695,1444.0278 827.06207,1444.0278 C 824.24987,1444.0278 822.11089,1443.4443 820.63924,1442.2774 C 819.16641,1441.1105 818.22979,1439.3813 817.82704,1437.09 L 817.827,1437.09 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path179" />
-
-   <path
-   d="M 840.138,1417.93 L 840.138,1413.7158 L 843.80414,1413.7158 L 843.80414,1417.93 L 840.138,1417.93 z M 840.138,1443.541 L 840.138,1421.9375 L 843.80414,1421.9375 L 843.80414,1443.541 L 840.138,1443.541 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path181" />
-
-   <path
-   d="M 857.374,1440.26 L 857.90077,1443.4962 C 856.87321,1443.7112 855.94959,1443.8222 855.13699,1443.8222 C 853.80471,1443.8222 852.77597,1443.6143 852.04014,1443.1903 C 851.3114,1442.7734 850.79762,1442.2183 850.4988,1441.5309 C 850.19998,1440.8505 850.04762,1439.4061 850.04762,1437.2116 L 850.04762,1424.7805 L 847.35943,1424.7805 L 847.35943,1421.934 L 850.04762,1421.934 L 850.04762,1416.5801 L 853.6925,1414.3856 L 853.6925,1421.934 L 857.374,1421.934 L 857.374,1424.7805 L 853.6925,1424.7805 L 853.6925,1437.4124 C 853.6925,1438.4612 853.7551,1439.1285 853.8803,1439.4262 C 854.01258,1439.725 854.22045,1439.9612 854.51219,1440.1419 C 854.80392,1440.3155 855.22085,1440.4053 855.76298,1440.4053 C 856.17164,1440.4053 856.70668,1440.3569 857.374,1440.26 L 857.374,1440.26 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path183" />
-
-   <path
-   d="M 875.741,1436.58 L 879.52525,1437.0454 C 878.92761,1439.2599 877.82446,1440.9749 876.21344,1442.1973 C 874.59533,1443.4127 872.53194,1444.0245 870.02564,1444.0245 C 866.86619,1444.0245 864.35871,1443.0513 862.51147,1441.1072 C 860.65714,1439.1631 859.73352,1436.4336 859.73352,1432.9198 C 859.73352,1429.2808 860.67131,1426.4615 862.53982,1424.4548 C 864.41423,1422.4481 866.83785,1421.4406 869.82368,1421.4406 C 872.71266,1421.4406 875.07368,1422.4269 876.90085,1424.3922 C 878.73392,1426.3576 879.65046,1429.1284 879.65046,1432.6906 C 879.65046,1432.9127 879.64337,1433.2399 879.6292,1433.6698 L 863.519,1433.6698 C 863.65128,1436.045 864.32451,1437.8639 865.53278,1439.1217 C 866.74105,1440.3855 868.24105,1441.0174 870.04695,1441.0174 C 871.38632,1441.0174 872.53199,1440.6631 873.48396,1439.9544 C 874.43475,1439.2529 875.18475,1438.1284 875.74105,1436.58 L 875.741,1436.58 z M 863.7197,1430.6568 L 875.7823,1430.6568 C 875.62285,1428.8438 875.1575,1427.4761 874.40041,1426.5725 C 873.23348,1425.1635 871.72049,1424.4548 869.86616,1424.4548 C 868.18545,1424.4548 866.76813,1425.017 865.62246,1426.1426 C 864.47679,1427.267 863.8449,1428.7741 863.7197,1430.6568 L 863.7197,1430.6568 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path185" />
-
-   <path
-   d="M 899.692,1443.54 L 893.08137,1421.9365 L 896.86562,1421.9365 L 900.30381,1434.4078 L 901.58058,1439.0472 C 901.63609,1438.811 902.01168,1437.3251 902.69908,1434.5885 L 906.13609,1421.9365 L 909.90026,1421.9365 L 913.13648,1434.4633 L 914.21955,1438.596 L 915.45616,1434.422 L 919.15655,1421.9366 L 922.71994,1421.9366 L 915.96285,1443.5401 L 912.16442,1443.5401 L 908.72623,1430.6023 L 907.88647,1426.9149 L 903.51875,1443.5401 L 899.69198,1443.5401 L 899.692,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path187" />
-
-   <polygon
-   points="923.046,1444.05 931.691,1413.21 934.622,1413.21 925.997,1444.05 923.046,1444.05 "
-   style="fill:#000000;fill-rule:nonzero"
-   id="polygon189" />
-
-   <path
-   d="M 936.698,1445.33 L 940.2602,1445.858 C 940.40666,1446.9552 940.8224,1447.7536 941.49681,1448.2603 C 942.40626,1448.9335 943.64878,1449.2737 945.21846,1449.2737 C 946.92043,1449.2737 948.22555,1448.9335 949.14917,1448.2603 C 950.07279,1447.58 950.69051,1446.628 951.01649,1445.4127 C 951.21137,1444.6627 951.29523,1443.1013 951.28106,1440.7119 C 949.68421,1442.5934 947.69051,1443.5383 945.30232,1443.5383 C 942.32949,1443.5383 940.03106,1442.4694 938.40586,1440.3233 C 936.78184,1438.1843 935.96216,1435.6083 935.96216,1432.6154 C 935.96216,1430.552 936.33657,1428.6493 937.07948,1426.9072 C 937.82948,1425.1639 938.91373,1423.8162 940.32987,1422.8654 C 941.74601,1421.9206 943.41255,1421.441 945.32239,1421.441 C 947.87121,1421.441 949.97593,1422.4757 951.6283,1424.5391 L 951.6283,1421.9347 L 955.0098,1421.9347 L 955.0098,1440.6079 C 955.0098,1443.9693 954.66255,1446.3575 953.98224,1447.7607 C 953.29483,1449.1627 952.21177,1450.2741 950.72594,1451.0867 C 949.23893,1451.8993 947.41295,1452.3091 945.23972,1452.3091 C 942.66255,1452.3091 940.58027,1451.7256 938.99641,1450.5658 C 937.40665,1449.406 936.64247,1447.6626 936.69798,1445.33 L 936.698,1445.33 z M 939.72517,1432.3509 C 939.72517,1435.1844 940.28856,1437.2537 941.42005,1438.5529 C 942.54564,1439.858 943.9547,1440.5041 945.64958,1440.5041 C 947.32911,1440.5041 948.73934,1439.858 949.87793,1438.5659 C 951.01651,1437.2678 951.58699,1435.2399 951.58699,1432.469 C 951.58699,1429.8233 951.00352,1427.8308 949.82951,1426.4903 C 948.65549,1425.1497 947.23935,1424.4765 945.58699,1424.4765 C 943.96179,1424.4765 942.5799,1425.1355 941.43423,1426.4619 C 940.29565,1427.7812 939.72517,1429.7466 939.72517,1432.3509 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path191" />
-
-   <path
-   d="M 960.503,1443.54 L 960.503,1421.9365 L 963.79473,1421.9365 L 963.79473,1425.207 C 964.63449,1423.6798 965.41284,1422.6652 966.12741,1422.1798 C 966.83607,1421.6932 967.62032,1421.4428 968.47544,1421.4428 C 969.71087,1421.4428 970.96166,1421.8396 972.23843,1422.6239 L 970.97465,1426.0267 C 970.08646,1425.4916 969.19,1425.2282 968.29473,1425.2282 C 967.48922,1425.2282 966.77347,1425.4715 966.13449,1425.9499 C 965.49551,1426.4365 965.04433,1427.1026 964.77386,1427.9566 C 964.36402,1429.2558 964.16323,1430.679 964.16323,1432.2274 L 964.16323,1443.54 L 960.50299,1443.54 L 960.503,1443.54 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path193" />
-
-  </g>
-    <g
-       transform="matrix(0.317715,0,0,0.317715,415.2513,-451.5858)"
-       style="fill-rule:evenodd"
-       id="_19509096">
-   <path
-   d="M 75.3272,2384.22 L 75.853972,2387.4562 C 74.826412,2387.6712 73.902792,2387.7822 73.090192,2387.7822 C 71.757912,2387.7822 70.729172,2387.5743 69.993342,2387.1503 C 69.264602,2386.7334 68.750822,2386.1783 68.452002,2385.4909 C 68.153183,2384.8105 68.000821,2383.3661 68.000821,2381.1716 L 68.000821,2368.7405 L 65.312631,2368.7405 L 65.312631,2365.894 L 68.000821,2365.894 L 68.000821,2360.5401 L 71.645701,2358.3456 L 71.645701,2365.894 L 75.327201,2365.894 L 75.327201,2368.7405 L 71.645701,2368.7405 L 71.645701,2381.3724 C 71.645701,2382.4212 71.708299,2383.0885 71.833496,2383.3862 C 71.965779,2383.685 72.173653,2383.9212 72.465386,2384.1019 C 72.757118,2384.2755 73.174047,2384.3653 73.716176,2384.3653 C 74.124837,2384.3653 74.659877,2384.3169 75.327196,2384.22 L 75.3272,2384.22 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="_19509000" />
-
-   <path
-   d="M 93.6945,2380.54 L 97.47875,2381.0054 C 96.881112,2383.2199 95.77796,2384.9349 94.16694,2386.1573 C 92.54883,2387.3727 90.48544,2387.9845 87.97914,2387.9845 C 84.81969,2387.9845 82.31221,2387.0113 80.46497,2385.0672 C 78.61064,2383.1231 77.68702,2380.3936 77.68702,2376.8798 C 77.68702,2373.2408 78.624815,2370.4215 80.49332,2368.4148 C 82.36773,2366.4081 84.79135,2365.4006 87.77718,2365.4006 C 90.66616,2365.4006 93.02718,2366.3869 94.85435,2368.3522 C 96.68742,2370.3176 97.60396,2373.0884 97.60396,2376.6506 C 97.60396,2376.8727 97.596873,2377.1999 97.5827,2377.6298 L 81.4725,2377.6298 C 81.604783,2380.005 82.278012,2381.8239 83.48628,2383.0817 C 84.69455,2384.3455 86.19455,2384.9774 88.00045,2384.9774 C 89.33982,2384.9774 90.48549,2384.6231 91.43746,2383.9144 C 92.388247,2383.2129 93.13825,2382.0884 93.69455,2380.54 L 93.6945,2380.54 z M 81.6732,2374.6168 L 93.7358,2374.6168 C 93.576351,2372.8038 93.110997,2371.4361 92.35391,2370.5325 C 91.18698,2369.1235 89.67399,2368.4148 87.81966,2368.4148 C 86.13895,2368.4148 84.72163,2368.977 83.57596,2370.1026 C 82.43029,2371.227 81.7984,2372.7341 81.6732,2374.6168 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path197" />
-
-   <path
-   d="M 99.639,2387.5 L 107.53467,2376.2713 L 100.22837,2365.8965 L 104.80514,2365.8965 L 108.12404,2370.9587 C 108.74294,2371.9237 109.24963,2372.7292 109.62404,2373.3823 C 110.22168,2372.487 110.77089,2371.6945 111.27758,2371 L 114.91656,2365.8965 L 119.29136,2365.8965 L 111.82561,2376.0693 L 119.86065,2387.5 L 115.36774,2387.5 L 110.93034,2380.7854 L 109.74924,2378.9724 L 104.07641,2387.5 L 99.63901,2387.5 L 99.639,2387.5 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path199" />
-
-   <path
-   d="M 130.909,2384.22 L 131.43577,2387.4562 C 130.40821,2387.6712 129.48459,2387.7822 128.67199,2387.7822 C 127.33971,2387.7822 126.31097,2387.5743 125.57514,2387.1503 C 124.8464,2386.7334 124.33262,2386.1783 124.0338,2385.4909 C 123.73498,2384.8105 123.58262,2383.3661 123.58262,2381.1716 L 123.58262,2368.7405 L 120.89443,2368.7405 L 120.89443,2365.894 L 123.58262,2365.894 L 123.58262,2360.5401 L 127.2275,2358.3456 L 127.2275,2365.894 L 130.909,2365.894 L 130.909,2368.7405 L 127.2275,2368.7405 L 127.2275,2381.3724 C 127.2275,2382.4212 127.2901,2383.0885 127.4153,2383.3862 C 127.54758,2383.685 127.75545,2383.9212 128.04719,2384.1019 C 128.33892,2384.2755 128.75585,2384.3653 129.29798,2384.3653 C 129.70664,2384.3653 130.24168,2384.3169 130.909,2384.22 L 130.909,2384.22 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path201" />
-
-   <path
-   d="M 146.067,2395.78 L 146.067,2365.8993 L 149.40007,2365.8993 L 149.40007,2368.7044 C 150.1855,2367.6072 151.07369,2366.7816 152.067,2366.2324 C 153.05322,2365.6843 154.2544,2365.4056 155.66464,2365.4056 C 157.51188,2365.4056 159.13708,2365.8851 160.54614,2366.83 C 161.96228,2367.7808 163.02527,2369.1213 163.74102,2370.8505 C 164.46267,2372.5796 164.82409,2374.4753 164.82409,2376.5375 C 164.82409,2378.7461 164.42842,2380.7387 163.63,2382.5103 C 162.83748,2384.2808 161.68472,2385.6343 160.17173,2386.5792 C 158.65756,2387.517 157.06661,2387.9895 155.40008,2387.9895 C 154.17882,2387.9895 153.08748,2387.732 152.11543,2387.2182 C 151.14338,2386.7044 150.35204,2386.0513 149.72724,2385.267 L 149.72724,2395.78 L 146.067,2395.78 L 146.067,2395.78 z M 149.37999,2376.8221 C 149.37999,2379.6001 149.9422,2381.6552 151.06779,2382.9886 C 152.1922,2384.315 153.55992,2384.9823 155.15795,2384.9823 C 156.78197,2384.9823 158.17803,2384.2949 159.33787,2382.9131 C 160.49771,2381.5383 161.08118,2379.4064 161.08118,2376.5174 C 161.08118,2373.7595 160.51189,2371.7044 159.37921,2370.3296 C 158.24771,2368.9619 156.89299,2368.2745 155.32449,2368.2745 C 153.76189,2368.2745 152.38,2369.0032 151.17882,2370.4619 C 149.97646,2371.9193 149.38,2374.0453 149.38,2376.8221 L 149.37999,2376.8221 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path203" />
-
-   <path
-   d="M 169.199,2387.5 L 169.199,2365.8965 L 172.49073,2365.8965 L 172.49073,2369.167 C 173.33049,2367.6398 174.10884,2366.6252 174.82341,2366.1398 C 175.53207,2365.6532 176.31632,2365.4028 177.17144,2365.4028 C 178.40687,2365.4028 179.65766,2365.7996 180.93443,2366.5839 L 179.67065,2369.9867 C 178.78246,2369.4516 177.886,2369.1882 176.99073,2369.1882 C 176.18522,2369.1882 175.46947,2369.4315 174.83049,2369.9099 C 174.19151,2370.3965 173.74033,2371.0626 173.46986,2371.9166 C 173.06002,2373.2158 172.85923,2374.639 172.85923,2376.1874 L 172.85923,2387.5 L 169.19899,2387.5 L 169.199,2387.5 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path205" />
-
-   <path
-   d="M 181.747,2376.69 C 181.747,2372.6908 182.85842,2369.725 185.08716,2367.8022 C 186.94149,2366.2042 189.20566,2365.3987 191.8785,2365.3987 C 194.85133,2365.3987 197.28086,2366.3719 199.16354,2368.3231 C 201.05212,2370.2672 201.98992,2372.9542 201.98992,2376.3853 C 201.98992,2379.1691 201.57299,2381.3577 200.73913,2382.9475 C 199.90645,2384.5443 198.6911,2385.7809 197.10133,2386.662 C 195.5033,2387.5443 193.76708,2387.9825 191.8785,2387.9825 C 188.85842,2387.9825 186.41354,2387.0164 184.54504,2385.0723 C 182.67772,2383.1353 181.74701,2380.3431 181.74701,2376.69 L 181.747,2376.69 z M 185.51117,2376.69 C 185.51117,2379.4609 186.11471,2381.5313 187.32298,2382.9061 C 188.53125,2384.288 190.05251,2384.9754 191.87849,2384.9754 C 193.69857,2384.9754 195.21156,2384.2809 196.41983,2382.8991 C 197.62219,2381.5172 198.22574,2379.4054 198.22574,2376.5731 C 198.22574,2373.8991 197.6222,2371.8711 196.40684,2370.4963 C 195.19149,2369.1215 193.6844,2368.4341 191.87849,2368.4341 C 190.05251,2368.4341 188.53125,2369.1215 187.32298,2370.4892 C 186.11471,2371.8569 185.51117,2373.9262 185.51117,2376.69 L 185.51117,2376.69 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path207" />
-
-   <path
-   d="M 206.288,2395.78 L 206.288,2365.8993 L 209.62107,2365.8993 L 209.62107,2368.7044 C 210.4065,2367.6072 211.29469,2366.7816 212.288,2366.2324 C 213.27422,2365.6843 214.4754,2365.4056 215.88564,2365.4056 C 217.73288,2365.4056 219.35808,2365.8851 220.76714,2366.83 C 222.18328,2367.7808 223.24627,2369.1213 223.96202,2370.8505 C 224.68367,2372.5796 225.04509,2374.4753 225.04509,2376.5375 C 225.04509,2378.7461 224.64942,2380.7387 223.851,2382.5103 C 223.05848,2384.2808 221.90572,2385.6343 220.39273,2386.5792 C 218.87856,2387.517 217.28761,2387.9895 215.62108,2387.9895 C 214.39982,2387.9895 213.30848,2387.732 212.33643,2387.2182 C 211.36438,2386.7044 210.57304,2386.0513 209.94824,2385.267 L 209.94824,2395.78 L 206.288,2395.78 L 206.288,2395.78 z M 209.60099,2376.8221 C 209.60099,2379.6001 210.1632,2381.6552 211.28879,2382.9886 C 212.4132,2384.315 213.78092,2384.9823 215.37895,2384.9823 C 217.00297,2384.9823 218.39903,2384.2949 219.55887,2382.9131 C 220.71871,2381.5383 221.30218,2379.4064 221.30218,2376.5174 C 221.30218,2373.7595 220.73289,2371.7044 219.60021,2370.3296 C 218.46871,2368.9619 217.11399,2368.2745 215.54549,2368.2745 C 213.98289,2368.2745 212.601,2369.0032 211.39982,2370.4619 C 210.19746,2371.9193 209.601,2374.0453 209.601,2376.8221 L 209.60099,2376.8221 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path209" />
-
-   <path
-   d="M 228.093,2376.69 C 228.093,2372.6908 229.20442,2369.725 231.43316,2367.8022 C 233.28749,2366.2042 235.55166,2365.3987 238.2245,2365.3987 C 241.19733,2365.3987 243.62686,2366.3719 245.50954,2368.3231 C 247.39812,2370.2672 248.33592,2372.9542 248.33592,2376.3853 C 248.33592,2379.1691 247.91899,2381.3577 247.08513,2382.9475 C 246.25245,2384.5443 245.0371,2385.7809 243.44733,2386.662 C 241.8493,2387.5443 240.11308,2387.9825 238.2245,2387.9825 C 235.20442,2387.9825 232.75954,2387.0164 230.89104,2385.0723 C 229.02372,2383.1353 228.09301,2380.3431 228.09301,2376.69 L 228.093,2376.69 z M 231.85717,2376.69 C 231.85717,2379.4609 232.46071,2381.5313 233.66898,2382.9061 C 234.87725,2384.288 236.39851,2384.9754 238.22449,2384.9754 C 240.04457,2384.9754 241.55756,2384.2809 242.76583,2382.8991 C 243.96819,2381.5172 244.57174,2379.4054 244.57174,2376.5731 C 244.57174,2373.8991 243.9682,2371.8711 242.75284,2370.4963 C 241.53749,2369.1215 240.0304,2368.4341 238.22449,2368.4341 C 236.39851,2368.4341 234.87725,2369.1215 233.66898,2370.4892 C 232.46071,2371.8569 231.85717,2373.9262 231.85717,2376.69 L 231.85717,2376.69 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path211" />
-
-   <path
-   d="M 252.593,2387.5 L 252.593,2365.8965 L 255.88473,2365.8965 L 255.88473,2369.167 C 256.72449,2367.6398 257.50284,2366.6252 258.21741,2366.1398 C 258.92607,2365.6532 259.71032,2365.4028 260.56544,2365.4028 C 261.80087,2365.4028 263.05166,2365.7996 264.32843,2366.5839 L 263.06465,2369.9867 C 262.17646,2369.4516 261.28,2369.1882 260.38473,2369.1882 C 259.57922,2369.1882 258.86347,2369.4315 258.22449,2369.9099 C 257.58551,2370.3965 257.13433,2371.0626 256.86386,2371.9166 C 256.45402,2373.2158 256.25323,2374.639 256.25323,2376.1874 L 256.25323,2387.5 L 252.59299,2387.5 L 252.593,2387.5 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path213" />
-
-   <path
-   d="M 274.502,2384.22 L 275.02877,2387.4562 C 274.00121,2387.6712 273.07759,2387.7822 272.26499,2387.7822 C 270.93271,2387.7822 269.90397,2387.5743 269.16814,2387.1503 C 268.4394,2386.7334 267.92562,2386.1783 267.6268,2385.4909 C 267.32798,2384.8105 267.17562,2383.3661 267.17562,2381.1716 L 267.17562,2368.7405 L 264.48743,2368.7405 L 264.48743,2365.894 L 267.17562,2365.894 L 267.17562,2360.5401 L 270.8205,2358.3456 L 270.8205,2365.894 L 274.502,2365.894 L 274.502,2368.7405 L 270.8205,2368.7405 L 270.8205,2381.3724 C 270.8205,2382.4212 270.8831,2383.0885 271.0083,2383.3862 C 271.14058,2383.685 271.34845,2383.9212 271.64019,2384.1019 C 271.93192,2384.2755 272.34885,2384.3653 272.89098,2384.3653 C 273.29964,2384.3653 273.83468,2384.3169 274.502,2384.22 L 274.502,2384.22 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path215" />
-
-   <path
-   d="M 278.099,2361.89 L 278.099,2357.6758 L 281.76514,2357.6758 L 281.76514,2361.89 L 278.099,2361.89 z M 278.099,2387.501 L 278.099,2365.8975 L 281.76514,2365.8975 L 281.76514,2387.501 L 278.099,2387.501 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path217" />
-
-   <path
-   d="M 285.973,2376.69 C 285.973,2372.6908 287.08442,2369.725 289.31316,2367.8022 C 291.16749,2366.2042 293.43166,2365.3987 296.1045,2365.3987 C 299.07733,2365.3987 301.50686,2366.3719 303.38954,2368.3231 C 305.27812,2370.2672 306.21592,2372.9542 306.21592,2376.3853 C 306.21592,2379.1691 305.79899,2381.3577 304.96513,2382.9475 C 304.13245,2384.5443 302.9171,2385.7809 301.32733,2386.662 C 299.7293,2387.5443 297.99308,2387.9825 296.1045,2387.9825 C 293.08442,2387.9825 290.63954,2387.0164 288.77104,2385.0723 C 286.90372,2383.1353 285.97301,2380.3431 285.97301,2376.69 L 285.973,2376.69 z M 289.73717,2376.69 C 289.73717,2379.4609 290.34071,2381.5313 291.54898,2382.9061 C 292.75725,2384.288 294.27851,2384.9754 296.10449,2384.9754 C 297.92457,2384.9754 299.43756,2384.2809 300.64583,2382.8991 C 301.84819,2381.5172 302.45174,2379.4054 302.45174,2376.5731 C 302.45174,2373.8991 301.8482,2371.8711 300.63284,2370.4963 C 299.41749,2369.1215 297.9104,2368.4341 296.10449,2368.4341 C 294.27851,2368.4341 292.75725,2369.1215 291.54898,2370.4892 C 290.34071,2371.8569 289.73717,2373.9262 289.73717,2376.69 L 289.73717,2376.69 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path219" />
-
-   <path
-   d="M 310.514,2387.5 L 310.514,2365.8965 L 313.80573,2365.8965 L 313.80573,2368.9662 C 315.39667,2366.591 317.68801,2365.4028 320.68093,2365.4028 C 321.98605,2365.4028 323.18014,2365.639 324.27148,2366.1044 C 325.36872,2366.5768 326.18014,2367.1874 326.72227,2367.9516 C 327.27148,2368.7087 327.64589,2369.6111 327.86794,2370.6528 C 328.00022,2371.3343 328.06991,2372.5213 328.06991,2374.2162 L 328.06991,2387.5001 L 324.40259,2387.5001 L 324.40259,2374.3544 C 324.40259,2372.8686 324.2644,2371.7501 323.97975,2371.0071 C 323.69511,2370.2713 323.18723,2369.6808 322.46558,2369.2438 C 321.73684,2368.7997 320.88881,2368.5764 319.90967,2368.5764 C 318.34707,2368.5764 317.0077,2369.0772 315.86794,2370.0634 C 314.73644,2371.0556 314.17424,2372.9312 314.17424,2375.702 L 314.17424,2387.5 L 310.514,2387.5 L 310.514,2387.5 z "
-   style="fill:#000000;fill-rule:nonzero"
-   id="path221" />
-
-  </g>
-    <path
-       d="M 88.126188,369.03622 C 88.126188,356.61906 103.01889,346.69059 127.84056,346.69059 C 152.66211,346.69059 167.55494,356.61906 167.55494,369.02307 L 167.55494,406.26181 C 167.55494,417.22297 158.65917,426.11874 147.698,426.11874 L 107.98331,426.11874 C 94.282043,426.11874 83.162145,437.23902 83.162145,450.94029 L 83.162145,468.32206 L 68.269064,468.30894 C 55.851904,468.30894 45.923056,453.41586 45.923056,428.59425 C 45.923056,403.7727 55.851904,388.87987 68.269064,388.87987 L 127.84063,388.893 L 127.84063,383.92876 L 88.126252,383.92876 L 88.126252,369.03606 L 88.126188,369.03622 z M 105.49443,359.10775 C 109.61173,359.10775 112.94774,362.44376 112.94774,366.54753 C 112.94774,370.66483 109.61173,374.00045 105.49443,374.00045 C 101.39066,374.00045 98.041501,370.66483 98.041501,366.54753 C 98.041501,362.44376 101.39063,359.10775 105.49443,359.10775 z "
-       style="fill:url(#pyBlue);fill-opacity:1;fill-rule:evenodd"
-       id="path223" />
-    <g
-       transform="matrix(0.317715,0,0,0.317715,-71.39343,-151.2348)"
-       style="fill-rule:evenodd"
-       id="_19487936">
-   <g
-   id="g226">
-    <path
-   d="M 1200.75,1694 C 1269.1252,1692.8331 1300.1244,1757.1665 1300.7079,1830.124 C 1300.7079,1894.4575 1268.5418,1954.749 1199.6259,1957.041 C 1171.459,1957.041 1147.3338,1948.4166 1123.792,1934.0827 L 1123.792,2082.8327 L 1082.418,2067.874 L 1083.0003,1737.625 C 1082.418,1737.625 1115.1676,1694.5833 1200.1683,1693.4163 L 1200.7506,1693.9998 L 1200.75,1694 z M 1190.4177,1927.166 C 1245.5421,1923.7491 1252.4586,1869.7503 1252.4586,1827.2495 C 1252.4586,1785.8743 1245.5421,1723.8745 1193.2925,1721.5835 C 1157.6669,1719.2496 1128.959,1735.9162 1123.2094,1741.667 L 1123.2094,1905.375 C 1137,1913.9581 1164.5834,1928.9167 1190.4177,1927.1663 L 1190.4177,1927.166 z "
-   style="fill:#6a6a6a"
-   id="_19487984" />
-
-    <path
-   d="M 1387.87,1869.75 L 1387.87,1693.416 L 1345.3704,1707.7912 L 1345.3704,1882.3742 C 1345.3704,1928.9155 1388.4535,1955.9155 1426.3704,1955.9155 C 1475.7452,1955.9155 1503.9121,1942.1238 1516.5369,1936.3742 C 1517.1204,1942.6659 1516.5369,1940.9569 1516.5369,1947.2899 C 1516.5369,1965.6655 1515.9534,1997.2493 1507.3704,2013.3324 C 1490.1204,2046.082 1444.1613,2050.6659 1411.9952,2055.2485 L 1418.9117,2081.665 C 1461.4113,2080.5406 1521.1197,2064.4575 1542.3697,2024.2481 C 1554.4536,2001.2485 1556.1614,1957.0398 1556.1614,1927.7485 L 1556.1614,1699.7485 L 1514.2453,1699.7485 L 1514.2453,1904.7905 C 1500.4536,1913.957 1475.2028,1926.6244 1452.7866,1927.1653 C 1415.4531,1927.7488 1387.8697,1907.6653 1387.8697,1869.1661 L 1387.8697,1869.7496 L 1387.87,1869.75 z "
-   style="fill:#6a6a6a"
-   id="_19488200" />
-
-    <path
-   d="M 1626.62,1726.75 L 1626.62,1891.583 C 1626.62,1934.6661 1659.9117,1959.9169 1715.6196,1954.7495 L 1715.6196,1932.9168 C 1686.3283,1931.7912 1668.5361,1923.7491 1668.5361,1890.416 L 1668.5361,1726.749 L 1715.6196,1726.749 L 1715.6196,1699.749 L 1668.5361,1699.749 L 1668.5361,1614.7498 L 1626.62,1629.6671 L 1626.62,1699.749 L 1597.8696,1699.749 L 1597.8696,1726.749 L 1626.62,1726.749 L 1626.62,1726.75 z "
-   style="fill:#6a6a6a"
-   id="_19488488" />
-
-    <path
-   d="M 1970.21,1951.29 L 1970.21,1776.123 C 1970.21,1732.4565 1940.3352,1697.999 1895.5431,1697.999 C 1861.6266,1697.999 1832.9187,1708.9147 1807.6691,1727.2903 L 1807.6691,1550.9993 L 1765.7104,1564.2087 L 1765.7104,1951.2897 L 1807.6691,1951.2897 L 1807.6691,1757.1647 C 1828.9183,1742.2474 1853.0435,1726.7478 1879.46,1726.7478 C 1913.3352,1726.7478 1927.7104,1760.0395 1927.7104,1789.3309 L 1927.7104,1951.2899 L 1970.21,1951.2899 L 1970.21,1951.29 z "
-   style="fill:#6a6a6a"
-   id="_126749024" />
-
-    <path
-   d="M 2007.75,1820.92 C 2007.75,1890.4196 2044.5,1955.92 2122.041,1956.462 C 2200.1662,1955.9199 2238.042,1890.4195 2238.042,1820.92 C 2237.4999,1753.1696 2195.0003,1694.003 2122.625,1693.42 C 2050.8341,1694.0035 2007.751,1753.1696 2007.751,1820.92 L 2007.75,1820.92 z M 2053.1244,1820.92 C 2053.1244,1775.5444 2064.5823,1725.5861 2122.0405,1722.1279 C 2176.0405,1725.0039 2192.1248,1775.5444 2192.1248,1820.92 C 2192.1248,1869.1704 2181.75,1928.92 2123.1661,1930.628 C 2069.2074,1930.0445 2053.7078,1869.1705 2053.7078,1820.92 L 2053.1243,1820.92 L 2053.1244,1820.92 z "
-   style="fill:#6a6a6a"
-   id="_126677456" />
-
-    <path
-   d="M 2477.04,1951.29 L 2477.04,1758.873 C 2477.04,1724.999 2450.0813,1703.1651 2419.6231,1696.2899 C 2389.7483,1689.4147 2361.6239,1695.1655 2340.957,1700.8738 C 2314.4991,1707.7903 2295.5814,1719.8317 2274.3322,1735.3313 L 2274.3322,1951.2903 L 2316.2483,1951.2903 L 2316.2483,1740.4993 C 2329.4566,1731.3327 2350.707,1721.5828 2373.0818,1720.9993 C 2409.8731,1720.4158 2435.1239,1741.6662 2435.1239,1780.1654 L 2435.1239,1951.2904 L 2477.04,1951.2904 L 2477.04,1951.29 z "
-   style="fill:#6a6a6a"
-   id="_126678176" />
-
-   </g>
-
-  </g>
-    <path
-       d="M 167.55462,488.16664 C 167.55462,500.58418 152.66192,510.51265 127.84025,510.51265 C 103.0187,510.51265 88.12587,500.58418 88.12587,488.17979 L 88.12587,450.94105 C 88.12587,439.97988 97.021636,431.08374 107.9828,431.08374 L 147.6975,431.08374 C 161.39877,431.08374 172.51904,419.96384 172.51904,406.26257 L 172.51904,388.8808 L 187.41174,388.89392 C 199.81575,388.89392 209.7446,403.787 209.7446,428.60829 C 209.7446,453.42984 199.81575,468.32298 187.41174,468.32298 L 127.84018,468.30986 L 127.84018,473.2741 L 167.55456,473.2741 L 167.55456,488.1668 L 167.55462,488.16664 z M 150.17323,498.0951 C 146.06946,498.0951 142.73345,494.75948 142.73345,490.65533 C 142.73345,486.53841 146.06946,483.2024 150.17323,483.2024 C 154.29015,483.2024 157.62615,486.53841 157.62615,490.65533 C 157.62615,494.75948 154.29015,498.0951 150.17323,498.0951 z "
-       style="fill:url(#pyYellow);fill-opacity:1;fill-rule:evenodd"
-       id="path234" />
-  </g>
-</svg>
diff --git a/PC/icons/source.xar b/PC/icons/source.xar
deleted file mode 100644 (file)
index 84cbbc4..0000000
Binary files a/PC/icons/source.xar and /dev/null differ
index 53c8289..5d1c90a 100644 (file)
@@ -368,7 +368,7 @@ Py_NO_ENABLE_SHARED to find out.  Also support MS_NO_COREDLL for b/w compat */
 #      define SIZEOF_FPOS_T 8
 #      define SIZEOF_HKEY 4
 #      define SIZEOF_SIZE_T 4
-       /* MS VS2005 changes time_t to an 64-bit type on all platforms */
+       /* MS VS2005 changes time_t to a 64-bit type on all platforms */
 #      if defined(_MSC_VER) && _MSC_VER >= 1400
 #      define SIZEOF_TIME_T 8
 #      else
index ae16097..19bcbdd 100644 (file)
@@ -61,7 +61,7 @@ BEGIN
             VALUE "FileDescription", "Python Core\0"
             VALUE "FileVersion", PYTHON_VERSION
             VALUE "InternalName", "Python DLL\0"
-            VALUE "LegalCopyright", "Copyright © 2001-2015 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
+            VALUE "LegalCopyright", "Copyright © 2001-2016 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
             VALUE "OriginalFilename", PYTHON_DLL_NAME "\0"
             VALUE "ProductName", "Python\0"
             VALUE "ProductVersion", PYTHON_VERSION
index 0f98966..5616a1e 100644 (file)
@@ -61,7 +61,7 @@
   </PropertyGroup>
   <ItemDefinitionGroup>
     <ClCompile>
-      <AdditionalIncludeDirectories>$(opensslDir)include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(opensslIncludeDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <AdditionalDependencies>ws2_32.lib;$(OutDir)libeay$(PyDebugExt).lib;$(OutDir)ssleay$(PyDebugExt).lib;%(AdditionalDependencies)</AdditionalDependencies>
index fff23c7..73c9571 100644 (file)
@@ -61,7 +61,7 @@
   </PropertyGroup>
   <ItemDefinitionGroup>
     <ClCompile>
-      <AdditionalIncludeDirectories>$(opensslDir)include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(opensslIncludeDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <AdditionalDependencies>ws2_32.lib;crypt32.lib;$(OutDir)libeay$(PyDebugExt).lib;$(OutDir)ssleay$(PyDebugExt).lib;%(AdditionalDependencies)</AdditionalDependencies>
index f3dcc91..766378f 100644 (file)
@@ -24,6 +24,8 @@ echo.  -M  Disable parallel build (disabled by default)
 echo.  -v  Increased output messages\r
 echo.  -k  Attempt to kill any running Pythons before building (usually done\r
 echo.      automatically by the pythoncore project)\r
+echo.  --pgo          Build with Profile-Guided Optimization.  This flag\r
+echo.                 overrides -c and -d\r
 echo.\r
 echo.Available flags to avoid building certain modules.\r
 echo.These flags have no effect if '-e' is not given:\r
@@ -38,6 +40,8 @@ echo.  -p x64 ^| Win32
 echo.     Set the platform (default: Win32)\r
 echo.  -t Build ^| Rebuild ^| Clean ^| CleanAll\r
 echo.     Set the target manually\r
+echo.  --pgo-job  The job to use for PGO training; implies --pgo\r
+echo.             (default: "-m test.regrtest --pgo")\r
 exit /b 127\r
 \r
 :Run\r
@@ -50,6 +54,12 @@ set dir=%~dp0
 set parallel=\r
 set verbose=/nologo /v:m\r
 set kill=\r
+set do_pgo=\r
+set pgo_job=-m test.regrtest --pgo\r
+set on_64_bit=true\r
+\r
+rem This may not be 100% accurate, but close enough.\r
+if "%ProgramFiles(x86)%"=="" (set on_64_bit=false)\r
 \r
 :CheckOpts\r
 if "%~1"=="-h" goto Usage\r
@@ -62,6 +72,8 @@ if "%~1"=="-m" (set parallel=/m) & shift & goto CheckOpts
 if "%~1"=="-M" (set parallel=) & shift & goto CheckOpts\r
 if "%~1"=="-v" (set verbose=/v:n) & shift & goto CheckOpts\r
 if "%~1"=="-k" (set kill=true) & shift & goto CheckOpts\r
+if "%~1"=="--pgo" (set do_pgo=true) & shift & goto CheckOpts\r
+if "%~1"=="--pgo-job" (set do_pgo=true) & (set pgo_job=%~2) & shift & shift & goto CheckOpts\r
 rem These use the actual property names used by MSBuild.  We could just let\r
 rem them in through the environment, but we specify them on the command line\r
 rem anyway for visibility so set defaults after this\r
@@ -77,15 +89,49 @@ if "%IncludeBsddb%"=="" set IncludeBsddb=true
 \r
 if "%IncludeExternals%"=="true" call "%dir%get_externals.bat"\r
 \r
-if "%platf%"=="x64" (set vs_platf=x86_amd64)\r
+if "%platf%"=="x64" (\r
+    if "%on_64_bit%"=="true" (\r
+        rem This ought to always be correct these days...\r
+        set vs_platf=amd64\r
+    ) else (\r
+        if "%do_pgo%"=="true" (\r
+            echo.ERROR: Cannot cross-compile with PGO\r
+            echo.    32bit operating system detected, if this is incorrect,\r
+            echo.    make sure the ProgramFiles(x86^) environment variable is set\r
+            exit /b 1\r
+        )\r
+        set vs_platf=x86_amd64\r
+    )\r
+)\r
 \r
 rem Setup the environment\r
 call "%dir%env.bat" %vs_platf% >nul\r
 \r
-if "%kill%"=="true" (\r
-    msbuild /v:m /nologo /target:KillPython "%dir%\pythoncore.vcxproj" /p:Configuration=%conf% /p:Platform=%platf% /p:KillPython=true\r
+if "%kill%"=="true" call :Kill\r
+\r
+if "%do_pgo%"=="true" (\r
+    set conf=PGInstrument\r
+    call :Build\r
+    del /s "%dir%\*.pgc"\r
+    del /s "%dir%\..\Lib\*.pyc"\r
+    echo on\r
+    call "%dir%\..\python.bat" %pgo_job%\r
+    @echo off\r
+    call :Kill\r
+    set conf=PGUpdate\r
 )\r
+goto Build\r
+\r
+:Kill\r
+echo on\r
+msbuild "%dir%\pythoncore.vcxproj" /t:KillPython %verbose%^\r
+ /p:Configuration=%conf% /p:Platform=%platf%^\r
+ /p:KillPython=true\r
+\r
+@echo off\r
+goto :eof\r
 \r
+:Build\r
 rem Call on MSBuild to do the work, echo the command.\r
 rem Passing %1-9 is not the preferred option, but argument parsing in\r
 rem batch is, shall we say, "lackluster"\r
@@ -96,3 +142,6 @@ msbuild "%dir%pcbuild.proj" /t:%target% %parallel% %verbose%^
  /p:IncludeSSL=%IncludeSSL% /p:IncludeTkinter=%IncludeTkinter%^\r
  /p:IncludeBsddb=%IncludeBsddb%^\r
  %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+\r
+@echo off\r
+goto :eof\r
index 79ec267..872c382 100644 (file)
@@ -1,48 +1,6 @@
 @echo off\r
-rem A batch program to build PGO (Profile guided optimization) by first\r
-rem building instrumented binaries, then running the testsuite, and\r
-rem finally building the optimized code.\r
-rem Note, after the first instrumented run, one can just keep on\r
-rem building the PGUpdate configuration while developing.\r
+echo.DeprecationWarning:\r
+echo.    This script is deprecated, use `build.bat --pgo` instead.\r
+echo.\r
 \r
-setlocal\r
-set platf=Win32\r
-set parallel=/m\r
-set dir=%~dp0\r
-\r
-rem use the performance testsuite.  This is quick and simple\r
-set job1="%dir%..\tools\pybench\pybench.py" -n 1 -C 1 --with-gc\r
-set path1="%dir%..\tools\pybench"\r
-\r
-rem or the whole testsuite for more thorough testing\r
-set job2="%dir%..\lib\test\regrtest.py"\r
-set path2="%dir%..\lib"\r
-\r
-set job=%job1%\r
-set clrpath=%path1%\r
-\r
-:CheckOpts\r
-if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts\r
-if "%1"=="-2" (set job=%job2%) & (set clrpath=%path2%) & shift & goto CheckOpts\r
-if "%1"=="-M" (set parallel=) & shift & goto CheckOpts\r
-\r
-\r
-rem We cannot cross compile PGO builds, as the optimization needs to be run natively\r
-set vs_platf=x86\r
-set PGO=%dir%win32-pgo\r
-\r
-if "%platf%"=="x64" (set vs_platf=amd64) & (set PGO=%dir%amd64-pgo)\r
-rem Setup the environment\r
-call "%dir%env.bat" %vs_platf%\r
-\r
-\r
-rem build the instrumented version\r
-msbuild "%dir%pcbuild.proj" %parallel% /t:Build /p:Configuration=PGInstrument /p:Platform=%platf% %1 %2 %3 %4 %5 %6 %7 %8 %9\r
-\r
-rem remove .pyc files, .pgc files and execute the job\r
-"%PGO%\python.exe" "%dir%rmpyc.py" %clrpath%\r
-del "%PGO%\*.pgc"\r
-"%PGO%\python.exe" %job%\r
-\r
-rem build optimized version\r
-msbuild "%dir%pcbuild.proj" %parallel% /t:Build /p:Configuration=PGUpdate /p:Platform=%platf% %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+call "%~dp0build.bat" --pgo %*\r
index ec8a695..1719cc1 100644 (file)
@@ -10,6 +10,12 @@ rem other than 'v90' is supported!
 \r
 echo Build environments: x86, amd64, x86_amd64\r
 echo.\r
+\r
+rem Set up the v90 tools first.  This is mostly needed to allow PGInstrument\r
+rem builds to find the PGO DLL.  Do it first so the newer MSBuild is found\r
+rem before the one from v90 (vcvarsall.bat prepends to PATH).\r
+call "%VS90COMNTOOLS%..\..\VC\vcvarsall.bat" %*\r
+\r
 set VSTOOLS=%VS140COMNTOOLS%\r
 if "%VSTOOLS%"=="" set VSTOOLS=%VS120COMNTOOLS%\r
 if "%VSTOOLS%"=="" set VSTOOLS=%VS110COMNTOOLS%\r
index ffd1a16..90b1068 100644 (file)
@@ -58,8 +58,8 @@ set libraries=
 set libraries=%libraries%                                    bzip2-1.0.6\r
 if NOT "%IncludeBsddb%"=="false" set libraries=%libraries%   db-4.7.25.0\r
 if NOT "%IncludeSSL%"=="false" set libraries=%libraries%     nasm-2.11.06\r
-if NOT "%IncludeSSL%"=="false" set libraries=%libraries%     openssl-1.0.2d\r
-set libraries=%libraries%                                    sqlite-3.6.21\r
+if NOT "%IncludeSSL%"=="false" set libraries=%libraries%     openssl-1.0.2h\r
+set libraries=%libraries%                                    sqlite-3.8.11.0\r
 if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tcl-8.5.15.0\r
 if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tk-8.5.15.0\r
 if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tix-8.4.3.5\r
index 54f3596..e45964e 100644 (file)
@@ -15,9 +15,8 @@
     <PreprocessorDefinitions Include="_CRT_SECURE_NO_WARNINGS" />
     <PreprocessorDefinitions Include="_CRT_SECURE_NO_DEPRECATE" />
     <PreprocessorDefinitions Include="OPENSSL_THREADS" />
-    <PreprocessorDefinitions Include="OPENSSL_SYSNAME_WIN32" />
+    <!-- <PreprocessorDefinitions Include="OPENSSL_SYSNAME_WIN32" /> -->
     <PreprocessorDefinitions Include="OPENSSL_IA32_SSE2" />
-    <PreprocessorDefinitions Include="OPENSSL_CPUID_OBJ" />
     <PreprocessorDefinitions Include="SHA1_ASM" />
     <PreprocessorDefinitions Include="SHA256_ASM" />
     <PreprocessorDefinitions Include="SHA512_ASM" />
@@ -51,7 +50,7 @@
     <ClCompile>
       <!-- Suppress 64-bit truncation warnings - they aren't ours to worry about -->
       <DisableSpecificWarnings>4244;4267</DisableSpecificWarnings>
-      <AdditionalIncludeDirectories>$(opensslDir);$(opensslDir)include;$(opensslDir)crypto;$(opensslDir)crypto\asn1;$(opensslDir)crypto\evp;$(opensslDir)crypto\modes</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(opensslDir);$(opensslIncludeDir);$(opensslDir)crypto;$(opensslDir)crypto\asn1;$(opensslDir)crypto\evp;$(opensslDir)crypto\modes</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>$(_PreprocessorDefinitionList);%(PreprocessorDefinitions)</PreprocessorDefinitions>
     </ClCompile>
   </ItemDefinitionGroup>
index fc93347..34938ea 100644 (file)
@@ -49,6 +49,9 @@
       <WholeProgramOptimization>false</WholeProgramOptimization>
       <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
     </ClCompile>
+    <ClCompile Condition="$(ICCBuild) == 'true'">
+      <FloatingPointModel>Strict</FloatingPointModel>
+    </ClCompile>
     <Link>
       <AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <GenerateDebugInformation>true</GenerateDebugInformation>
index 245e571..e40751a 100644 (file)
@@ -11,6 +11,8 @@
     Give a default for BasePlatformToolset as well, it's used by ICC and ignored otherwise
     -->
     <BasePlatformToolset Condition="'$(BasePlatformToolset)' == '' and '$(PlatformToolset)' != 'v90'">v90</BasePlatformToolset>
+    <ICCBuild>false</ICCBuild>
+    <ICCBuild Condition="$(PlatformToolset.StartsWith('Intel C++ Compiler'))">true</ICCBuild>
     <!--
     Convincing MSVC/MSBuild to prefer our platform names is too difficult,
     so we define our own constant ArchName and use wherever we need it.
 
     <!-- Directories of external projects. tcltk is handled in tcltk.props -->
     <ExternalsDir>$([System.IO.Path]::GetFullPath(`$(PySourcePath)externals\`))</ExternalsDir>
-    <sqlite3Dir>$(ExternalsDir)sqlite-3.6.21\</sqlite3Dir>
+    <sqlite3Dir>$(ExternalsDir)sqlite-3.8.11.0\</sqlite3Dir>
     <bz2Dir>$(ExternalsDir)bzip2-1.0.6\</bz2Dir>
     <bsddbDir>$(ExternalsDir)db-4.7.25.0</bsddbDir>
-    <opensslDir>$(ExternalsDir)openssl-1.0.2d\</opensslDir>
+    <opensslDir>$(ExternalsDir)openssl-1.0.2h\</opensslDir>
+    <opensslIncludeDir>$(opensslDir)include32</opensslIncludeDir>
+    <opensslIncludeDir Condition="'$(ArchName)' == 'amd64'">$(opensslDir)include64</opensslIncludeDir>
     <nasmDir>$(ExternalsDir)\nasm-2.11.06\</nasmDir>
 
     <!-- Suffix for all binaries when building for debug -->
 
     <!-- The version number for sys.winver -->
     <SysWinVer>$(MajorVersionNumber).$(MinorVersionNumber)</SysWinVer>
-    <SysWinVer Condition="$(Platform) == 'Win32' or $(Platform) == 'x86'">$(SysWinVer)-32</SysWinVer>
   </PropertyGroup>
 
   <!-- Displays the calculated version info -->
index 2388535..7fee48f 100644 (file)
@@ -183,7 +183,7 @@ _bz2
     Homepage:\r
         http://www.bzip.org/\r
 _ssl\r
-    Python wrapper for version 1.0.2d of the OpenSSL secure sockets\r
+    Python wrapper for version 1.0.2h of the OpenSSL secure sockets\r
     library, which is built by ssl.vcxproj\r
     Homepage:\r
         http://www.openssl.org/\r
@@ -218,7 +218,7 @@ _ssl
     functionality to _ssl or _hashlib. They will not clean up their output\r
     with the normal Clean target; CleanAll should be used instead.\r
 _sqlite3\r
-    Wraps SQLite 3.6.21, which is itself built by sqlite3.vcxproj\r
+    Wraps SQLite 3.8.11.0, which is itself built by sqlite3.vcxproj\r
     Homepage:\r
         http://www.sqlite.org/\r
 _tkinter\r
index 92d6547..8e8c0cc 100644 (file)
@@ -528,8 +528,7 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
                     goto handle_error;
                 }
                 else if (!is_true) {
-                    Py_DECREF(*filename);
-                    *filename = PyString_FromString("__main__");
+                    Py_SETREF(*filename, PyString_FromString("__main__"));
                     if (*filename == NULL)
                         goto handle_error;
                 }
index d99b676..2977bcd 100644 (file)
@@ -625,7 +625,7 @@ builtin_divmod(PyObject *self, PyObject *args)
 PyDoc_STRVAR(divmod_doc,
 "divmod(x, y) -> (quotient, remainder)\n\
 \n\
-Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.");
+Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.");
 
 
 static PyObject *
index 4fcf25e..0b747d8 100644 (file)
@@ -4360,8 +4360,7 @@ call_function(PyObject ***pp_stack, int oparg
             Py_INCREF(self);
             func = PyMethod_GET_FUNCTION(func);
             Py_INCREF(func);
-            Py_DECREF(*pfunc);
-            *pfunc = self;
+            Py_SETREF(*pfunc, self);
             na++;
             n++;
         } else
@@ -4616,10 +4615,12 @@ ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
             PyObject *t = NULL;
             t = PySequence_Tuple(stararg);
             if (t == NULL) {
-                if (PyErr_ExceptionMatches(PyExc_TypeError)) {
+                if (PyErr_ExceptionMatches(PyExc_TypeError) &&
+                        /* Don't mask TypeError raised from a generator */
+                        !PyGen_Check(stararg)) {
                     PyErr_Format(PyExc_TypeError,
                                  "%.200s%.200s argument after * "
-                                 "must be a sequence, not %200s",
+                                 "must be an iterable, not %200s",
                                  PyEval_GetFuncName(func),
                                  PyEval_GetFuncDesc(func),
                                  stararg->ob_type->tp_name);
index d672362..dbecd1d 100644 (file)
@@ -334,7 +334,7 @@ PyObject *PyCodec_StreamWriter(const char *encoding,
     return codec_getstreamcodec(encoding, stream, errors, 3);
 }
 
-/* Encode an object (e.g. an Unicode object) using the given encoding
+/* Encode an object (e.g. a Unicode object) using the given encoding
    and return the resulting encoded object (usually a Python string).
 
    errors is passed to the encoder factory as argument if non-NULL. */
@@ -379,7 +379,7 @@ _PyCodec_EncodeInternal(PyObject *object,
 }
 
 /* Decode an object (usually a Python string) using the given encoding
-   and return an equivalent object (e.g. an Unicode object).
+   and return an equivalent object (e.g. a Unicode object).
 
    errors is passed to the decoder factory as argument if non-NULL. */
 
index 2900757..51f2874 100644 (file)
@@ -338,7 +338,7 @@ list2dict(PyObject *list)
             return NULL;
         }
         k = PyList_GET_ITEM(list, i);
-        k = PyTuple_Pack(2, k, k->ob_type);
+        k = _PyCode_ConstantKey(k);
         if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
             Py_XDECREF(k);
             Py_DECREF(v);
@@ -399,7 +399,7 @@ dictbytype(PyObject *src, int scope_type, int flag, int offset)
                 return NULL;
             }
             i++;
-            tuple = PyTuple_Pack(2, k, k->ob_type);
+            tuple = _PyCode_ConstantKey(k);
             if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
                 Py_DECREF(sorted_keys);
                 Py_DECREF(item);
@@ -944,49 +944,8 @@ compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
 {
     PyObject *t, *v;
     Py_ssize_t arg;
-    double d;
-
-    /* necessary to make sure types aren't coerced (e.g., int and long) */
-    /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
-    if (PyFloat_Check(o)) {
-        d = PyFloat_AS_DOUBLE(o);
-        /* all we need is to make the tuple different in either the 0.0
-         * or -0.0 case from all others, just to avoid the "coercion".
-         */
-        if (d == 0.0 && copysign(1.0, d) < 0.0)
-            t = PyTuple_Pack(3, o, o->ob_type, Py_None);
-        else
-            t = PyTuple_Pack(2, o, o->ob_type);
-    }
-#ifndef WITHOUT_COMPLEX
-    else if (PyComplex_Check(o)) {
-        Py_complex z;
-        int real_negzero, imag_negzero;
-        /* For the complex case we must make complex(x, 0.)
-           different from complex(x, -0.) and complex(0., y)
-           different from complex(-0., y), for any x and y.
-           All four complex zeros must be distinguished.*/
-        z = PyComplex_AsCComplex(o);
-        real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
-        imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
-        if (real_negzero && imag_negzero) {
-            t = PyTuple_Pack(5, o, o->ob_type,
-                             Py_None, Py_None, Py_None);
-        }
-        else if (imag_negzero) {
-            t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
-        }
-        else if (real_negzero) {
-            t = PyTuple_Pack(3, o, o->ob_type, Py_None);
-        }
-        else {
-            t = PyTuple_Pack(2, o, o->ob_type);
-        }
-    }
-#endif /* WITHOUT_COMPLEX */
-    else {
-        t = PyTuple_Pack(2, o, o->ob_type);
-    }
+
+    t = _PyCode_ConstantKey(o);
     if (t == NULL)
         return -1;
 
@@ -1287,7 +1246,7 @@ static int
 compiler_lookup_arg(PyObject *dict, PyObject *name)
 {
     PyObject *k, *v;
-    k = PyTuple_Pack(2, name, name->ob_type);
+    k = _PyCode_ConstantKey(name);
     if (k == NULL)
         return -1;
     v = PyDict_GetItem(dict, k);
@@ -1455,9 +1414,8 @@ compiler_class(struct compiler *c, stmt_ty s)
     if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
                               s->lineno))
         return 0;
-    Py_XDECREF(c->u->u_private);
-    c->u->u_private = s->v.ClassDef.name;
-    Py_INCREF(c->u->u_private);
+    Py_INCREF(s->v.ClassDef.name);
+    Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
     str = PyString_InternFromString("__name__");
     if (!str || !compiler_nameop(c, str, Load)) {
         Py_XDECREF(str);
@@ -3795,7 +3753,7 @@ dict_keys_inorder(PyObject *dict, int offset)
         i = PyInt_AS_LONG(v);
         /* The keys of the dictionary are tuples. (see compiler_add_o)
            The object we want is always first, though. */
-        k = PyTuple_GET_ITEM(k, 0);
+        k = PyTuple_GET_ITEM(k, 1);
         Py_INCREF(k);
         assert((i - offset) < size);
         assert((i - offset) >= 0);
index 00dfd3e..d823e13 100644 (file)
@@ -227,14 +227,11 @@ finally:
     tstate = PyThreadState_GET();
     if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
         --tstate->recursion_depth;
-        /* throw away the old exception... */
-        Py_DECREF(*exc);
-        Py_DECREF(*val);
-        /* ... and use the recursion error instead */
-        *exc = PyExc_RuntimeError;
-        *val = PyExc_RecursionErrorInst;
-        Py_INCREF(*exc);
-        Py_INCREF(*val);
+        /* throw away the old exception and use the recursion error instead */
+        Py_INCREF(PyExc_RuntimeError);
+        Py_SETREF(*exc, PyExc_RuntimeError);
+        Py_INCREF(PyExc_RecursionErrorInst);
+        Py_SETREF(*val, PyExc_RecursionErrorInst);
         /* just keeping the old traceback */
         return;
     }
@@ -535,7 +532,7 @@ PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
 #endif /* MS_WINDOWS */
 
 void
-_PyErr_BadInternalCall(char *filename, int lineno)
+_PyErr_BadInternalCall(const char *filename, int lineno)
 {
     PyErr_Format(PyExc_SystemError,
                  "%s:%d: bad argument to internal function",
@@ -699,12 +696,18 @@ PyErr_WriteUnraisable(PyObject *obj)
                 PyFile_WriteString(className, f);
             if (v && v != Py_None) {
                 PyFile_WriteString(": ", f);
-                PyFile_WriteObject(v, f, 0);
+                if (PyFile_WriteObject(v, f, 0) < 0) {
+                    PyErr_Clear();
+                    PyFile_WriteString("<exception repr() failed>", f);
+                }
             }
             Py_XDECREF(moduleName);
         }
         PyFile_WriteString(" in ", f);
-        PyFile_WriteObject(obj, f, 0);
+        if (PyFile_WriteObject(obj, f, 0) < 0) {
+            PyErr_Clear();
+            PyFile_WriteString("<object repr() failed>", f);
+        }
         PyFile_WriteString(" ignored\n", f);
         PyErr_Clear(); /* Just in case */
     }
index 81a2721..bd15c2e 100644 (file)
@@ -346,7 +346,7 @@ vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags)
                           flags, levels, msgbuf,
                           sizeof(msgbuf), &freelist);
         if (msg) {
-            seterror(i+1, msg, levels, fname, msg);
+            seterror(i+1, msg, levels, fname, message);
             return cleanreturn(0, freelist);
         }
     }
@@ -533,9 +533,17 @@ converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize)
 {
     assert(expected != NULL);
     assert(arg != NULL);
-    PyOS_snprintf(msgbuf, bufsize,
-                  "must be %.50s, not %.50s", expected,
-                  arg == Py_None ? "None" : arg->ob_type->tp_name);
+    if (expected[0] == '(') {
+        PyOS_snprintf(msgbuf, bufsize,
+                      "%.100s", expected);
+        strncpy(msgbuf, expected, bufsize);
+        msgbuf[bufsize-1] = '\0';
+    }
+    else {
+        PyOS_snprintf(msgbuf, bufsize,
+                      "must be %.50s, not %.50s", expected,
+                      arg == Py_None ? "None" : arg->ob_type->tp_name);
+    }
     return msgbuf;
 }
 
@@ -753,7 +761,7 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
         else if (PyLong_Check(arg))
             ival = PyLong_AsUnsignedLongMask(arg);
         else
-            return converterr("integer<k>", arg, msgbuf, bufsize);
+            return converterr("an integer", arg, msgbuf, bufsize);
         *p = ival;
         break;
     }
@@ -781,7 +789,7 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
         else if (PyLong_Check(arg))
             ival = PyLong_AsUnsignedLongLongMask(arg);
         else
-            return converterr("integer<K>", arg, msgbuf, bufsize);
+            return converterr("an integer", arg, msgbuf, bufsize);
         *p = ival;
         break;
     }
@@ -1127,9 +1135,11 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
             } else {
                 if (size + 1 > BUFFER_LEN) {
                     Py_DECREF(s);
-                    return converterr(
-                        "(buffer overflow)",
-                        arg, msgbuf, bufsize);
+                    PyErr_Format(PyExc_TypeError,
+                                 "encoded string too long "
+                                 "(%zd, maximum length %zd)",
+                                 (Py_ssize_t)size, (Py_ssize_t)(BUFFER_LEN-1));
+                    return "";
                 }
             }
             memcpy(*buffer,
@@ -1154,7 +1164,7 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
                                                     != size) {
                 Py_DECREF(s);
                 return converterr(
-                    "encoded string without NULL bytes",
+                    "encoded string without null bytes",
                     arg, msgbuf, bufsize);
             }
             *buffer = PyMem_NEW(char, size + 1);
@@ -1261,7 +1271,6 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
         break;
     }
 
-
     case 'w': { /* memory buffer, read-write access */
         void **p = va_arg(*p_va, void **);
         void *res;
@@ -1353,7 +1362,7 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
     }
 
     default:
-        return converterr("impossible<bad format char>", arg, msgbuf, bufsize);
+        return converterr("(impossible<bad format char>)", arg, msgbuf, bufsize);
 
     }
 
index 913e1d2..c97eaeb 100644 (file)
@@ -4,7 +4,7 @@
 
 static char cprt[] = 
 "\
-Copyright (c) 2001-2015 Python Software Foundation.\n\
+Copyright (c) 2001-2016 Python Software Foundation.\n\
 All Rights Reserved.\n\
 \n\
 Copyright (c) 2000 BeOpen.com.\n\
index e47ce63..96f7d47 100644 (file)
@@ -632,27 +632,45 @@ _PyImport_FindExtension(char *name, char *filename)
    Because the former action is most common, THIS DOES NOT RETURN A
    'NEW' REFERENCE! */
 
-PyObject *
-PyImport_AddModule(const char *name)
+static PyObject *
+_PyImport_AddModuleObject(PyObject *name)
 {
     PyObject *modules = PyImport_GetModuleDict();
     PyObject *m;
 
-    if ((m = PyDict_GetItemString(modules, name)) != NULL &&
-        PyModule_Check(m))
+    if ((m = _PyDict_GetItemWithError(modules, name)) != NULL &&
+        PyModule_Check(m)) {
         return m;
-    m = PyModule_New(name);
-    if (m == NULL)
+    }
+    if (PyErr_Occurred()) {
+        return NULL;
+    }
+    m = PyModule_New(PyString_AS_STRING(name));
+    if (m == NULL) {
         return NULL;
-    if (PyDict_SetItemString(modules, name, m) != 0) {
+    }
+    if (PyDict_SetItem(modules, name, m) != 0) {
         Py_DECREF(m);
         return NULL;
     }
+    assert(Py_REFCNT(m) > 1);
     Py_DECREF(m); /* Yes, it still exists, in modules! */
 
     return m;
 }
 
+PyObject *
+PyImport_AddModule(const char *name)
+{
+    PyObject *nameobj, *module;
+    nameobj = PyString_FromString(name);
+    if (nameobj == NULL)
+        return NULL;
+    module = _PyImport_AddModuleObject(nameobj);
+    Py_DECREF(nameobj);
+    return module;
+}
+
 /* Remove name from sys.modules, if it's there. */
 static void
 remove_module(const char *name)
index 8bdec8b..ebe62c3 100644 (file)
@@ -156,48 +156,83 @@ static PyObject *do_mkdict(const char**, va_list *, int, int, int);
 static PyObject *do_mkvalue(const char**, va_list *, int);
 
 
+static void
+do_ignore(const char **p_format, va_list *p_va, int endchar, int n, int flags)
+{
+    PyObject *v;
+    int i;
+    assert(PyErr_Occurred());
+    v = PyTuple_New(n);
+    for (i = 0; i < n; i++) {
+        PyObject *exception, *value, *tb, *w;
+        PyErr_Fetch(&exception, &value, &tb);
+        w = do_mkvalue(p_format, p_va, flags);
+        PyErr_Restore(exception, value, tb);
+        if (w != NULL) {
+            if (v != NULL) {
+                PyTuple_SET_ITEM(v, i, w);
+            }
+            else {
+                Py_DECREF(w);
+            }
+        }
+    }
+    Py_XDECREF(v);
+    if (**p_format != endchar) {
+        PyErr_SetString(PyExc_SystemError,
+                        "Unmatched paren in format");
+        return;
+    }
+    if (endchar)
+        ++*p_format;
+}
+
 static PyObject *
 do_mkdict(const char **p_format, va_list *p_va, int endchar, int n, int flags)
 {
     PyObject *d;
     int i;
-    int itemfailed = 0;
     if (n < 0)
         return NULL;
-    if ((d = PyDict_New()) == NULL)
+    if (n % 2) {
+        PyErr_SetString(PyExc_SystemError,
+                        "Bad dict format");
+        do_ignore(p_format, p_va, endchar, n, flags);
         return NULL;
+    }
     /* Note that we can't bail immediately on error as this will leak
        refcounts on any 'N' arguments. */
+    if ((d = PyDict_New()) == NULL) {
+        do_ignore(p_format, p_va, endchar, n, flags);
+        return NULL;
+    }
     for (i = 0; i < n; i+= 2) {
         PyObject *k, *v;
-        int err;
+
         k = do_mkvalue(p_format, p_va, flags);
         if (k == NULL) {
-            itemfailed = 1;
-            Py_INCREF(Py_None);
-            k = Py_None;
+            do_ignore(p_format, p_va, endchar, n - i - 1, flags);
+            Py_DECREF(d);
+            return NULL;
         }
         v = do_mkvalue(p_format, p_va, flags);
-        if (v == NULL) {
-            itemfailed = 1;
-            Py_INCREF(Py_None);
-            v = Py_None;
-        }
-        err = PyDict_SetItem(d, k, v);
-        Py_DECREF(k);
-        Py_DECREF(v);
-        if (err < 0 || itemfailed) {
+        if (v == NULL || PyDict_SetItem(d, k, v) < 0) {
+            do_ignore(p_format, p_va, endchar, n - i - 2, flags);
+            Py_DECREF(k);
+            Py_XDECREF(v);
             Py_DECREF(d);
             return NULL;
         }
+        Py_DECREF(k);
+        Py_DECREF(v);
     }
-    if (d != NULL && **p_format != endchar) {
+    if (**p_format != endchar) {
         Py_DECREF(d);
-        d = NULL;
         PyErr_SetString(PyExc_SystemError,
                         "Unmatched paren in format");
+        return NULL;
     }
-    else if (endchar)
+    if (endchar)
         ++*p_format;
     return d;
 }
@@ -207,29 +242,24 @@ do_mklist(const char **p_format, va_list *p_va, int endchar, int n, int flags)
 {
     PyObject *v;
     int i;
-    int itemfailed = 0;
     if (n < 0)
         return NULL;
-    v = PyList_New(n);
-    if (v == NULL)
-        return NULL;
     /* Note that we can't bail immediately on error as this will leak
        refcounts on any 'N' arguments. */
+    v = PyList_New(n);
+    if (v == NULL) {
+        do_ignore(p_format, p_va, endchar, n, flags);
+        return NULL;
+    }
     for (i = 0; i < n; i++) {
         PyObject *w = do_mkvalue(p_format, p_va, flags);
         if (w == NULL) {
-            itemfailed = 1;
-            Py_INCREF(Py_None);
-            w = Py_None;
+            do_ignore(p_format, p_va, endchar, n - i - 1, flags);
+            Py_DECREF(v);
+            return NULL;
         }
         PyList_SET_ITEM(v, i, w);
     }
-
-    if (itemfailed) {
-        /* do_mkvalue() should have already set an error */
-        Py_DECREF(v);
-        return NULL;
-    }
     if (**p_format != endchar) {
         Py_DECREF(v);
         PyErr_SetString(PyExc_SystemError,
@@ -257,27 +287,23 @@ do_mktuple(const char **p_format, va_list *p_va, int endchar, int n, int flags)
 {
     PyObject *v;
     int i;
-    int itemfailed = 0;
     if (n < 0)
         return NULL;
-    if ((v = PyTuple_New(n)) == NULL)
-        return NULL;
     /* Note that we can't bail immediately on error as this will leak
        refcounts on any 'N' arguments. */
+    if ((v = PyTuple_New(n)) == NULL) {
+        do_ignore(p_format, p_va, endchar, n, flags);
+        return NULL;
+    }
     for (i = 0; i < n; i++) {
         PyObject *w = do_mkvalue(p_format, p_va, flags);
         if (w == NULL) {
-            itemfailed = 1;
-            Py_INCREF(Py_None);
-            w = Py_None;
+            do_ignore(p_format, p_va, endchar, n - i - 1, flags);
+            Py_DECREF(v);
+            return NULL;
         }
         PyTuple_SET_ITEM(v, i, w);
     }
-    if (itemfailed) {
-        /* do_mkvalue() should have already set an error */
-        Py_DECREF(v);
-        return NULL;
-    }
     if (**p_format != endchar) {
         Py_DECREF(v);
         PyErr_SetString(PyExc_SystemError,
index e3bc004..11f6f88 100644 (file)
@@ -289,7 +289,7 @@ markblocks(unsigned char *code, Py_ssize_t len)
    allows us to avoid overflow and sign issues.  Likewise, it bails when
    the lineno table has complex encoding for gaps >= 255.
 
-   Optimizations are restricted to simple transformations occuring within a
+   Optimizations are restricted to simple transformations occurring within a
    single basic block.  All transformations keep the code size the same or
    smaller.  For those that reduce size, the gaps are initially filled with
    NOPs.  Later those NOPs are removed and the jump addresses retargeted in
index ece709c..7b85268 100644 (file)
@@ -1299,8 +1299,11 @@ PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
             /* only print colon if the str() of the
                object is not the empty string
             */
-            if (s == NULL)
+            if (s == NULL) {
+                PyErr_Clear();
                 err = -1;
+                PyFile_WriteString(": <exception str() failed>", f);
+            }
             else if (!PyString_Check(s) ||
                      PyString_GET_SIZE(s) != 0)
                 err = PyFile_WriteString(": ", f);
@@ -1309,6 +1312,9 @@ PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
             Py_XDECREF(s);
         }
         /* try to write a newline in any case */
+        if (err < 0) {
+            PyErr_Clear();
+        }
         err += PyFile_WriteString("\n", f);
     }
     Py_DECREF(value);
@@ -1913,7 +1919,7 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler)
 #endif
 }
 
-/* Deprecated C API functions still provided for binary compatiblity */
+/* Deprecated C API functions still provided for binary compatibility */
 
 #undef PyParser_SimpleParseFile
 PyAPI_FUNC(node *)
index 50f4ac9..b4bc1f3 100644 (file)
@@ -93,7 +93,7 @@ win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
     return 0;
 }
 
-/* Issue #25003: Don' use getentropy() on Solaris (available since
+/* Issue #25003: Don't use getentropy() on Solaris (available since
  * Solaris 11.3), it is blocking whereas os.urandom() should not block. */
 #elif defined(HAVE_GETENTROPY) && !defined(sun)
 #define PY_GETENTROPY 1
index 8d4b0d3..137f12c 100644 (file)
@@ -738,7 +738,7 @@ analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
 
     /* Copy the bound and global dictionaries.
 
-       These dictionary are used by all blocks enclosed by the
+       These dictionaries are used by all blocks enclosed by the
        current block.  The analyze_block() call modifies these
        dictionaries.
 
index 9796a34..a161d7c 100644 (file)
@@ -178,7 +178,7 @@ PyThread_start_new_thread(void (*func)(void *), void *arg)
 }
 
 /*
- * Return the thread Id instead of an handle. The Id is said to uniquely identify the
+ * Return the thread Id instead of a handle. The Id is said to uniquely identify the
  * thread in the system
  */
 long
index 51ddc02..b9c10da 100644 (file)
@@ -42,7 +42,7 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg)
 }
 
 /*
- * Return the thread Id instead of an handle. The Id is said to uniquely identify the
+ * Return the thread Id instead of a handle. The Id is said to uniquely identify the
  * thread in the system
  */
 long PyThread_get_thread_ident(void)
index adfd66c..fd5309a 100644 (file)
@@ -170,10 +170,6 @@ _Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent)
 
     if (xfp == NULL)
         return err;
-    if (err != 0) {
-        fclose(xfp);
-        return err;
-    }
 
     for (i = 0; i < lineno; i++) {
         char* pLastChar = &linebuf[sizeof(linebuf)-2];
diff --git a/README b/README
index 16b7a46..9b27c32 100644 (file)
--- a/README
+++ b/README
@@ -1,8 +1,8 @@
-This is Python version 2.7.11
+This is Python version 2.7.12
 =============================
 
 Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013, 2014, 2015 Python Software Foundation.  All rights reserved.
+2012, 2013, 2014, 2015, 2016 Python Software Foundation.  All rights reserved.
 
 Copyright (c) 2000 BeOpen.com.
 All rights reserved.
@@ -197,7 +197,7 @@ PGO takes advantage of recent versions of the GCC or Clang compilers.
 If ran, the "profile-opt" rule will do several steps.
 
 First, the entire Python directory is cleaned of temporary files that
-may resulted in a previous compilation.
+may have resulted in a previous compilation.
 
 Then, an instrumented version of the interpreter is built, using suitable
 compiler flags for each flavour. Note that this is just an intermediary
@@ -210,7 +210,7 @@ profile the interpreter execution. Note also that any output, both stdout
 and stderr, that may appear at this step is supressed.
 
 Finally, the last step is to rebuild the interpreter, using the information
-collected in the previous one. The end result will be a the Python binary
+collected in the previous one. The end result will be a Python binary
 that is optimized and suitable for distribution or production installation.
 
 
index 0ad24b3..566438a 100644 (file)
@@ -20,7 +20,7 @@ class Variable:
 
     """A Variable holds a type, a name, a transfer mode and flags.
 
-    Most of its methods call the correponding type method with the
+    Most of its methods call the corresponding type method with the
     variable name.
     """
 
index 1724276..8298a7f 100644 (file)
@@ -1,7 +1,7 @@
 """Generate ast module from specification
 
 This script generates the ast module from a simple specification,
-which makes it easy to accomodate changes in the grammar.  This
+which makes it easy to accommodate changes in the grammar.  This
 approach would be quite reasonable if the grammar changed often.
 Instead, it is rather complex to generate the appropriate code.  And
 the Node interface has changed more often than the grammar.
index 390ea29..e218a31 100755 (executable)
@@ -55,11 +55,19 @@ if sys.version_info[0] >= 3:
     long = int
 
 # Look up the gdb.Type for some standard types:
-_type_char_ptr = gdb.lookup_type('char').pointer() # char*
-_type_unsigned_char_ptr = gdb.lookup_type('unsigned char').pointer() # unsigned char*
-_type_void_ptr = gdb.lookup_type('void').pointer() # void*
+# Those need to be refreshed as types (pointer sizes) may change when
+# gdb loads different executables
 
-SIZEOF_VOID_P = _type_void_ptr.sizeof
+def _type_char_ptr():
+    return gdb.lookup_type('char').pointer()  # char*
+
+
+def _type_unsigned_char_ptr():
+    return gdb.lookup_type('unsigned char').pointer()  # unsigned char*
+
+
+def _sizeof_void_p():
+    return gdb.lookup_type('void').pointer().sizeof
 
 
 Py_TPFLAGS_HEAPTYPE = (1 << 9)
@@ -84,7 +92,7 @@ class NullPyObjectPtr(RuntimeError):
 
 
 def safety_limit(val):
-    # Given a integer value from the process being debugged, limit it to some
+    # Given an integer value from the process being debugged, limit it to some
     # safety threshold so that arbitrary breakage within said process doesn't
     # break the gdb process too much (e.g. sizes of iterations, sizes of lists)
     return min(val, 1000)
@@ -132,7 +140,7 @@ class TruncatedStringIO(object):
 
 class PyObjectPtr(object):
     """
-    Class wrapping a gdb.Value that's either a (PyObject*) within the
+    Class wrapping a gdb.Value that's either a (PyObject*) within the
     inferior process, or some subclass pointer e.g. (PyStringObject*)
 
     There will be a subclass for every refined PyObject type that we care
@@ -439,8 +447,8 @@ def _PyObject_VAR_SIZE(typeobj, nitems):
 
     return ( ( typeobj.field('tp_basicsize') +
                nitems * typeobj.field('tp_itemsize') +
-               (SIZEOF_VOID_P - 1)
-             ) & ~(SIZEOF_VOID_P - 1)
+               (_sizeof_void_p() - 1)
+             ) & ~(_sizeof_void_p() - 1)
            ).cast(_PyObject_VAR_SIZE._type_size_t)
 _PyObject_VAR_SIZE._type_size_t = None
 
@@ -464,9 +472,9 @@ class HeapTypeObjectPtr(PyObjectPtr):
                     size = _PyObject_VAR_SIZE(typeobj, tsize)
                     dictoffset += size
                     assert dictoffset > 0
-                    assert dictoffset % SIZEOF_VOID_P == 0
+                    assert dictoffset % _sizeof_void_p() == 0
 
-                dictptr = self._gdbval.cast(_type_char_ptr) + dictoffset
+                dictptr = self._gdbval.cast(_type_char_ptr()) + dictoffset
                 PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
                 dictptr = dictptr.cast(PyObjectPtrPtr)
                 return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
@@ -1014,7 +1022,7 @@ class PyStringObjectPtr(PyObjectPtr):
     def __str__(self):
         field_ob_size = self.field('ob_size')
         field_ob_sval = self.field('ob_sval')
-        char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr)
+        char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr())
         # When gdb is linked with a Python 3 interpreter, this is really
         # a latin-1 mojibake decoding of the original string...
         return ''.join([chr(char_ptr[i]) for i in safe_range(field_ob_size)])
index 219c0ed..3ef4a65 100644 (file)
@@ -259,7 +259,7 @@ def remove_old_versions(db):
     # either both per-machine or per-user.
     migrate_features = 1
     # See "Upgrade Table". We remove releases with the same major and
-    # minor version. For an snapshot, we remove all earlier snapshots. For
+    # minor version. For a snapshot, we remove all earlier snapshots. For
     # a release, we remove all snapshots, and all earlier releases.
     if snapshot:
         add_data(db, "Upgrade",
@@ -1436,6 +1436,7 @@ merge(msiname, "SharedCRT", "TARGETDIR", modules)
 if certname:
     os.system('signtool sign /n "%s" '
       '/t http://timestamp.verisign.com/scripts/timestamp.dll '
+      '/fd SHA256 '
       '/d "Python %s" '
       '%s' % (certname, full_current_version, msiname))
 
index d028a11..b3032f8 100644 (file)
@@ -731,7 +731,7 @@ _Validation_records = [
 (u'CustomAction',u'Type',u'N',1,16383,None, None, None, None, u'The numeric custom action type, consisting of source location, code type, entry, option flags.',),
 (u'CustomAction',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Primary key, name of action, normally appears in sequence table unless private use.',),
 (u'CustomAction',u'Source',u'Y',None, None, None, None, u'CustomSource',None, u'The table reference of the source of the code.',),
-(u'CustomAction',u'Target',u'Y',None, None, None, None, u'Formatted',None, u'Excecution parameter, depends on the type of custom action',),
+(u'CustomAction',u'Target',u'Y',None, None, None, None, u'Formatted',None, u'Execution parameter, depends on the type of custom action',),
 (u'DrLocator',u'Signature_',u'N',None, None, None, None, u'Identifier',None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature table.',),
 (u'DrLocator',u'Path',u'Y',None, None, None, None, u'AnyPath',None, u'The path on the user system. This is a either a subpath below the value of the Parent or a full path. The path may contain properties enclosed within [ ] that will be expanded.',),
 (u'DrLocator',u'Depth',u'Y',0,32767,None, None, None, None, u'The depth below the path to which the Signature_ is recursively searched. If absent, the depth is assumed to be 0.',),
@@ -958,7 +958,7 @@ _Validation_records = [
 (u'ServiceInstall',u'StartType',u'N',0,4,None, None, None, None, u'Type of the service',),
 (u'Shortcut',u'Name',u'N',None, None, None, None, u'Filename',None, u'The name of the shortcut to be created.',),
 (u'Shortcut',u'Description',u'Y',None, None, None, None, u'Text',None, u'The description for the shortcut.',),
-(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.',),
+(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the shortcut creation/deletion.',),
 (u'Shortcut',u'Icon_',u'Y',None, None, u'Icon',1,u'Identifier',None, u'Foreign key into the File table denoting the external icon file for the shortcut.',),
 (u'Shortcut',u'IconIndex',u'Y',-32767,32767,None, None, None, None, u'The icon index for the shortcut.',),
 (u'Shortcut',u'Directory_',u'N',None, None, u'Directory',1,u'Identifier',None, u'Foreign key into the Directory table denoting the directory where the shortcut file is created.',),
index 2bdf59e..456d9ae 100644 (file)
@@ -996,7 +996,7 @@ _Validation = [
 (u'CustomAction', u'Type', u'N', 1, 16383, None, None, None, None, u'The numeric custom action type, consisting of source location, code type, entry, option flags.'),
 (u'CustomAction', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Primary key, name of action, normally appears in sequence table unless private use.'),
 (u'CustomAction', u'Source', u'Y', None, None, None, None, u'CustomSource', None, u'The table reference of the source of the code.'),
-(u'CustomAction', u'Target', u'Y', None, None, None, None, u'Formatted', None, u'Excecution parameter, depends on the type of custom action'),
+(u'CustomAction', u'Target', u'Y', None, None, None, None, u'Formatted', None, u'Execution parameter, depends on the type of custom action'),
 (u'DrLocator', u'Signature_', u'N', None, None, None, None, u'Identifier', None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature table.'),
 (u'DrLocator', u'Path', u'Y', None, None, None, None, u'AnyPath', None, u'The path on the user system. This is a either a subpath below the value of the Parent or a full path. The path may contain properties enclosed within [ ] that will be expanded.'),
 (u'DrLocator', u'Depth', u'Y', 0, 32767, None, None, None, None, u'The depth below the path to which the Signature_ is recursively searched. If absent, the depth is assumed to be 0.'),
@@ -1195,7 +1195,7 @@ _Validation = [
 (u'ServiceInstall', u'StartType', u'N', 0, 4, None, None, None, None, u'Type of the service'),
 (u'Shortcut', u'Name', u'N', None, None, None, None, u'Filename', None, u'The name of the shortcut to be created.'),
 (u'Shortcut', u'Description', u'Y', None, None, None, None, u'Text', None, u'The description for the shortcut.'),
-(u'Shortcut', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.'),
+(u'Shortcut', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table denoting the component whose selection gates the shortcut creation/deletion.'),
 (u'Shortcut', u'Icon_', u'Y', None, None, u'Icon', 1, u'Identifier', None, u'Foreign key into the File table denoting the external icon file for the shortcut.'),
 (u'Shortcut', u'IconIndex', u'Y', -32767, 32767, None, None, None, None, u'The icon index for the shortcut.'),
 (u'Shortcut', u'Directory_', u'N', None, None, u'Directory', 1, u'Identifier', None, u'Foreign key into the Directory table denoting the directory where the shortcut file is created.'),
index 70b1a66..79ea7e5 100755 (executable)
@@ -32,7 +32,7 @@ except ImportError:
                          "no sophisticated Python source file search will be done.")
 
 
-decl_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)')
+decl_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)')
 blank_re = re.compile(r'^[ \t\f]*(?:[#\r\n]|$)')
 
 def get_declaration(line):
index 7dab897..6b8e37f 100755 (executable)
--- a/configure
+++ b/configure
@@ -667,6 +667,7 @@ LLVM_PROF_FILE
 LLVM_PROF_MERGER
 PGO_PROF_USE_FLAG
 PGO_PROF_GEN_FLAG
+LTOFLAGS
 UNIVERSAL_ARCH_FLAGS
 BASECFLAGS
 OPT
@@ -743,6 +744,7 @@ build_os
 build_vendor
 build_cpu
 build
+cross_compiling
 target_alias
 host_alias
 build_alias
@@ -789,11 +791,13 @@ with_universal_archs
 with_framework_name
 enable_framework
 with_gcc
+with_icc
 with_cxx_main
 with_suffix
 enable_shared
 enable_profiling
 with_pydebug
+with_lto
 enable_toolbox_glue
 with_libs
 with_system_expat
@@ -1469,11 +1473,14 @@ Optional Packages:
                           specify an alternate name of the framework built
                           with --enable-framework
   --without-gcc           never use gcc
+  --with-icc              build with icc
   --with-cxx-main=<compiler>
                           compile main() and link python executable with C++
                           compiler
   --with-suffix=.exe      set executable suffix
   --with-pydebug          build with Py_DEBUG defined
+  --with-lto              Enable Link Time Optimization in PGO builds.
+                          Disabled by default.
   --with-libs='lib1 ...'  link against additional libs
   --with-system-expat     build pyexpat module using an installed expat
                           library
@@ -3375,7 +3382,7 @@ fi
 #
 # SGI compilers allow the specification of the both the ABI and the
 # ISA on the command line.  Depending on the values of these switches,
-# different and often incompatable code will be generated.
+# different and often incompatible code will be generated.
 #
 # The SGI_ABI variable can be used to modify the CC and LDFLAGS and
 # thus supply support for various ABI/ISA combinations.  The MACHDEP
@@ -3480,6 +3487,29 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $without_gcc" >&5
 $as_echo "$without_gcc" >&6; }
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-icc" >&5
+$as_echo_n "checking for --with-icc... " >&6; }
+
+# Check whether --with-icc was given.
+if test "${with_icc+set}" = set; then :
+  withval=$with_icc;
+       case $withval in
+       no)     CC=${CC:-cc}
+               with_icc=no;;
+       yes)    CC=icc
+               CXX=icpc
+               with_icc=yes;;
+       *)      CC=$withval
+               with_icc=$withval;;
+       esac
+else
+
+       with_icc=no
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_icc" >&5
+$as_echo "$with_icc" >&6; }
+
 # If the user switches compilers, we can't believe the cache
 if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC"
 then
@@ -6188,6 +6218,13 @@ $as_echo "$CC" >&6; }
     ;;
 esac
 
+# ICC needs -fp-model strict or floats behave badly
+case "$CC" in
+*icc*)
+    BASECFLAGS="$BASECFLAGS -fp-model strict"
+    ;;
+esac
+
 if test "$Py_DEBUG" = 'true'; then
   :
 else
@@ -6333,7 +6370,56 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
 
+# Enable LTO flags
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-lto" >&5
+$as_echo_n "checking for --with-lto... " >&6; }
+
+# Check whether --with-lto was given.
+if test "${with_lto+set}" = set; then :
+  withval=$with_lto;
+if test "$withval" != no
+then
+  Py_LTO='true'
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; };
+else
+  Py_LTO='false'
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; };
+fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+if test "$Py_LTO" = 'true' ; then
+  case $CC in
+    *clang*)
+      # Any changes made here should be reflected in the GCC+Darwin case below
+      LTOFLAGS="-flto"
+      ;;
+    *gcc*)
+      case $ac_sys_system in
+        Darwin*)
+          LTOFLAGS="-flto"
+          ;;
+        *)
+          LTOFLAGS="-flto -fuse-linker-plugin -ffat-lto-objects -flto-partition=none"
+          ;;
+      esac
+      ;;
+  esac
+fi
+
+
 # Enable PGO flags.
+
+
+
+
+
+
 # Extract the first word of "llvm-profdata", so it can be a program name with args.
 set dummy llvm-profdata; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
@@ -6405,6 +6491,12 @@ case $CC in
         ;;
     esac
     ;;
+  *icc*)
+    PGO_PROF_GEN_FLAG="-prof-gen"
+    PGO_PROF_USE_FLAG="-prof-use"
+    LLVM_PROF_MERGER="true"
+    LLVM_PROF_FILE=""
+    ;;
 esac
 
 
@@ -11918,19 +12010,9 @@ cat >>confdefs.h <<_ACEOF
 _ACEOF
 
 
-$as_echo "#define HAVE_ST_BLOCKS 1" >>confdefs.h
-
-else
-  case " $LIBOBJS " in
-  *" fileblocks.$ac_objext "* ) ;;
-  *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext"
- ;;
-esac
-
 fi
 
 
-
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for time.h that defines altzone" >&5
 $as_echo_n "checking for time.h that defines altzone... " >&6; }
 if ${ac_cv_header_time_altzone+:} false; then :
@@ -13891,6 +13973,50 @@ $as_echo "#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1" >>confdefs.h
 fi
 
 
+# also in 4.0, but not in editline
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_resize_terminal in -lreadline" >&5
+$as_echo_n "checking for rl_resize_terminal in -lreadline... " >&6; }
+if ${ac_cv_lib_readline_rl_resize_terminal+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lreadline $READLINE_LIBS $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char rl_resize_terminal ();
+int
+main ()
+{
+return rl_resize_terminal ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_readline_rl_resize_terminal=yes
+else
+  ac_cv_lib_readline_rl_resize_terminal=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_resize_terminal" >&5
+$as_echo "$ac_cv_lib_readline_rl_resize_terminal" >&6; }
+if test "x$ac_cv_lib_readline_rl_resize_terminal" = xyes; then :
+
+$as_echo "#define HAVE_RL_RESIZE_TERMINAL 1" >>confdefs.h
+
+fi
+
+
 # check for readline 4.2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_matches in -lreadline" >&5
 $as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; }
index decf0ec..06c877b 100644 (file)
@@ -12,6 +12,7 @@ AC_INIT(python, PYTHON_VERSION, http://bugs.python.org/)
 AC_CONFIG_SRCDIR([Include/object.h])
 AC_CONFIG_HEADER(pyconfig.h)
 
+AC_SUBST(cross_compiling)
 AC_CANONICAL_HOST
 AC_SUBST(build)
 AC_SUBST(host)
@@ -478,7 +479,7 @@ fi
 #
 # SGI compilers allow the specification of the both the ABI and the
 # ISA on the command line.  Depending on the values of these switches,
-# different and often incompatable code will be generated.
+# different and often incompatible code will be generated.
 #
 # The SGI_ABI variable can be used to modify the CC and LDFLAGS and
 # thus supply support for various ABI/ISA combinations.  The MACHDEP
@@ -573,6 +574,22 @@ AC_ARG_WITH(gcc,
        esac])
 AC_MSG_RESULT($without_gcc)
 
+AC_MSG_CHECKING(for --with-icc)
+AC_ARG_WITH(icc,
+            AS_HELP_STRING([--with-icc], [build with icc]),
+[
+       case $withval in
+       no)     CC=${CC:-cc}
+               with_icc=no;;
+       yes)    CC=icc
+               CXX=icpc
+               with_icc=yes;;
+       *)      CC=$withval
+               with_icc=$withval;;
+       esac], [
+       with_icc=no])
+AC_MSG_RESULT($with_icc)
+
 # If the user switches compilers, we can't believe the cache
 if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC"
 then
@@ -1266,6 +1283,13 @@ yes)
     ;;
 esac
 
+# ICC needs -fp-model strict or floats behave badly
+case "$CC" in
+*icc*)
+    BASECFLAGS="$BASECFLAGS -fp-model strict"
+    ;;
+esac
+
 if test "$Py_DEBUG" = 'true'; then
   :
 else
@@ -1353,6 +1377,40 @@ then
 fi
 
 
+# Enable LTO flags
+AC_SUBST(LTOFLAGS)
+AC_MSG_CHECKING(for --with-lto)
+AC_ARG_WITH(lto, AS_HELP_STRING([--with-lto], [Enable Link Time Optimization in PGO builds. Disabled by default.]),
+[
+if test "$withval" != no
+then
+  Py_LTO='true'
+  AC_MSG_RESULT(yes);
+else
+  Py_LTO='false'
+  AC_MSG_RESULT(no);
+fi],
+[AC_MSG_RESULT(no)])
+if test "$Py_LTO" = 'true' ; then
+  case $CC in
+    *clang*)
+      # Any changes made here should be reflected in the GCC+Darwin case below
+      LTOFLAGS="-flto"
+      ;;
+    *gcc*)
+      case $ac_sys_system in
+        Darwin*)
+          LTOFLAGS="-flto"
+          ;;
+        *)
+          LTOFLAGS="-flto -fuse-linker-plugin -ffat-lto-objects -flto-partition=none"
+          ;;
+      esac
+      ;;
+  esac
+fi
+
+
 # Enable PGO flags.
 AC_SUBST(PGO_PROF_GEN_FLAG)
 AC_SUBST(PGO_PROF_USE_FLAG)
@@ -1394,6 +1452,12 @@ case $CC in
         ;;
     esac
     ;;
+  *icc*)
+    PGO_PROF_GEN_FLAG="-prof-gen"
+    PGO_PROF_USE_FLAG="-prof-use"
+    LLVM_PROF_MERGER="true"
+    LLVM_PROF_FILE=""
+    ;;
 esac
 
 
@@ -3410,7 +3474,7 @@ AC_CHECK_MEMBERS([struct stat.st_blksize])
 AC_CHECK_MEMBERS([struct stat.st_flags])
 AC_CHECK_MEMBERS([struct stat.st_gen])
 AC_CHECK_MEMBERS([struct stat.st_birthtime])
-AC_STRUCT_ST_BLOCKS
+AC_CHECK_MEMBERS([struct stat.st_blocks])
 
 AC_MSG_CHECKING(for time.h that defines altzone)
 AC_CACHE_VAL(ac_cv_header_time_altzone,[
@@ -4170,6 +4234,11 @@ AC_CHECK_LIB(readline, rl_completion_display_matches_hook,
        AC_DEFINE(HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK, 1,
         [Define if you have readline 4.0]), ,$READLINE_LIBS)
 
+# also in 4.0, but not in editline
+AC_CHECK_LIB(readline, rl_resize_terminal,
+       AC_DEFINE(HAVE_RL_RESIZE_TERMINAL, 1,
+        [Define if you have readline 4.0]), ,$READLINE_LIBS)
+
 # check for readline 4.2
 AC_CHECK_LIB(readline, rl_completion_matches,
        AC_DEFINE(HAVE_RL_COMPLETION_MATCHES, 1,
index 219bff3..7a62abf 100644 (file)
 /* Define if you have readline 4.0 */
 #undef HAVE_RL_PRE_INPUT_HOOK
 
+/* Define if you have readline 4.0 */
+#undef HAVE_RL_RESIZE_TERMINAL
+
 /* Define to 1 if you have the `round' function. */
 #undef HAVE_ROUND
 
 /* Define to 1 if `tm_zone' is a member of `struct tm'. */
 #undef HAVE_STRUCT_TM_TM_ZONE
 
-/* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use
-   `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */
-#undef HAVE_ST_BLOCKS
-
 /* Define if you have the 'symlink' function. */
 #undef HAVE_SYMLINK
 
index 6a6ad23..aa08ada 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -117,6 +117,22 @@ def find_library_file(compiler, libname, std_dirs, paths):
         p = p.rstrip(os.sep)
 
         if host_platform == 'darwin' and is_macosx_sdk_path(p):
+            # Note that, as of Xcode 7, Apple SDKs may contain textual stub
+            # libraries with .tbd extensions rather than the normal .dylib
+            # shared libraries installed in /.  The Apple compiler tool
+            # chain handles this transparently but it can cause problems
+            # for programs that are being built with an SDK and searching
+            # for specific libraries.  Distutils find_library_file() now
+            # knows to also search for and return .tbd files.  But callers
+            # of find_library_file need to keep in mind that the base filename
+            # of the returned SDK library file might have a different extension
+            # from that of the library file installed on the running system,
+            # for example:
+            #   /Applications/Xcode.app/Contents/Developer/Platforms/
+            #       MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
+            #       usr/lib/libedit.tbd
+            # vs
+            #   /usr/lib/libedit.dylib
             if os.path.join(sysroot, p[1:]) == dirname:
                 return [ ]
 
@@ -568,13 +584,17 @@ class PyBuildExt(build_ext):
 
         # array objects
         exts.append( Extension('array', ['arraymodule.c']) )
+
+        shared_math = 'Modules/_math.o'
         # complex math library functions
-        exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'],
-                               depends=['_math.h'],
+        exts.append( Extension('cmath', ['cmathmodule.c'],
+                               extra_objects=[shared_math],
+                               depends=['_math.h', shared_math],
                                libraries=math_libs) )
         # math library functions, e.g. sin()
-        exts.append( Extension('math',  ['mathmodule.c', '_math.c'],
-                               depends=['_math.h'],
+        exts.append( Extension('math',  ['mathmodule.c'],
+                               extra_objects=[shared_math],
+                               depends=['_math.h', shared_math],
                                libraries=math_libs) )
         # fast string operations implemented in C
         exts.append( Extension('strop', ['stropmodule.c']) )
@@ -749,8 +769,8 @@ class PyBuildExt(build_ext):
             if host_platform == 'darwin' and os_release < 9:
                 # In every directory on the search path search for a dynamic
                 # library and then a static library, instead of first looking
-                # for dynamic libraries on the entiry path.
-                # This way a staticly linked custom readline gets picked up
+                # for dynamic libraries on the entire path.
+                # This way a statically linked custom readline gets picked up
                 # before the (possibly broken) dynamic library in /usr/lib.
                 readline_extra_link_args = ('-Wl,-search_paths_first',)
             else:
@@ -1747,7 +1767,7 @@ class PyBuildExt(build_ext):
         #     --with-tcltk-libs="-L/path/to/tcllibs -ltclm.n \
         #                        -L/path/to/tklibs -ltkm.n"
         #
-        # These values can also be specified or overriden via make:
+        # These values can also be specified or overridden via make:
         #    make TCLTK_INCLUDES="..." TCLTK_LIBS="..."
         #
         # This can be useful for building and testing tkinter with multiple