[Python-checkins] r83814 - in python/branches/py3k-dtoa: Demo/README Demo/embed/Makefile Demo/embed/demo.c Demo/embed/loop.c Demo/pdist Demo/scripts/README Demo/scripts/toaiff.py Demo/tkinter/guido/AttrDialog.py Demo/tkinter/guido/ManPage.py Demo/tkinter/guido/brownian2.py Demo/tkinter/guido/kill.py Demo/zlib/minigzip.py Demo/zlib/zlibdemo.py Doc/Makefile Doc/README.txt Doc/c-api/init.rst Doc/c-api/unicode.rst Doc/c-api/weakref.rst Doc/conf.py Doc/distutils/apiref.rst Doc/distutils/builtdist.rst Doc/distutils/commandref.rst Doc/distutils/examples.rst Doc/distutils/setupscript.rst Doc/distutils/sourcedist.rst Doc/distutils/uploading.rst Doc/documenting/building.rst Doc/documenting/markup.rst Doc/extending/extending.rst Doc/faq/extending.rst Doc/glossary.rst Doc/howto/descriptor.rst Doc/howto/doanddont.rst Doc/install/index.rst Doc/library/2to3.rst Doc/library/abc.rst Doc/library/argparse.rst Doc/library/ast.rst Doc/library/base64.rst Doc/library/bdb.rst Doc/library/binascii.rst Doc/library/bisect.rst Doc/library/cgi.rst Doc/library/cmath.rst Doc/library/cmd.rst Doc/library/collections.rst Doc/library/configparser.rst Doc/library/constants.rst Doc/library/contextlib.rst Doc/library/datetime.rst Doc/library/dbm.rst Doc/library/doctest.rst Doc/library/email.errors.rst Doc/library/fileinput.rst Doc/library/fnmatch.rst Doc/library/ftplib.rst Doc/library/functions.rst Doc/library/functools.rst Doc/library/heapq.rst Doc/library/html.parser.rst Doc/library/http.client.rst Doc/library/http.cookiejar.rst Doc/library/importlib.rst Doc/library/io.rst Doc/library/itertools.rst Doc/library/linecache.rst Doc/library/locale.rst Doc/library/math.rst Doc/library/mmap.rst Doc/library/multiprocessing.rst Doc/library/optparse.rst Doc/library/os.path.rst Doc/library/os.rst Doc/library/parser.rst Doc/library/pdb.rst Doc/library/pickletools.rst Doc/library/pyexpat.rst Doc/library/re.rst Doc/library/select.rst Doc/library/signal.rst Doc/library/smtpd.rst Doc/library/smtplib.rst Doc/library/socket.rst Doc/library/sqlite3.rst Doc/library/stdtypes.rst Doc/library/string.rst Doc/library/struct.rst Doc/library/subprocess.rst Doc/library/sys.rst Doc/library/test.rst Doc/library/threading.rst Doc/library/tkinter.rst Doc/library/unittest.rst Doc/library/urllib.parse.rst Doc/library/urllib.request.rst Doc/library/wsgiref.rst Doc/library/xml.dom.minidom.rst Doc/library/xml.dom.rst Doc/library/xml.sax.reader.rst Doc/library/zipfile.rst Doc/license.rst Doc/make.bat Doc/reference/compound_stmts.rst Doc/reference/expressions.rst Doc/reference/lexical_analysis.rst Doc/tools/sphinx-build.py Doc/tools/sphinxext/indexsidebar.html Doc/tools/sphinxext/pyspecific.py Doc/tutorial/classes.rst Doc/tutorial/datastructures.rst Doc/tutorial/floatingpoint.rst Doc/using/cmdline.rst Doc/whatsnew/2.0.rst Doc/whatsnew/2.4.rst Doc/whatsnew/2.5.rst Doc/whatsnew/2.7.rst Doc/whatsnew/3.2.rst Grammar/Grammar Include/Python.h Include/floatobject.h Include/patchlevel.h Include/pytime.h Include/structseq.h LICENSE Lib/_abcoll.py Lib/_strptime.py Lib/argparse.py Lib/ast.py Lib/asyncore.py Lib/base64.py Lib/bdb.py Lib/cProfile.py Lib/cmd.py Lib/collections.py Lib/configparser.py Lib/ctypes/__init__.py Lib/ctypes/test/test_arrays.py Lib/ctypes/test/test_bitfields.py Lib/ctypes/test/test_buffers.py Lib/ctypes/test/test_bytes.py Lib/ctypes/test/test_callbacks.py Lib/ctypes/test/test_cast.py Lib/ctypes/test/test_cfuncs.py Lib/ctypes/test/test_errno.py Lib/ctypes/test/test_internals.py Lib/ctypes/test/test_keeprefs.py Lib/ctypes/test/test_libc.py Lib/ctypes/test/test_loading.py Lib/ctypes/test/test_objects.py Lib/ctypes/test/test_parameters.py Lib/ctypes/test/test_prototypes.py Lib/ctypes/test/test_python_api.py Lib/ctypes/test/test_random_things.py Lib/ctypes/test/test_repr.py Lib/ctypes/test/test_returnfuncptrs.py Lib/ctypes/test/test_stringptr.py Lib/ctypes/test/test_strings.py Lib/ctypes/test/test_structures.py Lib/ctypes/test/test_unicode.py Lib/curses/wrapper.py Lib/datetime.py Lib/dbm/__init__.py Lib/decimal.py Lib/distutils/__init__.py Lib/distutils/archive_util.py Lib/distutils/bcppcompiler.py Lib/distutils/ccompiler.py Lib/distutils/cmd.py Lib/distutils/command/bdist.py Lib/distutils/command/bdist_dumb.py Lib/distutils/command/bdist_msi.py Lib/distutils/command/bdist_rpm.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/build.py Lib/distutils/command/build_clib.py Lib/distutils/command/build_ext.py Lib/distutils/command/build_py.py Lib/distutils/command/build_scripts.py Lib/distutils/command/config.py Lib/distutils/command/install.py Lib/distutils/command/register.py Lib/distutils/command/sdist.py Lib/distutils/command/upload.py Lib/distutils/config.py Lib/distutils/core.py Lib/distutils/cygwinccompiler.py Lib/distutils/dep_util.py Lib/distutils/dir_util.py Lib/distutils/dist.py Lib/distutils/emxccompiler.py Lib/distutils/errors.py Lib/distutils/extension.py Lib/distutils/fancy_getopt.py Lib/distutils/file_util.py Lib/distutils/filelist.py Lib/distutils/msvc9compiler.py Lib/distutils/msvccompiler.py Lib/distutils/sysconfig.py Lib/distutils/tests/support.py Lib/distutils/tests/test_archive_util.py Lib/distutils/tests/test_bdist.py Lib/distutils/tests/test_bdist_dumb.py Lib/distutils/tests/test_bdist_rpm.py Lib/distutils/tests/test_bdist_wininst.py Lib/distutils/tests/test_build_clib.py Lib/distutils/tests/test_build_ext.py Lib/distutils/tests/test_build_py.py Lib/distutils/tests/test_build_scripts.py Lib/distutils/tests/test_ccompiler.py Lib/distutils/tests/test_cmd.py Lib/distutils/tests/test_cygwinccompiler.py Lib/distutils/tests/test_dist.py Lib/distutils/tests/test_emxccompiler.py Lib/distutils/tests/test_extension.py Lib/distutils/tests/test_file_util.py Lib/distutils/tests/test_filelist.py Lib/distutils/tests/test_install.py Lib/distutils/tests/test_install_lib.py Lib/distutils/tests/test_log.py Lib/distutils/tests/test_register.py Lib/distutils/tests/test_sdist.py Lib/distutils/tests/test_sysconfig.py Lib/distutils/tests/test_unixccompiler.py Lib/distutils/tests/test_upload.py Lib/distutils/tests/test_util.py Lib/distutils/text_file.py Lib/distutils/unixccompiler.py Lib/distutils/util.py Lib/doctest.py Lib/email/base64mime.py Lib/email/feedparser.py Lib/email/header.py Lib/email/message.py Lib/email/test/test_email.py Lib/fileinput.py Lib/fnmatch.py Lib/functools.py Lib/getopt.py Lib/http/client.py Lib/http/cookiejar.py Lib/http/cookies.py Lib/http/server.py Lib/idlelib/NEWS.txt Lib/idlelib/PyShell.py Lib/idlelib/idlever.py Lib/imaplib.py Lib/importlib/test/benchmark.py Lib/json/__init__.py Lib/json/decoder.py Lib/json/encoder.py Lib/json/tests/test_fail.py Lib/mailbox.py Lib/multiprocessing/connection.py Lib/multiprocessing/forking.py Lib/multiprocessing/heap.py Lib/multiprocessing/reduction.py Lib/ntpath.py Lib/os.py Lib/pdb.doc Lib/pdb.py Lib/pickle.py Lib/pickletools.py Lib/platform.py Lib/posixpath.py Lib/profile.py Lib/pstats.py Lib/pydoc.py Lib/pydoc_data/topics.py Lib/re.py Lib/site.py Lib/smtpd.py Lib/smtplib.py Lib/sndhdr.py Lib/socket.py Lib/string.py Lib/subprocess.py Lib/sysconfig.py Lib/tarfile.py Lib/test/cfgparser.2 Lib/test/cfgparser.3 Lib/test/data/README Lib/test/datetimetester.py Lib/test/decimaltestdata/extra.decTest Lib/test/formatfloat_testcases.txt Lib/test/math_testcases.txt Lib/test/mock_socket.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/script_helper.py Lib/test/sndhdrdata Lib/test/sortperf.py Lib/test/support.py Lib/test/symlink_support.py Lib/test/test_SimpleHTTPServer.py Lib/test/test_argparse.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_asyncore.py Lib/test/test_binascii.py Lib/test/test_binop.py Lib/test/test_bz2.py Lib/test/test_calendar.py Lib/test/test_cfgparser.py Lib/test/test_cmath.py Lib/test/test_cmd.py Lib/test/test_collections.py Lib/test/test_complex.py Lib/test/test_curses.py Lib/test/test_datetime.py Lib/test/test_decimal.py Lib/test/test_doctest.py Lib/test/test_fileinput.py Lib/test/test_float.py Lib/test/test_fnmatch.py Lib/test/test_functools.py Lib/test/test_gdb.py Lib/test/test_getopt.py Lib/test/test_glob.py Lib/test/test_http_cookiejar.py Lib/test/test_http_cookies.py Lib/test/test_httplib.py Lib/test/test_httpservers.py Lib/test/test_import.py Lib/test/test_math.py Lib/test/test_minidom.py Lib/test/test_mmap.py Lib/test/test_ntpath.py Lib/test/test_numeric_tower.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_osx_env.py Lib/test/test_pdb.py Lib/test/test_platform.py Lib/test/test_posix.py Lib/test/test_posixpath.py Lib/test/test_pow.py Lib/test/test_profilehooks.py Lib/test/test_pstats.py Lib/test/test_queue.py Lib/test/test_re.py Lib/test/test_rlcompleter.py Lib/test/test_robotparser.py Lib/test/test_sax.py Lib/test/test_sched.py Lib/test/test_set.py Lib/test/test_shutil.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_smtpd.py Lib/test/test_smtplib.py Lib/test/test_sndhdr.py Lib/test/test_ssl.py Lib/test/test_struct.py Lib/test/test_structseq.py Lib/test/test_subprocess.py Lib/test/test_sunau.py Lib/test/test_sundry.py Lib/test/test_sys.py Lib/test/test_sys_setprofile.py Lib/test/test_sys_settrace.py Lib/test/test_sysconfig.py Lib/test/test_tarfile.py Lib/test/test_tcl.py Lib/test/test_threaded_import.py Lib/test/test_threading.py Lib/test/test_threading_local.py Lib/test/test_tokenize.py Lib/test/test_trace.py Lib/test/test_unicode.py Lib/test/test_unicodedata.py Lib/test/test_unpack.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urlparse.py Lib/test/test_xml_etree.py Lib/threading.py Lib/timeit.py Lib/tkinter/__main__.py Lib/trace.py Lib/unittest/case.py Lib/unittest/test/test_case.py Lib/urllib/parse.py Lib/urllib/request.py Lib/urllib/robotparser.py Lib/xml/dom/expatbuilder.py Lib/xml/dom/minidom.py Lib/xmlrpc/client.py Makefile.pre.in Misc/ACKS Misc/NEWS Misc/RPM/python-3.2.spec Misc/developers.txt Misc/maintainers.rst Misc/python-wing.wpr Modules/Setup.dist Modules/_ctypes/_ctypes.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_cursesmodule.c Modules/_datetimemodule.c Modules/_io/_iomodule.c Modules/_io/bufferedio.c Modules/_json.c Modules/_pickle.c Modules/_ssl.c Modules/_struct.c Modules/_time.c Modules/_time.h Modules/arraymodule.c Modules/binascii.c Modules/bz2module.c Modules/cmathmodule.c Modules/datetimemodule.c Modules/getpath.c Modules/main.c Modules/makesetup Modules/mathmodule.c Modules/mmapmodule.c Modules/posixmodule.c Modules/readline.c Modules/selectmodule.c Modules/sha1module.c Modules/signalmodule.c Modules/timemodule.c Modules/zipimport.c Modules/zlib/ChangeLog Modules/zlib/FAQ Modules/zlib/INDEX Modules/zlib/Makefile Modules/zlib/Makefile.in Modules/zlib/README Modules/zlib/adler32.c Modules/zlib/compress.c Modules/zlib/configure Modules/zlib/crc32.c Modules/zlib/deflate.c Modules/zlib/deflate.h Modules/zlib/example.c Modules/zlib/infback.c Modules/zlib/inffast.c Modules/zlib/inffast.h Modules/zlib/inflate.c Modules/zlib/inflate.h Modules/zlib/inftrees.c Modules/zlib/inftrees.h Modules/zlib/make_vms.com Modules/zlib/minigzip.c Modules/zlib/trees.c Modules/zlib/trees.h Modules/zlib/uncompr.c Modules/zlib/zconf.h Modules/zlib/zlib.3 Modules/zlib/zlib.h Modules/zlib/zutil.c Modules/zlib/zutil.h Objects/bytearrayobject.c Objects/complexobject.c Objects/floatobject.c Objects/iterobject.c Objects/memoryobject.c Objects/object.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/formatter.h Objects/structseq.c Objects/unicodeobject.c PC/VS8.0/pythoncore.vcproj PC/_subprocess.c PC/config.c PC/python_nt.rc PCbuild/build_ssl.py PCbuild/pyproject.vsprops PCbuild/pythoncore.vcproj PCbuild/readme.txt Python/ceval.c Python/getargs.c Python/getcopyright.c Python/getversion.c Python/graminit.c Python/pythonrun.c Python/pytime.c README Tools/README Tools/buildbot/external-common.bat Tools/faqwiz Tools/framer/framer/bases.py Tools/framer/framer/template.py Tools/freeze/freeze.py Tools/freeze/makeconfig.py Tools/gdb/libpython.py Tools/i18n/msgfmt.py Tools/msi/msi.py Tools/msi/msilib.py Tools/msi/uuids.py Tools/pynche/ChipViewer.py Tools/pynche/DetailsViewer.py Tools/pynche/ListViewer.py Tools/pynche/PyncheWidget.py Tools/pynche/StripViewer.py Tools/pynche/Switchboard.py Tools/pynche/TextViewer.py Tools/pynche/TypeinViewer.py Tools/scripts/README Tools/scripts/byext.py Tools/scripts/checkappend.py Tools/scripts/classfix.py Tools/scripts/cvsfiles.py Tools/scripts/logmerge.py Tools/scripts/methfix.py Tools/scripts/serve.py Tools/scripts/setup.py Tools/scripts/win_add2path.py Tools/scripts/xxci.py Tools/versioncheck configure configure.in setup.py

mark.dickinson python-checkins at python.org
Sun Aug 8 12:41:31 CEST 2010


Author: mark.dickinson
Date: Sun Aug  8 12:41:24 2010
New Revision: 83814

Log:
Merged revisions 82615,82617,82624-82626,82628-82630,82632-82633,82636-82637,82642,82644,82646-82647,82649-82650,82654,82659,82661-82663,82723-82724,82730-82731,82735,82737,82739,82741,82743-82746,82748-82750,82753,82757-82764,82766-82767,82771,82777,82780,82784-82785,82789-82790,82796,82798-82799,82801,82804-82806,82814,82817-82822,82825,82828,82830-82832,82834-82835,82837-82839,82842-82843,82848-82850,82856-82857,82871-82874,82879,82881,82885,82887,82890,82895,82899,82910,82915,82918-82919,82921-82922,82927,82931,82934,82937,82941,82943,82947,82949,82951-82952,82954,82957-82962,82964-82967,82971,82978,82983,82985,82995,82997,83005-83006,83009,83011,83016,83025,83030,83035,83046,83053,83059,83065-83067,83072-83073,83075,83078,83080,83088-83092,83094-83096,83099-83103,83106-83109,83111-83112,83115-83116,83120,83125,83127,83133,83139-83141,83149-83152,83154,83156-83157,83160-83163,83166,83168-83171,83173,83177,83181-83184,83186,83188,83191,83195-83197,83201-83202,83209,83212-83220,83222-83224,83226-83227,83229-83232,83234-83239,83259-83266,83268-83272,83274-83275,83277,83281,83283-83289,83291-83294,83296,83307-83308,83313,83315-83329,83335-83339,83341-83343,83348-83353,83355-83362,83366,83368-83376,83380,83384-83391,83393-83400,83403-83408,83411,83415,83417,83431,83440,83444,83456,83479,83488,83494,83501,83506,83513,83516,83521,83523-83529,83531,83536,83538,83542-83543,83546-83548,83550-83555,83558,83560-83561,83563,83565-83566,83569,83571,83574-83575,83580,83584,83599,83605-83618,83636,83644,83649,83659-83660,83663,83667,83670,83673,83675,83677-83678,83681,83683,83690,83696,83698-83699,83701,83705,83707-83709,83712-83715,83719,83722,83726-83727,83729,83731-83732,83735-83736,83741-83742,83744-83745,83747,83750-83752,83755,83758-83759,83762-83763,83767-83768,83770-83771,83774-83780,83783-83785,83792,83795,83802,83804,83808-83809 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/branches/py3k

........
  r82615 | georg.brandl | 2010-07-06 23:58:50 +0100 (Tue, 06 Jul 2010) | 1 line
  
  Fix typo.
........
  r82617 | alexander.belopolsky | 2010-07-07 00:19:45 +0100 (Wed, 07 Jul 2010) | 1 line
  
  Issue #9000: datetime.timezone objects now have eval-friendly repr.
........
  r82624 | mark.dickinson | 2010-07-07 17:10:44 +0100 (Wed, 07 Jul 2010) | 1 line
  
  Kill gratuitous space.
........
  r82625 | mark.dickinson | 2010-07-07 17:17:31 +0100 (Wed, 07 Jul 2010) | 1 line
  
  Minor refactoring in lgamma code, for clarity.
........
  r82626 | mark.dickinson | 2010-07-07 17:21:29 +0100 (Wed, 07 Jul 2010) | 1 line
  
  Issue #9186:  log1p(-1.0) should raise ValueError, not OverflowError.
........
  r82628 | benjamin.peterson | 2010-07-07 19:44:05 +0100 (Wed, 07 Jul 2010) | 1 line
  
  this needn't be in the loop
........
  r82629 | georg.brandl | 2010-07-07 19:51:43 +0100 (Wed, 07 Jul 2010) | 1 line
  
  Make comment out of an awkward note.
........
  r82630 | benjamin.peterson | 2010-07-07 19:54:59 +0100 (Wed, 07 Jul 2010) | 1 line
  
  don't ignore exceptions from PyObject_IsTrue
........
  r82632 | georg.brandl | 2010-07-07 20:04:36 +0100 (Wed, 07 Jul 2010) | 1 line
  
  Turn more notes into comments.
........
  r82633 | benjamin.peterson | 2010-07-07 20:04:48 +0100 (Wed, 07 Jul 2010) | 1 line
  
  add NEWS
........
  r82636 | benjamin.peterson | 2010-07-07 21:54:01 +0100 (Wed, 07 Jul 2010) | 4 lines
  
  make struct sequences subclass tuple; kill lots of code
  
  This fixes #8413.
........
  r82637 | benjamin.peterson | 2010-07-07 23:45:06 +0100 (Wed, 07 Jul 2010) | 1 line
  
  ValueError in this case is also acceptable
........
  r82642 | alexander.belopolsky | 2010-07-08 00:56:38 +0100 (Thu, 08 Jul 2010) | 1 line
  
  Issue #5288: Eliminated round-trips between timdelta and int offsets
........
  r82644 | ezio.melotti | 2010-07-08 16:03:02 +0100 (Thu, 08 Jul 2010) | 1 line
  
  Fix typo in a comment in mathmodule.c.
........
  r82646 | mark.dickinson | 2010-07-08 18:23:40 +0100 (Thu, 08 Jul 2010) | 1 line
  
  In test_decimal, convert heuristic for skipping tests into an explicit skiplist.
........
  r82647 | antoine.pitrou | 2010-07-08 19:51:30 +0100 (Thu, 08 Jul 2010) | 3 lines
  
  Issue #8605: Skip test_gdb if Python is compiled with optimizations.
........
  r82649 | mark.dickinson | 2010-07-08 20:03:34 +0100 (Thu, 08 Jul 2010) | 1 line
  
  Fix a performance issue in Decimal.pow.  Thanks Stefan Krah for finding this.
........
  r82650 | mark.dickinson | 2010-07-08 20:09:16 +0100 (Thu, 08 Jul 2010) | 1 line
  
  Fix misplaced exactness check that was causing unnecessary work in Decimal.__pow__.
........
  r82654 | mark.dickinson | 2010-07-08 22:15:36 +0100 (Thu, 08 Jul 2010) | 3 lines
  
  Issue #9136: Profiling Decimal gave 'dictionary changed size during iteration'.
  Remove the use of locals() that caused this error.
........
  r82659 | brian.curtin | 2010-07-08 22:39:08 +0100 (Thu, 08 Jul 2010) | 17 lines
  
  Implement #1578269. Patch by Jason R. Coombs.
  
  Added Windows support for os.symlink when run on Windows 6.0 or greater,
  aka Vista. Previous Windows versions will raise NotImplementedError
  when trying to symlink.
  
  Includes numerous test updates and additions to test_os, including
  a symlink_support module because of the fact that privilege escalation
  is required in order to run the tests to ensure that the user is able
  to create symlinks. By default, accounts do not have the required
  privilege, so the escalation code will have to be exposed later (or
  documented on how to do so). I'll be following up with that work next.
  
  Note that the tests use ctypes, which was agreed on during the PyCon
  language summit.
........
  r82661 | brian.curtin | 2010-07-08 23:13:25 +0100 (Thu, 08 Jul 2010) | 2 lines
  
  Undo inadvertant checkin.
........
  r82662 | benjamin.peterson | 2010-07-08 23:16:05 +0100 (Thu, 08 Jul 2010) | 1 line
  
  assert tuple inheritance
........
  r82663 | benjamin.peterson | 2010-07-08 23:33:03 +0100 (Thu, 08 Jul 2010) | 1 line
  
  fix repr of complicated structseqs #9206
........
  r82723 | benjamin.peterson | 2010-07-09 02:58:26 +0100 (Fri, 09 Jul 2010) | 1 line
  
  use assert method
........
  r82724 | georg.brandl | 2010-07-09 08:33:15 +0100 (Fri, 09 Jul 2010) | 1 line
  
  2.7 is now stable.
........
  r82730 | r.david.murray | 2010-07-09 13:23:21 +0100 (Fri, 09 Jul 2010) | 4 lines
  
  7846: limit fnmatch pattern cache to _MAXCACHE=100 entries.
  
  Patch by Andrew Clegg.
........
  r82731 | r.david.murray | 2010-07-09 14:14:03 +0100 (Fri, 09 Jul 2010) | 2 lines
  
  Fix sort order mistake in Misc/ACKS.
........
  r82735 | benjamin.peterson | 2010-07-09 14:20:40 +0100 (Fri, 09 Jul 2010) | 1 line
  
  OverflowError is fine
........
  r82737 | brian.curtin | 2010-07-09 14:22:07 +0100 (Fri, 09 Jul 2010) | 2 lines
  
  Reorder Jason "two O's" Coombs
........
  r82739 | benjamin.peterson | 2010-07-09 14:28:42 +0100 (Fri, 09 Jul 2010) | 1 line
  
  allow more exceptions
........
  r82741 | benjamin.peterson | 2010-07-09 14:31:11 +0100 (Fri, 09 Jul 2010) | 1 line
  
  wrap
........
  r82743 | brian.curtin | 2010-07-09 14:54:27 +0100 (Fri, 09 Jul 2010) | 8 lines
  
  Fix the breakage of Lib/tarfile.py on non-Windows platforms due to 
  using WindowsError in a try/except. Only add WindowsError to the list of
  exceptions to catch when we are actually running on Windows.
  
  Additionally, add a call that was left out in test_posixpath.
  
  Thanks Amaury, Antoine, and Jason.
........
  r82744 | brian.curtin | 2010-07-09 16:15:09 +0100 (Fri, 09 Jul 2010) | 3 lines
  
  Adding versionchanged to the various Windows os.symlink additions, along
  with a few minor touchups.
........
  r82745 | brian.curtin | 2010-07-09 16:58:59 +0100 (Fri, 09 Jul 2010) | 2 lines
  
  Re-flow several long lines from #1578269.
........
  r82746 | jeffrey.yasskin | 2010-07-09 17:30:58 +0100 (Fri, 09 Jul 2010) | 12 lines
  
  Issue #9189: Allow users to set $CFLAGS, $CPPFLAGS, and $LDFLAGS when running
  configure to append to Python's default values for those variables, and
  similarly allow users to set $XXFLAGS on the make command line to append to the
  values set by configure.
  
  In the makefile, this renames the variables that used to be $XXFLAGS to
  $PY_XXFLAGS, and renames the old $PY_CFLAGS to $PY_CORE_CFLAGS.  To compensate,
  sysconfig now aliases $XXFLAGS=$PY_XXFLAGS so that scripts using it keep
  working.  I see that as the right interface, not a backward-compatibility hack,
  since these are logically the $XXFLAGS variables; we just use a different name
  in the makefile to deal with make's semantics.
........
  r82748 | benjamin.peterson | 2010-07-09 19:28:25 +0100 (Fri, 09 Jul 2010) | 1 line
  
  remove SocketIO.__del__; close() can handle it
........
  r82749 | mark.dickinson | 2010-07-09 20:25:48 +0100 (Fri, 09 Jul 2010) | 1 line
  
  Silence gcc warning. (In function 'bytearray_init': warning: 'value' may be used uninitialized in this function).
........
  r82750 | benjamin.peterson | 2010-07-09 20:37:00 +0100 (Fri, 09 Jul 2010) | 1 line
  
  be more robust across platforms
........
  r82753 | jeffrey.yasskin | 2010-07-09 20:55:05 +0100 (Fri, 09 Jul 2010) | 2 lines
  
  Oops. Fix distutils tests that r82746 broke.
........
  r82757 | georg.brandl | 2010-07-10 09:58:37 +0100 (Sat, 10 Jul 2010) | 1 line
  
  Fix markup.
........
  r82758 | georg.brandl | 2010-07-10 11:23:40 +0100 (Sat, 10 Jul 2010) | 1 line
  
  Emphasize role of count for Pascal string.
........
  r82759 | georg.brandl | 2010-07-10 11:32:36 +0100 (Sat, 10 Jul 2010) | 1 line
  
  #3071: tell how many values were expected when unpacking too many.
........
  r82760 | georg.brandl | 2010-07-10 11:39:57 +0100 (Sat, 10 Jul 2010) | 1 line
  
  #3214: improve description of duck-typing in glossary.
........
  r82761 | georg.brandl | 2010-07-10 12:40:13 +0100 (Sat, 10 Jul 2010) | 1 line
  
  #1434090: properly append child in expatbuilder doctype handler.
........
  r82762 | georg.brandl | 2010-07-10 12:51:06 +0100 (Sat, 10 Jul 2010) | 1 line
  
  #8338: fix outdated class name.
........
  r82763 | georg.brandl | 2010-07-10 13:01:34 +0100 (Sat, 10 Jul 2010) | 1 line
  
  #8456: fix signature of sqlite3.connect().
........
  r82764 | georg.brandl | 2010-07-10 13:20:38 +0100 (Sat, 10 Jul 2010) | 1 line
  
  #8564: update docs on integrating doctest/unittest with unittest(2) test discovery.
........
  r82766 | r.david.murray | 2010-07-10 14:52:13 +0100 (Sat, 10 Jul 2010) | 5 lines
  
  Fix 'refleak' introduced by fnmatch cache purge tests.
  
  This introduces a 'purge' function for the fnmatch module analogous
  to the 'purge' function in the re module.
........
  r82767 | michael.foord | 2010-07-10 14:52:22 +0100 (Sat, 10 Jul 2010) | 2 lines
  
  Fix error message for comparing single line strings in unittest.TestCase.assertEqual.
  Issue 9174.
........
  r82771 | r.david.murray | 2010-07-10 15:23:36 +0100 (Sat, 10 Jul 2010) | 2 lines
  
  Add missing docs for re module 'purge' function.
........
  r82777 | benjamin.peterson | 2010-07-10 16:14:45 +0100 (Sat, 10 Jul 2010) | 1 line
  
  ValueError is eventually what we want to move to, I suppose
........
  r82780 | senthil.kumaran | 2010-07-11 04:12:43 +0100 (Sun, 11 Jul 2010) | 3 lines
  
  Stricter verification for file based url scheme and reliance on ftp protocol.
........
  r82784 | benjamin.peterson | 2010-07-11 04:36:35 +0100 (Sun, 11 Jul 2010) | 1 line
  
  remove unneeded error check
........
  r82785 | senthil.kumaran | 2010-07-11 06:01:52 +0100 (Sun, 11 Jul 2010) | 3 lines
  
  Issue2007: Removing reference to MSIE Cookie handling by mechanize. Suggested by John J Lee.
........
  r82789 | georg.brandl | 2010-07-11 09:33:16 +0100 (Sun, 11 Jul 2010) | 1 line
  
  Silence makeindex.
........
  r82790 | georg.brandl | 2010-07-11 09:36:20 +0100 (Sun, 11 Jul 2010) | 1 line
  
  #3214 followup: add link to ABC entry.
........
  r82796 | ronald.oussoren | 2010-07-11 10:05:07 +0100 (Sun, 11 Jul 2010) | 2 lines
  
  Fix for issue 9164
........
  r82798 | georg.brandl | 2010-07-11 10:23:11 +0100 (Sun, 11 Jul 2010) | 1 line
  
  #6774: explain shutdown() behavior varying with platform.
........
  r82799 | georg.brandl | 2010-07-11 10:26:57 +0100 (Sun, 11 Jul 2010) | 1 line
  
  Fix typo.
........
  r82801 | georg.brandl | 2010-07-11 10:33:39 +0100 (Sun, 11 Jul 2010) | 1 line
  
  #9184: fix default value for "buffering" param of open().
........
  r82804 | georg.brandl | 2010-07-11 10:41:21 +0100 (Sun, 11 Jul 2010) | 1 line
  
  Allow set literals in literal_eval().
........
  r82805 | georg.brandl | 2010-07-11 10:42:10 +0100 (Sun, 11 Jul 2010) | 1 line
  
  #7935: cross-reference to ast.literal_eval() from eval() docs.
........
  r82806 | georg.brandl | 2010-07-11 11:22:44 +0100 (Sun, 11 Jul 2010) | 1 line
  
  #9223: link to Command class reference, and move Command interface docs nearer to class docs.
........
  r82814 | antoine.pitrou | 2010-07-11 13:12:00 +0100 (Sun, 11 Jul 2010) | 4 lines
  
  Issue #7616: Fix copying of overlapping memoryview slices with the Intel
  compiler.
........
  r82817 | benjamin.peterson | 2010-07-11 13:59:24 +0100 (Sun, 11 Jul 2010) | 1 line
  
  test for set literals
........
  r82818 | mark.dickinson | 2010-07-11 18:38:24 +0100 (Sun, 11 Jul 2010) | 2 lines
  
  Issue #9165: Add math.isfinite and cmath.isfinite.
........
  r82819 | martin.v.loewis | 2010-07-11 18:39:46 +0100 (Sun, 11 Jul 2010) | 2 lines
  
  Issue #8974: fix print calls in msgfmt.py.
........
  r82820 | mark.dickinson | 2010-07-11 19:13:41 +0100 (Sun, 11 Jul 2010) | 1 line
  
  Improve docstrings for isnan, isinf and isfinite.
........
  r82821 | mark.dickinson | 2010-07-11 19:53:06 +0100 (Sun, 11 Jul 2010) | 3 lines
  
  Issue #9137: Fix issue in MutableMapping.update, which incorrectly
  treated keyword arguments called 'self' or 'other' specially.
........
  r82822 | mark.dickinson | 2010-07-11 20:12:10 +0100 (Sun, 11 Jul 2010) | 1 line
  
  assertEquals -> assertEqual
........
  r82825 | mark.dickinson | 2010-07-11 20:47:37 +0100 (Sun, 11 Jul 2010) | 1 line
  
  Include versionadded in (c)math.isfinite docs (thanks Ezio Melotti).  Other minor doc cleanups.
........
  r82828 | benjamin.peterson | 2010-07-12 00:06:06 +0100 (Mon, 12 Jul 2010) | 1 line
  
  allow byte literals
........
  r82830 | brian.curtin | 2010-07-12 00:32:11 +0100 (Mon, 12 Jul 2010) | 2 lines
  
  Put my name down for winreg.
........
  r82831 | martin.v.loewis | 2010-07-12 07:03:18 +0100 (Mon, 12 Jul 2010) | 2 lines
  
  Remove myself.
........
  r82832 | georg.brandl | 2010-07-12 10:00:29 +0100 (Mon, 12 Jul 2010) | 1 line
  
  Take care of duplicate target name warnings.
........
  r82834 | georg.brandl | 2010-07-12 10:06:13 +0100 (Mon, 12 Jul 2010) | 1 line
  
  Use raw string literals for regexes containing backlash.
........
  r82835 | mark.dickinson | 2010-07-12 10:37:40 +0100 (Mon, 12 Jul 2010) | 1 line
  
  Remove mention of execfile from the tutorial.
........
  r82837 | mark.dickinson | 2010-07-12 15:14:18 +0100 (Mon, 12 Jul 2010) | 1 line
  
  Issue #2009: refactor varargslist and typedargslist productions to make them more friendly for third-party parsers.
........
  r82838 | mark.dickinson | 2010-07-12 15:18:21 +0100 (Mon, 12 Jul 2010) | 1 line
  
  Regenerate Python/graminit.c.
........
  r82839 | ezio.melotti | 2010-07-12 20:49:41 +0100 (Mon, 12 Jul 2010) | 1 line
  
  #6026: skip test_get_file_list when zlib is not available.
........
  r82842 | antoine.pitrou | 2010-07-12 21:01:52 +0100 (Mon, 12 Jul 2010) | 3 lines
  
  Fix definition of len() and indexing for memoryview objects (part of #7696).
........
  r82843 | mark.dickinson | 2010-07-12 21:03:24 +0100 (Mon, 12 Jul 2010) | 1 line
  
  Yield more information on failure in test_struct boolean test.
........
  r82848 | georg.brandl | 2010-07-13 07:38:10 +0100 (Tue, 13 Jul 2010) | 1 line
  
  Add bytes in literal_eval doc.
........
  r82849 | jeroen.ruigrok | 2010-07-13 15:47:01 +0100 (Tue, 13 Jul 2010) | 2 lines
  
  Fix documentation typo: wprite() -> write().
........
  r82850 | alexander.belopolsky | 2010-07-13 15:50:16 +0100 (Tue, 13 Jul 2010) | 1 line
  
  Set sys.modules[name] to None instead of 0 to block module import.
........
  r82856 | victor.stinner | 2010-07-14 00:04:56 +0100 (Wed, 14 Jul 2010) | 2 lines
  
  Issue #9243: Fix sndhdr module and add unit tests, contributed by James Lee.
........
  r82857 | victor.stinner | 2010-07-14 00:08:01 +0100 (Wed, 14 Jul 2010) | 2 lines
  
  Woops, test_sndhdr.py contains the same code twice: fix it
........
  r82871 | georg.brandl | 2010-07-14 09:00:22 +0100 (Wed, 14 Jul 2010) | 1 line
  
  #9258: fix copy-paste errors.
........
  r82872 | georg.brandl | 2010-07-14 09:53:18 +0100 (Wed, 14 Jul 2010) | 1 line
  
  Remove XXX from text.
........
  r82873 | georg.brandl | 2010-07-14 09:53:36 +0100 (Wed, 14 Jul 2010) | 1 line
  
  Remove unused code that would raise a NameError.
........
  r82874 | georg.brandl | 2010-07-14 09:54:40 +0100 (Wed, 14 Jul 2010) | 1 line
  
  #9235: fix missing import of sys.
........
  r82879 | stefan.krah | 2010-07-14 11:16:11 +0100 (Wed, 14 Jul 2010) | 3 lines
  
  High byte is the exit status.
........
  r82881 | senthil.kumaran | 2010-07-14 11:21:22 +0100 (Wed, 14 Jul 2010) | 3 lines
  
  Fix Issue5842 - Moving the tests out of urllib.parse module
........
  r82885 | antoine.pitrou | 2010-07-14 12:52:38 +0100 (Wed, 14 Jul 2010) | 4 lines
  
  Issue #9251: test_threaded_import didn't fail when run through regrtest
  if the import lock was disabled.
........
  r82887 | alexander.belopolsky | 2010-07-14 14:46:57 +0100 (Wed, 14 Jul 2010) | 1 line
  
  PEP 8 conformance: class_ -> cls
........
  r82890 | senthil.kumaran | 2010-07-14 20:15:23 +0100 (Wed, 14 Jul 2010) | 3 lines
  
  Fix: Issue6853 - Get HTTPS system proxy in Windows.
........
  r82895 | senthil.kumaran | 2010-07-14 21:10:52 +0100 (Wed, 14 Jul 2010) | 3 lines
  
  Fix a mistake, https proxy shoud be https://
........
  r82899 | senthil.kumaran | 2010-07-14 21:30:02 +0100 (Wed, 14 Jul 2010) | 2 lines
  
  Fix issue9132 - Documentation for comparing dictionaries is out of date
........
  r82910 | brett.cannon | 2010-07-15 07:24:04 +0100 (Thu, 15 Jul 2010) | 2 lines
  
  Touch up comments and code along with outputting what the unit of measure is.
........
  r82915 | alexander.belopolsky | 2010-07-16 15:39:45 +0100 (Fri, 16 Jul 2010) | 1 line
  
  Corrected TUPLE<N> opcodes' docs.
........
  r82918 | brett.cannon | 2010-07-16 20:04:29 +0100 (Fri, 16 Jul 2010) | 4 lines
  
  Add benchmarks for importing just source w/o writing bytecode, importing source
  while writing bytecode, and importing bytecode with source existing (don't care
  about sourceless imports).
........
  r82919 | antoine.pitrou | 2010-07-16 20:10:38 +0100 (Fri, 16 Jul 2010) | 4 lines
  
  Fix possible failure in pickling tests due to different instantiations
  of the random module being around.
........
  r82921 | brett.cannon | 2010-07-16 20:26:23 +0100 (Fri, 16 Jul 2010) | 1 line
  
  Add comma grouping to max result so it's easier to read.
........
  r82922 | r.david.murray | 2010-07-17 02:19:57 +0100 (Sat, 17 Jul 2010) | 4 lines
  
  #1555570: correctly handle a \r\n that is split by the read buffer.
  
  Patch and test by Tony Nelson.
........
  r82927 | stefan.krah | 2010-07-17 12:46:52 +0100 (Sat, 17 Jul 2010) | 4 lines
  
  Issue #7384: On Gentoo, libreadline.so is a "fake library", so ldd fails.
  In that case, do not attempt to parse stderr output.
........
  r82931 | alexander.belopolsky | 2010-07-17 16:51:21 +0100 (Sat, 17 Jul 2010) | 2 lines
  
  Issue #9268: Add annotation option to pickletools.dis
........
  r82934 | benjamin.peterson | 2010-07-17 21:39:23 +0100 (Sat, 17 Jul 2010) | 1 line
  
  sharedinstall should depend on sharedmods #9280
........
  r82937 | alexander.belopolsky | 2010-07-17 23:50:45 +0100 (Sat, 17 Jul 2010) | 3 lines
  
  Issue #5180: Fixed a bug that prevented loading 2.x pickles in 3.x
  python when they contain instances of old-style classes.
........
  r82941 | mark.dickinson | 2010-07-18 08:29:02 +0100 (Sun, 18 Jul 2010) | 3 lines
  
  Issue #9277: Struct module: standard bool packing was incorrect if
  char is unsigned.  Thanks Stefan Krah for the patch.
........
  r82943 | mark.dickinson | 2010-07-18 08:48:20 +0100 (Sun, 18 Jul 2010) | 1 line
  
  Misc/NEWS entry for r82941.
........
  r82947 | mark.dickinson | 2010-07-18 09:03:10 +0100 (Sun, 18 Jul 2010) | 1 line
  
  Clarify Misc/NEWS entry.
........
  r82949 | georg.brandl | 2010-07-18 11:11:03 +0100 (Sun, 18 Jul 2010) | 1 line
  
  #9279: remove the pdb.doc file, put its contents in pdb.__doc__.  Also sync this and the pdb docs, introduce a new directive for pdb commands and a role to link to them.
........
  r82951 | georg.brandl | 2010-07-18 14:43:32 +0100 (Sun, 18 Jul 2010) | 1 line
  
  #9110: update to ContextDecorator doc.
........
  r82952 | benjamin.peterson | 2010-07-18 15:23:36 +0100 (Sun, 18 Jul 2010) | 1 line
  
  use classmethod
........
  r82954 | benjamin.peterson | 2010-07-18 15:27:02 +0100 (Sun, 18 Jul 2010) | 1 line
  
  nest method and attribute doc
........
  r82957 | mark.dickinson | 2010-07-18 17:01:36 +0100 (Sun, 18 Jul 2010) | 1 line
  
  Add configure check for a bug with gcc soft floating-point and subnormals, to help debug issue 8265.
........
  r82958 | jean-paul.calderone | 2010-07-18 17:13:27 +0100 (Sun, 18 Jul 2010) | 1 line
  
  There is no method named "register(fd, eventmask)"; fix markup to just indicate this is code.
........
  r82959 | jean-paul.calderone | 2010-07-18 17:30:31 +0100 (Sun, 18 Jul 2010) | 1 line
  
  Document the extra epoll flags
........
  r82960 | georg.brandl | 2010-07-19 07:52:35 +0100 (Mon, 19 Jul 2010) | 1 line
  
  Clarify.
........
  r82961 | georg.brandl | 2010-07-19 07:57:52 +0100 (Mon, 19 Jul 2010) | 1 line
  
  Clarify :option: description.
........
  r82962 | mark.dickinson | 2010-07-19 08:31:40 +0100 (Mon, 19 Jul 2010) | 1 line
  
  Remove temporary debugging code.
........
  r82964 | georg.brandl | 2010-07-19 09:02:46 +0100 (Mon, 19 Jul 2010) | 1 line
  
  pydoc.pager does not promise to use $PAGER.
........
  r82965 | georg.brandl | 2010-07-19 12:28:05 +0100 (Mon, 19 Jul 2010) | 1 line
  
  Clarification.  Yay importlib!
........
  r82966 | stefan.krah | 2010-07-19 13:36:57 +0100 (Mon, 19 Jul 2010) | 13 lines
  
  Issue #9036: Throughout the code base, Py_CHARMASK is used on 8-bit wide
  signed/unsigned chars or on integers directly derived from those. In all
  cases, it could be replaced by a simple cast to (unsigned char). Reasons
  for the change:
  
    a) Make the comment more explicit.
  
    b) If char is unsigned, the cast is optimized away.
  
    c) If char is unsigned, gcc emits spurious "array subscript
       has type 'char'" warnings.
........
  r82967 | ronald.oussoren | 2010-07-19 14:00:36 +0100 (Mon, 19 Jul 2010) | 8 lines
  
  This patch adds a testcase that demonstrates a problem
  with the expansion of LDSHARED when accessing that value
  through sysconfig.
  
  The problem is probably caused by the 9189.
  
  A fix will follow shortly.
........
  r82971 | stefan.krah | 2010-07-19 15:20:53 +0100 (Mon, 19 Jul 2010) | 4 lines
  
  Issue #9265: Incorrect name passed as arg[0] when shell=True
  and executable specified.
........
  r82978 | stefan.krah | 2010-07-19 18:58:26 +0100 (Mon, 19 Jul 2010) | 3 lines
  
  Sub-issue of #9036: Fix incorrect use of Py_CHARMASK.
........
  r82983 | senthil.kumaran | 2010-07-19 19:17:19 +0100 (Mon, 19 Jul 2010) | 3 lines
  
  Fix Issue9301 - urllib.parse.unquote and unquote_to_byte to raise TypeError for None.
........
  r82985 | gregory.p.smith | 2010-07-20 00:17:22 +0100 (Tue, 20 Jul 2010) | 3 lines
  
  Fixes Issue #3704: http.cookiejar was not properly handling URLs with a / in
  the parameters.  (This is jjlee's issue3704.patch ported to py3k)
........
  r82995 | ronald.oussoren | 2010-07-20 17:07:10 +0100 (Tue, 20 Jul 2010) | 14 lines
  
  Without this patch the value of sysconfig.get_config_var('LDSHARED')
  is wrong when PY_LDFLAGS is not empty.
  
  The bug was caused by LDSHARED getting expanded *before* sysconfig
  renamed PY_LDSHARED (and simular values) to names without a PY_
  prefix.
  
  The patch tries to maintain the intended behaviour of allowing users
  to set LDFLAGS in the environment and have that affect the build.
  
  Without this patch a universal build on OSX cannot build universal
  (fat binary) extensions.
........
  r82997 | alexander.belopolsky | 2010-07-20 20:55:18 +0100 (Tue, 20 Jul 2010) | 3 lines
  
  Issue #9282: Fixed --listfuncs option of trace.py.  Thanks Eli
  Bendersky for the patch.
........
  r83005 | benjamin.peterson | 2010-07-20 23:37:19 +0100 (Tue, 20 Jul 2010) | 1 line
  
  move test_trace.py so as not to conflict with future tests for the trace module
........
  r83006 | benjamin.peterson | 2010-07-20 23:39:34 +0100 (Tue, 20 Jul 2010) | 1 line
  
  revert unintended changes
........
  r83009 | brian.curtin | 2010-07-21 02:44:19 +0100 (Wed, 21 Jul 2010) | 2 lines
  
  Fix #9316. if/is grammar corrections.
........
  r83011 | brett.cannon | 2010-07-21 10:48:31 +0100 (Wed, 21 Jul 2010) | 2 lines
  
  Minor clarification about importlib.abc.SourceLoader.get_filename.
........
  r83016 | doug.hellmann | 2010-07-21 13:29:04 +0100 (Wed, 21 Jul 2010) | 1 line
  
  Apply patch from Ray Allen for issue 9296
........
  r83025 | antoine.pitrou | 2010-07-21 16:54:48 +0100 (Wed, 21 Jul 2010) | 3 lines
  
  Remove outdated mention of deprecated functions in the string module - they have been removed in 3.x.
........
  r83030 | antoine.pitrou | 2010-07-21 17:41:31 +0100 (Wed, 21 Jul 2010) | 5 lines
  
  Issue #5395: check that array.fromfile() re-raises an IOError instead of replacing it
  with EOFError.
  (this is only an added test, but 2.x will get a fix too)
........
  r83035 | alexander.belopolsky | 2010-07-21 18:43:42 +0100 (Wed, 21 Jul 2010) | 3 lines
  
  Issue #9323: Fixed a bug in trace.py that resulted in loosing the name
  of the script being traced.  Patch by Eli Bendersky.
........
  r83046 | brett.cannon | 2010-07-22 08:40:56 +0100 (Thu, 22 Jul 2010) | 3 lines
  
  Add importlib benchmarks which try to be "realistic" by importing the decimal
  module which is the largest module in the stdlib.
........
  r83053 | tarek.ziade | 2010-07-22 13:50:05 +0100 (Thu, 22 Jul 2010) | 1 line
  
  reverted distutils its 3.1 state. All new work is now happening in disutils2, and distutils is now feature-frozen.
........
  r83059 | brian.curtin | 2010-07-22 16:38:28 +0100 (Thu, 22 Jul 2010) | 3 lines
  
  Skip this test as it doesn't apply to Windows. It was added for
  #9189 for some GCC flags.
........
  r83065 | georg.brandl | 2010-07-23 09:46:35 +0100 (Fri, 23 Jul 2010) | 1 line
  
  Use augassign.
........
  r83066 | ronald.oussoren | 2010-07-23 10:43:17 +0100 (Fri, 23 Jul 2010) | 10 lines
  
  Ensure that the Makefile variable expansion
  in distutils.sysconfig matches that in the 
  toplevel sysconfig module.
  
  Without this patch universal builds on OSX are
  broken.
  
  Als add a test that checks that the two version
  of get_config_vars agree on important values.
........
  r83067 | ronald.oussoren | 2010-07-23 10:50:05 +0100 (Fri, 23 Jul 2010) | 8 lines
  
  Workaround for issue 4047: in some configurations of
  the Crash Reporter on OSX test_subprocess will trigger
  the reporter. 
  
  This patch prints a warning when the Crash Reporter will
  get triggered intentionally, which should avoid confusing
  people.
........
  r83072 | brett.cannon | 2010-07-23 12:31:31 +0100 (Fri, 23 Jul 2010) | 5 lines
  
  Document the fact that the 'test' package is meant only for use by Python
  itself and not by others.
  
  Closes issue 9255.
........
  r83073 | ronald.oussoren | 2010-07-23 12:48:36 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Minor tweak of test_osx_env to 
  avoid failing when the framework is not
  yet installed.
........
  r83075 | ronald.oussoren | 2010-07-23 12:54:59 +0100 (Fri, 23 Jul 2010) | 5 lines
  
  Fix for issue 7895. Avoid crashing the interpreter
  when calling platform.mac_ver after calling os.fork by
  reading from a system configuration file instead of
  using OSX APIs.
........
  r83078 | martin.v.loewis | 2010-07-23 13:16:41 +0100 (Fri, 23 Jul 2010) | 3 lines
  
  Issue #6095: Make directory argument to os.listdir optional.
  Patch by Virgil Dupras.
........
  r83080 | brett.cannon | 2010-07-23 13:26:35 +0100 (Fri, 23 Jul 2010) | 5 lines
  
  Clarify the wording for threading.is_alive() to not suggest something is
  "roughly" done.
  
  Closes issue 9339. Thanks Brian Brazil for the patch.
........
  r83088 | ronald.oussoren | 2010-07-23 14:53:51 +0100 (Fri, 23 Jul 2010) | 8 lines
  
  This fixes issue7900 by adding code that deals
  with the fact that getgroups(2) might return
  more that MAX_GROUPS on OSX.
  
  See the issue (and python-dev archives) for the
  gory details. Summarized: OSX behaves rather oddly
  and Apple says this is intentional.
........
  r83089 | brett.cannon | 2010-07-23 14:54:14 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Test calendar.monthrange.
  
  Closes issue 9342. Thanks John Chandler for the patch.
........
  r83090 | brett.cannon | 2010-07-23 15:03:16 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Explicitly test relative imports by reusing importlib tests.
  
  Closes issue 8392. Thanks Virgil Dupras for the initial patch.
........
  r83091 | brett.cannon | 2010-07-23 15:45:19 +0100 (Fri, 23 Jul 2010) | 1 line
  
  Stop shadowing a test class.
........
  r83092 | brett.cannon | 2010-07-23 16:43:14 +0100 (Fri, 23 Jul 2010) | 2 lines
  
  Rename some macros in the sha1 module to no longer conflict with termios.h.
........
  r83094 | brett.cannon | 2010-07-23 16:50:02 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Rip out old testing code that was inlined in threading.
  
  Partially closes issue 9346. Thanks Brian Brazil for the patch.
........
  r83095 | brett.cannon | 2010-07-23 16:50:52 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Add more tests for the threading.Thread.repr.
  
  Partially closes issue 9346. Thanks to Brian Brazil for the patch.
........
  r83096 | ronald.oussoren | 2010-07-23 17:05:35 +0100 (Fri, 23 Jul 2010) | 13 lines
  
  Ensure that sys.prefix can reliably be found
  on OSX. This fixes a small issue that was exposed
  by running test_subprocess through regrtest (and
  hence in a subdirectory).
  
  Without this patch running python.exe from the
  build tree will fail when these tree conditions
  are true:
  1) the CWD is not the root of build tree
  2) python.exe is found through $PATH
  3) the framework is not yet installed
........
  r83099 | richard.jones | 2010-07-23 17:20:40 +0100 (Fri, 23 Jul 2010) | 2 lines
  
  New tests for smtpd module. Has full coverage for SMTPChannel and SMTPServer.
........
  r83100 | brett.cannon | 2010-07-23 17:22:25 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Make fnmatch be more PEP 8 compliant.
  
  Partially closes issue 9356. Thanks to Brian Brazil for the patch.
........
  r83101 | brett.cannon | 2010-07-23 17:23:13 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Add tests for fnmatch.filter and translate.
  
  Partially closes issue 9356. Thanks to Brian Brazil for the patch.
........
  r83102 | brian.curtin | 2010-07-23 17:30:10 +0100 (Fri, 23 Jul 2010) | 3 lines
  
  Tab test_repr_daemon over so it's included in ThreadTests.
  Noticed by Amaury.
........
  r83103 | ezio.melotti | 2010-07-23 17:48:22 +0100 (Fri, 23 Jul 2010) | 1 line
  
  #9359: fix typo. Thanks to Piotr Kasprzyk for the patch.
........
  r83106 | georg.brandl | 2010-07-23 17:55:26 +0100 (Fri, 23 Jul 2010) | 1 line
  
  Fix some markup glitches.
........
  r83107 | georg.brandl | 2010-07-23 17:55:42 +0100 (Fri, 23 Jul 2010) | 1 line
  
  Update to 1.0.
........
  r83108 | brett.cannon | 2010-07-23 17:56:21 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Add queue tests for empty, full, put_nowait, and get_nowait.
  
  Closes issue 9357. Thanks to Brian Brazil for the patch.
........
  r83109 | brett.cannon | 2010-07-23 17:58:21 +0100 (Fri, 23 Jul 2010) | 4 lines
  
  Mention in the fnmatch docs that meta-characters in translate cannot be quoted.
  
  Closes issue 9358. Thanks to Brian Brazil for the patch.
........
  r83111 | brett.cannon | 2010-07-23 17:58:57 +0100 (Fri, 23 Jul 2010) | 2 lines
  
  Add Brian Brazil.
........
  r83112 | alexander.belopolsky | 2010-07-23 20:25:47 +0100 (Fri, 23 Jul 2010) | 2 lines
  
  Issue #7989: Added pure python implementation of the datetime module.
........
  r83115 | alexander.belopolsky | 2010-07-23 21:03:53 +0100 (Fri, 23 Jul 2010) | 1 line
  
  Use _datetime docstring if _datetime is available.
........
  r83116 | victor.stinner | 2010-07-24 01:49:20 +0100 (Sat, 24 Jul 2010) | 4 lines
  
  Issue #4629: getopt raises an error if an argument ends with = whereas getopt
  doesn't except a value (eg. --help= is rejected if getopt uses ['help='] long
  options).
........
  r83120 | victor.stinner | 2010-07-24 03:24:55 +0100 (Sat, 24 Jul 2010) | 12 lines
  
  #9032: XML-RPC client: Transport.request() retries on EPIPE error
  
  The EPIPE error occurs when the server closes the socket and the client sends a
  "big" XML-RPC request (I don't know exactly the size threshold).
  
  request() just have to ignore the error because single_request() closes the
  socket on error, and so the next call to single_request() will open a new
  socket.
  
  Remove also a comment in the HTTP client because it's now wrong: see r70643
  and issue #5542.
........
  r83125 | richard.jones | 2010-07-24 10:51:40 +0100 (Sat, 24 Jul 2010) | 8 lines
  
  Implementation for issue 4184
  
  Changes the previously private attributes to make them public, increasing the potential for extending the library in user code. Backward-compatible and documented.
........
  r83127 | martin.v.loewis | 2010-07-24 11:09:11 +0100 (Sat, 24 Jul 2010) | 2 lines
  
  Put listdir default argument into declaration.
........
  r83133 | ronald.oussoren | 2010-07-24 15:15:19 +0100 (Sat, 24 Jul 2010) | 5 lines
  
  Fix for issue 9367: the test code for os.getgroups
  assumes that the result of getgroups and the output
  of the id(1) command return groups in the same 
  order.  That assumption is both fragile and false.
........
  r83139 | alexander.belopolsky | 2010-07-25 15:58:54 +0100 (Sun, 25 Jul 2010) | 5 lines
  
  Issue #9315: Revert r83005 before renaming test_trace to
  test_sys_settrace and test_profilehooks to test_sys_setprofile in all
  three branches.
........
  r83140 | alexander.belopolsky | 2010-07-25 16:02:55 +0100 (Sun, 25 Jul 2010) | 5 lines
  
  Issue #9315: Renamed test_trace to test_sys_settrace and
  test_profilehooks to test_sys_setprofile so that test_trace can be
  used for testing the trace module and for naming consistency.
........
  r83141 | alexander.belopolsky | 2010-07-25 16:05:42 +0100 (Sun, 25 Jul 2010) | 1 line
  
  Corrected comments on where settrace and setprofile are tested.
........
  r83149 | andrew.kuchling | 2010-07-25 23:57:12 +0100 (Sun, 25 Jul 2010) | 1 line
  
  #1495229: update the type names used by the XML DOM mapping
........
  r83150 | michael.foord | 2010-07-26 00:09:25 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Issue #4686 - add .args to exceptions in the configparsermodule
........
  r83151 | andrew.kuchling | 2010-07-26 00:23:30 +0100 (Mon, 26 Jul 2010) | 1 line
  
  #7637: clarify description of encoding parameter
........
  r83152 | andrew.kuchling | 2010-07-26 00:38:47 +0100 (Mon, 26 Jul 2010) | 1 line
  
  #777884: make .normalize() do nothing for childless nodes, instead of raising an exception
........
  r83154 | brian.curtin | 2010-07-26 01:27:10 +0100 (Mon, 26 Jul 2010) | 5 lines
  
  Fix #7113. Patch by Łukasz Langa.
  
  Changes include using a list of lines instead of patching together using
  string interpolation, and a multi-line value test cases.
........
  r83156 | brian.curtin | 2010-07-26 03:36:32 +0100 (Mon, 26 Jul 2010) | 2 lines
  
  Add note about #7113 and add Łukasz Langa to ACKS
........
  r83157 | alexander.belopolsky | 2010-07-26 03:36:41 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Make python version of fromtimestamp behave more like C.
........
  r83160 | georg.brandl | 2010-07-26 09:51:42 +0100 (Mon, 26 Jul 2010) | 1 line
  
  #9381: fix markup.
........
  r83161 | georg.brandl | 2010-07-26 10:33:12 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Add Brian Quinlan.
........
  r83162 | andrew.kuchling | 2010-07-26 13:54:02 +0100 (Mon, 26 Jul 2010) | 1 line
  
  #7637: fix a grammar error; simplify a sentence
........
  r83163 | andrew.kuchling | 2010-07-26 14:08:58 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Reword paragraph
........
  r83166 | georg.brandl | 2010-07-26 16:11:49 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Fix grammar.
........
  r83168 | georg.brandl | 2010-07-26 18:00:20 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Fix indentation in example.
........
  r83169 | georg.brandl | 2010-07-26 18:09:32 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Add Reid.
........
  r83170 | alexander.belopolsky | 2010-07-26 19:27:49 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Added versionadded entry for the annotate argument.
........
  r83171 | georg.brandl | 2010-07-26 22:12:13 +0100 (Mon, 26 Jul 2010) | 1 line
  
  Clarify.
........
  r83173 | gregory.p.smith | 2010-07-27 06:31:29 +0100 (Tue, 27 Jul 2010) | 7 lines
  
  The default size of the re module's compiled regular expression cache has
  been increased from 100 to 500 and the cache replacement policy has changed
  from simply clearing the entire cache on overflow to randomly forgetting 20%
  of the existing cached compiled regular expressions.  This is a performance
  win for applications that use a lot of regular expressions and limits the
  impact of the performance hit anytime the cache is exceeded.
........
  r83177 | alexander.belopolsky | 2010-07-27 15:16:32 +0100 (Tue, 27 Jul 2010) | 1 line
  
  Issue #9384: python -m tkinter will now display a simple demo applet.
........
  r83181 | georg.brandl | 2010-07-27 19:19:21 +0100 (Tue, 27 Jul 2010) | 1 line
  
  Update Sphinx to 1.0.1.
........
  r83182 | florent.xicluna | 2010-07-27 22:20:15 +0100 (Tue, 27 Jul 2010) | 3 lines
  
  Issue #4770: Restrict binascii module to accept only bytes (as specified).
  And fix the email package to encode to ASCII instead of ``raw-unicode-escape`` before ASCII-to-binary decoding.
........
  r83183 | ezio.melotti | 2010-07-27 23:03:33 +0100 (Tue, 27 Jul 2010) | 1 line
  
  Use proper skips and assert* methods in test_asyncore.
........
  r83184 | antoine.pitrou | 2010-07-27 23:08:27 +0100 (Tue, 27 Jul 2010) | 3 lines
  
  Issue #9294: remove dead code in Objects/object.c.  Patch by Grant Limberg.
........
  r83186 | ezio.melotti | 2010-07-27 23:24:13 +0100 (Tue, 27 Jul 2010) | 1 line
  
  With skipUnless there is no need to add test classes conditionally.
........
  r83188 | alexander.belopolsky | 2010-07-28 00:02:38 +0100 (Wed, 28 Jul 2010) | 3 lines
  
  Issue #9378: python -m pickle <pickle file> will now load and display
  the first object in the pickle file.
........
  r83191 | victor.stinner | 2010-07-28 00:36:41 +0100 (Wed, 28 Jul 2010) | 2 lines
  
  Fix ctypes tests to avoid implicit bytes-unicode conversion
........
  r83195 | victor.stinner | 2010-07-28 01:15:03 +0100 (Wed, 28 Jul 2010) | 2 lines
  
  Issue #8966: ctypes: Remove implicit bytes-unicode conversion
........
  r83196 | ezio.melotti | 2010-07-28 01:23:21 +0100 (Wed, 28 Jul 2010) | 1 line
  
  Fix failure introduced in r83182.
........
  r83197 | victor.stinner | 2010-07-28 01:40:58 +0100 (Wed, 28 Jul 2010) | 2 lines
  
  Issue #8991: convertbuffer() rejects discontigious buffers
........
  r83201 | georg.brandl | 2010-07-28 09:19:35 +0100 (Wed, 28 Jul 2010) | 1 line
  
  #9354: Provide getsockopt() in asyncore file_wrapper().  Patch by Lukas Langa.
........
  r83202 | georg.brandl | 2010-07-28 14:13:46 +0100 (Wed, 28 Jul 2010) | 1 line
  
  #1682942: add some ConfigParser features: alternate delimiters, alternate comments, empty lines in values.  Also enhance the docs with more examples and mention SafeConfigParser before ConfigParser.  Patch by Lukas Langa, review by myself, Eric and Ezio.
........
  r83209 | senthil.kumaran | 2010-07-28 17:27:56 +0100 (Wed, 28 Jul 2010) | 3 lines
  
  Fix Issue6325 - robotparse to honor urls with query strings.
........
  r83212 | florent.xicluna | 2010-07-28 17:39:41 +0100 (Wed, 28 Jul 2010) | 2 lines
  
  Syntax cleanup.
........
  r83213 | georg.brandl | 2010-07-28 18:37:27 +0100 (Wed, 28 Jul 2010) | 1 line
  
  Add missing file.
........
  r83214 | victor.stinner | 2010-07-28 22:23:23 +0100 (Wed, 28 Jul 2010) | 2 lines
  
  #9283: Fix repr(os.environ), display unicode keys and values on POSIX systems
........
  r83215 | victor.stinner | 2010-07-28 22:25:42 +0100 (Wed, 28 Jul 2010) | 2 lines
  
  Issue #9283: Oops, add missing { and } to repr(os.environ)
........
  r83216 | victor.stinner | 2010-07-29 01:29:00 +0100 (Thu, 29 Jul 2010) | 2 lines
  
  Update test_os.py according to my last changes on _Environ.__repr__()
........
  r83217 | georg.brandl | 2010-07-29 12:15:36 +0100 (Thu, 29 Jul 2010) | 1 line
  
  Remove Python 1.5 compatibility note.
........
  r83218 | georg.brandl | 2010-07-29 12:49:05 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #6538: fix regex documentation again -- use fictional class names "regex" and "match" but do not document them as classes, remove 1.5 compat info and use new default argument syntax where possible.
........
  r83219 | georg.brandl | 2010-07-29 12:56:20 +0100 (Thu, 29 Jul 2010) | 1 line
  
  Fix for r83202: improve the handling of empty lines.
........
  r83220 | georg.brandl | 2010-07-29 13:17:40 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #9411: allow selecting an encoding for configparser files.  Also adds a new test config file to test special cases.
........
  r83222 | georg.brandl | 2010-07-29 14:19:42 +0100 (Thu, 29 Jul 2010) | 1 line
  
  Fix #9412: make list of messages an instance attribute instead of class attribute.
........
  r83223 | georg.brandl | 2010-07-29 14:38:37 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #3874: document HTMLParser.unknown_decl().
........
  r83224 | mark.dickinson | 2010-07-29 14:56:56 +0100 (Thu, 29 Jul 2010) | 1 line
  
  Fix typo.
........
  r83226 | georg.brandl | 2010-07-29 15:17:12 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #1090076: explain the behavior of *vars* in get() better.
........
  r83227 | georg.brandl | 2010-07-29 15:23:06 +0100 (Thu, 29 Jul 2010) | 1 line
  
  Use Py_CLEAR().
........
  r83229 | georg.brandl | 2010-07-29 15:32:22 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #9407: document configparser.Error.
........
  r83230 | georg.brandl | 2010-07-29 15:36:11 +0100 (Thu, 29 Jul 2010) | 1 line
  
  Use correct directive and name.
........
  r83231 | georg.brandl | 2010-07-29 15:46:07 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #9397: remove mention of dbm.bsd which does not exist anymore.
........
  r83232 | georg.brandl | 2010-07-29 15:49:08 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #9388: remove ERA_YEAR which is never defined in the source code.
........
  r83234 | georg.brandl | 2010-07-29 17:01:11 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #6522: add a "decorator" directive to explicitly document decorators, and use it in a few places.
........
  r83235 | victor.stinner | 2010-07-29 17:26:56 +0100 (Thu, 29 Jul 2010) | 2 lines
  
  #9397: remove mention of dbm.bsd which does not exist anymore.
........
  r83236 | georg.brandl | 2010-07-29 18:16:10 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #6630: allow customizing flags for compiling string.Template.idpattern.
........
  r83237 | victor.stinner | 2010-07-29 18:19:38 +0100 (Thu, 29 Jul 2010) | 2 lines
  
  #8603: Add environb to os.__all__
........
  r83238 | georg.brandl | 2010-07-29 18:55:01 +0100 (Thu, 29 Jul 2010) | 1 line
  
  #4108: the first default entry (User-agent: *) wins.
........
  r83239 | mark.dickinson | 2010-07-29 22:41:59 +0100 (Thu, 29 Jul 2010) | 2 lines
  
  Issue #9422:  Fix memory leak when re-initializing a struct.Struct object.
........
  r83259 | georg.brandl | 2010-07-30 08:03:39 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Clarification.
........
  r83260 | georg.brandl | 2010-07-30 08:14:01 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #4179: In pdb, allow "list ." as a command to return to the currently debugged line.
........
  r83261 | georg.brandl | 2010-07-30 08:21:26 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #9230: allow Pdb.checkline() to be called without a current frame, for setting breakpoints before starting debugging.
........
  r83262 | georg.brandl | 2010-07-30 09:29:39 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #1437051: allow "continue"/"next"/etc. in .pdbrc, also add pdb -c option to give these commands.  This allows to run a script until an exception occurs.
........
  r83263 | georg.brandl | 2010-07-30 09:43:32 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Allow giving an explicit line number to "until".
........
  r83264 | georg.brandl | 2010-07-30 09:45:26 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Document the "jump" command in pdb.__doc__, and add a version tag for "until X".
........
  r83265 | georg.brandl | 2010-07-30 09:54:49 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #8015: fix crash when entering an empty line for breakpoint commands.  Also restore environment properly when an exception occurs during the definition of commands.
........
  r83266 | georg.brandl | 2010-07-30 10:14:20 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #1472251: remove addition of "\n" to code given to pdb.run[eval](), the bug in exec() that made this necessary has been fixed.  Also document that you can give code objects to run() and runeval(), and add some tests to test_pdb.
........
  r83268 | georg.brandl | 2010-07-30 10:23:23 +0100 (Fri, 30 Jul 2010) | 2 lines
  
  Issue #8048: Prevent doctests from failing when sys.displayhook has
  been reassigned.
........
  r83269 | georg.brandl | 2010-07-30 10:43:00 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #6719: In pdb, do not stop somewhere in the encodings machinery if the source file to be debugged is in a non-builtin encoding.
........
  r83270 | georg.brandl | 2010-07-30 10:54:44 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Remove redundant import.
........
  r83271 | georg.brandl | 2010-07-30 10:59:28 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #5727: Restore the ability to use readline when calling into pdb in doctests.
........
  r83272 | georg.brandl | 2010-07-30 11:29:19 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #5294: Fix the behavior of pdb "continue" command when called in the top-level debugged frame.
........
  r83274 | georg.brandl | 2010-07-30 12:31:03 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #3143: enable "collapsible sidebar" feature of new Sphinx version.
........
  r83275 | georg.brandl | 2010-07-30 13:01:20 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #809887: improve pdb feedback for breakpoint-related actions.  Also add a functional test for these commands.
........
  r83277 | mark.dickinson | 2010-07-30 14:13:02 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Add note about surprising behaviour from round function.
........
  r83281 | georg.brandl | 2010-07-30 14:36:43 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Add myself for pdb.
........
  r83283 | georg.brandl | 2010-07-30 15:16:43 +0100 (Fri, 30 Jul 2010) | 1 line
  
  #7964 followup: add test case to ensure issue remains fixed.
........
  r83284 | georg.brandl | 2010-07-30 16:01:23 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Add Breakpoint.bpformat(), which returns the info usually printed by bpprint().  Necessary for major refactoring of pdb output handling.
........
  r83285 | georg.brandl | 2010-07-30 16:33:52 +0100 (Fri, 30 Jul 2010) | 1 line
  
  pdb now has its own tests.
........
  r83286 | georg.brandl | 2010-07-30 17:00:46 +0100 (Fri, 30 Jul 2010) | 7 lines
  
  Several enhancements to pdb and its test suite.
  
  * added basic test for basic commands
  * removed duplication of command docs, and moved them to their implementation
  * unified and useful display of exceptions
  * output messages and errors using overridable methods (also fixes #1503502)
........
  r83287 | georg.brandl | 2010-07-30 18:04:28 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Add "longlist" and "source" commands, ideas borrowed from pdb++ by Antonio Cuni.
........
  r83288 | martin.v.loewis | 2010-07-30 18:29:39 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Drop 2.4 support. Add disabled algorithms to Configure options.
........
  r83289 | martin.v.loewis | 2010-07-30 18:30:51 +0100 (Fri, 30 Jul 2010) | 2 lines
  
  Use OpenSSL 1.0.0a on Windows.
........
  r83291 | georg.brandl | 2010-07-30 19:08:12 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Fix source finding if the given frame is a module-level frame.
........
  r83292 | georg.brandl | 2010-07-30 19:15:16 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Test that "source" with nonexisting things works as expected.
........
  r83293 | georg.brandl | 2010-07-30 19:46:38 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Show the traceback line numbers as well as the current line numbers if an exception is being debugged.  Courtesy of pdb++ by Antonio Cuni.  Also document -> and >> markers for "list".
........
  r83294 | senthil.kumaran | 2010-07-30 20:34:36 +0100 (Fri, 30 Jul 2010) | 2 lines
  
  Fix issue9301 - handle unquote({}) kind of case.
........
  r83296 | martin.v.loewis | 2010-07-30 21:03:17 +0100 (Fri, 30 Jul 2010) | 2 lines
  
  Import files from zlib 1.2.5.
........
  r83307 | matthias.klose | 2010-07-30 22:40:57 +0100 (Fri, 30 Jul 2010) | 2 lines
  
  - Issue #7567: PyCurses_setupterm: Don't call `setupterm' twice.
........
  r83308 | georg.brandl | 2010-07-30 23:20:16 +0100 (Fri, 30 Jul 2010) | 1 line
  
  Part of #7245: when KeyboardInterrupt is raised while defining commands, restore the old commands instead of producing a traceback.
........
  r83313 | raymond.hettinger | 2010-07-31 08:12:50 +0100 (Sat, 31 Jul 2010) | 6 lines
  
  Only expose the abstract base classes.
  The concrete types are for internal use (registration).
  We are not trying to resurrect the types module
  in collections.
........
  r83315 | georg.brandl | 2010-07-31 09:14:16 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Fix pdb test failures on the buildbots.
........
  r83316 | georg.brandl | 2010-07-31 09:20:02 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Make urllib tests pass for now.  Will figure out what the correct semantics should be after release.
........
  r83317 | georg.brandl | 2010-07-31 09:27:46 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Update pydoc topics and adapt Topics builder to Sphinx 1.0.
........
  r83318 | georg.brandl | 2010-07-31 09:56:11 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Bump versions and review NEWS file.
........
  r83319 | florent.xicluna | 2010-07-31 09:56:55 +0100 (Sat, 31 Jul 2010) | 2 lines
  
  Fix an oversight in r83294.  unquote() should reject bytes.  Issue #9301.
........
  r83320 | georg.brandl | 2010-07-31 10:01:16 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Update copyright years and add releases to release list.  Also update Sphinx version number.
........
  r83321 | georg.brandl | 2010-07-31 10:03:30 +0100 (Sat, 31 Jul 2010) | 1 line
  
  At least give IDLE 3.1 a release date.  No further entries there for 3.2 though.
........
  r83322 | tarek.ziade | 2010-07-31 10:10:51 +0100 (Sat, 31 Jul 2010) | 1 line
  
  reverted distutils doc to its 3.1 state
........
  r83323 | georg.brandl | 2010-07-31 10:15:10 +0100 (Sat, 31 Jul 2010) | 1 line
  
  After distutils doc reversal, change back **bold todo** items to XXX comments.
........
  r83324 | martin.v.loewis | 2010-07-31 10:21:51 +0100 (Sat, 31 Jul 2010) | 2 lines
  
  Update OpenSSL version.
........
  r83325 | georg.brandl | 2010-07-31 10:37:03 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Copy Sun-specific inclusion of <alloca.h> from 2.7 maint to trunk; it seems to not have been merged to py3k.
........
  r83326 | georg.brandl | 2010-07-31 11:08:09 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Avoid triggering DeprecationWarnings in test_smtpd and smtpd.
........
  r83327 | raymond.hettinger | 2010-07-31 11:11:39 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Add functools.lfu_cache() and functools.lru_cache().
........
  r83328 | raymond.hettinger | 2010-07-31 11:14:41 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Document how to change OrderedDict update order from first to last.
........
  r83329 | georg.brandl | 2010-07-31 11:16:21 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Revert r83327.  This will have to wait until after the alpha1 release.
........
  r83335 | martin.v.loewis | 2010-07-31 11:49:53 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Copy asm files into place.
........
  r83336 | martin.v.loewis | 2010-07-31 11:50:16 +0100 (Sat, 31 Jul 2010) | 2 lines
  
  Delete openssl checkouts.
........
  r83337 | victor.stinner | 2010-07-31 11:52:56 +0100 (Sat, 31 Jul 2010) | 4 lines
  
  Issue #8966: Fix ctypes tests for Windows
  
  I removed the implicit conversion from str to bytes.
........
  r83338 | martin.v.loewis | 2010-07-31 11:56:53 +0100 (Sat, 31 Jul 2010) | 2 lines
  
  Truly uncomment rm lines.
........
  r83339 | georg.brandl | 2010-07-31 12:00:47 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Rewrap.
........
  r83341 | georg.brandl | 2010-07-31 12:40:07 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #9430: document timedelta str() and repr().
........
  r83342 | georg.brandl | 2010-07-31 12:52:46 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Import test_pdb with its full name, so that running python -m test.test_pdb succeeds.
........
  r83343 | georg.brandl | 2010-07-31 13:06:51 +0100 (Sat, 31 Jul 2010) | 1 line
  
  From Martin: New UUIDs for the 3.2 release series.
........
  r83348 | georg.brandl | 2010-07-31 19:05:35 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Post-release updates.
........
  r83349 | antoine.pitrou | 2010-07-31 19:08:33 +0100 (Sat, 31 Jul 2010) | 3 lines
  
  Add ssl changes to the 3.2 "what's new".
........
  r83350 | georg.brandl | 2010-07-31 19:09:23 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Re-commit r83327 now that the release is done.
........
  r83351 | georg.brandl | 2010-07-31 19:09:46 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Move news item to the correct position.
........
  r83352 | georg.brandl | 2010-07-31 19:11:07 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #9440: Remove borderline test case that fails based on unpredictable conditions such as compiler flags.
........
  r83353 | martin.v.loewis | 2010-07-31 19:59:20 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Drop webchecker and BerkeleyDB license.
........
  r83355 | georg.brandl | 2010-07-31 20:17:11 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Fix bad merge: test_support -> support.
........
  r83356 | georg.brandl | 2010-07-31 20:29:15 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Remove trailing whitespace.
........
  r83357 | georg.brandl | 2010-07-31 20:59:55 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #5778: document that sys.version can contain a newline.
........
  r83358 | georg.brandl | 2010-07-31 21:05:31 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #9442: do not document a specific format for sys.version; rather refer to version_info and the platform module.
........
  r83359 | georg.brandl | 2010-07-31 21:08:15 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #1286: allow using fileinput.FileInput as context manager.
........
  r83360 | georg.brandl | 2010-07-31 21:13:44 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Clarify comment in comments test case explaining comment semantics.
........
  r83361 | georg.brandl | 2010-07-31 22:04:00 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #3788: more tests for http.cookies, now at 95% coverage.  Also bring coding style in the module up to PEP 8, where it does not break backwards compatibility.
........
  r83362 | georg.brandl | 2010-07-31 22:12:15 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #8910: add a file explaining why Lib/test/data is there.
........
  r83366 | georg.brandl | 2010-07-31 22:26:40 +0100 (Sat, 31 Jul 2010) | 1 line
  
  There always is a False and True now.
........
  r83368 | georg.brandl | 2010-07-31 22:40:15 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #7909: the prefixes \\.\ and \\?\ indicate special Windows paths, do not try to manipulate them.  See http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx for details.
........
  r83369 | georg.brandl | 2010-07-31 22:41:42 +0100 (Sat, 31 Jul 2010) | 1 line
  
  Fix "Berkeley" name.
........
  r83370 | georg.brandl | 2010-07-31 22:51:48 +0100 (Sat, 31 Jul 2010) | 5 lines
  
  #8198: the Helper class should not save the stdin and stdout objects
  at import time, rather by default use the current streams like the
  other APIs that output help.
........
  r83371 | georg.brandl | 2010-07-31 22:54:24 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #8292: Fix three instances of truth tests on return values of filter() (which is always true in Python 3).
........
  r83372 | georg.brandl | 2010-07-31 23:05:54 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #4007: remove *.a and *.so.X.Y files in "make clean".
........
  r83373 | georg.brandl | 2010-07-31 23:11:11 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #5147: revert accidental indentation of header constant for MozillaCookieJar.
........
  r83374 | georg.brandl | 2010-07-31 23:32:52 +0100 (Sat, 31 Jul 2010) | 1 line
  
  #5146: handle UID THREAD command correctly.
........
  r83375 | antoine.pitrou | 2010-07-31 23:48:02 +0100 (Sat, 31 Jul 2010) | 3 lines
  
  Reorder entries by module lexicographic order
........
  r83376 | raymond.hettinger | 2010-08-01 00:33:22 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Fix build on VS8.
........
  r83380 | r.david.murray | 2010-08-01 04:31:09 +0100 (Sun, 01 Aug 2010) | 17 lines
  
  #8620: Cmd no longer truncates last character if stdin ends without newline
  
  Cmd used to blindly chop off the last character of every input line.  If
  the input reached EOF and there was no final new line, it would truncate
  the last character of the last command.  This fix instead strips trailing
  \r\n from the input lines.  While this is a small behavior change, it
  should not break any working code, since feeding a '\r\n' terminated
  file to Cmd would previously leave the \r's on the lines, resulting
  in failed command execution.
  
  I wrote the unit test in preparation for a PyOhio TeachMe session
  run by Catherine Devlin, and we can thank Catherine and the PyOhio
  session attendees for the fix.  I've added Catherine to the Acks file
  for organizing and leading the TeachMe session, out of which we will
  hopefully get some new contributors.
........
  r83384 | georg.brandl | 2010-08-01 07:32:55 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Build properties using lambdas.  This makes test_pyclbr pass again, because it does not think that input and output are methods anymore.
........
  r83385 | georg.brandl | 2010-08-01 07:42:45 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8773: mailbox.py does not need to be executable.
........
  r83386 | georg.brandl | 2010-08-01 07:44:46 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8768: name test method properly so that it gets executed.
........
  r83387 | georg.brandl | 2010-08-01 07:53:28 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8735: better explain semantics of *values* argument for parse().
........
  r83388 | georg.brandl | 2010-08-01 08:48:43 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #7395: fix traceback in do_add() when no stats are loaded.  Apply same fix for do_sort() and do_reverse().
........
  r83389 | georg.brandl | 2010-08-01 08:57:47 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Small improvements to pstats browser: do not crash on reading invalid file, and actually do a reload when executing "read" as intended.
........
  r83390 | georg.brandl | 2010-08-01 09:07:49 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8230: make Lib/test/sortperf.py run on Python 3.
........
  r83391 | georg.brandl | 2010-08-01 09:10:08 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Add another news entry.
........
  r83393 | georg.brandl | 2010-08-01 09:35:29 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #1690103: fix initial namespace for code run with trace.main().
........
  r83394 | georg.brandl | 2010-08-01 09:46:24 +0100 (Sun, 01 Aug 2010) | 1 line
  
  No need to split this, there are enough long lines.
........
  r83395 | georg.brandl | 2010-08-01 09:49:18 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8821: do not rely on Unicode strings being terminated with a \u0000, rather explicitly check range before looking for a second surrogate character.
........
  r83396 | georg.brandl | 2010-08-01 09:52:32 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #4810: document "--" option separator in timeit help.
........
  r83397 | ronald.oussoren | 2010-08-01 10:02:50 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Ensure that test_site actually passes with a framework build
........
  r83398 | georg.brandl | 2010-08-01 10:06:34 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8826: the "expires" attribute value is a date string with spaces, but apparently not all user-agents put it in quotes.  Handle that as a special case.
........
  r83399 | georg.brandl | 2010-08-01 10:17:53 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Package some new files that are needed for running the test suite from the MSI package.
........
  r83400 | mark.dickinson | 2010-08-01 11:41:49 +0100 (Sun, 01 Aug 2010) | 7 lines
  
  Issue #9416: Fix some issues with complex formatting where the
  output with no type specifier failed to match the str output:
  
    - format(complex(-0.0, 2.0), '-') omitted the real part from the output,
    - format(complex(0.0, 2.0), '-') included a sign and parentheses.
........
  r83403 | mark.dickinson | 2010-08-01 12:10:28 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Add test for memory leak reported in issue 9422.
........
  r83404 | georg.brandl | 2010-08-01 15:25:22 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #6439: fix argument type for PySys_SetArgvEx() and Py_SetProgramName() in Demo/embed code.
........
  r83405 | georg.brandl | 2010-08-01 15:38:17 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #4943: do not try to include drive letters (and colons) when looking for a probably module name.
........
  r83406 | georg.brandl | 2010-08-01 15:50:00 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #8046: add context manager protocol support to mmap objects.  Also add closed property.
........
  r83407 | brian.curtin | 2010-08-01 16:26:26 +0100 (Sun, 01 Aug 2010) | 3 lines
  
  Fix #8105. Add validation to mmap.mmap so invalid file descriptors
  don't cause a crash on Windows.
........
  r83408 | georg.brandl | 2010-08-01 16:30:56 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #5551: symbolic links never can be mount points.  Fixes the fix for #1713.
........
  r83411 | antoine.pitrou | 2010-08-01 17:53:42 +0100 (Sun, 01 Aug 2010) | 4 lines
  
  Issue #9448: Fix a leak of OS resources (mutexes or semaphores) when
  re-initializing a buffered IO object by calling its `__init__` method.
........
  r83415 | senthil.kumaran | 2010-08-01 18:53:37 +0100 (Sun, 01 Aug 2010) | 3 lines
  
  Fix Issue8123 - TypeError in urllib when trying to use HTTP authentication
........
  r83417 | georg.brandl | 2010-08-01 19:38:26 +0100 (Sun, 01 Aug 2010) | 1 line
  
  #5776: fix mistakes in python specfile.  (Nobody probably uses it anyway.)
........
  r83431 | ronald.oussoren | 2010-08-01 20:18:13 +0100 (Sun, 01 Aug 2010) | 6 lines
  
  
  test_getgroups as introduced with issue7900 failed on systems
  where 'id -G' and posix.getgroups() returned the same information,
  but one of the sources contains duplicate information. Rewrite the
  check using sets instead of lists.
........
  r83440 | antoine.pitrou | 2010-08-01 21:08:46 +0100 (Sun, 01 Aug 2010) | 4 lines
  
  Issue #8397: Raise an error when attempting to mix iteration and regular
  reads on a BZ2File object, rather than returning incorrect results.
........
  r83444 | georg.brandl | 2010-08-01 21:51:02 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Revert r83395, it introduces test failures and is not necessary anyway since we now have to nul-terminate the string anyway.
........
  r83456 | raymond.hettinger | 2010-08-01 22:10:35 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Issue 9445: Fix undefined symbols on VS8.0 build.
........
  r83479 | mark.dickinson | 2010-08-01 22:33:01 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Don't delete Lib/test/data/README when doing 'make distclean'
........
  r83488 | raymond.hettinger | 2010-08-01 22:50:38 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Fix VS8.0 build by adding _time.h and _time.c to the project file.
........
  r83494 | raymond.hettinger | 2010-08-01 23:10:57 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Update OrderedDict implementation to match that in Py2.7.
........
  r83501 | georg.brandl | 2010-08-01 23:31:05 +0100 (Sun, 01 Aug 2010) | 1 line
  
  Fix style of referring to issues.
........
  r83506 | r.david.murray | 2010-08-02 00:43:28 +0100 (Mon, 02 Aug 2010) | 2 lines
  
  Fix ACKS alphabetization.
........
  r83513 | raymond.hettinger | 2010-08-02 01:59:14 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Add example applications for the LRU and LFU cache docs.
........
  r83516 | raymond.hettinger | 2010-08-02 02:43:41 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Demonstrate the caching decorators in whatsnew.
........
  r83521 | senthil.kumaran | 2010-08-02 12:04:58 +0100 (Mon, 02 Aug 2010) | 3 lines
  
  Fix Issue8572  - httplib getheader() throws error instead of default
........
  r83523 | georg.brandl | 2010-08-02 13:06:18 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9209 and #7781: fix two crashes in pstats interactive browser.
........
  r83524 | georg.brandl | 2010-08-02 13:20:23 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9428: fix running scripts from profile/cProfile with their own name and the right namespace.  Same fix as for trace.py in #1690103.
........
  r83525 | georg.brandl | 2010-08-02 13:36:24 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Get rid of spurious "threading" entries in trace output.
........
  r83526 | georg.brandl | 2010-08-02 13:40:22 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Fix softspace relic.
........
  r83527 | georg.brandl | 2010-08-02 13:48:46 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #3821: beginnings of a trace.py unittest.
........
  r83528 | georg.brandl | 2010-08-02 13:54:24 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Document how to refer to decorators and decorator methods.
........
  r83529 | senthil.kumaran | 2010-08-02 18:09:02 +0100 (Mon, 02 Aug 2010) | 3 lines
  
  Rewording the getheader method of HTTPResponse.
........
  r83531 | georg.brandl | 2010-08-02 18:24:49 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #7372: fix regression in pstats: a previous fix to handle cProfile data in add_callers broke handling of profile data.
........
  r83536 | georg.brandl | 2010-08-02 18:49:25 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #8578: mention danger of not incref'ing weak referenced object.
........
  r83538 | georg.brandl | 2010-08-02 19:10:13 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #6928: fix class docs w.r.t. new metaclasses.
........
  r83542 | georg.brandl | 2010-08-02 19:56:54 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Move test_SimpleHTTPServer into test_httpservers.
........
  r83543 | georg.brandl | 2010-08-02 19:59:52 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #8560: add progress indicator to regrtest.
........
  r83546 | georg.brandl | 2010-08-02 20:16:34 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #7973: Fix distutils options spelling.
........
  r83547 | georg.brandl | 2010-08-02 20:19:26 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #7386: add example that shows that trailing path separators are stripped.
........
  r83548 | georg.brandl | 2010-08-02 20:23:34 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #8172: how does one use a property?
........
  r83550 | georg.brandl | 2010-08-02 20:32:43 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9451: strengthen warning about __*__ special name usage.
........
  r83551 | georg.brandl | 2010-08-02 20:35:06 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Remove XXX comment that was displayed.
........
  r83552 | georg.brandl | 2010-08-02 20:36:36 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9438: clarify that constant names also cannot be assigned as attributes.
........
  r83553 | georg.brandl | 2010-08-02 20:39:17 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Remove redundant information.
........
  r83554 | georg.brandl | 2010-08-02 20:43:05 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #7280: note about nasmw.exe.
........
  r83555 | georg.brandl | 2010-08-02 20:44:48 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #8861: remove unused variable.
........
  r83558 | georg.brandl | 2010-08-02 21:05:19 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #8648: document UTF-7 codec functions.
........
  r83560 | georg.brandl | 2010-08-02 21:16:18 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9087: update json docstrings -- unicode and long do not exist anymore.
........
  r83561 | georg.brandl | 2010-08-02 21:17:50 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #4280: remove outdated "versionchecker" tool.
........
  r83563 | georg.brandl | 2010-08-02 21:21:21 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9037: add example how to raise custom exceptions from C code.
........
  r83565 | georg.brandl | 2010-08-02 21:27:20 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9111: document that do_help() looks at docstrings.
........
  r83566 | georg.brandl | 2010-08-02 21:30:57 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9019: remove false (in 3k) claim about Headers updates.
........
  r83569 | georg.brandl | 2010-08-02 21:39:35 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #7797: be explicit about bytes-oriented interface of base64 functions.
........
  r83571 | georg.brandl | 2010-08-02 21:44:34 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Clarify that abs() is not a namespace.
........
  r83574 | georg.brandl | 2010-08-02 21:47:56 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #6867: epoll.register() returns None.
........
  r83575 | georg.brandl | 2010-08-02 21:52:10 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9238: zipfile does handle archive comments.
........
  r83580 | georg.brandl | 2010-08-02 22:02:36 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #8119: fix copy-paste error.
........
  r83584 | georg.brandl | 2010-08-02 22:07:14 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9457: fix documentation links for 3.2.
........
  r83599 | georg.brandl | 2010-08-02 22:51:18 +0100 (Mon, 02 Aug 2010) | 1 line
  
  #9061: warn that single quotes are never escaped.
........
  r83605 | georg.brandl | 2010-08-02 23:08:58 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Make the Pynche tool work with Python 3.
........
  r83606 | georg.brandl | 2010-08-02 23:25:16 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Minimum fixes to make freeze.py do something useful.
........
  r83607 | georg.brandl | 2010-08-02 23:28:01 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Remove faqwiz tool.
........
  r83608 | georg.brandl | 2010-08-02 23:31:22 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Update README for Tools.
........
  r83609 | georg.brandl | 2010-08-02 23:53:22 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Update README, remove obsolete scripts.
........
  r83610 | georg.brandl | 2010-08-02 23:55:17 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Update README, remove obsolete script.
........
  r83611 | georg.brandl | 2010-08-02 23:58:25 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Make the framer run (still generates wrong code for module creation though.)
........
  r83612 | georg.brandl | 2010-08-02 23:59:44 +0100 (Mon, 02 Aug 2010) | 1 line
  
  Fix unicode literal.
........
  r83613 | georg.brandl | 2010-08-03 00:13:12 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Update Demo README.
........
  r83614 | georg.brandl | 2010-08-03 00:13:24 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Make minigzip work again.
........
  r83615 | georg.brandl | 2010-08-03 00:15:58 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Another demo that at least runs again.
........
  r83616 | georg.brandl | 2010-08-03 00:17:21 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Remove obsolete pdist demo.
........
  r83617 | georg.brandl | 2010-08-03 00:18:35 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Remove reference to removed faqwiz tool.
........
  r83618 | georg.brandl | 2010-08-03 00:30:09 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Fix-up some tkinter demos.
........
  r83636 | richard.jones | 2010-08-03 07:39:33 +0100 (Tue, 03 Aug 2010) | 2 lines
  
  improvements to test_smtplib per issue2423
  merged the socket mock introduced in test_smtpd
........
  r83644 | ronald.oussoren | 2010-08-03 08:42:42 +0100 (Tue, 03 Aug 2010) | 2 lines
  
  Fix for issue 9455: platform.mac_ver() broken on OSX/ppc
........
  r83649 | georg.brandl | 2010-08-03 08:56:50 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Fix regrtest -F.
........
  r83659 | georg.brandl | 2010-08-03 13:06:29 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Terminology fix: exceptions are raised, except in generator.throw().
........
  r83660 | georg.brandl | 2010-08-03 13:31:59 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Get rid of UserWarnings when running Sphinx from tools dir.
........
  r83663 | georg.brandl | 2010-08-03 13:36:57 +0100 (Tue, 03 Aug 2010) | 1 line
  
  A couple of nits how to ignore errors.
........
  r83667 | mark.dickinson | 2010-08-03 17:08:16 +0100 (Tue, 03 Aug 2010) | 2 lines
  
  Issue #9450:  Fix memory leaks in readline.remove/replace_history_entry.
........
  r83670 | mark.dickinson | 2010-08-03 17:49:49 +0100 (Tue, 03 Aug 2010) | 3 lines
  
  Issue #8065:  Fix another memory leak in readline module, from failure to free
  the result of a call to history_get_history_state.
........
  r83673 | antoine.pitrou | 2010-08-03 18:09:36 +0100 (Tue, 03 Aug 2010) | 4 lines
  
  Issue #8867: Fix `Tools/scripts/serve.py` to work with files containing
  non-ASCII content.
........
  r83675 | r.david.murray | 2010-08-03 18:56:09 +0100 (Tue, 03 Aug 2010) | 12 lines
  
  #9444: use first of prefix_chars for help opt instead of raising error
  
  An argparse option parser created with a prefix_chars that did not
  include a '-' would happily add -h and --help options, and then throw
  an error when it tried to format the help because the - was an invalid
  prefix character.  This patch makes it use the first character of
  prefix_chars as the character for the help options if and only if '-'
  is not one of the valid prefix_chars.
  
  Fix by Theodore Turocy, unit tests by Catherine Devlin.
........
  r83677 | mark.dickinson | 2010-08-03 19:31:54 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Fix memory leak in ssl module.
........
  r83678 | antoine.pitrou | 2010-08-03 19:32:26 +0100 (Tue, 03 Aug 2010) | 4 lines
  
  In test_threading_local, test both the default _thread._local implementation
  and the pure Python implementation in Lib/_threading_local.py
........
  r83681 | martin.v.loewis | 2010-08-03 19:35:55 +0100 (Tue, 03 Aug 2010) | 2 lines
  
  Add various missing files.
  Improve detection of unpackaged files.
........
  r83683 | mark.dickinson | 2010-08-03 19:44:16 +0100 (Tue, 03 Aug 2010) | 1 line
  
  Misc/NEWS entry for r83677.
........
  r83690 | r.david.murray | 2010-08-03 23:14:10 +0100 (Tue, 03 Aug 2010) | 10 lines
  
  #3196: if needed pad a short base64 encoded word before trying to decode.
  
  The RFCs encourage following Postel's law: be liberal in what you accept.
  So if someone forgot to pad the base64 encoded word payload to an
  even four bytes, we add the padding before handing it to base64mime.decode.
  Previously, missing padding resulted in a HeaderParseError.
  
  Patch by Jason Williams.
........
  r83696 | antoine.pitrou | 2010-08-04 01:18:49 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  That test was never run (since thread has been renamed to _thread in 3.x)
........
  r83698 | richard.jones | 2010-08-04 02:19:22 +0100 (Wed, 04 Aug 2010) | 1 line
  
  note smtpd module changes in NEWS
........
  r83699 | richard.jones | 2010-08-04 02:20:14 +0100 (Wed, 04 Aug 2010) | 1 line
  
  improve smtpd module test coverage
........
  r83701 | senthil.kumaran | 2010-08-04 05:50:44 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Fix Issue754016 - urlparse goes wrong with IP:port without scheme
........
  r83705 | giampaolo.rodola | 2010-08-04 10:02:27 +0100 (Wed, 04 Aug 2010) | 1 line
  
  fix issue #2944: asyncore doesn't handle connection refused correctly (patch by Alexander Shigin). Merged from 2.7 branch.
........
  r83707 | giampaolo.rodola | 2010-08-04 10:28:05 +0100 (Wed, 04 Aug 2010) | 1 line
  
  issue #8687: provides a test suite for sched.py module
........
  r83708 | giampaolo.rodola | 2010-08-04 11:12:00 +0100 (Wed, 04 Aug 2010) | 1 line
  
  fix issue #6822: ftplib's storline method doesn't work with text files
........
  r83709 | antoine.pitrou | 2010-08-04 11:26:30 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Something fun to maintain
........
  r83712 | giampaolo.rodola | 2010-08-04 11:36:18 +0100 (Wed, 04 Aug 2010) | 1 line
  
  as per discussion with antoine revert changes made in 83708 as the user useing ftplib's readline methods is supposed to always use a binary file
........
  r83713 | antoine.pitrou | 2010-08-04 12:48:56 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Factor out stripping of interpreter debug output in test.support.strip_python_stderr()
........
  r83714 | richard.jones | 2010-08-04 13:27:36 +0100 (Wed, 04 Aug 2010) | 1 line
  
  fix test_smtplib/test_smtpd collision through pre-loaded reply data in mock_socket
........
  r83715 | antoine.pitrou | 2010-08-04 14:24:41 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  I'm interested in threading issues as well
........
  r83719 | antoine.pitrou | 2010-08-04 16:43:16 +0100 (Wed, 04 Aug 2010) | 4 lines
  
  Issue #9496: Provide a test suite for the rlcompleter module.  Patch by
  Michele Orrù.
........
  r83722 | brian.curtin | 2010-08-04 16:47:24 +0100 (Wed, 04 Aug 2010) | 7 lines
  
  Fix #9513 to remove relative imports from multiprocessing.
  
  The test suite currently skips test_multiprocessing on Windows
  because it fails on finding _multiprocessing in several
  win32-specific blocks. Removing the relative import lets this
  through and allows the test to run (and pass).
........
  r83726 | antoine.pitrou | 2010-08-04 17:45:21 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  In verbose mode, identify OpenSSL build and platform more precisely
........
  r83727 | antoine.pitrou | 2010-08-04 18:14:06 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Try to fix issue #9415: skip some tests on broken Ubuntu OpenSSL
........
  r83729 | senthil.kumaran | 2010-08-04 18:46:23 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Sending the auth info as string. Fix BytesWarning: str() on a bytes instance Exception on buildbot.
........
  r83731 | antoine.pitrou | 2010-08-04 19:28:02 +0100 (Wed, 04 Aug 2010) | 5 lines
  
  Issue #8814: function annotations (the `__annotations__` attribute)
  are now included in the set of attributes copied by default by
  functools.wraps and functools.update_wrapper.  Patch by Terrence Cole.
........
  r83732 | mark.dickinson | 2010-08-04 19:42:43 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Issue #9498:  Add reference to sys.float_info from 'numeric types' docs.
  Thanks Yitz Gale.
........
  r83735 | martin.v.loewis | 2010-08-04 20:08:20 +0100 (Wed, 04 Aug 2010) | 2 lines
  
  Add Terry Reedy.
........
  r83736 | mark.dickinson | 2010-08-04 21:56:28 +0100 (Wed, 04 Aug 2010) | 3 lines
  
  Issue #9337:  Make float.__str__ identical to float.__repr__.
  (And similarly for complex numbers.)
........
  r83741 | alexandre.vassalotti | 2010-08-05 08:12:18 +0100 (Thu, 05 Aug 2010) | 4 lines
  
  Issue 5077: Add documentation for operator fixer.
  
  Patch by Meador Inge.
........
  r83742 | gerhard.haering | 2010-08-05 15:08:44 +0100 (Thu, 05 Aug 2010) | 6 lines
  
  Issue #6683: For SMTP logins we now try all authentication methods advertised
  by the server. Many servers are buggy and advertise authentication methods they
  o not support in reality. This change makes smtplib.auth() work more often in
  the real world, where we face misconfigured servers and servers that advertise
  methods they don't support due to the madness that is SASL.
........
  r83744 | alexander.belopolsky | 2010-08-05 18:34:27 +0100 (Thu, 05 Aug 2010) | 5 lines
  
  Issue #9079: Added _PyTime_gettimeofday(_PyTime_timeval *tp) to C API
  exposed in Python.h.  This function is similar to POSIX
  gettimeofday(struct timeval *tp), but available on platforms without
  gettimeofday().
........
  r83745 | brian.curtin | 2010-08-05 19:56:00 +0100 (Thu, 05 Aug 2010) | 4 lines
  
  Issue #9524: Document that two CTRL* signals are meant for use only
  with os.kill.
........
  r83747 | gerhard.haering | 2010-08-06 07:12:05 +0100 (Fri, 06 Aug 2010) | 2 lines
  
  Issue #3854: Documented using the sqlite3 module with multiple threads.
........
  r83750 | raymond.hettinger | 2010-08-06 10:22:46 +0100 (Fri, 06 Aug 2010) | 1 line
  
  Fix the VS8.0 build
........
  r83751 | mark.dickinson | 2010-08-06 10:36:57 +0100 (Fri, 06 Aug 2010) | 1 line
  
  Issue #9526:  Remove outdated casts to int that were preventing the array module from working correctly with arrays > 2GB.
........
  r83752 | mark.dickinson | 2010-08-06 10:38:58 +0100 (Fri, 06 Aug 2010) | 1 line
  
  Misc/NEWS entry for r83751.
........
  r83755 | raymond.hettinger | 2010-08-06 10:52:17 +0100 (Fri, 06 Aug 2010) | 1 line
  
  Issue8757:  Implicit set-to-frozenset conversion not thread-safe.
........
  r83758 | martin.v.loewis | 2010-08-06 11:43:31 +0100 (Fri, 06 Aug 2010) | 1 line
  
  Change pyc removal to support __pycache__.
........
  r83759 | tim.golden | 2010-08-06 14:03:56 +0100 (Fri, 06 Aug 2010) | 1 line
  
  Issue #3210: Ensure stdio handles are closed if CreateProcess fails
........
  r83762 | mark.dickinson | 2010-08-06 19:55:26 +0100 (Fri, 06 Aug 2010) | 1 line
  
  In PySlice_IndicesEx, clip the step to [-PY_SSIZE_T_MAX, PY_SSIZE_T_MAX] rather than [PY_SSIZE_T_MIN, PY_SSIZE_T_MAX].
........
  r83763 | brian.curtin | 2010-08-06 20:27:32 +0100 (Fri, 06 Aug 2010) | 3 lines
  
  Fix #9324: Add parameter validation to signal.signal on Windows in order
  to prevent crashes.
........
  r83767 | r.david.murray | 2010-08-06 22:18:49 +0100 (Fri, 06 Aug 2010) | 4 lines
  
  Add xml subpackages, since they are likely to have different maintainers.
  
  And if not they can be merged back together when that becomes apparent.
........
  r83768 | mark.dickinson | 2010-08-06 22:33:18 +0100 (Fri, 06 Aug 2010) | 3 lines
  
  Issue #9530:  Fix a couple of places where undefined behaviour can
  occur, as a result of signed integer overflow.
........
  r83770 | raymond.hettinger | 2010-08-07 00:23:49 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Improve the whatsnew article on the lru/lfu cache decorators.
........
  r83771 | brian.curtin | 2010-08-07 04:47:21 +0100 (Sat, 07 Aug 2010) | 3 lines
  
  Fix an assertRaises situation and typo. Also pass all tests to run_unittest
  rather than do it by platform -- the proper skips are in place already.
........
  r83774 | raymond.hettinger | 2010-08-07 05:19:49 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Fix markup
........
  r83775 | raymond.hettinger | 2010-08-07 06:36:53 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Add partition recipe to itertools docs.
........
  r83776 | raymond.hettinger | 2010-08-07 06:54:08 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Fix nit (sentinel on lhs of comparison).
........
  r83777 | raymond.hettinger | 2010-08-07 08:36:55 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Improve the docs for bisect to cover common searching tasks.
........
  r83778 | victor.stinner | 2010-08-07 11:09:35 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Issue #9425: skip tests if a filename is not encodable
........
  r83779 | victor.stinner | 2010-08-07 11:57:17 +0100 (Sat, 07 Aug 2010) | 3 lines
  
  Issue #9425: Create run_command() subfunction
  
  Use PyUnicode_AsUTF8String() instead of _PyUnicode_AsString()
........
  r83780 | mark.dickinson | 2010-08-07 13:33:36 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Issue #8433: Fix test_curses failure for platforms with recent versions of ncurses.
........
  r83783 | victor.stinner | 2010-08-07 17:34:25 +0100 (Sat, 07 Aug 2010) | 5 lines
  
  Issue #9425: Create run_file() subfunction
  
   * Call Py_MakePendingCalls() before converting the filename from
     wchar_t* to char*
   * Use PyUnicode_AsUTF8String() instead of _PyUnicode_AsString()
........
  r83784 | raymond.hettinger | 2010-08-07 22:31:55 +0100 (Sat, 07 Aug 2010) | 1 line
  
  Clean-up docstring in examples.
........
  r83785 | benjamin.peterson | 2010-08-07 22:32:12 +0100 (Sat, 07 Aug 2010) | 1 line
  
  kill outdated comment
........
  r83792 | raymond.hettinger | 2010-08-08 00:31:27 +0100 (Sun, 08 Aug 2010) | 1 line
  
  Document implementation notes for priority queues
........
  r83795 | raymond.hettinger | 2010-08-08 00:37:37 +0100 (Sun, 08 Aug 2010) | 1 line
  
  Fix typo
........
  r83802 | benjamin.peterson | 2010-08-08 01:04:26 +0100 (Sun, 08 Aug 2010) | 1 line
  
  set svn:eol-style
........
  r83804 | raymond.hettinger | 2010-08-08 01:29:08 +0100 (Sun, 08 Aug 2010) | 4 lines
  
  Improve readability of collections docs by adding a summary table
  at the top and by list concrete classes before abstract base classes.
........
  r83808 | raymond.hettinger | 2010-08-08 02:13:42 +0100 (Sun, 08 Aug 2010) | 4 lines
  
  Issue #9507:  Named tuple repr will now automatically display the right
  name in a tuple subclass.
........
  r83809 | raymond.hettinger | 2010-08-08 02:30:45 +0100 (Sun, 08 Aug 2010) | 1 line
  
  Issue #4570:  Clean-up tutorial example
........


Added:
   python/branches/py3k-dtoa/Include/pytime.h
      - copied unchanged from r83809, /python/branches/py3k/Include/pytime.h
   python/branches/py3k-dtoa/Lib/datetime.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/datetime.py
   python/branches/py3k-dtoa/Lib/test/cfgparser.2
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/cfgparser.2
   python/branches/py3k-dtoa/Lib/test/cfgparser.3
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/cfgparser.3
   python/branches/py3k-dtoa/Lib/test/data/README
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/data/README
   python/branches/py3k-dtoa/Lib/test/datetimetester.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/datetimetester.py
   python/branches/py3k-dtoa/Lib/test/mock_socket.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/mock_socket.py
   python/branches/py3k-dtoa/Lib/test/sndhdrdata/
      - copied from r83809, /python/branches/py3k/Lib/test/sndhdrdata/
   python/branches/py3k-dtoa/Lib/test/symlink_support.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/symlink_support.py
   python/branches/py3k-dtoa/Lib/test/test_rlcompleter.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_rlcompleter.py
   python/branches/py3k-dtoa/Lib/test/test_sched.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_sched.py
   python/branches/py3k-dtoa/Lib/test/test_smtpd.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_smtpd.py
   python/branches/py3k-dtoa/Lib/test/test_sndhdr.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_sndhdr.py
   python/branches/py3k-dtoa/Lib/test/test_sys_setprofile.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_sys_setprofile.py
   python/branches/py3k-dtoa/Lib/test/test_sys_settrace.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_sys_settrace.py
   python/branches/py3k-dtoa/Lib/test/test_trace.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/test/test_trace.py
   python/branches/py3k-dtoa/Lib/tkinter/__main__.py
      - copied unchanged from r83809, /python/branches/py3k/Lib/tkinter/__main__.py
   python/branches/py3k-dtoa/Modules/_datetimemodule.c
      - copied unchanged from r83809, /python/branches/py3k/Modules/_datetimemodule.c
   python/branches/py3k-dtoa/Python/pytime.c
      - copied unchanged from r83809, /python/branches/py3k/Python/pytime.c
Removed:
   python/branches/py3k-dtoa/Demo/pdist/
   python/branches/py3k-dtoa/Demo/scripts/toaiff.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_ccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_emxccompiler.py
   python/branches/py3k-dtoa/Lib/pdb.doc
   python/branches/py3k-dtoa/Lib/test/test_SimpleHTTPServer.py
   python/branches/py3k-dtoa/Lib/test/test_profilehooks.py
   python/branches/py3k-dtoa/Modules/datetimemodule.c
   python/branches/py3k-dtoa/Tools/faqwiz/
   python/branches/py3k-dtoa/Tools/scripts/checkappend.py
   python/branches/py3k-dtoa/Tools/scripts/classfix.py
   python/branches/py3k-dtoa/Tools/scripts/cvsfiles.py
   python/branches/py3k-dtoa/Tools/scripts/logmerge.py
   python/branches/py3k-dtoa/Tools/scripts/methfix.py
   python/branches/py3k-dtoa/Tools/scripts/setup.py
   python/branches/py3k-dtoa/Tools/scripts/xxci.py
   python/branches/py3k-dtoa/Tools/versioncheck/
Modified:
   python/branches/py3k-dtoa/   (props changed)
   python/branches/py3k-dtoa/Demo/README
   python/branches/py3k-dtoa/Demo/embed/Makefile
   python/branches/py3k-dtoa/Demo/embed/demo.c
   python/branches/py3k-dtoa/Demo/embed/loop.c
   python/branches/py3k-dtoa/Demo/scripts/README
   python/branches/py3k-dtoa/Demo/tkinter/guido/AttrDialog.py
   python/branches/py3k-dtoa/Demo/tkinter/guido/ManPage.py
   python/branches/py3k-dtoa/Demo/tkinter/guido/brownian2.py
   python/branches/py3k-dtoa/Demo/tkinter/guido/kill.py
   python/branches/py3k-dtoa/Demo/zlib/minigzip.py
   python/branches/py3k-dtoa/Demo/zlib/zlibdemo.py
   python/branches/py3k-dtoa/Doc/Makefile
   python/branches/py3k-dtoa/Doc/README.txt
   python/branches/py3k-dtoa/Doc/c-api/init.rst
   python/branches/py3k-dtoa/Doc/c-api/unicode.rst
   python/branches/py3k-dtoa/Doc/c-api/weakref.rst
   python/branches/py3k-dtoa/Doc/conf.py
   python/branches/py3k-dtoa/Doc/distutils/apiref.rst
   python/branches/py3k-dtoa/Doc/distutils/builtdist.rst
   python/branches/py3k-dtoa/Doc/distutils/commandref.rst
   python/branches/py3k-dtoa/Doc/distutils/examples.rst
   python/branches/py3k-dtoa/Doc/distutils/setupscript.rst
   python/branches/py3k-dtoa/Doc/distutils/sourcedist.rst
   python/branches/py3k-dtoa/Doc/distutils/uploading.rst
   python/branches/py3k-dtoa/Doc/documenting/building.rst   (props changed)
   python/branches/py3k-dtoa/Doc/documenting/markup.rst
   python/branches/py3k-dtoa/Doc/extending/extending.rst
   python/branches/py3k-dtoa/Doc/faq/extending.rst
   python/branches/py3k-dtoa/Doc/glossary.rst
   python/branches/py3k-dtoa/Doc/howto/descriptor.rst   (props changed)
   python/branches/py3k-dtoa/Doc/howto/doanddont.rst
   python/branches/py3k-dtoa/Doc/install/index.rst
   python/branches/py3k-dtoa/Doc/library/2to3.rst
   python/branches/py3k-dtoa/Doc/library/abc.rst
   python/branches/py3k-dtoa/Doc/library/argparse.rst
   python/branches/py3k-dtoa/Doc/library/ast.rst
   python/branches/py3k-dtoa/Doc/library/base64.rst
   python/branches/py3k-dtoa/Doc/library/bdb.rst
   python/branches/py3k-dtoa/Doc/library/binascii.rst
   python/branches/py3k-dtoa/Doc/library/bisect.rst
   python/branches/py3k-dtoa/Doc/library/cgi.rst
   python/branches/py3k-dtoa/Doc/library/cmath.rst
   python/branches/py3k-dtoa/Doc/library/cmd.rst
   python/branches/py3k-dtoa/Doc/library/collections.rst
   python/branches/py3k-dtoa/Doc/library/configparser.rst
   python/branches/py3k-dtoa/Doc/library/constants.rst
   python/branches/py3k-dtoa/Doc/library/contextlib.rst
   python/branches/py3k-dtoa/Doc/library/datetime.rst
   python/branches/py3k-dtoa/Doc/library/dbm.rst
   python/branches/py3k-dtoa/Doc/library/doctest.rst
   python/branches/py3k-dtoa/Doc/library/email.errors.rst
   python/branches/py3k-dtoa/Doc/library/fileinput.rst
   python/branches/py3k-dtoa/Doc/library/fnmatch.rst
   python/branches/py3k-dtoa/Doc/library/ftplib.rst
   python/branches/py3k-dtoa/Doc/library/functions.rst
   python/branches/py3k-dtoa/Doc/library/functools.rst
   python/branches/py3k-dtoa/Doc/library/heapq.rst
   python/branches/py3k-dtoa/Doc/library/html.parser.rst
   python/branches/py3k-dtoa/Doc/library/http.client.rst
   python/branches/py3k-dtoa/Doc/library/http.cookiejar.rst
   python/branches/py3k-dtoa/Doc/library/importlib.rst
   python/branches/py3k-dtoa/Doc/library/io.rst
   python/branches/py3k-dtoa/Doc/library/itertools.rst
   python/branches/py3k-dtoa/Doc/library/linecache.rst
   python/branches/py3k-dtoa/Doc/library/locale.rst
   python/branches/py3k-dtoa/Doc/library/math.rst
   python/branches/py3k-dtoa/Doc/library/mmap.rst
   python/branches/py3k-dtoa/Doc/library/multiprocessing.rst
   python/branches/py3k-dtoa/Doc/library/optparse.rst
   python/branches/py3k-dtoa/Doc/library/os.path.rst
   python/branches/py3k-dtoa/Doc/library/os.rst
   python/branches/py3k-dtoa/Doc/library/parser.rst
   python/branches/py3k-dtoa/Doc/library/pdb.rst
   python/branches/py3k-dtoa/Doc/library/pickletools.rst
   python/branches/py3k-dtoa/Doc/library/pyexpat.rst
   python/branches/py3k-dtoa/Doc/library/re.rst
   python/branches/py3k-dtoa/Doc/library/select.rst
   python/branches/py3k-dtoa/Doc/library/signal.rst
   python/branches/py3k-dtoa/Doc/library/smtpd.rst
   python/branches/py3k-dtoa/Doc/library/smtplib.rst
   python/branches/py3k-dtoa/Doc/library/socket.rst
   python/branches/py3k-dtoa/Doc/library/sqlite3.rst
   python/branches/py3k-dtoa/Doc/library/stdtypes.rst
   python/branches/py3k-dtoa/Doc/library/string.rst
   python/branches/py3k-dtoa/Doc/library/struct.rst
   python/branches/py3k-dtoa/Doc/library/subprocess.rst
   python/branches/py3k-dtoa/Doc/library/sys.rst
   python/branches/py3k-dtoa/Doc/library/test.rst
   python/branches/py3k-dtoa/Doc/library/threading.rst
   python/branches/py3k-dtoa/Doc/library/tkinter.rst
   python/branches/py3k-dtoa/Doc/library/unittest.rst
   python/branches/py3k-dtoa/Doc/library/urllib.parse.rst
   python/branches/py3k-dtoa/Doc/library/urllib.request.rst
   python/branches/py3k-dtoa/Doc/library/wsgiref.rst
   python/branches/py3k-dtoa/Doc/library/xml.dom.minidom.rst
   python/branches/py3k-dtoa/Doc/library/xml.dom.rst
   python/branches/py3k-dtoa/Doc/library/xml.sax.reader.rst
   python/branches/py3k-dtoa/Doc/library/zipfile.rst
   python/branches/py3k-dtoa/Doc/license.rst
   python/branches/py3k-dtoa/Doc/make.bat
   python/branches/py3k-dtoa/Doc/reference/compound_stmts.rst
   python/branches/py3k-dtoa/Doc/reference/expressions.rst
   python/branches/py3k-dtoa/Doc/reference/lexical_analysis.rst
   python/branches/py3k-dtoa/Doc/tools/sphinx-build.py
   python/branches/py3k-dtoa/Doc/tools/sphinxext/indexsidebar.html
   python/branches/py3k-dtoa/Doc/tools/sphinxext/pyspecific.py
   python/branches/py3k-dtoa/Doc/tutorial/classes.rst
   python/branches/py3k-dtoa/Doc/tutorial/datastructures.rst
   python/branches/py3k-dtoa/Doc/tutorial/floatingpoint.rst
   python/branches/py3k-dtoa/Doc/using/cmdline.rst
   python/branches/py3k-dtoa/Doc/whatsnew/2.0.rst
   python/branches/py3k-dtoa/Doc/whatsnew/2.4.rst
   python/branches/py3k-dtoa/Doc/whatsnew/2.5.rst
   python/branches/py3k-dtoa/Doc/whatsnew/2.7.rst
   python/branches/py3k-dtoa/Doc/whatsnew/3.2.rst
   python/branches/py3k-dtoa/Grammar/Grammar
   python/branches/py3k-dtoa/Include/Python.h
   python/branches/py3k-dtoa/Include/floatobject.h
   python/branches/py3k-dtoa/Include/patchlevel.h
   python/branches/py3k-dtoa/Include/structseq.h
   python/branches/py3k-dtoa/LICENSE
   python/branches/py3k-dtoa/Lib/_abcoll.py
   python/branches/py3k-dtoa/Lib/_strptime.py
   python/branches/py3k-dtoa/Lib/argparse.py
   python/branches/py3k-dtoa/Lib/ast.py
   python/branches/py3k-dtoa/Lib/asyncore.py
   python/branches/py3k-dtoa/Lib/base64.py
   python/branches/py3k-dtoa/Lib/bdb.py
   python/branches/py3k-dtoa/Lib/cProfile.py
   python/branches/py3k-dtoa/Lib/cmd.py
   python/branches/py3k-dtoa/Lib/collections.py
   python/branches/py3k-dtoa/Lib/configparser.py
   python/branches/py3k-dtoa/Lib/ctypes/__init__.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_arrays.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_bitfields.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_buffers.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_bytes.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_callbacks.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_cast.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_cfuncs.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_errno.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_internals.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_keeprefs.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_libc.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_loading.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_objects.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_parameters.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_prototypes.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_python_api.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_random_things.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_repr.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_returnfuncptrs.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_stringptr.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_strings.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_structures.py
   python/branches/py3k-dtoa/Lib/ctypes/test/test_unicode.py
   python/branches/py3k-dtoa/Lib/curses/wrapper.py
   python/branches/py3k-dtoa/Lib/dbm/__init__.py
   python/branches/py3k-dtoa/Lib/decimal.py
   python/branches/py3k-dtoa/Lib/distutils/__init__.py
   python/branches/py3k-dtoa/Lib/distutils/archive_util.py
   python/branches/py3k-dtoa/Lib/distutils/bcppcompiler.py
   python/branches/py3k-dtoa/Lib/distutils/ccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/cmd.py
   python/branches/py3k-dtoa/Lib/distutils/command/bdist.py
   python/branches/py3k-dtoa/Lib/distutils/command/bdist_dumb.py
   python/branches/py3k-dtoa/Lib/distutils/command/bdist_msi.py
   python/branches/py3k-dtoa/Lib/distutils/command/bdist_rpm.py
   python/branches/py3k-dtoa/Lib/distutils/command/bdist_wininst.py
   python/branches/py3k-dtoa/Lib/distutils/command/build.py
   python/branches/py3k-dtoa/Lib/distutils/command/build_clib.py
   python/branches/py3k-dtoa/Lib/distutils/command/build_ext.py
   python/branches/py3k-dtoa/Lib/distutils/command/build_py.py
   python/branches/py3k-dtoa/Lib/distutils/command/build_scripts.py
   python/branches/py3k-dtoa/Lib/distutils/command/config.py
   python/branches/py3k-dtoa/Lib/distutils/command/install.py
   python/branches/py3k-dtoa/Lib/distutils/command/register.py
   python/branches/py3k-dtoa/Lib/distutils/command/sdist.py
   python/branches/py3k-dtoa/Lib/distutils/command/upload.py
   python/branches/py3k-dtoa/Lib/distutils/config.py
   python/branches/py3k-dtoa/Lib/distutils/core.py
   python/branches/py3k-dtoa/Lib/distutils/cygwinccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/dep_util.py
   python/branches/py3k-dtoa/Lib/distutils/dir_util.py
   python/branches/py3k-dtoa/Lib/distutils/dist.py
   python/branches/py3k-dtoa/Lib/distutils/emxccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/errors.py
   python/branches/py3k-dtoa/Lib/distutils/extension.py
   python/branches/py3k-dtoa/Lib/distutils/fancy_getopt.py
   python/branches/py3k-dtoa/Lib/distutils/file_util.py
   python/branches/py3k-dtoa/Lib/distutils/filelist.py
   python/branches/py3k-dtoa/Lib/distutils/msvc9compiler.py
   python/branches/py3k-dtoa/Lib/distutils/msvccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/sysconfig.py
   python/branches/py3k-dtoa/Lib/distutils/tests/support.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_archive_util.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_dumb.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_rpm.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_wininst.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_build_clib.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_build_ext.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_build_py.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_build_scripts.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_cmd.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_cygwinccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_dist.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_extension.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_file_util.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_filelist.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_install.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_install_lib.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_log.py   (props changed)
   python/branches/py3k-dtoa/Lib/distutils/tests/test_register.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_sdist.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_sysconfig.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_unixccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_upload.py
   python/branches/py3k-dtoa/Lib/distutils/tests/test_util.py
   python/branches/py3k-dtoa/Lib/distutils/text_file.py
   python/branches/py3k-dtoa/Lib/distutils/unixccompiler.py
   python/branches/py3k-dtoa/Lib/distutils/util.py
   python/branches/py3k-dtoa/Lib/doctest.py
   python/branches/py3k-dtoa/Lib/email/base64mime.py
   python/branches/py3k-dtoa/Lib/email/feedparser.py
   python/branches/py3k-dtoa/Lib/email/header.py
   python/branches/py3k-dtoa/Lib/email/message.py
   python/branches/py3k-dtoa/Lib/email/test/test_email.py
   python/branches/py3k-dtoa/Lib/fileinput.py
   python/branches/py3k-dtoa/Lib/fnmatch.py
   python/branches/py3k-dtoa/Lib/functools.py
   python/branches/py3k-dtoa/Lib/getopt.py
   python/branches/py3k-dtoa/Lib/http/client.py
   python/branches/py3k-dtoa/Lib/http/cookiejar.py
   python/branches/py3k-dtoa/Lib/http/cookies.py
   python/branches/py3k-dtoa/Lib/http/server.py
   python/branches/py3k-dtoa/Lib/idlelib/NEWS.txt
   python/branches/py3k-dtoa/Lib/idlelib/PyShell.py
   python/branches/py3k-dtoa/Lib/idlelib/idlever.py
   python/branches/py3k-dtoa/Lib/imaplib.py
   python/branches/py3k-dtoa/Lib/importlib/test/benchmark.py
   python/branches/py3k-dtoa/Lib/json/__init__.py
   python/branches/py3k-dtoa/Lib/json/decoder.py
   python/branches/py3k-dtoa/Lib/json/encoder.py
   python/branches/py3k-dtoa/Lib/json/tests/test_fail.py
   python/branches/py3k-dtoa/Lib/mailbox.py   (props changed)
   python/branches/py3k-dtoa/Lib/multiprocessing/connection.py
   python/branches/py3k-dtoa/Lib/multiprocessing/forking.py
   python/branches/py3k-dtoa/Lib/multiprocessing/heap.py
   python/branches/py3k-dtoa/Lib/multiprocessing/reduction.py
   python/branches/py3k-dtoa/Lib/ntpath.py
   python/branches/py3k-dtoa/Lib/os.py
   python/branches/py3k-dtoa/Lib/pdb.py
   python/branches/py3k-dtoa/Lib/pickle.py
   python/branches/py3k-dtoa/Lib/pickletools.py
   python/branches/py3k-dtoa/Lib/platform.py
   python/branches/py3k-dtoa/Lib/posixpath.py
   python/branches/py3k-dtoa/Lib/profile.py
   python/branches/py3k-dtoa/Lib/pstats.py
   python/branches/py3k-dtoa/Lib/pydoc.py
   python/branches/py3k-dtoa/Lib/pydoc_data/topics.py
   python/branches/py3k-dtoa/Lib/re.py
   python/branches/py3k-dtoa/Lib/site.py
   python/branches/py3k-dtoa/Lib/smtpd.py
   python/branches/py3k-dtoa/Lib/smtplib.py
   python/branches/py3k-dtoa/Lib/sndhdr.py
   python/branches/py3k-dtoa/Lib/socket.py
   python/branches/py3k-dtoa/Lib/string.py
   python/branches/py3k-dtoa/Lib/subprocess.py
   python/branches/py3k-dtoa/Lib/sysconfig.py
   python/branches/py3k-dtoa/Lib/tarfile.py
   python/branches/py3k-dtoa/Lib/test/decimaltestdata/extra.decTest
   python/branches/py3k-dtoa/Lib/test/formatfloat_testcases.txt
   python/branches/py3k-dtoa/Lib/test/math_testcases.txt
   python/branches/py3k-dtoa/Lib/test/pickletester.py
   python/branches/py3k-dtoa/Lib/test/regrtest.py
   python/branches/py3k-dtoa/Lib/test/script_helper.py
   python/branches/py3k-dtoa/Lib/test/sortperf.py
   python/branches/py3k-dtoa/Lib/test/support.py
   python/branches/py3k-dtoa/Lib/test/test_argparse.py
   python/branches/py3k-dtoa/Lib/test/test_array.py
   python/branches/py3k-dtoa/Lib/test/test_ast.py
   python/branches/py3k-dtoa/Lib/test/test_asyncore.py
   python/branches/py3k-dtoa/Lib/test/test_binascii.py
   python/branches/py3k-dtoa/Lib/test/test_binop.py
   python/branches/py3k-dtoa/Lib/test/test_bz2.py
   python/branches/py3k-dtoa/Lib/test/test_calendar.py
   python/branches/py3k-dtoa/Lib/test/test_cfgparser.py
   python/branches/py3k-dtoa/Lib/test/test_cmath.py
   python/branches/py3k-dtoa/Lib/test/test_cmd.py
   python/branches/py3k-dtoa/Lib/test/test_collections.py
   python/branches/py3k-dtoa/Lib/test/test_complex.py
   python/branches/py3k-dtoa/Lib/test/test_curses.py
   python/branches/py3k-dtoa/Lib/test/test_datetime.py
   python/branches/py3k-dtoa/Lib/test/test_decimal.py
   python/branches/py3k-dtoa/Lib/test/test_doctest.py
   python/branches/py3k-dtoa/Lib/test/test_fileinput.py
   python/branches/py3k-dtoa/Lib/test/test_float.py
   python/branches/py3k-dtoa/Lib/test/test_fnmatch.py
   python/branches/py3k-dtoa/Lib/test/test_functools.py
   python/branches/py3k-dtoa/Lib/test/test_gdb.py
   python/branches/py3k-dtoa/Lib/test/test_getopt.py
   python/branches/py3k-dtoa/Lib/test/test_glob.py
   python/branches/py3k-dtoa/Lib/test/test_http_cookiejar.py
   python/branches/py3k-dtoa/Lib/test/test_http_cookies.py
   python/branches/py3k-dtoa/Lib/test/test_httplib.py
   python/branches/py3k-dtoa/Lib/test/test_httpservers.py
   python/branches/py3k-dtoa/Lib/test/test_import.py
   python/branches/py3k-dtoa/Lib/test/test_math.py
   python/branches/py3k-dtoa/Lib/test/test_minidom.py
   python/branches/py3k-dtoa/Lib/test/test_mmap.py
   python/branches/py3k-dtoa/Lib/test/test_ntpath.py
   python/branches/py3k-dtoa/Lib/test/test_numeric_tower.py   (props changed)
   python/branches/py3k-dtoa/Lib/test/test_optparse.py
   python/branches/py3k-dtoa/Lib/test/test_os.py
   python/branches/py3k-dtoa/Lib/test/test_osx_env.py
   python/branches/py3k-dtoa/Lib/test/test_pdb.py
   python/branches/py3k-dtoa/Lib/test/test_platform.py
   python/branches/py3k-dtoa/Lib/test/test_posix.py
   python/branches/py3k-dtoa/Lib/test/test_posixpath.py
   python/branches/py3k-dtoa/Lib/test/test_pow.py
   python/branches/py3k-dtoa/Lib/test/test_pstats.py
   python/branches/py3k-dtoa/Lib/test/test_queue.py
   python/branches/py3k-dtoa/Lib/test/test_re.py
   python/branches/py3k-dtoa/Lib/test/test_robotparser.py
   python/branches/py3k-dtoa/Lib/test/test_sax.py
   python/branches/py3k-dtoa/Lib/test/test_set.py
   python/branches/py3k-dtoa/Lib/test/test_shutil.py
   python/branches/py3k-dtoa/Lib/test/test_signal.py
   python/branches/py3k-dtoa/Lib/test/test_site.py
   python/branches/py3k-dtoa/Lib/test/test_smtplib.py
   python/branches/py3k-dtoa/Lib/test/test_ssl.py
   python/branches/py3k-dtoa/Lib/test/test_struct.py
   python/branches/py3k-dtoa/Lib/test/test_structseq.py
   python/branches/py3k-dtoa/Lib/test/test_subprocess.py
   python/branches/py3k-dtoa/Lib/test/test_sunau.py   (props changed)
   python/branches/py3k-dtoa/Lib/test/test_sundry.py
   python/branches/py3k-dtoa/Lib/test/test_sys.py
   python/branches/py3k-dtoa/Lib/test/test_sysconfig.py
   python/branches/py3k-dtoa/Lib/test/test_tarfile.py
   python/branches/py3k-dtoa/Lib/test/test_tcl.py
   python/branches/py3k-dtoa/Lib/test/test_threaded_import.py
   python/branches/py3k-dtoa/Lib/test/test_threading.py
   python/branches/py3k-dtoa/Lib/test/test_threading_local.py
   python/branches/py3k-dtoa/Lib/test/test_tokenize.py
   python/branches/py3k-dtoa/Lib/test/test_unicode.py
   python/branches/py3k-dtoa/Lib/test/test_unicodedata.py
   python/branches/py3k-dtoa/Lib/test/test_unpack.py
   python/branches/py3k-dtoa/Lib/test/test_urllib.py
   python/branches/py3k-dtoa/Lib/test/test_urllib2.py
   python/branches/py3k-dtoa/Lib/test/test_urlparse.py
   python/branches/py3k-dtoa/Lib/test/test_xml_etree.py
   python/branches/py3k-dtoa/Lib/threading.py
   python/branches/py3k-dtoa/Lib/timeit.py
   python/branches/py3k-dtoa/Lib/trace.py
   python/branches/py3k-dtoa/Lib/unittest/case.py
   python/branches/py3k-dtoa/Lib/unittest/test/test_case.py
   python/branches/py3k-dtoa/Lib/urllib/parse.py
   python/branches/py3k-dtoa/Lib/urllib/request.py
   python/branches/py3k-dtoa/Lib/urllib/robotparser.py
   python/branches/py3k-dtoa/Lib/xml/dom/expatbuilder.py
   python/branches/py3k-dtoa/Lib/xml/dom/minidom.py
   python/branches/py3k-dtoa/Lib/xmlrpc/client.py
   python/branches/py3k-dtoa/Makefile.pre.in
   python/branches/py3k-dtoa/Misc/ACKS
   python/branches/py3k-dtoa/Misc/NEWS
   python/branches/py3k-dtoa/Misc/RPM/python-3.2.spec
   python/branches/py3k-dtoa/Misc/developers.txt
   python/branches/py3k-dtoa/Misc/maintainers.rst
   python/branches/py3k-dtoa/Misc/python-wing.wpr
   python/branches/py3k-dtoa/Modules/Setup.dist
   python/branches/py3k-dtoa/Modules/_ctypes/_ctypes.c
   python/branches/py3k-dtoa/Modules/_ctypes/callproc.c
   python/branches/py3k-dtoa/Modules/_ctypes/cfield.c
   python/branches/py3k-dtoa/Modules/_ctypes/ctypes.h
   python/branches/py3k-dtoa/Modules/_cursesmodule.c
   python/branches/py3k-dtoa/Modules/_io/_iomodule.c
   python/branches/py3k-dtoa/Modules/_io/bufferedio.c
   python/branches/py3k-dtoa/Modules/_json.c
   python/branches/py3k-dtoa/Modules/_pickle.c
   python/branches/py3k-dtoa/Modules/_ssl.c
   python/branches/py3k-dtoa/Modules/_struct.c
   python/branches/py3k-dtoa/Modules/_time.c   (props changed)
   python/branches/py3k-dtoa/Modules/_time.h   (props changed)
   python/branches/py3k-dtoa/Modules/arraymodule.c
   python/branches/py3k-dtoa/Modules/binascii.c
   python/branches/py3k-dtoa/Modules/bz2module.c
   python/branches/py3k-dtoa/Modules/cmathmodule.c
   python/branches/py3k-dtoa/Modules/getpath.c
   python/branches/py3k-dtoa/Modules/main.c
   python/branches/py3k-dtoa/Modules/makesetup
   python/branches/py3k-dtoa/Modules/mathmodule.c
   python/branches/py3k-dtoa/Modules/mmapmodule.c
   python/branches/py3k-dtoa/Modules/posixmodule.c
   python/branches/py3k-dtoa/Modules/readline.c
   python/branches/py3k-dtoa/Modules/selectmodule.c
   python/branches/py3k-dtoa/Modules/sha1module.c
   python/branches/py3k-dtoa/Modules/signalmodule.c
   python/branches/py3k-dtoa/Modules/timemodule.c
   python/branches/py3k-dtoa/Modules/zipimport.c
   python/branches/py3k-dtoa/Modules/zlib/ChangeLog
   python/branches/py3k-dtoa/Modules/zlib/FAQ
   python/branches/py3k-dtoa/Modules/zlib/INDEX
   python/branches/py3k-dtoa/Modules/zlib/Makefile
   python/branches/py3k-dtoa/Modules/zlib/Makefile.in
   python/branches/py3k-dtoa/Modules/zlib/README
   python/branches/py3k-dtoa/Modules/zlib/adler32.c
   python/branches/py3k-dtoa/Modules/zlib/compress.c
   python/branches/py3k-dtoa/Modules/zlib/configure
   python/branches/py3k-dtoa/Modules/zlib/crc32.c
   python/branches/py3k-dtoa/Modules/zlib/deflate.c
   python/branches/py3k-dtoa/Modules/zlib/deflate.h
   python/branches/py3k-dtoa/Modules/zlib/example.c
   python/branches/py3k-dtoa/Modules/zlib/infback.c
   python/branches/py3k-dtoa/Modules/zlib/inffast.c
   python/branches/py3k-dtoa/Modules/zlib/inffast.h
   python/branches/py3k-dtoa/Modules/zlib/inflate.c
   python/branches/py3k-dtoa/Modules/zlib/inflate.h
   python/branches/py3k-dtoa/Modules/zlib/inftrees.c
   python/branches/py3k-dtoa/Modules/zlib/inftrees.h
   python/branches/py3k-dtoa/Modules/zlib/make_vms.com
   python/branches/py3k-dtoa/Modules/zlib/minigzip.c
   python/branches/py3k-dtoa/Modules/zlib/trees.c
   python/branches/py3k-dtoa/Modules/zlib/trees.h
   python/branches/py3k-dtoa/Modules/zlib/uncompr.c
   python/branches/py3k-dtoa/Modules/zlib/zconf.h
   python/branches/py3k-dtoa/Modules/zlib/zlib.3
   python/branches/py3k-dtoa/Modules/zlib/zlib.h
   python/branches/py3k-dtoa/Modules/zlib/zutil.c
   python/branches/py3k-dtoa/Modules/zlib/zutil.h
   python/branches/py3k-dtoa/Objects/bytearrayobject.c
   python/branches/py3k-dtoa/Objects/complexobject.c
   python/branches/py3k-dtoa/Objects/floatobject.c
   python/branches/py3k-dtoa/Objects/iterobject.c
   python/branches/py3k-dtoa/Objects/memoryobject.c
   python/branches/py3k-dtoa/Objects/object.c
   python/branches/py3k-dtoa/Objects/setobject.c
   python/branches/py3k-dtoa/Objects/sliceobject.c
   python/branches/py3k-dtoa/Objects/stringlib/formatter.h
   python/branches/py3k-dtoa/Objects/structseq.c
   python/branches/py3k-dtoa/Objects/unicodeobject.c
   python/branches/py3k-dtoa/PC/VS8.0/pythoncore.vcproj
   python/branches/py3k-dtoa/PC/_subprocess.c
   python/branches/py3k-dtoa/PC/config.c
   python/branches/py3k-dtoa/PC/python_nt.rc
   python/branches/py3k-dtoa/PCbuild/build_ssl.py
   python/branches/py3k-dtoa/PCbuild/pyproject.vsprops
   python/branches/py3k-dtoa/PCbuild/pythoncore.vcproj
   python/branches/py3k-dtoa/PCbuild/readme.txt
   python/branches/py3k-dtoa/Python/ceval.c
   python/branches/py3k-dtoa/Python/getargs.c
   python/branches/py3k-dtoa/Python/getcopyright.c
   python/branches/py3k-dtoa/Python/getversion.c
   python/branches/py3k-dtoa/Python/graminit.c
   python/branches/py3k-dtoa/Python/pythonrun.c
   python/branches/py3k-dtoa/README
   python/branches/py3k-dtoa/Tools/README
   python/branches/py3k-dtoa/Tools/buildbot/external-common.bat
   python/branches/py3k-dtoa/Tools/framer/framer/bases.py
   python/branches/py3k-dtoa/Tools/framer/framer/template.py
   python/branches/py3k-dtoa/Tools/freeze/freeze.py
   python/branches/py3k-dtoa/Tools/freeze/makeconfig.py
   python/branches/py3k-dtoa/Tools/gdb/libpython.py
   python/branches/py3k-dtoa/Tools/i18n/msgfmt.py
   python/branches/py3k-dtoa/Tools/msi/msi.py
   python/branches/py3k-dtoa/Tools/msi/msilib.py
   python/branches/py3k-dtoa/Tools/msi/uuids.py
   python/branches/py3k-dtoa/Tools/pynche/ChipViewer.py
   python/branches/py3k-dtoa/Tools/pynche/DetailsViewer.py
   python/branches/py3k-dtoa/Tools/pynche/ListViewer.py
   python/branches/py3k-dtoa/Tools/pynche/PyncheWidget.py
   python/branches/py3k-dtoa/Tools/pynche/StripViewer.py
   python/branches/py3k-dtoa/Tools/pynche/Switchboard.py
   python/branches/py3k-dtoa/Tools/pynche/TextViewer.py
   python/branches/py3k-dtoa/Tools/pynche/TypeinViewer.py
   python/branches/py3k-dtoa/Tools/scripts/README
   python/branches/py3k-dtoa/Tools/scripts/byext.py
   python/branches/py3k-dtoa/Tools/scripts/serve.py
   python/branches/py3k-dtoa/Tools/scripts/win_add2path.py
   python/branches/py3k-dtoa/configure
   python/branches/py3k-dtoa/configure.in
   python/branches/py3k-dtoa/setup.py

Modified: python/branches/py3k-dtoa/Demo/README
==============================================================================
--- python/branches/py3k-dtoa/Demo/README	(original)
+++ python/branches/py3k-dtoa/Demo/README	Sun Aug  8 12:41:24 2010
@@ -13,49 +13,50 @@
 in case I change my mind about them.
 
 
-cgi             CGI examples (see also ../Tools/faqwiz/.)
+cgi             CGI examples.
 
-classes		Some examples of how to use classes.
+classes         Some examples of how to use classes.
 
-comparisons	A set of responses to a really old language-comparison
-		challenge.
+comparisons     A set of responses to a really old language-comparison
+                challenge.
 
-curses		A set of curses demos.
+curses          A set of curses demos.
 
-embed		An example of embedding Python in another application
-		(see also pysvr).
+distutils       Test for using transparent 2to3 conversion in distutils.
 
-imputil		Demonstration subclasses of imputil.Importer.
+embed           An example of embedding Python in another application
+                (see also pysvr).
 
-md5test		Test program for the optional md5 module.
+imputil         Demonstration subclasses of imputil.Importer.
 
-metaclasses	The code from the 1.5 metaclasses paper on the web.
+md5test         Test program for the optional md5 module.
 
-parser		Example using the parser module.
+newmetaclasses  Demonstration of metaclasses.
 
-pdist		Old, unfinished code messing with CVS, RCS and remote
-		files.
+parser          Example using the parser module.
 
-pysvr		An example of embedding Python in a threaded
-		application.
+pysvr           An example of embedding Python in a threaded
+                application.
 
-rpc		A set of classes for building clients and servers for
-		Sun RPC.
+rpc             A set of classes for building clients and servers for
+                Sun RPC.
 
-scripts		Some useful Python scripts that I put in my bin
-		directory.  No optional built-in modules needed.
+scripts         Some useful Python scripts that I put in my bin
+                directory.  No optional built-in modules needed.
 
-sockets		Examples for the new built-in module 'socket'.
+sockets         Examples for the new built-in module 'socket'.
 
-threads		Demos that use the 'thread' module.  (Currently these
-		only run on SGIs, but this may change in the future.)
+threads         Demos that use the 'thread' module.  (Currently these
+                only run on SGIs, but this may change in the future.)
 
-tix		Demos using the Tix widget set addition to Tkinter.
+tix             Demos using the Tix widget set addition to Tkinter.
 
-tkinter		Demos using the Tk interface (including Matt Conway's
-		excellent set of demos).
+tkinter         Demos using the Tk interface (including Matt Conway's
+                excellent set of demos).
 
-xml		Some XML demos.
+turtle          Demos for the "turtle" module.
 
-zlib		Some demos for the zlib module (see also the standard
-		library module gzip.py).
+xml             Some XML demos.
+
+zlib            Some demos for the zlib module (see also the standard
+                library module gzip.py).

Modified: python/branches/py3k-dtoa/Demo/embed/Makefile
==============================================================================
--- python/branches/py3k-dtoa/Demo/embed/Makefile	(original)
+++ python/branches/py3k-dtoa/Demo/embed/Makefile	Sun Aug  8 12:41:24 2010
@@ -22,7 +22,7 @@
 LIBPYTHON=	$(blddir)/libpython$(VERSION).a
 
 # XXX edit LIBS (in particular) to match $(blddir)/Makefile
-LIBS=		-lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil
+LIBS=		-lnsl -ldl -lreadline -lieee -lpthread -lutil
 LDFLAGS=	-Xlinker -export-dynamic
 SYSLIBS=	-lm
 MODLIBS=	

Modified: python/branches/py3k-dtoa/Demo/embed/demo.c
==============================================================================
--- python/branches/py3k-dtoa/Demo/embed/demo.c	(original)
+++ python/branches/py3k-dtoa/Demo/embed/demo.c	Sun Aug  8 12:41:24 2010
@@ -22,7 +22,7 @@
     /* Define sys.argv.  It is up to the application if you
        want this; you can also leave it undefined (since the Python
        code is generally not a main program it has no business
-       touching sys.argv...) 
+       touching sys.argv...)
 
        If the third argument is true, sys.path is modified to include
        either the directory containing the script named by argv[0], or
@@ -32,7 +32,7 @@
        directory (say, a file named os.py) that your application would
        then import and run.
     */
-    PySys_SetArgvEx(argc, argv, 0);
+    PySys_SetArgvEx(2, args, 0);
 
     /* Do some application specific code */
     printf("Hello, brave new world\n\n");

Modified: python/branches/py3k-dtoa/Demo/embed/loop.c
==============================================================================
--- python/branches/py3k-dtoa/Demo/embed/loop.c	(original)
+++ python/branches/py3k-dtoa/Demo/embed/loop.c	Sun Aug  8 12:41:24 2010
@@ -19,7 +19,7 @@
         count = atoi(argv[2]);
     }
 
-    Py_SetProgramName(argv[0]);
+    Py_SetProgramName(L"loop");
 
     /* uncomment this if you don't want to load site.py */
     /* Py_NoSiteFlag = 1; */

Modified: python/branches/py3k-dtoa/Demo/scripts/README
==============================================================================
--- python/branches/py3k-dtoa/Demo/scripts/README	(original)
+++ python/branches/py3k-dtoa/Demo/scripts/README	Sun Aug  8 12:41:24 2010
@@ -2,21 +2,21 @@
 
 See also the Tools/scripts directory!
 
-beer.py			Print the classic 'bottles of beer' list
-eqfix.py		Fix .py files to use the correct equality test operator
-fact.py			Factorize numbers
-find-uname.py		Search for Unicode characters using regexps
-from.py			Summarize mailbox
-lpwatch.py		Watch BSD line printer queues
-makedir.py		Like mkdir -p
-markov.py		Markov chain simulation of words or characters
-mboxconvert.py		Convert MH or MMDF mailboxes to unix mailbox format
-morse.py		Produce morse code (as an AIFF file)
-newslist.py		List all newsgroups on a NNTP server as HTML pages
-pi.py			Print all digits of pi -- given enough time and memory
-pp.py			Emulate some Perl command line options
-primes.py		Print prime numbers
-queens.py		Dijkstra's solution to Wirth's "N Queens problem"
-script.py		Equivalent to BSD script(1) -- by Steen Lumholt
-unbirthday.py		Print unbirthday count
-update.py		Update a bunch of files according to a script.
+beer.py                 Print the classic 'bottles of beer' list
+eqfix.py                Fix .py files to use the correct equality test operator
+fact.py                 Factorize numbers
+find-uname.py           Search for Unicode characters using regexps
+from.py                 Summarize mailbox
+lpwatch.py              Watch BSD line printer queues
+makedir.py              Like mkdir -p
+markov.py               Markov chain simulation of words or characters
+mboxconvert.py          Convert MH or MMDF mailboxes to unix mailbox format
+morse.py                Produce morse code (as an AIFF file)
+newslist.py             List all newsgroups on a NNTP server as HTML pages
+pi.py                   Print all digits of pi -- given enough time and memory
+pp.py                   Emulate some Perl command line options
+primes.py               Print prime numbers
+queens.py               Dijkstra's solution to Wirth's "N Queens problem"
+script.py               Equivalent to BSD script(1) -- by Steen Lumholt
+unbirthday.py           Print unbirthday count
+update.py               Update a bunch of files according to a script

Deleted: python/branches/py3k-dtoa/Demo/scripts/toaiff.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/scripts/toaiff.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,107 +0,0 @@
-"""Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
-
-Input may be compressed.
-Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others.
-An exception is raised if the file is not of a recognized type.
-Returned filename is either the input filename or a temporary filename;
-in the latter case the caller must ensure that it is removed.
-Other temporary files used are removed by the function.
-"""
-
-import os
-import tempfile
-import pipes
-import sndhdr
-
-__all__ = ["error", "toaiff"]
-
-table = {}
-
-t = pipes.Template()
-t.append('sox -t au - -t aiff -r 8000 -', '--')
-table['au'] = t
-
-# XXX The following is actually sub-optimal.
-# XXX The HCOM sampling rate can be 22k, 22k/2, 22k/3 or 22k/4.
-# XXX We must force the output sampling rate else the SGI won't play
-# XXX files sampled at 5.5k or 7.333k; however this means that files
-# XXX sampled at 11k are unnecessarily expanded.
-# XXX Similar comments apply to some other file types.
-t = pipes.Template()
-t.append('sox -t hcom - -t aiff -r 22050 -', '--')
-table['hcom'] = t
-
-t = pipes.Template()
-t.append('sox -t voc - -t aiff -r 11025 -', '--')
-table['voc'] = t
-
-t = pipes.Template()
-t.append('sox -t wav - -t aiff -', '--')
-table['wav'] = t
-
-t = pipes.Template()
-t.append('sox -t 8svx - -t aiff -r 16000 -', '--')
-table['8svx'] = t
-
-t = pipes.Template()
-t.append('sox -t sndt - -t aiff -r 16000 -', '--')
-table['sndt'] = t
-
-t = pipes.Template()
-t.append('sox -t sndr - -t aiff -r 16000 -', '--')
-table['sndr'] = t
-
-uncompress = pipes.Template()
-uncompress.append('uncompress', '--')
-
-
-class error(Exception):
-    pass
-
-def toaiff(filename):
-    temps = []
-    ret = None
-    try:
-        ret = _toaiff(filename, temps)
-    finally:
-        for temp in temps[:]:
-            if temp != ret:
-                try:
-                    os.unlink(temp)
-                except os.error:
-                    pass
-                temps.remove(temp)
-    return ret
-
-def _toaiff(filename, temps):
-    if filename[-2:] == '.Z':
-        (fd, fname) = tempfile.mkstemp()
-        os.close(fd)
-        temps.append(fname)
-        sts = uncompress.copy(filename, fname)
-        if sts:
-            raise error(filename + ': uncompress failed')
-    else:
-        fname = filename
-    try:
-        ftype = sndhdr.whathdr(fname)
-        if ftype:
-            ftype = ftype[0] # All we're interested in
-    except IOError as msg:
-        if type(msg) == type(()) and len(msg) == 2 and \
-                type(msg.args[0]) == type(0) and type(msg.args[1]) == type(''):
-            msg = msg.args[1]
-        if type(msg) != type(''):
-            msg = repr(msg)
-        raise error(filename + ': ' + msg)
-    if ftype == 'aiff':
-        return fname
-    if ftype is None or not ftype in table:
-        raise error('%s: unsupported audio file type %r' % (filename, ftype))
-    (fd, temp) = tempfile.mkstemp()
-    os.close(fd)
-    temps.append(temp)
-    sts = table[ftype].copy(fname, temp)
-    if sts:
-        raise error(filename + ': conversion to aiff failed')
-    return temp

Modified: python/branches/py3k-dtoa/Demo/tkinter/guido/AttrDialog.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/tkinter/guido/AttrDialog.py	(original)
+++ python/branches/py3k-dtoa/Demo/tkinter/guido/AttrDialog.py	Sun Aug  8 12:41:24 2010
@@ -120,7 +120,7 @@
                 cl = self.classes[c]
             except KeyError:
                 cl = 'unknown'
-            if type(cl) == TupleType:
+            if type(cl) == tuple:
                 cl = self.enumoption
             elif cl == 'boolean':
                 cl = self.booleanoption

Modified: python/branches/py3k-dtoa/Demo/tkinter/guido/ManPage.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/tkinter/guido/ManPage.py	(original)
+++ python/branches/py3k-dtoa/Demo/tkinter/guido/ManPage.py	Sun Aug  8 12:41:24 2010
@@ -107,13 +107,13 @@
             # Save this line -- we need one line read-ahead
             self.buffer = nextline
             return
-        if emptyprog.match(self.buffer) >= 0:
+        if emptyprog.match(self.buffer):
             # Buffered line was empty -- set a flag
             self.empty = 1
             self.buffer = nextline
             return
         textline = self.buffer
-        if ulprog.match(nextline) >= 0:
+        if ulprog.match(nextline):
             # Next line is properties for buffered line
             propline = nextline
             self.buffer = None
@@ -127,7 +127,7 @@
             self.ok = 1
             self.empty = 0
             return
-        if footerprog.match(textline) >= 0:
+        if footerprog.match(textline):
             # Footer -- start skipping until next non-blank line
             self.ok = 0
             self.empty = 0
@@ -190,7 +190,7 @@
     import os
     import sys
     # XXX This directory may be different on your system
-    MANDIR = '/usr/local/man/mann'
+    MANDIR = ''
     DEFAULTPAGE = 'Tcl'
     formatted = 0
     if sys.argv[1:] and sys.argv[1] == '-f':

Modified: python/branches/py3k-dtoa/Demo/tkinter/guido/brownian2.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/tkinter/guido/brownian2.py	(original)
+++ python/branches/py3k-dtoa/Demo/tkinter/guido/brownian2.py	Sun Aug  8 12:41:24 2010
@@ -32,7 +32,7 @@
             yield None
 
 def move(particle): # move the particle at random time
-    particle.next()
+    next(particle)
     dt = random.expovariate(LAMBDA)
     root.after(int(dt*1000), move, particle)
 

Modified: python/branches/py3k-dtoa/Demo/tkinter/guido/kill.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/tkinter/guido/kill.py	(original)
+++ python/branches/py3k-dtoa/Demo/tkinter/guido/kill.py	Sun Aug  8 12:41:24 2010
@@ -2,8 +2,6 @@
 # Tkinter interface to Linux `kill' command.
 
 from tkinter import *
-from string import splitfields
-from string import split
 import subprocess
 import os
 
@@ -26,13 +24,13 @@
                    ('Hex', '-X', 0)]
     def kill(self, selected):
         c = self.format_list[self.format.get()][2]
-        pid = split(selected)[c]
+        pid = selected.split()[c]
         os.system('kill -9 ' + pid)
         self.do_update()
     def do_update(self):
         name, option, column = self.format_list[self.format.get()]
         s = subprocess.getoutput('ps -w ' + option)
-        list = splitfields(s, '\n')
+        list = s.split('\n')
         self.header.set(list[0])
         del list[0]
         y = self.frame.vscroll.get()[0]

Modified: python/branches/py3k-dtoa/Demo/zlib/minigzip.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/zlib/minigzip.py	(original)
+++ python/branches/py3k-dtoa/Demo/zlib/minigzip.py	Sun Aug  8 12:41:24 2010
@@ -10,10 +10,10 @@
 FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
 
 def write32(output, value):
-    output.write(chr(value & 255)) ; value=value // 256
-    output.write(chr(value & 255)) ; value=value // 256
-    output.write(chr(value & 255)) ; value=value // 256
-    output.write(chr(value & 255))
+    output.write(bytes([value & 255])) ; value=value // 256
+    output.write(bytes([value & 255])) ; value=value // 256
+    output.write(bytes([value & 255])) ; value=value // 256
+    output.write(bytes([value & 255]))
 
 def read32(input):
     v = ord(input.read(1))
@@ -22,23 +22,24 @@
     v += (ord(input.read(1)) << 24)
     return v
 
-def compress (filename, input, output):
-    output.write('\037\213\010')        # Write the header, ...
-    output.write(chr(FNAME))            # ... flag byte ...
+def compress(filename, input, output):
+    output.write(b'\037\213\010')        # Write the header, ...
+    output.write(bytes([FNAME]))         # ... flag byte ...
 
-    statval = os.stat(filename)           # ... modification time ...
+    statval = os.stat(filename)          # ... modification time ...
     mtime = statval[8]
     write32(output, mtime)
-    output.write('\002')                # ... slowest compression alg. ...
-    output.write('\377')                # ... OS (=unknown) ...
-    output.write(filename+'\000')       # ... original filename ...
+    output.write(b'\002')                # ... slowest compression alg. ...
+    output.write(b'\377')                # ... OS (=unknown) ...
+    bfilename = filename.encode(sys.getfilesystemencoding())
+    output.write(bfilename + b'\000')    # ... original filename ...
 
-    crcval = zlib.crc32("")
+    crcval = zlib.crc32(b'')
     compobj = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
                              zlib.DEF_MEM_LEVEL, 0)
     while True:
         data = input.read(1024)
-        if data == "":
+        if data == b'':
             break
         crcval = zlib.crc32(data, crcval)
         output.write(compobj.compress(data))
@@ -46,9 +47,9 @@
     write32(output, crcval)             # ... the CRC ...
     write32(output, statval[6])         # and the file size.
 
-def decompress (input, output):
+def decompress(input, output):
     magic = input.read(2)
-    if magic != '\037\213':
+    if magic != b'\037\213':
         print('Not a gzipped file')
         sys.exit(0)
     if ord(input.read(1)) != 8:
@@ -66,21 +67,21 @@
         # Read and discard a null-terminated string containing the filename
         while True:
             s = input.read(1)
-            if s == '\0': break
+            if s == b'\0': break
     if flag & FCOMMENT:
         # Read and discard a null-terminated string containing a comment
         while True:
-            s=input.read(1)
-            if s=='\0': break
+            s = input.read(1)
+            if s == b'\0': break
     if flag & FHCRC:
         input.read(2)                   # Read & discard the 16-bit header CRC
 
     decompobj = zlib.decompressobj(-zlib.MAX_WBITS)
-    crcval = zlib.crc32("")
+    crcval = zlib.crc32(b'')
     length = 0
     while True:
-        data=input.read(1024)
-        if data == "":
+        data = input.read(1024)
+        if data == b"":
             break
         decompdata = decompobj.decompress(data)
         output.write(decompdata)

Modified: python/branches/py3k-dtoa/Demo/zlib/zlibdemo.py
==============================================================================
--- python/branches/py3k-dtoa/Demo/zlib/zlibdemo.py	(original)
+++ python/branches/py3k-dtoa/Demo/zlib/zlibdemo.py	Sun Aug  8 12:41:24 2010
@@ -13,9 +13,8 @@
         filename = sys.argv[0]
     print('Reading', filename)
 
-    f = open(filename, 'rb')           # Get the data to compress
-    s = f.read()
-    f.close()
+    with open(filename, 'rb') as f:           # Get the data to compress
+        s = f.read()
 
     # First, we'll compress the string in one step
     comptext = zlib.compress(s, 1)
@@ -30,15 +29,15 @@
     chunk = 256
     compressor = zlib.compressobj(9)
     decompressor = zlib.decompressobj()
-    comptext = decomp = ''
+    comptext = decomp = b''
     for i in range(0, len(s), chunk):
-        comptext = comptext+compressor.compress(s[i:i+chunk])
+        comptext += compressor.compress(s[i:i+chunk])
     # Don't forget to call flush()!!
-    comptext = comptext + compressor.flush()
+    comptext += compressor.flush()
 
     for i in range(0, len(comptext), chunk):
-        decomp = decomp + decompressor.decompress(comptext[i:i+chunk])
-    decomp=decomp+decompressor.flush()
+        decomp += decompressor.decompress(comptext[i:i+chunk])
+    decomp += decompressor.flush()
 
     print('Progressive compression (level 9):')
     print('    Original:', len(s), 'Compressed:', len(comptext), end=' ')

Modified: python/branches/py3k-dtoa/Doc/Makefile
==============================================================================
--- python/branches/py3k-dtoa/Doc/Makefile	(original)
+++ python/branches/py3k-dtoa/Doc/Makefile	Sun Aug  8 12:41:24 2010
@@ -40,7 +40,7 @@
 checkout:
 	@if [ ! -d tools/sphinx ]; then \
 	  echo "Checking out Sphinx..."; \
-	  svn checkout $(SVNROOT)/external/Sphinx-0.6.5/sphinx tools/sphinx; \
+	  svn checkout $(SVNROOT)/external/Sphinx-1.0.1/sphinx tools/sphinx; \
 	fi
 	@if [ ! -d tools/docutils ]; then \
 	  echo "Checking out Docutils..."; \
@@ -120,7 +120,7 @@
 	-rm -rf tools/docutils
 
 dist:
-	-rm -rf dist
+	rm -rf dist
 	mkdir -p dist
 
 	# archive the HTML
@@ -142,15 +142,17 @@
 	rm dist/python-$(DISTVERSION)-docs-text.tar
 
 	# archive the A4 latex
-	-rm -r build/latex
+	rm -rf build/latex
 	make latex PAPER=a4
+	-sed -i 's/makeindex/makeindex -q/' build/latex/Makefile
 	(cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2)
 	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-a4.zip
 	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-a4.tar.bz2
 
 	# archive the letter latex
-	rm -r build/latex
+	rm -rf build/latex
 	make latex PAPER=letter
+	-sed -i 's/makeindex/makeindex -q/' build/latex/Makefile
 	(cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2)
 	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-letter.zip
 	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-letter.tar.bz2

Modified: python/branches/py3k-dtoa/Doc/README.txt
==============================================================================
--- python/branches/py3k-dtoa/Doc/README.txt	(original)
+++ python/branches/py3k-dtoa/Doc/README.txt	Sun Aug  8 12:41:24 2010
@@ -78,7 +78,7 @@
 
 You'll need to install the Sphinx package, either by checking it out via ::
 
-   svn co http://svn.python.org/projects/external/Sphinx-0.6.5/sphinx tools/sphinx
+   svn co http://svn.python.org/projects/external/Sphinx-1.0.1/sphinx tools/sphinx
 
 or by installing it from PyPI.
 
@@ -132,7 +132,7 @@
 as long as you don't change or remove the copyright notice:
 
 ----------------------------------------------------------------------
-Copyright (c) 2000-2008 Python Software Foundation.
+Copyright (c) 2000-2010 Python Software Foundation.
 All rights reserved.
 
 Copyright (c) 2000 BeOpen.com.

Modified: python/branches/py3k-dtoa/Doc/c-api/init.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/c-api/init.rst	(original)
+++ python/branches/py3k-dtoa/Doc/c-api/init.rst	Sun Aug  8 12:41:24 2010
@@ -959,7 +959,7 @@
 .. cvar:: int PyTrace_C_EXCEPTION
 
    The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C
-   function has thrown an exception.
+   function has raised an exception.
 
 
 .. cvar:: int PyTrace_C_RETURN

Modified: python/branches/py3k-dtoa/Doc/c-api/unicode.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/c-api/unicode.rst	(original)
+++ python/branches/py3k-dtoa/Doc/c-api/unicode.rst	Sun Aug  8 12:41:24 2010
@@ -376,7 +376,7 @@
 :cdata:`Py_FileSystemEncoding` should be used as the encoding, and
 ``"surrogateescape"`` should be used as the error handler (:pep:`383`). To
 encode file names during argument parsing, the ``"O&"`` converter should be
-used, passsing :func:PyUnicode_FSConverter as the conversion function:
+used, passsing :func:`PyUnicode_FSConverter` as the conversion function:
 
 .. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result)
 
@@ -670,6 +670,38 @@
    Return *NULL* if an exception was raised by the codec.
 
 
+UTF-7 Codecs
+""""""""""""
+
+These are the UTF-7 codec APIs:
+
+
+.. cfunction:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors)
+
+   Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string
+   *s*.  Return *NULL* if an exception was raised by the codec.
+
+
+.. cfunction:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
+
+   If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF7`.  If
+   *consumed* is not *NULL*, trailing incomplete UTF-7 base-64 sections will not
+   be treated as an error.  Those bytes will not be decoded and the number of
+   bytes that have been decoded will be stored in *consumed*.
+
+
+.. cfunction:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors)
+
+   Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-7 and
+   return a Python bytes object.  Return *NULL* if an exception was raised by
+   the codec.
+
+   If *base64SetO* is nonzero, "Set O" (punctuation that has no otherwise
+   special meaning) will be encoded in base-64.  If *base64WhiteSpace* is
+   nonzero, whitespace will be encoded in base-64.  Both are set to zero for the
+   Python "utf-7" codec.
+
+
 Unicode-Escape Codecs
 """""""""""""""""""""
 

Modified: python/branches/py3k-dtoa/Doc/c-api/weakref.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/c-api/weakref.rst	(original)
+++ python/branches/py3k-dtoa/Doc/c-api/weakref.rst	Sun Aug  8 12:41:24 2010
@@ -53,7 +53,14 @@
 .. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref)
 
    Return the referenced object from a weak reference, *ref*.  If the referent is
-   no longer live, returns ``None``.
+   no longer live, returns :const:`Py_None`.
+
+   .. warning::
+
+      This function returns a **borrowed reference** to the referenced object.
+      This means that you should always call :cfunc:`Py_INCREF` on the object
+      except if you know that it cannot be destroyed while you are still
+      using it.
 
 
 .. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref)

Modified: python/branches/py3k-dtoa/Doc/conf.py
==============================================================================
--- python/branches/py3k-dtoa/Doc/conf.py	(original)
+++ python/branches/py3k-dtoa/Doc/conf.py	Sun Aug  8 12:41:24 2010
@@ -66,6 +66,9 @@
 # Options for HTML output
 # -----------------------
 
+html_theme = 'default'
+html_theme_options = {'collapsiblesidebar': True}
+
 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
 # using the given strftime format.
 html_last_updated_fmt = '%b %d, %Y'
@@ -152,7 +155,7 @@
 latex_appendices = ['glossary', 'about', 'license', 'copyright']
 
 # Get LaTeX to handle Unicode correctly
-latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}'}
+latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''}
 
 # Options for the coverage checker
 # --------------------------------

Modified: python/branches/py3k-dtoa/Doc/distutils/apiref.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/apiref.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/apiref.rst	Sun Aug  8 12:41:24 2010
@@ -995,7 +995,7 @@
    errors are ignored (apart from being reported to ``sys.stdout`` if *verbose* is
    true).
 
-**\*\*** Some of this could be replaced with the shutil module? **\*\***
+.. XXX Some of this could be replaced with the shutil module?
 
 
 :mod:`distutils.file_util` --- Single file operations
@@ -1311,9 +1311,7 @@
   the "negative alias" of :option:`--verbose`, then :option:`--quiet` on the
   command line sets *verbose* to false.
 
-**\*\*** Should be replaced with :mod:`optik` (which is also now known as
-:mod:`optparse` in Python 2.3 and later). **\*\***
-
+.. XXX Should be replaced with optparse
 
 .. function:: fancy_getopt(options, negative_opt, object, args)
 
@@ -1944,6 +1942,19 @@
 
 .. % todo
 
+:mod:`distutils.command.check` --- Check the meta-data of a package
+===================================================================
+
+.. module:: distutils.command.check
+   :synopsis: Check the metadata of a package
+
+
+The ``check`` command performs some tests on the meta-data of a package.
+For example, it verifies that all required meta-data are provided as
+the arguments passed to the :func:`setup` function.
+
+.. % todo
+
 
 Creating a new Distutils command
 ================================

Modified: python/branches/py3k-dtoa/Doc/distutils/builtdist.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/builtdist.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/builtdist.rst	Sun Aug  8 12:41:24 2010
@@ -141,13 +141,13 @@
 commands.
 
 
-.. _creating-dumb:
+.. .. _creating-dumb:
 
-Creating dumb built distributions
-=================================
+.. Creating dumb built distributions
+.. =================================
 
-**\*\*** Need to document absolute vs. prefix-relative packages here, but first
-I have to implement it! **\*\***
+.. XXX Need to document absolute vs. prefix-relative packages here, but first
+   I have to implement it!
 
 
 .. _creating-rpms:
@@ -176,7 +176,7 @@
 explicitly specify multiple :command:`bdist_\*` commands and their options::
 
    python setup.py bdist_rpm --packager="John Doe <jdoe at example.org>" \
-                   bdist_wininst --target_version="2.0"
+                   bdist_wininst --target-version="2.0"
 
 Creating RPM packages is driven by a :file:`.spec` file, much as using the
 Distutils is driven by the setup script.  To make your life easier, the
@@ -241,8 +241,7 @@
 configuration file, :file:`setup.cfg`\ ---see section :ref:`setup-config`.  If
 you distribute or package many Python module distributions, you might want to
 put options that apply to all of them in your personal Distutils configuration
-file (:file:`~/.pydistutils.cfg`).  If you want to temporarily disable
-this file, you can pass the --no-user-cfg option to setup.py.
+file (:file:`~/.pydistutils.cfg`).
 
 There are three steps to building a binary RPM package, all of which are
 handled automatically by the Distutils:

Modified: python/branches/py3k-dtoa/Doc/distutils/commandref.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/commandref.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/commandref.rst	Sun Aug  8 12:41:24 2010
@@ -48,6 +48,50 @@
 .. % \label{clean-cmd}
 
 
+.. _sdist-cmd:
+
+Creating a source distribution: the :command:`sdist` command
+============================================================
+
+.. XXX fragment moved down from above: needs context!
+
+The manifest template commands are:
+
++-------------------------------------------+-----------------------------------------------+
+| Command                                   | Description                                   |
++===========================================+===============================================+
+| :command:`include pat1 pat2 ...`          | include all files matching any of the listed  |
+|                                           | patterns                                      |
++-------------------------------------------+-----------------------------------------------+
+| :command:`exclude pat1 pat2 ...`          | exclude all files matching any of the listed  |
+|                                           | patterns                                      |
++-------------------------------------------+-----------------------------------------------+
+| :command:`recursive-include dir pat1 pat2 | include all files under *dir* matching any of |
+| ...`                                      | the listed patterns                           |
++-------------------------------------------+-----------------------------------------------+
+| :command:`recursive-exclude dir pat1 pat2 | exclude all files under *dir* matching any of |
+| ...`                                      | the listed patterns                           |
++-------------------------------------------+-----------------------------------------------+
+| :command:`global-include pat1 pat2 ...`   | include all files anywhere in the source tree |
+|                                           | matching --- & any of the listed patterns     |
++-------------------------------------------+-----------------------------------------------+
+| :command:`global-exclude pat1 pat2 ...`   | exclude all files anywhere in the source tree |
+|                                           | matching --- & any of the listed patterns     |
++-------------------------------------------+-----------------------------------------------+
+| :command:`prune dir`                      | exclude all files under *dir*                 |
++-------------------------------------------+-----------------------------------------------+
+| :command:`graft dir`                      | include all files under *dir*                 |
++-------------------------------------------+-----------------------------------------------+
+
+The patterns here are Unix-style "glob" patterns: ``*`` matches any sequence of
+regular filename characters, ``?`` matches any single regular filename
+character, and ``[range]`` matches any of the characters in *range* (e.g.,
+``a-z``, ``a-zA-Z``, ``a-f0-9_.``).  The definition of "regular filename
+character" is platform-specific: on Unix it is anything except slash; on Windows
+anything except backslash or colon.
+
+.. XXX Windows support not there yet
+
 .. % \section{Creating a built distribution: the
 .. % \protect\command{bdist} command family}
 .. % \label{bdist-cmds}

Modified: python/branches/py3k-dtoa/Doc/distutils/examples.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/examples.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/examples.rst	Sun Aug  8 12:41:24 2010
@@ -233,6 +233,58 @@
          ext_modules=[Extension('foopkg.foo', ['foo.c'])],
          )
 
+Checking a package
+==================
+
+The ``check`` command allows you to verify if your package meta-data
+meet the minimum requirements to build a distribution.
+
+To run it, just call it using your :file:`setup.py` script. If something is
+missing, ``check`` will display a warning.
+
+Let's take an example with a simple script::
+
+    from distutils.core import setup
+
+    setup(name='foobar')
+
+Running the ``check`` command will display some warnings::
+
+    $ python setup.py check
+    running check
+    warning: check: missing required meta-data: version, url
+    warning: check: missing meta-data: either (author and author_email) or
+             (maintainer and maintainer_email) must be supplied
+
+
+If you use the reStructuredText syntax in the `long_description` field and
+`docutils <http://docutils.sourceforge.net/>`_ is installed you can check if
+the syntax is fine with the ``check`` command, using the `restructuredtext`
+option.
+
+For example, if the :file:`setup.py` script is changed like this::
+
+    from distutils.core import setup
+
+    desc = """\
+    My description
+    =============
+
+    This is the description of the ``foobar`` package.
+    """
+
+    setup(name='foobar', version='1', author='tarek',
+        author_email='tarek at ziade.org',
+        url='http://example.com', long_description=desc)
+
+Where the long description is broken, ``check`` will be able to detect it
+by using the `docutils` parser::
+
+    $ pythontrunk setup.py check --restructuredtext
+    running check
+    warning: check: Title underline too short. (line 2)
+    warning: check: Could not finish the parsing.
+
 .. % \section{Multiple extension modules}
 .. % \label{multiple-ext}
 

Modified: python/branches/py3k-dtoa/Doc/distutils/setupscript.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/setupscript.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/setupscript.rst	Sun Aug  8 12:41:24 2010
@@ -207,7 +207,7 @@
 SWIG on the interface file and compile the resulting C/C++ file into your
 extension.
 
-**\*\*** SWIG support is rough around the edges and largely untested! **\*\***
+.. XXX SWIG support is rough around the edges and largely untested!
 
 This warning notwithstanding, options to SWIG can be currently passed like
 this::
@@ -326,7 +326,7 @@
 (Again, this sort of non-portable construct should be avoided if you intend to
 distribute your code.)
 
-**\*\*** Should mention clib libraries here or somewhere else! **\*\***
+.. XXX Should mention clib libraries here or somewhere else!
 
 
 Other options

Modified: python/branches/py3k-dtoa/Doc/distutils/sourcedist.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/sourcedist.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/sourcedist.rst	Sun Aug  8 12:41:24 2010
@@ -26,16 +26,16 @@
 +===========+=========================+=========+
 | ``zip``   | zip file (:file:`.zip`) | (1),(3) |
 +-----------+-------------------------+---------+
-| ``gztar`` | gzip'ed tar file        | \(2)    |
+| ``gztar`` | gzip'ed tar file        | (2),(4) |
 |           | (:file:`.tar.gz`)       |         |
 +-----------+-------------------------+---------+
-| ``bztar`` | bzip2'ed tar file       |         |
+| ``bztar`` | bzip2'ed tar file       | \(4)    |
 |           | (:file:`.tar.bz2`)      |         |
 +-----------+-------------------------+---------+
 | ``ztar``  | compressed tar file     | \(4)    |
 |           | (:file:`.tar.Z`)        |         |
 +-----------+-------------------------+---------+
-| ``tar``   | tar file (:file:`.tar`) |         |
+| ``tar``   | tar file (:file:`.tar`) | \(4)    |
 +-----------+-------------------------+---------+
 
 Notes:
@@ -51,16 +51,8 @@
    of the standard Python library since Python 1.6)
 
 (4)
-   requires the :program:`compress` program. Notice that this format is now
-   pending for deprecation and will be removed in the future versions of Python.
-
-When using any ``tar`` format (``gztar``, ``bztar``, ``ztar`` or
-``tar``) under Unix, you can specify the ``owner`` and ``group`` names
-that will be set for each member of the archive.
-
-For example, if you want all files of the archive to be owned by root::
-
-    python setup.py sdist --owner=root --group=root
+   requires external utilities: :program:`tar` and possibly one of :program:`gzip`,
+   :program:`bzip2`, or :program:`compress`
 
 
 .. _manifest:
@@ -78,8 +70,8 @@
 * all C source files mentioned in the :option:`ext_modules` or
   :option:`libraries` options (
 
-  **\*\*** getting C library sources currently broken---no
-  :meth:`get_source_files` method in :file:`build_clib.py`! **\*\***)
+  .. XXX getting C library sources currently broken---no
+         :meth:`get_source_files` method in :file:`build_clib.py`!
 
 * scripts identified by the :option:`scripts` option
   See :ref:`distutils-installing-scripts`.
@@ -111,60 +103,9 @@
 :file:`MANIFEST`, you must specify everything: the default set of files
 described above does not apply in this case.
 
-See :ref:`manifest_template` section for a syntax reference.
-
-.. _manifest-options:
-
-Manifest-related options
-========================
-
-The normal course of operations for the :command:`sdist` command is as follows:
-
-* if the manifest file, :file:`MANIFEST` doesn't exist, read :file:`MANIFEST.in`
-  and create the manifest
-
-* if neither :file:`MANIFEST` nor :file:`MANIFEST.in` exist, create a manifest
-  with just the default file set
-
-* if either :file:`MANIFEST.in` or the setup script (:file:`setup.py`) are more
-  recent than :file:`MANIFEST`, recreate :file:`MANIFEST` by reading
-  :file:`MANIFEST.in`
-
-* use the list of files now in :file:`MANIFEST` (either just generated or read
-  in) to create the source distribution archive(s)
-
-There are a couple of options that modify this behaviour.  First, use the
-:option:`--no-defaults` and :option:`--no-prune` to disable the standard
-"include" and "exclude" sets.
-
-Second, you might just want to (re)generate the manifest, but not create a
-source distribution::
-
-   python setup.py sdist --manifest-only
-
-:option:`-o` is a sortcut for :option:`--manifest-only`.
-
-.. _manifest_template:
-
-The MANIFEST.in template
-========================
-
-A :file:`MANIFEST.in` file can be added in a project to define the list of
-files to include in the distribution built by the :command:`sdist` command.
-
-When :command:`sdist` is run, it will look for the :file:`MANIFEST.in` file
-and interpret it to generate the :file:`MANIFEST` file that contains the
-list of files that will be included in the package.
-
-This mechanism can be used when the default list of files is not enough.
-(See :ref:`manifest`).
-
-Principle
----------
-
 The manifest template has one command per line, where each command specifies a
 set of files to include or exclude from the source distribution.  For an
-example, let's look at the Distutils' own manifest template::
+example, again we turn to the Distutils' own manifest template::
 
    include *.txt
    recursive-include examples *.txt *.py
@@ -176,7 +117,9 @@
 :file:`examples/sample?/build`.  All of this is done *after* the standard
 include set, so you can exclude files from the standard set with explicit
 instructions in the manifest template.  (Or, you can use the
-:option:`--no-defaults` option to disable the standard set entirely.)
+:option:`--no-defaults` option to disable the standard set entirely.)  There are
+several other commands available in the manifest template mini-language; see
+section :ref:`sdist-cmd`.
 
 The order of commands in the manifest template matters: initially, we have the
 list of default files as described above, and each command in the template adds
@@ -230,41 +173,36 @@
 them to the standard representation on your platform. That way, the manifest
 template is portable across operating systems.
 
-Commands
---------
 
-The manifest template commands are:
+.. _manifest-options:
+
+Manifest-related options
+========================
+
+The normal course of operations for the :command:`sdist` command is as follows:
+
+* if the manifest file, :file:`MANIFEST` doesn't exist, read :file:`MANIFEST.in`
+  and create the manifest
+
+* if neither :file:`MANIFEST` nor :file:`MANIFEST.in` exist, create a manifest
+  with just the default file set
+
+* if either :file:`MANIFEST.in` or the setup script (:file:`setup.py`) are more
+  recent than :file:`MANIFEST`, recreate :file:`MANIFEST` by reading
+  :file:`MANIFEST.in`
+
+* use the list of files now in :file:`MANIFEST` (either just generated or read
+  in) to create the source distribution archive(s)
+
+There are a couple of options that modify this behaviour.  First, use the
+:option:`--no-defaults` and :option:`--no-prune` to disable the standard
+"include" and "exclude" sets.
+
+Second, you might just want to (re)generate the manifest, but not create a source
+distribution::
+
+   python setup.py sdist --manifest-only
+
+:option:`-o` is a shortcut for :option:`--manifest-only`.
 
-+-------------------------------------------+-----------------------------------------------+
-| Command                                   | Description                                   |
-+===========================================+===============================================+
-| :command:`include pat1 pat2 ...`          | include all files matching any of the listed  |
-|                                           | patterns                                      |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`exclude pat1 pat2 ...`          | exclude all files matching any of the listed  |
-|                                           | patterns                                      |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`recursive-include dir pat1 pat2 | include all files under *dir* matching any of |
-| ...`                                      | the listed patterns                           |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`recursive-exclude dir pat1 pat2 | exclude all files under *dir* matching any of |
-| ...`                                      | the listed patterns                           |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`global-include pat1 pat2 ...`   | include all files anywhere in the source tree |
-|                                           | matching --- & any of the listed patterns     |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`global-exclude pat1 pat2 ...`   | exclude all files anywhere in the source tree |
-|                                           | matching --- & any of the listed patterns     |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`prune dir`                      | exclude all files under *dir*                 |
-+-------------------------------------------+-----------------------------------------------+
-| :command:`graft dir`                      | include all files under *dir*                 |
-+-------------------------------------------+-----------------------------------------------+
-
-The patterns here are Unix-style "glob" patterns: ``*`` matches any sequence of
-regular filename characters, ``?`` matches any single regular filename
-character, and ``[range]`` matches any of the characters in *range* (e.g.,
-``a-z``, ``a-zA-Z``, ``a-f0-9_.``).  The definition of "regular filename
-character" is platform-specific: on Unix it is anything except slash; on Windows
-anything except backslash or colon.
 

Modified: python/branches/py3k-dtoa/Doc/distutils/uploading.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/distutils/uploading.rst	(original)
+++ python/branches/py3k-dtoa/Doc/distutils/uploading.rst	Sun Aug  8 12:41:24 2010
@@ -60,13 +60,13 @@
     setup(name='Distutils',
           long_description=open('README.txt'))
 
-In that case, :file:`README.txt` is a regular reStructuredText text file located
-in the root of the package besides :file:`setup.py`.
+In that case, `README.txt` is a regular reStructuredText text file located
+in the root of the package besides `setup.py`.
 
 To prevent registering broken reStructuredText content, you can use the
-:program:`rst2html` program that is provided by the :mod:`docutils` package
+:program:`rst2html` program that is provided by the `docutils` package
 and check the ``long_description`` from the command line::
 
     $ python setup.py --long-description | rst2html.py > output.html
 
-:mod:`docutils` will display a warning if there's something wrong with your syntax.
+`docutils` will display a warning if there's something wrong with your syntax.

Modified: python/branches/py3k-dtoa/Doc/documenting/markup.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/documenting/markup.rst	(original)
+++ python/branches/py3k-dtoa/Doc/documenting/markup.rst	Sun Aug  8 12:41:24 2010
@@ -177,6 +177,37 @@
    are modified), side effects, and possible exceptions.  A small example may be
    provided.
 
+.. describe:: decorator
+
+   Describes a decorator function.  The signature should *not* represent the
+   signature of the actual function, but the usage as a decorator.  For example,
+   given the functions
+
+   .. code-block:: python
+
+      def removename(func):
+          func.__name__ = ''
+          return func
+
+      def setnewname(name):
+          def decorator(func):
+              func.__name__ = name
+              return func
+          return decorator
+
+   the descriptions should look like this::
+
+      .. decorator:: removename
+
+         Remove name of the decorated function.
+
+      .. decorator:: setnewname(name)
+
+         Set name of the decorated function to *name*.
+
+   There is no ``deco`` role to link to a decorator that is marked up with
+   this directive; rather, use the ``:func:`` role.
+
 .. describe:: class
 
    Describes a class.  The signature can include parentheses with parameters
@@ -194,14 +225,20 @@
    parameter.  The description should include similar information to that
    described for ``function``.
 
+.. describe:: decoratormethod
+
+   Same as ``decorator``, but for decorators that are methods.
+
+   Refer to a decorator method using the ``:meth:`` role.
+
 .. describe:: opcode
 
    Describes a Python :term:`bytecode` instruction.
 
 .. describe:: cmdoption
 
-   Describes a command line option or switch.  Option argument names should be
-   enclosed in angle brackets.  Example::
+   Describes a Python command line option or switch.  Option argument names
+   should be enclosed in angle brackets.  Example::
 
       .. cmdoption:: -m <module>
 
@@ -502,8 +539,9 @@
 
 .. describe:: option
 
-   A command-line option to an executable program.  The leading hyphen(s) must
-   be included.
+   A command-line option of Python.  The leading hyphen(s) must be included.
+   If a matching ``cmdoption`` directive exists, it is linked to.  For options
+   of other programs or scripts, use simple ````code```` markup.
 
 .. describe:: program
 

Modified: python/branches/py3k-dtoa/Doc/extending/extending.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/extending/extending.rst	(original)
+++ python/branches/py3k-dtoa/Doc/extending/extending.rst	Sun Aug  8 12:41:24 2010
@@ -226,9 +226,28 @@
 become a dangling pointer. Should it become a dangling pointer, C code which
 raises the exception could cause a core dump or other unintended side effects.
 
-We discuss the use of PyMODINIT_FUNC as a function return type later in this
+We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this
 sample.
 
+The :exc:`spam.error` exception can be raised in your extension module using a
+call to :cfunc:`PyErr_SetString` as shown below::
+
+   static PyObject *
+   spam_system(PyObject *self, PyObject *args)
+   {
+       const char *command;
+       int sts;
+
+       if (!PyArg_ParseTuple(args, "s", &command))
+           return NULL;
+       sts = system(command);
+       if (sts < 0) {
+           PyErr_SetString(SpamError, "System command failed");
+           return NULL;
+       }
+       return PyLong_FromLong(sts);
+   }
+
 
 .. _backtoexample:
 

Modified: python/branches/py3k-dtoa/Doc/faq/extending.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/faq/extending.rst	(original)
+++ python/branches/py3k-dtoa/Doc/faq/extending.rst	Sun Aug  8 12:41:24 2010
@@ -29,6 +29,8 @@
 C++ objects with constructors are probably not a good idea.
 
 
+.. _c-wrapper-software:
+
 Writing C is hard; are there any alternatives?
 ----------------------------------------------
 
@@ -200,11 +202,7 @@
 whole lot of difference between C and C++ -- so the strategy of building a new
 Python type around a C structure (pointer) type will also work for C++ objects.
 
-For C++ libraries, you can look at `SIP
-<http://www.riverbankcomputing.co.uk/software/sip/>`_, `CXX
-<http://cxx.sourceforge.net/>`_, `Boost
-<http://www.boost.org/libs/python/doc/index.html>`_, `Weave
-<http://www.scipy.org/Weave>`_ or `SWIG <http://www.swig.org>`_
+For C++ libraries, see :ref:`c-wrapper-software`.
 
 
 I added a module using the Setup file and the make fails; why?

Modified: python/branches/py3k-dtoa/Doc/glossary.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/glossary.rst	(original)
+++ python/branches/py3k-dtoa/Doc/glossary.rst	Sun Aug  8 12:41:24 2010
@@ -154,15 +154,15 @@
       object.
 
    duck-typing
-      A pythonic programming style which determines an object's type by inspection
-      of its method or attribute signature rather than by explicit relationship
-      to some type object ("If it looks like a duck and quacks like a duck, it
+      A programming style which does not look at an object's type to determine
+      if it has the right interface; instead, the method or attribute is simply
+      called or used ("If it looks like a duck and quacks like a duck, it
       must be a duck.")  By emphasizing interfaces rather than specific types,
       well-designed code improves its flexibility by allowing polymorphic
       substitution.  Duck-typing avoids tests using :func:`type` or
-      :func:`isinstance`. (Note, however, that duck-typing can be complemented
-      with abstract base classes.) Instead, it typically employs :func:`hasattr`
-      tests or :term:`EAFP` programming.
+      :func:`isinstance`.  (Note, however, that duck-typing can be complemented
+      with :term:`abstract base class`\ es.)  Instead, it typically employs
+      :func:`hasattr` tests or :term:`EAFP` programming.
 
    EAFP
       Easier to ask for forgiveness than permission.  This common Python coding

Modified: python/branches/py3k-dtoa/Doc/howto/doanddont.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/howto/doanddont.rst	(original)
+++ python/branches/py3k-dtoa/Doc/howto/doanddont.rst	Sun Aug  8 12:41:24 2010
@@ -154,7 +154,7 @@
 
 Consider the case the file gets deleted between the time the call to
 :func:`os.path.exists` is made and the time :func:`open` is called. That means
-the last line will throw an :exc:`IOError`. The same would happen if *file*
+the last line will raise an :exc:`IOError`. The same would happen if *file*
 exists but has no read permission. Since testing this on a normal machine on
 existing and non-existing files make it seem bugless, that means in testing the
 results will seem fine, and the code will get shipped. Then an unhandled

Modified: python/branches/py3k-dtoa/Doc/install/index.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/install/index.rst	(original)
+++ python/branches/py3k-dtoa/Doc/install/index.rst	Sun Aug  8 12:41:24 2010
@@ -314,8 +314,8 @@
 stash of Python modules.  This scheme's name is derived from the idea of a
 "home" directory on Unix, since it's not unusual for a Unix user to make their
 home directory have a layout similar to :file:`/usr/` or :file:`/usr/local/`.
-This scheme can be used by anyone, regardless of the operating system their
-installing for.
+This scheme can be used by anyone, regardless of the operating system they
+are installing for.
 
 Installing a new module distribution is as simple as ::
 

Modified: python/branches/py3k-dtoa/Doc/library/2to3.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/2to3.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/2to3.rst	Sun Aug  8 12:41:24 2010
@@ -267,6 +267,25 @@
 
    Converts octal literals into the new syntax.
 
+.. 2to3fixer:: operator
+
+   Converts calls to various functions in the :mod:`operator` module to other,
+   but equivalent, function calls.  When needed, the appropriate ``import``
+   statements are added, e.g. ``import collections``.  The following mapping
+   are made:
+
+   ==================================  ==========================================
+   From                                To
+   ==================================  ==========================================
+   ``operator.isCallable(obj)``        ``hasattr(obj, '__call__')``
+   ``operator.sequenceIncludes(obj)``  ``operator.contains(obj)``
+   ``operator.isSequenceType(obj)``    ``isinstance(obj, collections.Sequence)``
+   ``operator.isMappingType(obj)``     ``isinstance(obj, collections.Mapping)``
+   ``operator.isNumberType(obj)``      ``isinstance(obj, numbers.Number)``
+   ``operator.repeat(obj, n)``         ``operator.mul(obj, n)``
+   ``operator.irepeat(obj, n)``        ``operator.imul(obj, n)``
+   ==================================  ==========================================
+
 .. 2to3fixer:: paren
 
    Add extra parenthesis where they are required in list comprehensions.  For

Modified: python/branches/py3k-dtoa/Doc/library/abc.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/abc.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/abc.rst	Sun Aug  8 12:41:24 2010
@@ -122,7 +122,7 @@
 
 It also provides the following decorators:
 
-.. function:: abstractmethod(function)
+.. decorator:: abstractmethod(function)
 
    A decorator indicating abstract methods.
 

Modified: python/branches/py3k-dtoa/Doc/library/argparse.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/argparse.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/argparse.rst	Sun Aug  8 12:41:24 2010
@@ -203,8 +203,8 @@
 add_help
 ^^^^^^^^
 
-By default, ArgumentParser objects add a ``-h/--help`` option which simply
-displays the parser's help message.  For example, consider a file named
+By default, ArgumentParser objects add an option which simply displays
+the parser's help message. For example, consider a file named
 ``myprogram.py`` containing the following code::
 
    import argparse
@@ -234,12 +234,27 @@
    optional arguments:
     --foo FOO  foo help
 
+The help option is typically ``-h/--help``. The exception to this is
+if the ``prefix_chars=`` is specified and does not include ``'-'``, in
+which case ``-h`` and ``--help`` are not valid options.  In
+this case, the first character in ``prefix_chars`` is used to prefix
+the help options::
+
+   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
+   >>> parser.print_help()
+   usage: PROG [+h]
+
+   optional arguments:
+     +h, ++help  show this help message and exit
+
+
 
 prefix_chars
 ^^^^^^^^^^^^
 
 Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
-Parsers that need to support additional prefix characters, e.g. for options
+Parsers that need to support different or additional prefix
+characters, e.g. for options
 like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
 to the ArgumentParser constructor::
 
@@ -698,8 +713,8 @@
 
    >>> class FooAction(argparse.Action):
    ...     def __call__(self, parser, namespace, values, option_string=None):
-   ...     print('%r %r %r' % (namespace, values, option_string))
-   ...     setattr(namespace, self.dest, values)
+   ...         print('%r %r %r' % (namespace, values, option_string))
+   ...         setattr(namespace, self.dest, values)
    ...
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action=FooAction)

Modified: python/branches/py3k-dtoa/Doc/library/ast.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/ast.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/ast.rst	Sun Aug  8 12:41:24 2010
@@ -119,12 +119,15 @@
 
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
-   Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
-   and ``None``.
+   Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
+   sets, booleans, and ``None``.
 
    This can be used for safely evaluating strings containing Python expressions
    from untrusted sources without the need to parse the values oneself.
 
+   .. versionchanged:: 3.2
+      Now allows bytes and set literals.
+
 
 .. function:: get_docstring(node, clean=True)
 

Modified: python/branches/py3k-dtoa/Doc/library/base64.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/base64.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/base64.rst	Sun Aug  8 12:41:24 2010
@@ -24,7 +24,7 @@
 
 .. function:: b64encode(s, altchars=None)
 
-   Encode a string use Base64.
+   Encode a byte string use 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
@@ -32,54 +32,54 @@
    generate URL or filesystem safe Base64 strings.  The default is ``None``, for
    which the standard Base64 alphabet is used.
 
-   The encoded string is returned.
+   The encoded byte string is returned.
 
 
 .. function:: b64decode(s, altchars=None)
 
-   Decode a Base64 encoded string.
+   Decode a Base64 encoded byte string.
 
    *s* is the string to decode.  Optional *altchars* must be a string of at least
    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
+   The decoded byte string is returned.  A :exc:`TypeError` is raised if *s* were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
 
 
 .. function:: standard_b64encode(s)
 
-   Encode string *s* using the standard Base64 alphabet.
+   Encode byte string *s* using the standard Base64 alphabet.
 
 
 .. function:: standard_b64decode(s)
 
-   Decode string *s* using the standard Base64 alphabet.
+   Decode byte string *s* using the standard Base64 alphabet.
 
 
 .. function:: urlsafe_b64encode(s)
 
-   Encode string *s* using a URL-safe alphabet, which substitutes ``-`` instead of
+   Encode byte string *s* using a URL-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 byte string *s* using a URL-safe alphabet, which substitutes ``-`` instead of
    ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet.
 
 
 .. function:: b32encode(s)
 
-   Encode a string using Base32.  *s* is the string to encode.  The encoded string
+   Encode a byte string using Base32.  *s* is the string to encode.  The encoded string
    is returned.
 
 
 .. function:: b32decode(s, casefold=False, map01=None)
 
-   Decode a Base32 encoded string.
+   Decode a Base32 encoded byte string.
 
    *s* is the string to decode.  Optional *casefold* is a flag specifying whether a
    lowercase alphabet is acceptable as input.  For security purposes, the default
@@ -92,27 +92,27 @@
    digit 0 is always mapped to the letter O).  For security purposes the default is
    ``None``, so that 0 and 1 are not allowed in the input.
 
-   The decoded string is returned.  A :exc:`TypeError` is raised if *s* were
+   The decoded byte string is returned.  A :exc:`TypeError` is raised if *s* were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
 
 
 .. function:: b16encode(s)
 
-   Encode a string using Base16.
+   Encode a byte string using Base16.
 
-   *s* is the string to encode.  The encoded string is returned.
+   *s* is the string to encode.  The encoded byte string is returned.
 
 
 .. function:: b16decode(s, casefold=False)
 
-   Decode a Base16 encoded string.
+   Decode a Base16 encoded byte string.
 
    *s* is the string to decode.  Optional *casefold* is a flag specifying whether a
    lowercase alphabet is acceptable as input.  For security purposes, the default
    is ``False``.
 
-   The decoded string is returned.  A :exc:`TypeError` is raised if *s* were
+   The decoded byte string is returned.  A :exc:`TypeError` is raised if *s* were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
 

Modified: python/branches/py3k-dtoa/Doc/library/bdb.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/bdb.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/bdb.rst	Sun Aug  8 12:41:24 2010
@@ -50,9 +50,10 @@
       Mark the breakpoint as disabled.
 
 
-   .. method:: bpprint(out=None)
+   .. method:: bpformat()
 
-      Print all the information about the breakpoint:
+      Return a string with all the information about the breakpoint, nicely
+      formatted:
 
       * The breakpoint number.
       * If it is temporary or not.
@@ -61,6 +62,13 @@
       * If it must be ignored the next N times.
       * The breakpoint hit count.
 
+      .. versionadded:: 3.2
+
+   .. method:: bpprint(out=None)
+
+      Print the output of :meth:`bpformat` to the file *out*, or if it is
+      ``None``, to standard output.
+
 
 .. class:: Bdb(skip=None)
 
@@ -108,7 +116,7 @@
       * ``"exception"``: An exception has occurred.
       * ``"c_call"``: A C function is about to be called.
       * ``"c_return"``: A C function has returned.
-      * ``"c_exception"``: A C function has thrown an exception.
+      * ``"c_exception"``: A C function has raised an exception.
 
       For the Python events, specialized functions (see below) are called.  For
       the C events, no action is taken.
@@ -267,6 +275,15 @@
 
       Delete all existing breakpoints.
 
+   .. method:: get_bpbynumber(arg)
+
+      Return a breakpoint specified by the given number.  If *arg* is a string,
+      it will be converted to a number.  If *arg* is a non-numeric string, if
+      the given breakpoint never existed or has been deleted, a
+      :exc:`ValueError` is raised.
+
+      .. versionadded:: 3.2
+
    .. method:: get_break(filename, lineno)
 
       Check if there is a breakpoint for *lineno* of *filename*.

Modified: python/branches/py3k-dtoa/Doc/library/binascii.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/binascii.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/binascii.rst	Sun Aug  8 12:41:24 2010
@@ -18,6 +18,11 @@
 low-level functions written in C for greater speed that are used by the
 higher-level modules.
 
+.. note::
+
+   Encoding and decoding functions do not accept Unicode strings.  Only bytestring
+   and bytearray objects can be processed.
+
 The :mod:`binascii` module defines the following functions:
 
 
@@ -54,6 +59,9 @@
    data. More than one line may be passed at a time. If the optional argument
    *header* is present and true, underscores will be decoded as spaces.
 
+   .. versionchanged:: 3.2
+      accept only bytestring or bytearray object as input.
+
 
 .. function:: b2a_qp(data, quotetabs=False, istext=True, header=False)
 
@@ -83,6 +91,9 @@
    decompressed data, unless data input data ends in an orphaned repeat indicator,
    in which case the :exc:`Incomplete` exception is raised.
 
+   .. versionchanged:: 3.2
+      accept only bytestring or bytearray object as input.
+
 
 .. function:: rlecode_hqx(data)
 
@@ -139,6 +150,9 @@
    of hexadecimal digits (which can be upper or lower case), otherwise a
    :exc:`TypeError` is raised.
 
+   .. versionchanged:: 3.2
+      accept only bytestring or bytearray object as input.
+
 
 .. exception:: Error
 
@@ -164,4 +178,3 @@
 
    Module :mod:`quopri`
       Support for quoted-printable encoding used in MIME email messages.
-

Modified: python/branches/py3k-dtoa/Doc/library/bisect.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/bisect.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/bisect.rst	Sun Aug  8 12:41:24 2010
@@ -39,6 +39,9 @@
    ``a.insert(bisect.bisect_left(a, x, lo, hi), x)``.  This assumes that *a* is
    already sorted.
 
+   Also note that while the fast search step is O(log n), the slower insertion
+   step is O(n), so the overall operation is slow.
+
 
 .. function:: insort_right(a, x, lo=0, hi=len(a))
               insort(a, x, lo=0, hi=len(a))
@@ -46,9 +49,53 @@
    Similar to :func:`insort_left`, but inserting *x* in *a* after any existing
    entries of *x*.
 
+   Also note that while the fast search step is O(log n), the slower insertion
+   step is O(n), so the overall operation is slow.
+
+Searching Sorted Lists
+----------------------
+
+The above :func:`bisect` functions are useful for finding insertion points, but
+can be tricky or awkward to use for common searching tasks. The following three
+functions show how to transform them into the standard lookups for sorted
+lists::
+
+    def find(a, key):
+        '''Find leftmost item exact equal to the key.
+        Raise ValueError if no such item exists.
+
+        '''
+        i = bisect_left(a, key)
+        if i < len(a) and a[i] == key:
+            return a[i]
+        raise ValueError('No item found with key equal to: %r' % (key,))
+
+    def find_le(a, key):
+        '''Find largest item less-than or equal to key.
+        Raise ValueError if no such item exists.
+        If multiple keys are equal, return the leftmost.
+
+        '''
+        i = bisect_left(a, key)
+        if i < len(a) and a[i] == key:
+            return a[i]
+        if i == 0:
+            raise ValueError('No item found with key at or below: %r' % (key,))
+        return a[i-1]
+
+    def find_ge(a, key):
+        '''Find smallest item greater-than or equal to key.
+        Raise ValueError if no such item exists.
+        If multiple keys are equal, return the leftmost.
+
+        '''
+        i = bisect_left(a, key)
+        if i == len(a):
+            raise ValueError('No item found with key at or above: %r' % (key,))
+        return a[i]
 
-Examples
---------
+Other Examples
+--------------
 
 .. _bisect-example:
 
@@ -87,3 +134,10 @@
     ('red', 5)
     >>> data[bisect_left(keys, 8)]
     ('yellow', 8)
+
+.. seealso::
+
+   `SortedCollection recipe
+   <http://code.activestate.com/recipes/577197-sortedcollection/>`_ that
+   encapsulates precomputed keys, allowing straight-forward insertion and
+   searching using a *key* function.

Modified: python/branches/py3k-dtoa/Doc/library/cgi.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/cgi.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/cgi.rst	Sun Aug  8 12:41:24 2010
@@ -324,10 +324,13 @@
    Convert the characters ``'&'``, ``'<'`` and ``'>'`` in string *s* to HTML-safe
    sequences.  Use this if you need to display text that might contain such
    characters in HTML.  If the optional flag *quote* is true, the quotation mark
-   character (``'"'``) is also translated; this helps for inclusion in an HTML
-   attribute value, as in ``<A HREF="...">``.  If the value to be quoted might
-   include single- or double-quote characters, or both, consider using the
-   :func:`quoteattr` function in the :mod:`xml.sax.saxutils` module instead.
+   character (``"``) is also translated; this helps for inclusion in an HTML
+   attribute value delimited by double quotes, as in ``<a href="...">``.  Note
+   that single quotes are never translated.
+
+   If the value to be quoted might include single- or double-quote characters,
+   or both, consider using the :func:`quoteattr` function in the
+   :mod:`xml.sax.saxutils` module instead.
 
 
 .. _cgi-security:

Modified: python/branches/py3k-dtoa/Doc/library/cmath.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/cmath.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/cmath.rst	Sun Aug  8 12:41:24 2010
@@ -187,15 +187,24 @@
 Classification functions
 ------------------------
 
+.. function:: isfinite(x)
+
+   Return ``True`` if both the real and imaginary parts of *x* are finite, and
+   ``False`` otherwise.
+
+   .. versionadded:: 3.2
+
+
 .. function:: isinf(x)
 
-   Return *True* if the real or the imaginary part of x is positive
-   or negative infinity.
+   Return ``True`` if either the real or the imaginary part of *x* is an
+   infinity, and ``False`` otherwise.
 
 
 .. function:: isnan(x)
 
-   Return *True* if the real or imaginary part of x is not a number (NaN).
+   Return ``True`` if either the real or the imaginary part of *x* is a NaN,
+   and ``False`` otherwise.
 
 
 Constants

Modified: python/branches/py3k-dtoa/Doc/library/cmd.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/cmd.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/cmd.rst	Sun Aug  8 12:41:24 2010
@@ -76,11 +76,13 @@
    are the beginning and ending indexes of the prefix text, which could be used to
    provide different completion depending upon which position the argument is in.
 
-   All subclasses of :class:`Cmd` inherit a predefined :meth:`do_help`. This
+   All subclasses of :class:`Cmd` inherit a predefined :meth:`do_help`.  This
    method, called with an argument ``'bar'``, invokes the corresponding method
-   :meth:`help_bar`.  With no argument, :meth:`do_help` lists all available help
-   topics (that is, all commands with corresponding :meth:`help_\*` methods), and
-   also lists any undocumented commands.
+   :meth:`help_bar`, and if that is not present, prints the docstring of
+   :meth:`do_bar`, if available.  With no argument, :meth:`do_help` lists all
+   available help topics (that is, all commands with corresponding
+   :meth:`help_\*` methods or commands that have docstrings), and also lists any
+   undocumented commands.
 
 
 .. method:: Cmd.onecmd(str)

Modified: python/branches/py3k-dtoa/Doc/library/collections.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/collections.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/collections.rst	Sun Aug  8 12:41:24 2010
@@ -12,131 +12,24 @@
    import itertools
    __name__ = '<doctest>'
 
-This module implements high-performance container datatypes.  Currently,
-there are four datatypes, :class:`Counter`, :class:`deque`, :class:`OrderedDict` and
-:class:`defaultdict`, and one datatype factory function, :func:`namedtuple`.
-
-The specialized containers provided in this module provide alternatives
-to Python's general purpose built-in containers, :class:`dict`,
-:class:`list`, :class:`set`, and :class:`tuple`.
-
-In addition to containers, the collections module provides some ABCs
-(abstract base classes) that can be used to test whether a class
-provides a particular interface, for example, whether it is hashable or
-a mapping.
-
-ABCs - abstract base classes
-----------------------------
-
-The collections module offers the following ABCs:
-
-=========================  =====================  ======================  ====================================================
-ABC                        Inherits               Abstract Methods        Mixin Methods
-=========================  =====================  ======================  ====================================================
-:class:`Container`                                ``__contains__``
-:class:`Hashable`                                 ``__hash__``
-:class:`Iterable`                                 ``__iter__``
-:class:`Iterator`          :class:`Iterable`      ``__next__``            ``__iter__``
-:class:`Sized`                                    ``__len__``
-:class:`Callable`                                 ``__call__``
-
-:class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
-                           :class:`Iterable`,                             ``index``, and ``count``
-                           :class:`Container`
-
-:class:`MutableSequence`   :class:`Sequence`      ``__setitem__``         Inherited Sequence methods and
-                                                  ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
-                                                  and ``insert``          ``remove``, and ``__iadd__``
-
-:class:`Set`               :class:`Sized`,                                ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
-                           :class:`Iterable`,                             ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
-                           :class:`Container`                             ``__sub__``, ``__xor__``, and ``isdisjoint``
-
-:class:`MutableSet`        :class:`Set`           ``add`` and             Inherited Set methods and
-                                                  ``discard``             ``clear``, ``pop``, ``remove``, ``__ior__``,
-                                                                          ``__iand__``, ``__ixor__``, and ``__isub__``
-
-:class:`Mapping`           :class:`Sized`,        ``__getitem__``         ``__contains__``, ``keys``, ``items``, ``values``,
-                           :class:`Iterable`,                             ``get``, ``__eq__``, and ``__ne__``
-                           :class:`Container`
-
-:class:`MutableMapping`    :class:`Mapping`       ``__setitem__`` and     Inherited Mapping methods and
-                                                  ``__delitem__``         ``pop``, ``popitem``, ``clear``, ``update``,
-                                                                          and ``setdefault``
-
-
-:class:`MappingView`       :class:`Sized`                                 ``__len__``
-:class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
-                           :class:`Set`                                   ``__iter__``
-:class:`ItemsView`         :class:`MappingView`,                          ``__contains__``,
-                           :class:`Set`                                   ``__iter__``
-:class:`ValuesView`        :class:`MappingView`                           ``__contains__``, ``__iter__``
-=========================  =====================  ======================  ====================================================
-
-These ABCs allow us to ask classes or instances if they provide
-particular functionality, for example::
-
-    size = None
-    if isinstance(myvar, collections.Sized):
-        size = len(myvar)
-
-Several of the ABCs are also useful as mixins that make it easier to develop
-classes supporting container APIs.  For example, to write a class supporting
-the full :class:`Set` API, it only necessary to supply the three underlying
-abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
-The ABC supplies the remaining methods such as :meth:`__and__` and
-:meth:`isdisjoint` ::
-
-    class ListBasedSet(collections.Set):
-         ''' Alternate set implementation favoring space over speed
-             and not requiring the set elements to be hashable. '''
-         def __init__(self, iterable):
-             self.elements = lst = []
-             for value in iterable:
-                 if value not in lst:
-                     lst.append(value)
-         def __iter__(self):
-             return iter(self.elements)
-         def __contains__(self, value):
-             return value in self.elements
-         def __len__(self):
-             return len(self.elements)
-
-    s1 = ListBasedSet('abcdef')
-    s2 = ListBasedSet('defghi')
-    overlap = s1 & s2            # The __and__() method is supported automatically
-
-Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
-
-(1)
-   Since some set operations create new sets, the default mixin methods need
-   a way to create new instances from an iterable. The class constructor is
-   assumed to have a signature in the form ``ClassName(iterable)``.
-   That assumption is factored-out to an internal classmethod called
-   :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
-   If the :class:`Set` mixin is being used in a class with a different
-   constructor signature, you will need to override :meth:`from_iterable`
-   with a classmethod that can construct new instances from
-   an iterable argument.
-
-(2)
-   To override the comparisons (presumably for speed, as the
-   semantics are fixed), redefine :meth:`__le__` and
-   then the other operations will automatically follow suit.
-
-(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,
-   inherit from both :meth:`Set` and :meth:`Hashable`, then define
-   ``__hash__ = Set._hash``.
-
-.. seealso::
-
-   * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
-     example built on :class:`MutableSet`.
-
-   * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.
+This module implements specialized container datatypes providing alternatives to
+Python's general purpose built-in containers, :class:`dict`, :class:`list`,
+:class:`set`, and :class:`tuple`.
+
+=====================   ====================================================================
+:func:`namedtuple`      factory function for creating tuple subclasses with named fields
+:class:`deque`          list-like container with fast appends and pops on either end
+:class:`Counter`        dict subclass for counting hashable objects
+:class:`OrderedDict`    dict subclass that remembers the order entries were added
+:class:`defaultdict`    dict subclass that calls a factory function to supply missing values
+:class:`UserDict`       wrapper around dictionary objects for easier dict subclassing
+:class:`UserList`       wrapper around list objects for easier list subclassing
+:class:`UserString`     wrapper around string objects for easier string subclassing
+=====================   ====================================================================
+
+In addition to the concrete container classes, the collections module provides
+ABCs (abstract base classes) that can be used to test whether a class provides a
+particular interface, for example, whether it is hashable or a mapping.
 
 
 :class:`Counter` objects
@@ -551,7 +444,7 @@
    :class:`defaultdict` objects support the following method in addition to the
    standard :class:`dict` operations:
 
-   .. method:: defaultdict.__missing__(key)
+   .. method:: __missing__(key)
 
       If the :attr:`default_factory` attribute is ``None``, this raises a
       :exc:`KeyError` exception with the *key* as argument.
@@ -571,7 +464,7 @@
    :class:`defaultdict` objects support the following instance variable:
 
 
-   .. attribute:: defaultdict.default_factory
+   .. attribute:: default_factory
 
       This attribute is used by the :meth:`__missing__` method; it is
       initialized from the first argument to the constructor, if present, or to
@@ -712,7 +605,7 @@
    <BLANKLINE>
            def __repr__(self):
                'Return a nicely formatted representation string'
-               return 'Point(x=%r, y=%r)' % self
+               return self.__class__.__name__ + '(x=%r, y=%r)' % self
    <BLANKLINE>
            def _asdict(self):
                'Return a new OrderedDict which maps field names to their values'
@@ -763,7 +656,7 @@
 three additional methods and one attribute.  To prevent conflicts with
 field names, the method and attribute names start with an underscore.
 
-.. method:: somenamedtuple._make(iterable)
+.. classmethod:: somenamedtuple._make(iterable)
 
    Class method that makes a new instance from an existing sequence or iterable.
 
@@ -891,11 +784,11 @@
 
    .. versionadded:: 3.1
 
-.. method:: OrderedDict.popitem(last=True)
+   .. method:: popitem(last=True)
 
-   The :meth:`popitem` method for ordered dictionaries returns and removes
-   a (key, value) pair.  The pairs are returned in LIFO order if *last* is
-   true or FIFO order if false.
+      The :meth:`popitem` method for ordered dictionaries returns and removes a
+      (key, value) pair.  The pairs are returned in LIFO order if *last* is true
+      or FIFO order if false.
 
 In addition to the usual mapping methods, ordered dictionaries also support
 reverse iteration using :func:`reversed`.
@@ -938,6 +831,18 @@
 are deleted.  But when new keys are added, the keys are appended
 to the end and the sort is not maintained.
 
+It is also straight-forward to create an ordered dictionary variant
+that the remembers the order the keys were *last* inserted.
+If a new entry overwrites an existing entry, the
+original insertion position is changed and moved to the end::
+
+    class LastUpdatedOrderedDict(OrderedDict):
+        'Store items is the order the keys were last added'
+        def __setitem__(self, key, value):
+            if key in self:
+                del self[key]
+            OrderedDict.__setitem__(self, key, value)
+
 
 :class:`UserDict` objects
 -------------------------
@@ -956,12 +861,13 @@
    initialized with its contents; note that a reference to *initialdata* will not
    be kept, allowing it be used for other purposes.
 
-In addition to supporting the methods and operations of mappings,
-:class:`UserDict` instances provide the following attribute:
+   In addition to supporting the methods and operations of mappings,
+   :class:`UserDict` instances provide the following attribute:
 
-.. attribute:: UserDict.data
+   .. attribute:: data
 
-   A real dictionary used to store the contents of the :class:`UserDict` class.
+      A real dictionary used to store the contents of the :class:`UserDict`
+      class.
 
 
 
@@ -985,13 +891,13 @@
    defaulting to the empty list ``[]``.  *list* can be any iterable, for
    example a real Python list or a :class:`UserList` object.
 
-In addition to supporting the methods and operations of mutable sequences,
-:class:`UserList` instances provide the following attribute:
+   In addition to supporting the methods and operations of mutable sequences,
+   :class:`UserList` instances provide the following attribute:
 
-.. attribute:: UserList.data
+   .. attribute:: data
 
-   A real :class:`list` object used to store the contents of the
-   :class:`UserList` class.
+      A real :class:`list` object used to store the contents of the
+      :class:`UserList` class.
 
 **Subclassing requirements:** Subclasses of :class:`UserList` are expect to
 offer a constructor which can be called with either no arguments or one
@@ -1023,3 +929,117 @@
    be an instance of :class:`bytes`, :class:`str`, :class:`UserString` (or a
    subclass) or an arbitrary sequence which can be converted into a string using
    the built-in :func:`str` function.
+
+
+ABCs - abstract base classes
+----------------------------
+
+The collections module offers the following ABCs:
+
+=========================  =====================  ======================  ====================================================
+ABC                        Inherits               Abstract Methods        Mixin Methods
+=========================  =====================  ======================  ====================================================
+:class:`Container`                                ``__contains__``
+:class:`Hashable`                                 ``__hash__``
+:class:`Iterable`                                 ``__iter__``
+:class:`Iterator`          :class:`Iterable`      ``__next__``            ``__iter__``
+:class:`Sized`                                    ``__len__``
+:class:`Callable`                                 ``__call__``
+
+:class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
+                           :class:`Iterable`,                             ``index``, and ``count``
+                           :class:`Container`
+
+:class:`MutableSequence`   :class:`Sequence`      ``__setitem__``         Inherited Sequence methods and
+                                                  ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
+                                                  and ``insert``          ``remove``, and ``__iadd__``
+
+:class:`Set`               :class:`Sized`,                                ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
+                           :class:`Iterable`,                             ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
+                           :class:`Container`                             ``__sub__``, ``__xor__``, and ``isdisjoint``
+
+:class:`MutableSet`        :class:`Set`           ``add`` and             Inherited Set methods and
+                                                  ``discard``             ``clear``, ``pop``, ``remove``, ``__ior__``,
+                                                                          ``__iand__``, ``__ixor__``, and ``__isub__``
+
+:class:`Mapping`           :class:`Sized`,        ``__getitem__``         ``__contains__``, ``keys``, ``items``, ``values``,
+                           :class:`Iterable`,                             ``get``, ``__eq__``, and ``__ne__``
+                           :class:`Container`
+
+:class:`MutableMapping`    :class:`Mapping`       ``__setitem__`` and     Inherited Mapping methods and
+                                                  ``__delitem__``         ``pop``, ``popitem``, ``clear``, ``update``,
+                                                                          and ``setdefault``
+
+
+:class:`MappingView`       :class:`Sized`                                 ``__len__``
+:class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
+                           :class:`Set`                                   ``__iter__``
+:class:`ItemsView`         :class:`MappingView`,                          ``__contains__``,
+                           :class:`Set`                                   ``__iter__``
+:class:`ValuesView`        :class:`MappingView`                           ``__contains__``, ``__iter__``
+=========================  =====================  ======================  ====================================================
+
+These ABCs allow us to ask classes or instances if they provide
+particular functionality, for example::
+
+    size = None
+    if isinstance(myvar, collections.Sized):
+        size = len(myvar)
+
+Several of the ABCs are also useful as mixins that make it easier to develop
+classes supporting container APIs.  For example, to write a class supporting
+the full :class:`Set` API, it only necessary to supply the three underlying
+abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
+The ABC supplies the remaining methods such as :meth:`__and__` and
+:meth:`isdisjoint` ::
+
+    class ListBasedSet(collections.Set):
+         ''' Alternate set implementation favoring space over speed
+             and not requiring the set elements to be hashable. '''
+         def __init__(self, iterable):
+             self.elements = lst = []
+             for value in iterable:
+                 if value not in lst:
+                     lst.append(value)
+         def __iter__(self):
+             return iter(self.elements)
+         def __contains__(self, value):
+             return value in self.elements
+         def __len__(self):
+             return len(self.elements)
+
+    s1 = ListBasedSet('abcdef')
+    s2 = ListBasedSet('defghi')
+    overlap = s1 & s2            # The __and__() method is supported automatically
+
+Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
+
+(1)
+   Since some set operations create new sets, the default mixin methods need
+   a way to create new instances from an iterable. The class constructor is
+   assumed to have a signature in the form ``ClassName(iterable)``.
+   That assumption is factored-out to an internal classmethod called
+   :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
+   If the :class:`Set` mixin is being used in a class with a different
+   constructor signature, you will need to override :meth:`from_iterable`
+   with a classmethod that can construct new instances from
+   an iterable argument.
+
+(2)
+   To override the comparisons (presumably for speed, as the
+   semantics are fixed), redefine :meth:`__le__` and
+   then the other operations will automatically follow suit.
+
+(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,
+   inherit from both :meth:`Set` and :meth:`Hashable`, then define
+   ``__hash__ = Set._hash``.
+
+.. seealso::
+
+   * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
+     example built on :class:`MutableSet`.
+
+   * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.

Modified: python/branches/py3k-dtoa/Doc/library/configparser.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/configparser.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/configparser.rst	Sun Aug  8 12:41:24 2010
@@ -15,105 +15,172 @@
    single: ini file
    single: Windows ini file
 
-This module defines the class :class:`ConfigParser`.   The :class:`ConfigParser`
-class implements a basic configuration file parser language which provides a
-structure similar to what you would find on Microsoft Windows INI files.  You
-can use this to write Python programs which can be customized by end users
-easily.
+This module provides the classes :class:`RawConfigParser` and
+:class:`SafeConfigParser`.  They implement a basic configuration file parser
+language which provides a structure similar to what you would find in Microsoft
+Windows INI files.  You can use this to write Python programs which can be
+customized by end users easily.
 
 .. note::
 
    This library does *not* interpret or write the value-type prefixes used in
    the Windows Registry extended version of INI syntax.
 
-The configuration file consists of sections, led by a ``[section]`` header and
-followed by ``name: value`` entries, with continuations in the style of
-:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
-accepted.  Note that leading whitespace is removed from values. The optional
-values can contain format strings which refer to other values in the same
-section, or values in a special ``DEFAULT`` section.  Additional defaults can be
-provided on initialization and retrieval.  Lines beginning with ``'#'`` or
-``';'`` are ignored and may be used to provide comments.
+A configuration file consists of sections, each led by a ``[section]`` header,
+followed by name/value entries separated by a specific string (``=`` or ``:`` by
+default).  Note that leading whitespace is removed from values.  Values can be
+ommitted, in which case the key/value delimiter may also be left out.  Values
+can also span multiple lines, as long as they are indented deeper than the first
+line of the value.  Depending on the parser's mode, blank lines may be treated
+as parts of multiline values or ignored.
+
+Configuration files may include comments, prefixed by specific characters (``#``
+and ``;`` by default).  Comments may appear on their own in an otherwise empty
+line, or may be entered in lines holding values or spection names.  In the
+latter case, they need to be preceded by a whitespace character to be recognized
+as a comment.  (For backwards compatibility, by default only ``;`` starts an
+inline comment, while ``#`` does not.)
+
+On top of the core functionality, :class:`SafeConfigParser` supports
+interpolation.  This means values can contain format strings which refer to
+other values in the same section, or values in a special ``DEFAULT`` section.
+Additional defaults can be provided on initialization.
 
 For example::
 
-   [My Section]
-   foodir: %(dir)s/whatever
-   dir=frob
-   long: this value continues
-      in the next line
-
-would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
-All reference expansions are done on demand.
-
-Default values can be specified by passing them into the :class:`ConfigParser`
-constructor as a dictionary.  Additional defaults  may be passed into the
-:meth:`get` method which will override all others.
-
-Sections are normally stored in a built-in dictionary. An alternative dictionary
-type can be passed to the :class:`ConfigParser` constructor. For example, if a
-dictionary type is passed that sorts its keys, the sections will be sorted on
-write-back, as will be the keys within each section.
+   [Paths]
+   home_dir: /Users
+   my_dir: %(home_dir)s/lumberjack
+   my_pictures: %(my_dir)s/Pictures
+
+   [Multiline Values]
+   chorus: I'm a lumberjack, and I'm okay
+      I sleep all night and I work all day
+
+   [No Values]
+   key_without_value
+   empty string value here =
+
+   [You can use comments] ; after a useful line
+   ; in an empty line
+   after: a_value ; here's another comment
+   inside: a         ;comment
+           multiline ;comment
+           value!    ;comment
+
+      [Sections Can Be Indented]
+         can_values_be_as_well = True
+         does_that_mean_anything_special = False
+         purpose = formatting for readability
+         multiline_values = are
+            handled just fine as
+            long as they are indented
+            deeper than the first line
+            of a value
+         # Did I mention we can indent comments, too?
+
+
+In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s``
+to the value of ``home_dir`` (``/Users`` in this case).  ``%(my_dir)s`` in
+effect would resolve to ``/Users/lumberjack``.  All interpolations are done on
+demand so keys used in the chain of references do not have to be specified in
+any specific order in the configuration file.
+
+:class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the
+value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of
+``my_dir``.  Other features presented in the example are handled in the same
+manner by both parsers.
+
+Default values can be specified by passing them as a dictionary when
+constructing the :class:`SafeConfigParser`.
+
+Sections are normally stored in an :class:`collections.OrderedDict` which
+maintains the order of all keys.  An alternative dictionary type can be passed
+to the :meth:`__init__` method.  For example, if a dictionary type is passed
+that sorts its keys, the sections will be sorted on write-back, as will be the
+keys within each section.
 
 
-.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict,
-                           allow_no_value=False)
+.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, empty_lines_in_values=True, allow_no_value=False)
 
    The basic configuration object.  When *defaults* is given, it is initialized
-   into the dictionary of intrinsic defaults.  When *dict_type* is given, it will
-   be used to create the dictionary objects for the list of sections, for the
-   options within a section, and for the default values.  When *allow_no_value*
-   is true (default: ``False``), options without values are accepted; the value
+   into the dictionary of intrinsic defaults.  When *dict_type* is given, it
+   will be used to create the dictionary objects for the list of sections, for
+   the options within a section, and for the default values.
+
+   When *delimiters* is given, it will be used as the set of substrings that
+   divide keys from values.  When *comment_prefixes* is given, it will be used
+   as the set of substrings that prefix comments in a line, both for the whole
+   line and inline comments.  For backwards compatibility, the default value for
+   *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
+   start whole line comments while only ``;`` can start inline comments.
+
+   When *empty_lines_in_values* is ``False`` (default: ``True``), each empty
+   line marks the end of an option.  Otherwise, internal empty lines of a
+   multiline option are kept as part of the value.  When *allow_no_value* is
+   true (default: ``False``), options without values are accepted; the value
    presented for these is ``None``.
 
-   This class does not
-   support the magical interpolation behavior.
+   This class does not support the magical interpolation behavior.
 
    .. versionchanged:: 3.1
       The default *dict_type* is :class:`collections.OrderedDict`.
 
    .. versionchanged:: 3.2
-      *allow_no_value* was added.
+      *delimiters*, *comment_prefixes*, *empty_lines_in_values* and
+      *allow_no_value* were added.
 
 
-.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict,
-                        allow_no_value=False)
+.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=('#', ';'), empty_lines_in_values=True, allow_no_value=False)
 
-   Derived class of :class:`RawConfigParser` that implements the magical
-   interpolation feature and adds optional arguments to the :meth:`get` and
-   :meth:`items` methods.  The values in *defaults* must be appropriate for the
-   ``%()s`` string interpolation.  Note that *__name__* is an intrinsic default;
-   its value is the section name, and will override any value provided in
-   *defaults*.
+   Derived class of :class:`ConfigParser` that implements a sane variant of the
+   magical interpolation feature.  This implementation is more predictable as it
+   validates the interpolation syntax used within a configuration file.  This
+   class also enables escaping the interpolation character (e.g. a key can have
+   ``%`` as part of the value by specifying ``%%`` in the file).
 
-   All option names used in interpolation will be passed through the
-   :meth:`optionxform` method just like any other option name reference.  For
-   example, using the default implementation of :meth:`optionxform` (which converts
-   option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
-   equivalent.
+   Applications that don't require interpolation should use
+   :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best
+   option.
 
    .. versionchanged:: 3.1
       The default *dict_type* is :class:`collections.OrderedDict`.
 
    .. versionchanged:: 3.2
-      *allow_no_value* was added.
+      *delimiters*, *comment_prefixes*, *empty_lines_in_values* and
+      *allow_no_value* were added.
 
 
-.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict,
-                            allow_no_value=False)
+.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=('#', ';'), empty_lines_in_values=True, allow_no_value=False)
 
-   Derived class of :class:`ConfigParser` that implements a more-sane variant of
-   the magical interpolation feature.  This implementation is more predictable as
-   well. New applications should prefer this version if they don't need to be
-   compatible with older versions of Python.
+   Derived class of :class:`RawConfigParser` that implements the magical
+   interpolation feature and adds optional arguments to the :meth:`get` and
+   :meth:`items` methods.
 
-   .. XXX Need to explain what's safer/more predictable about it.
+   :class:`SafeConfigParser` is generally recommended over this class if you
+   need interpolation.
+
+   The values in *defaults* must be appropriate for the ``%()s`` string
+   interpolation.  Note that *__name__* is an intrinsic default; its value is
+   the section name, and will override any value provided in *defaults*.
+
+   All option names used in interpolation will be passed through the
+   :meth:`optionxform` method just like any other option name reference.  For
+   example, using the default implementation of :meth:`optionxform` (which
+   converts option names to lower case), the values ``foo %(bar)s`` and ``foo
+   %(BAR)s`` are equivalent.
 
    .. versionchanged:: 3.1
       The default *dict_type* is :class:`collections.OrderedDict`.
 
    .. versionchanged:: 3.2
-      *allow_no_value* was added.
+      *delimiters*, *comment_prefixes*, *empty_lines_in_values* and
+      *allow_no_value* were added.
+
+
+.. exception:: Error
+
+   Base class for all other configparser exceptions.
 
 
 .. exception:: NoSectionError
@@ -223,25 +290,29 @@
    :const:`True`; otherwise return :const:`False`.
 
 
-.. method:: RawConfigParser.read(filenames)
+.. method:: RawConfigParser.read(filenames, encoding=None)
 
    Attempt to read and parse a list of filenames, returning a list of filenames
-   which were successfully parsed.  If *filenames* is a string,
-   it is treated as a single filename. If a file named in *filenames* cannot be
-   opened, that file will be ignored.  This is designed so that you can specify a
-   list of potential configuration file locations (for example, the current
-   directory, the user's home directory, and some system-wide directory), and all
-   existing configuration files in the list will be read.  If none of the named
-   files exist, the :class:`ConfigParser` instance will contain an empty dataset.
-   An application which requires initial values to be loaded from a file should
-   load the required file or files using :meth:`readfp` before calling :meth:`read`
-   for any optional files::
+   which were successfully parsed.  If *filenames* is a string, it is treated as
+   a single filename.  If a file named in *filenames* cannot be opened, that
+   file will be ignored.  This is designed so that you can specify a list of
+   potential configuration file locations (for example, the current directory,
+   the user's home directory, and some system-wide directory), and all existing
+   configuration files in the list will be read.  If none of the named files
+   exist, the :class:`ConfigParser` instance will contain an empty dataset.  An
+   application which requires initial values to be loaded from a file should
+   load the required file or files using :meth:`readfp` before calling
+   :meth:`read` for any optional files::
 
       import configparser, os
 
       config = configparser.ConfigParser()
       config.readfp(open('defaults.cfg'))
-      config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
+      config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
+
+   .. versionadded:: 3.2
+      The *encoding* parameter.  Previously, all files were read using the
+      default encoding for :func:`open`.
 
 
 .. method:: RawConfigParser.readfp(fp, filename=None)
@@ -295,11 +366,13 @@
    interpolation and output to files) can only be achieved using string values.
 
 
-.. method:: RawConfigParser.write(fileobject)
+.. method:: RawConfigParser.write(fileobject, space_around_delimiters=True)
 
    Write a representation of the configuration to the specified file object,
    which must be opened in text mode (accepting strings).  This representation
-   can be parsed by a future :meth:`read` call.
+   can be parsed by a future :meth:`read` call. If ``space_around_delimiters``
+   is ``True`` (the default), delimiters between keys and values are surrounded
+   by spaces.
 
 
 .. method:: RawConfigParser.remove_option(section, option)
@@ -342,21 +415,27 @@
 --------------------
 
 The :class:`ConfigParser` class extends some methods of the
-:class:`RawConfigParser` interface, adding some optional arguments.
+:class:`RawConfigParser` interface, adding some optional arguments. Whenever you
+can, consider using :class:`SafeConfigParser` which adds validation and escaping
+for the interpolation.
 
 
 .. method:: ConfigParser.get(section, option, raw=False, vars=None)
 
-   Get an *option* value for the named *section*.  All the ``'%'`` interpolations
-   are expanded in the return values, based on the defaults passed into the
-   constructor, as well as the options *vars* provided, unless the *raw* argument
-   is true.
+   Get an *option* value for the named *section*.  If *vars* is provided, it
+   must be a dictionary.  The *option* is looked up in *vars* (if provided),
+   *section*, and in *defaults* in that order.
+
+   All the ``'%'`` interpolations are expanded in the return values, unless the
+   *raw* argument is true.  Values for interpolation keys are looked up in the
+   same manner as the option.
 
 
 .. method:: ConfigParser.items(section, raw=False, vars=None)
 
-   Return a list of ``(name, value)`` pairs for each option in the given *section*.
-   Optional arguments have the same meaning as for the :meth:`get` method.
+   Return a list of ``(name, value)`` pairs for each option in the given
+   *section*.  Optional arguments have the same meaning as for the :meth:`get`
+   method.
 
 
 .. _safeconfigparser-objects:
@@ -466,8 +545,8 @@
 
 Some configuration files are known to include settings without values, but which
 otherwise conform to the syntax supported by :mod:`configparser`.  The
-*allow_no_value* parameter to the constructor can be used to indicate that such
-values should be accepted:
+*allow_no_value* parameter to the :meth:`__init__` method can be used to
+indicate that such values should be accepted:
 
 .. doctest::
 
@@ -476,12 +555,12 @@
 
    >>> sample_config = """
    ... [mysqld]
-   ... user = mysql
-   ... pid-file = /var/run/mysqld/mysqld.pid
-   ... skip-external-locking
-   ... old_passwords = 1
-   ... skip-bdb
-   ... skip-innodb
+   ...   user = mysql
+   ...   pid-file = /var/run/mysqld/mysqld.pid
+   ...   skip-external-locking
+   ...   old_passwords = 1
+   ...   skip-bdb
+   ...   skip-innodb # we don't need ACID today
    ... """
    >>> config = configparser.RawConfigParser(allow_no_value=True)
    >>> config.readfp(io.BytesIO(sample_config))

Modified: python/branches/py3k-dtoa/Doc/library/constants.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/constants.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/constants.rst	Sun Aug  8 12:41:24 2010
@@ -3,15 +3,6 @@
 
 A small number of constants live in the built-in namespace.  They are:
 
-
-.. note::
-
-   :data:`None`, :data:`False`, :data:`True` and :data:`__debug__` cannot be
-   reassigned (assignments to them raise :exc:`SyntaxError`), so they can be
-   considered "true" constants.
-
-.. XXX False, True, None are keywords too
-
 .. data:: False
 
    The false value of the :class:`bool` type. Assignments to ``False``
@@ -40,19 +31,23 @@
 
 .. data:: Ellipsis
 
-   The same as ``...``. Special value used mostly in conjunction with extended
-   slicing syntax for user-defined container data types, as in ::
-
-   .. XXX Someone who understands extended slicing should fill in here.
+   The same as ``...``.  Special value used mostly in conjunction with extended
+   slicing syntax for user-defined container data types.
 
 
 .. data:: __debug__
 
    This constant is true if Python was not started with an :option:`-O` option.
-   Assignments to :const:`__debug__` are illegal and raise a :exc:`SyntaxError`.
    See also the :keyword:`assert` statement.
 
 
+.. note::
+
+   The names :data:`None`, :data:`False`, :data:`True` and :data:`__debug__`
+   cannot be reassigned (assignments to them, even as an attribute name, raise
+   :exc:`SyntaxError`), so they can be considered "true" constants.
+
+
 Constants added by the :mod:`site` module
 -----------------------------------------
 

Modified: python/branches/py3k-dtoa/Doc/library/contextlib.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/contextlib.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/contextlib.rst	Sun Aug  8 12:41:24 2010
@@ -12,7 +12,7 @@
 Functions provided:
 
 
-.. function:: contextmanager(func)
+.. decorator:: contextmanager
 
    This function is a :term:`decorator` that can be used to define a factory
    function for :keyword:`with` statement context managers, without needing to
@@ -57,6 +57,7 @@
    .. versionchanged:: 3.2
       Use of :class:`ContextDecorator`.
 
+
 .. function:: closing(thing)
 
    Return a context manager that closes *thing* upon completion of the block.  This
@@ -92,22 +93,25 @@
    ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional
    exception handling even when used as a decorator.
 
-   Example::
+   ``ContextDecorator`` is used by :func:`contextmanager`, so you get this
+   functionality automatically.
+
+   Example of ``ContextDecorator``::
 
       from contextlib import ContextDecorator
 
       class mycontext(ContextDecorator):
-         def __enter__(self):
-            print('Starting')
-            return self
-
-         def __exit__(self, *exc):
-            print('Finishing')
-            return False
+          def __enter__(self):
+              print('Starting')
+              return self
+
+          def __exit__(self, *exc):
+              print('Finishing')
+              return False
 
       >>> @mycontext()
       ... def function():
-      ...    print('The bit in the middle')
+      ...     print('The bit in the middle')
       ...
       >>> function()
       Starting
@@ -115,23 +119,38 @@
       Finishing
 
       >>> with mycontext():
-      ...    print('The bit in the middle')
+      ...     print('The bit in the middle')
       ...
       Starting
       The bit in the middle
       Finishing
 
+   This change is just syntactic sugar for any construct of the following form::
+
+      def f():
+          with cm():
+              # Do stuff
+
+   ``ContextDecorator`` lets you instead write::
+
+      @cm()
+      def f():
+          # Do stuff
+
+   It makes it clear that the ``cm`` applies to the whole function, rather than
+   just a piece of it (and saving an indentation level is nice, too).
+
    Existing context managers that already have a base class can be extended by
    using ``ContextDecorator`` as a mixin class::
 
       from contextlib import ContextDecorator
 
       class mycontext(ContextBaseClass, ContextDecorator):
-         def __enter__(self):
-            return self
+          def __enter__(self):
+              return self
 
-         def __exit__(self, *exc):
-            return False
+          def __exit__(self, *exc):
+              return False
 
    .. versionadded:: 3.2
 

Modified: python/branches/py3k-dtoa/Doc/library/datetime.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/datetime.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/datetime.rst	Sun Aug  8 12:41:24 2010
@@ -265,6 +265,14 @@
 | ``abs(t)``                     | equivalent to +\ *t* when ``t.days >= 0``, and|
 |                                | to -*t* when ``t.days < 0``. (2)              |
 +--------------------------------+-----------------------------------------------+
+| ``str(t)``                     | Returns a string in the form                  |
+|                                | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D  |
+|                                | is negative for negative ``t``. (5)           |
++--------------------------------+-----------------------------------------------+
+| ``repr(t)``                    | Returns a string in the form                  |
+|                                | ``datetime.timedelta(D[, S[, U]])``, where D  |
+|                                | is negative for negative ``t``. (5)           |
++--------------------------------+-----------------------------------------------+
 
 Notes:
 
@@ -280,6 +288,16 @@
 (4)
    -*timedelta.max* is not representable as a :class:`timedelta` object.
 
+(5)
+  String representations of :class:`timedelta` objects are normalized
+  similarly to their internal representation.  This leads to somewhat
+  unusual results for negative timedeltas.  For example:
+
+  >>> timedelta(hours=-5)
+  datetime.timedelta(-1, 68400)
+  >>> print(_)
+  -1 day, 19:00:00
+
 In addition to the operations listed above :class:`timedelta` objects support
 certain additions and subtractions with :class:`date` and :class:`datetime`
 objects (see below).

Modified: python/branches/py3k-dtoa/Doc/library/dbm.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/dbm.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/dbm.rst	Sun Aug  8 12:41:24 2010
@@ -5,10 +5,10 @@
    :synopsis: Interfaces to various Unix "database" formats.
 
 :mod:`dbm` is a generic interface to variants of the DBM database ---
- :mod:`dbm.gnu` or :mod:`dbm.ndbm`.  If none of these modules is installed, the
- slow-but-simple implementation in module :mod:`dbm.dumb` will be used.  There
- is a `third party interface <http://www.jcea.es/programacion/pybsddb.htm>`_ to
- the Oracle Berkely DB.
+:mod:`dbm.gnu` or :mod:`dbm.ndbm`.  If none of these modules is installed, the
+slow-but-simple implementation in module :mod:`dbm.dumb` will be used.  There
+is a `third party interface <http://www.jcea.es/programacion/pybsddb.htm>`_ to
+the Oracle Berkeley DB.
 
 
 .. exception:: error
@@ -21,8 +21,8 @@
 .. function:: whichdb(filename)
 
    This functionattempts to guess which of the several simple database modules
-   available --- :mod:`dbm.bsd`, :mod:`dbm.gnu`, :mod:`dbm.ndbm` or
-   :mod:`dbm.dumb` --- should be used to open a given file.
+   available --- :mod:`dbm.gnu`, :mod:`dbm.ndbm` or :mod:`dbm.dumb` --- should
+   be used to open a given file.
 
    Returns one of the following values: ``None`` if the file can't be opened
    because it's unreadable or doesn't exist; the empty string (``''``) if the
@@ -227,10 +227,9 @@
 always stored as bytes. Printing a ``dbm`` object doesn't print the keys and
 values, and the :meth:`items` and :meth:`values` methods are not supported.
 
-This module can be used with the "classic" ndbm interface, the BSD DB
-compatibility interface, or the GNU GDBM compatibility interface. On Unix, the
-:program:`configure` script will attempt to locate the appropriate header file
-to simplify building this module.
+This module can be used with the "classic" ndbm interface or the GNU GDBM
+compatibility interface. On Unix, the :program:`configure` script will attempt
+to locate the appropriate header file to simplify building this module.
 
 .. exception:: error
 
@@ -246,9 +245,7 @@
 .. function:: open(filename[, flag[, mode]])
 
    Open a dbm database and return a ``dbm`` object.  The *filename* argument is the
-   name of the database file (without the :file:`.dir` or :file:`.pag` extensions;
-   note that the BSD DB implementation of the interface will append the extension
-   :file:`.db` and only create one file).
+   name of the database file (without the :file:`.dir` or :file:`.pag` extensions).
 
    The optional *flag* argument must be one of these values:
 

Modified: python/branches/py3k-dtoa/Doc/library/doctest.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/doctest.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/doctest.rst	Sun Aug  8 12:41:24 2010
@@ -913,18 +913,16 @@
 As your collection of doctest'ed modules grows, you'll want a way to run all
 their doctests systematically.  :mod:`doctest` provides two functions that can
 be used to create :mod:`unittest` test suites from modules and text files
-containing doctests.  These test suites can then be run using :mod:`unittest`
-test runners::
+containing doctests.  To integrate with :mod:`unittest` test discovery, include
+a :func:`load_tests` function in your test module::
 
    import unittest
    import doctest
-   import my_module_with_doctests, and_another
+   import my_module_with_doctests
 
-   suite = unittest.TestSuite()
-   for mod in my_module_with_doctests, and_another:
-       suite.addTest(doctest.DocTestSuite(mod))
-   runner = unittest.TextTestRunner()
-   runner.run(suite)
+   def load_tests(loader, tests, ignore):
+       tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
+       return test
 
 There are two main functions for creating :class:`unittest.TestSuite` instances
 from text files and modules with doctests:
@@ -1675,7 +1673,7 @@
 
 .. exception:: DocTestFailure(test, example, got)
 
-   An exception thrown by :class:`DocTestRunner` to signal that a doctest example's
+   An exception raised by :class:`DocTestRunner` to signal that a doctest example's
    actual output did not match its expected output. The constructor arguments are
    used to initialize the member variables of the same names.
 
@@ -1699,9 +1697,9 @@
 
 .. exception:: UnexpectedException(test, example, exc_info)
 
-   An exception thrown by :class:`DocTestRunner` to signal that a doctest example
-   raised an unexpected exception.  The constructor arguments are used to
-   initialize the member variables of the same names.
+   An exception raised by :class:`DocTestRunner` to signal that a doctest
+   example raised an unexpected exception.  The constructor arguments are used
+   to initialize the member variables of the same names.
 
 :exc:`UnexpectedException` defines the following member variables:
 

Modified: python/branches/py3k-dtoa/Doc/library/email.errors.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/email.errors.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/email.errors.rst	Sun Aug  8 12:41:24 2010
@@ -17,7 +17,7 @@
 
 .. exception:: MessageParseError()
 
-   This is the base class for exceptions thrown by the :class:`~email.parser.Parser`
+   This is the base class for exceptions raised by the :class:`~email.parser.Parser`
    class.  It is derived from :exc:`MessageError`.
 
 

Modified: python/branches/py3k-dtoa/Doc/library/fileinput.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/fileinput.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/fileinput.rst	Sun Aug  8 12:41:24 2010
@@ -24,7 +24,7 @@
 
 All files are opened in text mode by default, but you can override this by
 specifying the *mode* parameter in the call to :func:`.input` or
-:class:`FileInput()`.  If an I/O error occurs during opening or reading a file,
+:class:`FileInput`.  If an I/O error occurs during opening or reading a file,
 :exc:`IOError` is raised.
 
 If ``sys.stdin`` is used more than once, the second and further use will return
@@ -54,6 +54,16 @@
    during iteration.  The parameters to this function will be passed along to the
    constructor of the :class:`FileInput` class.
 
+   The :class:`FileInput` instance can be used as a context manager in the
+   :keyword:`with` statement.  In this example, *input* is closed after the
+   :keyword:`with` statement is exited, even if an exception occurs::
+
+      with fileinput.input(files=('spam.txt', 'eggs.txt')) as input:
+          process(input)
+
+   .. versionchanged:: 3.2
+      Can be used as a context manager.
+
 
 The following functions use the global state created by :func:`fileinput.input`;
 if there is no active state, :exc:`RuntimeError` is raised.
@@ -132,13 +142,23 @@
    *filename* and *mode*, and returns an accordingly opened file-like object. You
    cannot use *inplace* and *openhook* together.
 
-
-**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
-file of the same name as the backup file already exists, it will be replaced
-silently).  This makes it possible to write a filter that rewrites its input
-file in place.  If the *backup* parameter is given (typically as
+   A :class:`FileInput` instance can be used as a context manager in the
+   :keyword:`with` statement.  In this example, *input* is closed after the
+   :keyword:`with` statement is exited, even if an exception occurs::
+
+      with FileInput(files=('spam.txt', 'eggs.txt')) as input:
+          process(input)
+
+   .. versionchanged:: 3.2
+      Can be used as a context manager.
+
+
+**Optional in-place filtering:** if the keyword argument ``inplace=True`` 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 file of the same name as the backup file already exists, it will be
+replaced silently).  This makes it possible to write a filter that rewrites its
+input file in place.  If the *backup* parameter is given (typically as
 ``backup='.<some extension>'``), it specifies the extension for the backup file,
 and the backup file remains around; by default, the extension is ``'.bak'`` and
 it is deleted when the output file is closed.  In-place filtering is disabled

Modified: python/branches/py3k-dtoa/Doc/library/fnmatch.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/fnmatch.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/fnmatch.rst	Sun Aug  8 12:41:24 2010
@@ -70,6 +70,8 @@
 
    Return the shell-style *pattern* converted to a regular expression.
 
+   Be aware there is no way to quote meta-characters.
+
    Example:
 
       >>> import fnmatch, re
@@ -82,6 +84,13 @@
       <_sre.SRE_Match object at 0x...>
 
 
+.. function:: purge()
+
+   Clear the internal pattern cache.
+
+   .. versionadded:: 3.2
+
+
 .. seealso::
 
    Module :mod:`glob`

Modified: python/branches/py3k-dtoa/Doc/library/ftplib.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/ftplib.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/ftplib.rst	Sun Aug  8 12:41:24 2010
@@ -231,9 +231,9 @@
    Retrieve a file or directory listing in ASCII transfer mode.  *cmd*
    should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or a
    command such as ``LIST``, ``NLST`` or ``MLSD`` (usually just the string
-   ``'LIST'``).  The *callback* function is called for each line, with the
-   trailing CRLF stripped.  The default *callback* prints the line to
-   ``sys.stdout``.
+   ``'LIST'``).  The *callback* function is called for each line with a
+   string argument containing the line with the trailing CRLF stripped.
+   The default *callback* prints the line to ``sys.stdout``.
 
 
 .. method:: FTP.set_pasv(boolean)

Modified: python/branches/py3k-dtoa/Doc/library/functions.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/functions.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/functions.rst	Sun Aug  8 12:41:24 2010
@@ -335,6 +335,9 @@
    returns the current global and local dictionary, respectively, which may be
    useful to pass around for use by :func:`eval` or :func:`exec`.
 
+   See :func:`ast.literal_eval` for a function that can safely evaluate strings
+   with expressions containing only literals.
+
 
 .. function:: exec(object[, globals[, locals]])
 
@@ -676,7 +679,7 @@
    :meth:`__index__` method that returns an integer.
 
 
-.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
+.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
 
    Open *file* and return a corresponding stream.  If the file cannot be opened,
    an :exc:`IOError` is raised.
@@ -844,7 +847,7 @@
 
    *fget* is a function for getting an attribute value, likewise *fset* is a
    function for setting, and *fdel* a function for del'ing, an attribute.  Typical
-   use is to define a managed attribute x::
+   use is to define a managed attribute ``x``::
 
       class C(object):
           def __init__(self):
@@ -858,6 +861,9 @@
               del self._x
           x = property(getx, setx, delx, "I'm the 'x' property.")
 
+   If then *c* is an instance of *C*, ``c.x`` will invoke the getter,
+   ``c.x = value`` will invoke the setter and ``del c.x`` the deleter.
+
    If given, *doc* will be the docstring of the property attribute. Otherwise, the
    property will copy *fget*'s docstring (if it exists).  This makes it possible to
    create read-only properties easily using :func:`property` as a :term:`decorator`::
@@ -969,6 +975,13 @@
    The return value is an integer if called with one argument, otherwise of the
    same type as *x*.
 
+   .. note::
+
+      The behavior of :func:`round` for floats can be surprising: for example,
+      ``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``.
+      This is not a bug: it's a result of the fact that most decimal fractions
+      can't be represented exactly as a float.  See :ref:`tut-fp-issues` for
+      more information.
 
 .. function:: set([iterable])
    :noindex:

Modified: python/branches/py3k-dtoa/Doc/library/functools.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/functools.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/functools.rst	Sun Aug  8 12:41:24 2010
@@ -37,7 +37,61 @@
 
    .. versionadded:: 3.2
 
-.. function:: total_ordering(cls)
+.. decorator:: lfu_cache(maxsize)
+
+   Decorator to wrap a function with a memoizing callable that saves up to the
+   *maxsize* most frequent calls.  It can save time when an expensive or I/O
+   bound function is periodically called with the same arguments.
+
+   The *maxsize* parameter defaults to 100.  Since a dictionary is used to cache
+   results, the positional and keyword arguments to the function must be
+   hashable.
+
+   The wrapped function is instrumented with two attributes, :attr:`hits`
+   and :attr:`misses` which count the number of successful or unsuccessful
+   cache lookups.  These statistics are helpful for tuning the *maxsize*
+   parameter and for measuring the cache's effectiveness.
+
+   The wrapped function also has a :attr:`clear` attribute which can be
+   called (with no arguments) to clear the cache.
+
+   A `LFU (least frequently used) cache
+   <http://en.wikipedia.org/wiki/Cache_algorithms#Least-Frequently_Used>`_
+   is indicated when the pattern of calls does not change over time, when
+   more the most common calls already seen are the best predictors of the
+   most common upcoming calls (for example, a phonelist of popular
+   help-lines may have access patterns that persist over time).
+
+   .. versionadded:: 3.2
+
+.. decorator:: lru_cache(maxsize)
+
+   Decorator to wrap a function with a memoizing callable that saves up to the
+   *maxsize* most recent calls.  It can save time when an expensive or I/O bound
+   function is periodically called with the same arguments.
+
+   The *maxsize* parameter defaults to 100.  Since a dictionary is used to cache
+   results, the positional and keyword arguments to the function must be
+   hashable.
+
+   The wrapped function is instrumented with two attributes, :attr:`hits`
+   and :attr:`misses` which count the number of successful or unsuccessful
+   cache lookups.  These statistics are helpful for tuning the *maxsize*
+   parameter and for measuring the cache's effectiveness.
+
+   The wrapped function also has a :attr:`clear` attribute which can be
+   called (with no arguments) to clear the cache.
+
+   A `LRU (least recently used) cache
+   <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
+   is indicated when the pattern of calls changes over time, such as
+   when more recent calls are the best predictors of upcoming calls
+   (for example, the most popular articles on a news server tend to
+   change every day).
+
+   .. versionadded:: 3.2
+
+.. decorator:: total_ordering
 
    Given a class defining one or more rich comparison ordering methods, this
    class decorator supplies the rest.  This simplifies the effort involved
@@ -111,9 +165,9 @@
    attributes of the wrapper function are updated with the corresponding attributes
    from the original function. The default values for these arguments are the
    module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
-   function's *__name__*, *__module__* and *__doc__*, the documentation string) and
-   *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
-   instance dictionary).
+   function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
+   documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
+   function's *__dict__*, i.e. the instance dictionary).
 
    The main intended use for this function is in :term:`decorator` functions which
    wrap the decorated function and return the wrapper. If the wrapper function is
@@ -122,7 +176,7 @@
    than helpful.
 
 
-.. function:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
+.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
 
    This is a convenience function for invoking ``partial(update_wrapper,
    wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator

Modified: python/branches/py3k-dtoa/Doc/library/heapq.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/heapq.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/heapq.rst	Sun Aug  8 12:41:24 2010
@@ -6,6 +6,7 @@
 .. moduleauthor:: Kevin O'Connor
 .. sectionauthor:: Guido van Rossum <guido at python.org>
 .. sectionauthor:: François Pinard
+.. sectionauthor:: Raymond Hettinger
 
 This module provides an implementation of the heap queue algorithm, also known
 as the priority queue algorithm.
@@ -138,6 +139,67 @@
 functions.
 
 
+Priority Queue Implementation Notes
+-----------------------------------
+
+A `priority queue <http://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
+  in the order they were originally added?
+
+* Tuple comparison breaks for (priority, task) pairs if the priorities are equal
+  and the tasks do not have a default comparison order.
+
+* If the priority of a task changes, how do you move it to a new position in
+  the heap?
+
+* Or if a pending task needs to be deleted, how do you find it and remove it
+  from the queue?
+
+A solution to the first two challenges is to store entries as 3-element list
+including the priority, an entry count, and the task.  The entry count serves as
+a tie-breaker so that two tasks with the same priority are returned in the order
+they were added. And since no two entry counts are the same, the tuple
+comparison will never attempt to directly compare two tasks.
+
+The remaining challenges revolve around finding a pending task and making
+changes to its priority or removing it entirely.  Finding a task can be done
+with a dictionary pointing to an entry in the queue.
+
+Removing the entry or changing its priority is more difficult because it would
+break the heap structure invariants.  So, a possible solution is to mark an
+entry as invalid and optionally add a new entry with the revised priority::
+
+    pq = []                         # the priority queue list
+    counter = itertools.count(1)    # unique sequence count
+    task_finder = {}                # mapping of tasks to entries
+    INVALID = 0                     # mark an entry as deleted
+
+    def add_task(priority, task, count=None):
+        if count is None:
+            count = next(counter)
+        entry = [priority, count, task]
+        task_finder[task] = entry
+        heappush(pq, entry)
+
+    def get_top_priority():
+        while True:
+            priority, count, task = heappop(pq)
+            del task_finder[task]
+            if count is not INVALID:
+                return task
+
+    def delete_task(task):
+        entry = task_finder[task]
+        entry[1] = INVALID
+
+    def reprioritize(priority, task):
+        entry = task_finder[task]
+        add_task(priority, task, entry[1])
+        entry[1] = INVALID
+
+
 Theory
 ------
 

Modified: python/branches/py3k-dtoa/Doc/library/html.parser.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/html.parser.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/html.parser.rst	Sun Aug  8 12:41:24 2010
@@ -134,10 +134,18 @@
 
 .. method:: HTMLParser.handle_decl(decl)
 
-   Method called when an SGML declaration is read by the parser.  The *decl*
-   parameter will be the entire contents of the declaration inside the ``<!``...\
-   ``>`` markup.  It is intended to be overridden by a derived class; the base
-   class implementation does nothing.
+   Method called when an SGML ``doctype`` declaration is read by the parser.
+   The *decl* parameter will be the entire contents of the declaration inside
+   the ``<!...>`` markup.  It is intended to be overridden by a derived class;
+   the base class implementation does nothing.
+
+
+.. method:: HTMLParser.unknown_decl(data)
+
+   Method called when an unrecognized SGML declaration is read by the parser.
+   The *data* parameter will be the entire contents of the declaration inside
+   the ``<!...>`` markup.  It is sometimes useful to be be overridden by a
+   derived class; the base class implementation raises an :exc:`HTMLParseError`.
 
 
 .. method:: HTMLParser.handle_pi(data)

Modified: python/branches/py3k-dtoa/Doc/library/http.client.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/http.client.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/http.client.rst	Sun Aug  8 12:41:24 2010
@@ -465,8 +465,10 @@
 
 .. method:: HTTPResponse.getheader(name, default=None)
 
-   Get the contents of the header *name*, or *default* if there is no matching
-   header.
+   Return the value of the header *name*, or *default* if there is no header
+   matching *name*.  If there is more than one  header with the name *name*,
+   return all of the values joined by ', '.  If 'default' is any iterable other
+   than a single string, its elements are similarly returned joined by commas.
 
 
 .. method:: HTTPResponse.getheaders()

Modified: python/branches/py3k-dtoa/Doc/library/http.cookiejar.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/http.cookiejar.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/http.cookiejar.rst	Sun Aug  8 12:41:24 2010
@@ -108,10 +108,6 @@
       :mod:`http.cookiejar` and :mod:`http.cookies` modules do not depend on each
       other.
 
-   http://wwwsearch.sourceforge.net/mechanize/
-      Extensions to this module, including a class for reading Microsoft Internet
-      Explorer cookies on Windows.
-
    http://wp.netscape.com/newsref/std/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
@@ -292,11 +288,8 @@
 FileCookieJar subclasses and co-operation with web browsers
 -----------------------------------------------------------
 
-The following :class:`CookieJar` subclasses are provided for reading and writing
-.  Further :class:`CookieJar` subclasses, including one that reads Microsoft
-Internet Explorer cookies, are available at
-http://wwwsearch.sourceforge.net/mechanize/.
-
+The following :class:`CookieJar` subclasses are provided for reading and
+writing .
 
 .. class:: MozillaCookieJar(filename, delayload=None, policy=None)
 

Modified: python/branches/py3k-dtoa/Doc/library/importlib.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/importlib.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/importlib.rst	Sun Aug  8 12:41:24 2010
@@ -228,7 +228,7 @@
 
     * :meth:`ResourceLoader.get_data`
     * :meth:`ExecutionLoader.get_filename`
-          Implement to only return the path to the source file; sourceless
+          Should only return the path to the source file; sourceless
           loading is not supported.
 
     The abstract methods defined by this class are to add optional bytecode
@@ -469,7 +469,7 @@
 This module contains the various objects that help in the construction of
 an :term:`importer`.
 
-.. function:: module_for_loader(method)
+.. decorator:: module_for_loader
 
     A :term:`decorator` for a :term:`loader` method,
     to handle selecting the proper
@@ -494,7 +494,7 @@
     Use of this decorator handles all the details of which module object a
     loader should initialize as specified by :pep:`302`.
 
-.. function:: set_loader(fxn)
+.. decorator:: set_loader
 
     A :term:`decorator` for a :term:`loader` method,
     to set the :attr:`__loader__`
@@ -502,7 +502,7 @@
     does nothing. It is assumed that the first positional argument to the
     wrapped method is what :attr:`__loader__` should be set to.
 
-.. function:: set_package(fxn)
+.. decorator:: set_package
 
     A :term:`decorator` for a :term:`loader` to set the :attr:`__package__`
     attribute on the module returned by the loader. If :attr:`__package__` is

Modified: python/branches/py3k-dtoa/Doc/library/io.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/io.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/io.rst	Sun Aug  8 12:41:24 2010
@@ -17,7 +17,7 @@
 At the top of the I/O hierarchy is the abstract base class :class:`IOBase`.  It
 defines the basic interface to a stream.  Note, however, that there is no
 separation between reading and writing to streams; implementations are allowed
-to throw an :exc:`IOError` if they do not support a given operation.
+to raise an :exc:`IOError` if they do not support a given operation.
 
 Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
 reading and writing of raw bytes to a stream.  :class:`FileIO` subclasses
@@ -61,8 +61,8 @@
    Open *file* and return a corresponding stream.  If the file cannot be opened,
    an :exc:`IOError` is raised.
 
-   *file* is either a string or bytes object giving the name (and the path if
-   the file isn't in the current working directory) of the file to be opened or
+   *file* is either a string or bytes object giving the pathname (absolute or
+   relative to the current working directory) of the file to be opened or
    an integer file descriptor of the file to be wrapped.  (If a file descriptor
    is given, it is closed when the returned I/O object is closed, unless
    *closefd* is set to ``False``.)

Modified: python/branches/py3k-dtoa/Doc/library/itertools.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/itertools.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/itertools.rst	Sun Aug  8 12:41:24 2010
@@ -99,7 +99,7 @@
                   yield element
 
 
-.. function:: itertools.chain.from_iterable(iterable)
+.. classmethod:: chain.from_iterable(iterable)
 
    Alternate constructor for :func:`chain`.  Gets chained inputs from a
    single iterable argument that is evaluated lazily.  Equivalent to::
@@ -653,6 +653,12 @@
                pending -= 1
                nexts = cycle(islice(nexts, pending))
 
+   def partition(pred, iterable):
+       'Use a predicate to partition entries into false entries and true entries'
+       # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
+       t1, t2 = tee(iterable)
+       return filterfalse(pred, t1), filter(pred, t2)
+
    def powerset(iterable):
        "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
        s = list(iterable)

Modified: python/branches/py3k-dtoa/Doc/library/linecache.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/linecache.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/linecache.rst	Sun Aug  8 12:41:24 2010
@@ -16,7 +16,7 @@
 
 .. function:: getline(filename, lineno, module_globals=None)
 
-   Get line *lineno* from file named *filename*. This function will never throw an
+   Get line *lineno* from file named *filename*. This function will never raise an
    exception --- it will return ``''`` on errors (the terminating newline character
    will be included for lines that are found).
 

Modified: python/branches/py3k-dtoa/Doc/library/locale.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/locale.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/locale.rst	Sun Aug  8 12:41:24 2010
@@ -244,10 +244,6 @@
       specified, and therefore you should not assume knowledge of it on different
       systems.
 
-   .. data:: ERA_YEAR
-
-      Get the year in the relevant era of the locale.
-
    .. data:: ERA_D_T_FMT
 
       Get a format string for :func:`strftime` to represent dates and times in a

Modified: python/branches/py3k-dtoa/Doc/library/math.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/math.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/math.rst	Sun Aug  8 12:41:24 2010
@@ -97,15 +97,23 @@
    <http://code.activestate.com/recipes/393090/>`_\.
 
 
+.. function:: isfinite(x)
+
+   Return ``True`` if *x* is neither an infinity nor a NaN, and
+   ``False`` otherwise.  (Note that ``0.0`` *is* considered finite.)
+
+   .. versionadded:: 3.2
+
+
 .. function:: isinf(x)
 
-   Check if the float *x* is positive or negative infinity.
+   Return ``True`` if *x* is a positive or negative infinity, and
+   ``False`` otherwise.
 
 
 .. function:: isnan(x)
 
-   Check if the float *x* is a NaN (not a number).  For more information
-   on NaNs, see the IEEE 754 standards.
+   Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise.
 
 
 .. function:: ldexp(x, i)

Modified: python/branches/py3k-dtoa/Doc/library/mmap.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/mmap.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/mmap.rst	Sun Aug  8 12:41:24 2010
@@ -112,6 +112,18 @@
           map.close()
 
 
+   :class:`mmap` can also be used as a context manager in a :keyword:`with`
+   statement.::
+
+      import mmap
+
+      with mmap.mmap(-1, 13) as map:
+          map.write("Hello world!")
+
+   .. versionadded:: 3.2
+      Context manager support.
+
+
    The next example demonstrates how to create an anonymous map and exchange
    data between the parent and child processes::
 
@@ -132,13 +144,19 @@
 
    Memory-mapped file objects support the following methods:
 
-
    .. method:: close()
 
       Close the file.  Subsequent calls to other methods of the object will
       result in an exception being raised.
 
 
+   .. attribute:: closed
+
+      True if the file is closed.
+
+      .. versionadded:: 3.2
+
+
    .. method:: find(sub[, start[, end]])
 
       Returns the lowest index in the object where the subsequence *sub* is
@@ -166,7 +184,7 @@
 
       Copy the *count* bytes starting at offset *src* to the destination index
       *dest*.  If the mmap was created with :const:`ACCESS_READ`, then calls to
-      move will throw a :exc:`TypeError` exception.
+      move will raise a :exc:`TypeError` exception.
 
 
    .. method:: read(num)
@@ -192,7 +210,7 @@
 
       Resizes the map and the underlying file, if any. If the mmap was created
       with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
-      throw a :exc:`TypeError` exception.
+      raise a :exc:`TypeError` exception.
 
 
    .. method:: rfind(sub[, start[, end]])
@@ -227,7 +245,7 @@
       Write the bytes in *bytes* into memory at the current position of the
       file pointer; the file position is updated to point after the bytes that
       were written. If the mmap was created with :const:`ACCESS_READ`, then
-      writing to it will throw a :exc:`TypeError` exception.
+      writing to it will raise a :exc:`TypeError` exception.
 
 
    .. method:: write_byte(byte)
@@ -235,6 +253,4 @@
       Write the the integer *byte* into memory at the current
       position of the file pointer; the file position is advanced by ``1``. If
       the mmap was created with :const:`ACCESS_READ`, then writing to it will
-      throw a :exc:`TypeError` exception.
-
-
+      raise a :exc:`TypeError` exception.

Modified: python/branches/py3k-dtoa/Doc/library/multiprocessing.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/multiprocessing.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/multiprocessing.rst	Sun Aug  8 12:41:24 2010
@@ -2228,8 +2228,8 @@
 
 
 An example of how a pool of worker processes can each run a
-:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
-socket.
+:class:`~http.server.SimpleHTTPRequestHandler` instance while sharing a single
+listening socket.
 
 .. literalinclude:: ../includes/mp_webserver.py
 

Modified: python/branches/py3k-dtoa/Doc/library/optparse.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/optparse.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/optparse.rst	Sun Aug  8 12:41:24 2010
@@ -1234,8 +1234,9 @@
    the list of arguments to process (default: ``sys.argv[1:]``)
 
 ``values``
-   object to store option arguments in (default: a new instance of
-   :class:`optparse.Values`)
+   a :class:`optparse.Values` object to store option arguments in (default: a
+   new instance of :class:`Values`) -- if you give an existing object, the
+   option defaults will not be initialized on it
 
 and the return values are
 

Modified: python/branches/py3k-dtoa/Doc/library/os.path.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/os.path.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/os.path.rst	Sun Aug  8 12:41:24 2010
@@ -207,7 +207,9 @@
 .. function:: normpath(path)
 
    Normalize a pathname.  This collapses redundant separators and up-level
-   references so that ``A//B``, ``A/./B`` and ``A/foo/../B`` all become ``A/B``.
+   references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all become
+   ``A/B``.
+
    It does not normalize the case (use :func:`normcase` for that).  On Windows, it
    converts forward slashes to backward slashes. It should be understood that this
    may change the meaning of the path if it contains symbolic links!
@@ -231,11 +233,18 @@
 
 .. function:: samefile(path1, path2)
 
-   Return ``True`` if both pathname arguments refer to the same file or directory
-   (as indicated by device number and i-node number). Raise an exception if a
-   :func:`os.stat` call on either pathname fails.
+   Return ``True`` if both pathname arguments refer to the same file or directory.
+   On Unix, this is determined by the device number and i-node number and raises an
+   exception if a :func:`os.stat` call on either pathname fails.
+
+   On Windows, two files are the same if they resolve to the same final path
+   name using the Windows API call GetFinalPathNameByHandle. This function
+   raises an exception if handles cannot be obtained to either file.
 
-   Availability: Unix.
+   Availability: Windows, Unix.
+
+   .. versionchanged:: 3.2
+      Added Windows support.
 
 
 .. function:: sameopenfile(fp1, fp2)

Modified: python/branches/py3k-dtoa/Doc/library/os.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/os.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/os.rst	Sun Aug  8 12:41:24 2010
@@ -723,7 +723,7 @@
 
       This function is intended for low-level I/O.  For normal usage, use the
       built-in function :func:`open`, which returns a "file object" with
-      :meth:`~file.read` and :meth:`~file.wprite` methods (and many more).  To
+      :meth:`~file.read` and :meth:`~file.write` methods (and many more).  To
       wrap a file descriptor in a "file object", use :func:`fdopen`.
 
 
@@ -1049,10 +1049,10 @@
    Availability: Unix.
 
 
-.. function:: listdir(path)
+.. function:: listdir(path='.')
 
    Return a list containing the names of the entries in the directory given by
-   *path*.  The list is in arbitrary order.  It does not include the special
+   *path* (default: ``'.'``).  The list is in arbitrary order.  It does not include the special
    entries ``'.'`` and ``'..'`` even if they are present in the directory.
 
    This function can be called with a bytes or string argument, and returns
@@ -1060,12 +1060,16 @@
 
    Availability: Unix, Windows.
 
+   .. versionchanged:: 3.2
+      The *path* parameter became optional.
 
 .. function:: lstat(path)
 
    Like :func:`stat`, but do not follow symbolic links.  This is an alias for
-   :func:`stat` on platforms that do not support symbolic links, such as
-   Windows.
+   :func:`stat` on platforms that do not support symbolic links.
+
+   .. versionchanged:: 3.2
+      Added support for Windows 6.0 (Vista) symbolic links.
 
 
 .. function:: mkfifo(path[, mode])
@@ -1181,7 +1185,10 @@
    and the call may raise an UnicodeDecodeError. If the *path* is a bytes
    object, the result will be a bytes object.
 
-   Availability: Unix.
+   Availability: Unix, Windows
+
+   .. versionchanged:: 3.2
+      Added support for Windows 6.0 (Vista) symbolic links.
 
 
 .. function:: remove(path)
@@ -1343,7 +1350,27 @@
 
    Create a symbolic link pointing to *source* named *link_name*.
 
-   Availability: Unix.
+   On Windows, symlink version takes an additional, optional parameter,
+   *target_is_directory*, which defaults to False.
+
+   symlink(source, link_name, target_is_directory=False)
+
+   On Windows, a symlink represents a file or a directory, and does not
+   morph to the target dynamically.  For this reason, when creating a
+   symlink on Windows, if the target is not already present, the symlink
+   will default to being a file symlink.  If *target_is_directory* is set to
+   True, the symlink will be created as a directory symlink.  This
+   parameter is ignored if the target exists (and the symlink is created
+   with the same type as the target).
+
+   Symbolic link support was introduced in Windows 6.0 (Vista). *symlink*
+   will raise a NotImplementedError on Windows versions earlier than 6.0. The
+   SeCreateSymbolicLinkPrivilege is required in order to create symlinks.
+
+   Availability:  Unix, Windows
+
+   .. versionchanged:: 3.2
+      Added support for Windows 6.0 (Vista) symbolic links.
 
 
 .. function:: unlink(path)
@@ -1896,8 +1923,9 @@
 
    The :mod:`subprocess` module provides more powerful facilities for spawning new
    processes and retrieving their results; using that module is preferable to using
-   this function.  Use the :mod:`subprocess` module.  Check especially the
-   :ref:`subprocess-replacements` section.
+   this function.  See the
+   :ref:`subprocess-replacements` section in the :mod:`subprocess` documentation
+   for some helpful recipes.
 
    Availability: Unix, Windows.
 

Modified: python/branches/py3k-dtoa/Doc/library/parser.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/parser.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/parser.rst	Sun Aug  8 12:41:24 2010
@@ -114,7 +114,7 @@
    The :func:`expr` function parses the parameter *source* as if it were an input
    to ``compile(source, 'file.py', 'eval')``.  If the parse succeeds, an ST object
    is created to hold the internal parse tree representation, otherwise an
-   appropriate exception is thrown.
+   appropriate exception is raised.
 
 
 .. function:: suite(source)
@@ -122,7 +122,7 @@
    The :func:`suite` function parses the parameter *source* as if it were an input
    to ``compile(source, 'file.py', 'exec')``.  If the parse succeeds, an ST object
    is created to hold the internal parse tree representation, otherwise an
-   appropriate exception is thrown.
+   appropriate exception is raised.
 
 
 .. function:: sequence2st(sequence)
@@ -132,9 +132,9 @@
    to the Python grammar and all nodes are valid node types in the host version of
    Python, an ST object is created from the internal representation and returned
    to the called.  If there is a problem creating the internal representation, or
-   if the tree cannot be validated, a :exc:`ParserError` exception is thrown.  An
+   if the tree cannot be validated, a :exc:`ParserError` exception is raised.  An
    ST object created this way should not be assumed to compile correctly; normal
-   exceptions thrown by compilation may still be initiated when the ST object is
+   exceptions raised by compilation may still be initiated when the ST object is
    passed to :func:`compilest`.  This may indicate problems not related to syntax
    (such as a :exc:`MemoryError` exception), but may also be due to constructs such
    as the result of parsing ``del f(0)``, which escapes the Python parser but is
@@ -259,8 +259,8 @@
 .. exception:: ParserError
 
    Exception raised when a failure occurs within the parser module.  This is
-   generally produced for validation failures rather than the built in
-   :exc:`SyntaxError` thrown during normal parsing. The exception argument is
+   generally produced for validation failures rather than the built-in
+   :exc:`SyntaxError` raised during normal parsing. The exception argument is
    either a string describing the reason of the failure or a tuple containing a
    sequence causing the failure from a parse tree passed to :func:`sequence2st`
    and an explanatory string.  Calls to :func:`sequence2st` need to be able to
@@ -268,7 +268,7 @@
    will only need to be aware of the simple string values.
 
 Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may
-throw exceptions which are normally thrown by the parsing and compilation
+raise exceptions which are normally thrown by the parsing and compilation
 process.  These include the built in exceptions :exc:`MemoryError`,
 :exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`.  In these
 cases, these exceptions carry all the meaning normally associated with them.

Modified: python/branches/py3k-dtoa/Doc/library/pdb.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/pdb.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/pdb.rst	Sun Aug  8 12:41:24 2010
@@ -20,7 +20,7 @@
    module: bdb
    module: cmd
 
-The debugger is extensible --- it is actually defined as the class :class:`Pdb`.
+The debugger is extensible -- it is actually defined as the class :class:`Pdb`.
 This is currently undocumented but easily understood by reading the source.  The
 extension interface uses the modules :mod:`bdb` and :mod:`cmd`.
 
@@ -44,19 +44,23 @@
    python3 -m pdb myscript.py
 
 When invoked as a script, pdb will automatically enter post-mortem debugging if
-the program being debugged exits abnormally. After post-mortem debugging (or
-after normal exit of the program), pdb will restart the program. Automatic
+the program being debugged exits abnormally.  After post-mortem debugging (or
+after normal exit of the program), pdb will restart the program.  Automatic
 restarting preserves pdb's state (such as breakpoints) and in most cases is more
 useful than quitting the debugger upon program's exit.
 
+.. versionadded:: 3.2
+   :file:`pdb.py` now accepts a ``-c`` option that executes commands as if given
+   in a :file:`.pdbrc` file, see :ref:`debugger-commands`.
+
 The typical usage to break into the debugger from a running program is to
 insert ::
 
    import pdb; pdb.set_trace()
 
 at the location you want to break into the debugger.  You can then step through
-the code following this statement, and continue running without the debugger using
-the ``c`` command.
+the code following this statement, and continue running without the debugger
+using the :pdbcmd:`continue` command.
 
 The typical usage to inspect a crashed program is::
 
@@ -81,27 +85,29 @@
 
 .. function:: run(statement, globals=None, locals=None)
 
-   Execute the *statement* (given as a string) under debugger control.  The
-   debugger prompt appears before any code is executed; you can set breakpoints and
-   type ``continue``, or you can step through the statement using ``step`` or
-   ``next`` (all these commands are explained below).  The optional *globals* and
-   *locals* arguments specify the environment in which the code is executed; by
-   default the dictionary of the module :mod:`__main__` is used.  (See the
-   explanation of the built-in :func:`exec` or :func:`eval` functions.)
+   Execute the *statement* (given as a string or a code object) under debugger
+   control.  The debugger prompt appears before any code is executed; you can
+   set breakpoints and type :pdbcmd:`continue`, or you can step through the
+   statement using :pdbcmd:`step` or :pdbcmd:`next` (all these commands are
+   explained below).  The optional *globals* and *locals* arguments specify the
+   environment in which the code is executed; by default the dictionary of the
+   module :mod:`__main__` is used.  (See the explanation of the built-in
+   :func:`exec` or :func:`eval` functions.)
 
 
 .. function:: runeval(expression, globals=None, locals=None)
 
-   Evaluate the *expression* (given as a string) under debugger control.  When
-   :func:`runeval` returns, it returns the value of the expression.  Otherwise this
-   function is similar to :func:`run`.
+   Evaluate the *expression* (given as a string or a code object) under debugger
+   control.  When :func:`runeval` returns, it returns the value of the
+   expression.  Otherwise this function is similar to :func:`run`.
 
 
 .. function:: runcall(function, *args, **kwds)
 
-   Call the *function* (a function or method object, not a string) with the given
-   arguments.  When :func:`runcall` returns, it returns whatever the function call
-   returned.  The debugger prompt appears as soon as the function is entered.
+   Call the *function* (a function or method object, not a string) with the
+   given arguments.  When :func:`runcall` returns, it returns whatever the
+   function call returned.  The debugger prompt appears as soon as the function
+   is entered.
 
 
 .. function:: set_trace()
@@ -160,16 +166,17 @@
 Debugger Commands
 =================
 
-The debugger recognizes the following commands.  Most commands can be
-abbreviated to one or two letters; e.g. ``h(elp)`` means that either ``h`` or
-``help`` can be used to enter the help command (but not ``he`` or ``hel``, nor
-``H`` or ``Help`` or ``HELP``).  Arguments to commands must be separated by
-whitespace (spaces or tabs).  Optional arguments are enclosed in square brackets
-(``[]``) in the command syntax; the square brackets must not be typed.
-Alternatives in the command syntax are separated by a vertical bar (``|``).
+The commands recognized by the debugger are listed below.  Most commands can be
+abbreviated to one or two letters as indicated; e.g. ``h(elp)`` means that
+either ``h`` or ``help`` can be used to enter the help command (but not ``he``
+or ``hel``, nor ``H`` or ``Help`` or ``HELP``).  Arguments to commands must be
+separated by whitespace (spaces or tabs).  Optional arguments are enclosed in
+square brackets (``[]``) in the command syntax; the square brackets must not be
+typed.  Alternatives in the command syntax are separated by a vertical bar
+(``|``).
 
 Entering a blank line repeats the last command entered.  Exception: if the last
-command was a ``list`` command, the next 11 lines are listed.
+command was a :pdbcmd:`list` command, the next 11 lines are listed.
 
 Commands that the debugger doesn't recognize are assumed to be Python statements
 and are executed in the context of the program being debugged.  Python
@@ -179,93 +186,111 @@
 statement, the exception name is printed but the debugger's state is not
 changed.
 
+The debugger supports :ref:`aliases <debugger-aliases>`.  Aliases can have
+parameters which allows one a certain level of adaptability to the context under
+examination.
+
 Multiple commands may be entered on a single line, separated by ``;;``.  (A
 single ``;`` is not used as it is the separator for multiple commands in a line
-that is passed to the Python parser.) No intelligence is applied to separating
+that is passed to the Python parser.)  No intelligence is applied to separating
 the commands; the input is split at the first ``;;`` pair, even if it is in the
 middle of a quoted string.
 
-The debugger supports aliases.  Aliases can have parameters which allows one a
-certain level of adaptability to the context under examination.
-
 .. index::
    pair: .pdbrc; file
    triple: debugger; configuration; file
 
-If a file :file:`.pdbrc`  exists in the user's home directory or in the current
+If a file :file:`.pdbrc` exists in the user's 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
+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 overridden
 by the local file.
 
-h(elp) [*command*]
+.. versionchanged:: 3.2
+   :file:`.pdbrc` can now contain commands that continue debugging, such as
+   :pdbcmd:`continue` or :pdbcmd:`next`.  Previously, these commands had no
+   effect.
+
+
+.. pdbcommand:: h(elp) [command]
+
    Without argument, print the list of available commands.  With a *command* as
    argument, print help about that command.  ``help pdb`` displays the full
-   documentation file; if the environment variable :envvar:`PAGER` is defined, the
-   file is piped through that command instead.  Since the *command* argument must
-   be an identifier, ``help exec`` must be entered to get help on the ``!``
-   command.
+   documentation (the docstring of the :mod:`pdb` module).  Since the *command*
+   argument must be an identifier, ``help exec`` must be entered to get help on
+   the ``!`` command.
+
+.. pdbcommand:: w(here)
 
-w(here)
    Print a stack trace, with the most recent frame at the bottom.  An arrow
    indicates the current frame, which determines the context of most commands.
 
-d(own) [*count*]
+.. pdbcommand:: d(own) [count]
+
    Move the current frame *count* (default one) levels down in the stack trace
    (to a newer frame).
 
-u(p) [*count*]
-   Move the current frame *count* (default one) levels up in the stack trace
-   (to an older frame).
+.. pdbcommand:: u(p) [count]
+
+   Move the current frame *count* (default one) levels up in the stack trace (to
+   an older frame).
+
+.. pdbcommand:: b(reak) [([filename:]lineno | function) [, condition]]
 
-b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
    With a *lineno* argument, set a break there in the current file.  With a
-   *function* argument, set a break at the first executable statement within that
-   function. The line number may be prefixed with a filename and a colon, to
-   specify a breakpoint in another file (probably one that hasn't been loaded yet).
-   The file is searched on ``sys.path``. Note that each breakpoint is assigned a
-   number to which all the other breakpoint commands refer.
-
-   If a second argument is present, it is an expression which must evaluate to true
-   before the breakpoint is honored.
-
-   Without argument, list all breaks, including for each breakpoint, the number of
-   times that breakpoint has been hit, the current ignore count, and the associated
-   condition if any.
-
-tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
-   Temporary breakpoint, which is removed automatically when it is first hit.  The
-   arguments are the same as break.
+   *function* argument, set a break at the first executable statement within
+   that function.  The line number may be prefixed with a filename and a colon,
+   to specify a breakpoint in another file (probably one that hasn't been loaded
+   yet).  The file is searched on :data:`sys.path`.  Note that each breakpoint
+   is assigned a number to which all the other breakpoint commands refer.
+
+   If a second argument is present, it is an expression which must evaluate to
+   true before the breakpoint is honored.
+
+   Without argument, list all breaks, including for each breakpoint, the number
+   of times that breakpoint has been hit, the current ignore count, and the
+   associated condition if any.
+
+.. pdbcommand:: tbreak [([filename:]lineno | function) [, condition]]
+
+   Temporary breakpoint, which is removed automatically when it is first hit.
+   The arguments are the same as for :pdbcmd:`break`.
+
+.. pdbcommand:: cl(ear) [bpnumber [bpnumber ...]]
 
-cl(ear) [*bpnumber* [*bpnumber ...*]]
    With a space separated list of breakpoint numbers, clear those breakpoints.
    Without argument, clear all breaks (but first ask confirmation).
 
-disable [*bpnumber* [*bpnumber ...*]]
-   Disables the breakpoints given as a space separated list of breakpoint numbers.
-   Disabling a breakpoint means it cannot cause the program to stop execution, but
-   unlike clearing a breakpoint, it remains in the list of breakpoints and can be
-   (re-)enabled.
-
-enable [*bpnumber* [*bpnumber ...*]]
-   Enables the breakpoints specified.
-
-ignore *bpnumber* [*count*]
-   Sets the ignore count for the given breakpoint number.  If count is omitted, the
-   ignore count is set to 0.  A breakpoint becomes active when the ignore count is
-   zero.  When non-zero, the count is decremented each time the breakpoint is
-   reached and the breakpoint is not disabled and any associated condition
-   evaluates to true.
-
-condition *bpnumber* [*condition*]
-   Condition is an expression which must evaluate to true before the breakpoint is
-   honored.  If condition is absent, any existing condition is removed; i.e., the
-   breakpoint is made unconditional.
+.. pdbcommand:: disable [bpnumber [bpnumber ...]]
+
+   Disable the breakpoints given as a space separated list of breakpoint
+   numbers.  Disabling a breakpoint means it cannot cause the program to stop
+   execution, but unlike clearing a breakpoint, it remains in the list of
+   breakpoints and can be (re-)enabled.
+
+.. pdbcommand:: enable [bpnumber [bpnumber ...]]
+
+   Enable the breakpoints specified.
+
+.. pdbcommand:: ignore bpnumber [count]
+
+   Set the ignore count for the given breakpoint number.  If count is omitted,
+   the ignore count is set to 0.  A breakpoint becomes active when the ignore
+   count is zero.  When non-zero, the count is decremented each time the
+   breakpoint is reached and the breakpoint is not disabled and any associated
+   condition evaluates to true.
+
+.. pdbcommand:: condition bpnumber [condition]
+
+   Set a new *condition* for the breakpoint, an expression which must evaluate
+   to true before the breakpoint is honored.  If *condition* is absent, any
+   existing condition is removed; i.e., the breakpoint is made unconditional.
+
+.. pdbcommand:: commands [bpnumber]
 
-commands [*bpnumber*]
    Specify a list of commands for breakpoint number *bpnumber*.  The commands
-   themselves appear on the following lines.  Type a line containing just 'end' to
-   terminate the commands. An example::
+   themselves appear on the following lines.  Type a line containing just
+   ``end`` to terminate the commands. An example::
 
       (Pdb) commands 1
       (com) print some_variable
@@ -273,12 +298,12 @@
       (Pdb)
 
    To remove all commands from a breakpoint, type commands and follow it
-   immediately with  end; that is, give no commands.
+   immediately with ``end``; that is, give no commands.
 
    With no *bpnumber* argument, commands refers to the last breakpoint set.
 
-   You can use breakpoint commands to start your program up again. Simply use the
-   continue command, or step, or any other command that resumes execution.
+   You can use breakpoint commands to start your program up again.  Simply use
+   the continue command, or step, or any other command that resumes execution.
 
    Specifying any command resuming execution (currently continue, step, next,
    return, jump, quit and their abbreviations) terminates the command list (as if
@@ -292,91 +317,145 @@
    that are to print a specific message and then continue.  If none of the other
    commands print anything, you see no sign that the breakpoint was reached.
 
-s(tep)
+.. pdbcommand:: s(tep)
+
    Execute the current line, stop at the first possible occasion (either in a
    function that is called or on the next line in the current function).
 
-n(ext)
-   Continue execution until the next line in the current function is reached or it
-   returns.  (The difference between ``next`` and ``step`` is that ``step`` stops
-   inside a called function, while ``next`` executes called functions at (nearly)
-   full speed, only stopping at the next line in the current function.)
-
-unt(il)
-   Continue execution until the line with the line number greater than the
-   current one is reached or when returning from current frame.
+.. pdbcommand:: n(ext)
+
+   Continue execution until the next line in the current function is reached or
+   it returns.  (The difference between :pdbcmd:`next` and :pdbcmd:`step` is
+   that :pdbcmd:`step` stops inside a called function, while :pdbcmd:`next`
+   executes called functions at (nearly) full speed, only stopping at the next
+   line in the current function.)
+
+.. pdbcommand:: unt(il) [lineno]
+
+   Without argument, continue execution until the line with a number greater
+   than the current one is reached.
+
+   With a line number, continue execution until a line with a number greater or
+   equal to that is reached.  In both cases, also stop when the current frame
+   returns.
+
+   .. versionchanged:: 3.2
+      Allow giving an explicit line number.
+
+.. pdbcommand:: r(eturn)
 
-r(eturn)
    Continue execution until the current function returns.
 
-c(ont(inue))
+.. pdbcommand:: c(ont(inue))
+
    Continue execution, only stop when a breakpoint is encountered.
 
-j(ump) *lineno*
+.. pdbcommand:: j(ump) lineno
+
    Set the next line that will be executed.  Only available in the bottom-most
-   frame.  This lets you jump back and execute code again, or jump forward to skip
-   code that you don't want to run.
+   frame.  This lets you jump back and execute code again, or jump forward to
+   skip code that you don't want to run.
 
-   It should be noted that not all jumps are allowed --- for instance it is not
+   It should be noted that not all jumps are allowed -- for instance it is not
    possible to jump into the middle of a :keyword:`for` loop or out of a
    :keyword:`finally` clause.
 
-l(ist) [*first*\ [, *last*]]
-   List source code for the current file.  Without arguments, list 11 lines around
-   the current line or continue the previous listing.  With one argument, list 11
-   lines around at that line.  With two arguments, list the given range; if the
-   second argument is less than the first, it is interpreted as a count.
+.. pdbcommand:: l(ist) [first[, last]]
+
+   List source code for the current file.  Without arguments, list 11 lines
+   around the current line or continue the previous listing.  With ``.`` as
+   argument, list 11 lines around the current line.  With one argument,
+   list 11 lines around at that line.  With two arguments, list the given range;
+   if the second argument is less than the first, it is interpreted as a count.
+
+   The current line in the current frame is indicated by ``->``.  If an
+   exception is being debugged, the line where the exception was originally
+   raised or propagated is indicated by ``>>``, if it differs from the current
+   line.
+
+   .. versionadded:: 3.2
+      The ``>>`` marker.
+
+.. pdbcommand:: ll | longlist
+
+   List all source code for the current function or frame.  Interesting lines
+   are marked as for :pdbcmd:`list`.
+
+   .. versionadded:: 3.2
+
+.. pdbcommand:: a(rgs)
 
-a(rgs)
    Print the argument list of the current function.
 
-p(rint) *expression*
+.. pdbcommand:: p(rint) expression
+
    Evaluate the *expression* in the current context and print its value.
 
-pp *expression*
-   Like the ``p`` command, except the value of the expression is pretty-printed
-   using the :mod:`pprint` module.
-
-alias [*name* [command]]
-   Creates an alias called *name* that executes *command*.  The command must *not*
-   be enclosed in quotes.  Replaceable parameters can be indicated by ``%1``,
-   ``%2``, and so on, while ``%*`` is replaced by all the parameters.  If no
-   command is given, the current alias for *name* is shown. If no arguments are
-   given, all aliases are listed.
-
-   Aliases may be nested and can contain anything that can be legally typed at the
-   pdb prompt.  Note that internal pdb commands *can* be overridden by aliases.
-   Such a command is then hidden until the alias is removed.  Aliasing is
-   recursively applied to the first word of the command line; all other words in
-   the line are left alone.
+.. pdbcommand:: pp expression
+
+   Like the :pdbcmd:`print` command, except the value of the expression is
+   pretty-printed using the :mod:`pprint` module.
+
+.. pdbcommand:: whatis expression
+
+   Print the type of the *expression*.
+
+.. pdbcommand:: source expression
+
+   Try to get source code for the given object and display it.
+
+   .. versionadded:: 3.2
+
+.. _debugger-aliases:
+
+.. pdbcommand:: alias [name [command]]
+
+   Create an alias called *name* that executes *command*.  The command must
+   *not* be enclosed in quotes.  Replaceable parameters can be indicated by
+   ``%1``, ``%2``, and so on, while ``%*`` is replaced by all the parameters.
+   If no command is given, the current alias for *name* is shown. If no
+   arguments are given, all aliases are listed.
+
+   Aliases may be nested and can contain anything that can be legally typed at
+   the pdb prompt.  Note that internal pdb commands *can* be overridden by
+   aliases.  Such a command is then hidden until the alias is removed.  Aliasing
+   is recursively applied to the first word of the command line; all other words
+   in the line are left alone.
 
    As an example, here are two useful aliases (especially when placed in the
    :file:`.pdbrc` file)::
 
-      #Print instance variables (usage "pi classInst")
+      # Print instance variables (usage "pi classInst")
       alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
-      #Print instance variables in self
+      # Print instance variables in self
       alias ps pi self
 
-unalias *name*
-   Deletes the specified alias.
+.. pdbcommand:: unalias name
+
+   Delete the specified alias.
+
+.. pdbcommand:: ! statement
 
-[!]\ *statement*
    Execute the (one-line) *statement* in the context of the current stack frame.
    The exclamation point can be omitted unless the first word of the statement
-   resembles a debugger command. To set a global variable, you can prefix the
-   assignment command with a ``global`` command on the same line, e.g.::
+   resembles a debugger command.  To set a global variable, you can prefix the
+   assignment command with a :keyword:`global` statement on the same line,
+   e.g.::
 
       (Pdb) global list_options; list_options = ['-l']
       (Pdb)
 
-run [*args* ...]
-   Restart the debugged Python program. If an argument is supplied, it is split
-   with "shlex" and the result is used as the new sys.argv. History, breakpoints,
-   actions and debugger options are preserved. "restart" is an alias for "run".
+.. pdbcommand:: run [args ...]
+                restart [args ...]
+
+   Restart the debugged Python program.  If an argument is supplied, it is split
+   with :mod:`shlex` and the result is used as the new :data:`sys.argv`.
+   History, breakpoints, actions and debugger options are preserved.
+   :pdbcmd:`restart` is an alias for :pdbcmd:`run`.
+
+.. pdbcommand:: q(uit)
 
-q(uit)
-   Quit from the debugger. The program being executed is aborted.
+   Quit from the debugger.  The program being executed is aborted.
 
 
 .. rubric:: Footnotes

Modified: python/branches/py3k-dtoa/Doc/library/pickletools.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/pickletools.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/pickletools.rst	Sun Aug  8 12:41:24 2010
@@ -13,14 +13,20 @@
 :mod:`pickletools` module relevant.
 
 
-.. function:: dis(pickle, out=None, memo=None, indentlevel=4)
+.. function:: dis(pickle, out=None, memo=None, indentlevel=4, annotate=0)
 
-   Outputs a symbolic disassembly of the pickle to the file-like object *out*,
-   defaulting to ``sys.stdout``.  *pickle* can be a string or a file-like object.
-   *memo* can be a Python dictionary that will be used as the pickle's memo; it can
-   be used to perform disassemblies across multiple pickles created by the same
-   pickler. Successive levels, indicated by ``MARK`` opcodes in the stream, are
-   indented by *indentlevel* spaces.
+   Outputs a symbolic disassembly of the pickle to the file-like
+   object *out*, defaulting to ``sys.stdout``.  *pickle* can be a
+   string or a file-like object.  *memo* can be a Python dictionary
+   that will be used as the pickle's memo; it can be used to perform
+   disassemblies across multiple pickles created by the same
+   pickler. Successive levels, indicated by ``MARK`` opcodes in the
+   stream, are indented by *indentlevel* spaces.  If a nonzero value
+   is given to *annotate*, each opcode in the output is annotated with
+   a short description.  The value of *annotate* is used as a hint for
+   the column where annotation should start.
+
+  .. versionadded:: 3.2 the *annotate* argument.
 
 .. function:: genops(pickle)
 

Modified: python/branches/py3k-dtoa/Doc/library/pyexpat.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/pyexpat.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/pyexpat.rst	Sun Aug  8 12:41:24 2010
@@ -429,7 +429,7 @@
    Called if the XML document hasn't been declared as being a standalone document.
    This happens when there is an external subset or a reference to a parameter
    entity, but the XML declaration does not set standalone to ``yes`` in an XML
-   declaration.  If this handler returns ``0``, then the parser will throw an
+   declaration.  If this handler returns ``0``, then the parser will raise an
    :const:`XML_ERROR_NOT_STANDALONE` error.  If this handler is not set, no
    exception is raised by the parser for this condition.
 
@@ -446,7 +446,7 @@
    responsible for creating the sub-parser using
    ``ExternalEntityParserCreate(context)``, initializing it with the appropriate
    callbacks, and parsing the entity.  This handler should return an integer; if it
-   returns ``0``, the parser will throw an
+   returns ``0``, the parser will raise an
    :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will
    continue.
 

Modified: python/branches/py3k-dtoa/Doc/library/re.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/re.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/re.rst	Sun Aug  8 12:41:24 2010
@@ -33,8 +33,9 @@
 string notation.
 
 It is important to note that most regular expression operations are available as
-module-level functions and :class:`RegexObject` methods.  The functions are
-shortcuts that don't require you to compile a regex object first, but miss some
+module-level functions and methods on
+:ref:`compiled regular expressions <re-objects>`.  The functions are shortcuts
+that don't require you to compile a regex object first, but miss some
 fine-tuning parameters.
 
 .. seealso::
@@ -485,7 +486,7 @@
 
    Note that for backward compatibility, the :const:`re.U` flag still
    exists (as well as its synonym :const:`re.UNICODE` and its embedded
-   counterpart ``(?u)``), but these are redundant in Python 3.0 since
+   counterpart ``(?u)``), but these are redundant in Python 3 since
    matches are Unicode by default for strings (and Unicode matching
    isn't allowed for bytes).
 
@@ -504,7 +505,7 @@
    Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the
    current locale. The use of this flag is discouraged as the locale mechanism
    is very unreliable, and it only handles one "culture" at a time anyway;
-   you should use Unicode matching instead, which is the default in Python 3.0
+   you should use Unicode matching instead, which is the default in Python 3
    for Unicode (str) patterns.
 
 
@@ -546,21 +547,21 @@
 
 
 
-.. function:: search(pattern, string[, flags])
+.. function:: search(pattern, string, flags=0)
 
    Scan through *string* looking for a location where the regular expression
-   *pattern* produces a match, and return a corresponding :class:`MatchObject`
-   instance. Return ``None`` if no position in the string matches the pattern; note
-   that this is different from finding a zero-length match at some point in the
-   string.
+   *pattern* produces a match, and return a corresponding :ref:`match object
+   <match-objects>`.  Return ``None`` if no position in the string matches the
+   pattern; note that this is different from finding a zero-length match at some
+   point in the string.
 
 
 .. function:: match(pattern, string, flags=0)
 
    If zero or more characters at the beginning of *string* match the regular
-   expression *pattern*, return a corresponding :class:`MatchObject` instance.
-   Return ``None`` if the string does not match the pattern; note that this is
-   different from a zero-length match.
+   expression *pattern*, return a corresponding :ref:`match object
+   <match-objects>`.  Return ``None`` if the string does not match the pattern;
+   note that this is different from a zero-length match.
 
    .. note::
 
@@ -620,9 +621,9 @@
 
 .. function:: finditer(pattern, string, flags=0)
 
-   Return an :term:`iterator` yielding :class:`MatchObject` instances over all
-   non-overlapping matches for the RE *pattern* in *string*.  The *string* is
-   scanned left-to-right, and matches are returned in the order found.  Empty
+   Return an :term:`iterator` yielding :ref:`match objects <match-objects>` over
+   all non-overlapping matches for the RE *pattern* in *string*.  The *string*
+   is scanned left-to-right, and matches are returned in the order found.  Empty
    matches are included in the result unless they touch the beginning of another
    match.
 
@@ -692,6 +693,11 @@
    metacharacters in it.
 
 
+.. function:: purge()
+
+   Clear the regular expression cache.
+
+
 .. exception:: error
 
    Exception raised when a string passed to one of the functions here is not a
@@ -705,107 +711,107 @@
 Regular Expression Objects
 --------------------------
 
-.. class:: RegexObject
-
-   The :class:`RegexObject` class supports the following methods and attributes:
-
-   .. method:: RegexObject.search(string[, pos[, endpos]])
+Compiled regular expression objects support the following methods and
+attributes.
 
-      Scan through *string* looking for a location where this regular expression
-      produces a match, and return a corresponding :class:`MatchObject` instance.
-      Return ``None`` if no position in the string matches the pattern; note that this
-      is different from finding a zero-length match at some point in the string.
+.. method:: regex.search(string[, pos[, endpos]])
 
-      The optional second parameter *pos* gives an index in the string where the
-      search is to start; it defaults to ``0``.  This is not completely equivalent to
-      slicing the string; the ``'^'`` pattern character matches at the real beginning
-      of the string and at positions just after a newline, but not necessarily at the
-      index where the search is to start.
+   Scan through *string* looking for a location where this regular expression
+   produces a match, and return a corresponding :ref:`match object
+   <match-objects>`.  Return ``None`` if no position in the string matches the
+   pattern; note that this is different from finding a zero-length match at some
+   point in the string.
+
+   The optional second parameter *pos* gives an index in the string where the
+   search is to start; it defaults to ``0``.  This is not completely equivalent to
+   slicing the string; the ``'^'`` pattern character matches at the real beginning
+   of the string and at positions just after a newline, but not necessarily at the
+   index where the search is to start.
+
+   The optional parameter *endpos* limits how far the string will be searched; it
+   will be as if the string is *endpos* characters long, so only the characters
+   from *pos* to ``endpos - 1`` will be searched for a match.  If *endpos* is less
+   than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
+   expression object, ``rx.search(string, 0, 50)`` is equivalent to
+   ``rx.search(string[:50], 0)``.
 
-      The optional parameter *endpos* limits how far the string will be searched; it
-      will be as if the string is *endpos* characters long, so only the characters
-      from *pos* to ``endpos - 1`` will be searched for a match.  If *endpos* is less
-      than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
-      expression object, ``rx.search(string, 0, 50)`` is equivalent to
-      ``rx.search(string[:50], 0)``.
-
-      >>> pattern = re.compile("d")
-      >>> pattern.search("dog")     # Match at index 0
-      <_sre.SRE_Match object at ...>
-      >>> pattern.search("dog", 1)  # No match; search doesn't include the "d"
+   >>> pattern = re.compile("d")
+   >>> pattern.search("dog")     # Match at index 0
+   <_sre.SRE_Match object at ...>
+   >>> pattern.search("dog", 1)  # No match; search doesn't include the "d"
 
 
-   .. method:: RegexObject.match(string[, pos[, endpos]])
+.. method:: regex.match(string[, pos[, endpos]])
 
-      If zero or more characters at the *beginning* of *string* match this regular
-      expression, return a corresponding :class:`MatchObject` instance.  Return
-      ``None`` if the string does not match the pattern; note that this is different
-      from a zero-length match.
+   If zero or more characters at the *beginning* of *string* match this regular
+   expression, return a corresponding :ref:`match object <match-objects>`.
+   Return ``None`` if the string does not match the pattern; note that this is
+   different from a zero-length match.
 
-      The optional *pos* and *endpos* parameters have the same meaning as for the
-      :meth:`~RegexObject.search` method.
+   The optional *pos* and *endpos* parameters have the same meaning as for the
+   :meth:`~regex.search` method.
 
-      .. note::
+   .. note::
 
-         If you want to locate a match anywhere in *string*, use
-         :meth:`~RegexObject.search` instead.
+      If you want to locate a match anywhere in *string*, use
+      :meth:`~regex.search` instead.
 
-      >>> pattern = re.compile("o")
-      >>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
-      >>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
-      <_sre.SRE_Match object at ...>
+   >>> pattern = re.compile("o")
+   >>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
+   >>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
+   <_sre.SRE_Match object at ...>
 
 
-   .. method:: RegexObject.split(string[, maxsplit=0])
+.. method:: regex.split(string, maxsplit=0)
 
-      Identical to the :func:`split` function, using the compiled pattern.
+   Identical to the :func:`split` function, using the compiled pattern.
 
 
-   .. method:: RegexObject.findall(string[, pos[, endpos]])
+.. method:: regex.findall(string[, pos[, endpos]])
 
-      Similar to the :func:`findall` function, using the compiled pattern, but
-      also accepts optional *pos* and *endpos* parameters that limit the search
-      region like for :meth:`match`.
+   Similar to the :func:`findall` function, using the compiled pattern, but
+   also accepts optional *pos* and *endpos* parameters that limit the search
+   region like for :meth:`match`.
 
 
-   .. method:: RegexObject.finditer(string[, pos[, endpos]])
+.. method:: regex.finditer(string[, pos[, endpos]])
 
-      Similar to the :func:`finditer` function, using the compiled pattern, but
-      also accepts optional *pos* and *endpos* parameters that limit the search
-      region like for :meth:`match`.
+   Similar to the :func:`finditer` function, using the compiled pattern, but
+   also accepts optional *pos* and *endpos* parameters that limit the search
+   region like for :meth:`match`.
 
 
-   .. method:: RegexObject.sub(repl, string[, count=0])
+.. method:: regex.sub(repl, string, count=0)
 
-      Identical to the :func:`sub` function, using the compiled pattern.
+   Identical to the :func:`sub` function, using the compiled pattern.
 
 
-   .. method:: RegexObject.subn(repl, string[, count=0])
+.. method:: regex.subn(repl, string, count=0)
 
-      Identical to the :func:`subn` function, using the compiled pattern.
+   Identical to the :func:`subn` function, using the compiled pattern.
 
 
-   .. attribute:: RegexObject.flags
+.. attribute:: regex.flags
 
-      The flags argument used when the RE object was compiled, or ``0`` if no flags
-      were provided.
+   The flags argument used when the RE object was compiled, or ``0`` if no flags
+   were provided.
 
 
-   .. attribute:: RegexObject.groups
+.. attribute:: regex.groups
 
-      The number of capturing groups in the pattern.
+   The number of capturing groups in the pattern.
 
 
-   .. attribute:: RegexObject.groupindex
+.. attribute:: regex.groupindex
 
-      A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
-      numbers.  The dictionary is empty if no symbolic groups were used in the
-      pattern.
+   A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
+   numbers.  The dictionary is empty if no symbolic groups were used in the
+   pattern.
 
 
-   .. attribute:: RegexObject.pattern
+.. attribute:: regex.pattern
 
-      The pattern string from which the RE object was compiled.
+   The pattern string from which the RE object was compiled.
 
 
 .. _match-objects:
@@ -813,181 +819,176 @@
 Match Objects
 -------------
 
-.. class:: MatchObject
-
-   Match Objects always have a boolean value of :const:`True`, so that you can test
-   whether e.g. :func:`match` resulted in a match with a simple if statement.  They
-   support the following methods and attributes:
-
-
-   .. method:: MatchObject.expand(template)
+Match objects always have a boolean value of :const:`True`, so that you can test
+whether e.g. :func:`match` resulted in a match with a simple if statement.  They
+support the following methods and attributes:
+
+
+.. method:: match.expand(template)
+
+   Return the string obtained by doing backslash substitution on the template
+   string *template*, as done by the :meth:`~regex.sub` method.
+   Escapes such as ``\n`` are converted to the appropriate characters,
+   and numeric backreferences (``\1``, ``\2``) and named backreferences
+   (``\g<1>``, ``\g<name>``) are replaced by the contents of the
+   corresponding group.
+
+
+.. method:: match.group([group1, ...])
+
+   Returns one or more subgroups of the match.  If there is a single argument, the
+   result is a single string; if there are multiple arguments, the result is a
+   tuple with one item per argument. Without arguments, *group1* defaults to zero
+   (the whole match is returned). If a *groupN* argument is zero, the corresponding
+   return value is the entire matching string; if it is in the inclusive range
+   [1..99], it is the string matching the corresponding parenthesized group.  If a
+   group number is negative or larger than the number of groups defined in the
+   pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
+   part of the pattern that did not match, the corresponding result is ``None``.
+   If a group is contained in a part of the pattern that matched multiple times,
+   the last match is returned.
+
+      >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
+      >>> m.group(0)       # The entire match
+      'Isaac Newton'
+      >>> m.group(1)       # The first parenthesized subgroup.
+      'Isaac'
+      >>> m.group(2)       # The second parenthesized subgroup.
+      'Newton'
+      >>> m.group(1, 2)    # Multiple arguments give us a tuple.
+      ('Isaac', 'Newton')
+
+   If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
+   arguments may also be strings identifying groups by their group name.  If a
+   string argument is not used as a group name in the pattern, an :exc:`IndexError`
+   exception is raised.
+
+   A moderately complicated example:
+
+      >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
+      >>> m.group('first_name')
+      'Malcolm'
+      >>> m.group('last_name')
+      'Reynolds'
+
+   Named groups can also be referred to by their index:
+
+      >>> m.group(1)
+      'Malcolm'
+      >>> m.group(2)
+      'Reynolds'
+
+   If a group matches multiple times, only the last match is accessible:
+
+      >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
+      >>> m.group(1)                        # Returns only the last match.
+      'c3'
+
+
+.. method:: match.groups(default=None)
+
+   Return a tuple containing all the subgroups of the match, from 1 up to however
+   many groups are in the pattern.  The *default* argument is used for groups that
+   did not participate in the match; it defaults to ``None``.
 
-      Return the string obtained by doing backslash substitution on the template
-      string *template*, as done by the :meth:`~RegexObject.sub` method.  Escapes
-      such as ``\n`` are converted to the appropriate characters, and numeric
-      backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
-      ``\g<name>``) are replaced by the contents of the corresponding group.
-
-
-   .. method:: MatchObject.group([group1, ...])
-
-      Returns one or more subgroups of the match.  If there is a single argument, the
-      result is a single string; if there are multiple arguments, the result is a
-      tuple with one item per argument. Without arguments, *group1* defaults to zero
-      (the whole match is returned). If a *groupN* argument is zero, the corresponding
-      return value is the entire matching string; if it is in the inclusive range
-      [1..99], it is the string matching the corresponding parenthesized group.  If a
-      group number is negative or larger than the number of groups defined in the
-      pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
-      part of the pattern that did not match, the corresponding result is ``None``.
-      If a group is contained in a part of the pattern that matched multiple times,
-      the last match is returned.
-
-         >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
-         >>> m.group(0)       # The entire match
-         'Isaac Newton'
-         >>> m.group(1)       # The first parenthesized subgroup.
-         'Isaac'
-         >>> m.group(2)       # The second parenthesized subgroup.
-         'Newton'
-         >>> m.group(1, 2)    # Multiple arguments give us a tuple.
-         ('Isaac', 'Newton')
-
-      If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
-      arguments may also be strings identifying groups by their group name.  If a
-      string argument is not used as a group name in the pattern, an :exc:`IndexError`
-      exception is raised.
-
-      A moderately complicated example:
-
-         >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
-         >>> m.group('first_name')
-         'Malcolm'
-         >>> m.group('last_name')
-         'Reynolds'
-
-      Named groups can also be referred to by their index:
-
-         >>> m.group(1)
-         'Malcolm'
-         >>> m.group(2)
-         'Reynolds'
-
-      If a group matches multiple times, only the last match is accessible:
-
-         >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
-         >>> m.group(1)                        # Returns only the last match.
-         'c3'
-
-
-   .. method:: MatchObject.groups(default=None)
-
-      Return a tuple containing all the subgroups of the match, from 1 up to however
-      many groups are in the pattern.  The *default* argument is used for groups that
-      did not participate in the match; it defaults to ``None``.  (Incompatibility
-      note: in the original Python 1.5 release, if the tuple was one element long, a
-      string would be returned instead.  In later versions (from 1.5.1 on), a
-      singleton tuple is returned in such cases.)
-
-      For example:
+   For example:
 
-         >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
-         >>> m.groups()
-         ('24', '1632')
+      >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
+      >>> m.groups()
+      ('24', '1632')
 
-      If we make the decimal place and everything after it optional, not all groups
-      might participate in the match.  These groups will default to ``None`` unless
-      the *default* argument is given:
+   If we make the decimal place and everything after it optional, not all groups
+   might participate in the match.  These groups will default to ``None`` unless
+   the *default* argument is given:
 
-         >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
-         >>> m.groups()      # Second group defaults to None.
-         ('24', None)
-         >>> m.groups('0')   # Now, the second group defaults to '0'.
-         ('24', '0')
+      >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
+      >>> m.groups()      # Second group defaults to None.
+      ('24', None)
+      >>> m.groups('0')   # Now, the second group defaults to '0'.
+      ('24', '0')
 
 
-   .. method:: MatchObject.groupdict([default])
+.. method:: match.groupdict(default=None)
 
-      Return a dictionary containing all the *named* subgroups of the match, keyed by
-      the subgroup name.  The *default* argument is used for groups that did not
-      participate in the match; it defaults to ``None``.  For example:
+   Return a dictionary containing all the *named* subgroups of the match, keyed by
+   the subgroup name.  The *default* argument is used for groups that did not
+   participate in the match; it defaults to ``None``.  For example:
 
-         >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
-         >>> m.groupdict()
-         {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
+      >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
+      >>> m.groupdict()
+      {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
 
 
-   .. method:: MatchObject.start([group])
-               MatchObject.end([group])
+.. method:: match.start([group])
+            match.end([group])
 
-      Return the indices of the start and end of the substring matched by *group*;
-      *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
-      *group* exists but did not contribute to the match.  For a match object *m*, and
-      a group *g* that did contribute to the match, the substring matched by group *g*
-      (equivalent to ``m.group(g)``) is ::
+   Return the indices of the start and end of the substring matched by *group*;
+   *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
+   *group* exists but did not contribute to the match.  For a match object *m*, and
+   a group *g* that did contribute to the match, the substring matched by group *g*
+   (equivalent to ``m.group(g)``) is ::
 
-         m.string[m.start(g):m.end(g)]
+      m.string[m.start(g):m.end(g)]
 
-      Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
-      null string.  For example, after ``m = re.search('b(c?)', 'cba')``,
-      ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
-      2, and ``m.start(2)`` raises an :exc:`IndexError` exception.
+   Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
+   null string.  For example, after ``m = re.search('b(c?)', 'cba')``,
+   ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
+   2, and ``m.start(2)`` raises an :exc:`IndexError` exception.
 
-      An example that will remove *remove_this* from email addresses:
+   An example that will remove *remove_this* from email addresses:
 
-         >>> email = "tony at tiremove_thisger.net"
-         >>> m = re.search("remove_this", email)
-         >>> email[:m.start()] + email[m.end():]
-         'tony at tiger.net'
+      >>> email = "tony at tiremove_thisger.net"
+      >>> m = re.search("remove_this", email)
+      >>> email[:m.start()] + email[m.end():]
+      'tony at tiger.net'
 
 
-   .. method:: MatchObject.span([group])
+.. method:: match.span([group])
 
-      For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group),
-      m.end(group))``. Note that if *group* did not contribute to the match, this is
-      ``(-1, -1)``.  *group* defaults to zero, the entire match.
+   For a match *m*, return the 2-tuple ``(m.start(group), m.end(group))``. Note
+   that if *group* did not contribute to the match, this is ``(-1, -1)``.
+   *group* defaults to zero, the entire match.
 
 
-   .. attribute:: MatchObject.pos
+.. attribute:: match.pos
 
-      The value of *pos* which was passed to the :meth:`~RegexObject.search` or
-      :meth:`~RegexObject.match` method of the :class:`RegexObject`.  This is the
-      index into the string at which the RE engine started looking for a match.
+   The value of *pos* which was passed to the :meth:`~regex.search` or
+   :meth:`~regex.match` method of a :ref:`match object <match-objects>`.  This
+   is the index into the string at which the RE engine started looking for a
+   match.
 
 
-   .. attribute:: MatchObject.endpos
+.. attribute:: match.endpos
 
-      The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
-      :meth:`~RegexObject.match` method of the :class:`RegexObject`.  This is the
-      index into the string beyond which the RE engine will not go.
+   The value of *endpos* which was passed to the :meth:`~regex.search` or
+   :meth:`~regex.match` method of a :ref:`match object <match-objects>`.  This
+   is the index into the string beyond which the RE engine will not go.
 
 
-   .. attribute:: MatchObject.lastindex
+.. attribute:: match.lastindex
 
-      The integer index of the last matched capturing group, or ``None`` if no group
-      was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and
-      ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while
-      the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same
-      string.
+   The integer index of the last matched capturing group, or ``None`` if no group
+   was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and
+   ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while
+   the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same
+   string.
 
 
-   .. attribute:: MatchObject.lastgroup
+.. attribute:: match.lastgroup
 
-      The name of the last matched capturing group, or ``None`` if the group didn't
-      have a name, or if no group was matched at all.
+   The name of the last matched capturing group, or ``None`` if the group didn't
+   have a name, or if no group was matched at all.
 
 
-   .. attribute:: MatchObject.re
+.. attribute:: match.re
 
-      The regular expression object whose :meth:`~RegexObject.match` or
-      :meth:`~RegexObject.search` method produced this :class:`MatchObject`
-      instance.
+   The regular expression object whose :meth:`~regex.match` or
+   :meth:`~regex.search` method produced this match instance.
 
 
-   .. attribute:: MatchObject.string
+.. attribute:: match.string
 
-      The string passed to :meth:`~RegexObject.match` or
-      :meth:`~RegexObject.search`.
+   The string passed to :meth:`~regex.match` or :meth:`~regex.search`.
 
 
 Examples
@@ -1033,8 +1034,7 @@
    "<Match: '354aa', groups=('a',)>"
 
 To find out what card the pair consists of, one could use the
-:meth:`~MatchObject.group` method of :class:`MatchObject` in the following
-manner:
+:meth:`~match.group` method of the match object in the following manner:
 
 .. doctest::
 
@@ -1109,7 +1109,7 @@
    >>> re.match('Begin (\w| )*? end', s).end()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
-     File "/usr/local/lib/python2.5/re.py", line 132, in match
+     File "/usr/local/lib/python3.2/re.py", line 132, in match
        return _compile(pattern, flags).match(string)
    RuntimeError: maximum recursion limit exceeded
 
@@ -1225,9 +1225,9 @@
    ...   random.shuffle(inner_word)
    ...   return m.group(1) + "".join(inner_word) + m.group(3)
    >>> text = "Professor Abdolmalek, please report your absences promptly."
-   >>> re.sub("(\w)(\w+)(\w)", repl, text)
+   >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
    'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
-   >>> re.sub("(\w)(\w+)(\w)", repl, text)
+   >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
    'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
 
 
@@ -1248,10 +1248,10 @@
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 If one wants more information about all matches of a pattern than the matched
-text, :func:`finditer` is useful as it provides instances of
-:class:`MatchObject` instead of strings.  Continuing with the previous example,
-if one was a writer who wanted to find all of the adverbs *and their positions*
-in some text, he or she would use :func:`finditer` in the following manner:
+text, :func:`finditer` is useful as it provides :ref:`match objects
+<match-objects>` instead of strings.  Continuing with the previous example, if
+one was a writer who wanted to find all of the adverbs *and their positions* in
+some text, he or she would use :func:`finditer` in the following manner:
 
    >>> text = "He was carefully disguised but captured quickly by police."
    >>> for m in re.finditer(r"\w+ly", text):

Modified: python/branches/py3k-dtoa/Doc/library/select.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/select.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/select.rst	Sun Aug  8 12:41:24 2010
@@ -41,14 +41,14 @@
 
 .. function:: kqueue()
 
-   (Only supported on BSD.)  Returns a kernel queue object object; see section
+   (Only supported on BSD.)  Returns a kernel queue object; see section
    :ref:`kqueue-objects` below for the methods supported by kqueue objects.
 
 
 .. function:: kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)
 
-   (Only supported on BSD.)  Returns a kernel event object object; see section
-   :ref:`kevent-objects` below for the methods supported by kqueue objects.
+   (Only supported on BSD.)  Returns a kernel event object; see section
+   :ref:`kevent-objects` below for the methods supported by kevent objects.
 
 
 .. function:: select(rlist, wlist, xlist[, timeout])
@@ -131,15 +131,15 @@
    | :const:`EPOLLONESHOT` | Set one-shot behavior. After one event is     |
    |                       | pulled out, the fd is internally disabled     |
    +-----------------------+-----------------------------------------------+
-   | :const:`EPOLLRDNORM`  | ???                                           |
+   | :const:`EPOLLRDNORM`  | Equivalent to :const:`EPOLLIN`                |
    +-----------------------+-----------------------------------------------+
-   | :const:`EPOLLRDBAND`  | ???                                           |
+   | :const:`EPOLLRDBAND`  | Priority data band can be read.               |
    +-----------------------+-----------------------------------------------+
-   | :const:`EPOLLWRNORM`  | ???                                           |
+   | :const:`EPOLLWRNORM`  | Equivalent to :const:`EPOLLOUT`               |
    +-----------------------+-----------------------------------------------+
-   | :const:`EPOLLWRBAND`  | ???                                           |
+   | :const:`EPOLLWRBAND`  | Priority data may be written.                 |
    +-----------------------+-----------------------------------------------+
-   | :const:`EPOLLMSG`     | ???                                           |
+   | :const:`EPOLLMSG`     | Ignored.                                      |
    +-----------------------+-----------------------------------------------+
 
 
@@ -233,7 +233,7 @@
 .. method:: poll.modify(fd, eventmask)
 
    Modifies an already registered fd. This has the same effect as
-   :meth:`register(fd, eventmask)`.  Attempting to modify a file descriptor
+   ``register(fd, eventmask)``.  Attempting to modify a file descriptor
    that was never registered causes an :exc:`IOError` exception with errno
    :const:`ENOENT` to be raised.
 

Modified: python/branches/py3k-dtoa/Doc/library/signal.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/signal.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/signal.rst	Sun Aug  8 12:41:24 2010
@@ -76,7 +76,9 @@
 
 .. data:: CTRL_C_EVENT
 
-   The signal corresponding to the CTRL+C keystroke event.
+   The signal corresponding to the CTRL+C keystroke event. This signal can
+   only be used with :func:`os.kill`.
+
    Availability: Windows.
 
    .. versionadded:: 3.2
@@ -84,7 +86,9 @@
 
 .. data:: CTRL_BREAK_EVENT
 
-   The signal corresponding to the CTRL+BREAK keystroke event.
+   The signal corresponding to the CTRL+BREAK keystroke event. This signal can
+   only be used with :func:`os.kill`.
+
    Availability: Windows.
 
    .. versionadded:: 3.2
@@ -226,6 +230,10 @@
    see the :ref:`description in the type hierarchy <frame-objects>` or see the
    attribute descriptions in the :mod:`inspect` module).
 
+   On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
+   :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
+   :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
+
 
 .. _signal-example:
 

Modified: python/branches/py3k-dtoa/Doc/library/smtpd.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/smtpd.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/smtpd.rst	Sun Aug  8 12:41:24 2010
@@ -10,10 +10,14 @@
 
 
 
-This module offers several classes to implement SMTP servers.  One is a generic
+This module offers several classes to implement SMTP (email) servers.
+
+Several server implementations are present; one is a generic
 do-nothing implementation, which can be overridden, while the other two offer
 specific mail-sending strategies.
 
+Additionally the SMTPChannel may be extended to implement very specific
+interaction behaviour with SMTP clients.
 
 SMTPServer Objects
 ------------------
@@ -26,7 +30,6 @@
    inherits from :class:`asyncore.dispatcher`, and so will insert itself into
    :mod:`asyncore`'s event loop on instantiation.
 
-
    .. method:: process_message(peer, mailfrom, rcpttos, data)
 
       Raise :exc:`NotImplementedError` exception. Override this in subclasses to
@@ -37,6 +40,11 @@
       containing the contents of the e-mail (which should be in :rfc:`2822`
       format).
 
+   .. attribute:: channel_class
+
+      Override this in subclasses to use a custom :class:`SMTPChannel` for
+      managing SMTP clients.
+
 
 DebuggingServer Objects
 -----------------------
@@ -71,3 +79,91 @@
    running this has a good chance to make you into an open relay, so please be
    careful.
 
+SMTPChannel Objects
+-------------------
+
+.. class:: SMTPChannel(server, conn, addr)
+
+   Create a new :class:`SMTPChannel` object which manages the communication
+   between the server and a single SMTP client.
+
+   To use a custom SMTPChannel implementation you need to override the
+   :attr:`SMTPServer.channel_class` of your :class:`SMTPServer`.
+
+   The :class:`SMTPChannel` has the following instance variables:
+
+   .. attribute:: smtp_server
+
+      Holds the :class:`SMTPServer` that spawned this channel.
+
+   .. attribute:: conn
+
+      Holds the socket object connecting to the client.
+
+   .. attribute:: addr
+
+      Holds the address of the client, the second value returned by
+      socket.accept()
+
+   .. attribute:: received_lines
+
+      Holds a list of the line strings (decoded using UTF-8) received from
+      the client. The lines have their "\r\n" line ending translated to "\n".
+
+   .. attribute:: smtp_state
+
+      Holds the current state of the channel. This will be either
+      :attr:`COMMAND` initially and then :attr:`DATA` after the client sends
+      a "DATA" line.
+
+   .. attribute:: seen_greeting
+
+      Holds a string containing the greeting sent by the client in its "HELO".
+
+   .. attribute:: mailfrom
+
+      Holds a string containing the address identified in the "MAIL FROM:" line
+      from the client.
+
+   .. attribute:: rcpttos
+
+      Holds a list of strings containing the addresses identified in the
+      "RCPT TO:" lines from the client.
+
+   .. attribute:: received_data
+
+      Holds a string containing all of the data sent by the client during the
+      DATA state, up to but not including the terminating "\r\n.\r\n".
+
+   .. attribute:: fqdn
+
+      Holds the fully-qualified domain name of the server as returned by
+      ``socket.getfqdn()``.
+
+   .. attribute:: peer
+
+      Holds the name of the client peer as returned by ``conn.getpeername()``
+      where ``conn`` is :attr:`conn`.
+
+   The :class:`SMTPChannel` operates by invoking methods named ``smtp_<command>``
+   upon reception of a command line from the client. Built into the base
+   :class:`SMTPChannel` class are methods for handling the following commands
+   (and responding to them appropriately):
+
+   ======== ===================================================================
+   Command  Action taken
+   ======== ===================================================================
+   HELO     Accepts the greeting from the client and stores it in
+            :attr:`seen_greeting`.
+   NOOP     Takes no action.
+   QUIT     Closes the connection cleanly.
+   MAIL     Accepts the "MAIL FROM:" syntax and stores the supplied address as
+            :attr:`mailfrom`.
+   RCPT     Accepts the "RCPT TO:" syntax and stores the supplied addresses in
+            the :attr:`rcpttos` list.
+   RSET     Resets the :attr:`mailfrom`, :attr:`rcpttos`, and
+            :attr:`received_data`, but not the greeting.
+   DATA     Sets the internal state to :attr:`DATA` and stores remaining lines
+            from the client in :attr:`received_data` until the terminator
+            "\r\n.\r\n" is received.
+   ======== ===================================================================
\ No newline at end of file

Modified: python/branches/py3k-dtoa/Doc/library/smtplib.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/smtplib.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/smtplib.rst	Sun Aug  8 12:41:24 2010
@@ -284,9 +284,9 @@
    and ESMTP options suppressed.
 
    This method will return normally if the mail is accepted for at least one
-   recipient. Otherwise it will throw an exception.  That is, if this method does
-   not throw an exception, then someone should get your mail. If this method does
-   not throw an exception, it returns a dictionary, with one entry for each
+   recipient. Otherwise it will raise an exception.  That is, if this method does
+   not raise an exception, then someone should get your mail. If this method does
+   not raise an exception, it returns a dictionary, with one entry for each
    recipient that was refused.  Each entry contains a tuple of the SMTP error code
    and the accompanying error message sent by the server.
 

Modified: python/branches/py3k-dtoa/Doc/library/socket.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/socket.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/socket.rst	Sun Aug  8 12:41:24 2010
@@ -748,7 +748,9 @@
    Shut down one or both halves of the connection.  If *how* is :const:`SHUT_RD`,
    further receives are disallowed.  If *how* is :const:`SHUT_WR`, further sends
    are disallowed.  If *how* is :const:`SHUT_RDWR`, further sends and receives are
-   disallowed.
+   disallowed.  Depending on the platform, shutting down one half of the connection
+   can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` does
+   not allow further reads on the other end of the connection).
 
 Note that there are no methods :meth:`read` or :meth:`write`; use
 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.

Modified: python/branches/py3k-dtoa/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/sqlite3.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/sqlite3.rst	Sun Aug  8 12:41:24 2010
@@ -136,7 +136,7 @@
    first blank for the column name: the column name would simply be "x".
 
 
-.. function:: connect(database[, timeout, isolation_level, detect_types, factory])
+.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
 
    Opens a connection to the SQLite database file *database*. You can use
    ``":memory:"`` to open a database connection to a database that resides in RAM
@@ -867,3 +867,18 @@
 committed:
 
 .. literalinclude:: ../includes/sqlite3/ctx_manager.py
+
+
+Common issues
+-------------
+
+Multithreading
+^^^^^^^^^^^^^^
+
+Older SQLite versions had issues with sharing connections between threads.
+That's why the Python module disallows sharing connections and cursors between
+threads. If you still try to do so, you will get an exception at runtime.
+
+The only exception is calling the :meth:`~Connection.interrupt` method, which
+only makes sense to call from a different thread.
+

Modified: python/branches/py3k-dtoa/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/stdtypes.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/stdtypes.rst	Sun Aug  8 12:41:24 2010
@@ -217,14 +217,15 @@
 There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
 point numbers`, and :dfn:`complex numbers`.  In addition, Booleans are a
 subtype of integers.  Integers have unlimited precision.  Floating point
-numbers are implemented using :ctype:`double` in C---all bets on their
-precision are off unless you happen to know the machine you are working
-with. Complex numbers have a real and imaginary part, which are each
-implemented using :ctype:`double` in C.  To extract these parts from a
-complex number *z*, use ``z.real`` and ``z.imag``. (The standard library
-includes additional numeric types, :mod:`fractions` that hold rationals,
-and :mod:`decimal` that hold floating-point numbers with user-definable
-precision.)
+numbers are usually implemented using :ctype:`double` in C; information
+about the precision and internal representation of floating point
+numbers for the machine on which your program is running is available
+in :data:`sys.float_info`.  Complex numbers have a real and imaginary
+part, which are each a floating point number.  To extract these parts
+from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard
+library includes additional numeric types, :mod:`fractions` that hold
+rationals, and :mod:`decimal` that hold floating-point numbers with
+user-definable precision.)
 
 .. index::
    pair: numeric; literals
@@ -2264,10 +2265,19 @@
    buffer protocol.  Builtin objects that support the buffer protocol include
    :class:`bytes` and :class:`bytearray`.
 
-   ``len(view)`` returns the total number of bytes in the memoryview, *view*.
+   A :class:`memoryview` has the notion of an *element*, which is the
+   atomic memory unit handled by the originating object *obj*.  For many
+   simple types such as :class:`bytes` and :class:`bytearray`, an element
+   is a single byte, but other types such as :class:`array.array` may have
+   bigger elements.
+
+   ``len(view)`` returns the total number of elements in the memoryview,
+   *view*.  The :class:`~memoryview.itemsize` attribute will give you the
+   number of bytes in a single element.
 
    A :class:`memoryview` supports slicing to expose its data.  Taking a single
-   index will return a single byte.  Full slicing will result in a subview::
+   index will return a single element as a :class:`bytes` object.  Full
+   slicing will result in a subview::
 
       >>> v = memoryview(b'abcefg')
       >>> v[1]
@@ -2278,11 +2288,8 @@
       <memory at 0x77ab28>
       >>> bytes(v[1:4])
       b'bce'
-      >>> v[3:-1]
-      <memory at 0x744f18>
-      >>> bytes(v[4:-1])
 
-   If the object the memory view is over supports changing its data, the
+   If the object the memoryview is over supports changing its data, the
    memoryview supports slice assignment::
 
       >>> data = bytearray(b'abcefg')
@@ -2302,12 +2309,18 @@
 
    Notice how the size of the memoryview object cannot be changed.
 
-
    :class:`memoryview` has two methods:
 
    .. method:: tobytes()
 
-      Return the data in the buffer as a bytestring.
+      Return the data in the buffer as a bytestring.  This is equivalent to
+      calling the :class:`bytes` constructor on the memoryview. ::
+
+         >>> m = memoryview(b"abc")
+         >>> m.tobytes()
+         b'abc'
+         >>> bytes(m)
+         b'abc'
 
    .. method:: tolist()
 
@@ -2325,7 +2338,15 @@
 
    .. attribute:: itemsize
 
-      The size in bytes of each element of the memoryview.
+      The size in bytes of each element of the memoryview::
+
+         >>> m = memoryview(array.array('H', [1,2,3]))
+         >>> m.itemsize
+         2
+         >>> m[0]
+         b'\x01\x00'
+         >>> len(m[0]) == m.itemsize
+         True
 
    .. attribute:: shape
 

Modified: python/branches/py3k-dtoa/Doc/library/string.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/string.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/string.rst	Sun Aug  8 12:41:24 2010
@@ -7,13 +7,13 @@
 
 .. index:: module: re
 
-The :mod:`string` module contains a number of useful constants and classes, as
-well as some deprecated legacy functions that are also available as methods on
-strings. In addition, Python's built-in string classes support the sequence type
-methods described in the :ref:`typesseq` section, and also the string-specific
-methods described in the :ref:`string-methods` section. To output formatted
-strings, see the :ref:`string-formatting` section. Also, see the :mod:`re`
-module for string functions based on regular expressions.
+The :mod:`string` module contains a number of useful constants and classes
+for string formatting.  In addition, Python's built-in string classes
+support the sequence type methods described in the :ref:`typesseq`
+section, and also the string-specific methods described in the
+:ref:`string-methods` section.  To output formatted strings, see the
+:ref:`string-formatting` section.  Also, see the :mod:`re` module for
+string functions based on regular expressions.
 
 
 String constants
@@ -163,7 +163,7 @@
       the format string (integers for positional arguments, and strings for
       named arguments), and a reference to the *args* and *kwargs* that was
       passed to vformat.  The set of unused args can be calculated from these
-      parameters.  :meth:`check_unused_args` is assumed to throw an exception if
+      parameters.  :meth:`check_unused_args` is assumed to raise an exception if
       the check fails.
 
    .. method:: format_field(value, format_spec)
@@ -710,6 +710,14 @@
   appropriate).  The default value is the regular expression
   ``[_a-z][_a-z0-9]*``.
 
+* *flags* -- The regular expression flags that will be applied when compiling
+  the regular expression used for recognizing substitutions.  The default value
+  is ``re.IGNORECASE``.  Note that ``re.VERBOSE`` will always be added to the
+  flags, so custom *idpattern*\ s must follow conventions for verbose regular
+  expressions.
+
+  .. versionadded:: 3.2
+
 Alternatively, you can provide the entire regular expression pattern by
 overriding the class attribute *pattern*.  If you do this, the value must be a
 regular expression object with four named capturing groups.  The capturing

Modified: python/branches/py3k-dtoa/Doc/library/struct.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/struct.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/struct.rst	Sun Aug  8 12:41:24 2010
@@ -259,18 +259,16 @@
    In 3.0, some of the integer formats wrapped out-of-range values and
    raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
 
-
 The ``'p'`` format character encodes a "Pascal string", meaning a short
-variable-length string stored in a fixed number of bytes. The count is the total
-number of bytes stored.  The first byte stored is the length of the string, or
-255, whichever is smaller.  The bytes of the string follow.  If the string
-passed in to :func:`pack` is too long (longer than the count minus 1), only the
-leading count-1 bytes of the string are stored.  If the string is shorter than
-count-1, it is padded with null bytes so that exactly count bytes in all are
-used.  Note that for :func:`unpack`, the ``'p'`` format character consumes count
-bytes, but that the string returned can never contain more than 255 bytes.
-
-
+variable-length string stored in a *fixed number of bytes*, given by the count.
+The first byte stored is the length of the string, or 255, whichever is
+smaller.  The bytes of the string follow.  If the string passed in to
+:func:`pack` is too long (longer than the count minus 1), only the leading
+``count-1`` bytes of the string are stored.  If the string is shorter than
+``count-1``, it is padded with null bytes so that exactly count bytes in all
+are used.  Note that for :func:`unpack`, the ``'p'`` format character consumes
+``count`` bytes, but that the string returned can never contain more than 255
+bytes.
 
 For the ``'?'`` format character, the return value is either :const:`True` or
 :const:`False`. When packing, the truth value of the argument object is used.

Modified: python/branches/py3k-dtoa/Doc/library/subprocess.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/subprocess.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/subprocess.rst	Sun Aug  8 12:41:24 2010
@@ -575,7 +575,7 @@
    pipe = os.popen(cmd, 'w')
    ...
    rc = pipe.close()
-   if rc is not None and rc % 256:
+   if rc is not None and rc >> 8:
        print("There were some errors")
    ==>
    process = Popen(cmd, 'w', stdin=PIPE)

Modified: python/branches/py3k-dtoa/Doc/library/sys.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/sys.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/sys.rst	Sun Aug  8 12:41:24 2010
@@ -843,7 +843,7 @@
       A C function has returned. *arg* is ``None``.
 
    ``'c_exception'``
-      A C function has thrown an exception.  *arg* is ``None``.
+      A C function has raised an exception.  *arg* is ``None``.
 
    Note that as an exception is propagated down the chain of callers, an
    ``'exception'`` event is generated at each level.
@@ -935,14 +935,10 @@
 .. data:: version
 
    A string containing the version number of the Python interpreter plus additional
-   information on the build number and compiler used. It has a value of the form
-   ``'version (#build_number, build_date, build_time) [compiler]'``.  The first
-   three characters are used to identify the version in the installation
-   directories (where appropriate on each platform).  An example::
-
-      >>> import sys
-      >>> sys.version
-      '1.5.2 (#0 Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)]'
+   information on the build number and compiler used.  This string is displayed
+   when the interactive interpreter is started.  Do not extract version information
+   out of it, rather, use :data:`version_info` and the functions provided by the
+   :mod:`platform` module.
 
 
 .. data:: api_version

Modified: python/branches/py3k-dtoa/Doc/library/test.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/test.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/test.rst	Sun Aug  8 12:41:24 2010
@@ -5,6 +5,13 @@
    :synopsis: Regression tests package containing the testing suite for Python.
 .. sectionauthor:: Brett Cannon <brett at python.org>
 
+.. note::
+    The :mod:`test` package is meant for internal use by Python only. It is
+    documented for the benefit of the core developers of Python. Any use of
+    this package outside of Python's standard library is discouraged as code
+    mentioned here can change or be removed without notice between releases of
+    Python.
+
 
 The :mod:`test` package contains all regression tests for Python as well as the
 modules :mod:`test.support` and :mod:`test.regrtest`.

Modified: python/branches/py3k-dtoa/Doc/library/threading.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/threading.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/threading.rst	Sun Aug  8 12:41:24 2010
@@ -310,8 +310,8 @@
 
       Return whether the thread is alive.
 
-      Roughly, a thread is alive from the moment the :meth:`start` method
-      returns until its :meth:`run` method terminates. The module function
+      This method returns ``True`` just before the :meth:`run` method starts
+      until just after the :meth:`run` method terminates.  The module function
       :func:`.enumerate` returns a list of all alive threads.
 
    .. attribute:: daemon

Modified: python/branches/py3k-dtoa/Doc/library/tkinter.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/tkinter.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/tkinter.rst	Sun Aug  8 12:41:24 2010
@@ -9,7 +9,9 @@
 The :mod:`tkinter` package ("Tk interface") is the standard Python interface to
 the Tk GUI toolkit.  Both Tk and :mod:`tkinter` are available on most Unix
 platforms, as well as on Windows systems.  (Tk itself is not part of Python; it
-is maintained at ActiveState.)
+is maintained at ActiveState.) You can check that :mod:`tkinter` is properly
+installed on your system by running ``python -m tkinter`` from the command line;
+this should open a window demonstrating a simple Tk interface.
 
 .. seealso::
 

Modified: python/branches/py3k-dtoa/Doc/library/unittest.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/unittest.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/unittest.rst	Sun Aug  8 12:41:24 2010
@@ -621,20 +621,20 @@
 
 The following decorators implement test skipping and expected failures:
 
-.. function:: skip(reason)
+.. decorator:: skip(reason)
 
    Unconditionally skip the decorated test.  *reason* should describe why the
    test is being skipped.
 
-.. function:: skipIf(condition, reason)
+.. decorator:: skipIf(condition, reason)
 
    Skip the decorated test if *condition* is true.
 
-.. function:: skipUnless(condition, reason)
+.. decorator:: skipUnless(condition, reason)
 
    Skip the decoratored test unless *condition* is true.
 
-.. function:: expectedFailure
+.. decorator:: expectedFailure
 
    Mark the test as an expected failure.  If the test fails when run, the test
    is not counted as a failure.
@@ -1048,11 +1048,11 @@
       :attr:`exception` attribute.  This can be useful if the intention
       is to perform additional checks on the exception raised::
 
-        with self.assertRaises(SomeException) as cm:
-            do_something()
+         with self.assertRaises(SomeException) as cm:
+             do_something()
 
-        the_exception = cm.exception
-        self.assertEqual(the_exception.error_code, 3)
+         the_exception = cm.exception
+         self.assertEqual(the_exception.error_code, 3)
 
       .. versionchanged:: 3.1
          Added the ability to use :meth:`assertRaises` as a context manager.

Modified: python/branches/py3k-dtoa/Doc/library/urllib.parse.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/urllib.parse.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/urllib.parse.rst	Sun Aug  8 12:41:24 2010
@@ -48,6 +48,23 @@
       >>> o.geturl()
       'http://www.cwi.nl:80/%7Eguido/Python.html'
 
+   If the scheme value is not specified, urlparse following the syntax
+   specifications from RFC 1808, expects the netloc value to start with '//',
+   Otherwise, it is not possible to distinguish between net_loc and path
+   component and would classify the indistinguishable component as path as in
+   a relative url.
+
+       >>> from urlparse import urlparse
+       >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
+       ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
+                  params='', query='', fragment='')
+       >>> urlparse('www.cwi.nl:80/%7Eguido/Python.html')
+       ParseResult(scheme='', netloc='', path='www.cwi.nl:80/%7Eguido/Python.html',
+                  params='', query='', fragment='')
+       >>> urlparse('help/Python.html')
+       ParseResult(scheme='', netloc='', path='help/Python.html', params='',
+                  query='', fragment='')
+
    If the *scheme* argument is specified, it gives the default addressing
    scheme, to be used only if the URL does not specify one.  The default value for
    this argument is the empty string.

Modified: python/branches/py3k-dtoa/Doc/library/urllib.request.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/urllib.request.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/urllib.request.rst	Sun Aug  8 12:41:24 2010
@@ -638,7 +638,8 @@
    :meth:`unknown_open`.
 
    Note that the implementation of these methods may involve calls of the parent
-   :class:`OpenerDirector` instance's :meth:`.open` and :meth:`.error` methods.
+   :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and
+   :meth:`~OpenerDirector.error` methods.
 
 #. Every handler with a method named like :meth:`protocol_response` has that
    method called to post-process the response.

Modified: python/branches/py3k-dtoa/Doc/library/wsgiref.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/wsgiref.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/wsgiref.rst	Sun Aug  8 12:41:24 2010
@@ -187,9 +187,7 @@
 .. class:: Headers(headers)
 
    Create a mapping-like object wrapping *headers*, which must be a list of header
-   name/value tuples as described in :pep:`333`.  Any changes made to the new
-   :class:`Headers` object will directly update the *headers* list it was created
-   with.
+   name/value tuples as described in :pep:`333`.
 
    :class:`Headers` objects support typical mapping operations including
    :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`,

Modified: python/branches/py3k-dtoa/Doc/library/xml.dom.minidom.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/xml.dom.minidom.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/xml.dom.minidom.rst	Sun Aug  8 12:41:24 2010
@@ -136,18 +136,20 @@
 
 .. method:: Node.toxml(encoding=None)
 
-   Return the XML that the DOM represents as a string.
-
-   With no argument, the XML header does not specify an encoding, and the result is
-   Unicode string if the default encoding cannot represent all characters in the
-   document. Encoding this string in an encoding other than UTF-8 is likely
-   incorrect, since UTF-8 is the default encoding of XML.
-
-   With an explicit *encoding* [1]_ argument, the result is a byte string in the
-   specified encoding. It is recommended that this argument is always specified. To
-   avoid :exc:`UnicodeError` exceptions in case of unrepresentable text data, the
-   encoding argument should be specified as "utf-8".
+   Return a string or byte string containing the XML represented by
+   the DOM node.
 
+   With an explicit *encoding* [1]_ argument, the result is a byte
+   string in the specified encoding.  It is recommended that you
+   always specify an encoding; you may use any encoding you like, but
+   an argument of "utf-8" is the most common choice, avoiding
+   :exc:`UnicodeError` exceptions in case of unrepresentable text
+   data.
+
+   With no *encoding* argument, the result is a Unicode string, and the
+   XML declaration in the resulting string does not specify an
+   encoding. Encoding this string in an encoding other than UTF-8 is
+   likely incorrect, since UTF-8 is the default encoding of XML.
 
 .. method:: Node.toprettyxml(indent="", newl="", encoding="")
 
@@ -155,7 +157,8 @@
    indentation string and defaults to a tabulator; *newl* specifies the string
    emitted at the end of each line and defaults to ``\n``.
 
-   There's also an *encoding* argument; see :meth:`toxml`.
+   The *encoding* argument behaves like the corresponding argument of
+   :meth:`toxml`.
 
 
 .. _dom-example:
@@ -240,7 +243,9 @@
 
 .. rubric:: Footnotes
 
-.. [#] 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
+.. [#] The encoding name included in the XML output should conform to
+   the appropriate standards. For example, "UTF-8" is valid, but
+   "UTF8" is not valid in an XML document's declaration, even though
+   Python accepts it as an encoding name.
+   See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
    and http://www.iana.org/assignments/character-sets .

Modified: python/branches/py3k-dtoa/Doc/library/xml.dom.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/xml.dom.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/xml.dom.rst	Sun Aug  8 12:41:24 2010
@@ -976,29 +976,24 @@
 Type Mapping
 ^^^^^^^^^^^^
 
-The primitive IDL types used in the DOM specification are mapped to Python types
+The IDL types used in the DOM specification are mapped to Python types
 according to the following table.
 
 +------------------+-------------------------------------------+
 | IDL Type         | Python Type                               |
 +==================+===========================================+
-| ``boolean``      | ``IntegerType`` (with a value of ``0`` or |
-|                  | ``1``)                                    |
+| ``boolean``      | ``bool`` or ``int``                       |
 +------------------+-------------------------------------------+
-| ``int``          | ``IntegerType``                           |
+| ``int``          | ``int``                                   |
 +------------------+-------------------------------------------+
-| ``long int``     | ``IntegerType``                           |
+| ``long int``     | ``int``                                   |
 +------------------+-------------------------------------------+
-| ``unsigned int`` | ``IntegerType``                           |
+| ``unsigned int`` | ``int``                                   |
++------------------+-------------------------------------------+
+| ``DOMString``    | ``str`` or ``bytes``                      |
++------------------+-------------------------------------------+
+| ``null``         | ``None``                                  |
 +------------------+-------------------------------------------+
-
-Additionally, the :class:`DOMString` defined in the recommendation is mapped to
-a bytes or string object.  Applications should be able to handle
-Unicode whenever a string is returned from the DOM.
-
-The IDL ``null`` value is mapped to ``None``, which may be accepted or
-provided by the implementation whenever ``null`` is allowed by the API.
-
 
 .. _dom-accessor-methods:
 

Modified: python/branches/py3k-dtoa/Doc/library/xml.sax.reader.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/xml.sax.reader.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/xml.sax.reader.rst	Sun Aug  8 12:41:24 2010
@@ -154,7 +154,7 @@
    Allow an application to set the locale for errors and warnings.
 
    SAX parsers are not required to provide localization for errors and warnings; if
-   they cannot support the requested locale, however, they must throw a SAX
+   they cannot support the requested locale, however, they must raise a SAX
    exception.  Applications may request a locale change in the middle of a parse.
 
 

Modified: python/branches/py3k-dtoa/Doc/library/zipfile.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/library/zipfile.rst	(original)
+++ python/branches/py3k-dtoa/Doc/library/zipfile.rst	Sun Aug  8 12:41:24 2010
@@ -12,10 +12,8 @@
 defined in `PKZIP Application Note
 <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
 
-This module does not currently handle multi-disk ZIP files, or ZIP files
-which have appended comments (although it correctly handles comments
-added to individual archive members---for which see the :ref:`zipinfo-objects`
-documentation). It can handle ZIP files that use the ZIP64 extensions
+This module does not currently handle multi-disk ZIP files.
+It can handle ZIP files that use the ZIP64 extensions
 (that is ZIP files that are more than 4 GByte in size).  It supports
 decryption of encrypted files in ZIP archives, but it currently cannot
 create an encrypted file.  Decryption is extremely slow as it is
@@ -64,7 +62,6 @@
 
    Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
    otherwise returns ``False``.  *filename* may be a file or file-like object too.
-   This module does not currently handle ZIP files which have appended comments.
 
    .. versionchanged:: 3.1
       Support for file and file-like objects.

Modified: python/branches/py3k-dtoa/Doc/license.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/license.rst	(original)
+++ python/branches/py3k-dtoa/Doc/license.rst	Sun Aug  8 12:41:24 2010
@@ -106,6 +106,10 @@
 +----------------+--------------+------------+------------+-----------------+
 | 3.1.1          | 3.1          | 2009       | PSF        | yes             |
 +----------------+--------------+------------+------------+-----------------+
+| 3.1.2          | 3.1          | 2010       | PSF        | yes             |
++----------------+--------------+------------+------------+-----------------+
+| 3.2            | 3.1          | 2010       | PSF        | yes             |
++----------------+--------------+------------+------------+-----------------+
 
 .. note::
 

Modified: python/branches/py3k-dtoa/Doc/make.bat
==============================================================================
--- python/branches/py3k-dtoa/Doc/make.bat	(original)
+++ python/branches/py3k-dtoa/Doc/make.bat	Sun Aug  8 12:41:24 2010
@@ -34,7 +34,7 @@
 goto end
 
 :checkout
-svn co %SVNROOT%/external/Sphinx-0.6.5/sphinx tools/sphinx
+svn co %SVNROOT%/external/Sphinx-1.0.1/sphinx tools/sphinx
 svn co %SVNROOT%/external/docutils-0.6/docutils tools/docutils
 svn co %SVNROOT%/external/Jinja-2.3.1/jinja2 tools/jinja2
 svn co %SVNROOT%/external/Pygments-1.3.1/pygments tools/pygments

Modified: python/branches/py3k-dtoa/Doc/reference/compound_stmts.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/reference/compound_stmts.rst	(original)
+++ python/branches/py3k-dtoa/Doc/reference/compound_stmts.rst	Sun Aug  8 12:41:24 2010
@@ -552,24 +552,27 @@
 
 A class definition defines a class object (see section :ref:`types`):
 
-.. XXX need to document PEP 3115 changes here (new metaclasses)
-
 .. productionlist::
    classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite`
-   inheritance: "(" [`expression_list`] ")"
+   inheritance: "(" [`argument_list` [","] ] ")"
    classname: `identifier`
 
 
-A class definition is an executable statement.  It first evaluates the
-inheritance list, if present.  Each item in the inheritance list should evaluate
-to a class object or class type which allows subclassing.  The class's suite is
-then executed in a new execution frame (see section :ref:`naming`), using a
-newly created local namespace and the original global namespace. (Usually, the
-suite contains only function definitions.)  When the class's suite finishes
-execution, its execution frame is discarded but its local namespace is
-saved. [#]_ A class object is then created using the inheritance list for the
-base classes and the saved local namespace for the attribute dictionary.  The
-class name is bound to this class object in the original local namespace.
+A class definition is an executable statement.  The inheritance list usually
+gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so
+each item in the list should evaluate to a class object which allows
+subclassing.
+
+The class's suite is then executed in a new execution frame (see :ref:`naming`),
+using a newly created local namespace and the original global namespace.
+(Usually, the suite contains mostly function definitions.)  When the class's
+suite finishes execution, its execution frame is discarded but its local
+namespace is saved. [#]_ A class object is then created using the inheritance
+list for the base classes and the saved local namespace for the attribute
+dictionary.  The class name is bound to this class object in the original local
+namespace.
+
+Class creation can be customized heavily using :ref:`metaclasses <metaclasses>`.
 
 Classes can also be decorated; as with functions, ::
 
@@ -583,25 +586,20 @@
    Foo = f1(arg)(f2(Foo))
 
 **Programmer's note:** Variables defined in the class definition are class
-variables; they are shared by instances. Instance variables can be set in a
-method with ``self.name = value``.  Both class and instance variables are
-accessible through the notation "``self.name``", and an instance variable hides
-a class variable with the same name when accessed in this way.  Class variables
-can be used as defaults for instance variables, but using mutable values there
-can lead to unexpected results.  Descriptors can be used to create instance
-variables with different implementation details.
+attributes; they are shared by instances.  Instance attributes can be set in a
+method with ``self.name = value``.  Both class and instance attributes are
+accessible through the notation "``self.name``", and an instance attribute hides
+a class attribute with the same name when accessed in this way.  Class
+attributes can be used as defaults for instance attributes, but using mutable
+values there can lead to unexpected results.  :ref:`Descriptors <descriptors>`
+can be used to create instance variables with different implementation details.
 
-.. XXX add link to descriptor docs above
 
 .. seealso::
 
+   :pep:`3116` - Metaclasses in Python 3
    :pep:`3129` - Class Decorators
 
-Class definitions, like function definitions, may be wrapped by one or more
-:term:`decorator` expressions.  The evaluation rules for the decorator
-expressions are the same as for functions.  The result must be a class object,
-which is then bound to the class name.
-
 
 .. rubric:: Footnotes
 

Modified: python/branches/py3k-dtoa/Doc/reference/expressions.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/reference/expressions.rst	(original)
+++ python/branches/py3k-dtoa/Doc/reference/expressions.rst	Sun Aug  8 12:41:24 2010
@@ -1031,9 +1031,9 @@
   ``x <= y``.  If the corresponding element does not exist, the shorter
   sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
 
-* Mappings (dictionaries) compare equal if and only if their sorted ``(key,
-  value)`` lists compare equal. [#]_ Outcomes other than equality are resolved
-  consistently, but are not otherwise defined. [#]_
+* Mappings (dictionaries) compare equal if and only if they have the same
+  ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
+  raise :exc:`TypeError`.
 
 * Sets and frozensets define comparison operators to mean subset and superset
   tests.  Those relations do not define total orderings (the two sets ``{1,2}``
@@ -1330,15 +1330,6 @@
    strings in a human recognizable way, compare using
    :func:`unicodedata.normalize`.
 
-.. [#] The implementation computes this efficiently, without constructing lists
-   or sorting.
-
-.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
-   value) lists, but this was very expensive for the common case of comparing
-   for equality.  An even earlier version of Python compared dictionaries by
-   identity only, but this caused surprises because people expected to be able
-   to test a dictionary for emptiness by comparing it to ``{}``.
-
 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
    descriptors, you may notice seemingly unusual behaviour in certain uses of
    the :keyword:`is` operator, like those involving comparisons between instance

Modified: python/branches/py3k-dtoa/Doc/reference/lexical_analysis.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/reference/lexical_analysis.rst	(original)
+++ python/branches/py3k-dtoa/Doc/reference/lexical_analysis.rst	Sun Aug  8 12:41:24 2010
@@ -362,11 +362,12 @@
       information on this convention.
 
 ``__*__``
-   System-defined names.  These names are defined by the interpreter and its
-   implementation (including the standard library); applications should not expect
-   to define additional names using this convention.  The set of names of this
-   class defined by Python may be extended in future versions. See section
-   :ref:`specialnames`.
+   System-defined names. These names are defined by the interpreter and its
+   implementation (including the standard library).  Current system names are
+   discussed in the :ref:`specialnames` section and elsewhere.  More will likely
+   be defined in future versions of Python.  *Any* use of ``__*__`` names, in
+   any context, that does not follow explicitly documented use, is subject to
+   breakage without warning.
 
 ``__*``
    Class-private names.  Names in this category, when used within the context of a

Modified: python/branches/py3k-dtoa/Doc/tools/sphinx-build.py
==============================================================================
--- python/branches/py3k-dtoa/Doc/tools/sphinx-build.py	(original)
+++ python/branches/py3k-dtoa/Doc/tools/sphinx-build.py	Sun Aug  8 12:41:24 2010
@@ -3,11 +3,15 @@
     Sphinx - Python documentation toolchain
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-    :copyright: 2007 by Georg Brandl.
+    :copyright: 2007-2010 by Georg Brandl.
     :license: Python license.
 """
 
 import sys
+import warnings
+
+# Get rid of UserWarnings reported by pkg_resources.
+warnings.filterwarnings('ignore', category=UserWarning, module='jinja2')
 
 if __name__ == '__main__':
 

Modified: python/branches/py3k-dtoa/Doc/tools/sphinxext/indexsidebar.html
==============================================================================
--- python/branches/py3k-dtoa/Doc/tools/sphinxext/indexsidebar.html	(original)
+++ python/branches/py3k-dtoa/Doc/tools/sphinxext/indexsidebar.html	Sun Aug  8 12:41:24 2010
@@ -2,8 +2,7 @@
             <p><a href="{{ pathto('download') }}">Download these documents</a></p>
 	    <h3>Docs for other versions</h3>
 	    <ul>
-	      <li><a href="http://docs.python.org/2.6/">Python 2.6 (stable)</a></li>
-	      <li><a href="http://docs.python.org/2.7/">Python 2.7 (in development)</a></li>
+	      <li><a href="http://docs.python.org/2.7/">Python 2.7 (stable)</a></li>
 	      <li><a href="http://docs.python.org/3.1/">Python 3.1 (stable)</a></li>
               <li><a href="http://www.python.org/doc/versions/">Old versions</a></li>
             </ul>

Modified: python/branches/py3k-dtoa/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/py3k-dtoa/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/py3k-dtoa/Doc/tools/sphinxext/pyspecific.py	Sun Aug  8 12:41:24 2010
@@ -72,6 +72,32 @@
         return [pnode]
 
 
+# Support for documenting decorators
+
+from sphinx import addnodes
+from sphinx.domains.python import PyModulelevel, PyClassmember
+
+class PyDecoratorMixin(object):
+    def handle_signature(self, sig, signode):
+        ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
+        signode.insert(0, addnodes.desc_addname('@', '@'))
+        return ret
+
+    def needs_arglist(self):
+        return False
+
+class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
+    def run(self):
+        # a decorator function is a function after all
+        self.name = 'py:function'
+        return PyModulelevel.run(self)
+
+class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
+    def run(self):
+        self.name = 'py:method'
+        return PyClassmember.run(self)
+
+
 # Support for building "topic help" for pydoc
 
 pydoc_topic_labels = [
@@ -119,10 +145,10 @@
         for label in self.status_iterator(pydoc_topic_labels,
                                           'building topics... ',
                                           length=len(pydoc_topic_labels)):
-            if label not in self.env.labels:
+            if label not in self.env.domaindata['std']['labels']:
                 self.warn('label %r not in documentation' % label)
                 continue
-            docname, labelid, sectname = self.env.labels[label]
+            docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
             doctree = self.env.get_and_resolve_doctree(docname, self)
             document = new_document('<section node>')
             document.append(doctree.ids[labelid])
@@ -147,7 +173,6 @@
 # Support for documenting Opcodes
 
 import re
-from sphinx import addnodes
 
 opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
 
@@ -165,6 +190,28 @@
     return opname.strip()
 
 
+pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
+
+# later...
+#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+  |  # identifiers
+#                                   [.,:]+     |  # punctuation
+#                                   [\[\]()]   |  # parens
+#                                   \s+           # whitespace
+#                                   ''', re.X)
+
+def parse_pdb_command(env, sig, signode):
+    """Transform a pdb command signature into RST nodes."""
+    m = pdbcmd_sig_re.match(sig)
+    if m is None:
+        raise ValueError
+    name, args = m.groups()
+    fullname = name.replace('(', '').replace(')', '')
+    signode += addnodes.desc_name(name, name)
+    if args:
+        signode += addnodes.desc_addname(' '+args, ' '+args)
+    return fullname
+
+
 def setup(app):
     app.add_role('issue', issue_role)
     app.add_directive('impl-detail', ImplementationDetail)
@@ -172,4 +219,8 @@
     app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
     app.add_description_unit('opcode', 'opcode', '%s (opcode)',
                              parse_opcode_signature)
+    app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
+                             parse_pdb_command)
     app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
+    app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
+    app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)

Modified: python/branches/py3k-dtoa/Doc/tutorial/classes.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/tutorial/classes.rst	(original)
+++ python/branches/py3k-dtoa/Doc/tutorial/classes.rst	Sun Aug  8 12:41:24 2010
@@ -65,7 +65,7 @@
 A *namespace* is a mapping from names to objects.  Most namespaces are currently
 implemented as Python dictionaries, but that's normally not noticeable in any
 way (except for performance), and it may change in the future.  Examples of
-namespaces are: the set of built-in names (functions such as :func:`abs`, and
+namespaces are: the set of built-in names (containing functions such as :func:`abs`, and
 built-in exception names); the global names in a module; and the local names in
 a function invocation.  In a sense the set of attributes of an object also form
 a namespace.  The important thing to know about namespaces is that there is
@@ -599,12 +599,12 @@
 possible to access or modify a variable that is considered private.  This can
 even be useful in special circumstances, such as in the debugger.
 
-Notice that code passed to ``exec()``, ``eval()`` or ``execfile()`` does not
-consider the classname of the invoking  class to be the current class; this is
-similar to the effect of the  ``global`` statement, the effect of which is
-likewise restricted to  code that is byte-compiled together.  The same
-restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well
-as when referencing ``__dict__`` directly.
+Notice that code passed to ``exec()`` or ``eval()`` does not consider the
+classname of the invoking class to be the current class; this is similar to the
+effect of the ``global`` statement, the effect of which is likewise restricted
+to code that is byte-compiled together.  The same restriction applies to
+``getattr()``, ``setattr()`` and ``delattr()``, as well as when referencing
+``__dict__`` directly.
 
 
 .. _tut-odds:
@@ -737,7 +737,7 @@
    StopIteration
 
 Having seen the mechanics behind the iterator protocol, it is easy to add
-iterator behavior to your classes.  Define a :meth:`__iter__` method which
+iterator behavior to your classes.  Define an :meth:`__iter__` method which
 returns an object with a :meth:`__next__` method.  If the class defines
 :meth:`__next__`, then :meth:`__iter__` can just return ``self``::
 
@@ -754,7 +754,10 @@
            self.index = self.index - 1
            return self.data[self.index]
 
-   >>> for char in Reverse('spam'):
+   >>> rev = Reverse('spam')
+   >>> iter(rev)
+   <__main__.Reverse object at 0x00A1DB50>
+   >>> for char in rev:
    ...     print(char)
    ...
    m

Modified: python/branches/py3k-dtoa/Doc/tutorial/datastructures.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/tutorial/datastructures.rst	(original)
+++ python/branches/py3k-dtoa/Doc/tutorial/datastructures.rst	Sun Aug  8 12:41:24 2010
@@ -377,16 +377,12 @@
 
 Here is a brief demonstration::
 
-   >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
-   >>> fruit = set(basket)               # create a set without duplicates
-   >>> fruit
-   {'orange', 'pear', 'apple', 'banana'}
-   >>> fruit = {'orange', 'apple'}       # {} syntax is equivalent to [] for lists
-   >>> fruit
-   {'orange', 'apple'}
-   >>> 'orange' in fruit                 # fast membership testing
+   >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
+   >>> print(basket)                      # show that duplicates have been removed
+   {'orange', 'bananna', 'pear', 'apple'}
+   >>> 'orange' in basket                 # fast membership testing
    True
-   >>> 'crabgrass' in fruit
+   >>> 'crabgrass' in basket
    False
 
    >>> # Demonstrate set operations on unique letters from two words

Modified: python/branches/py3k-dtoa/Doc/tutorial/floatingpoint.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/tutorial/floatingpoint.rst	(original)
+++ python/branches/py3k-dtoa/Doc/tutorial/floatingpoint.rst	Sun Aug  8 12:41:24 2010
@@ -81,7 +81,7 @@
 values share the same approximation, any one of them could be displayed
 while still preserving the invariant ``eval(repr(x)) == x``.
 
-Historically, the Python prompt and built-in :func:`repr` function would chose
+Historically, the Python prompt and built-in :func:`repr` function would choose
 the one with 17 significant digits, ``0.10000000000000001``.   Starting with
 Python 3.1, Python (on most systems) is now able to choose the shortest of
 these and simply display ``0.1``.
@@ -92,18 +92,17 @@
 (although some languages may not *display* the difference by default, or in all
 output modes).
 
-Python's built-in :func:`str` function produces only 12 significant digits, and
-you may wish to use that instead.  It's unusual for ``eval(str(x))`` to
-reproduce *x*, but the output may be more pleasant to look at::
+For more pleasant output, you may may wish to use string formatting to produce a limited number of significant digits::
 
-   >>> str(math.pi)
+   >>> format(math.pi, '.12g')  # give 12 significant digits
    '3.14159265359'
 
+   >>> format(math.pi, '.2f')   # give 2 digits after the point
+   '3.14'
+
    >>> repr(math.pi)
    '3.141592653589793'
 
-   >>> format(math.pi, '.2f')
-   '3.14'
 
 It's important to realize that this is, in a real sense, an illusion: you're
 simply rounding the *display* of the true machine value.

Modified: python/branches/py3k-dtoa/Doc/using/cmdline.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/using/cmdline.rst	(original)
+++ python/branches/py3k-dtoa/Doc/using/cmdline.rst	Sun Aug  8 12:41:24 2010
@@ -61,7 +61,7 @@
 
 .. cmdoption:: -c <command>
 
-   Execute the Python code in *command*.  *command* can be one ore more
+   Execute the Python code in *command*.  *command* can be one or more
    statements separated by newlines, with significant leading whitespace as in
    normal module code.
 

Modified: python/branches/py3k-dtoa/Doc/whatsnew/2.0.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/whatsnew/2.0.rst	(original)
+++ python/branches/py3k-dtoa/Doc/whatsnew/2.0.rst	Sun Aug  8 12:41:24 2010
@@ -656,7 +656,7 @@
 The change which will probably break the most code is tightening up the
 arguments accepted by some methods.  Some methods would take multiple arguments
 and treat them as a tuple, particularly various list methods such as
-:meth:`.append` and :meth:`.insert`. In earlier versions of Python, if ``L`` is
+:meth:`append` and :meth:`insert`. In earlier versions of Python, if ``L`` is
 a list, ``L.append( 1,2 )`` appends the tuple ``(1,2)`` to the list.  In Python
 2.0 this causes a :exc:`TypeError` exception to be raised, with the message:
 'append requires exactly 1 argument; 2 given'.  The fix is to simply add an

Modified: python/branches/py3k-dtoa/Doc/whatsnew/2.4.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/whatsnew/2.4.rst	(original)
+++ python/branches/py3k-dtoa/Doc/whatsnew/2.4.rst	Sun Aug  8 12:41:24 2010
@@ -1066,7 +1066,7 @@
   deprecated APIs and removes support for Python versions earlier than 2.3.  The
   3.0 version of the package uses a new incremental parser for MIME messages,
   available in the :mod:`email.FeedParser` module.  The new parser doesn't require
-  reading the entire message into memory, and doesn't throw exceptions if a
+  reading the entire message into memory, and doesn't raise exceptions if a
   message is malformed; instead it records any problems in the  :attr:`defect`
   attribute of the message.  (Developed by Anthony Baxter, Barry Warsaw, Thomas
   Wouters, and others.)

Modified: python/branches/py3k-dtoa/Doc/whatsnew/2.5.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/whatsnew/2.5.rst	(original)
+++ python/branches/py3k-dtoa/Doc/whatsnew/2.5.rst	Sun Aug  8 12:41:24 2010
@@ -1765,7 +1765,7 @@
 http://effbot.org/zone/element-index.htm.
 
 ElementTree represents an XML document as a tree of element nodes. The text
-content of the document is stored as the :attr:`.text` and :attr:`.tail`
+content of the document is stored as the :attr:`text` and :attr:`tail`
 attributes of  (This is one of the major differences between ElementTree and
 the Document Object Model; in the DOM there are many different types of node,
 including :class:`TextNode`.)

Modified: python/branches/py3k-dtoa/Doc/whatsnew/2.7.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/whatsnew/2.7.rst	(original)
+++ python/branches/py3k-dtoa/Doc/whatsnew/2.7.rst	Sun Aug  8 12:41:24 2010
@@ -146,7 +146,7 @@
 * Float-to-string and string-to-float conversions now round their
   results more correctly, and :func:`repr` of a floating-point
   number *x* returns a result that's guaranteed to round back to the
-  same number when converted back to a string.
+  same number when converted back to a float.
 * The :ctype:`PyCapsule` type, used to provide a C API for extension modules.
 * The :cfunc:`PyLong_AsLongAndOverflow` C API function.
 

Modified: python/branches/py3k-dtoa/Doc/whatsnew/3.2.rst
==============================================================================
--- python/branches/py3k-dtoa/Doc/whatsnew/3.2.rst	(original)
+++ python/branches/py3k-dtoa/Doc/whatsnew/3.2.rst	Sun Aug  8 12:41:24 2010
@@ -66,18 +66,46 @@
 New, Improved, and Deprecated Modules
 =====================================
 
-* The :class:`ftplib.FTP` class now supports the context manager protocol
-  (Contributed by Tarek Ziadé and Giampaolo Rodolà; :issue:`4972`.)
+* The functools module now includes two new decorators for caching function
+  calls, :func:`functools.lru_cache` and :func:`functools.lfu_cache`. These can
+  save repeated queries to an external resource whenever the results are
+  expected to be the same.
+
+  For example, adding a caching decorator to a database query function can save
+  database accesses for popular searches::
+
+      @functools.lfu_cache(maxsize=50)
+      def get_phone_number(name):
+          c = conn.cursor()
+          c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
+          return c.fetchone()[0]
+
+  The caches support two strategies for limiting their size to *maxsize*. The
+  LFU (least-frequently-used) cache works bests when popular queries remain the
+  same over time.  In contrast, the LRU (least-recently-used) cache works best
+  query popularity changes over time (for example, the most popular news
+  articles change each day as newer articles are added).
+
+  The two caching decorators can be composed (nested) to handle hybrid cases.
+  For example, music searches can reflect both long-term patterns (popular
+  classics) and short-term trends (new releases)::
+
+        @functools.lfu_cache(maxsize=500)
+        @functools.lru_cache(maxsize=100)
+        def find_lyrics(song):
+            query = 'http://www.example.com/songlist/%s' % urllib.quote(song)
+            page = urllib.urlopen(query).read()
+            return parse_lyrics(page)
+
+  To help with choosing an effective cache size, the wrapped function
+  is instrumented with two attributes *hits* and *misses*::
+
+        >>> for song in user_requests:
+        ...     find_lyrics(song)
+        >>> print(find_lyrics.hits, find_lyrics.misses)
+        4805 980
 
-* The previously deprecated :func:`string.maketrans` function has been
-  removed in favor of the static methods, :meth:`bytes.maketrans` and
-  :meth:`bytearray.maketrans`.  This change solves the confusion around which
-  types were supported by the :mod:`string` module. Now, :class:`str`,
-  :class:`bytes`, and :class:`bytearray` each have their own **maketrans** and
-  **translate** methods with intermediate translation tables of the
-  appropriate type.
-
-  (Contributed by Georg Brandl; :issue:`5675`.)
+  (Contributed by Raymond Hettinger)
 
 * The previously deprecated :func:`contextlib.nested` function has been
   removed in favor of a plain :keyword:`with` statement which can
@@ -88,17 +116,20 @@
   (Contributed by Georg Brandl and Mattias Brändström;
   `appspot issue 53094 <http://codereview.appspot.com/53094>`_.)
 
+* The :class:`ftplib.FTP` class now supports the context manager protocol
+  (Contributed by Tarek Ziadé and Giampaolo Rodolà; :issue:`4972`.)
+
 * The :func:`shutil.copytree` function has two new options:
 
   * *ignore_dangling_symlinks*: when ``symlinks=False`` (meaning that the
     function copies the file pointed to by the symlink, not the symlink
-    itself) this option will silence the error thrown if the file doesn't
+    itself) this option will silence the error raised if the file doesn't
     exist.
 
   * *copy_function*: a callable that will be used to copy files.
     :func:`shutil.copy2` is used by default.
 
-  (Contributed by Tarek Ziade.)
+  (Contributed by Tarek Ziadé.)
 
 * The *sqlite3* module has some new features:
 
@@ -111,6 +142,47 @@
     are uncommitted changes, and :const:`False` otherwise.  (Contributed
     by R. David Murray and Shashwat Anand, :issue:`8845`.)
 
+* The :mod:`ssl` module has a new class, :class:`~ssl.SSLContext` which
+  serves as a container for various persistent SSL data, such as protocol
+  settings, certificates, private keys, and various other options.
+  The :meth:`~ssl.SSLContext.wrap_socket` method allows to create an
+  SSL socket from such an SSL context.
+  (Added by Antoine Pitrou; :issue:`8550`.)
+
+  The :func:`ssl.wrap_socket` constructor function now takes a
+  *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>`__.
+  (Added by Antoine Pitrou; :issue:`8322`.)
+
+  Various options have been added to the :mod:`ssl` module, such as
+  :data:`~ssl.OP_NO_SSLv2` which allows to force disabling of the insecure
+  and obsolete SSLv2 protocol.
+  (Added by Antoine Pitrou; :issue:`4870`.)
+
+  Another change makes the extension load all of OpenSSL's ciphers and
+  digest algorithms so that they're all available.  Some SSL
+  certificates couldn't be verified, reporting an "unknown algorithm"
+  error.  (Reported by Beda Kosata, and fixed by Antoine Pitrou;
+  :issue:`8484`.)
+
+  The version of OpenSSL being used is now available as the module
+  attributes :data:`ssl.OPENSSL_VERSION` (a string),
+  :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
+  :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer).  (Added by Antoine
+  Pitrou; :issue:`8321`.)
+
+* The previously deprecated :func:`string.maketrans` function has been
+  removed in favor of the static methods, :meth:`bytes.maketrans` and
+  :meth:`bytearray.maketrans`.  This change solves the confusion around which
+  types were supported by the :mod:`string` module. Now, :class:`str`,
+  :class:`bytes`, and :class:`bytearray` each have their own **maketrans** and
+  **translate** methods with intermediate translation tables of the
+  appropriate type.
+
+  (Contributed by Georg Brandl; :issue:`5675`.)
+
 
 Multi-threading
 ===============

Modified: python/branches/py3k-dtoa/Grammar/Grammar
==============================================================================
--- python/branches/py3k-dtoa/Grammar/Grammar	(original)
+++ python/branches/py3k-dtoa/Grammar/Grammar	Sun Aug  8 12:41:24 2010
@@ -24,13 +24,13 @@
 decorated: decorators (classdef | funcdef)
 funcdef: 'def' NAME parameters ['->' test] ':' suite
 parameters: '(' [typedargslist] ')'
-typedargslist: ((tfpdef ['=' test] ',')*
-                ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
-                | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
+typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
+       ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]]
+     |  '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
 tfpdef: NAME [':' test]
-varargslist: ((vfpdef ['=' test] ',')*
-              ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] | '**' vfpdef)
-              | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
+varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [','
+       ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]]
+     |  '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
 vfpdef: NAME
 
 stmt: simple_stmt | compound_stmt

Modified: python/branches/py3k-dtoa/Include/Python.h
==============================================================================
--- python/branches/py3k-dtoa/Include/Python.h	(original)
+++ python/branches/py3k-dtoa/Include/Python.h	Sun Aug  8 12:41:24 2010
@@ -61,6 +61,7 @@
 #error "PYMALLOC_DEBUG requires WITH_PYMALLOC"
 #endif
 #include "pymath.h"
+#include "pytime.h"
 #include "pymem.h"
 
 #include "object.h"
@@ -134,13 +135,8 @@
 }
 #endif
 
-/* Convert a possibly signed character to a nonnegative int */
-/* XXX This assumes characters are 8 bits wide */
-#ifdef __CHAR_UNSIGNED__
-#define Py_CHARMASK(c)		(c)
-#else
+/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
 #define Py_CHARMASK(c)		((unsigned char)((c) & 0xff))
-#endif
 
 #include "pyfpe.h"
 

Modified: python/branches/py3k-dtoa/Include/floatobject.h
==============================================================================
--- python/branches/py3k-dtoa/Include/floatobject.h	(original)
+++ python/branches/py3k-dtoa/Include/floatobject.h	Sun Aug  8 12:41:24 2010
@@ -21,12 +21,6 @@
 #define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type)
 #define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type)
 
-/* The str() precision PyFloat_STR_PRECISION is chosen so that in most cases,
-   the rounding noise created by various operations is suppressed, while
-   giving plenty of precision for practical use. */
-
-#define PyFloat_STR_PRECISION 12
-
 #ifdef Py_NAN
 #define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN)
 #endif

Modified: python/branches/py3k-dtoa/Include/patchlevel.h
==============================================================================
--- python/branches/py3k-dtoa/Include/patchlevel.h	(original)
+++ python/branches/py3k-dtoa/Include/patchlevel.h	Sun Aug  8 12:41:24 2010
@@ -20,10 +20,10 @@
 #define PY_MINOR_VERSION	2
 #define PY_MICRO_VERSION	0
 #define PY_RELEASE_LEVEL	PY_RELEASE_LEVEL_ALPHA
-#define PY_RELEASE_SERIAL	0
+#define PY_RELEASE_SERIAL	1
 
 /* Version as a string */
-#define PY_VERSION      	"3.2a0"
+#define PY_VERSION      	"3.2a1+"
 /*--end constants--*/
 
 /* Subversion Revision number of this file (not of the repository) */

Modified: python/branches/py3k-dtoa/Include/structseq.h
==============================================================================
--- python/branches/py3k-dtoa/Include/structseq.h	(original)
+++ python/branches/py3k-dtoa/Include/structseq.h	Sun Aug  8 12:41:24 2010
@@ -26,17 +26,12 @@
 
 PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type);
 
-typedef struct {
-    PyObject_VAR_HEAD
-    PyObject *ob_item[1];
-} PyStructSequence;
+typedef PyTupleObject PyStructSequence;
 
 /* Macro, *only* to be used to fill in brand new objects */
-#define PyStructSequence_SET_ITEM(op, i, v) \
-    (((PyStructSequence *)(op))->ob_item[i] = v)
+#define PyStructSequence_SET_ITEM(op, i, v) PyTuple_SET_ITEM(op, i, v)
 
-#define PyStructSequence_GET_ITEM(op, i) \
-    (((PyStructSequence *)(op))->ob_item[i])
+#define PyStructSequence_GET_ITEM(op, i) PyTuple_GET_ITEM(op, i)
 
 
 #ifdef __cplusplus

Modified: python/branches/py3k-dtoa/LICENSE
==============================================================================
--- python/branches/py3k-dtoa/LICENSE	(original)
+++ python/branches/py3k-dtoa/LICENSE	Sun Aug  8 12:41:24 2010
@@ -68,6 +68,7 @@
     3.1             3.0.1       2009        PSF         yes
     3.1.1           3.1         2009        PSF         yes
     3.1.2           3.1         2010        PSF         yes
+    3.2             3.1         2010        PSF         yes
 
 Footnotes:
 

Modified: python/branches/py3k-dtoa/Lib/_abcoll.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/_abcoll.py	(original)
+++ python/branches/py3k-dtoa/Lib/_abcoll.py	Sun Aug  8 12:41:24 2010
@@ -18,11 +18,6 @@
            "MappingView", "KeysView", "ItemsView", "ValuesView",
            "Sequence", "MutableSequence",
            "ByteString",
-           "bytearray_iterator", "bytes_iterator", "dict_itemiterator",
-           "dict_items", "dict_keyiterator", "dict_keys", "dict_proxy",
-           "dict_valueiterator", "dict_values", "list_iterator",
-           "list_reverseiterator", "range_iterator", "set_iterator",
-           "str_iterator", "tuple_iterator", "zip_iterator",
            ]
 
 
@@ -480,7 +475,15 @@
         except KeyError:
             pass
 
-    def update(self, other=(), **kwds):
+    def update(*args, **kwds):
+        if len(args) > 2:
+            raise TypeError("update() takes at most 2 positional "
+                            "arguments ({} given)".format(len(args)))
+        elif not args:
+            raise TypeError("update() takes at least 1 argument (0 given)")
+        self = args[0]
+        other = args[1] if len(args) >= 2 else ()
+
         if isinstance(other, Mapping):
             for key in other:
                 self[key] = other[key]

Modified: python/branches/py3k-dtoa/Lib/_strptime.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/_strptime.py	(original)
+++ python/branches/py3k-dtoa/Lib/_strptime.py	Sun Aug  8 12:41:24 2010
@@ -482,8 +482,8 @@
     tt = _strptime(data_string, format)[0]
     return time.struct_time(tt[:9])
 
-def _strptime_datetime(class_, data_string, format="%a %b %d %H:%M:%S %Y"):
-    """Return a class_ instance based on the input string and the
+def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
+    """Return a class cls instance based on the input string and the
     format string."""
     tt, fraction = _strptime(data_string, format)
     gmtoff, tzname = tt[-2:]
@@ -496,4 +496,4 @@
             tz = datetime_timezone(tzdelta)
         args += (tz,)
 
-    return class_(*args)
+    return cls(*args)

Modified: python/branches/py3k-dtoa/Lib/argparse.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/argparse.py	(original)
+++ python/branches/py3k-dtoa/Lib/argparse.py	Sun Aug  8 12:41:24 2010
@@ -1561,13 +1561,16 @@
 
         # add help and version arguments if necessary
         # (using explicit default to override global argument_default)
+        default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
         if self.add_help:
             self.add_argument(
-                '-h', '--help', action='help', default=SUPPRESS,
+                default_prefix+'h', default_prefix*2+'help',
+                action='help', default=SUPPRESS,
                 help=_('show this help message and exit'))
         if self.version:
             self.add_argument(
-                '-v', '--version', action='version', default=SUPPRESS,
+                default_prefix+'v', default_prefix*2+'version',
+                action='version', default=SUPPRESS,
                 version=self.version,
                 help=_("show program's version number and exit"))
 

Modified: python/branches/py3k-dtoa/Lib/ast.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ast.py	(original)
+++ python/branches/py3k-dtoa/Lib/ast.py	Sun Aug  8 12:41:24 2010
@@ -50,7 +50,7 @@
     if isinstance(node_or_string, Expression):
         node_or_string = node_or_string.body
     def _convert(node):
-        if isinstance(node, Str):
+        if isinstance(node, (Str, Bytes)):
             return node.s
         elif isinstance(node, Num):
             return node.n
@@ -58,6 +58,8 @@
             return tuple(map(_convert, node.elts))
         elif isinstance(node, List):
             return list(map(_convert, node.elts))
+        elif isinstance(node, Set):
+            return set(map(_convert, node.elts))
         elif isinstance(node, Dict):
             return dict((_convert(k), _convert(v)) for k, v
                         in zip(node.keys, node.values))

Modified: python/branches/py3k-dtoa/Lib/asyncore.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/asyncore.py	(original)
+++ python/branches/py3k-dtoa/Lib/asyncore.py	Sun Aug  8 12:41:24 2010
@@ -435,8 +435,11 @@
             self.handle_read()
 
     def handle_connect_event(self):
-        self.connected = True
+        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
+        if err != 0:
+            raise socket.error(err, _strerror(err))
         self.handle_connect()
+        self.connected = True
 
     def handle_write_event(self):
         if self.accepting:
@@ -607,6 +610,14 @@
         def send(self, *args):
             return os.write(self.fd, *args)
 
+        def getsockopt(self, level, optname, buflen=None):
+            if (level == socket.SOL_SOCKET and
+                optname == socket.SO_ERROR and
+                not buflen):
+                return 0
+            raise NotImplementedError("Only asyncore specific behaviour "
+                                      "implemented.")
+
         read = recv
         write = send
 

Modified: python/branches/py3k-dtoa/Lib/base64.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/base64.py	(original)
+++ python/branches/py3k-dtoa/Lib/base64.py	Sun Aug  8 12:41:24 2010
@@ -241,7 +241,7 @@
         acc += _b32rev[c] << shift
         shift -= 5
         if shift < 0:
-            parts.append(binascii.unhexlify('%010x' % acc))
+            parts.append(binascii.unhexlify(bytes('%010x' % acc, "ascii")))
             acc = 0
             shift = 35
     # Process the last, partial quanta

Modified: python/branches/py3k-dtoa/Lib/bdb.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/bdb.py	(original)
+++ python/branches/py3k-dtoa/Lib/bdb.py	Sun Aug  8 12:41:24 2010
@@ -109,6 +109,8 @@
                self.is_skipped_module(frame.f_globals.get('__name__')):
             return False
         if frame is self.stopframe:
+            if self.stoplineno == -1:
+                return False
             return frame.f_lineno >= self.stoplineno
         while frame is not None and frame is not self.stopframe:
             if frame is self.botframe:
@@ -165,23 +167,28 @@
         but only if we are to stop at or just below this level."""
         pass
 
-    def _set_stopinfo(self, stopframe, returnframe, stoplineno=-1):
+    def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
         self.stopframe = stopframe
         self.returnframe = returnframe
         self.quitting = 0
+        # stoplineno >= 0 means: stop at line >= the stoplineno
+        # stoplineno -1 means: don't stop at all
         self.stoplineno = stoplineno
 
     # Derived classes and clients can call the following methods
     # to affect the stepping state.
 
-    def set_until(self, frame): #the name "until" is borrowed from gdb
+    def set_until(self, frame, lineno=None):
         """Stop when the line with the line no greater than the current one is
         reached or when returning from current frame"""
-        self._set_stopinfo(frame, frame, frame.f_lineno+1)
+        # the name "until" is borrowed from gdb
+        if lineno is None:
+            lineno = frame.f_lineno + 1
+        self._set_stopinfo(frame, frame, lineno)
 
     def set_step(self):
         """Stop after one line of code."""
-        self._set_stopinfo(None,None)
+        self._set_stopinfo(None, None)
 
     def set_next(self, frame):
         """Stop on the next line in or below the given frame."""
@@ -208,7 +215,7 @@
 
     def set_continue(self):
         # Don't stop except at breakpoints or when finished
-        self._set_stopinfo(self.botframe, None)
+        self._set_stopinfo(self.botframe, None, -1)
         if not self.breaks:
             # no breakpoints; run without debugger overhead
             sys.settrace(None)
@@ -263,15 +270,9 @@
 
     def clear_bpbynumber(self, arg):
         try:
-            number = int(arg)
-        except:
-            return 'Non-numeric breakpoint number (%s)' % arg
-        try:
-            bp = Breakpoint.bpbynumber[number]
-        except IndexError:
-            return 'Breakpoint number (%d) out of range' % number
-        if not bp:
-            return 'Breakpoint (%d) already deleted' % number
+            bp = self.get_bpbynumber(arg)
+        except ValueError as err:
+            return str(err)
         self.clear_break(bp.file, bp.line)
 
     def clear_all_file_breaks(self, filename):
@@ -292,6 +293,21 @@
                 bp.deleteMe()
         self.breaks = {}
 
+    def get_bpbynumber(self, arg):
+        if not arg:
+            raise ValueError('Breakpoint number expected')
+        try:
+            number = int(arg)
+        except ValueError:
+            raise ValueError('Non-numeric breakpoint number %s' % arg)
+        try:
+            bp = Breakpoint.bpbynumber[number]
+        except IndexError:
+            raise ValueError('Breakpoint number %d out of range' % number)
+        if bp is None:
+            raise ValueError('Breakpoint %d already deleted' % number)
+        return bp
+
     def get_break(self, filename, lineno):
         filename = self.canonic(filename)
         return filename in self.breaks and \
@@ -361,8 +377,9 @@
         if line: s = s + lprefix + line.strip()
         return s
 
-    # The following two methods can be called by clients to use
-    # a debugger to debug a statement, given as a string.
+    # The following methods can be called by clients to use
+    # a debugger to debug a statement or an expression.
+    # Both can be given as a string, or a code object.
 
     def run(self, cmd, globals=None, locals=None):
         if globals is None:
@@ -372,8 +389,6 @@
             locals = globals
         self.reset()
         sys.settrace(self.trace_dispatch)
-        if not isinstance(cmd, types.CodeType):
-            cmd = cmd+'\n'
         try:
             exec(cmd, globals, locals)
         except BdbQuit:
@@ -390,8 +405,6 @@
             locals = globals
         self.reset()
         sys.settrace(self.trace_dispatch)
-        if not isinstance(expr, types.CodeType):
-            expr = expr+'\n'
         try:
             return eval(expr, globals, locals)
         except BdbQuit:
@@ -486,6 +499,9 @@
     def bpprint(self, out=None):
         if out is None:
             out = sys.stdout
+        print(self.bpformat(), file=out)
+
+    def bpformat(self):
         if self.temporary:
             disp = 'del  '
         else:
@@ -494,17 +510,22 @@
             disp = disp + 'yes  '
         else:
             disp = disp + 'no   '
-        print('%-4dbreakpoint   %s at %s:%d' % (self.number, disp,
-                                                       self.file, self.line), file=out)
+        ret = '%-4dbreakpoint   %s at %s:%d' % (self.number, disp,
+                                                self.file, self.line)
         if self.cond:
-            print('\tstop only if %s' % (self.cond,), file=out)
+            ret += '\n\tstop only if %s' % (self.cond,)
         if self.ignore:
-            print('\tignore next %d hits' % (self.ignore), file=out)
-        if (self.hits):
-            if (self.hits > 1): ss = 's'
-            else: ss = ''
-            print(('\tbreakpoint already hit %d time%s' %
-                          (self.hits, ss)), file=out)
+            ret += '\n\tignore next %d hits' % (self.ignore,)
+        if self.hits:
+            if self.hits > 1:
+                ss = 's'
+            else:
+                ss = ''
+            ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss)
+        return ret
+
+    def __str__(self):
+        return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
 
 # -----------end of Breakpoint class----------
 

Modified: python/branches/py3k-dtoa/Lib/cProfile.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/cProfile.py	(original)
+++ python/branches/py3k-dtoa/Lib/cProfile.py	Sun Aug  8 12:41:24 2010
@@ -36,7 +36,7 @@
             result = prof.print_stats(sort)
     return result
 
-def runctx(statement, globals, locals, filename=None):
+def runctx(statement, globals, locals, filename=None, sort=-1):
     """Run statement under profiler, supplying your own globals and locals,
     optionally saving results in filename.
 
@@ -53,7 +53,7 @@
         if filename is not None:
             prof.dump_stats(filename)
         else:
-            result = prof.print_stats()
+            result = prof.print_stats(sort)
     return result
 
 # ____________________________________________________________
@@ -164,7 +164,8 @@
     parser.add_option('-o', '--outfile', dest="outfile",
         help="Save stats to <outfile>", default=None)
     parser.add_option('-s', '--sort', dest="sort",
-        help="Sort order when printing to stdout, based on pstats.Stats class", default=-1)
+        help="Sort order when printing to stdout, based on pstats.Stats class",
+        default=-1)
 
     if not sys.argv[1:]:
         parser.print_usage()
@@ -173,14 +174,18 @@
     (options, args) = parser.parse_args()
     sys.argv[:] = args
 
-    if (len(sys.argv) > 0):
-        sys.path.insert(0, os.path.dirname(sys.argv[0]))
-        fp = open(sys.argv[0])
-        try:
-            script = fp.read()
-        finally:
-            fp.close()
-        run('exec(%r)' % script, options.outfile, options.sort)
+    if len(args) > 0:
+        progname = args[0]
+        sys.path.insert(0, os.path.dirname(progname))
+        with open(progname, 'rb') as fp:
+            code = compile(fp.read(), progname, 'exec')
+        globs = {
+            '__file__': progname,
+            '__name__': '__main__',
+            '__package__': None,
+            '__cached__': None,
+        }
+        runctx(code, globs, None, options.outfile, options.sort)
     else:
         parser.print_usage()
     return parser

Modified: python/branches/py3k-dtoa/Lib/cmd.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/cmd.py	(original)
+++ python/branches/py3k-dtoa/Lib/cmd.py	Sun Aug  8 12:41:24 2010
@@ -84,7 +84,6 @@
         sys.stdin and sys.stdout are used.
 
         """
-        import sys
         if stdin is not None:
             self.stdin = stdin
         else:
@@ -134,7 +133,7 @@
                         if not len(line):
                             line = 'EOF'
                         else:
-                            line = line[:-1] # chop \n
+                            line = line.rstrip('\r\n')
                 line = self.precmd(line)
                 stop = self.onecmd(line)
                 stop = self.postcmd(stop, line)

Modified: python/branches/py3k-dtoa/Lib/collections.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/collections.py	(original)
+++ python/branches/py3k-dtoa/Lib/collections.py	Sun Aug  8 12:41:24 2010
@@ -11,16 +11,12 @@
 from keyword import iskeyword as _iskeyword
 import sys as _sys
 import heapq as _heapq
-from weakref import proxy as _proxy
 from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
 
 ################################################################################
 ### OrderedDict
 ################################################################################
 
-class _Link(object):
-    __slots__ = 'prev', 'next', 'key', '__weakref__'
-
 class OrderedDict(dict, MutableMapping):
     'Dictionary that remembers insertion order'
     # An inherited dict maps keys to values.
@@ -31,9 +27,7 @@
     # The internal self.__map dictionary maps keys to links in a doubly linked list.
     # The circular doubly linked list starts and ends with a sentinel element.
     # The sentinel element never gets deleted (this simplifies the algorithm).
-    # The prev/next links are weakref proxies (to prevent circular references).
-    # Individual links are kept alive by the hard reference in self.__map.
-    # Those hard references disappear when a key is deleted from an OrderedDict.
+    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].
 
     def __init__(self, *args, **kwds):
         '''Initialize an ordered dictionary.  Signature is the same as for
@@ -46,56 +40,51 @@
         try:
             self.__root
         except AttributeError:
-            self.__root = root = _Link()    # sentinel node for the doubly linked list
-            root.prev = root.next = root
+            self.__root = root = [None, None, None]     # sentinel node
+            PREV = 0
+            NEXT = 1
+            root[PREV] = root[NEXT] = root
             self.__map = {}
         self.update(*args, **kwds)
 
-    def clear(self):
-        'od.clear() -> None.  Remove all items from od.'
-        root = self.__root
-        root.prev = root.next = root
-        self.__map.clear()
-        dict.clear(self)
-
-    def __setitem__(self, key, value):
+    def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
         'od.__setitem__(i, y) <==> od[i]=y'
         # Setting a new item creates a new link which goes at the end of the linked
         # list, and the inherited dictionary is updated with the new key/value pair.
         if key not in self:
-            self.__map[key] = link = _Link()
             root = self.__root
-            last = root.prev
-            link.prev, link.next, link.key = last, root, key
-            last.next = root.prev = _proxy(link)
-        dict.__setitem__(self, key, value)
+            last = root[PREV]
+            last[NEXT] = root[PREV] = self.__map[key] = [last, root, key]
+        dict_setitem(self, key, value)
 
-    def __delitem__(self, key):
+    def __delitem__(self, key, PREV=0, NEXT=1, dict_delitem=dict.__delitem__):
         'od.__delitem__(y) <==> del od[y]'
         # Deleting an existing item uses self.__map to find the link which is
         # then removed by updating the links in the predecessor and successor nodes.
-        dict.__delitem__(self, key)
+        dict_delitem(self, key)
         link = self.__map.pop(key)
-        link.prev.next = link.next
-        link.next.prev = link.prev
+        link_prev = link[PREV]
+        link_next = link[NEXT]
+        link_prev[NEXT] = link_next
+        link_next[PREV] = link_prev
 
-    def __iter__(self):
+    def __iter__(self, NEXT=1, KEY=2):
         'od.__iter__() <==> iter(od)'
         # Traverse the linked list in order.
         root = self.__root
-        curr = root.next
+        curr = root[NEXT]
         while curr is not root:
-            yield curr.key
-            curr = curr.next
+            yield curr[KEY]
+            curr = curr[NEXT]
 
-    def __reversed__(self):
+    def __reversed__(self, PREV=0, KEY=2):
         'od.__reversed__() <==> reversed(od)'
         # Traverse the linked list in reverse order.
         root = self.__root
-        curr = root.prev
+        curr = root[PREV]
         while curr is not root:
-            yield curr.key
-            curr = curr.prev
+            yield curr[KEY]
+            curr = curr[PREV]
 
     def __reduce__(self):
         'Return state information for pickling'
@@ -108,12 +97,24 @@
             return (self.__class__, (items,), inst_dict)
         return self.__class__, (items,)
 
+    def clear(self):
+        'od.clear() -> None.  Remove all items from od.'
+        try:
+            for node in self.__map.values():
+                del node[:]
+            self.__root[:] = [self.__root, self.__root, None]
+            self.__map.clear()
+        except AttributeError:
+            pass
+        dict.clear(self)
+
     setdefault = MutableMapping.setdefault
     update = MutableMapping.update
     pop = MutableMapping.pop
     keys = MutableMapping.keys
     values = MutableMapping.values
     items = MutableMapping.items
+    __ne__ = MutableMapping.__ne__
 
     def popitem(self, last=True):
         '''od.popitem() -> (k, v), return and remove a (key, value) pair.
@@ -157,13 +158,8 @@
                    all(p==q for p, q in zip(self.items(), other.items()))
         return dict.__eq__(self, other)
 
-    def __ne__(self, other):
-        '''od.__ne__(y) <==> od!=y.  Comparison to another OD is order-sensitive
-        while comparison to a regular mapping is order-insensitive.
-
-        '''
-        return not self == other
-
+    def __del__(self):
+        self.clear()                # eliminate cyclical references
 
 
 ################################################################################
@@ -244,7 +240,7 @@
             return result \n
         def __repr__(self):
             'Return a nicely formatted representation string'
-            return '%(typename)s(%(reprtxt)s)' %% self \n
+            return self.__class__.__name__ + '(%(reprtxt)s)' %% self \n
         def _asdict(self):
             'Return a new OrderedDict which maps field names to their values'
             return OrderedDict(zip(self._fields, self)) \n

Modified: python/branches/py3k-dtoa/Lib/configparser.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/configparser.py	(original)
+++ python/branches/py3k-dtoa/Lib/configparser.py	Sun Aug  8 12:41:24 2010
@@ -1,6 +1,6 @@
 """Configuration file parser.
 
-A setup file consists of sections, lead by a "[section]" header,
+A configuration file consists of sections, lead by a "[section]" header,
 and followed by "name: value" entries, with continuations and such in
 the style of RFC 822.
 
@@ -24,67 +24,88 @@
 
     methods:
 
-    __init__(defaults=None)
-        create the parser and specify a dictionary of intrinsic defaults.  The
-        keys must be strings, the values must be appropriate for %()s string
-        interpolation.  Note that `__name__' is always an intrinsic default;
-        its value is the section's name.
+    __init__(defaults=None, dict_type=_default_dict,
+             delimiters=('=', ':'), comment_prefixes=('#', ';'),
+             empty_lines_in_values=True, allow_no_value=False):
+        Create the parser. When `defaults' is given, it is initialized into the
+        dictionary or intrinsic defaults. The keys must be strings, the values
+        must be appropriate for %()s string interpolation.  Note that `__name__'
+        is always an intrinsic default; its value is the section's name.
+
+        When `dict_type' is given, it will be used to create the dictionary
+        objects for the list of sections, for the options within a section, and
+        for the default values.
+
+        When `delimiters' is given, it will be used as the set of substrings
+        that divide keys from values.
+
+        When `comment_prefixes' is given, it will be used as the set of
+        substrings that prefix comments in a line.
+
+        When `empty_lines_in_values' is False (default: True), each empty line
+        marks the end of an option. Otherwise, internal empty lines of
+        a multiline option are kept as part of the value.
+
+        When `allow_no_value' is True (default: False), options without
+        values are accepted; the value presented for these is None.
 
     sections()
-        return all the configuration section names, sans DEFAULT
+        Return all the configuration section names, sans DEFAULT.
 
     has_section(section)
-        return whether the given section exists
+        Return whether the given section exists.
 
     has_option(section, option)
-        return whether the given option exists in the given section
+        Return whether the given option exists in the given section.
 
     options(section)
-        return list of configuration options for the named section
+        Return list of configuration options for the named section.
 
-    read(filenames)
-        read and parse the list of named configuration files, given by
+    read(filenames, encoding=None)
+        Read and parse the list of named configuration files, given by
         name.  A single filename is also allowed.  Non-existing files
         are ignored.  Return list of successfully read files.
 
     readfp(fp, filename=None)
-        read and parse one configuration file, given as a file object.
+        Read and parse one configuration file, given as a file object.
         The filename defaults to fp.name; it is only used in error
         messages (if fp has no `name' attribute, the string `<???>' is used).
 
     get(section, option, raw=False, vars=None)
-        return a string value for the named option.  All % interpolations are
+        Return a string value for the named option.  All % interpolations are
         expanded in the return values, based on the defaults passed into the
         constructor and the DEFAULT section.  Additional substitutions may be
         provided using the `vars' argument, which must be a dictionary whose
         contents override any pre-existing defaults.
 
     getint(section, options)
-        like get(), but convert value to an integer
+        Like get(), but convert value to an integer.
 
     getfloat(section, options)
-        like get(), but convert value to a float
+        Like get(), but convert value to a float.
 
     getboolean(section, options)
-        like get(), but convert value to a boolean (currently case
+        Like get(), but convert value to a boolean (currently case
         insensitively defined as 0, false, no, off for False, and 1, true,
         yes, on for True).  Returns False or True.
 
     items(section, raw=False, vars=None)
-        return a list of tuples with (name, value) for each option
+        Return a list of tuples with (name, value) for each option
         in the section.
 
     remove_section(section)
-        remove the given file section and all its options
+        Remove the given file section and all its options.
 
     remove_option(section, option)
-        remove the given option from the given section
+        Remove the given option from the given section.
 
     set(section, option, value)
-        set the given option
+        Set the given option.
 
-    write(fp)
-        write the configuration state in .ini format
+    write(fp, space_around_delimiters=True)
+        Write the configuration state in .ini format. If
+        `space_around_delimiters' is True (the default), delimiters
+        between keys and values are surrounded by spaces.
 """
 
 try:
@@ -94,6 +115,7 @@
     _default_dict = dict
 
 import re
+import sys
 
 __all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
            "InterpolationError", "InterpolationDepthError",
@@ -114,17 +136,19 @@
 
     def _get_message(self):
         """Getter for 'message'; needed only to override deprecation in
-        BaseException."""
+        BaseException.
+        """
         return self.__message
 
     def _set_message(self, value):
         """Setter for 'message'; needed only to override deprecation in
-        BaseException."""
+        BaseException.
+        """
         self.__message = value
 
     # BaseException.message has been deprecated since Python 2.6.  To prevent
-    # DeprecationWarning from popping up over this pre-existing attribute, use
-    # a new property that takes lookup precedence.
+    # DeprecationWarning from popping up over this pre-existing attribute, use a
+    # new property that takes lookup precedence.
     message = property(_get_message, _set_message)
 
     def __init__(self, msg=''):
@@ -136,12 +160,15 @@
 
     __str__ = __repr__
 
+
 class NoSectionError(Error):
     """Raised when no section matches a requested option."""
 
     def __init__(self, section):
         Error.__init__(self, 'No section: %r' % (section,))
         self.section = section
+        self.args = (section, )
+
 
 class DuplicateSectionError(Error):
     """Raised when a section is multiply-created."""
@@ -149,6 +176,8 @@
     def __init__(self, section):
         Error.__init__(self, "Section %r already exists" % section)
         self.section = section
+        self.args = (section, )
+
 
 class NoOptionError(Error):
     """A requested option was not found."""
@@ -158,6 +187,8 @@
                        (option, section))
         self.option = option
         self.section = section
+        self.args = (option, section)
+
 
 class InterpolationError(Error):
     """Base class for interpolation-related exceptions."""
@@ -166,6 +197,8 @@
         Error.__init__(self, msg)
         self.option = option
         self.section = section
+        self.args = (option, section, msg)
+
 
 class InterpolationMissingOptionError(InterpolationError):
     """A string substitution required a setting which was not available."""
@@ -179,11 +212,14 @@
                % (section, option, reference, rawval))
         InterpolationError.__init__(self, option, section, msg)
         self.reference = reference
+        self.args = (option, section, rawval, reference)
+
 
 class InterpolationSyntaxError(InterpolationError):
     """Raised when the source text into which substitutions are made
     does not conform to the required syntax."""
 
+
 class InterpolationDepthError(InterpolationError):
     """Raised when substitutions are nested too deeply."""
 
@@ -194,6 +230,8 @@
                "\trawval : %s\n"
                % (section, option, rawval))
         InterpolationError.__init__(self, option, section, msg)
+        self.args = (option, section, rawval)
+
 
 class ParsingError(Error):
     """Raised when a configuration file does not follow legal syntax."""
@@ -202,11 +240,13 @@
         Error.__init__(self, 'File contains parsing errors: %s' % filename)
         self.filename = filename
         self.errors = []
+        self.args = (filename, )
 
     def append(self, lineno, line):
         self.errors.append((lineno, line))
         self.message += '\n\t[line %2d]: %s' % (lineno, line)
 
+
 class MissingSectionHeaderError(ParsingError):
     """Raised when a key-value pair is found before any section header."""
 
@@ -218,21 +258,76 @@
         self.filename = filename
         self.lineno = lineno
         self.line = line
+        self.args = (filename, lineno, line)
 
 
 class RawConfigParser:
+    """ConfigParser that does not do interpolation."""
+
+    # Regular expressions for parsing section headers and options
+    _SECT_TMPL = r"""
+        \[                                 # [
+        (?P<header>[^]]+)                  # very permissive!
+        \]                                 # ]
+        """
+    _OPT_TMPL = r"""
+        (?P<option>.*?)                    # very permissive!
+        \s*(?P<vi>{delim})\s*              # any number of space/tab,
+                                           # followed by any of the
+                                           # allowed delimiters,
+                                           # followed by any space/tab
+        (?P<value>.*)$                     # everything up to eol
+        """
+    _OPT_NV_TMPL = r"""
+        (?P<option>.*?)                    # very permissive!
+        \s*(?:                             # any number of space/tab,
+        (?P<vi>{delim})\s*                 # optionally followed by
+                                           # any of the allowed
+                                           # delimiters, followed by any
+                                           # space/tab
+        (?P<value>.*))?$                   # everything up to eol
+        """
+
+    # Compiled regular expression for matching sections
+    SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
+    # Compiled regular expression for matching options with typical separators
+    OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
+    # Compiled regular expression for matching options with optional values
+    # delimited using typical separators
+    OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
+    # Compiled regular expression for matching leading whitespace in a line
+    NONSPACECRE = re.compile(r"\S")
+    # Select backwards-compatible inline comment character behavior
+    # (; and # are comments at the start of a line, but ; only inline)
+    _COMPATIBLE = object()
+
     def __init__(self, defaults=None, dict_type=_default_dict,
-                 allow_no_value=False):
+                 delimiters=('=', ':'), comment_prefixes=_COMPATIBLE,
+                 empty_lines_in_values=True, allow_no_value=False):
         self._dict = dict_type
         self._sections = self._dict()
         self._defaults = self._dict()
-        if allow_no_value:
-            self._optcre = self.OPTCRE_NV
-        else:
-            self._optcre = self.OPTCRE
         if defaults:
             for key, value in defaults.items():
                 self._defaults[self.optionxform(key)] = value
+        self._delimiters = tuple(delimiters)
+        if delimiters == ('=', ':'):
+            self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
+        else:
+            delim = "|".join(re.escape(d) for d in delimiters)
+            if allow_no_value:
+                self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=delim),
+                                          re.VERBOSE)
+            else:
+                self._optcre = re.compile(self._OPT_TMPL.format(delim=delim),
+                                          re.VERBOSE)
+        if comment_prefixes is self._COMPATIBLE:
+            self._startonly_comment_prefixes = ('#',)
+            self._comment_prefixes = (';',)
+        else:
+            self._startonly_comment_prefixes = ()
+            self._comment_prefixes = tuple(comment_prefixes or ())
+        self._empty_lines_in_values = empty_lines_in_values
 
     def defaults(self):
         return self._defaults
@@ -274,7 +369,7 @@
             del opts['__name__']
         return list(opts.keys())
 
-    def read(self, filenames):
+    def read(self, filenames, encoding=None):
         """Read and parse a filename or a list of filenames.
 
         Files that cannot be opened are silently ignored; this is
@@ -291,7 +386,7 @@
         read_ok = []
         for filename in filenames:
             try:
-                fp = open(filename)
+                fp = open(filename, encoding=encoding)
             except IOError:
                 continue
             self._read(fp, filename)
@@ -306,7 +401,6 @@
         second argument is the `filename', which if not given, is
         taken from fp.name.  If fp has no `name' attribute, `<???>' is
         used.
-
         """
         if filename is None:
             try:
@@ -367,6 +461,7 @@
 
     def has_option(self, section, option):
         """Check for the existence of a given option in a given section."""
+
         if not section or section == DEFAULTSECT:
             option = self.optionxform(option)
             return option in self._defaults
@@ -379,6 +474,7 @@
 
     def set(self, section, option, value=None):
         """Set an option."""
+
         if not section or section == DEFAULTSECT:
             sectdict = self._defaults
         else:
@@ -388,23 +484,34 @@
                 raise NoSectionError(section)
         sectdict[self.optionxform(option)] = value
 
-    def write(self, fp):
-        """Write an .ini-format representation of the configuration state."""
+    def write(self, fp, space_around_delimiters=True):
+        """Write an .ini-format representation of the configuration state.
+
+        If `space_around_delimiters' is True (the default), delimiters
+        between keys and values are surrounded by spaces.
+        """
+        if space_around_delimiters:
+            d = " {} ".format(self._delimiters[0])
+        else:
+            d = self._delimiters[0]
         if self._defaults:
-            fp.write("[%s]\n" % DEFAULTSECT)
-            for (key, value) in self._defaults.items():
-                fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
-            fp.write("\n")
+            self._write_section(fp, DEFAULTSECT, self._defaults.items(), d)
         for section in self._sections:
-            fp.write("[%s]\n" % section)
-            for (key, value) in self._sections[section].items():
-                if key != "__name__":
-                    if value is None:
-                        fp.write("%s\n" % (key))
-                    else:
-                        fp.write("%s = %s\n" %
-                                 (key, str(value).replace('\n', '\n\t')))
-            fp.write("\n")
+            self._write_section(fp, section,
+                                self._sections[section].items(), d)
+
+    def _write_section(self, fp, section_name, section_items, delimiter):
+        """Write a single section to the specified `fp'."""
+        fp.write("[{}]\n".format(section_name))
+        for key, value in section_items:
+            if key == "__name__":
+                continue
+            if value is not None:
+                value = delimiter + str(value).replace('\n', '\n\t')
+            else:
+                value = ""
+            fp.write("{}{}\n".format(key, value))
+        fp.write("\n")
 
     def remove_option(self, section, option):
         """Remove an option."""
@@ -428,66 +535,66 @@
             del self._sections[section]
         return existed
 
-    #
-    # Regular expressions for parsing section headers and options.
-    #
-    SECTCRE = re.compile(
-        r'\['                                 # [
-        r'(?P<header>[^]]+)'                  # very permissive!
-        r'\]'                                 # ]
-        )
-    OPTCRE = re.compile(
-        r'(?P<option>[^:=\s][^:=]*)'          # very permissive!
-        r'\s*(?P<vi>[:=])\s*'                 # any number of space/tab,
-                                              # followed by separator
-                                              # (either : or =), followed
-                                              # by any # space/tab
-        r'(?P<value>.*)$'                     # everything up to eol
-        )
-    OPTCRE_NV = re.compile(
-        r'(?P<option>[^:=\s][^:=]*)'          # very permissive!
-        r'\s*(?:'                             # any number of space/tab,
-        r'(?P<vi>[:=])\s*'                    # optionally followed by
-                                              # separator (either : or
-                                              # =), followed by any #
-                                              # space/tab
-        r'(?P<value>.*))?$'                   # everything up to eol
-        )
-
     def _read(self, fp, fpname):
-        """Parse a sectioned setup file.
+        """Parse a sectioned configuration file.
 
-        The sections in setup file contains a title line at the top,
-        indicated by a name in square brackets (`[]'), plus key/value
-        options lines, indicated by `name: value' format lines.
-        Continuations are represented by an embedded newline then
-        leading whitespace.  Blank lines, lines beginning with a '#',
-        and just about everything else are ignored.
+        Each section in a configuration file contains a header, indicated by a
+        name in square brackets (`[]'), plus key/value options, indicated by
+        `name' and `value' delimited with a specific substring (`=' or `:' by
+        default).
+
+        Values can span multiple lines, as long as they are indented deeper than
+        the first line of the value. Depending on the parser's mode, blank lines
+        may be treated as parts of multiline values or ignored.
+
+        Configuration files may include comments, prefixed by specific
+        characters (`#' and `;' by default). Comments may appear on their own in
+        an otherwise empty line or may be entered in lines holding values or
+        section names.
         """
-        cursect = None                            # None, or a dictionary
+        cursect = None                        # None, or a dictionary
         optname = None
         lineno = 0
-        e = None                                  # None, or an exception
-        while True:
-            line = fp.readline()
-            if not line:
-                break
-            lineno = lineno + 1
-            # comment or blank line?
-            if line.strip() == '' or line[0] in '#;':
-                continue
-            if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
-                # no leading whitespace
+        indent_level = 0
+        e = None                              # None, or an exception
+        for lineno, line in enumerate(fp, start=1):
+            # strip full line comments
+            comment_start = None
+            for prefix in self._startonly_comment_prefixes:
+                if line.strip().startswith(prefix):
+                    comment_start = 0
+                    break
+            # strip inline comments
+            for prefix in self._comment_prefixes:
+                index = line.find(prefix)
+                if index == 0 or (index > 0 and line[index-1].isspace()):
+                    comment_start = index
+                    break
+            value = line[:comment_start].strip()
+            if not value:
+                if self._empty_lines_in_values:
+                    # add empty line to the value, but only if there was no
+                    # comment on the line
+                    if (comment_start is None and
+                        cursect is not None and
+                        optname and
+                        cursect[optname] is not None):
+                        cursect[optname].append('') # newlines added at join
+                else:
+                    # empty line marks end of value
+                    indent_level = sys.maxsize
                 continue
             # continuation line?
-            if line[0].isspace() and cursect is not None and optname:
-                value = line.strip()
-                if value:
-                    cursect[optname] = "%s\n%s" % (cursect[optname], value)
+            first_nonspace = self.NONSPACECRE.search(line)
+            cur_indent_level = first_nonspace.start() if first_nonspace else 0
+            if (cursect is not None and optname and
+                cur_indent_level > indent_level):
+                cursect[optname].append(value)
             # a section header or option header?
             else:
+                indent_level = cur_indent_level
                 # is it a section header?
-                mo = self.SECTCRE.match(line)
+                mo = self.SECTCRE.match(value)
                 if mo:
                     sectname = mo.group('header')
                     if sectname in self._sections:
@@ -505,47 +612,61 @@
                     raise MissingSectionHeaderError(fpname, lineno, line)
                 # an option line?
                 else:
-                    mo = self._optcre.match(line)
+                    mo = self._optcre.match(value)
                     if mo:
                         optname, vi, optval = mo.group('option', 'vi', 'value')
+                        if not optname:
+                            e = self._handle_error(e, fpname, lineno, line)
+                        optname = self.optionxform(optname.rstrip())
                         # This check is fine because the OPTCRE cannot
                         # match if it would set optval to None
                         if optval is not None:
-                            if vi in ('=', ':') and ';' in optval:
-                                # ';' is a comment delimiter only if it follows
-                                # a spacing character
-                                pos = optval.find(';')
-                                if pos != -1 and optval[pos-1].isspace():
-                                    optval = optval[:pos]
                             optval = optval.strip()
-                        # allow empty values
-                        if optval == '""':
-                            optval = ''
-                        optname = self.optionxform(optname.rstrip())
-                        cursect[optname] = optval
+                            # allow empty values
+                            if optval == '""':
+                                optval = ''
+                            cursect[optname] = [optval]
+                        else:
+                            # valueless option handling
+                            cursect[optname] = optval
                     else:
-                        # a non-fatal parsing error occurred.  set up the
+                        # a non-fatal parsing error occurred. set up the
                         # exception but keep going. the exception will be
                         # raised at the end of the file and will contain a
                         # list of all bogus lines
-                        if not e:
-                            e = ParsingError(fpname)
-                        e.append(lineno, repr(line))
+                        e = self._handle_error(e, fpname, lineno, line)
         # if any parsing errors occurred, raise an exception
         if e:
             raise e
+        self._join_multiline_values()
+
+    def _join_multiline_values(self):
+        all_sections = [self._defaults]
+        all_sections.extend(self._sections.values())
+        for options in all_sections:
+            for name, val in options.items():
+                if isinstance(val, list):
+                    options[name] = '\n'.join(val).rstrip()
+
+    def _handle_error(self, exc, fpname, lineno, line):
+        if not exc:
+            exc = ParsingError(fpname)
+        exc.append(lineno, repr(line))
+        return exc
 
 
 class ConfigParser(RawConfigParser):
+    """ConfigParser implementing interpolation."""
 
     def get(self, section, option, raw=False, vars=None):
         """Get an option value for a given section.
 
-        All % interpolations are expanded in the return values, based on the
-        defaults passed into the constructor, unless the optional argument
-        `raw' is true.  Additional substitutions may be provided using the
-        `vars' argument, which must be a dictionary whose contents overrides
-        any pre-existing defaults.
+        If `vars' is provided, it must be a dictionary. The option is looked up
+        in `vars' (if provided), `section', and in `defaults' in that order.
+
+        All % interpolations are expanded in the return values, unless the
+        optional argument `raw' is true.  Values for interpolation keys are
+        looked up in the same manner as the option.
 
         The section DEFAULT is special.
         """
@@ -632,6 +753,7 @@
 
 
 class SafeConfigParser(ConfigParser):
+    """ConfigParser implementing sane interpolation."""
 
     def _interpolate(self, section, option, rawval, vars):
         # do the string interpolation

Modified: python/branches/py3k-dtoa/Lib/ctypes/__init__.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/__init__.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/__init__.py	Sun Aug  8 12:41:24 2010
@@ -259,41 +259,31 @@
 
 from _ctypes import POINTER, pointer, _pointer_type_cache
 
-try:
-    from _ctypes import set_conversion_mode
-except ImportError:
-    pass
-else:
-    if _os.name in ("nt", "ce"):
-        set_conversion_mode("mbcs", "strict")
-    else:
-        set_conversion_mode("ascii", "strict")
-
-    class c_wchar_p(_SimpleCData):
-        _type_ = "Z"
+class c_wchar_p(_SimpleCData):
+    _type_ = "Z"
 
-    class c_wchar(_SimpleCData):
-        _type_ = "u"
+class c_wchar(_SimpleCData):
+    _type_ = "u"
 
-    POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param
+POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param
 
-    def create_unicode_buffer(init, size=None):
-        """create_unicode_buffer(aString) -> character array
-        create_unicode_buffer(anInteger) -> character array
-        create_unicode_buffer(aString, anInteger) -> character array
-        """
-        if isinstance(init, (str, bytes)):
-            if size is None:
-                size = len(init)+1
-            buftype = c_wchar * size
-            buf = buftype()
-            buf.value = init
-            return buf
-        elif isinstance(init, int):
-            buftype = c_wchar * init
-            buf = buftype()
-            return buf
-        raise TypeError(init)
+def create_unicode_buffer(init, size=None):
+    """create_unicode_buffer(aString) -> character array
+    create_unicode_buffer(anInteger) -> character array
+    create_unicode_buffer(aString, anInteger) -> character array
+    """
+    if isinstance(init, (str, bytes)):
+        if size is None:
+            size = len(init)+1
+        buftype = c_wchar * size
+        buf = buftype()
+        buf.value = init
+        return buf
+    elif isinstance(init, int):
+        buftype = c_wchar * init
+        buf = buftype()
+        return buf
+    raise TypeError(init)
 
 POINTER(c_char).from_param = c_char_p.from_param #_SimpleCData.c_char_p_from_param
 

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_arrays.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_arrays.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_arrays.py	Sun Aug  8 12:41:24 2010
@@ -42,7 +42,7 @@
 
         CharArray = ARRAY(c_char, 3)
 
-        ca = CharArray("a", "b", "c")
+        ca = CharArray(b"a", b"b", b"c")
 
         # Should this work? It doesn't:
         # CharArray("abc")
@@ -89,7 +89,7 @@
 
     def test_from_address(self):
         # Failed with 0.9.8, reported by JUrner
-        p = create_string_buffer("foo")
+        p = create_string_buffer(b"foo")
         sz = (c_char * 3).from_address(addressof(p))
         self.assertEqual(sz[:], b"foo")
         self.assertEqual(sz[::], b"foo")

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_bitfields.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_bitfields.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_bitfields.py	Sun Aug  8 12:41:24 2010
@@ -37,14 +37,14 @@
             for name in "ABCDEFGHI":
                 b = BITS()
                 setattr(b, name, i)
-                self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name)))
+                self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii')))
 
     def test_shorts(self):
         for i in range(256):
             for name in "MNOPQRS":
                 b = BITS()
                 setattr(b, name, i)
-                self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name)))
+                self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii')))
 
 signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong)
 unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong)

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_buffers.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_buffers.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_buffers.py	Sun Aug  8 12:41:24 2010
@@ -9,19 +9,7 @@
         self.assertEqual(sizeof(b), 32 * sizeof(c_char))
         self.assertTrue(type(b[0]) is bytes)
 
-        b = create_string_buffer("abc")
-        self.assertEqual(len(b), 4) # trailing nul char
-        self.assertEqual(sizeof(b), 4 * sizeof(c_char))
-        self.assertTrue(type(b[0]) is bytes)
-        self.assertEqual(b[0], b"a")
-        self.assertEqual(b[:], b"abc\0")
-        self.assertEqual(b[::], b"abc\0")
-        self.assertEqual(b[::-1], b"\0cba")
-        self.assertEqual(b[::2], b"ac")
-        self.assertEqual(b[::5], b"a")
-
-    def test_string_conversion(self):
-        b = create_string_buffer("abc")
+        b = create_string_buffer(b"abc")
         self.assertEqual(len(b), 4) # trailing nul char
         self.assertEqual(sizeof(b), 4 * sizeof(c_char))
         self.assertTrue(type(b[0]) is bytes)

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_bytes.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_bytes.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_bytes.py	Sun Aug  8 12:41:24 2010
@@ -11,24 +11,21 @@
         (c_char * 3)(b"a", b"b", b"c")
 
     def test_c_wchar(self):
-        x = c_wchar(b"x")
-        x.value = b"y"
-        c_wchar.from_param(b"x")
-        (c_wchar * 3)(b"a", b"b", b"c")
+        x = c_wchar("x")
+        x.value = "y"
+        c_wchar.from_param("x")
+        (c_wchar * 3)("a", "b", "c")
 
     def test_c_char_p(self):
-        c_char_p("foo bar")
         c_char_p(b"foo bar")
 
     def test_c_wchar_p(self):
         c_wchar_p("foo bar")
-        c_wchar_p(b"foo bar")
 
     def test_struct(self):
         class X(Structure):
             _fields_ = [("a", c_char * 3)]
 
-        X("abc")
         x = X(b"abc")
         self.assertEqual(x.a, b"abc")
         self.assertEqual(type(x.a), bytes)
@@ -37,8 +34,7 @@
         class X(Structure):
             _fields_ = [("a", c_wchar * 3)]
 
-        X("abc")
-        x = X(b"abc")
+        x = X("abc")
         self.assertEqual(x.a, "abc")
         self.assertEqual(type(x.a), str)
 
@@ -49,7 +45,6 @@
                 _type_ = "X"
 
             BSTR("abc")
-            BSTR(b"abc")
 
 if __name__ == '__main__':
     unittest.main()

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_callbacks.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_callbacks.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_callbacks.py	Sun Aug  8 12:41:24 2010
@@ -164,7 +164,7 @@
         result = integrate(0.0, 1.0, CALLBACK(func), 10)
         diff = abs(result - 1./3.)
 
-        self.assertTrue(diff < 0.01, "%s not less than 0.01" % diff)
+        self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)
 
     def test_issue_8959_a(self):
         from ctypes.util import find_library

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_cast.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_cast.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_cast.py	Sun Aug  8 12:41:24 2010
@@ -33,17 +33,17 @@
     def test_p2a_objects(self):
         array = (c_char_p * 5)()
         self.assertEqual(array._objects, None)
-        array[0] = "foo bar"
+        array[0] = b"foo bar"
         self.assertEqual(array._objects, {'0': b"foo bar"})
 
         p = cast(array, POINTER(c_char_p))
         # array and p share a common _objects attribute
         self.assertTrue(p._objects is array._objects)
         self.assertEqual(array._objects, {'0': b"foo bar", id(array): array})
-        p[0] = "spam spam"
+        p[0] = b"spam spam"
         self.assertEqual(p._objects, {'0': b"spam spam", id(array): array})
         self.assertTrue(array._objects is p._objects)
-        p[1] = "foo bar"
+        p[1] = b"foo bar"
         self.assertEqual(p._objects, {'1': b'foo bar', '0': b"spam spam", id(array): array})
         self.assertTrue(array._objects is p._objects)
 
@@ -71,7 +71,7 @@
 
     def test_char_p(self):
         # This didn't work: bad argument to internal function
-        s = c_char_p("hiho")
+        s = c_char_p(b"hiho")
         self.assertEqual(cast(cast(s, c_void_p), c_char_p).value,
                              b"hiho")
 

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_cfuncs.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_cfuncs.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_cfuncs.py	Sun Aug  8 12:41:24 2010
@@ -107,7 +107,7 @@
     def test_ulong_plus(self):
         self._dll.tf_bL.restype = c_ulong
         self._dll.tf_bL.argtypes = (c_char, c_ulong)
-        self.assertEqual(self._dll.tf_bL(' ', 4294967295), 1431655765)
+        self.assertEqual(self._dll.tf_bL(b' ', 4294967295), 1431655765)
         self.assertEqual(self.U(), 4294967295)
 
     def test_longlong(self):

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_errno.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_errno.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_errno.py	Sun Aug  8 12:41:24 2010
@@ -19,7 +19,7 @@
 
         libc_open.argtypes = c_char_p, c_int
 
-        self.assertEqual(libc_open("", 0), -1)
+        self.assertEqual(libc_open(b"", 0), -1)
         self.assertEqual(get_errno(), errno.ENOENT)
 
         self.assertEqual(set_errno(32), errno.ENOENT)
@@ -35,7 +35,7 @@
                 else:
                     libc_open = libc.open
                 libc_open.argtypes = c_char_p, c_int
-                self.assertEqual(libc_open("", 0), -1)
+                self.assertEqual(libc_open(b"", 0), -1)
                 self.assertEqual(get_errno(), 0)
 
             t = threading.Thread(target=_worker)

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_internals.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_internals.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_internals.py	Sun Aug  8 12:41:24 2010
@@ -70,19 +70,17 @@
         class Y(Structure):
             _fields_ = [("x", X), ("y", X)]
 
-        s1 = "Hello, World"
-        s2 = "Hallo, Welt"
+        s1 = b"Hello, World"
+        s2 = b"Hallo, Welt"
 
         x = X()
         x.a = s1
         x.b = s2
-        self.assertEqual(x._objects, {"0": bytes(s1, "ascii"),
-                                          "1": bytes(s2, "ascii")})
+        self.assertEqual(x._objects, {"0": s1, "1": s2})
 
         y = Y()
         y.x = x
-        self.assertEqual(y._objects, {"0": {"0": bytes(s1, "ascii"),
-                                                "1": bytes(s2, "ascii")}})
+        self.assertEqual(y._objects, {"0": {"0": s1, "1": s2}})
 ##        x = y.x
 ##        del y
 ##        print x._b_base_._objects

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_keeprefs.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_keeprefs.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_keeprefs.py	Sun Aug  8 12:41:24 2010
@@ -13,9 +13,9 @@
     def test_ccharp(self):
         x = c_char_p()
         self.assertEquals(x._objects, None)
-        x.value = "abc"
+        x.value = b"abc"
         self.assertEquals(x._objects, b"abc")
-        x = c_char_p("spam")
+        x = c_char_p(b"spam")
         self.assertEquals(x._objects, b"spam")
 
 class StructureTestCase(unittest.TestCase):
@@ -37,8 +37,8 @@
         x = X()
         self.assertEquals(x._objects, None)
 
-        x.a = "spam"
-        x.b = "foo"
+        x.a = b"spam"
+        x.b = b"foo"
         self.assertEquals(x._objects, {"0": b"spam", "1": b"foo"})
 
     def test_struct_struct(self):

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_libc.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_libc.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_libc.py	Sun Aug  8 12:41:24 2010
@@ -25,7 +25,7 @@
         def sort(a, b):
             return three_way_cmp(a[0], b[0])
 
-        chars = create_string_buffer("spam, spam, and spam")
+        chars = create_string_buffer(b"spam, spam, and spam")
         lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort))
         self.assertEqual(chars.raw, b"   ,,aaaadmmmnpppsss\x00")
 

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_loading.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_loading.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_loading.py	Sun Aug  8 12:41:24 2010
@@ -97,7 +97,7 @@
             self.assertEqual(0, advapi32.CloseEventLog(None))
             windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
             windll.kernel32.GetProcAddress.restype = c_void_p
-            proc = windll.kernel32.GetProcAddress(advapi32._handle, "CloseEventLog")
+            proc = windll.kernel32.GetProcAddress(advapi32._handle, b"CloseEventLog")
             self.assertTrue(proc)
             # This is the real test: call the function via 'call_function'
             self.assertEqual(0, call_function(proc, (None,)))

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_objects.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_objects.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_objects.py	Sun Aug  8 12:41:24 2010
@@ -20,7 +20,7 @@
 The memory block stores pointers to strings, and the strings itself
 assigned from Python must be kept.
 
->>> array[4] = 'foo bar'
+>>> array[4] = b'foo bar'
 >>> array._objects
 {'4': b'foo bar'}
 >>> array[4]
@@ -45,7 +45,7 @@
 <ctypes.test.test_objects.X object at 0x...>
 >>>
 
->>> x.array[0] = 'spam spam spam'
+>>> x.array[0] = b'spam spam spam'
 >>> x._objects
 {'0:2': b'spam spam spam'}
 >>> x.array._b_base_._objects

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_parameters.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_parameters.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_parameters.py	Sun Aug  8 12:41:24 2010
@@ -19,7 +19,6 @@
         else:
             set_conversion_mode(*self.prev_conv_mode)
 
-
     def test_subclasses(self):
         from ctypes import c_void_p, c_char_p
         # ctypes 0.9.5 and before did overwrite from_param in SimpleType_new
@@ -58,14 +57,13 @@
         self.assertTrue(c_char_p.from_param(s)._obj is s)
 
         # new in 0.9.1: convert (encode) unicode to ascii
-        self.assertEqual(c_char_p.from_param("123")._obj, b"123")
-        self.assertRaises(UnicodeEncodeError, c_char_p.from_param, "123\377")
-
+        self.assertEqual(c_char_p.from_param(b"123")._obj, b"123")
+        self.assertRaises(TypeError, c_char_p.from_param, "123\377")
         self.assertRaises(TypeError, c_char_p.from_param, 42)
 
         # calling c_char_p.from_param with a c_char_p instance
         # returns the argument itself:
-        a = c_char_p("123")
+        a = c_char_p(b"123")
         self.assertTrue(c_char_p.from_param(a) is a)
 
     def test_cw_strings(self):
@@ -82,7 +80,7 @@
 
             # new in 0.9.1: convert (decode) ascii to unicode
             self.assertEqual(c_wchar_p.from_param("123")._obj, "123")
-        self.assertRaises(UnicodeDecodeError, c_wchar_p.from_param, b"123\377")
+        self.assertRaises(TypeError, c_wchar_p.from_param, b"123\377")
 
         pa = c_wchar_p.from_param(c_wchar_p("123"))
         self.assertEqual(type(pa), c_wchar_p)

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_prototypes.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_prototypes.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_prototypes.py	Sun Aug  8 12:41:24 2010
@@ -127,7 +127,7 @@
         self.assertEqual(None, func(c_char_p(None)))
 
         self.assertEqual(b"123", func(c_buffer(b"123")))
-        ca = c_char("a")
+        ca = c_char(b"a")
         self.assertEqual(ord(b"a"), func(pointer(ca))[0])
         self.assertEqual(ord(b"a"), func(byref(ca))[0])
 

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_python_api.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_python_api.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_python_api.py	Sun Aug  8 12:41:24 2010
@@ -72,10 +72,10 @@
         PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
 
         buf = c_buffer(256)
-        PyOS_snprintf(buf, sizeof(buf), "Hello from %s", b"ctypes")
+        PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes")
         self.assertEqual(buf.value, b"Hello from ctypes")
 
-        PyOS_snprintf(buf, sizeof(buf), "Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3)
+        PyOS_snprintf(buf, sizeof(buf), b"Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3)
         self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)")
 
         # not enough arguments

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_random_things.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_random_things.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_random_things.py	Sun Aug  8 12:41:24 2010
@@ -18,7 +18,7 @@
             windll.kernel32.GetProcAddress.restype = c_void_p
 
             hdll = windll.kernel32.LoadLibraryA(b"kernel32")
-            funcaddr = windll.kernel32.GetProcAddress(hdll, "GetModuleHandleA")
+            funcaddr = windll.kernel32.GetProcAddress(hdll, b"GetModuleHandleA")
 
             self.assertEqual(call_function(funcaddr, (None,)),
                                  windll.kernel32.GetModuleHandleA(None))
@@ -66,7 +66,7 @@
 
     def test_TypeErrorDivisionError(self):
         cb = CFUNCTYPE(c_int, c_char_p)(callback_func)
-        out = self.capture_stderr(cb, "spam")
+        out = self.capture_stderr(cb, b"spam")
         self.assertEqual(out.splitlines()[-1],
                              "TypeError: "
                              "unsupported operand type(s) for /: 'int' and 'bytes'")

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_repr.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_repr.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_repr.py	Sun Aug  8 12:41:24 2010
@@ -22,8 +22,8 @@
             self.assertEqual("<X object at", repr(typ(42))[:12])
 
     def test_char(self):
-        self.assertEqual("c_char(b'x')", repr(c_char('x')))
-        self.assertEqual("<X object at", repr(X('x'))[:12])
+        self.assertEqual("c_char(b'x')", repr(c_char(b'x')))
+        self.assertEqual("<X object at", repr(X(b'x'))[:12])
 
 if __name__ == "__main__":
     unittest.main()

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_returnfuncptrs.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_returnfuncptrs.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_returnfuncptrs.py	Sun Aug  8 12:41:24 2010
@@ -28,10 +28,10 @@
         # _CFuncPtr instances are now callable with an integer argument
         # which denotes a function address:
         strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(addr)
-        self.assertTrue(strchr("abcdef", "b"), "bcdef")
-        self.assertEqual(strchr("abcdef", "x"), None)
-        self.assertRaises(ArgumentError, strchr, "abcdef", 3.0)
-        self.assertRaises(TypeError, strchr, "abcdef")
+        self.assertTrue(strchr(b"abcdef", b"b"), "bcdef")
+        self.assertEqual(strchr(b"abcdef", b"x"), None)
+        self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0)
+        self.assertRaises(TypeError, strchr, b"abcdef")
 
 if __name__ == "__main__":
     unittest.main()

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_stringptr.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_stringptr.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_stringptr.py	Sun Aug  8 12:41:24 2010
@@ -14,7 +14,7 @@
 
         # NULL pointer access
         self.assertRaises(ValueError, getattr, x.str, "contents")
-        b = c_buffer("Hello, World")
+        b = c_buffer(b"Hello, World")
         from sys import getrefcount as grc
         self.assertEqual(grc(b), 2)
         x.str = b
@@ -63,8 +63,8 @@
         # So we must keep a reference to buf separately
 
         strchr.restype = POINTER(c_char)
-        buf = c_buffer("abcdef")
-        r = strchr(buf, "c")
+        buf = c_buffer(b"abcdef")
+        r = strchr(buf, b"c")
         x = r[0], r[1], r[2], r[3], r[4]
         self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000"))
         del buf

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_strings.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_strings.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_strings.py	Sun Aug  8 12:41:24 2010
@@ -5,23 +5,23 @@
     def test(self):
         BUF = c_char * 4
 
-        buf = BUF("a", "b", "c")
+        buf = BUF(b"a", b"b", b"c")
         self.assertEqual(buf.value, b"abc")
         self.assertEqual(buf.raw, b"abc\000")
 
-        buf.value = "ABCD"
+        buf.value = b"ABCD"
         self.assertEqual(buf.value, b"ABCD")
         self.assertEqual(buf.raw, b"ABCD")
 
-        buf.value = "x"
+        buf.value = b"x"
         self.assertEqual(buf.value, b"x")
         self.assertEqual(buf.raw, b"x\000CD")
 
-        buf[1] = "Z"
+        buf[1] = b"Z"
         self.assertEqual(buf.value, b"xZCD")
         self.assertEqual(buf.raw, b"xZCD")
 
-        self.assertRaises(ValueError, setattr, buf, "value", "aaaaaaaa")
+        self.assertRaises(ValueError, setattr, buf, "value", b"aaaaaaaa")
         self.assertRaises(TypeError, setattr, buf, "value", 42)
 
     def test_c_buffer_value(self):

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_structures.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_structures.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_structures.py	Sun Aug  8 12:41:24 2010
@@ -205,15 +205,15 @@
                         ("age", c_int)]
 
         self.assertRaises(TypeError, Person, 42)
-        self.assertRaises(ValueError, Person, "asldkjaslkdjaslkdj")
+        self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
         self.assertRaises(TypeError, Person, "Name", "HI")
 
         # short enough
-        self.assertEqual(Person("12345", 5).name, b"12345")
+        self.assertEqual(Person(b"12345", 5).name, b"12345")
         # exact fit
-        self.assertEqual(Person("123456", 5).name, b"123456")
+        self.assertEqual(Person(b"123456", 5).name, b"123456")
         # too long
-        self.assertRaises(ValueError, Person, "1234567", 5)
+        self.assertRaises(ValueError, Person, b"1234567", 5)
 
     def test_conflicting_initializers(self):
         class POINT(Structure):
@@ -267,7 +267,7 @@
                         ("phone", Phone),
                         ("age", c_int)]
 
-        p = Person("Someone", ("1234", "5678"), 5)
+        p = Person(b"Someone", (b"1234", b"5678"), 5)
 
         self.assertEqual(p.name, b"Someone")
         self.assertEqual(p.phone.areacode, b"1234")
@@ -284,8 +284,8 @@
             _fields_ = [("name", c_wchar * 12),
                         ("age", c_int)]
 
-        p = PersonW("Someone")
-        self.assertEqual(p.name, "Someone")
+        p = PersonW("Someone \xe9")
+        self.assertEqual(p.name, "Someone \xe9")
 
         self.assertEqual(PersonW("1234567890").name, "1234567890")
         self.assertEqual(PersonW("12345678901").name, "12345678901")
@@ -304,13 +304,13 @@
                         ("phone", Phone),
                         ("age", c_int)]
 
-        cls, msg = self.get_except(Person, "Someone", (1, 2))
+        cls, msg = self.get_except(Person, b"Someone", (1, 2))
         self.assertEqual(cls, RuntimeError)
         self.assertEqual(msg,
                              "(Phone) <class 'TypeError'>: "
                              "expected string, int found")
 
-        cls, msg = self.get_except(Person, "Someone", ("a", "b", "c"))
+        cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
         self.assertEqual(cls, RuntimeError)
         if issubclass(Exception, object):
             self.assertEqual(msg,

Modified: python/branches/py3k-dtoa/Lib/ctypes/test/test_unicode.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ctypes/test/test_unicode.py	(original)
+++ python/branches/py3k-dtoa/Lib/ctypes/test/test_unicode.py	Sun Aug  8 12:41:24 2010
@@ -7,122 +7,53 @@
     pass
 else:
     import _ctypes_test
-    dll = ctypes.CDLL(_ctypes_test.__file__)
-    wcslen = dll.my_wcslen
-    wcslen.argtypes = [ctypes.c_wchar_p]
-
 
     class UnicodeTestCase(unittest.TestCase):
-        def setUp(self):
-            self.prev_conv_mode = ctypes.set_conversion_mode("ascii", "strict")
+        def test_wcslen(self):
+            dll = ctypes.CDLL(_ctypes_test.__file__)
+            wcslen = dll.my_wcslen
+            wcslen.argtypes = [ctypes.c_wchar_p]
 
-        def tearDown(self):
-            ctypes.set_conversion_mode(*self.prev_conv_mode)
-
-        def test_ascii_strict(self):
-            ctypes.set_conversion_mode("ascii", "strict")
-            # no conversions take place with unicode arguments
             self.assertEqual(wcslen("abc"), 3)
             self.assertEqual(wcslen("ab\u2070"), 3)
-            # string args are converted
-            self.assertEqual(wcslen("abc"), 3)
             self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4")
 
-        def test_ascii_replace(self):
-            ctypes.set_conversion_mode("ascii", "replace")
-            self.assertEqual(wcslen("abc"), 3)
-            self.assertEqual(wcslen("ab\u2070"), 3)
-            self.assertEqual(wcslen("abc"), 3)
-            self.assertEqual(wcslen("ab\xe4"), 3)
-
-        def test_ascii_ignore(self):
-            ctypes.set_conversion_mode("ascii", "ignore")
-            self.assertEqual(wcslen("abc"), 3)
-            self.assertEqual(wcslen("ab\u2070"), 3)
-            # ignore error mode skips non-ascii characters
-            self.assertEqual(wcslen("abc"), 3)
-            self.assertEqual(wcslen(b"\xe4\xf6\xfc\xdf"), 0)
-
-        def test_latin1_strict(self):
-            ctypes.set_conversion_mode("latin-1", "strict")
-            self.assertEqual(wcslen("abc"), 3)
-            self.assertEqual(wcslen("ab\u2070"), 3)
-            self.assertEqual(wcslen("abc"), 3)
-            self.assertEqual(wcslen("\xe4\xf6\xfc\xdf"), 4)
-
         def test_buffers(self):
-            ctypes.set_conversion_mode("ascii", "strict")
             buf = ctypes.create_unicode_buffer("abc")
             self.assertEqual(len(buf), 3+1)
 
-            ctypes.set_conversion_mode("ascii", "replace")
-            buf = ctypes.create_unicode_buffer(b"ab\xe4\xf6\xfc")
-            self.assertEqual(buf[:], "ab\uFFFD\uFFFD\uFFFD\0")
-            self.assertEqual(buf[::], "ab\uFFFD\uFFFD\uFFFD\0")
-            self.assertEqual(buf[::-1], "\0\uFFFD\uFFFD\uFFFDba")
-            self.assertEqual(buf[::2], "a\uFFFD\uFFFD")
+            buf = ctypes.create_unicode_buffer("ab\xe4\xf6\xfc")
+            self.assertEqual(buf[:], "ab\xe4\xf6\xfc\0")
+            self.assertEqual(buf[::], "ab\xe4\xf6\xfc\0")
+            self.assertEqual(buf[::-1], '\x00\xfc\xf6\xe4ba')
+            self.assertEqual(buf[::2], 'a\xe4\xfc')
             self.assertEqual(buf[6:5:-1], "")
 
-            ctypes.set_conversion_mode("ascii", "ignore")
-            buf = ctypes.create_unicode_buffer(b"ab\xe4\xf6\xfc")
-            # is that correct? not sure.  But with 'ignore', you get what you pay for..
-            self.assertEqual(buf[:], "ab\0\0\0\0")
-            self.assertEqual(buf[::], "ab\0\0\0\0")
-            self.assertEqual(buf[::-1], "\0\0\0\0ba")
-            self.assertEqual(buf[::2], "a\0\0")
-            self.assertEqual(buf[6:5:-1], "")
-
-    import _ctypes_test
     func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
 
     class StringTestCase(UnicodeTestCase):
         def setUp(self):
-            self.prev_conv_mode = ctypes.set_conversion_mode("ascii", "strict")
             func.argtypes = [ctypes.c_char_p]
             func.restype = ctypes.c_char_p
 
         def tearDown(self):
-            ctypes.set_conversion_mode(*self.prev_conv_mode)
             func.argtypes = None
             func.restype = ctypes.c_int
 
-        def test_ascii_replace(self):
-            ctypes.set_conversion_mode("ascii", "strict")
-            self.assertEqual(func("abc"), "abc")
-            self.assertEqual(func("abc"), "abc")
-            self.assertRaises(ctypes.ArgumentError, func, "ab\xe4")
-
-        def test_ascii_ignore(self):
-            ctypes.set_conversion_mode("ascii", "ignore")
-            self.assertEqual(func("abc"), b"abc")
-            self.assertEqual(func("abc"), b"abc")
-            self.assertEqual(func("\xe4\xf6\xfc\xdf"), b"")
-
-        def test_ascii_replace(self):
-            ctypes.set_conversion_mode("ascii", "replace")
-            self.assertEqual(func("abc"), b"abc")
-            self.assertEqual(func("abc"), b"abc")
-            self.assertEqual(func("\xe4\xf6\xfc\xdf"), b"????")
+        def test_func(self):
+            self.assertEqual(func(b"abc\xe4"), b"abc\xe4")
 
         def test_buffers(self):
-            ctypes.set_conversion_mode("ascii", "strict")
-            buf = ctypes.create_string_buffer("abc")
+            buf = ctypes.create_string_buffer(b"abc")
             self.assertEqual(len(buf), 3+1)
 
-            ctypes.set_conversion_mode("ascii", "replace")
-            buf = ctypes.create_string_buffer("ab\xe4\xf6\xfc")
-            self.assertEqual(buf[:], b"ab???\0")
-            self.assertEqual(buf[::], b"ab???\0")
-            self.assertEqual(buf[::-1], b"\0???ba")
-            self.assertEqual(buf[::2], b"a??")
+            buf = ctypes.create_string_buffer(b"ab\xe4\xf6\xfc")
+            self.assertEqual(buf[:], b"ab\xe4\xf6\xfc\0")
+            self.assertEqual(buf[::], b"ab\xe4\xf6\xfc\0")
+            self.assertEqual(buf[::-1], b'\x00\xfc\xf6\xe4ba')
+            self.assertEqual(buf[::2], b'a\xe4\xfc')
             self.assertEqual(buf[6:5:-1], b"")
 
-            ctypes.set_conversion_mode("ascii", "ignore")
-            buf = ctypes.create_string_buffer("ab\xe4\xf6\xfc")
-            # is that correct? not sure.  But with 'ignore', you get what you pay for..
-            self.assertEqual(buf[:], b"ab\0\0\0\0")
-            self.assertEqual(buf[::], b"ab\0\0\0\0")
-            self.assertEqual(buf[::-1], b"\0\0\0\0ba")
 
 if __name__ == '__main__':
     unittest.main()

Modified: python/branches/py3k-dtoa/Lib/curses/wrapper.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/curses/wrapper.py	(original)
+++ python/branches/py3k-dtoa/Lib/curses/wrapper.py	Sun Aug  8 12:41:24 2010
@@ -17,10 +17,9 @@
     wrapper().
     """
 
-    res = None
     try:
         # Initialize curses
-        stdscr=curses.initscr()
+        stdscr = curses.initscr()
 
         # Turn off echoing of keys, and enter cbreak mode,
         # where no buffering is performed on keyboard input

Modified: python/branches/py3k-dtoa/Lib/dbm/__init__.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/dbm/__init__.py	(original)
+++ python/branches/py3k-dtoa/Lib/dbm/__init__.py	Sun Aug  8 12:41:24 2010
@@ -5,12 +5,11 @@
         import dbm
         d = dbm.open(file, 'w', 0o666)
 
-The returned object is a dbm.bsd, dbm.gnu, dbm.ndbm or dbm.dumb
-object, dependent on the type of database being opened (determined by
-the whichdb function) in the case of an existing dbm.  If the dbm does
-not exist and the create or new flag ('c' or 'n') was specified, the
-dbm type will be determined by the availability of the modules (tested
-in the above order).
+The returned object is a dbm.gnu, dbm.ndbm or dbm.dumb object, dependent on the
+type of database being opened (determined by the whichdb function) in the case
+of an existing dbm. If the dbm does not exist and the create or new flag ('c'
+or 'n') was specified, the dbm type will be determined by the availability of
+the modules (tested in the above order).
 
 It has the following interface (key and data are strings):
 
@@ -47,7 +46,7 @@
 class error(Exception):
     pass
 
-_names = ['dbm.bsd', 'dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
+_names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
 _defaultmod = None
 _modules = {}
 
@@ -168,10 +167,6 @@
     if magic == 0x13579ace:
         return "dbm.gnu"
 
-    ## Check for old Berkeley db hash file format v2
-    #if magic in (0x00061561, 0x61150600):
-    #    return "bsddb185" # not supported anymore
-
     # Later versions of Berkeley db hash file have a 12-byte pad in
     # front of the file type
     try:
@@ -179,10 +174,6 @@
     except struct.error:
         return ""
 
-    ## Check for BSD hash
-    #if magic in (0x00061561, 0x61150600):
-    #    return "dbm.bsd"
-
     # Unknown
     return ""
 

Modified: python/branches/py3k-dtoa/Lib/decimal.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/decimal.py	(original)
+++ python/branches/py3k-dtoa/Lib/decimal.py	Sun Aug  8 12:41:24 2010
@@ -2047,12 +2047,14 @@
         # case where xc == 1: result is 10**(xe*y), with xe*y
         # required to be an integer
         if xc == 1:
-            if ye >= 0:
-                exponent = xe*yc*10**ye
-            else:
-                exponent, remainder = divmod(xe*yc, 10**-ye)
-                if remainder:
-                    return None
+            xe *= yc
+            # result is now 10**(xe * 10**ye);  xe * 10**ye must be integral
+            while xe % 10 == 0:
+                xe //= 10
+                ye += 1
+            if ye < 0:
+                return None
+            exponent = xe * 10**ye
             if y.sign == 1:
                 exponent = -exponent
             # if other is a nonnegative integer, use ideal exponent
@@ -2325,9 +2327,10 @@
         # try for an exact result with precision +1
         if ans is None:
             ans = self._power_exact(other, context.prec + 1)
-            if ans is not None and result_sign == 1:
-                ans = _dec_from_triple(1, ans._int, ans._exp)
-            exact = True
+            if ans is not None:
+                if result_sign == 1:
+                    ans = _dec_from_triple(1, ans._int, ans._exp)
+                exact = True
 
         # usual case: inexact result, x**y computed directly as exp(y*log(x))
         if ans is None:
@@ -3810,20 +3813,38 @@
                  Emin=None, Emax=None,
                  capitals=None, clamp=None,
                  _ignored_flags=None):
-        if flags is None:
-            flags = []
+        # Set defaults; for everything except flags and _ignored_flags,
+        # inherit from DefaultContext.
+        try:
+            dc = DefaultContext
+        except NameError:
+            pass
+
+        self.prec = prec if prec is not None else dc.prec
+        self.rounding = rounding if rounding is not None else dc.rounding
+        self.Emin = Emin if Emin is not None else dc.Emin
+        self.Emax = Emax if Emax is not None else dc.Emax
+        self.capitals = capitals if capitals is not None else dc.capitals
+        self.clamp = clamp if clamp is not None else dc.clamp
+
         if _ignored_flags is None:
-            _ignored_flags = []
-        if not isinstance(flags, dict):
-            flags = dict([(s, int(s in flags)) for s in _signals])
-        if traps is not None and not isinstance(traps, dict):
-            traps = dict([(s, int(s in traps)) for s in _signals])
-        for name, val in locals().items():
-            if val is None:
-                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
-            else:
-                setattr(self, name, val)
-        del self.self
+            self._ignored_flags = []
+        else:
+            self._ignored_flags = _ignored_flags
+
+        if traps is None:
+            self.traps = dc.traps.copy()
+        elif not isinstance(traps, dict):
+            self.traps = dict((s, int(s in traps)) for s in _signals)
+        else:
+            self.traps = traps
+
+        if flags is None:
+            self.flags = dict.fromkeys(_signals, 0)
+        elif not isinstance(flags, dict):
+            self.flags = dict((s, int(s in flags)) for s in _signals)
+        else:
+            self.flags = flags
 
     def __repr__(self):
         """Show the current context."""

Modified: python/branches/py3k-dtoa/Lib/distutils/__init__.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/__init__.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/__init__.py	Sun Aug  8 12:41:24 2010
@@ -15,5 +15,5 @@
 # Updated automatically by the Python release process.
 #
 #--start constants--
-__version__ = "3.2a0"
+__version__ = "3.2a1"
 #--end constants--

Modified: python/branches/py3k-dtoa/Lib/distutils/archive_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/archive_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/archive_util.py	Sun Aug  8 12:41:24 2010
@@ -14,55 +14,15 @@
 from distutils.dir_util import mkpath
 from distutils import log
 
-try:
-    from pwd import getpwnam
-except ImportError:
-    getpwnam = None
-
-try:
-    from grp import getgrnam
-except ImportError:
-    getgrnam = None
-
-def _get_gid(name):
-    """Returns a gid, given a group name."""
-    if getgrnam is None or name is None:
-        return None
-    try:
-        result = getgrnam(name)
-    except KeyError:
-        result = None
-    if result is not None:
-        return result[2]
-    return None
-
-def _get_uid(name):
-    """Returns an uid, given a user name."""
-    if getpwnam is None or name is None:
-        return None
-    try:
-        result = getpwnam(name)
-    except KeyError:
-        result = None
-    if result is not None:
-        return result[2]
-    return None
-
-def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
-                 owner=None, group=None):
+def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0):
     """Create a (possibly compressed) tar file from all the files under
     'base_dir'.
 
     'compress' must be "gzip" (the default), "compress", "bzip2", or None.
-    (compress will be deprecated in Python 3.2)
-
-    'owner' and 'group' can be used to define an owner and a group for the
-    archive that is being built. If not provided, the current owner and group
-    will be used.
-
+    Both "tar" and the compression utility named by 'compress' must be on
+    the default program search path, so this is probably Unix-specific.
     The output tar file will be named 'base_dir' +  ".tar", possibly plus
     the appropriate compression extension (".gz", ".bz2" or ".Z").
-
     Returns the output filename.
     """
     tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''}
@@ -84,23 +44,10 @@
     import tarfile  # late import so Python build itself doesn't break
 
     log.info('Creating tar archive')
-
-    uid = _get_uid(owner)
-    gid = _get_gid(group)
-
-    def _set_uid_gid(tarinfo):
-        if gid is not None:
-            tarinfo.gid = gid
-            tarinfo.gname = group
-        if uid is not None:
-            tarinfo.uid = uid
-            tarinfo.uname = owner
-        return tarinfo
-
     if not dry_run:
         tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
         try:
-            tar.add(base_dir, filter=_set_uid_gid)
+            tar.add(base_dir)
         finally:
             tar.close()
 
@@ -190,7 +137,7 @@
     return None
 
 def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
-                 dry_run=0, owner=None, group=None):
+                 dry_run=0):
     """Create an archive file (eg. zip or tar).
 
     'base_name' is the name of the file to create, minus any format-specific
@@ -203,9 +150,6 @@
     ie. 'base_dir' will be the common prefix of all files and
     directories in the archive.  'root_dir' and 'base_dir' both default
     to the current directory.  Returns the name of the archive file.
-
-    'owner' and 'group' are used when creating a tar archive. By default,
-    uses the current owner and group.
     """
     save_cwd = os.getcwd()
     if root_dir is not None:
@@ -227,11 +171,6 @@
     func = format_info[0]
     for arg, val in format_info[1]:
         kwargs[arg] = val
-
-    if format != 'zip':
-        kwargs['owner'] = owner
-        kwargs['group'] = group
-
     try:
         filename = func(base_name, base_dir, **kwargs)
     finally:

Modified: python/branches/py3k-dtoa/Lib/distutils/bcppcompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/bcppcompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/bcppcompiler.py	Sun Aug  8 12:41:24 2010
@@ -13,11 +13,13 @@
 
 __revision__ = "$Id$"
 
-import os
 
-from distutils.errors import (DistutilsExecError, CompileError, LibError,
-                              LinkError, UnknownFileError)
-from distutils.ccompiler import CCompiler, gen_preprocess_options
+import os
+from distutils.errors import \
+     DistutilsExecError, DistutilsPlatformError, \
+     CompileError, LibError, LinkError, UnknownFileError
+from distutils.ccompiler import \
+     CCompiler, gen_preprocess_options, gen_lib_options
 from distutils.file_util import write_file
 from distutils.dep_util import newer
 from distutils import log

Modified: python/branches/py3k-dtoa/Lib/distutils/ccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/ccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/ccompiler.py	Sun Aug  8 12:41:24 2010
@@ -5,71 +5,15 @@
 
 __revision__ = "$Id$"
 
-import sys
-import os
-import re
-
-from distutils.errors import (CompileError, LinkError, UnknownFileError,
-                              DistutilsPlatformError, DistutilsModuleError)
+import sys, os, re
+from distutils.errors import *
 from distutils.spawn import spawn
 from distutils.file_util import move_file
 from distutils.dir_util import mkpath
-from distutils.dep_util import newer_group
+from distutils.dep_util import newer_pairwise, newer_group
 from distutils.util import split_quoted, execute
 from distutils import log
 
-_sysconfig = __import__('sysconfig')
-
-def customize_compiler(compiler):
-    """Do any platform-specific customization of a CCompiler instance.
-
-    Mainly needed on Unix, so we can plug in the information that
-    varies across Unices and is stored in Python's Makefile.
-    """
-    if compiler.compiler_type == "unix":
-        (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
-            _sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
-                                       'CCSHARED', 'LDSHARED', 'SO', 'AR',
-                                       'ARFLAGS')
-
-        if 'CC' in os.environ:
-            cc = os.environ['CC']
-        if 'CXX' in os.environ:
-            cxx = os.environ['CXX']
-        if 'LDSHARED' in os.environ:
-            ldshared = os.environ['LDSHARED']
-        if 'CPP' in os.environ:
-            cpp = os.environ['CPP']
-        else:
-            cpp = cc + " -E"           # not always
-        if 'LDFLAGS' in os.environ:
-            ldshared = ldshared + ' ' + os.environ['LDFLAGS']
-        if 'CFLAGS' in os.environ:
-            cflags = opt + ' ' + os.environ['CFLAGS']
-            ldshared = ldshared + ' ' + os.environ['CFLAGS']
-        if 'CPPFLAGS' in os.environ:
-            cpp = cpp + ' ' + os.environ['CPPFLAGS']
-            cflags = cflags + ' ' + os.environ['CPPFLAGS']
-            ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
-        if 'AR' in os.environ:
-            ar = os.environ['AR']
-        if 'ARFLAGS' in os.environ:
-            archiver = ar + ' ' + os.environ['ARFLAGS']
-        else:
-            archiver = ar + ' ' + ar_flags
-
-        cc_cmd = cc + ' ' + cflags
-        compiler.set_executables(
-            preprocessor=cpp,
-            compiler=cc_cmd,
-            compiler_so=cc_cmd + ' ' + ccshared,
-            compiler_cxx=cxx,
-            linker_so=ldshared,
-            linker_exe=cc,
-            archiver=archiver)
-
-        compiler.shared_lib_extension = so_ext
-
 class CCompiler:
     """Abstract base class to define the interface that must be implemented
     by real compiler classes.  Also has some utility methods used by
@@ -449,6 +393,22 @@
 
         return output_dir, macros, include_dirs
 
+    def _prep_compile(self, sources, output_dir, depends=None):
+        """Decide which souce files must be recompiled.
+
+        Determine the list of object files corresponding to 'sources',
+        and figure out which ones really need to be recompiled.
+        Return a list of all object files and a dictionary telling
+        which source files can be skipped.
+        """
+        # Get the list of expected output (object) files
+        objects = self.object_filenames(sources, output_dir=output_dir)
+        assert len(objects) == len(sources)
+
+        # Return an empty dict for the "which source files can be skipped"
+        # return value to preserve API compatibility.
+        return objects, {}
+
     def _fix_object_args(self, objects, output_dir):
         """Typecheck and fix up some arguments supplied to various methods.
         Specifically: ensure that 'objects' is a list; if output_dir is
@@ -650,15 +610,26 @@
         """
         pass
 
+
     # values for target_desc parameter in link()
     SHARED_OBJECT = "shared_object"
     SHARED_LIBRARY = "shared_library"
     EXECUTABLE = "executable"
 
-    def link(self, target_desc, objects, output_filename, output_dir=None,
-             libraries=None, library_dirs=None, runtime_library_dirs=None,
-             export_symbols=None, debug=0, extra_preargs=None,
-             extra_postargs=None, build_temp=None, target_lang=None):
+    def link(self,
+             target_desc,
+             objects,
+             output_filename,
+             output_dir=None,
+             libraries=None,
+             library_dirs=None,
+             runtime_library_dirs=None,
+             export_symbols=None,
+             debug=0,
+             extra_preargs=None,
+             extra_postargs=None,
+             build_temp=None,
+             target_lang=None):
         """Link a bunch of stuff together to create an executable or
         shared library file.
 
@@ -707,11 +678,19 @@
 
     # Old 'link_*()' methods, rewritten to use the new 'link()' method.
 
-    def link_shared_lib(self, objects, output_libname, output_dir=None,
-                        libraries=None, library_dirs=None,
-                        runtime_library_dirs=None, export_symbols=None,
-                        debug=0, extra_preargs=None, extra_postargs=None,
-                        build_temp=None, target_lang=None):
+    def link_shared_lib(self,
+                        objects,
+                        output_libname,
+                        output_dir=None,
+                        libraries=None,
+                        library_dirs=None,
+                        runtime_library_dirs=None,
+                        export_symbols=None,
+                        debug=0,
+                        extra_preargs=None,
+                        extra_postargs=None,
+                        build_temp=None,
+                        target_lang=None):
         self.link(CCompiler.SHARED_LIBRARY, objects,
                   self.library_filename(output_libname, lib_type='shared'),
                   output_dir,
@@ -720,11 +699,19 @@
                   extra_preargs, extra_postargs, build_temp, target_lang)
 
 
-    def link_shared_object(self, objects, output_filename, output_dir=None,
-                           libraries=None, library_dirs=None,
-                           runtime_library_dirs=None, export_symbols=None,
-                           debug=0, extra_preargs=None, extra_postargs=None,
-                           build_temp=None, target_lang=None):
+    def link_shared_object(self,
+                           objects,
+                           output_filename,
+                           output_dir=None,
+                           libraries=None,
+                           library_dirs=None,
+                           runtime_library_dirs=None,
+                           export_symbols=None,
+                           debug=0,
+                           extra_preargs=None,
+                           extra_postargs=None,
+                           build_temp=None,
+                           target_lang=None):
         self.link(CCompiler.SHARED_OBJECT, objects,
                   output_filename, output_dir,
                   libraries, library_dirs, runtime_library_dirs,
@@ -732,10 +719,17 @@
                   extra_preargs, extra_postargs, build_temp, target_lang)
 
 
-    def link_executable(self, objects, output_progname, output_dir=None,
-                        libraries=None, library_dirs=None,
-                        runtime_library_dirs=None, debug=0, extra_preargs=None,
-                        extra_postargs=None, target_lang=None):
+    def link_executable(self,
+                        objects,
+                        output_progname,
+                        output_dir=None,
+                        libraries=None,
+                        library_dirs=None,
+                        runtime_library_dirs=None,
+                        debug=0,
+                        extra_preargs=None,
+                        extra_postargs=None,
+                        target_lang=None):
         self.link(CCompiler.EXECUTABLE, objects,
                   self.executable_filename(output_progname), output_dir,
                   libraries, library_dirs, runtime_library_dirs, None,
@@ -917,7 +911,7 @@
     def move_file(self, src, dst):
         return move_file(src, dst, dry_run=self.dry_run)
 
-    def mkpath(self, name, mode=0o777):
+    def mkpath (self, name, mode=0o777):
         mkpath(name, mode, dry_run=self.dry_run)
 
 
@@ -1085,14 +1079,12 @@
     return pp_opts
 
 
-def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
+def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
     """Generate linker options for searching library directories and
-    linking with specific libraries.
-
-    'libraries' and 'library_dirs' are, respectively, lists of library names
-    (not filenames!) and search directories.  Returns a list of command-line
-    options suitable for use with some compiler (depending on the two format
-    strings passed in).
+    linking with specific libraries.  'libraries' and 'library_dirs' are,
+    respectively, lists of library names (not filenames!) and search
+    directories.  Returns a list of command-line options suitable for use
+    with some compiler (depending on the two format strings passed in).
     """
     lib_opts = []
 
@@ -1102,7 +1094,7 @@
     for dir in runtime_library_dirs:
         opt = compiler.runtime_library_dir_option(dir)
         if isinstance(opt, list):
-            lib_opts.extend(opt)
+            lib_opts = lib_opts + opt
         else:
             lib_opts.append(opt)
 
@@ -1113,14 +1105,14 @@
     # pretty nasty way to arrange your C code.
 
     for lib in libraries:
-        lib_dir, lib_name = os.path.split(lib)
-        if lib_dir != '':
+        (lib_dir, lib_name) = os.path.split(lib)
+        if lib_dir:
             lib_file = compiler.find_library_file([lib_dir], lib_name)
-            if lib_file is not None:
+            if lib_file:
                 lib_opts.append(lib_file)
             else:
                 compiler.warn("no library file corresponding to "
                               "'%s' found (skipping)" % lib)
         else:
-            lib_opts.append(compiler.library_option(lib))
+            lib_opts.append(compiler.library_option (lib))
     return lib_opts

Modified: python/branches/py3k-dtoa/Lib/distutils/cmd.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/cmd.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/cmd.py	Sun Aug  8 12:41:24 2010
@@ -367,11 +367,9 @@
         from distutils.spawn import spawn
         spawn(cmd, search_path, dry_run=self.dry_run)
 
-    def make_archive(self, base_name, format, root_dir=None, base_dir=None,
-                     owner=None, group=None):
-        return archive_util.make_archive(base_name, format, root_dir,
-                                         base_dir, dry_run=self.dry_run,
-                                         owner=owner, group=group)
+    def make_archive(self, base_name, format, root_dir=None, base_dir=None):
+        return archive_util.make_archive(base_name, format, root_dir, base_dir,
+                                         dry_run=self.dry_run)
 
     def make_file(self, infiles, outfile, func, args,
                   exec_msg=None, skip_msg=None, level=1):

Modified: python/branches/py3k-dtoa/Lib/distutils/command/bdist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/bdist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/bdist.py	Sun Aug  8 12:41:24 2010
@@ -6,10 +6,9 @@
 __revision__ = "$Id$"
 
 import os
-
-from distutils.util import get_platform
 from distutils.core import Command
-from distutils.errors import DistutilsPlatformError, DistutilsOptionError
+from distutils.errors import *
+from distutils.util import get_platform
 
 
 def show_formats():
@@ -40,12 +39,6 @@
                      "[default: dist]"),
                     ('skip-build', None,
                      "skip rebuilding everything (for testing/debugging)"),
-                    ('owner=', 'u',
-                     "Owner name used when creating a tar file"
-                     " [default: current user]"),
-                    ('group=', 'g',
-                     "Group name used when creating a tar file"
-                     " [default: current group]"),
                    ]
 
     boolean_options = ['skip-build']
@@ -87,8 +80,6 @@
         self.formats = None
         self.dist_dir = None
         self.skip_build = 0
-        self.group = None
-        self.owner = None
 
     def finalize_options(self):
         # have to finalize 'plat_name' before 'bdist_base'
@@ -134,11 +125,6 @@
             if cmd_name not in self.no_format_option:
                 sub_cmd.format = self.formats[i]
 
-            # passing the owner and group names for tar archiving
-            if cmd_name == 'bdist_dumb':
-                sub_cmd.owner = self.owner
-                sub_cmd.group = self.group
-
             # If we're going to need to run this command again, tell it to
             # keep its temporary files around so subsequent runs go faster.
             if cmd_name in commands[i+1:]:

Modified: python/branches/py3k-dtoa/Lib/distutils/command/bdist_dumb.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/bdist_dumb.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/bdist_dumb.py	Sun Aug  8 12:41:24 2010
@@ -7,18 +7,16 @@
 __revision__ = "$Id$"
 
 import os
-
-from sysconfig import get_python_version
-
-from distutils.util import get_platform
 from distutils.core import Command
+from distutils.util import get_platform
 from distutils.dir_util import remove_tree, ensure_relative
-from distutils.errors import DistutilsPlatformError
+from distutils.errors import *
+from distutils.sysconfig import get_python_version
 from distutils import log
 
 class bdist_dumb(Command):
 
-    description = 'create a "dumb" built distribution'
+    description = "create a \"dumb\" built distribution"
 
     user_options = [('bdist-dir=', 'd',
                      "temporary directory for creating the distribution"),
@@ -37,12 +35,6 @@
                     ('relative', None,
                      "build the archive using relative paths"
                      "(default: false)"),
-                    ('owner=', 'u',
-                     "Owner name used when creating a tar file"
-                     " [default: current user]"),
-                    ('group=', 'g',
-                     "Group name used when creating a tar file"
-                     " [default: current group]"),
                    ]
 
     boolean_options = ['keep-temp', 'skip-build', 'relative']
@@ -59,8 +51,6 @@
         self.dist_dir = None
         self.skip_build = 0
         self.relative = 0
-        self.owner = None
-        self.group = None
 
     def finalize_options(self):
         if self.bdist_dir is None:
@@ -118,8 +108,7 @@
 
         # Make the archive
         filename = self.make_archive(pseudoinstall_root,
-                                     self.format, root_dir=archive_root,
-                                     owner=self.owner, group=self.group)
+                                     self.format, root_dir=archive_root)
         if self.distribution.has_ext_modules():
             pyversion = get_python_version()
         else:

Modified: python/branches/py3k-dtoa/Lib/distutils/command/bdist_msi.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/bdist_msi.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/bdist_msi.py	Sun Aug  8 12:41:24 2010
@@ -6,15 +6,15 @@
 """
 Implements the bdist_msi command.
 """
-import sys, os
-from sysconfig import get_python_version, get_platform
 
+import sys, os
 from distutils.core import Command
 from distutils.dir_util import remove_tree
+from distutils.sysconfig import get_python_version
 from distutils.version import StrictVersion
 from distutils.errors import DistutilsOptionError
+from distutils.util import get_platform
 from distutils import log
-
 import msilib
 from msilib import schema, sequence, text
 from msilib import Directory, Feature, Dialog, add_data
@@ -28,6 +28,7 @@
         default, cancel, bitmap=true)"""
         Dialog.__init__(self, *args)
         ruler = self.h - 36
+        bmwidth = 152*ruler/328
         #if kw.get("bitmap", True):
         #    self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
         self.line("BottomLine", 0, ruler, self.w, 0)
@@ -147,7 +148,7 @@
             if not self.skip_build and self.distribution.has_ext_modules()\
                and self.target_version != short_version:
                 raise DistutilsOptionError(
-                      "target version can only be %s, or the '--skip_build'"
+                      "target version can only be %s, or the '--skip-build'"
                       " option must be specified" % (short_version,))
         else:
             self.versions = list(self.all_versions)
@@ -418,6 +419,7 @@
         # see "Dialog Style Bits"
         modal = 3      # visible | modal
         modeless = 1   # visible
+        track_disk_space = 32
 
         # UI customization properties
         add_data(db, "Property",

Modified: python/branches/py3k-dtoa/Lib/distutils/command/bdist_rpm.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/bdist_rpm.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/bdist_rpm.py	Sun Aug  8 12:41:24 2010
@@ -5,14 +5,13 @@
 
 __revision__ = "$Id$"
 
-import sys
-import os
-
+import sys, os
 from distutils.core import Command
 from distutils.debug import DEBUG
+from distutils.util import get_platform
 from distutils.file_util import write_file
-from distutils.errors import (DistutilsOptionError, DistutilsPlatformError,
-                              DistutilsFileError, DistutilsExecError)
+from distutils.errors import *
+from distutils.sysconfig import get_python_version
 from distutils import log
 
 class bdist_rpm(Command):

Modified: python/branches/py3k-dtoa/Lib/distutils/command/bdist_wininst.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/bdist_wininst.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/bdist_wininst.py	Sun Aug  8 12:41:24 2010
@@ -5,16 +5,13 @@
 
 __revision__ = "$Id$"
 
-import sys
-import os
-
-from sysconfig import get_python_version
-
+import sys, os
 from distutils.core import Command
-from distutils.dir_util import remove_tree
-from distutils.errors import DistutilsOptionError, DistutilsPlatformError
-from distutils import log
 from distutils.util import get_platform
+from distutils.dir_util import create_tree, remove_tree
+from distutils.errors import *
+from distutils.sysconfig import get_python_version
+from distutils import log
 
 class bdist_wininst(Command):
 
@@ -92,7 +89,7 @@
             short_version = get_python_version()
             if self.target_version and self.target_version != short_version:
                 raise DistutilsOptionError(
-                      "target version can only be %s, or the '--skip_build'" \
+                      "target version can only be %s, or the '--skip-build'" \
                       " option must be specified" % (short_version,))
             self.target_version = short_version
 

Modified: python/branches/py3k-dtoa/Lib/distutils/command/build.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/build.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/build.py	Sun Aug  8 12:41:24 2010
@@ -5,15 +5,16 @@
 __revision__ = "$Id$"
 
 import sys, os
-
-from distutils.util import get_platform
 from distutils.core import Command
 from distutils.errors import DistutilsOptionError
+from distutils.util import get_platform
+
 
 def show_compilers():
     from distutils.ccompiler import show_compilers
     show_compilers()
 
+
 class build(Command):
 
     description = "build everything needed to install"
@@ -126,6 +127,7 @@
         for cmd_name in self.get_sub_commands():
             self.run_command(cmd_name)
 
+
     # -- Predicates for the sub-command list ---------------------------
 
     def has_pure_modules(self):
@@ -140,6 +142,7 @@
     def has_scripts(self):
         return self.distribution.has_scripts()
 
+
     sub_commands = [('build_py',      has_pure_modules),
                     ('build_clib',    has_c_libraries),
                     ('build_ext',     has_ext_modules),

Modified: python/branches/py3k-dtoa/Lib/distutils/command/build_clib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/build_clib.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/build_clib.py	Sun Aug  8 12:41:24 2010
@@ -18,8 +18,8 @@
 
 import os
 from distutils.core import Command
-from distutils.errors import DistutilsSetupError
-from distutils.ccompiler import customize_compiler
+from distutils.errors import *
+from distutils.sysconfig import customize_compiler
 from distutils import log
 
 def show_compilers():

Modified: python/branches/py3k-dtoa/Lib/distutils/command/build_ext.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/build_ext.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/build_ext.py	Sun Aug  8 12:41:24 2010
@@ -7,14 +7,12 @@
 __revision__ = "$Id$"
 
 import sys, os, re
-from warnings import warn
-
-from distutils.util import get_platform
 from distutils.core import Command
 from distutils.errors import *
-from distutils.ccompiler import customize_compiler
+from distutils.sysconfig import customize_compiler, get_python_version
 from distutils.dep_util import newer_group
 from distutils.extension import Extension
+from distutils.util import get_platform
 from distutils import log
 
 # this keeps compatibility from 2.3 to 2.5
@@ -114,39 +112,6 @@
          "list available compilers", show_compilers),
         ]
 
-    # making 'compiler' a property to deprecate
-    # its usage as something else than a compiler type
-    # e.g. like a compiler instance
-    def __init__(self, dist):
-        self._compiler = None
-        Command.__init__(self, dist)
-
-    def __setattr__(self, name, value):
-        # need this to make sure setattr() (used in distutils)
-        # doesn't kill our property
-        if name == 'compiler':
-            self._set_compiler(value)
-        else:
-            self.__dict__[name] = value
-
-    def _set_compiler(self, compiler):
-        if not isinstance(compiler, str) and compiler is not None:
-            # we don't want to allow that anymore in the future
-            warn("'compiler' specifies the compiler type in build_ext. "
-                 "If you want to get the compiler object itself, "
-                 "use 'compiler_obj'", DeprecationWarning)
-        self._compiler = compiler
-
-    def _get_compiler(self):
-        if not isinstance(self._compiler, str) and self._compiler is not None:
-            # we don't want to allow that anymore in the future
-            warn("'compiler' specifies the compiler type in build_ext. "
-                 "If you want to get the compiler object itself, "
-                 "use 'compiler_obj'", DeprecationWarning)
-        return self._compiler
-
-    compiler = property(_get_compiler, _set_compiler)
-
     def initialize_options(self):
         self.extensions = None
         self.build_lib = None
@@ -171,7 +136,8 @@
         self.user = None
 
     def finalize_options(self):
-        _sysconfig = __import__('sysconfig')
+        from distutils import sysconfig
+
         self.set_undefined_options('build',
                                    ('build_lib', 'build_lib'),
                                    ('build_temp', 'build_temp'),
@@ -188,8 +154,8 @@
 
         # Make sure Python's include directories (for Python.h, pyconfig.h,
         # etc.) are in the include search path.
-        py_include = _sysconfig.get_path('include')
-        plat_py_include = _sysconfig.get_path('platinclude')
+        py_include = sysconfig.get_python_inc()
+        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
         if self.include_dirs is None:
             self.include_dirs = self.distribution.include_dirs or []
         if isinstance(self.include_dirs, str):
@@ -261,13 +227,13 @@
         if os.name == 'os2':
             self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
 
-        # for extensions under Cygwin Python's library directory must be
+        # for extensions under Cygwin and AtheOS Python's library directory must be
         # appended to library_dirs
-        if sys.platform[:6] == 'cygwin':
+        if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
                 # building third party extensions
                 self.library_dirs.append(os.path.join(sys.prefix, "lib",
-                                  "python" + _sysconfig.get_python_version(),
+                                                      "python" + get_python_version(),
                                                       "config"))
             else:
                 # building python standard extensions
@@ -275,13 +241,13 @@
 
         # for extensions under Linux or Solaris with a shared Python library,
         # Python's library directory must be appended to library_dirs
-        _sysconfig.get_config_var('Py_ENABLE_SHARED')
+        sysconfig.get_config_var('Py_ENABLE_SHARED')
         if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')
              or sys.platform.startswith('sunos'))
-            and _sysconfig.get_config_var('Py_ENABLE_SHARED')):
+            and sysconfig.get_config_var('Py_ENABLE_SHARED')):
             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
                 # building third party extensions
-                self.library_dirs.append(_sysconfig.get_config_var('LIBDIR'))
+                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
             else:
                 # building python standard extensions
                 self.library_dirs.append('.')
@@ -344,50 +310,38 @@
 
         # Setup the CCompiler object that we'll use to do all the
         # compiling and linking
-
-        # used to prevent the usage of an existing compiler for the
-        # compiler option when calling new_compiler()
-        # this will be removed in 3.3 and 2.8
-        if not isinstance(self._compiler, str):
-            self._compiler = None
-
-        self.compiler_obj = new_compiler(compiler=self._compiler,
-                                         verbose=self.verbose,
-                                         dry_run=self.dry_run,
-                                         force=self.force)
-
-        # used to keep the compiler object reachable with
-        # "self.compiler". this will be removed in 3.3 and 2.8
-        self._compiler = self.compiler_obj
-
-        customize_compiler(self.compiler_obj)
+        self.compiler = new_compiler(compiler=self.compiler,
+                                     verbose=self.verbose,
+                                     dry_run=self.dry_run,
+                                     force=self.force)
+        customize_compiler(self.compiler)
         # If we are cross-compiling, init the compiler now (if we are not
         # cross-compiling, init would not hurt, but people may rely on
         # late initialization of compiler even if they shouldn't...)
         if os.name == 'nt' and self.plat_name != get_platform():
-            self.compiler_obj.initialize(self.plat_name)
+            self.compiler.initialize(self.plat_name)
 
         # And make sure that any compile/link-related options (which might
         # come from the command-line or from the setup script) are set in
         # that CCompiler object -- that way, they automatically apply to
         # all compiling and linking done here.
         if self.include_dirs is not None:
-            self.compiler_obj.set_include_dirs(self.include_dirs)
+            self.compiler.set_include_dirs(self.include_dirs)
         if self.define is not None:
             # 'define' option is a list of (name,value) tuples
             for (name, value) in self.define:
-                self.compiler_obj.define_macro(name, value)
+                self.compiler.define_macro(name, value)
         if self.undef is not None:
             for macro in self.undef:
-                self.compiler_obj.undefine_macro(macro)
+                self.compiler.undefine_macro(macro)
         if self.libraries is not None:
-            self.compiler_obj.set_libraries(self.libraries)
+            self.compiler.set_libraries(self.libraries)
         if self.library_dirs is not None:
-            self.compiler_obj.set_library_dirs(self.library_dirs)
+            self.compiler.set_library_dirs(self.library_dirs)
         if self.rpath is not None:
-            self.compiler_obj.set_runtime_library_dirs(self.rpath)
+            self.compiler.set_runtime_library_dirs(self.rpath)
         if self.link_objects is not None:
-            self.compiler_obj.set_link_objects(self.link_objects)
+            self.compiler.set_link_objects(self.link_objects)
 
         # Now actually compile and link everything.
         self.build_extensions()
@@ -548,13 +502,13 @@
         for undef in ext.undef_macros:
             macros.append((undef,))
 
-        objects = self.compiler_obj.compile(sources,
-                                            output_dir=self.build_temp,
-                                            macros=macros,
-                                            include_dirs=ext.include_dirs,
-                                            debug=self.debug,
-                                            extra_postargs=extra_args,
-                                            depends=ext.depends)
+        objects = self.compiler.compile(sources,
+                                         output_dir=self.build_temp,
+                                         macros=macros,
+                                         include_dirs=ext.include_dirs,
+                                         debug=self.debug,
+                                         extra_postargs=extra_args,
+                                         depends=ext.depends)
 
         # XXX -- this is a Vile HACK!
         #
@@ -575,9 +529,9 @@
         extra_args = ext.extra_link_args or []
 
         # Detect target language, if not provided
-        language = ext.language or self.compiler_obj.detect_language(sources)
+        language = ext.language or self.compiler.detect_language(sources)
 
-        self.compiler_obj.link_shared_object(
+        self.compiler.link_shared_object(
             objects, ext_path,
             libraries=self.get_libraries(ext),
             library_dirs=ext.library_dirs,
@@ -710,13 +664,13 @@
         of the file from which it will be loaded (eg. "foo/bar.so", or
         "foo\bar.pyd").
         """
-        _sysconfig = __import__('sysconfig')
+        from distutils.sysconfig import get_config_var
         ext_path = ext_name.split('.')
         # OS/2 has an 8 character module (extension) limit :-(
         if os.name == "os2":
             ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
         # extensions in debug_mode are named 'module_d.pyd' under windows
-        so_ext = _sysconfig.get_config_var('SO')
+        so_ext = get_config_var('SO')
         if os.name == 'nt' and self.debug:
             return os.path.join(*ext_path) + '_d' + so_ext
         return os.path.join(*ext_path) + so_ext
@@ -744,7 +698,7 @@
         # Append '_d' to the python import library on debug builds.
         if sys.platform == "win32":
             from distutils.msvccompiler import MSVCCompiler
-            if not isinstance(self.compiler_obj, MSVCCompiler):
+            if not isinstance(self.compiler, MSVCCompiler):
                 template = "python%d%d"
                 if self.debug:
                     template = template + '_d'
@@ -775,12 +729,28 @@
             # don't extend ext.libraries, it may be shared with other
             # extensions, it is a reference to the original list
             return ext.libraries + [pythonlib]
+        elif sys.platform[:6] == "atheos":
+            from distutils import sysconfig
+
+            template = "python%d.%d"
+            pythonlib = (template %
+                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
+            # Get SHLIBS from Makefile
+            extra = []
+            for lib in sysconfig.get_config_var('SHLIBS').split():
+                if lib.startswith('-l'):
+                    extra.append(lib[2:])
+                else:
+                    extra.append(lib)
+            # don't extend ext.libraries, it may be shared with other
+            # extensions, it is a reference to the original list
+            return ext.libraries + [pythonlib, "m"] + extra
         elif sys.platform == 'darwin':
             # Don't use the default code below
             return ext.libraries
         else:
-            _sysconfig = __import__('sysconfig')
-            if _sysconfig.get_config_var('Py_ENABLE_SHARED'):
+            from distutils import sysconfig
+            if sysconfig.get_config_var('Py_ENABLE_SHARED'):
                 template = "python%d.%d"
                 pythonlib = (template %
                              (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))

Modified: python/branches/py3k-dtoa/Lib/distutils/command/build_py.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/build_py.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/build_py.py	Sun Aug  8 12:41:24 2010
@@ -4,16 +4,16 @@
 
 __revision__ = "$Id$"
 
-import os
+import sys, os
 import sys
 from glob import glob
 
 from distutils.core import Command
-from distutils.errors import DistutilsOptionError, DistutilsFileError
+from distutils.errors import *
 from distutils.util import convert_path, Mixin2to3
 from distutils import log
 
-class build_py(Command):
+class build_py (Command):
 
     description = "\"build\" pure Python modules (copy to build directory)"
 
@@ -133,6 +133,7 @@
 
     def build_package_data(self):
         """Copy data files into build directory"""
+        lastdir = None
         for package, src_dir, build_dir, filenames in self.data_files:
             for filename in filenames:
                 target = os.path.join(build_dir, filename)

Modified: python/branches/py3k-dtoa/Lib/distutils/command/build_scripts.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/build_scripts.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/build_scripts.py	Sun Aug  8 12:41:24 2010
@@ -6,6 +6,7 @@
 
 import os, re
 from stat import ST_MODE
+from distutils import sysconfig
 from distutils.core import Command
 from distutils.dep_util import newer
 from distutils.util import convert_path, Mixin2to3
@@ -56,7 +57,6 @@
         ie. starts with "\#!" and contains "python"), then adjust the first
         line to refer to the current Python interpreter as we copy.
         """
-        _sysconfig = __import__('sysconfig')
         self.mkpath(self.build_dir)
         outfiles = []
         updated_files = []
@@ -96,16 +96,16 @@
                 updated_files.append(outfile)
                 if not self.dry_run:
                     outf = open(outfile, "w")
-                    if not _sysconfig.is_python_build():
+                    if not sysconfig.python_build:
                         outf.write("#!%s%s\n" %
                                    (self.executable,
                                     post_interp))
                     else:
                         outf.write("#!%s%s\n" %
                                    (os.path.join(
-                            _sysconfig.get_config_var("BINDIR"),
-                           "python%s%s" % (_sysconfig.get_config_var("VERSION"),
-                                           _sysconfig.get_config_var("EXE"))),
+                            sysconfig.get_config_var("BINDIR"),
+                           "python%s%s" % (sysconfig.get_config_var("VERSION"),
+                                           sysconfig.get_config_var("EXE"))),
                                     post_interp))
                     outf.writelines(f.readlines())
                     outf.close()

Modified: python/branches/py3k-dtoa/Lib/distutils/command/config.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/config.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/config.py	Sun Aug  8 12:41:24 2010
@@ -11,12 +11,11 @@
 
 __revision__ = "$Id$"
 
-import os
-import re
+import sys, os, re
 
 from distutils.core import Command
 from distutils.errors import DistutilsExecError
-from distutils.ccompiler import customize_compiler
+from distutils.sysconfig import customize_compiler
 from distutils import log
 
 LANG_EXT = {"c": ".c", "c++": ".cxx"}

Modified: python/branches/py3k-dtoa/Lib/distutils/command/install.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/install.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/install.py	Sun Aug  8 12:41:24 2010
@@ -7,17 +7,26 @@
 import sys
 import os
 
-from sysconfig import get_config_vars, get_paths, get_path, get_config_var
-
 from distutils import log
 from distutils.core import Command
 from distutils.debug import DEBUG
+from distutils.sysconfig import get_config_vars
 from distutils.errors import DistutilsPlatformError
 from distutils.file_util import write_file
-from distutils.util import convert_path, change_root, get_platform
+from distutils.util import convert_path, subst_vars, change_root
+from distutils.util import get_platform
 from distutils.errors import DistutilsOptionError
 
-# kept for backward compat, will be removed in 3.2
+# this keeps compatibility from 2.3 to 2.5
+if sys.version < "2.6":
+    USER_BASE = None
+    USER_SITE = None
+    HAS_USER_SITE = False
+else:
+    from site import USER_BASE
+    from site import USER_SITE
+    HAS_USER_SITE = True
+
 if sys.version < "2.2":
     WINDOWS_SCHEME = {
         'purelib': '$base',
@@ -50,21 +59,15 @@
         'scripts': '$base/bin',
         'data'   : '$base',
         },
-    'unix_user': {
-        'purelib': '$usersite',
-        'platlib': '$usersite',
-        'headers': '$userbase/include/python$py_version_short/$dist_name',
-        'scripts': '$userbase/bin',
-        'data'   : '$userbase',
-        },
     'nt': WINDOWS_SCHEME,
-    'nt_user': {
-        'purelib': '$usersite',
-        'platlib': '$usersite',
-        'headers': '$userbase/Python$py_version_nodot/Include/$dist_name',
-        'scripts': '$userbase/Scripts',
-        'data'   : '$userbase',
+    'mac': {
+        'purelib': '$base/Lib/site-packages',
+        'platlib': '$base/Lib/site-packages',
+        'headers': '$base/Include/$dist_name',
+        'scripts': '$base/Scripts',
+        'data'   : '$base',
         },
+
     'os2': {
         'purelib': '$base/Lib/site-packages',
         'platlib': '$base/Lib/site-packages',
@@ -72,26 +75,47 @@
         'scripts': '$base/Scripts',
         'data'   : '$base',
         },
-    'os2_home': {
+    }
+
+# user site schemes
+if HAS_USER_SITE:
+    INSTALL_SCHEMES['nt_user'] = {
+        'purelib': '$usersite',
+        'platlib': '$usersite',
+        'headers': '$userbase/Python$py_version_nodot/Include/$dist_name',
+        'scripts': '$userbase/Scripts',
+        'data'   : '$userbase',
+        }
+
+    INSTALL_SCHEMES['unix_user'] = {
         'purelib': '$usersite',
         'platlib': '$usersite',
         'headers': '$userbase/include/python$py_version_short/$dist_name',
         'scripts': '$userbase/bin',
         'data'   : '$userbase',
-        },
-    }
+        }
+
+    INSTALL_SCHEMES['mac_user'] = {
+        'purelib': '$usersite',
+        'platlib': '$usersite',
+        'headers': '$userbase/$py_version_short/include/$dist_name',
+        'scripts': '$userbase/bin',
+        'data'   : '$userbase',
+        }
 
+    INSTALL_SCHEMES['os2_home'] = {
+        'purelib': '$usersite',
+        'platlib': '$usersite',
+        'headers': '$userbase/include/python$py_version_short/$dist_name',
+        'scripts': '$userbase/bin',
+        'data'   : '$userbase',
+        }
+
+# The keys to an installation scheme; if any new types of files are to be
+# installed, be sure to add an entry to every installation scheme above,
+# and to SCHEME_KEYS here.
 SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')
-# end of backward compat
 
-def _subst_vars(s, local_vars):
-    try:
-        return s.format(**local_vars)
-    except KeyError:
-        try:
-            return s.format(**os.environ)
-        except KeyError as var:
-            raise AttributeError('{%s}' % var)
 
 class install(Command):
 
@@ -158,10 +182,11 @@
 
     boolean_options = ['compile', 'force', 'skip-build']
 
-    user_options.append(('user', None,
-                        "install in user site-package '%s'" % \
-                            get_path('purelib', '%s_user' % os.name)))
-    boolean_options.append('user')
+    if HAS_USER_SITE:
+        user_options.append(('user', None,
+                             "install in user site-package '%s'" % USER_SITE))
+        boolean_options.append('user')
+
     negative_opt = {'no-compile' : 'compile'}
 
 
@@ -191,8 +216,8 @@
         self.install_lib = None         # set to either purelib or platlib
         self.install_scripts = None
         self.install_data = None
-        self.install_userbase = get_config_var('userbase')
-        self.install_usersite = get_path('purelib', '%s_user' % os.name)
+        self.install_userbase = USER_BASE
+        self.install_usersite = USER_SITE
 
         self.compile = None
         self.optimize = None
@@ -302,9 +327,7 @@
         # about needing recursive variable expansion (shudder).
 
         py_version = sys.version.split()[0]
-        prefix, exec_prefix, srcdir, projectbase = get_config_vars('prefix', 'exec_prefix',
-                                                      'srcdir', 'projectbase')
-
+        (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
         self.config_vars = {'dist_name': self.distribution.get_name(),
                             'dist_version': self.distribution.get_version(),
                             'dist_fullname': self.distribution.get_fullname(),
@@ -315,12 +338,12 @@
                             'prefix': prefix,
                             'sys_exec_prefix': exec_prefix,
                             'exec_prefix': exec_prefix,
-                            'srcdir': srcdir,
-                            'projectbase': projectbase,
                            }
 
-        self.config_vars['userbase'] = self.install_userbase
-        self.config_vars['usersite'] = self.install_usersite
+        if HAS_USER_SITE:
+            self.config_vars['userbase'] = self.install_userbase
+            self.config_vars['usersite'] = self.install_usersite
+
         self.expand_basedirs()
 
         self.dump_dirs("post-expand_basedirs()")
@@ -424,10 +447,10 @@
                 raise DistutilsPlatformError(
                     "User base directory is not specified")
             self.install_base = self.install_platbase = self.install_userbase
-            self.select_scheme("posix_user")
+            self.select_scheme("unix_user")
         elif self.home is not None:
             self.install_base = self.install_platbase = self.home
-            self.select_scheme("posix_home")
+            self.select_scheme("unix_home")
         else:
             if self.prefix is None:
                 if self.exec_prefix is not None:
@@ -443,7 +466,7 @@
 
             self.install_base = self.prefix
             self.install_platbase = self.exec_prefix
-            self.select_scheme("posix_prefix")
+            self.select_scheme("unix_prefix")
 
     def finalize_other(self):
         """Finalizes options for non-posix platforms"""
@@ -455,7 +478,7 @@
             self.select_scheme(os.name + "_user")
         elif self.home is not None:
             self.install_base = self.install_platbase = self.home
-            self.select_scheme("posix_home")
+            self.select_scheme("unix_home")
         else:
             if self.prefix is None:
                 self.prefix = os.path.normpath(sys.prefix)
@@ -470,15 +493,11 @@
     def select_scheme(self, name):
         """Sets the install directories by applying the install schemes."""
         # it's the caller's problem if they supply a bad name!
-        scheme = get_paths(name, expand=False)
-        for key, value in scheme.items():
-            if key == 'platinclude':
-                key = 'headers'
-                value = os.path.join(value, self.distribution.get_name())
+        scheme = INSTALL_SCHEMES[name]
+        for key in SCHEME_KEYS:
             attrname = 'install_' + key
-            if hasattr(self, attrname):
-                if getattr(self, attrname) is None:
-                    setattr(self, attrname, value)
+            if getattr(self, attrname) is None:
+                setattr(self, attrname, scheme[key])
 
     def _expand_attrs(self, attrs):
         for attr in attrs:
@@ -486,7 +505,7 @@
             if val is not None:
                 if os.name == 'posix' or os.name == 'nt':
                     val = os.path.expanduser(val)
-                val = _subst_vars(val, self.config_vars)
+                val = subst_vars(val, self.config_vars)
                 setattr(self, attr, val)
 
     def expand_basedirs(self):

Modified: python/branches/py3k-dtoa/Lib/distutils/command/register.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/register.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/register.py	Sun Aug  8 12:41:24 2010
@@ -7,15 +7,13 @@
 
 __revision__ = "$Id$"
 
-import os
-import string
-import getpass
+import os, string, getpass
 import io
-import urllib.parse
-import urllib.request
+import urllib.parse, urllib.request
 from warnings import warn
 
 from distutils.core import PyPIRCCommand
+from distutils.errors import *
 from distutils import log
 
 class register(PyPIRCCommand):

Modified: python/branches/py3k-dtoa/Lib/distutils/command/sdist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/sdist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/sdist.py	Sun Aug  8 12:41:24 2010
@@ -7,14 +7,14 @@
 import os
 import string
 import sys
+from types import *
 from glob import glob
 from warnings import warn
 
 from distutils.core import Command
 from distutils import dir_util, dep_util, file_util, archive_util
 from distutils.text_file import TextFile
-from distutils.errors import (DistutilsPlatformError, DistutilsOptionError,
-                              DistutilsTemplateError)
+from distutils.errors import *
 from distutils.filelist import FileList
 from distutils import log
 from distutils.util import convert_path
@@ -76,10 +76,6 @@
         ('medata-check', None,
          "Ensure that all required elements of meta-data "
          "are supplied. Warn if any missing. [default]"),
-        ('owner=', 'u',
-         "Owner name used when creating a tar file [default: current user]"),
-        ('group=', 'g',
-         "Group name used when creating a tar file [default: current group]"),
         ]
 
     boolean_options = ['use-defaults', 'prune',
@@ -119,8 +115,6 @@
 
         self.archive_files = None
         self.metadata_check = 1
-        self.owner = None
-        self.group = None
 
     def finalize_options(self):
         if self.manifest is None:
@@ -246,8 +240,7 @@
         optional = ['test/test*.py', 'setup.cfg']
         for pattern in optional:
             files = filter(os.path.isfile, glob(pattern))
-            if files:
-                self.filelist.extend(files)
+            self.filelist.extend(files)
 
         # build_py is used to get:
         #  - python modules
@@ -424,8 +417,7 @@
             self.formats.append(self.formats.pop(self.formats.index('tar')))
 
         for fmt in self.formats:
-            file = self.make_archive(base_name, fmt, base_dir=base_dir,
-                                     owner=self.owner, group=self.group)
+            file = self.make_archive(base_name, fmt, base_dir=base_dir)
             archive_files.append(file)
             self.distribution.dist_files.append(('sdist', '', file))
 

Modified: python/branches/py3k-dtoa/Lib/distutils/command/upload.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/command/upload.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/command/upload.py	Sun Aug  8 12:41:24 2010
@@ -1,19 +1,25 @@
 """distutils.command.upload
 
 Implements the Distutils 'upload' subcommand (upload package to PyPI)."""
-import os
-import io
-import socket
-import platform
-from urllib.request import urlopen, Request, HTTPError
-from base64 import standard_b64encode
-from urllib.parse import urlparse
-from hashlib import md5
 
-from distutils.errors import DistutilsOptionError
+from distutils.errors import *
 from distutils.core import PyPIRCCommand
 from distutils.spawn import spawn
 from distutils import log
+import sys
+import os, io
+import socket
+import platform
+import configparser
+import http.client as httpclient
+from base64 import standard_b64encode
+import urllib.parse
+
+# this keeps compatibility for 2.3 and 2.4
+if sys.version < "2.5":
+    from md5 import md5
+else:
+    from hashlib import md5
 
 class upload(PyPIRCCommand):
 
@@ -60,15 +66,6 @@
             self.upload_file(command, pyversion, filename)
 
     def upload_file(self, command, pyversion, filename):
-        # Makes sure the repository URL is compliant
-        schema, netloc, url, params, query, fragments = \
-            urlparse(self.repository)
-        if params or query or fragments:
-            raise AssertionError("Incompatible url %s" % self.repository)
-
-        if schema not in ('http', 'https'):
-            raise AssertionError("unsupported schema " + schema)
-
         # Sign if requested
         if self.sign:
             gpg_args = ["gpg", "--detach-sign", "-a", filename]
@@ -140,10 +137,10 @@
         for key, value in data.items():
             title = '\nContent-Disposition: form-data; name="%s"' % key
             # handle multiple entries for the same name
-            if not isinstance(value, list):
+            if type(value) != type([]):
                 value = [value]
             for value in value:
-                if isinstance(value, tuple):
+                if type(value) is tuple:
                     title += '; filename="%s"' % value[0]
                     value = value[1]
                 else:
@@ -161,30 +158,40 @@
         self.announce("Submitting %s to %s" % (filename, self.repository), log.INFO)
 
         # build the Request
-        headers = {'Content-type':
-                        'multipart/form-data; boundary=%s' % boundary,
-                   'Content-length': str(len(body)),
-                   'Authorization': auth}
-
-        request = Request(self.repository, data=body,
-                          headers=headers)
-        # send the data
+        # We can't use urllib since we need to send the Basic
+        # auth right with the first request
+        # TODO(jhylton): Can we fix urllib?
+        schema, netloc, url, params, query, fragments = \
+            urllib.parse.urlparse(self.repository)
+        assert not params and not query and not fragments
+        if schema == 'http':
+            http = httpclient.HTTPConnection(netloc)
+        elif schema == 'https':
+            http = httpclient.HTTPSConnection(netloc)
+        else:
+            raise AssertionError("unsupported schema "+schema)
+
+        data = ''
+        loglevel = log.INFO
         try:
-            result = urlopen(request)
-            status = result.getcode()
-            reason = result.msg
+            http.connect()
+            http.putrequest("POST", url)
+            http.putheader('Content-type',
+                           'multipart/form-data; boundary=%s'%boundary)
+            http.putheader('Content-length', str(len(body)))
+            http.putheader('Authorization', auth)
+            http.endheaders()
+            http.send(body)
         except socket.error as e:
             self.announce(str(e), log.ERROR)
             return
-        except HTTPError as e:
-            status = e.code
-            reason = e.msg
 
-        if status == 200:
-            self.announce('Server response (%s): %s' % (status, reason),
+        r = http.getresponse()
+        if r.status == 200:
+            self.announce('Server response (%s): %s' % (r.status, r.reason),
                           log.INFO)
         else:
-            self.announce('Upload failed (%s): %s' % (status, reason),
+            self.announce('Upload failed (%s): %s' % (r.status, r.reason),
                           log.ERROR)
         if self.show_response:
-            self.announce('-'*75, result.read(), '-'*75)
+            self.announce('-'*75, r.read(), '-'*75)

Modified: python/branches/py3k-dtoa/Lib/distutils/config.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/config.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/config.py	Sun Aug  8 12:41:24 2010
@@ -4,6 +4,7 @@
 that uses .pypirc in the distutils.command package.
 """
 import os
+import sys
 from configparser import ConfigParser
 
 from distutils.cmd import Command
@@ -59,6 +60,8 @@
         if os.path.exists(rc):
             self.announce('Using PyPI login from %s' % rc)
             repository = self.repository or self.DEFAULT_REPOSITORY
+            realm = self.realm or self.DEFAULT_REALM
+
             config = ConfigParser()
             config.read(rc)
             sections = config.sections()

Modified: python/branches/py3k-dtoa/Lib/distutils/core.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/core.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/core.py	Sun Aug  8 12:41:24 2010
@@ -8,12 +8,10 @@
 
 __revision__ = "$Id$"
 
-import sys
-import os
+import sys, os
 
 from distutils.debug import DEBUG
-from distutils.errors import (DistutilsSetupError, DistutilsArgError,
-                              DistutilsError, CCompilerError)
+from distutils.errors import *
 from distutils.util import grok_environment_error
 
 # Mainly import these so setup scripts can "from distutils.core import" them.
@@ -33,9 +31,9 @@
    or: %(script)s cmd --help
 """
 
-def gen_usage(script_name):
+def gen_usage (script_name):
     script = os.path.basename(script_name)
-    return USAGE % {'script': script}
+    return USAGE % vars()
 
 
 # Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
@@ -58,7 +56,7 @@
                       'extra_objects', 'extra_compile_args', 'extra_link_args',
                       'swig_opts', 'export_symbols', 'depends', 'language')
 
-def setup(**attrs):
+def setup (**attrs):
     """The gateway to the Distutils: do everything your setup script needs
     to do, in a highly flexible and user-driven way.  Briefly: create a
     Distribution instance; find and parse config files; parse the command
@@ -131,9 +129,8 @@
     if _setup_stop_after == "config":
         return dist
 
-    # Parse the command line and override config files; any
-    # command-line errors are the end user's fault, so turn them into
-    # SystemExit to suppress tracebacks.
+    # Parse the command line; any command-line errors are the end user's
+    # fault, so turn them into SystemExit to suppress tracebacks.
     try:
         ok = dist.parse_command_line()
     except DistutilsArgError as msg:
@@ -170,8 +167,10 @@
 
     return dist
 
+# setup ()
 
-def run_setup(script_name, script_args=None, stop_after="run"):
+
+def run_setup (script_name, script_args=None, stop_after="run"):
     """Run a setup script in a somewhat controlled environment, and
     return the Distribution instance that drives things.  This is useful
     if you need to find out the distribution meta-data (passed as
@@ -234,4 +233,7 @@
 
     # I wonder if the setup script's namespace -- g and l -- would be of
     # any interest to callers?
+    #print "_setup_distribution:", _setup_distribution
     return _setup_distribution
+
+# run_setup ()

Modified: python/branches/py3k-dtoa/Lib/distutils/cygwinccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/cygwinccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/cygwinccompiler.py	Sun Aug  8 12:41:24 2010
@@ -50,13 +50,16 @@
 import os
 import sys
 import copy
+from subprocess import Popen, PIPE
 import re
-from warnings import warn
 
+from distutils.ccompiler import gen_preprocess_options, gen_lib_options
 from distutils.unixccompiler import UnixCCompiler
 from distutils.file_util import write_file
 from distutils.errors import DistutilsExecError, CompileError, UnknownFileError
-from distutils.util import get_compiler_versions
+from distutils import log
+from distutils.version import LooseVersion
+from distutils.spawn import find_executable
 
 def get_msvcr():
     """Include the appropriate MSVC runtime library if Python was built
@@ -107,7 +110,7 @@
                 % details)
 
         self.gcc_version, self.ld_version, self.dllwrap_version = \
-            get_compiler_versions()
+            get_versions()
         self.debug_print(self.compiler_type + ": gcc %s, ld %s, dllwrap %s\n" %
                          (self.gcc_version,
                           self.ld_version,
@@ -337,7 +340,7 @@
     # XXX since this function also checks sys.version, it's not strictly a
     # "pyconfig.h" check -- should probably be renamed...
 
-    _sysconfig = __import__('sysconfig')
+    from distutils import sysconfig
 
     # if sys.version contains GCC then python was compiled with GCC, and the
     # pyconfig.h file should be OK
@@ -345,7 +348,7 @@
         return CONFIG_H_OK, "sys.version mentions 'GCC'"
 
     # let's see if __GNUC__ is mentioned in python.h
-    fn = _sysconfig.get_config_h_filename()
+    fn = sysconfig.get_config_h_filename()
     try:
         with open(fn) as config_h:
             if "__GNUC__" in config_h.read():
@@ -356,27 +359,33 @@
         return (CONFIG_H_UNCERTAIN,
                 "couldn't read '%s': %s" % (fn, exc.strerror))
 
-class _Deprecated_SRE_Pattern(object):
-    def __init__(self, pattern):
-        self.pattern = pattern
-
-    def __getattr__(self, name):
-        if name in ('findall', 'finditer', 'match', 'scanner', 'search',
-                    'split', 'sub', 'subn'):
-            warn("'distutils.cygwinccompiler.RE_VERSION' is deprecated "
-                 "and will be removed in the next version", DeprecationWarning)
-        return getattr(self.pattern, name)
+RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)')
 
+def _find_exe_version(cmd):
+    """Find the version of an executable by running `cmd` in the shell.
 
-RE_VERSION = _Deprecated_SRE_Pattern(re.compile('(\d+\.\d+(\.\d+)*)'))
+    If the command is not found, or the output does not match
+    `RE_VERSION`, returns None.
+    """
+    executable = cmd.split()[0]
+    if find_executable(executable) is None:
+        return None
+    out = Popen(cmd, shell=True, stdout=PIPE).stdout
+    try:
+        out_string = out.read()
+    finally:
+        out.close()
+    result = RE_VERSION.search(out_string)
+    if result is None:
+        return None
+    # LooseVersion works with strings
+    # so we need to decode our bytes
+    return LooseVersion(result.group(1).decode())
 
 def get_versions():
     """ Try to find out the versions of gcc, ld and dllwrap.
 
     If not possible it returns None for it.
     """
-    warn("'distutils.cygwinccompiler.get_versions' is deprecated "
-         "use 'distutils.util.get_compiler_versions' instead",
-         DeprecationWarning)
-
-    return get_compiler_versions()
+    commands = ['gcc -dumpversion', 'ld -v', 'dllwrap --version']
+    return tuple([_find_exe_version(cmd) for cmd in commands])

Modified: python/branches/py3k-dtoa/Lib/distutils/dep_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/dep_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/dep_util.py	Sun Aug  8 12:41:24 2010
@@ -9,27 +9,29 @@
 import os
 from distutils.errors import DistutilsFileError
 
-def newer(source, target):
-    """Tells if the target is newer than the source.
 
-    Return true if 'source' exists and is more recently modified than
-    'target', or if 'source' exists and 'target' doesn't.
-
-    Return false if both exist and 'target' is the same age or younger
-    than 'source'. Raise DistutilsFileError if 'source' does not exist.
-
-    Note that this test is not very accurate: files created in the same second
-    will have the same "age".
+def newer (source, target):
+    """Return true if 'source' exists and is more recently modified than
+    'target', or if 'source' exists and 'target' doesn't.  Return false if
+    both exist and 'target' is the same age or younger than 'source'.
+    Raise DistutilsFileError if 'source' does not exist.
     """
     if not os.path.exists(source):
         raise DistutilsFileError("file '%s' does not exist" %
                                  os.path.abspath(source))
     if not os.path.exists(target):
-        return True
+        return 1
+
+    from stat import ST_MTIME
+    mtime1 = os.stat(source)[ST_MTIME]
+    mtime2 = os.stat(target)[ST_MTIME]
+
+    return mtime1 > mtime2
+
+# newer ()
 
-    return os.stat(source).st_mtime > os.stat(target).st_mtime
 
-def newer_pairwise(sources, targets):
+def newer_pairwise (sources, targets):
     """Walk two filename lists in parallel, testing if each source is newer
     than its corresponding target.  Return a pair of lists (sources,
     targets) where source is newer than target, according to the semantics
@@ -41,18 +43,19 @@
     # build a pair of lists (sources, targets) where  source is newer
     n_sources = []
     n_targets = []
-    for source, target in zip(sources, targets):
-        if newer(source, target):
-            n_sources.append(source)
-            n_targets.append(target)
+    for i in range(len(sources)):
+        if newer(sources[i], targets[i]):
+            n_sources.append(sources[i])
+            n_targets.append(targets[i])
 
-    return n_sources, n_targets
+    return (n_sources, n_targets)
+
+# newer_pairwise ()
 
-def newer_group(sources, target, missing='error'):
-    """Return true if 'target' is out-of-date with respect to any file
-    listed in 'sources'.
 
-    In other words, if 'target' exists and is newer
+def newer_group (sources, target, missing='error'):
+    """Return true if 'target' is out-of-date with respect to any file
+    listed in 'sources'.  In other words, if 'target' exists and is newer
     than every file in 'sources', return false; otherwise return true.
     'missing' controls what we do when a source file is missing; the
     default ("error") is to blow up with an OSError from inside 'stat()';
@@ -65,14 +68,14 @@
     """
     # If the target doesn't even exist, then it's definitely out-of-date.
     if not os.path.exists(target):
-        return True
+        return 1
 
     # Otherwise we have to find out the hard way: if *any* source file
     # is more recent than 'target', then 'target' is out-of-date and
     # we can immediately return true.  If we fall through to the end
     # of the loop, then 'target' is up-to-date and we return false.
-    target_mtime = os.stat(target).st_mtime
-
+    from stat import ST_MTIME
+    target_mtime = os.stat(target)[ST_MTIME]
     for source in sources:
         if not os.path.exists(source):
             if missing == 'error':      # blow up when we stat() the file
@@ -80,9 +83,12 @@
             elif missing == 'ignore':   # missing source dropped from
                 continue                #  target's dependency list
             elif missing == 'newer':    # missing source means target is
-                return True             #  out-of-date
+                return 1                #  out-of-date
 
-        if os.stat(source).st_mtime > target_mtime:
-            return True
+        source_mtime = os.stat(source)[ST_MTIME]
+        if source_mtime > target_mtime:
+            return 1
+    else:
+        return 0
 
-    return False
+# newer_group ()

Modified: python/branches/py3k-dtoa/Lib/distutils/dir_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/dir_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/dir_util.py	Sun Aug  8 12:41:24 2010
@@ -4,7 +4,7 @@
 
 __revision__ = "$Id$"
 
-import os
+import os, sys
 from distutils.errors import DistutilsFileError, DistutilsInternalError
 from distutils import log
 

Modified: python/branches/py3k-dtoa/Lib/distutils/dist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/dist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/dist.py	Sun Aug  8 12:41:24 2010
@@ -7,15 +7,13 @@
 __revision__ = "$Id$"
 
 import sys, os, re
-from email import message_from_file
 
 try:
     import warnings
 except ImportError:
     warnings = None
 
-from distutils.errors import (DistutilsOptionError, DistutilsArgError,
-                              DistutilsModuleError, DistutilsClassError)
+from distutils.errors import *
 from distutils.fancy_getopt import FancyGetopt, translate_longopt
 from distutils.util import check_environ, strtobool, rfc822_escape
 from distutils import log
@@ -55,9 +53,7 @@
                       ('quiet', 'q', "run quietly (turns verbosity off)"),
                       ('dry-run', 'n', "don't actually do anything"),
                       ('help', 'h', "show detailed help message"),
-                      ('no-user-cfg', None,
-                       'ignore pydistutils.cfg in your home directory'),
-    ]
+                     ]
 
     # 'common_usage' is a short (2-3 line) string describing the common
     # usage of the setup script.
@@ -264,22 +260,6 @@
                     else:
                         sys.stderr.write(msg + "\n")
 
-        # no-user-cfg is handled before other command line args
-        # because other args override the config files, and this
-        # one is needed before we can load the config files.
-        # If attrs['script_args'] wasn't passed, assume false.
-        #
-        # This also make sure we just look at the global options
-        self.want_user_cfg = True
-
-        if self.script_args is not None:
-            for arg in self.script_args:
-                if not arg.startswith('-'):
-                    break
-                if arg == '--no-user-cfg':
-                    self.want_user_cfg = False
-                    break
-
         self.finalize_options()
 
     def get_option_dict(self, command):
@@ -331,10 +311,7 @@
         Distutils installation directory (ie. where the top-level
         Distutils __inst__.py file lives), a file in the user's home
         directory named .pydistutils.cfg on Unix and pydistutils.cfg
-        on Windows/Mac; and setup.cfg in the current directory.
-
-        The file in the user's home directory can be disabled with the
-        --no-user-cfg option.
+        on Windows/Mac, and setup.cfg in the current directory.
         """
         files = []
         check_environ()
@@ -354,19 +331,15 @@
             user_filename = "pydistutils.cfg"
 
         # And look for the user config file
-        if self.want_user_cfg:
-            user_file = os.path.join(os.path.expanduser('~'), user_filename)
-            if os.path.isfile(user_file):
-                files.append(user_file)
+        user_file = os.path.join(os.path.expanduser('~'), user_filename)
+        if os.path.isfile(user_file):
+            files.append(user_file)
 
         # All platforms support local setup.cfg
         local_file = "setup.cfg"
         if os.path.isfile(local_file):
             files.append(local_file)
 
-        if DEBUG:
-            self.announce("using config files: %s" % ', '.join(files))
-
         return files
 
     def parse_config_files(self, filenames=None):
@@ -1016,80 +989,25 @@
                          "provides", "requires", "obsoletes",
                          )
 
-    def __init__(self, path=None):
-        if path is not None:
-            self.read_pkg_file(open(path))
-        else:
-            self.name = None
-            self.version = None
-            self.author = None
-            self.author_email = None
-            self.maintainer = None
-            self.maintainer_email = None
-            self.url = None
-            self.license = None
-            self.description = None
-            self.long_description = None
-            self.keywords = None
-            self.platforms = None
-            self.classifiers = None
-            self.download_url = None
-            # PEP 314
-            self.provides = None
-            self.requires = None
-            self.obsoletes = None
-
-    def read_pkg_file(self, file):
-        """Reads the metadata values from a file object."""
-        msg = message_from_file(file)
-
-        def _read_field(name):
-            value = msg[name]
-            if value == 'UNKNOWN':
-                return None
-            return value
-
-        def _read_list(name):
-            values = msg.get_all(name, None)
-            if values == []:
-                return None
-            return values
-
-        metadata_version = msg['metadata-version']
-        self.name = _read_field('name')
-        self.version = _read_field('version')
-        self.description = _read_field('summary')
-        # we are filling author only.
-        self.author = _read_field('author')
+    def __init__ (self):
+        self.name = None
+        self.version = None
+        self.author = None
+        self.author_email = None
         self.maintainer = None
-        self.author_email = _read_field('author-email')
         self.maintainer_email = None
-        self.url = _read_field('home-page')
-        self.license = _read_field('license')
-
-        if 'download-url' in msg:
-            self.download_url = _read_field('download-url')
-        else:
-            self.download_url = None
-
-        self.long_description = _read_field('description')
-        self.description = _read_field('summary')
-
-        if 'keywords' in msg:
-            self.keywords = _read_field('keywords').split(',')
-
-        self.platforms = _read_list('platform')
-        self.classifiers = _read_list('classifier')
-
-        # PEP 314 - these fields only exist in 1.1
-        if metadata_version == '1.1':
-            self.requires = _read_list('requires')
-            self.provides = _read_list('provides')
-            self.obsoletes = _read_list('obsoletes')
-        else:
-            self.requires = None
-            self.provides = None
-            self.obsoletes = None
+        self.url = None
+        self.license = None
+        self.description = None
+        self.long_description = None
+        self.keywords = None
+        self.platforms = None
+        self.classifiers = None
+        self.download_url = None
+        # PEP 314
+        self.provides = None
+        self.requires = None
+        self.obsoletes = None
 
     def write_pkg_info(self, base_dir):
         """Write the PKG-INFO file into the release tree.

Modified: python/branches/py3k-dtoa/Lib/distutils/emxccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/emxccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/emxccompiler.py	Sun Aug  8 12:41:24 2010
@@ -21,13 +21,12 @@
 
 __revision__ = "$Id$"
 
-import os, sys, copy
-from warnings import warn
-
+import os,sys,copy
+from distutils.ccompiler import gen_preprocess_options, gen_lib_options
 from distutils.unixccompiler import UnixCCompiler
 from distutils.file_util import write_file
 from distutils.errors import DistutilsExecError, CompileError, UnknownFileError
-from distutils.util import get_compiler_versions
+from distutils import log
 
 class EMXCCompiler (UnixCCompiler):
 
@@ -56,8 +55,8 @@
                 ("Reason: %s." % details) +
                 "Compiling may fail because of undefined preprocessor macros.")
 
-        gcc_version, ld_version, dllwrap_version = get_compiler_versions()
-        self.gcc_version, self.ld_version = gcc_version, ld_version
+        (self.gcc_version, self.ld_version) = \
+            get_versions()
         self.debug_print(self.compiler_type + ": gcc %s, ld %s\n" %
                          (self.gcc_version,
                           self.ld_version) )
@@ -292,11 +291,23 @@
     """ Try to find out the versions of gcc and ld.
         If not possible it returns None for it.
     """
-    warn("'distutils.emxccompiler.get_versions' is deprecated "
-         "use 'distutils.util.get_compiler_versions' instead",
-         DeprecationWarning)
-
+    from distutils.version import StrictVersion
+    from distutils.spawn import find_executable
+    import re
+
+    gcc_exe = find_executable('gcc')
+    if gcc_exe:
+        out = os.popen(gcc_exe + ' -dumpversion','r')
+        out_string = out.read()
+        out.close()
+        result = re.search('(\d+\.\d+\.\d+)', out_string, re.ASCII)
+        if result:
+            gcc_version = StrictVersion(result.group(1))
+        else:
+            gcc_version = None
+    else:
+        gcc_version = None
     # EMX ld has no way of reporting version number, and we use GCC
     # anyway - so we can link OMF DLLs
-    gcc_version, ld_version, dllwrap_version = get_compiler_versions()
-    return gcc_version, None
+    ld_version = None
+    return (gcc_version, ld_version)

Modified: python/branches/py3k-dtoa/Lib/distutils/errors.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/errors.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/errors.py	Sun Aug  8 12:41:24 2010
@@ -10,79 +10,90 @@
 
 __revision__ = "$Id$"
 
-class DistutilsError(Exception):
+class DistutilsError (Exception):
     """The root of all Distutils evil."""
+    pass
 
-class DistutilsModuleError(DistutilsError):
+class DistutilsModuleError (DistutilsError):
     """Unable to load an expected module, or to find an expected class
     within some module (in particular, command modules and classes)."""
+    pass
 
-class DistutilsClassError(DistutilsError):
+class DistutilsClassError (DistutilsError):
     """Some command class (or possibly distribution class, if anyone
     feels a need to subclass Distribution) is found not to be holding
     up its end of the bargain, ie. implementing some part of the
     "command "interface."""
+    pass
 
-class DistutilsGetoptError(DistutilsError):
+class DistutilsGetoptError (DistutilsError):
     """The option table provided to 'fancy_getopt()' is bogus."""
+    pass
 
-class DistutilsArgError(DistutilsError):
+class DistutilsArgError (DistutilsError):
     """Raised by fancy_getopt in response to getopt.error -- ie. an
     error in the command line usage."""
+    pass
 
-class DistutilsFileError(DistutilsError):
+class DistutilsFileError (DistutilsError):
     """Any problems in the filesystem: expected file not found, etc.
     Typically this is for problems that we detect before IOError or
     OSError could be raised."""
+    pass
 
-class DistutilsOptionError(DistutilsError):
+class DistutilsOptionError (DistutilsError):
     """Syntactic/semantic errors in command options, such as use of
     mutually conflicting options, or inconsistent options,
     badly-spelled values, etc.  No distinction is made between option
     values originating in the setup script, the command line, config
     files, or what-have-you -- but if we *know* something originated in
     the setup script, we'll raise DistutilsSetupError instead."""
+    pass
 
-class DistutilsSetupError(DistutilsError):
+class DistutilsSetupError (DistutilsError):
     """For errors that can be definitely blamed on the setup script,
     such as invalid keyword arguments to 'setup()'."""
+    pass
 
-class DistutilsPlatformError(DistutilsError):
+class DistutilsPlatformError (DistutilsError):
     """We don't know how to do something on the current platform (but
     we do know how to do it on some platform) -- eg. trying to compile
     C files on a platform not supported by a CCompiler subclass."""
+    pass
 
-class DistutilsExecError(DistutilsError):
+class DistutilsExecError (DistutilsError):
     """Any problems executing an external program (such as the C
     compiler, when compiling C files)."""
+    pass
 
-class DistutilsInternalError(DistutilsError):
+class DistutilsInternalError (DistutilsError):
     """Internal inconsistencies or impossibilities (obviously, this
     should never be seen if the code is working!)."""
+    pass
 
-class DistutilsTemplateError(DistutilsError):
+class DistutilsTemplateError (DistutilsError):
     """Syntax error in a file list template."""
 
 class DistutilsByteCompileError(DistutilsError):
     """Byte compile error."""
 
 # Exception classes used by the CCompiler implementation classes
-class CCompilerError(Exception):
+class CCompilerError (Exception):
     """Some compile/link operation failed."""
 
-class PreprocessError(CCompilerError):
+class PreprocessError (CCompilerError):
     """Failure to preprocess one or more C/C++ files."""
 
-class CompileError(CCompilerError):
+class CompileError (CCompilerError):
     """Failure to compile one or more C/C++ source files."""
 
-class LibError(CCompilerError):
+class LibError (CCompilerError):
     """Failure to create a static library from one or more C/C++ object
     files."""
 
-class LinkError(CCompilerError):
+class LinkError (CCompilerError):
     """Failure to link one or more C/C++ object files into an executable
     or shared library file."""
 
-class UnknownFileError(CCompilerError):
+class UnknownFileError (CCompilerError):
     """Attempt to process an unknown file type."""

Modified: python/branches/py3k-dtoa/Lib/distutils/extension.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/extension.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/extension.py	Sun Aug  8 12:41:24 2010
@@ -6,6 +6,7 @@
 __revision__ = "$Id$"
 
 import os
+import sys
 import warnings
 
 # This class is really only used by the "build_ext" command, so it might
@@ -134,17 +135,14 @@
 
 def read_setup_file(filename):
     """Reads a Setup file and returns Extension instances."""
-    warnings.warn('distutils.extensions.read_setup_file is deprecated. '
-                  'It will be removed in the next Python release.')
-    _sysconfig = __import__('sysconfig')
-    from distutils.sysconfig import (expand_makefile_vars,
+    from distutils.sysconfig import (parse_makefile, expand_makefile_vars,
                                      _variable_rx)
 
     from distutils.text_file import TextFile
     from distutils.util import split_quoted
 
     # First pass over the file to gather "VAR = VALUE" assignments.
-    vars = _sysconfig._parse_makefile(filename)
+    vars = parse_makefile(filename)
 
     # Second pass to gobble up the real content: lines of the form
     #   <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
@@ -164,10 +162,7 @@
             file.warn("'%s' lines not handled yet" % line)
             continue
 
-        with warnings.catch_warnings():
-            warnings.simplefilter("ignore")
-            line = expand_makefile_vars(line, vars)
-
+        line = expand_makefile_vars(line, vars)
         words = split_quoted(line)
 
         # NB. this parses a slightly different syntax than the old

Modified: python/branches/py3k-dtoa/Lib/distutils/fancy_getopt.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/fancy_getopt.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/fancy_getopt.py	Sun Aug  8 12:41:24 2010
@@ -10,11 +10,9 @@
 
 __revision__ = "$Id$"
 
-import sys
-import string
-import re
+import sys, string, re
 import getopt
-from distutils.errors import DistutilsGetoptError, DistutilsArgError
+from distutils.errors import *
 
 # Much like command_re in distutils.core, this is close to but not quite
 # the same as a Python NAME -- except, in the spirit of most GNU
@@ -446,3 +444,16 @@
         'options' will be initialized to None."""
         for opt in options:
             setattr(self, opt, None)
+
+
+if __name__ == "__main__":
+    text = """\
+Tra-la-la, supercalifragilisticexpialidocious.
+How *do* you spell that odd word, anyways?
+(Someone ask Mary -- she'll know [or she'll
+say, "How should I know?"].)"""
+
+    for w in (10, 20, 30, 40):
+        print("width: %d" % w)
+        print("\n".join(wrap_text(text, w)))
+        print()

Modified: python/branches/py3k-dtoa/Lib/distutils/file_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/file_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/file_util.py	Sun Aug  8 12:41:24 2010
@@ -10,18 +10,17 @@
 from distutils import log
 
 # for generating verbose output in 'copy_file()'
-_copy_action = {None: 'copying',
-                'hard': 'hard linking',
-                'sym': 'symbolically linking'}
+_copy_action = { None:   'copying',
+                 'hard': 'hard linking',
+                 'sym':  'symbolically linking' }
 
 
 def _copy_file_contents(src, dst, buffer_size=16*1024):
-    """Copy the file 'src' to 'dst'.
-
-    Both must be filenames. Any error opening either file, reading from
-    'src', or writing to 'dst', raises DistutilsFileError.  Data is
-    read/written in chunks of 'buffer_size' bytes (default 16k).  No attempt
-    is made to handle anything apart from regular files.
+    """Copy the file 'src' to 'dst'; both must be filenames.  Any error
+    opening either file, reading from 'src', or writing to 'dst', raises
+    DistutilsFileError.  Data is read/written in chunks of 'buffer_size'
+    bytes (default 16k).  No attempt is made to handle anything apart from
+    regular files.
     """
     # Stolen from shutil module in the standard library, but with
     # custom error-handling added.
@@ -69,16 +68,15 @@
 
 def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
               link=None, verbose=1, dry_run=0):
-    """Copy a file 'src' to 'dst'.
-
-    If 'dst' is a directory, then 'src' is copied there with the same name;
-    otherwise, it must be a filename.  (If the file exists, it will be
-    ruthlessly clobbered.)  If 'preserve_mode' is true (the default),
-    the file's mode (type and permission bits, or whatever is analogous on
-    the current platform) is copied.  If 'preserve_times' is true (the
-    default), the last-modified and last-access times are copied as well.
-    If 'update' is true, 'src' will only be copied if 'dst' does not exist,
-    or if 'dst' does exist but is older than 'src'.
+    """Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is
+    copied there with the same name; otherwise, it must be a filename.  (If
+    the file exists, it will be ruthlessly clobbered.)  If 'preserve_mode'
+    is true (the default), the file's mode (type and permission bits, or
+    whatever is analogous on the current platform) is copied.  If
+    'preserve_times' is true (the default), the last-modified and
+    last-access times are copied as well.  If 'update' is true, 'src' will
+    only be copied if 'dst' does not exist, or if 'dst' does exist but is
+    older than 'src'.
 
     'link' allows you to make hard links (os.link) or symbolic links
     (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
@@ -132,6 +130,15 @@
     if dry_run:
         return (dst, 1)
 
+    # On Mac OS, use the native file copy routine
+    if os.name == 'mac':
+        import macostools
+        try:
+            macostools.copy(src, dst, 0, preserve_times)
+        except os.error as exc:
+            raise DistutilsFileError(
+                  "could not copy '%s' to '%s': %s" % (src, dst, exc.args[-1]))
+
     # If linking (hard or symbolic), use the appropriate system call
     # (Unix only, of course, but that's the caller's responsibility)
     elif link == 'hard':
@@ -159,12 +166,13 @@
 
 
 # XXX I suspect this is Unix-specific -- need porting help!
-def move_file(src, dst, verbose=1, dry_run=0):
-    """Move a file 'src' to 'dst'.
-
-    If 'dst' is a directory, the file will be moved into it with the same
-    name; otherwise, 'src' is just renamed to 'dst'.  Return the new
-    full name of the file.
+def move_file (src, dst,
+               verbose=1,
+               dry_run=0):
+
+    """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
+    be moved into it with the same name; otherwise, 'src' is just renamed
+    to 'dst'.  Return the new full name of the file.
 
     Handles cross-device moves on Unix using 'copy_file()'.  What about
     other systems???
@@ -221,7 +229,7 @@
     return dst
 
 
-def write_file(filename, contents):
+def write_file (filename, contents):
     """Create a file with the specified name and write 'contents' (a
     sequence of strings without line terminators) to it.
     """

Modified: python/branches/py3k-dtoa/Lib/distutils/filelist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/filelist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/filelist.py	Sun Aug  8 12:41:24 2010
@@ -108,7 +108,7 @@
         # defined: it's the first word of the line.  Which of the other
         # three are defined depends on the action; it'll be either
         # patterns, (dir and patterns), or (dir_pattern).
-        action, patterns, dir, dir_pattern = self._parse_template_line(line)
+        (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
 
         # OK, now we know that the action is valid and we have the
         # right number of words on the line for that action -- so we
@@ -175,15 +175,15 @@
             raise DistutilsInternalError(
                   "this cannot happen: invalid action '%s'" % action)
 
+
     # -- Filtering/selection methods -----------------------------------
 
     def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
         """Select strings (presumably filenames) from 'self.files' that
-        match 'pattern', a Unix-style wildcard (glob) pattern.
-
-        Patterns are not quite the same as implemented by the 'fnmatch'
-        module: '*' and '?'  match non-special characters, where "special"
-        is platform-dependent: slash on Unix; colon, slash, and backslash on
+        match 'pattern', a Unix-style wildcard (glob) pattern.  Patterns
+        are not quite the same as implemented by the 'fnmatch' module: '*'
+        and '?'  match non-special characters, where "special" is platform-
+        dependent: slash on Unix; colon, slash, and backslash on
         DOS/Windows; and colon on Mac OS.
 
         If 'anchor' is true (the default), then the pattern match is more
@@ -220,13 +220,13 @@
         return files_found
 
 
-    def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
+    def exclude_pattern (self, pattern,
+                         anchor=1, prefix=None, is_regex=0):
         """Remove strings (presumably filenames) from 'files' that match
-        'pattern'.
-
-        Other parameters are the same as for 'include_pattern()', above.
-        The list 'self.files' is modified in place. Return 1 if files are
-        found.
+        'pattern'.  Other parameters are the same as for
+        'include_pattern()', above.
+        The list 'self.files' is modified in place.
+        Return True if files are found, False otherwise.
         """
         files_found = False
         pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
@@ -275,11 +275,10 @@
 
 
 def glob_to_re(pattern):
-    """Translate a shell-like glob pattern to a regular expression.
-
-    Return a string containing the regex.  Differs from
-    'fnmatch.translate()' in that '*' does not match "special characters"
-    (which are platform-specific).
+    """Translate a shell-like glob pattern to a regular expression; return
+    a string containing the regex.  Differs from 'fnmatch.translate()' in
+    that '*' does not match "special characters" (which are
+    platform-specific).
     """
     pattern_re = fnmatch.translate(pattern)
 
@@ -297,9 +296,7 @@
 
 def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
     """Translate a shell-like wildcard pattern to a compiled regular
-    expression.
-
-    Return the compiled regex.  If 'is_regex' true,
+    expression.  Return the compiled regex.  If 'is_regex' true,
     then 'pattern' is directly compiled to a regex (if it's a string)
     or just returned as-is (assumes it's a regex object).
     """
@@ -317,7 +314,7 @@
     if prefix is not None:
         # ditch end of pattern character
         empty_pattern = glob_to_re('')
-        prefix_re = glob_to_re(prefix)[:-len(empty_pattern)]
+        prefix_re = (glob_to_re(prefix))[:-len(empty_pattern)]
         pattern_re = "^" + os.path.join(prefix_re, ".*" + pattern_re)
     else:                               # no prefix -- respect anchor flag
         if anchor:

Modified: python/branches/py3k-dtoa/Lib/distutils/msvc9compiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/msvc9compiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/msvc9compiler.py	Sun Aug  8 12:41:24 2010
@@ -19,9 +19,10 @@
 import sys
 import re
 
-from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
-                              CompileError, LibError, LinkError)
-from distutils.ccompiler import CCompiler, gen_lib_options
+from distutils.errors import DistutilsExecError, DistutilsPlatformError, \
+                             CompileError, LibError, LinkError
+from distutils.ccompiler import CCompiler, gen_preprocess_options, \
+                                gen_lib_options
 from distutils import log
 from distutils.util import get_platform
 

Modified: python/branches/py3k-dtoa/Lib/distutils/msvccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/msvccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/msvccompiler.py	Sun Aug  8 12:41:24 2010
@@ -10,12 +10,12 @@
 
 __revision__ = "$Id$"
 
-import sys
-import os
-
-from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
-                              CompileError, LibError, LinkError)
-from distutils.ccompiler import CCompiler, gen_lib_options
+import sys, os
+from distutils.errors import \
+     DistutilsExecError, DistutilsPlatformError, \
+     CompileError, LibError, LinkError
+from distutils.ccompiler import \
+     CCompiler, gen_preprocess_options, gen_lib_options
 from distutils import log
 
 _can_read_reg = False
@@ -124,7 +124,7 @@
                 self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
             else:
                 self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
-        except KeyError:
+        except KeyError as exc: #
             raise DistutilsPlatformError(
             """Python was built with Visual Studio 2003;
 extensions must be built with a compiler than can generate compatible binaries.

Modified: python/branches/py3k-dtoa/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/sysconfig.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/sysconfig.py	Sun Aug  8 12:41:24 2010
@@ -7,9 +7,6 @@
 
 Written by:   Fred L. Drake, Jr.
 Email:        <fdrake at acm.org>
-
-**This module has been moved out of Distutils and will be removed from
-Python in the next version (3.3)**
 """
 
 __revision__ = "$Id$"
@@ -17,45 +14,51 @@
 import io
 import os
 import re
-from warnings import warn
-
-from distutils.errors import DistutilsPlatformError
+import sys
 
-# importing sysconfig from Lib
-# to avoid this module to shadow it
-_sysconfig = __import__('sysconfig')
-
-# names defined here to keep backward compatibility
-# for APIs that were relocated
-get_python_version = _sysconfig.get_python_version
-get_config_h_filename = _sysconfig.get_config_h_filename
-parse_config_h = _sysconfig.parse_config_h
-get_config_vars = _sysconfig.get_config_vars
-get_config_var = _sysconfig.get_config_var
-from distutils.ccompiler import customize_compiler
-
-_DEPRECATION_MSG = ("distutils.sysconfig.%s is deprecated. "
-                    "Use the APIs provided by the sysconfig module instead")
-
-def _get_project_base():
-    return _sysconfig._PROJECT_BASE
-
-project_base = _get_project_base()
-
-class _DeprecatedBool(int):
-    def __nonzero__(self):
-        warn(_DEPRECATION_MSG % 'get_python_version', DeprecationWarning)
-        return super(_DeprecatedBool, self).__nonzero__()
+from .errors import DistutilsPlatformError
 
+# These are needed in a couple of spots, so just compute them once.
+PREFIX = os.path.normpath(sys.prefix)
+EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
+
+# Path to the base directory of the project. On Windows the binary may
+# live in project/PCBuild9.  If we're dealing with an x64 Windows build,
+# it'll live in project/PCbuild/amd64.
+project_base = os.path.dirname(os.path.abspath(sys.executable))
+if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
+    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
+# PC/VS7.1
+if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
+    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
+                                                os.path.pardir))
+# PC/AMD64
+if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
+    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
+                                                os.path.pardir))
+
+# python_build: (Boolean) if true, we're either building Python or
+# building an extension with an un-installed Python, so we use
+# different (hard-wired) directories.
+# Setup.local is available for Makefile builds including VPATH builds,
+# Setup.dist is available on Windows
 def _python_build():
-    return _DeprecatedBool(_sysconfig.is_python_build())
-
+    for fn in ("Setup.dist", "Setup.local"):
+        if os.path.isfile(os.path.join(project_base, "Modules", fn)):
+            return True
+    return False
 python_build = _python_build()
 
-def get_python_inc(plat_specific=0, prefix=None):
-    """This function is deprecated.
+def get_python_version():
+    """Return a string containing the major and minor Python version,
+    leaving off the patchlevel.  Sample return values could be '1.5'
+    or '2.2'.
+    """
+    return sys.version[:3]
+
 
-    Return the directory containing installed Python header files.
+def get_python_inc(plat_specific=0, prefix=None):
+    """Return the directory containing installed Python header files.
 
     If 'plat_specific' is false (the default), this is the path to the
     non-platform-specific header files, i.e. Python.h and so on;
@@ -65,22 +68,39 @@
     If 'prefix' is supplied, use it instead of sys.prefix or
     sys.exec_prefix -- i.e., ignore 'plat_specific'.
     """
-    warn(_DEPRECATION_MSG % 'get_python_inc', DeprecationWarning)
-    get_path = _sysconfig.get_path
-
-    if prefix is not None:
-        vars = {'base': prefix}
-        return get_path('include', vars=vars)
-
-    if not plat_specific:
-        return get_path('include')
+    if prefix is None:
+        prefix = plat_specific and EXEC_PREFIX or PREFIX
+    if os.name == "posix":
+        if python_build:
+            # Assume the executable is in the build directory.  The
+            # pyconfig.h file should be in the same directory.  Since
+            # the build directory may not be the source directory, we
+            # must use "srcdir" from the makefile to find the "Include"
+            # directory.
+            base = os.path.dirname(os.path.abspath(sys.executable))
+            if plat_specific:
+                return base
+            else:
+                incdir = os.path.join(get_config_var('srcdir'), 'Include')
+                return os.path.normpath(incdir)
+        return os.path.join(prefix, "include", "python" + get_python_version())
+    elif os.name == "nt":
+        return os.path.join(prefix, "include")
+    elif os.name == "mac":
+        if plat_specific:
+            return os.path.join(prefix, "Mac", "Include")
+        else:
+            return os.path.join(prefix, "Include")
+    elif os.name == "os2":
+        return os.path.join(prefix, "Include")
     else:
-        return get_path('platinclude')
+        raise DistutilsPlatformError(
+            "I don't know where Python installs its C header files "
+            "on platform '%s'" % os.name)
 
-def get_python_lib(plat_specific=False, standard_lib=False, prefix=None):
-    """This function is deprecated.
 
-    Return the directory containing the Python library (standard or
+def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
+    """Return the directory containing the Python library (standard or
     site additions).
 
     If 'plat_specific' is true, return the directory containing
@@ -93,33 +113,149 @@
     If 'prefix' is supplied, use it instead of sys.prefix or
     sys.exec_prefix -- i.e., ignore 'plat_specific'.
     """
-    warn(_DEPRECATION_MSG % 'get_python_lib', DeprecationWarning)
-    vars = {}
-    get_path = _sysconfig.get_path
-    if prefix is not None:
-        if plat_specific:
-            vars['platbase'] = prefix
+    if prefix is None:
+        prefix = plat_specific and EXEC_PREFIX or PREFIX
+
+    if os.name == "posix":
+        libpython = os.path.join(prefix,
+                                 "lib", "python" + get_python_version())
+        if standard_lib:
+            return libpython
+        else:
+            return os.path.join(libpython, "site-packages")
+    elif os.name == "nt":
+        if standard_lib:
+            return os.path.join(prefix, "Lib")
         else:
-            vars['base'] = prefix
-    if standard_lib:
+            if get_python_version() < "2.2":
+                return prefix
+            else:
+                return os.path.join(prefix, "Lib", "site-packages")
+    elif os.name == "mac":
         if plat_specific:
-            return get_path('platstdlib', vars=vars)
+            if standard_lib:
+                return os.path.join(prefix, "Lib", "lib-dynload")
+            else:
+                return os.path.join(prefix, "Lib", "site-packages")
         else:
-            return get_path('stdlib', vars=vars)
+            if standard_lib:
+                return os.path.join(prefix, "Lib")
+            else:
+                return os.path.join(prefix, "Lib", "site-packages")
+    elif os.name == "os2":
+        if standard_lib:
+            return os.path.join(prefix, "Lib")
+        else:
+            return os.path.join(prefix, "Lib", "site-packages")
     else:
-        if plat_specific:
-            return get_path('platlib', vars=vars)
+        raise DistutilsPlatformError(
+            "I don't know where Python installs its library "
+            "on platform '%s'" % os.name)
+
+
+def customize_compiler(compiler):
+    """Do any platform-specific customization of a CCompiler instance.
+
+    Mainly needed on Unix, so we can plug in the information that
+    varies across Unices and is stored in Python's Makefile.
+    """
+    if compiler.compiler_type == "unix":
+        (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
+            get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
+                            'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS')
+
+        if 'CC' in os.environ:
+            cc = os.environ['CC']
+        if 'CXX' in os.environ:
+            cxx = os.environ['CXX']
+        if 'LDSHARED' in os.environ:
+            ldshared = os.environ['LDSHARED']
+        if 'CPP' in os.environ:
+            cpp = os.environ['CPP']
         else:
-            return get_path('purelib', vars=vars)
+            cpp = cc + " -E"           # not always
+        if 'LDFLAGS' in os.environ:
+            ldshared = ldshared + ' ' + os.environ['LDFLAGS']
+        if 'CFLAGS' in os.environ:
+            cflags = opt + ' ' + os.environ['CFLAGS']
+            ldshared = ldshared + ' ' + os.environ['CFLAGS']
+        if 'CPPFLAGS' in os.environ:
+            cpp = cpp + ' ' + os.environ['CPPFLAGS']
+            cflags = cflags + ' ' + os.environ['CPPFLAGS']
+            ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
+        if 'AR' in os.environ:
+            ar = os.environ['AR']
+        if 'ARFLAGS' in os.environ:
+            archiver = ar + ' ' + os.environ['ARFLAGS']
+        else:
+            archiver = ar + ' ' + ar_flags
+
+        cc_cmd = cc + ' ' + cflags
+        compiler.set_executables(
+            preprocessor=cpp,
+            compiler=cc_cmd,
+            compiler_so=cc_cmd + ' ' + ccshared,
+            compiler_cxx=cxx,
+            linker_so=ldshared,
+            linker_exe=cc,
+            archiver=archiver)
+
+        compiler.shared_lib_extension = so_ext
+
+
+def get_config_h_filename():
+    """Return full pathname of installed pyconfig.h file."""
+    if python_build:
+        if os.name == "nt":
+            inc_dir = os.path.join(project_base, "PC")
+        else:
+            inc_dir = project_base
+    else:
+        inc_dir = get_python_inc(plat_specific=1)
+    if get_python_version() < '2.2':
+        config_h = 'config.h'
+    else:
+        # The name of the config.h file changed in 2.2
+        config_h = 'pyconfig.h'
+    return os.path.join(inc_dir, config_h)
+
 
 def get_makefile_filename():
-    """This function is deprecated.
+    """Return full pathname of installed Makefile from the Python build."""
+    if python_build:
+        return os.path.join(os.path.dirname(sys.executable), "Makefile")
+    lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
+    return os.path.join(lib_dir, "config", "Makefile")
+
+
+def parse_config_h(fp, g=None):
+    """Parse a config.h-style file.
 
-    Return full pathname of installed Makefile from the Python build.
+    A dictionary containing name/value pairs is returned.  If an
+    optional dictionary is passed in as the second argument, it is
+    used instead of a new dictionary.
     """
+    if g is None:
+        g = {}
+    define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
+    undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
+    #
+    while True:
+        line = fp.readline()
+        if not line:
+            break
+        m = define_rx.match(line)
+        if m:
+            n, v = m.group(1, 2)
+            try: v = int(v)
+            except ValueError: pass
+            g[n] = v
+        else:
+            m = undef_rx.match(line)
+            if m:
+                g[m.group(1)] = 0
+    return g
 
-    warn(_DEPRECATION_MSG % 'get_makefile_filename', DeprecationWarning)
-    return _sysconfig._get_makefile_filename()
 
 # Regexes needed for parsing Makefile (and similar syntaxes,
 # like old-style Setup files).
@@ -128,29 +264,114 @@
 _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
 
 def parse_makefile(fn, g=None):
-    """This function is deprecated.
-
-    Parse a Makefile-style file.
+    """Parse a Makefile-style file.
 
     A dictionary containing name/value pairs is returned.  If an
     optional dictionary is passed in as the second argument, it is
     used instead of a new dictionary.
     """
-    warn(_DEPRECATION_MSG % 'parse_makefile', DeprecationWarning)
-    return _sysconfig._parse_makefile(fn, g)
+    from distutils.text_file import TextFile
+    fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
+
+    if g is None:
+        g = {}
+    done = {}
+    notdone = {}
+
+    while True:
+        line = fp.readline()
+        if line is None: # eof
+            break
+        m = _variable_rx.match(line)
+        if m:
+            n, v = m.group(1, 2)
+            v = v.strip()
+            # `$$' is a literal `$' in make
+            tmpv = v.replace('$$', '')
+
+            if "$" in tmpv:
+                notdone[n] = v
+            else:
+                try:
+                    v = int(v)
+                except ValueError:
+                    # insert literal `$'
+                    done[n] = v.replace('$$', '$')
+                else:
+                    done[n] = v
+
+    # Variables with a 'PY_' prefix in the makefile. These need to
+    # be made available without that prefix through sysconfig.
+    # Special care is needed to ensure that variable expansion works, even
+    # if the expansion uses the name without a prefix.
+    renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
+
+    # do variable interpolation here
+    while notdone:
+        for name in list(notdone):
+            value = notdone[name]
+            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
+            if m:
+                n = m.group(1)
+                found = True
+                if n in done:
+                    item = str(done[n])
+                elif n in notdone:
+                    # get it on a subsequent round
+                    found = False
+                elif n in os.environ:
+                    # do it like make: fall back to environment
+                    item = os.environ[n]
+
+                elif n in renamed_variables:
+                    if name.startswith('PY_') and name[3:] in renamed_variables:
+                        item = ""
+
+                    elif 'PY_' + n in notdone:
+                        found = False
+
+                    else:
+                        item = str(done['PY_' + n])
+                else:
+                    done[n] = item = ""
+                if found:
+                    after = value[m.end():]
+                    value = value[:m.start()] + item + after
+                    if "$" in after:
+                        notdone[name] = value
+                    else:
+                        try: value = int(value)
+                        except ValueError:
+                            done[name] = value.strip()
+                        else:
+                            done[name] = value
+                        del notdone[name]
+
+                        if name.startswith('PY_') \
+                            and name[3:] in renamed_variables:
+
+                            name = name[3:]
+                            if name not in done:
+                                done[name] = value
+            else:
+                # bogus variable reference; just drop it since we can't deal
+                del notdone[name]
+
+    fp.close()
+
+    # save the results in the global dictionary
+    g.update(done)
+    return g
 
-def expand_makefile_vars(s, vars):
-    """This function is deprecated.
 
-    Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
+def expand_makefile_vars(s, vars):
+    """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
     'string' according to 'vars' (a dictionary mapping variable names to
     values).  Variables not present in 'vars' are silently expanded to the
     empty string.  The variable values in 'vars' should not contain further
     variable expansions; if 'vars' is the output of 'parse_makefile()',
     you're fine.  Returns a variable-expanded version of 's'.
     """
-    warn('this function will be removed in then next version of Python',
-         DeprecationWarning)
 
     # This algorithm does multiple expansion, so if vars['foo'] contains
     # "${bar}", it will expand ${foo} to ${bar}, and then expand
@@ -166,3 +387,220 @@
         else:
             break
     return s
+
+
+_config_vars = None
+
+def _init_posix():
+    """Initialize the module as appropriate for POSIX systems."""
+    g = {}
+    # load the installed Makefile:
+    try:
+        filename = get_makefile_filename()
+        parse_makefile(filename, g)
+    except IOError as msg:
+        my_msg = "invalid Python installation: unable to open %s" % filename
+        if hasattr(msg, "strerror"):
+            my_msg = my_msg + " (%s)" % msg.strerror
+
+        raise DistutilsPlatformError(my_msg)
+
+    # load the installed pyconfig.h:
+    try:
+        filename = get_config_h_filename()
+        parse_config_h(io.open(filename), g)
+    except IOError as msg:
+        my_msg = "invalid Python installation: unable to open %s" % filename
+        if hasattr(msg, "strerror"):
+            my_msg = my_msg + " (%s)" % msg.strerror
+
+        raise DistutilsPlatformError(my_msg)
+
+    # On MacOSX we need to check the setting of the environment variable
+    # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
+    # it needs to be compatible.
+    # If it isn't set we set it to the configure-time value
+    if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g:
+        cfg_target = g['MACOSX_DEPLOYMENT_TARGET']
+        cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
+        if cur_target == '':
+            cur_target = cfg_target
+            os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
+        elif [int(x) for x in cfg_target.split('.')] > [int(x) for x in cur_target.split('.')]:
+            my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
+                % (cur_target, cfg_target))
+            raise DistutilsPlatformError(my_msg)
+
+    # On AIX, there are wrong paths to the linker scripts in the Makefile
+    # -- these paths are relative to the Python source, but when installed
+    # the scripts are in another directory.
+    if python_build:
+        g['LDSHARED'] = g['BLDSHARED']
+
+    elif get_python_version() < '2.1':
+        # The following two branches are for 1.5.2 compatibility.
+        if sys.platform == 'aix4':          # what about AIX 3.x ?
+            # Linker script is in the config directory, not in Modules as the
+            # Makefile says.
+            python_lib = get_python_lib(standard_lib=1)
+            ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
+            python_exp = os.path.join(python_lib, 'config', 'python.exp')
+
+            g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
+
+    global _config_vars
+    _config_vars = g
+
+
+def _init_nt():
+    """Initialize the module as appropriate for NT"""
+    g = {}
+    # set basic install directories
+    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
+    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
+
+    # XXX hmmm.. a normal install puts include files here
+    g['INCLUDEPY'] = get_python_inc(plat_specific=0)
+
+    g['SO'] = '.pyd'
+    g['EXE'] = ".exe"
+    g['VERSION'] = get_python_version().replace(".", "")
+    g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
+
+    global _config_vars
+    _config_vars = g
+
+
+def _init_mac():
+    """Initialize the module as appropriate for Macintosh systems"""
+    g = {}
+    # set basic install directories
+    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
+    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
+
+    # XXX hmmm.. a normal install puts include files here
+    g['INCLUDEPY'] = get_python_inc(plat_specific=0)
+
+    import MacOS
+    if not hasattr(MacOS, 'runtimemodel'):
+        g['SO'] = '.ppc.slb'
+    else:
+        g['SO'] = '.%s.slb' % MacOS.runtimemodel
+
+    # XXX are these used anywhere?
+    g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib")
+    g['install_platlib'] = os.path.join(EXEC_PREFIX, "Mac", "Lib")
+
+    # These are used by the extension module build
+    g['srcdir'] = ':'
+    global _config_vars
+    _config_vars = g
+
+
+def _init_os2():
+    """Initialize the module as appropriate for OS/2"""
+    g = {}
+    # set basic install directories
+    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
+    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
+
+    # XXX hmmm.. a normal install puts include files here
+    g['INCLUDEPY'] = get_python_inc(plat_specific=0)
+
+    g['SO'] = '.pyd'
+    g['EXE'] = ".exe"
+
+    global _config_vars
+    _config_vars = g
+
+
+def get_config_vars(*args):
+    """With no arguments, return a dictionary of all configuration
+    variables relevant for the current platform.  Generally this includes
+    everything needed to build extensions and install both pure modules and
+    extensions.  On Unix, this means every variable defined in Python's
+    installed Makefile; on Windows and Mac OS it's a much smaller set.
+
+    With arguments, return a list of values that result from looking up
+    each argument in the configuration variable dictionary.
+    """
+    global _config_vars
+    if _config_vars is None:
+        func = globals().get("_init_" + os.name)
+        if func:
+            func()
+        else:
+            _config_vars = {}
+
+        # Normalized versions of prefix and exec_prefix are handy to have;
+        # in fact, these are the standard versions used most places in the
+        # Distutils.
+        _config_vars['prefix'] = PREFIX
+        _config_vars['exec_prefix'] = EXEC_PREFIX
+
+        # Convert srcdir into an absolute path if it appears necessary.
+        # Normally it is relative to the build directory.  However, during
+        # testing, for example, we might be running a non-installed python
+        # from a different directory.
+        if python_build and os.name == "posix":
+            base = os.path.dirname(os.path.abspath(sys.executable))
+            if (not os.path.isabs(_config_vars['srcdir']) and
+                base != os.getcwd()):
+                # srcdir is relative and we are not in the same directory
+                # as the executable. Assume executable is in the build
+                # directory and make srcdir absolute.
+                srcdir = os.path.join(base, _config_vars['srcdir'])
+                _config_vars['srcdir'] = os.path.normpath(srcdir)
+
+        if sys.platform == 'darwin':
+            kernel_version = os.uname()[2] # Kernel version (8.4.3)
+            major_version = int(kernel_version.split('.')[0])
+
+            if major_version < 8:
+                # On Mac OS X before 10.4, check if -arch and -isysroot
+                # are in CFLAGS or LDFLAGS and remove them if they are.
+                # This is needed when building extensions on a 10.3 system
+                # using a universal build of python.
+                for key in ('LDFLAGS', 'BASECFLAGS',
+                        # a number of derived variables. These need to be
+                        # patched up as well.
+                        'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
+                    flags = _config_vars[key]
+                    flags = re.sub('-arch\s+\w+\s', ' ', flags, re.ASCII)
+                    flags = re.sub('-isysroot [^ \t]*', ' ', flags)
+                    _config_vars[key] = flags
+
+            else:
+
+                # Allow the user to override the architecture flags using
+                # an environment variable.
+                # NOTE: This name was introduced by Apple in OSX 10.5 and
+                # is used by several scripting languages distributed with
+                # that OS release.
+
+                if 'ARCHFLAGS' in os.environ:
+                    arch = os.environ['ARCHFLAGS']
+                    for key in ('LDFLAGS', 'BASECFLAGS',
+                        # a number of derived variables. These need to be
+                        # patched up as well.
+                        'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
+
+                        flags = _config_vars[key]
+                        flags = re.sub('-arch\s+\w+\s', ' ', flags)
+                        flags = flags + ' ' + arch
+                        _config_vars[key] = flags
+
+    if args:
+        vals = []
+        for name in args:
+            vals.append(_config_vars.get(name))
+        return vals
+    else:
+        return _config_vars
+
+def get_config_var(name):
+    """Return the value of a single variable using the dictionary
+    returned by 'get_config_vars()'.  Equivalent to
+    get_config_vars().get(name)
+    """
+    return get_config_vars().get(name)

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/support.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/support.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/support.py	Sun Aug  8 12:41:24 2010
@@ -3,19 +3,11 @@
 import shutil
 import tempfile
 from copy import deepcopy
-import warnings
 
 from distutils import log
 from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL
 from distutils.core import Distribution
 
-def capture_warnings(func):
-    def _capture_warnings(*args, **kw):
-        with warnings.catch_warnings():
-            warnings.simplefilter("ignore")
-            return func(*args, **kw)
-    return _capture_warnings
-
 class LoggingSilencer(object):
 
     def setUp(self):
@@ -63,8 +55,6 @@
         super().tearDown()
         while self.tempdirs:
             d = self.tempdirs.pop()
-            if not os.path.exists(d):
-                continue
             shutil.rmtree(d, os.name in ('nt', 'cygwin'))
 
     def mkdtemp(self):

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_archive_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_archive_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_archive_util.py	Sun Aug  8 12:41:24 2010
@@ -15,30 +15,15 @@
 from test.support import check_warnings
 
 try:
-    import grp
-    import pwd
-    UID_GID_SUPPORT = True
-except ImportError:
-    UID_GID_SUPPORT = False
-
-try:
     import zipfile
     ZIP_SUPPORT = True
 except ImportError:
     ZIP_SUPPORT = find_executable('zip')
 
-# some tests will fail if zlib is not available
-try:
-    import zlib
-except ImportError:
-    zlib = None
-
-
 class ArchiveUtilTestCase(support.TempdirManager,
                           support.LoggingSilencer,
                           unittest.TestCase):
 
-    @unittest.skipUnless(zlib, "requires zlib")
     def test_make_tarball(self):
         # creating something to tar
         tmpdir = self.mkdtemp()
@@ -49,7 +34,7 @@
 
         tmpdir2 = self.mkdtemp()
         unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
-                            "source and target should be on same drive")
+                            "Source and target should be on same drive")
 
         base_name = os.path.join(tmpdir2, 'archive')
 
@@ -99,7 +84,6 @@
         base_name = os.path.join(tmpdir2, 'archive')
         return tmpdir, tmpdir2, base_name
 
-    @unittest.skipUnless(zlib, "Requires zlib")
     @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
                          'Need the tar command to run')
     def test_tarfile_vs_tar(self):
@@ -185,7 +169,6 @@
         self.assertTrue(not os.path.exists(tarball))
         self.assertEquals(len(w.warnings), 1)
 
-    @unittest.skipUnless(zlib, "Requires zlib")
     @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
     def test_make_zipfile(self):
         # creating something to tar
@@ -210,59 +193,6 @@
         base_name = os.path.join(tmpdir, 'archive')
         self.assertRaises(ValueError, make_archive, base_name, 'xxx')
 
-    @unittest.skipUnless(zlib, "Requires zlib")
-    def test_make_archive_owner_group(self):
-        # testing make_archive with owner and group, with various combinations
-        # this works even if there's not gid/uid support
-        if UID_GID_SUPPORT:
-            group = grp.getgrgid(0)[0]
-            owner = pwd.getpwuid(0)[0]
-        else:
-            group = owner = 'root'
-
-        base_dir, root_dir, base_name =  self._create_files()
-        base_name = os.path.join(self.mkdtemp() , 'archive')
-        res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
-                           group=group)
-        self.assertTrue(os.path.exists(res))
-
-        res = make_archive(base_name, 'zip', root_dir, base_dir)
-        self.assertTrue(os.path.exists(res))
-
-        res = make_archive(base_name, 'tar', root_dir, base_dir,
-                           owner=owner, group=group)
-        self.assertTrue(os.path.exists(res))
-
-        res = make_archive(base_name, 'tar', root_dir, base_dir,
-                           owner='kjhkjhkjg', group='oihohoh')
-        self.assertTrue(os.path.exists(res))
-
-    @unittest.skipUnless(zlib, "Requires zlib")
-    @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
-    def test_tarfile_root_owner(self):
-        tmpdir, tmpdir2, base_name =  self._create_files()
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        group = grp.getgrgid(0)[0]
-        owner = pwd.getpwuid(0)[0]
-        try:
-            archive_name = make_tarball(base_name, 'dist', compress=None,
-                                        owner=owner, group=group)
-        finally:
-            os.chdir(old_dir)
-
-        # check if the compressed tarball was created
-        self.assertTrue(os.path.exists(archive_name))
-
-        # now checks the rights
-        archive = tarfile.open(archive_name)
-        try:
-            for member in archive.getmembers():
-                self.assertEquals(member.uid, 0)
-                self.assertEquals(member.gid, 0)
-        finally:
-            archive.close()
-
     def test_make_archive_cwd(self):
         current_dir = os.getcwd()
         def _breaks(*args, **kw):

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist.py	Sun Aug  8 12:41:24 2010
@@ -5,8 +5,6 @@
 import tempfile
 import shutil
 
-from test.support import run_unittest
-
 from distutils.core import Distribution
 from distutils.command.bdist import bdist
 from distutils.tests import support
@@ -42,4 +40,4 @@
     return unittest.makeSuite(BuildTestCase)
 
 if __name__ == '__main__':
-    run_unittest(test_suite())
+    test_support.run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_dumb.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_dumb.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_dumb.py	Sun Aug  8 12:41:24 2010
@@ -4,15 +4,6 @@
 import sys
 import os
 
-# zlib is not used here, but if it's not available
-# test_simple_built will fail
-try:
-    import zlib
-except ImportError:
-    zlib = None
-
-from test.support import run_unittest
-
 from distutils.core import Distribution
 from distutils.command.bdist_dumb import bdist_dumb
 from distutils.tests import support
@@ -42,7 +33,6 @@
         sys.argv[:] = self.old_sys_argv[1]
         super(BuildDumbTestCase, self).tearDown()
 
-    @unittest.skipUnless(zlib, "requires zlib")
     def test_simple_built(self):
 
         # let's create a simple package
@@ -83,23 +73,8 @@
         # now let's check what we have in the zip file
         # XXX to be done
 
-    def test_finalize_options(self):
-        pkg_dir, dist = self.create_dist()
-        os.chdir(pkg_dir)
-        cmd = bdist_dumb(dist)
-        self.assertEquals(cmd.bdist_dir, None)
-        cmd.finalize_options()
-
-        # bdist_dir is initialized to bdist_base/dumb if not set
-        base = cmd.get_finalized_command('bdist').bdist_base
-        self.assertEquals(cmd.bdist_dir, os.path.join(base, 'dumb'))
-
-        # the format is set to a default value depending on the os.name
-        default = cmd.default_format[os.name]
-        self.assertEquals(cmd.format, default)
-
 def test_suite():
     return unittest.makeSuite(BuildDumbTestCase)
 
 if __name__ == '__main__':
-    run_unittest(test_suite())
+    test_support.run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_rpm.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_rpm.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_rpm.py	Sun Aug  8 12:41:24 2010
@@ -6,8 +6,6 @@
 import tempfile
 import shutil
 
-from test.support import run_unittest
-
 from distutils.core import Distribution
 from distutils.command.bdist_rpm import bdist_rpm
 from distutils.tests import support
@@ -124,4 +122,4 @@
     return unittest.makeSuite(BuildRpmTestCase)
 
 if __name__ == '__main__':
-    run_unittest(test_suite())
+    test_support.run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_wininst.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_wininst.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_bdist_wininst.py	Sun Aug  8 12:41:24 2010
@@ -1,8 +1,6 @@
 """Tests for distutils.command.bdist_wininst."""
 import unittest
 
-from test.support import run_unittest
-
 from distutils.command.bdist_wininst import bdist_wininst
 from distutils.tests import support
 
@@ -29,4 +27,4 @@
     return unittest.makeSuite(BuildWinInstTestCase)
 
 if __name__ == '__main__':
-    run_unittest(test_suite())
+    test_support.run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_build_clib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_build_clib.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_build_clib.py	Sun Aug  8 12:41:24 2010
@@ -120,7 +120,8 @@
         # before we run the command, we want to make sure
         # all commands are present on the system
         # by creating a compiler and checking its executables
-        from distutils.ccompiler import new_compiler, customize_compiler
+        from distutils.ccompiler import new_compiler
+        from distutils.sysconfig import customize_compiler
 
         compiler = new_compiler()
         customize_compiler(compiler)

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_build_ext.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_build_ext.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_build_ext.py	Sun Aug  8 12:41:24 2010
@@ -3,13 +3,10 @@
 import tempfile
 import shutil
 from io import StringIO
-import warnings
-from test.support import check_warnings
-from test.support import captured_stdout
 
 from distutils.core import Extension, Distribution
 from distutils.command.build_ext import build_ext
-import sysconfig
+from distutils import sysconfig
 from distutils.tests.support import TempdirManager
 from distutils.tests.support import LoggingSilencer
 from distutils.extension import Extension
@@ -25,23 +22,19 @@
 
 def _get_source_filename():
     srcdir = sysconfig.get_config_var('srcdir')
-    if srcdir is None:
-        return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')
     return os.path.join(srcdir, 'Modules', 'xxmodule.c')
 
-_XX_MODULE_PATH = _get_source_filename()
-
-class BuildExtTestCase(TempdirManager, LoggingSilencer, unittest.TestCase):
-
+class BuildExtTestCase(TempdirManager,
+                       LoggingSilencer,
+                       unittest.TestCase):
     def setUp(self):
         # Create a simple test environment
         # Note that we're making changes to sys.path
         super(BuildExtTestCase, self).setUp()
         self.tmp_dir = self.mkdtemp()
-        if os.path.exists(_XX_MODULE_PATH):
-            self.sys_path = sys.path[:]
-            sys.path.append(self.tmp_dir)
-            shutil.copy(_XX_MODULE_PATH, self.tmp_dir)
+        self.sys_path = sys.path, sys.path[:]
+        sys.path.append(self.tmp_dir)
+        shutil.copy(_get_source_filename(), self.tmp_dir)
         if sys.version > "2.6":
             import site
             self.old_user_base = site.USER_BASE
@@ -49,19 +42,6 @@
             from distutils.command import build_ext
             build_ext.USER_BASE = site.USER_BASE
 
-    def tearDown(self):
-        # Get everything back to normal
-        if os.path.exists(_XX_MODULE_PATH):
-            support.unload('xx')
-            sys.path[:] = self.sys_path
-            # XXX on Windows the test leaves a directory
-            # with xx module in TEMP
-        shutil.rmtree(self.tmp_dir, os.name == 'nt' or
-                                    sys.platform == 'cygwin')
-        super(BuildExtTestCase, self).tearDown()
-
-    @unittest.skipIf(not os.path.exists(_XX_MODULE_PATH),
-                     'xxmodule.c not found')
     def test_build_ext(self):
         global ALREADY_TESTED
         xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
@@ -104,23 +84,35 @@
         self.assertTrue(isinstance(xx.Null(), xx.Null))
         self.assertTrue(isinstance(xx.Str(), xx.Str))
 
+    def tearDown(self):
+        # Get everything back to normal
+        support.unload('xx')
+        sys.path = self.sys_path[0]
+        sys.path[:] = self.sys_path[1]
+        if sys.version > "2.6":
+            import site
+            site.USER_BASE = self.old_user_base
+            from distutils.command import build_ext
+            build_ext.USER_BASE = self.old_user_base
+        super(BuildExtTestCase, self).tearDown()
+
     def test_solaris_enable_shared(self):
         dist = Distribution({'name': 'xx'})
         cmd = build_ext(dist)
         old = sys.platform
 
         sys.platform = 'sunos' # fooling finalize_options
-        from sysconfig import _CONFIG_VARS
-        old_var = _CONFIG_VARS.get('Py_ENABLE_SHARED')
-        _CONFIG_VARS['Py_ENABLE_SHARED'] = 1
+        from distutils.sysconfig import  _config_vars
+        old_var = _config_vars.get('Py_ENABLE_SHARED')
+        _config_vars['Py_ENABLE_SHARED'] = 1
         try:
             cmd.ensure_finalized()
         finally:
             sys.platform = old
             if old_var is None:
-                del _CONFIG_VARS['Py_ENABLE_SHARED']
+                del _config_vars['Py_ENABLE_SHARED']
             else:
-                _CONFIG_VARS['Py_ENABLE_SHARED'] = old_var
+                _config_vars['Py_ENABLE_SHARED'] = old_var
 
         # make sure we get some library dirs under solaris
         self.assertTrue(len(cmd.library_dirs) > 0)
@@ -182,10 +174,11 @@
         cmd = build_ext(dist)
         cmd.finalize_options()
 
-        py_include = sysconfig.get_path('include')
+        from distutils import sysconfig
+        py_include = sysconfig.get_python_inc()
         self.assertTrue(py_include in cmd.include_dirs)
 
-        plat_py_include = sysconfig.get_path('platinclude')
+        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
         self.assertTrue(plat_py_include in cmd.include_dirs)
 
         # make sure cmd.libraries is turned into a list
@@ -336,6 +329,7 @@
         self.assertEquals(so_dir, other_tmp_dir)
 
         cmd.inplace = 0
+        cmd.compiler = None
         cmd.run()
         so_file = cmd.get_outputs()[0]
         self.assertTrue(os.path.exists(so_file))
@@ -404,26 +398,6 @@
         wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
         self.assertEquals(wanted, path)
 
-    def test_compiler_deprecation_warning(self):
-        dist = Distribution()
-        cmd = build_ext(dist)
-
-        class MyCompiler(object):
-            def do_something(self):
-                pass
-
-        with check_warnings() as w:
-            warnings.simplefilter("always")
-            cmd.compiler = MyCompiler()
-            self.assertEquals(len(w.warnings), 1)
-            cmd.compile = 'unix'
-            self.assertEquals(len(w.warnings), 1)
-            cmd.compiler = MyCompiler()
-            cmd.compiler.do_something()
-            # two more warnings genereated by the get
-            # and the set
-            self.assertEquals(len(w.warnings), 3)
-
 def test_suite():
     src = _get_source_filename()
     if not os.path.exists(src):

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_build_py.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_build_py.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_build_py.py	Sun Aug  8 12:41:24 2010
@@ -16,7 +16,7 @@
                       support.LoggingSilencer,
                       unittest.TestCase):
 
-    def _setup_package_data(self):
+    def test_package_data(self):
         sources = self.mkdtemp()
         f = open(os.path.join(sources, "__init__.py"), "w")
         f.write("# Pretend this is a package.")
@@ -52,18 +52,9 @@
         self.assertEqual(len(cmd.get_outputs()), 3)
         pkgdest = os.path.join(destination, "pkg")
         files = os.listdir(pkgdest)
-        return files
-
-    def test_package_data(self):
-        files = self._setup_package_data()
         self.assertTrue("__init__.py" in files)
-        self.assertTrue("README.txt" in files)
-
-    @unittest.skipIf(sys.flags.optimize >= 2,
-                     "pyc files are not written with -O2 and above")
-    def test_package_data_pyc(self):
-        files = self._setup_package_data()
         self.assertTrue("__init__.pyc" in files)
+        self.assertTrue("README.txt" in files)
 
     def test_empty_package_dir (self):
         # See SF 1668596/1720897.

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_build_scripts.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_build_scripts.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_build_scripts.py	Sun Aug  8 12:41:24 2010
@@ -5,7 +5,7 @@
 
 from distutils.command.build_scripts import build_scripts
 from distutils.core import Distribution
-import sysconfig
+from distutils import sysconfig
 
 from distutils.tests import support
 
@@ -91,12 +91,12 @@
         # --with-suffix=3`, python is compiled okay but the build scripts
         # failed when writing the name of the executable
         old = sysconfig.get_config_vars().get('VERSION')
-        sysconfig._CONFIG_VARS['VERSION'] = 4
+        sysconfig._config_vars['VERSION'] = 4
         try:
             cmd.run()
         finally:
             if old is not None:
-                sysconfig._CONFIG_VARS['VERSION'] = old
+                sysconfig._config_vars['VERSION'] = old
 
         built = os.listdir(target)
         for name in expected:

Deleted: python/branches/py3k-dtoa/Lib/distutils/tests/test_ccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_ccompiler.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,81 +0,0 @@
-"""Tests for distutils.ccompiler."""
-import os
-import unittest
-from test.support import captured_stdout
-
-from distutils.ccompiler import (gen_lib_options, CCompiler,
-                                 get_default_compiler, customize_compiler)
-from distutils import debug
-from distutils.tests import support
-
-class FakeCompiler(object):
-    def library_dir_option(self, dir):
-        return "-L" + dir
-
-    def runtime_library_dir_option(self, dir):
-        return ["-cool", "-R" + dir]
-
-    def find_library_file(self, dirs, lib, debug=0):
-        return 'found'
-
-    def library_option(self, lib):
-        return "-l" + lib
-
-class CCompilerTestCase(support.EnvironGuard, unittest.TestCase):
-
-    def test_gen_lib_options(self):
-        compiler = FakeCompiler()
-        libdirs = ['lib1', 'lib2']
-        runlibdirs = ['runlib1']
-        libs = [os.path.join('dir', 'name'), 'name2']
-
-        opts = gen_lib_options(compiler, libdirs, runlibdirs, libs)
-        wanted = ['-Llib1', '-Llib2', '-cool', '-Rrunlib1', 'found',
-                  '-lname2']
-        self.assertEquals(opts, wanted)
-
-    def test_debug_print(self):
-
-        class MyCCompiler(CCompiler):
-            executables = {}
-
-        compiler = MyCCompiler()
-        with captured_stdout() as stdout:
-            compiler.debug_print('xxx')
-        stdout.seek(0)
-        self.assertEquals(stdout.read(), '')
-
-        debug.DEBUG = True
-        try:
-            with captured_stdout() as stdout:
-                compiler.debug_print('xxx')
-            stdout.seek(0)
-            self.assertEquals(stdout.read(), 'xxx\n')
-        finally:
-            debug.DEBUG = False
-
-    def test_customize_compiler(self):
-
-        # not testing if default compiler is not unix
-        if get_default_compiler() != 'unix':
-            return
-
-        os.environ['AR'] = 'my_ar'
-        os.environ['ARFLAGS'] = '-arflags'
-
-        # make sure AR gets caught
-        class compiler:
-            compiler_type = 'unix'
-
-            def set_executables(self, **kw):
-                self.exes = kw
-
-        comp = compiler()
-        customize_compiler(comp)
-        self.assertEquals(comp.exes['archiver'], 'my_ar -arflags')
-
-def test_suite():
-    return unittest.makeSuite(CCompilerTestCase)
-
-if __name__ == "__main__":
-    unittest.main(defaultTest="test_suite")

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_cmd.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_cmd.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_cmd.py	Sun Aug  8 12:41:24 2010
@@ -1,7 +1,7 @@
 """Tests for distutils.cmd."""
 import unittest
 import os
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
 
 from distutils.cmd import Command
 from distutils.dist import Distribution
@@ -124,4 +124,4 @@
     return unittest.makeSuite(CommandTestCase)
 
 if __name__ == '__main__':
-    run_unittest(test_suite())
+    test_support.run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_cygwinccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_cygwinccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_cygwinccompiler.py	Sun Aug  8 12:41:24 2010
@@ -2,21 +2,29 @@
 import unittest
 import sys
 import os
+from io import BytesIO
 import subprocess
-import warnings
-import sysconfig
-
-from test.support import check_warnings, run_unittest
-from test.support import captured_stdout
 
 from distutils import cygwinccompiler
 from distutils.cygwinccompiler import (CygwinCCompiler, check_config_h,
                                        CONFIG_H_OK, CONFIG_H_NOTOK,
                                        CONFIG_H_UNCERTAIN, get_versions,
-                                       get_msvcr, RE_VERSION)
-from distutils.util import get_compiler_versions
+                                       get_msvcr)
 from distutils.tests import support
 
+class FakePopen(object):
+    test_class = None
+
+    def __init__(self, cmd, shell, stdout):
+        self.cmd = cmd.split()[0]
+        exes = self.test_class._exes
+        if self.cmd in exes:
+            # issue #6438 in Python 3.x, Popen returns bytes
+            self.stdout = BytesIO(exes[self.cmd])
+        else:
+            self.stdout = os.popen(cmd, 'r')
+
+
 class CygwinCCompilerTestCase(support.TempdirManager,
                               unittest.TestCase):
 
@@ -24,17 +32,32 @@
         super(CygwinCCompilerTestCase, self).setUp()
         self.version = sys.version
         self.python_h = os.path.join(self.mkdtemp(), 'python.h')
+        from distutils import sysconfig
         self.old_get_config_h_filename = sysconfig.get_config_h_filename
         sysconfig.get_config_h_filename = self._get_config_h_filename
+        self.old_find_executable = cygwinccompiler.find_executable
+        cygwinccompiler.find_executable = self._find_executable
+        self._exes = {}
+        self.old_popen = cygwinccompiler.Popen
+        FakePopen.test_class = self
+        cygwinccompiler.Popen = FakePopen
 
     def tearDown(self):
         sys.version = self.version
+        from distutils import sysconfig
         sysconfig.get_config_h_filename = self.old_get_config_h_filename
+        cygwinccompiler.find_executable = self.old_find_executable
+        cygwinccompiler.Popen = self.old_popen
         super(CygwinCCompilerTestCase, self).tearDown()
 
     def _get_config_h_filename(self):
         return self.python_h
 
+    def _find_executable(self, name):
+        if name in self._exes:
+            return name
+        return None
+
     def test_check_config_h(self):
 
         # check_config_h looks for "GCC" in sys.version first
@@ -58,6 +81,40 @@
         self.write_file(self.python_h, 'xxx __GNUC__ xxx')
         self.assertEquals(check_config_h()[0], CONFIG_H_OK)
 
+    def test_get_versions(self):
+
+        # get_versions calls distutils.spawn.find_executable on
+        # 'gcc', 'ld' and 'dllwrap'
+        self.assertEquals(get_versions(), (None, None, None))
+
+        # Let's fake we have 'gcc' and it returns '3.4.5'
+        self._exes['gcc'] = b'gcc (GCC) 3.4.5 (mingw special)\nFSF'
+        res = get_versions()
+        self.assertEquals(str(res[0]), '3.4.5')
+
+        # and let's see what happens when the version
+        # doesn't match the regular expression
+        # (\d+\.\d+(\.\d+)*)
+        self._exes['gcc'] = b'very strange output'
+        res = get_versions()
+        self.assertEquals(res[0], None)
+
+        # same thing for ld
+        self._exes['ld'] = b'GNU ld version 2.17.50 20060824'
+        res = get_versions()
+        self.assertEquals(str(res[1]), '2.17.50')
+        self._exes['ld'] = b'@(#)PROGRAM:ld  PROJECT:ld64-77'
+        res = get_versions()
+        self.assertEquals(res[1], None)
+
+        # and dllwrap
+        self._exes['dllwrap'] = b'GNU dllwrap 2.17.50 20060824\nFSF'
+        res = get_versions()
+        self.assertEquals(str(res[2]), '2.17.50')
+        self._exes['dllwrap'] = b'Cheese Wrap'
+        res = get_versions()
+        self.assertEquals(res[2], None)
+
     def test_get_msvcr(self):
 
         # none
@@ -90,23 +147,8 @@
                        '[MSC v.1999 32 bits (Intel)]')
         self.assertRaises(ValueError, get_msvcr)
 
-
-    def test_get_version_deprecated(self):
-        with check_warnings() as w:
-            warnings.simplefilter("always")
-            # make sure get_compiler_versions and get_versions
-            # returns the same thing
-            self.assertEquals(get_compiler_versions(), get_versions())
-            # make sure using get_version() generated a warning
-            self.assertEquals(len(w.warnings), 1)
-            # make sure any usage of RE_VERSION will also
-            # generate a warning, but till works
-            version = RE_VERSION.search('1.2').group(1)
-            self.assertEquals(version, '1.2')
-            self.assertEquals(len(w.warnings), 2)
-
 def test_suite():
     return unittest.makeSuite(CygwinCCompilerTestCase)
 
 if __name__ == '__main__':
-    run_unittest(test_suite())
+    test_support.run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_dist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_dist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_dist.py	Sun Aug  8 12:41:24 2010
@@ -7,9 +7,8 @@
 import warnings
 import textwrap
 
-from distutils.dist import Distribution, fix_help_options, DistributionMetadata
+from distutils.dist import Distribution, fix_help_options
 from distutils.cmd import Command
-import distutils.dist
 
 from test.support import TESTFN, captured_stdout
 from distutils.tests import support
@@ -38,8 +37,7 @@
         return self._config_files
 
 
-class DistributionTestCase(support.TempdirManager,
-                           support.LoggingSilencer,
+class DistributionTestCase(support.LoggingSilencer,
                            support.EnvironGuard,
                            unittest.TestCase):
 
@@ -60,27 +58,6 @@
         d.parse_command_line()
         return d
 
-    def test_debug_mode(self):
-        with open(TESTFN, "w") as f:
-            f.write("[global]")
-            f.write("command_packages = foo.bar, splat")
-
-        files = [TESTFN]
-        sys.argv.append("build")
-
-        with captured_stdout() as stdout:
-            self.create_distribution(files)
-        stdout.seek(0)
-        self.assertEquals(stdout.read(), '')
-        distutils.dist.DEBUG = True
-        try:
-            with captured_stdout() as stdout:
-                self.create_distribution(files)
-            stdout.seek(0)
-            self.assertEquals(stdout.read(), '')
-        finally:
-            distutils.dist.DEBUG = False
-
     def test_command_packages_unspecified(self):
         sys.argv.append("build")
         d = self.create_distribution()
@@ -182,35 +159,6 @@
         kwargs = {'level': 'ok2'}
         self.assertRaises(ValueError, dist.announce, args, kwargs)
 
-    def test_find_config_files_disable(self):
-        # Ticket #1180: Allow user to disable their home config file.
-        temp_home = self.mkdtemp()
-        if os.name == 'posix':
-            user_filename = os.path.join(temp_home, ".pydistutils.cfg")
-        else:
-            user_filename = os.path.join(temp_home, "pydistutils.cfg")
-
-        with open(user_filename, 'w') as f:
-            f.write('[distutils]\n')
-
-        def _expander(path):
-            return temp_home
-
-        old_expander = os.path.expanduser
-        os.path.expanduser = _expander
-        try:
-            d = distutils.dist.Distribution()
-            all_files = d.find_config_files()
-
-            d = distutils.dist.Distribution(attrs={'script_args':
-                                            ['--no-user-cfg']})
-            files = d.find_config_files()
-        finally:
-            os.path.expanduser = old_expander
-
-        # make sure --no-user-cfg disables the user cfg file
-        self.assertEquals(len(all_files)-1, len(files))
-
 class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
                        unittest.TestCase):
 
@@ -364,38 +312,11 @@
                  "version": "1.0",
                  "long_description": long_desc}
 
-        dist = distutils.dist.Distribution(attrs)
+        dist = Distribution(attrs)
         meta = self.format_metadata(dist)
         meta = meta.replace('\n' + 8 * ' ', '\n')
         self.assertTrue(long_desc in meta)
 
-    def test_read_metadata(self):
-        attrs = {"name": "package",
-                 "version": "1.0",
-                 "long_description": "desc",
-                 "description": "xxx",
-                 "download_url": "http://example.com",
-                 "keywords": ['one', 'two'],
-                 "requires": ['foo']}
-
-        dist = Distribution(attrs)
-        metadata = dist.metadata
-
-        # write it then reloads it
-        PKG_INFO = io.StringIO()
-        metadata.write_pkg_file(PKG_INFO)
-        PKG_INFO.seek(0)
-        metadata.read_pkg_file(PKG_INFO)
-
-        self.assertEquals(metadata.name, "package")
-        self.assertEquals(metadata.version, "1.0")
-        self.assertEquals(metadata.description, "xxx")
-        self.assertEquals(metadata.download_url, 'http://example.com')
-        self.assertEquals(metadata.keywords, ['one', 'two'])
-        self.assertEquals(metadata.platforms, ['UNKNOWN'])
-        self.assertEquals(metadata.obsoletes, None)
-        self.assertEquals(metadata.requires, ['foo'])
-
 def test_suite():
     suite = unittest.TestSuite()
     suite.addTest(unittest.makeSuite(DistributionTestCase))

Deleted: python/branches/py3k-dtoa/Lib/distutils/tests/test_emxccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_emxccompiler.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,33 +0,0 @@
-"""Tests for distutils.emxccompiler."""
-import unittest
-import sys
-import os
-import warnings
-
-from test.support import check_warnings, run_unittest
-from test.support import captured_stdout
-
-from distutils.emxccompiler import get_versions
-from distutils.util import get_compiler_versions
-from distutils.tests import support
-
-class EmxCCompilerTestCase(support.TempdirManager,
-                           unittest.TestCase):
-
-    def test_get_version_deprecated(self):
-        with check_warnings() as w:
-            warnings.simplefilter("always")
-            # make sure get_compiler_versions and get_versions
-            # returns the same gcc
-            gcc, ld, dllwrap = get_compiler_versions()
-            emx_gcc, emx_ld = get_versions()
-            self.assertEquals(gcc, emx_gcc)
-
-            # make sure using get_version() generated a warning
-            self.assertEquals(len(w.warnings), 1)
-
-def test_suite():
-    return unittest.makeSuite(EmxCCompilerTestCase)
-
-if __name__ == '__main__':
-    run_unittest(test_suite())

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_extension.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_extension.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_extension.py	Sun Aug  8 12:41:24 2010
@@ -1,16 +1,13 @@
 """Tests for distutils.extension."""
-import os
-import sys
 import unittest
+import os
 import warnings
 
 from test.support import check_warnings
 from distutils.extension import read_setup_file, Extension
-from distutils.tests.support import capture_warnings
 
 class ExtensionTestCase(unittest.TestCase):
 
-    @capture_warnings
     def test_read_setup_file(self):
         # trying to read a Setup file
         # (sample extracted from the PyGame project)
@@ -33,22 +30,16 @@
 
         self.assertEquals(names, wanted)
 
-    @unittest.skipIf(sys.flags.optimize >= 2,
-                     "Assertions are omitted with -O2 and above")
-    def test_extension_init_assertions(self):
-        # The first argument, which is the name, must be a string.
+    def test_extension_init(self):
+        # the first argument, which is the name, must be a string
         self.assertRaises(AssertionError, Extension, 1, [])
+        ext = Extension('name', [])
+        self.assertEquals(ext.name, 'name')
 
         # the second argument, which is the list of files, must
         # be a list of strings
         self.assertRaises(AssertionError, Extension, 'name', 'file')
         self.assertRaises(AssertionError, Extension, 'name', ['file', 1])
-
-    def test_extension_init(self):
-        ext = Extension('name', [])
-        self.assertEquals(ext.name, 'name')
-
-
         ext = Extension('name', ['file1', 'file2'])
         self.assertEquals(ext.sources, ['file1', 'file2'])
 

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_file_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_file_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_file_util.py	Sun Aug  8 12:41:24 2010
@@ -3,7 +3,7 @@
 import os
 import shutil
 
-from distutils.file_util import move_file, write_file, copy_file
+from distutils.file_util import move_file
 from distutils import log
 from distutils.tests import support
 
@@ -55,21 +55,6 @@
         wanted = ['moving %s -> %s' % (self.source, self.target_dir)]
         self.assertEquals(self._logs, wanted)
 
-    def test_write_file(self):
-        lines = ['a', 'b', 'c']
-        dir = self.mkdtemp()
-        foo = os.path.join(dir, 'foo')
-        write_file(foo, lines)
-        content = [line.strip() for line in open(foo).readlines()]
-        self.assertEquals(content, lines)
-
-    def test_copy_file(self):
-        src_dir = self.mkdtemp()
-        foo = os.path.join(src_dir, 'foo')
-        write_file(foo, 'content')
-        dst_dir = self.mkdtemp()
-        copy_file(foo, dst_dir)
-        self.assertTrue(os.path.exists(os.path.join(dst_dir, 'foo')))
 
 def test_suite():
     return unittest.makeSuite(FileUtilTestCase)

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_filelist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_filelist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_filelist.py	Sun Aug  8 12:41:24 2010
@@ -1,25 +1,10 @@
 """Tests for distutils.filelist."""
-from os.path import join
 import unittest
-from test.support import captured_stdout
 
 from distutils.filelist import glob_to_re, FileList
+from test.support import captured_stdout
 from distutils import debug
 
-MANIFEST_IN = """\
-include ok
-include xo
-exclude xo
-include foo.tmp
-global-include *.x
-global-include *.txt
-global-exclude *.tmp
-recursive-include f *.oo
-recursive-exclude global *.x
-graft dir
-prune dir3
-"""
-
 class FileListTestCase(unittest.TestCase):
 
     def test_glob_to_re(self):
@@ -34,34 +19,6 @@
         self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)')
         self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)')
 
-    def test_process_template_line(self):
-        # testing  all MANIFEST.in template patterns
-        file_list = FileList()
-
-        # simulated file list
-        file_list.allfiles = ['foo.tmp', 'ok', 'xo', 'four.txt',
-                              join('global', 'one.txt'),
-                              join('global', 'two.txt'),
-                              join('global', 'files.x'),
-                              join('global', 'here.tmp'),
-                              join('f', 'o', 'f.oo'),
-                              join('dir', 'graft-one'),
-                              join('dir', 'dir2', 'graft2'),
-                              join('dir3', 'ok'),
-                              join('dir3', 'sub', 'ok.txt')
-                              ]
-
-        for line in MANIFEST_IN.split('\n'):
-            if line.strip() == '':
-                continue
-            file_list.process_template_line(line)
-
-        wanted = ['ok', 'four.txt', join('global', 'one.txt'),
-                  join('global', 'two.txt'), join('f', 'o', 'f.oo'),
-                  join('dir', 'graft-one'), join('dir', 'dir2', 'graft2')]
-
-        self.assertEquals(file_list.files, wanted)
-
     def test_debug_print(self):
         file_list = FileList()
         with captured_stdout() as stdout:

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_install.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_install.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_install.py	Sun Aug  8 12:41:24 2010
@@ -5,14 +5,12 @@
 import sys
 import unittest
 import site
-import sysconfig
-from sysconfig import (get_scheme_names, _CONFIG_VARS, _INSTALL_SCHEMES,
-                       get_config_var, get_path)
 
 from test.support import captured_stdout
 
 from distutils.command.install import install
 from distutils.command import install as install_module
+from distutils.command.install import INSTALL_SCHEMES
 from distutils.core import Distribution
 from distutils.errors import DistutilsOptionError
 
@@ -38,23 +36,9 @@
             build_lib=os.path.join(builddir, "lib"),
             )
 
-
-
-        posix_prefix = _INSTALL_SCHEMES['posix_prefix']
-        old_posix_prefix = posix_prefix['platinclude']
-        posix_prefix['platinclude'] = \
-                '{platbase}/include/python{py_version_short}'
-
-        posix_home = _INSTALL_SCHEMES['posix_home']
-        old_posix_home = posix_home['platinclude']
-        posix_home['platinclude'] = '{base}/include/python'
-        try:
-            cmd = install(dist)
-            cmd.home = destination
-            cmd.ensure_finalized()
-        finally:
-            posix_home['platinclude'] = old_posix_home
-            posix_prefix['platinclude'] = old_posix_prefix
+        cmd = install(dist)
+        cmd.home = destination
+        cmd.ensure_finalized()
 
         self.assertEqual(cmd.install_base, destination)
         self.assertEqual(cmd.install_platbase, destination)
@@ -79,19 +63,18 @@
             return
 
         # preparing the environement for the test
-        self.old_user_base = get_config_var('userbase')
-        self.old_user_site = get_path('purelib', '%s_user' % os.name)
+        self.old_user_base = site.USER_BASE
+        self.old_user_site = site.USER_SITE
         self.tmpdir = self.mkdtemp()
         self.user_base = os.path.join(self.tmpdir, 'B')
         self.user_site = os.path.join(self.tmpdir, 'S')
-        _CONFIG_VARS['userbase'] = self.user_base
-        scheme = _INSTALL_SCHEMES['%s_user' % os.name]
-        scheme['purelib'] = self.user_site
+        site.USER_BASE = self.user_base
+        site.USER_SITE = self.user_site
+        install_module.USER_BASE = self.user_base
+        install_module.USER_SITE = self.user_site
 
         def _expanduser(path):
-            if path[0] == '~':
-                path = os.path.normpath(self.tmpdir) + path[1:]
-            return path
+            return self.tmpdir
         self.old_expand = os.path.expanduser
         os.path.expanduser = _expanduser
 
@@ -99,17 +82,19 @@
             # this is the actual test
             self._test_user_site()
         finally:
-            _CONFIG_VARS['userbase'] = self.old_user_base
-            scheme['purelib'] = self.old_user_site
+            site.USER_BASE = self.old_user_base
+            site.USER_SITE = self.old_user_site
+            install_module.USER_BASE = self.old_user_base
+            install_module.USER_SITE = self.old_user_site
             os.path.expanduser = self.old_expand
 
     def _test_user_site(self):
-        schemes = get_scheme_names()
-        for key in ('nt_user', 'posix_user', 'os2_home'):
-            self.assertTrue(key in schemes)
+        for key in ('nt_user', 'unix_user', 'os2_home'):
+            self.assertTrue(key in INSTALL_SCHEMES)
 
         dist = Distribution({'name': 'xx'})
         cmd = install(dist)
+
         # making sure the user option is there
         options = [name for name, short, lable in
                    cmd.user_options]
@@ -200,7 +185,7 @@
         with open(cmd.record) as f:
             self.assertEquals(len(f.readlines()), 1)
 
-    def _test_debug_mode(self):
+    def test_debug_mode(self):
         # this covers the code called when DEBUG is set
         old_logs_len = len(self.logs)
         install_module.DEBUG = True

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_install_lib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_install_lib.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_install_lib.py	Sun Aug  8 12:41:24 2010
@@ -1,6 +1,6 @@
 """Tests for distutils.command.install_data."""
-import os
 import sys
+import os
 import unittest
 
 from distutils.command.install_lib import install_lib
@@ -31,7 +31,9 @@
         cmd.finalize_options()
         self.assertEquals(cmd.optimize, 2)
 
-    def _setup_byte_compile(self):
+    @unittest.skipUnless(not sys.dont_write_bytecode,
+                         'byte-compile not supported')
+    def test_byte_compile(self):
         pkg_dir, dist = self.create_dist()
         cmd = install_lib(dist)
         cmd.compile = cmd.optimize = 1
@@ -39,15 +41,8 @@
         f = os.path.join(pkg_dir, 'foo.py')
         self.write_file(f, '# python file')
         cmd.byte_compile([f])
-        return pkg_dir
-
-    @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile not enabled')
-    def test_byte_compile(self):
-        pkg_dir = self._setup_byte_compile()
-        if sys.flags.optimize < 1:
-            self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc')))
-        else:
-            self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo')))
+        self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc')))
+        self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo')))
 
     def test_get_outputs(self):
         pkg_dir, dist = self.create_dist()

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_register.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_register.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_register.py	Sun Aug  8 12:41:24 2010
@@ -202,10 +202,10 @@
         self.assertRaises(DistutilsSetupError, cmd.run)
 
         # we don't test the reSt feature if docutils
-        # is not installed or we our on py3k
+        # is not installed
         try:
             import docutils
-        except Exception:
+        except ImportError:
             return
 
         # metadata are OK but long_description is broken

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_sdist.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_sdist.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_sdist.py	Sun Aug  8 12:41:24 2010
@@ -3,22 +3,6 @@
 import unittest
 import shutil
 import zipfile
-import tarfile
-
-# zlib is not used here, but if it's not available
-# the tests that use zipfile may fail
-try:
-    import zlib
-except ImportError:
-    zlib = None
-
-try:
-    import grp
-    import pwd
-    UID_GID_SUPPORT = True
-except ImportError:
-    UID_GID_SUPPORT = False
-
 from os.path import join
 import sys
 import tempfile
@@ -95,7 +79,6 @@
         cmd.warn = _warn
         return dist, cmd
 
-    @unittest.skipUnless(zlib, "requires zlib")
     def test_prune_file_list(self):
         # this test creates a package with some vcs dirs in it
         # and launch sdist to make sure they get pruned
@@ -137,7 +120,6 @@
         # making sure everything has been pruned correctly
         self.assertEquals(len(content), 4)
 
-    @unittest.skipUnless(zlib, "requires zlib")
     def test_make_distribution(self):
 
         # check if tar and gzip are installed
@@ -174,7 +156,6 @@
         self.assertEquals(result,
                 ['fake-1.0.tar', 'fake-1.0.tar.gz'])
 
-    @unittest.skipUnless(zlib, "requires zlib")
     def test_add_defaults(self):
 
         # http://bugs.python.org/issue2279
@@ -236,7 +217,6 @@
         manifest = open(join(self.tmp_dir, 'MANIFEST')).read()
         self.assertEquals(manifest, MANIFEST % {'sep': os.sep})
 
-    @unittest.skipUnless(zlib, "requires zlib")
     def test_metadata_check_option(self):
         # testing the `medata-check` option
         dist, cmd = self.get_cmd(metadata={})
@@ -296,55 +276,6 @@
         cmd.formats = 'supazipa'
         self.assertRaises(DistutilsOptionError, cmd.finalize_options)
 
-    @unittest.skipUnless(zlib, "requires zlib")
-    @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
-    def test_make_distribution_owner_group(self):
-
-        # check if tar and gzip are installed
-        if (find_executable('tar') is None or
-            find_executable('gzip') is None):
-            return
-
-        # now building a sdist
-        dist, cmd = self.get_cmd()
-
-        # creating a gztar and specifying the owner+group
-        cmd.formats = ['gztar']
-        cmd.owner = pwd.getpwuid(0)[0]
-        cmd.group = grp.getgrgid(0)[0]
-        cmd.ensure_finalized()
-        cmd.run()
-
-        # making sure we have the good rights
-        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
-        archive = tarfile.open(archive_name)
-        try:
-            for member in archive.getmembers():
-                self.assertEquals(member.uid, 0)
-                self.assertEquals(member.gid, 0)
-        finally:
-            archive.close()
-
-        # building a sdist again
-        dist, cmd = self.get_cmd()
-
-        # creating a gztar
-        cmd.formats = ['gztar']
-        cmd.ensure_finalized()
-        cmd.run()
-
-        # making sure we have the good rights
-        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
-        archive = tarfile.open(archive_name)
-
-        # note that we are not testing the group ownership here
-        # because, depending on the platforms and the container
-        # rights (see #7408)
-        try:
-            for member in archive.getmembers():
-                self.assertEquals(member.uid, os.getuid())
-        finally:
-            archive.close()
 
     def test_get_file_list(self):
         # make sure MANIFEST is recalculated

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_sysconfig.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_sysconfig.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_sysconfig.py	Sun Aug  8 12:41:24 2010
@@ -2,9 +2,9 @@
 import os
 import test
 import unittest
-import shutil
 
 from distutils import sysconfig
+from distutils.ccompiler import get_default_compiler
 from distutils.tests import support
 from test.support import TESTFN, run_unittest
 
@@ -26,7 +26,10 @@
         elif os.path.isdir(TESTFN):
             shutil.rmtree(TESTFN)
 
-    @support.capture_warnings
+    def test_get_config_h_filename(self):
+        config_h = sysconfig.get_config_h_filename()
+        self.assertTrue(os.path.isfile(config_h), config_h)
+
     def test_get_python_lib(self):
         lib_dir = sysconfig.get_python_lib()
         # XXX doesn't work on Linux when Python was never installed before
@@ -34,11 +37,7 @@
         # test for pythonxx.lib?
         self.assertNotEqual(sysconfig.get_python_lib(),
                             sysconfig.get_python_lib(prefix=TESTFN))
-        _sysconfig = __import__('sysconfig')
-        res = sysconfig.get_python_lib(True, True)
-        self.assertEquals(_sysconfig.get_path('platstdlib'), res)
 
-    @support.capture_warnings
     def test_get_python_inc(self):
         inc_dir = sysconfig.get_python_inc()
         # This is not much of a test.  We make sure Python.h exists
@@ -48,7 +47,31 @@
         python_h = os.path.join(inc_dir, "Python.h")
         self.assertTrue(os.path.isfile(python_h), python_h)
 
-    @support.capture_warnings
+    def test_get_config_vars(self):
+        cvars = sysconfig.get_config_vars()
+        self.assertTrue(isinstance(cvars, dict))
+        self.assertTrue(cvars)
+
+    def test_customize_compiler(self):
+
+        # not testing if default compiler is not unix
+        if get_default_compiler() != 'unix':
+            return
+
+        os.environ['AR'] = 'my_ar'
+        os.environ['ARFLAGS'] = '-arflags'
+
+        # make sure AR gets caught
+        class compiler:
+            compiler_type = 'unix'
+
+            def set_executables(self, **kw):
+                self.exes = kw
+
+        comp = compiler()
+        sysconfig.customize_compiler(comp)
+        self.assertEquals(comp.exes['archiver'], 'my_ar -arflags')
+
     def test_parse_makefile_base(self):
         self.makefile = TESTFN
         fd = open(self.makefile, 'w')
@@ -70,6 +93,15 @@
                               'OTHER': 'foo'})
 
 
+    def test_sysconfig_module(self):
+        import sysconfig as global_sysconfig
+        self.assertEquals(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS'))
+        self.assertEquals(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS'))
+        self.assertEquals(global_sysconfig.get_config_var('LDSHARED'),sysconfig.get_config_var('LDSHARED'))
+        self.assertEquals(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC'))
+
+
+
 def test_suite():
     suite = unittest.TestSuite()
     suite.addTest(unittest.makeSuite(SysconfigTestCase))

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_unixccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_unixccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_unixccompiler.py	Sun Aug  8 12:41:24 2010
@@ -1,8 +1,8 @@
 """Tests for distutils.unixccompiler."""
 import sys
 import unittest
-import sysconfig
 
+from distutils import sysconfig
 from distutils.unixccompiler import UnixCCompiler
 
 class UnixCCompilerTestCase(unittest.TestCase):
@@ -114,14 +114,6 @@
         sysconfig.get_config_var = gcv
         self.assertEqual(self.cc.rpath_foo(), '-R/foo')
 
-        # AIX C/C++ linker
-        sys.platform = 'aix'
-        def gcv(v):
-            return 'xxx'
-        sysconfig.get_config_var = gcv
-        self.assertEqual(self.cc.rpath_foo(), '-blibpath:/foo')
-
-
 def test_suite():
     return unittest.makeSuite(UnixCCompilerTestCase)
 

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_upload.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_upload.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_upload.py	Sun Aug  8 12:41:24 2010
@@ -2,8 +2,8 @@
 import sys
 import os
 import unittest
+import http.client as httpclient
 
-from distutils.command import upload as upload_mod
 from distutils.command.upload import upload
 from distutils.core import Distribution
 
@@ -38,37 +38,48 @@
 [server1]
 username:me
 """
+class Response(object):
+    def __init__(self, status=200, reason='OK'):
+        self.status = status
+        self.reason = reason
 
-class FakeOpen(object):
+class FakeConnection(object):
 
-    def __init__(self, url):
-        self.url = url
-        if not isinstance(url, str):
-            self.req = url
-        else:
-            self.req = None
-        self.msg = 'OK'
+    def __init__(self):
+        self.requests = []
+        self.headers = []
+        self.body = ''
 
-    def getcode(self):
-        return 200
+    def __call__(self, netloc):
+        return self
 
+    def connect(self):
+        pass
+    endheaders = connect
+
+    def putrequest(self, method, url):
+        self.requests.append((method, url))
+
+    def putheader(self, name, value):
+        self.headers.append((name, value))
+
+    def send(self, body):
+        self.body = body
+
+    def getresponse(self):
+        return Response()
 
 class uploadTestCase(PyPIRCCommandTestCase):
 
     def setUp(self):
         super(uploadTestCase, self).setUp()
-        self.old_open = upload_mod.urlopen
-        upload_mod.urlopen = self._urlopen
-        self.last_open = None
+        self.old_class = httpclient.HTTPConnection
+        self.conn = httpclient.HTTPConnection = FakeConnection()
 
     def tearDown(self):
-        upload_mod.urlopen = self.old_open
+        httpclient.HTTPConnection = self.old_class
         super(uploadTestCase, self).tearDown()
 
-    def _urlopen(self, url):
-        self.last_open = FakeOpen(url)
-        return self.last_open
-
     def test_finalize_options(self):
 
         # new format
@@ -113,15 +124,13 @@
         cmd.run()
 
         # what did we send ?
-        headers = dict(self.last_open.req.headers)
+        headers = dict(self.conn.headers)
         self.assertEquals(headers['Content-length'], '2087')
         self.assertTrue(headers['Content-type'].startswith('multipart/form-data'))
-        self.assertEquals(self.last_open.req.get_method(), 'POST')
-        self.assertEquals(self.last_open.req.get_full_url(),
-                          'http://pypi.python.org/pypi')
-        self.assertTrue(b'xxx' in self.last_open.req.data)
-        auth = self.last_open.req.headers['Authorization']
-        self.assertFalse('\n' in auth)
+        self.assertFalse('\n' in headers['Authorization'])
+
+        self.assertEquals(self.conn.requests, [('POST', '/pypi')])
+        self.assert_((b'xxx') in self.conn.body)
 
 def test_suite():
     return unittest.makeSuite(uploadTestCase)

Modified: python/branches/py3k-dtoa/Lib/distutils/tests/test_util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/tests/test_util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/tests/test_util.py	Sun Aug  8 12:41:24 2010
@@ -3,33 +3,15 @@
 import sys
 import unittest
 from copy import copy
-from io import BytesIO
-import subprocess
 
-from sysconfig import get_config_vars, get_platform
 from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
-from distutils.util import (convert_path, change_root,
+from distutils.util import (get_platform, convert_path, change_root,
                             check_environ, split_quoted, strtobool,
-                            rfc822_escape, get_compiler_versions,
-                            _find_exe_version, _MAC_OS_X_LD_VERSION,
-                            byte_compile)
-from distutils import util
+                            rfc822_escape, byte_compile)
+from distutils import util # used to patch _environ_checked
+from distutils.sysconfig import get_config_vars
+from distutils import sysconfig
 from distutils.tests import support
-from distutils.version import LooseVersion
-
-class FakePopen(object):
-    test_class = None
-    def __init__(self, cmd, shell, stdout, stderr):
-        self.cmd = cmd.split()[0]
-        exes = self.test_class._exes
-        if self.cmd not in exes:
-            # we don't want to call the system, returning an empty
-            # output so it doesn't match
-            self.stdout = BytesIO()
-            self.stderr = BytesIO()
-        else:
-            self.stdout = BytesIO(exes[self.cmd])
-            self.stderr = BytesIO()
 
 class UtilTestCase(support.EnvironGuard, unittest.TestCase):
 
@@ -43,7 +25,7 @@
         self.join = os.path.join
         self.isabs = os.path.isabs
         self.splitdrive = os.path.splitdrive
-        #self._config_vars = copy(sysconfig._config_vars)
+        self._config_vars = copy(sysconfig._config_vars)
 
         # patching os.uname
         if hasattr(os, 'uname'):
@@ -52,17 +34,8 @@
         else:
             self.uname = None
             self._uname = None
-        os.uname = self._get_uname
 
-        # patching POpen
-        self.old_find_executable = util.find_executable
-        util.find_executable = self._find_executable
-        self._exes = {}
-        self.old_popen = subprocess.Popen
-        self.old_stdout  = sys.stdout
-        self.old_stderr = sys.stderr
-        FakePopen.test_class = self
-        subprocess.Popen = FakePopen
+        os.uname = self._get_uname
 
     def tearDown(self):
         # getting back the environment
@@ -77,11 +50,7 @@
             os.uname = self.uname
         else:
             del os.uname
-        #sysconfig._config_vars = copy(self._config_vars)
-        util.find_executable = self.old_find_executable
-        subprocess.Popen = self.old_popen
-        sys.old_stdout  = self.old_stdout
-        sys.old_stderr = self.old_stderr
+        sysconfig._config_vars = copy(self._config_vars)
         super(UtilTestCase, self).tearDown()
 
     def _set_uname(self, uname):
@@ -91,11 +60,103 @@
         return self._uname
 
     def test_get_platform(self):
-        platform = util.get_platform()
-        self.assertEquals(platform, get_platform())
-        util.set_platform('MyOwnPlatform')
-        self.assertEquals('MyOwnPlatform', util.get_platform())
-        util.set_platform(platform)
+
+        # windows XP, 32bits
+        os.name = 'nt'
+        sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
+                       '[MSC v.1310 32 bit (Intel)]')
+        sys.platform = 'win32'
+        self.assertEquals(get_platform(), 'win32')
+
+        # windows XP, amd64
+        os.name = 'nt'
+        sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
+                       '[MSC v.1310 32 bit (Amd64)]')
+        sys.platform = 'win32'
+        self.assertEquals(get_platform(), 'win-amd64')
+
+        # windows XP, itanium
+        os.name = 'nt'
+        sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
+                       '[MSC v.1310 32 bit (Itanium)]')
+        sys.platform = 'win32'
+        self.assertEquals(get_platform(), 'win-ia64')
+
+        # macbook
+        os.name = 'posix'
+        sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
+                       '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
+        sys.platform = 'darwin'
+        self._set_uname(('Darwin', 'macziade', '8.11.1',
+                   ('Darwin Kernel Version 8.11.1: '
+                    'Wed Oct 10 18:23:28 PDT 2007; '
+                    'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
+        os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
+
+        get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
+                                       '-fwrapv -O3 -Wall -Wstrict-prototypes')
+
+        cursize = sys.maxsize
+        sys.maxsize = (2 ** 31)-1
+        try:
+            self.assertEquals(get_platform(), 'macosx-10.3-i386')
+        finally:
+            sys.maxsize = cursize
+
+        # macbook with fat binaries (fat, universal or fat64)
+        os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
+        get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
+                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
+                                       '-fno-strict-aliasing -fno-common '
+                                       '-dynamic -DNDEBUG -g -O3')
+
+        self.assertEquals(get_platform(), 'macosx-10.4-fat')
+
+        get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
+                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
+                                       '-fno-strict-aliasing -fno-common '
+                                       '-dynamic -DNDEBUG -g -O3')
+
+        self.assertEquals(get_platform(), 'macosx-10.4-intel')
+
+        get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
+                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
+                                       '-fno-strict-aliasing -fno-common '
+                                       '-dynamic -DNDEBUG -g -O3')
+        self.assertEquals(get_platform(), 'macosx-10.4-fat3')
+
+        get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
+                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
+                                       '-fno-strict-aliasing -fno-common '
+                                       '-dynamic -DNDEBUG -g -O3')
+        self.assertEquals(get_platform(), 'macosx-10.4-universal')
+
+        get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
+                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
+                                       '-fno-strict-aliasing -fno-common '
+                                       '-dynamic -DNDEBUG -g -O3')
+
+        self.assertEquals(get_platform(), 'macosx-10.4-fat64')
+
+        for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
+            get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
+                                           '/Developer/SDKs/MacOSX10.4u.sdk  '
+                                           '-fno-strict-aliasing -fno-common '
+                                           '-dynamic -DNDEBUG -g -O3'%(arch,))
+
+            self.assertEquals(get_platform(), 'macosx-10.4-%s'%(arch,))
+
+        # linux debian sarge
+        os.name = 'posix'
+        sys.version = ('2.3.5 (#1, Jul  4 2007, 17:28:59) '
+                       '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
+        sys.platform = 'linux2'
+        self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
+                    '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
+
+        self.assertEquals(get_platform(), 'linux-i686')
+
+        # XXX more platforms to tests here
 
     def test_convert_path(self):
         # linux/mac
@@ -199,70 +260,6 @@
                   'header%(8s)s') % {'8s': '\n'+8*' '}
         self.assertEquals(res, wanted)
 
-    def test_find_exe_version(self):
-        # the ld version scheme under MAC OS is:
-        #   ^@(#)PROGRAM:ld  PROJECT:ld64-VERSION
-        #
-        # where VERSION is a 2-digit number for major
-        # revisions. For instance under Leopard, it's
-        # currently 77
-        #
-        # Dots are used when branching is done.
-        #
-        # The SnowLeopard ld64 is currently 95.2.12
-
-        for output, version in ((b'@(#)PROGRAM:ld  PROJECT:ld64-77', '77'),
-                                (b'@(#)PROGRAM:ld  PROJECT:ld64-95.2.12',
-                                 '95.2.12')):
-            result = _MAC_OS_X_LD_VERSION.search(output)
-            self.assertEquals(result.group(1).decode(), version)
-
-    def _find_executable(self, name):
-        if name in self._exes:
-            return name
-        return None
-
-    def test_get_compiler_versions(self):
-        # get_versions calls distutils.spawn.find_executable on
-        # 'gcc', 'ld' and 'dllwrap'
-        self.assertEquals(get_compiler_versions(), (None, None, None))
-
-        # Let's fake we have 'gcc' and it returns '3.4.5'
-        self._exes['gcc'] = b'gcc (GCC) 3.4.5 (mingw special)\nFSF'
-        res = get_compiler_versions()
-        self.assertEquals(str(res[0]), '3.4.5')
-
-        # and let's see what happens when the version
-        # doesn't match the regular expression
-        # (\d+\.\d+(\.\d+)*)
-        self._exes['gcc'] = b'very strange output'
-        res = get_compiler_versions()
-        self.assertEquals(res[0], None)
-
-        # same thing for ld
-        if sys.platform != 'darwin':
-            self._exes['ld'] = b'GNU ld version 2.17.50 20060824'
-            res = get_compiler_versions()
-            self.assertEquals(str(res[1]), '2.17.50')
-            self._exes['ld'] = b'@(#)PROGRAM:ld  PROJECT:ld64-77'
-            res = get_compiler_versions()
-            self.assertEquals(res[1], None)
-        else:
-            self._exes['ld'] = b'GNU ld version 2.17.50 20060824'
-            res = get_compiler_versions()
-            self.assertEquals(res[1], None)
-            self._exes['ld'] = b'@(#)PROGRAM:ld  PROJECT:ld64-77'
-            res = get_compiler_versions()
-            self.assertEquals(str(res[1]), '77')
-
-        # and dllwrap
-        self._exes['dllwrap'] = b'GNU dllwrap 2.17.50 20060824\nFSF'
-        res = get_compiler_versions()
-        self.assertEquals(str(res[2]), '2.17.50')
-        self._exes['dllwrap'] = b'Cheese Wrap'
-        res = get_compiler_versions()
-        self.assertEquals(res[2], None)
-
     def test_dont_write_bytecode(self):
         # makes sure byte_compile raise a DistutilsError
         # if sys.dont_write_bytecode is True

Modified: python/branches/py3k-dtoa/Lib/distutils/text_file.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/text_file.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/text_file.py	Sun Aug  8 12:41:24 2010
@@ -6,8 +6,8 @@
 
 __revision__ = "$Id$"
 
-import sys
-import io
+import sys, os, io
+
 
 class TextFile:
     """Provides a file-like object that takes care of all the things you

Modified: python/branches/py3k-dtoa/Lib/distutils/unixccompiler.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/unixccompiler.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/unixccompiler.py	Sun Aug  8 12:41:24 2010
@@ -17,6 +17,7 @@
 
 import os, sys, re
 
+from distutils import sysconfig
 from distutils.dep_util import newer
 from distutils.ccompiler import \
      CCompiler, gen_preprocess_options, gen_lib_options
@@ -24,7 +25,6 @@
      DistutilsExecError, CompileError, LibError, LinkError
 from distutils import log
 
-
 # XXX Things not currently handled:
 #   * optimization/debug/warning flags; we just use whatever's in Python's
 #     Makefile and live with it.  Is this adequate?  If not, we might
@@ -74,7 +74,7 @@
 
     if 'ARCHFLAGS' in os.environ and not stripArch:
         # User specified different -arch flags in the environ,
-        # see also the sysconfig
+        # see also distutils.sysconfig
         compiler_so = compiler_so + os.environ['ARCHFLAGS'].split()
 
     if stripSysroot:
@@ -281,9 +281,7 @@
         # this time, there's no way to determine this information from
         # the configuration data stored in the Python installation, so
         # we use this hack.
-        _sysconfig = __import__('sysconfig')
-
-        compiler = os.path.basename(_sysconfig.get_config_var("CC"))
+        compiler = os.path.basename(sysconfig.get_config_var("CC"))
         if sys.platform[:6] == "darwin":
             # MacOSX's linker doesn't understand the -R flag at all
             return "-L" + dir
@@ -293,24 +291,23 @@
             return ["+s", "-L" + dir]
         elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5":
             return ["-rpath", dir]
-        elif self._is_gcc(compiler):
-            # gcc on non-GNU systems does not need -Wl, but can
-            # use it anyway.  Since distutils has always passed in
-            # -Wl whenever gcc was used in the past it is probably
-            # safest to keep doing so.
-            if _sysconfig.get_config_var("GNULD") == "yes":
-                # GNU ld needs an extra option to get a RUNPATH
-                # instead of just an RPATH.
-                return "-Wl,--enable-new-dtags,-R" + dir
-            else:
-                return "-Wl,-R" + dir
-        elif sys.platform[:3] == "aix":
-            return "-blibpath:" + dir
         else:
-            # No idea how --enable-new-dtags would be passed on to
-            # ld if this system was using GNU ld.  Don't know if a
-            # system like this even exists.
-            return "-R" + dir
+            if self._is_gcc(compiler):
+                # gcc on non-GNU systems does not need -Wl, but can
+                # use it anyway.  Since distutils has always passed in
+                # -Wl whenever gcc was used in the past it is probably
+                # safest to keep doing so.
+                if sysconfig.get_config_var("GNULD") == "yes":
+                    # GNU ld needs an extra option to get a RUNPATH
+                    # instead of just an RPATH.
+                    return "-Wl,--enable-new-dtags,-R" + dir
+                else:
+                    return "-Wl,-R" + dir
+            else:
+                # No idea how --enable-new-dtags would be passed on to
+                # ld if this system was using GNU ld.  Don't know if a
+                # system like this even exists.
+                return "-R" + dir
 
     def library_option(self, lib):
         return "-l" + lib
@@ -324,8 +321,7 @@
             # On OSX users can specify an alternate SDK using
             # '-isysroot', calculate the SDK root if it is specified
             # (and use it further on)
-            _sysconfig = __import__('sysconfig')
-            cflags = _sysconfig.get_config_var('CFLAGS')
+            cflags = sysconfig.get_config_var('CFLAGS')
             m = re.search(r'-isysroot\s+(\S+)', cflags)
             if m is None:
                 sysroot = '/'

Modified: python/branches/py3k-dtoa/Lib/distutils/util.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/distutils/util.py	(original)
+++ python/branches/py3k-dtoa/Lib/distutils/util.py	Sun Aug  8 12:41:24 2010
@@ -7,40 +7,182 @@
 __revision__ = "$Id$"
 
 import sys, os, string, re
-
 from distutils.errors import DistutilsPlatformError
 from distutils.dep_util import newer
-from distutils.spawn import spawn, find_executable
+from distutils.spawn import spawn
 from distutils import log
-from distutils.version import LooseVersion
 from distutils.errors import DistutilsByteCompileError
 
-_sysconfig = __import__('sysconfig')
-_PLATFORM = None
+def get_platform ():
+    """Return a string that identifies the current platform.  This is used
+    mainly to distinguish platform-specific build directories and
+    platform-specific built distributions.  Typically includes the OS name
+    and version and the architecture (as supplied by 'os.uname()'),
+    although the exact information included depends on the OS; eg. for IRIX
+    the architecture isn't particularly important (IRIX only runs on SGI
+    hardware), but for Linux the kernel version isn't particularly
+    important.
+
+    Examples of returned values:
+       linux-i586
+       linux-alpha (?)
+       solaris-2.6-sun4u
+       irix-5.3
+       irix64-6.2
+
+    Windows will return one of:
+       win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
+       win-ia64 (64bit Windows on Itanium)
+       win32 (all others - specifically, sys.platform is returned)
+
+    For other non-POSIX platforms, currently just returns 'sys.platform'.
+    """
+    if os.name == 'nt':
+        # sniff sys.version for architecture.
+        prefix = " bit ("
+        i = sys.version.find(prefix)
+        if i == -1:
+            return sys.platform
+        j = sys.version.find(")", i)
+        look = sys.version[i+len(prefix):j].lower()
+        if look == 'amd64':
+            return 'win-amd64'
+        if look == 'itanium':
+            return 'win-ia64'
+        return sys.platform
+
+    if os.name != "posix" or not hasattr(os, 'uname'):
+        # XXX what about the architecture? NT is Intel or Alpha,
+        # Mac OS is M68k or PPC, etc.
+        return sys.platform
+
+    # Try to distinguish various flavours of Unix
+
+    (osname, host, release, version, machine) = os.uname()
+
+    # Convert the OS name to lowercase, remove '/' characters
+    # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
+    osname = osname.lower().replace('/', '')
+    machine = machine.replace(' ', '_')
+    machine = machine.replace('/', '-')
+
+    if osname[:5] == "linux":
+        # At least on Linux/Intel, 'machine' is the processor --
+        # i386, etc.
+        # XXX what about Alpha, SPARC, etc?
+        return  "%s-%s" % (osname, machine)
+    elif osname[:5] == "sunos":
+        if release[0] >= "5":           # SunOS 5 == Solaris 2
+            osname = "solaris"
+            release = "%d.%s" % (int(release[0]) - 3, release[2:])
+        # fall through to standard osname-release-machine representation
+    elif osname[:4] == "irix":              # could be "irix64"!
+        return "%s-%s" % (osname, release)
+    elif osname[:3] == "aix":
+        return "%s-%s.%s" % (osname, version, release)
+    elif osname[:6] == "cygwin":
+        osname = "cygwin"
+        rel_re = re.compile (r'[\d.]+', re.ASCII)
+        m = rel_re.match(release)
+        if m:
+            release = m.group()
+    elif osname[:6] == "darwin":
+        #
+        # For our purposes, we'll assume that the system version from
+        # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
+        # to. This makes the compatibility story a bit more sane because the
+        # machine is going to compile and link as if it were
+        # MACOSX_DEPLOYMENT_TARGET.
+        from distutils.sysconfig import get_config_vars
+        cfgvars = get_config_vars()
+
+        macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
+        if not macver:
+            macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
+
+        if 1:
+            # Always calculate the release of the running machine,
+            # needed to determine if we can build fat binaries or not.
+
+            macrelease = macver
+            # Get the system version. Reading this plist is a documented
+            # way to get the system version (see the documentation for
+            # the Gestalt Manager)
+            try:
+                f = open('/System/Library/CoreServices/SystemVersion.plist')
+            except IOError:
+                # We're on a plain darwin box, fall back to the default
+                # behaviour.
+                pass
+            else:
+                m = re.search(
+                        r'<key>ProductUserVisibleVersion</key>\s*' +
+                        r'<string>(.*?)</string>', f.read())
+                f.close()
+                if m is not None:
+                    macrelease = '.'.join(m.group(1).split('.')[:2])
+                # else: fall back to the default behaviour
+
+        if not macver:
+            macver = macrelease
+
+        if macver:
+            from distutils.sysconfig import get_config_vars
+            release = macver
+            osname = "macosx"
+
+            if (macrelease + '.') >= '10.4.' and \
+                    '-arch' in get_config_vars().get('CFLAGS', '').strip():
+                # The universal build will build fat binaries, but not on
+                # systems before 10.4
+                #
+                # Try to detect 4-way universal builds, those have machine-type
+                # 'universal' instead of 'fat'.
+
+                machine = 'fat'
+                cflags = get_config_vars().get('CFLAGS')
+
+                archs = re.findall('-arch\s+(\S+)', cflags)
+                archs = tuple(sorted(set(archs)))
+
+                if len(archs) == 1:
+                    machine = archs[0]
+                elif archs == ('i386', 'ppc'):
+                    machine = 'fat'
+                elif archs == ('i386', 'x86_64'):
+                    machine = 'intel'
+                elif archs == ('i386', 'ppc', 'x86_64'):
+                    machine = 'fat3'
+                elif archs == ('ppc64', 'x86_64'):
+                    machine = 'fat64'
+                elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
+                    machine = 'universal'
+                else:
+                    raise ValueError(
+                       "Don't know machine value for archs=%r"%(archs,))
 
-def get_platform():
-    """Return a string that identifies the current platform.
+            elif machine == 'i386':
+                # On OSX the machine type returned by uname is always the
+                # 32-bit variant, even if the executable architecture is
+                # the 64-bit variant
+                if sys.maxsize >= 2**32:
+                    machine = 'x86_64'
 
-    By default, will return the value returned by sysconfig.get_platform(),
-    but it can be changed by calling set_platform().
-    """
-    global _PLATFORM
-    if _PLATFORM is None:
-        _PLATFORM = _sysconfig.get_platform()
-    return _PLATFORM
+            elif machine in ('PowerPC', 'Power_Macintosh'):
+                # Pick a sane name for the PPC architecture.
+                machine = 'ppc'
 
-def set_platform(identifier):
-    """Sets the platform string identifier returned by get_platform().
+                # See 'i386' case
+                if sys.maxsize >= 2**32:
+                    machine = 'ppc64'
 
-    Note that this change doesn't impact the value returned by
-    sysconfig.get_platform() and is local to Distutils
-    """
-    global _PLATFORM
-    _PLATFORM = identifier
+    return "%s-%s-%s" % (osname, release, machine)
+
+# get_platform ()
 
-def convert_path(pathname):
-    """Return 'pathname' as a name that will work on the native filesystem.
 
+def convert_path (pathname):
+    """Return 'pathname' as a name that will work on the native filesystem,
     i.e. split it on '/' and put it back together again using the current
     directory separator.  Needed because filenames in the setup script are
     always supplied in Unix style, and have to be converted to the local
@@ -64,12 +206,12 @@
         return os.curdir
     return os.path.join(*paths)
 
+# convert_path ()
 
-def change_root(new_root, pathname):
-    """Return 'pathname' with 'new_root' prepended.
 
-    If 'pathname' is relative, this is equivalent to
-    "os.path.join(new_root,pathname)".
+def change_root (new_root, pathname):
+    """Return 'pathname' with 'new_root' prepended.  If 'pathname' is
+    relative, this is equivalent to "os.path.join(new_root,pathname)".
     Otherwise, it requires making 'pathname' relative and then joining the
     two, which is tricky on DOS/Windows and Mac OS.
     """
@@ -91,16 +233,23 @@
             path = path[1:]
         return os.path.join(new_root, path)
 
-    else:
-        raise DistutilsPlatformError("nothing known about "
-                                     "platform '%s'" % os.name)
+    elif os.name == 'mac':
+        if not os.path.isabs(pathname):
+            return os.path.join(new_root, pathname)
+        else:
+            # Chop off volume name from start of path
+            elements = pathname.split(":", 1)
+            pathname = ":" + elements[1]
+            return os.path.join(new_root, pathname)
 
-_environ_checked = 0
+    else:
+        raise DistutilsPlatformError("nothing known about platform '%s'" % os.name)
 
-def check_environ():
-    """Ensure that 'os.environ' has all the environment variables needed.
 
-    We guarantee that users can use in config files, command-line options,
+_environ_checked = 0
+def check_environ ():
+    """Ensure that 'os.environ' has all the environment variables we
+    guarantee that users can use in config files, command-line options,
     etc.  Currently this includes:
       HOME - user's home directory (Unix only)
       PLAT - description of the current platform, including hardware
@@ -115,14 +264,14 @@
         os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
 
     if 'PLAT' not in os.environ:
-        os.environ['PLAT'] = _sysconfig.get_platform()
+        os.environ['PLAT'] = get_platform()
 
     _environ_checked = 1
 
-def subst_vars(s, local_vars):
-    """Perform shell/Perl-style variable substitution on 'string'.
 
-    Every occurrence of '$' followed by a name is considered a variable, and
+def subst_vars (s, local_vars):
+    """Perform shell/Perl-style variable substitution on 'string'.  Every
+    occurrence of '$' followed by a name is considered a variable, and
     variable is substituted by the value found in the 'local_vars'
     dictionary, or in 'os.environ' if it's not in 'local_vars'.
     'os.environ' is first checked/augmented to guarantee that it contains
@@ -142,11 +291,12 @@
     except KeyError as var:
         raise ValueError("invalid variable '$%s'" % var)
 
-def grok_environment_error(exc, prefix="error: "):
-    """Generate a useful error message from an EnvironmentError.
+# subst_vars ()
+
 
-    This will generate an IOError or an OSError exception object.
-    Handles Python 1.5.1 and 1.5.2 styles, and
+def grok_environment_error (exc, prefix="error: "):
+    """Generate a useful error message from an EnvironmentError (IOError or
+    OSError) exception object.  Handles Python 1.5.1 and 1.5.2 styles, and
     does what it can to deal with exception objects that don't have a
     filename (which happens when the error is due to a two-file operation,
     such as 'rename()' or 'link()'.  Returns the error message as a string
@@ -165,20 +315,18 @@
 
     return error
 
+
 # Needed by 'split_quoted()'
 _wordchars_re = _squote_re = _dquote_re = None
-
 def _init_regex():
     global _wordchars_re, _squote_re, _dquote_re
     _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
     _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
     _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
 
-def split_quoted(s):
+def split_quoted (s):
     """Split a string up according to Unix shell-like rules for quotes and
-    backslashes.
-
-    In short: words are delimited by spaces, as long as those
+    backslashes.  In short: words are delimited by spaces, as long as those
     spaces are not escaped by a backslash, or inside a quoted string.
     Single and double quotes are equivalent, and the quote characters can
     be backslash-escaped.  The backslash is stripped from any two-character
@@ -186,6 +334,7 @@
     characters are stripped from any quoted string.  Returns a list of
     words.
     """
+
     # This is a nice algorithm for splitting up a single string, since it
     # doesn't require character-by-character examination.  It was a little
     # bit of a brain-bender to get it working right, though...
@@ -233,12 +382,13 @@
 
     return words
 
+# split_quoted ()
 
-def execute(func, args, msg=None, verbose=0, dry_run=0):
-    """Perform some action that affects the outside world.
 
-    eg. by writing to the filesystem).  Such actions are special because
-    they are disabled by the 'dry_run' flag.  This method takes care of all
+def execute (func, args, msg=None, verbose=0, dry_run=0):
+    """Perform some action that affects the outside world (eg.  by
+    writing to the filesystem).  Such actions are special because they
+    are disabled by the 'dry_run' flag.  This method takes care of all
     that bureaucracy for you; all you have to do is supply the
     function to call and an argument tuple for it (to embody the
     "external action" being performed), and an optional message to
@@ -254,7 +404,7 @@
         func(*args)
 
 
-def strtobool(val):
+def strtobool (val):
     """Convert a string representation of truth to true (1) or false (0).
 
     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
@@ -270,13 +420,15 @@
         raise ValueError("invalid truth value %r" % (val,))
 
 
-def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
-                  verbose=1, dry_run=0, direct=None):
+def byte_compile (py_files,
+                  optimize=0, force=0,
+                  prefix=None, base_dir=None,
+                  verbose=1, dry_run=0,
+                  direct=None):
     """Byte-compile a collection of Python source files to either .pyc
-    or .pyo files in the same directory.
-
-    'py_files' is a list of files to compile; any files that don't end in
-    ".py" are silently skipped. 'optimize' must be one of the following:
+    or .pyo files in the same directory.  'py_files' is a list of files
+    to compile; any files that don't end in ".py" are silently skipped.
+    'optimize' must be one of the following:
       0 - don't optimize (generate .pyc)
       1 - normal optimization (like "python -O")
       2 - extra optimization (like "python -OO")
@@ -392,8 +544,8 @@
             dfile = file
             if prefix:
                 if file[:len(prefix)] != prefix:
-                    raise ValueError("invalid prefix: filename %r doesn't "
-                                     "start with %r" % (file, prefix))
+                    raise ValueError("invalid prefix: filename %r doesn't start with %r"
+                           % (file, prefix))
                 dfile = dfile[len(prefix):]
             if base_dir:
                 dfile = os.path.join(base_dir, dfile)
@@ -408,8 +560,9 @@
                     log.debug("skipping byte-compilation of %s to %s",
                               file, cfile_base)
 
+# byte_compile ()
 
-def rfc822_escape(header):
+def rfc822_escape (header):
     """Return a version of the string escaped for inclusion in an
     RFC-822 header, by ensuring there are 8 spaces space after each newline.
     """
@@ -417,56 +570,6 @@
     sep = '\n' + 8 * ' '
     return sep.join(lines)
 
-_RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)')
-_MAC_OS_X_LD_VERSION = re.compile(b'^@\(#\)PROGRAM:ld  PROJECT:ld64-((\d+)(\.\d+)*)')
-
-def _find_ld_version():
-    """Finds the ld version. The version scheme differs under Mac OSX."""
-    if sys.platform == 'darwin':
-        return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
-    else:
-        return _find_exe_version('ld -v')
-
-def _find_exe_version(cmd, pattern=_RE_VERSION):
-    """Find the version of an executable by running `cmd` in the shell.
-
-    `pattern` is a compiled regular expression. If not provided, default
-    to _RE_VERSION. If the command is not found, or the output does not
-    match the mattern, returns None.
-    """
-    from subprocess import Popen, PIPE
-    executable = cmd.split()[0]
-    if find_executable(executable) is None:
-        return None
-    pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
-    try:
-        stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
-    finally:
-        pipe.stdout.close()
-        pipe.stderr.close()
-    # some commands like ld under MacOS X, will give the
-    # output in the stderr, rather than stdout.
-    if stdout != b'':
-        out_string = stdout
-    else:
-        out_string = stderr
-
-    result = pattern.search(out_string)
-    if result is None:
-        return None
-    return LooseVersion(result.group(1).decode())
-
-def get_compiler_versions():
-    """Returns a tuple providing the versions of gcc, ld and dllwrap
-
-    For each command, if a command is not found, None is returned.
-    Otherwise a LooseVersion instance is returned.
-    """
-    gcc = _find_exe_version('gcc -dumpversion')
-    ld = _find_ld_version()
-    dllwrap = _find_exe_version('dllwrap --version')
-    return gcc, ld, dllwrap
-
 # 2to3 support
 
 def run_2to3(files, fixer_names=None, options=None, explicit=None):

Modified: python/branches/py3k-dtoa/Lib/doctest.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/doctest.py	(original)
+++ python/branches/py3k-dtoa/Lib/doctest.py	Sun Aug  8 12:41:24 2010
@@ -318,6 +318,8 @@
         self.__out = out
         self.__debugger_used = False
         pdb.Pdb.__init__(self, stdout=out)
+        # still use input() to get user input
+        self.use_rawinput = 1
 
     def set_trace(self, frame=None):
         self.__debugger_used = True
@@ -1379,12 +1381,17 @@
         self.save_linecache_getlines = linecache.getlines
         linecache.getlines = self.__patched_linecache_getlines
 
+        # Make sure sys.displayhook just prints the value to stdout
+        save_displayhook = sys.displayhook
+        sys.displayhook = sys.__displayhook__
+
         try:
             return self.__run(test, compileflags, out)
         finally:
             sys.stdout = save_stdout
             pdb.set_trace = save_set_trace
             linecache.getlines = self.save_linecache_getlines
+            sys.displayhook = save_displayhook
             if clear_globs:
                 test.globs.clear()
                 import builtins

Modified: python/branches/py3k-dtoa/Lib/email/base64mime.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/email/base64mime.py	(original)
+++ python/branches/py3k-dtoa/Lib/email/base64mime.py	Sun Aug  8 12:41:24 2010
@@ -74,12 +74,12 @@
 
 
 def body_encode(s, maxlinelen=76, eol=NL):
-    """Encode a string with base64.
+    r"""Encode a string with base64.
 
     Each line will be wrapped at, at most, maxlinelen characters (defaults to
     76 characters).
 
-    Each line of encoded text will end with eol, which defaults to "\\n".  Set
+    Each line of encoded text will end with eol, which defaults to "\n".  Set
     this to "\r\n" if you will be using the result of this function directly
     in an email.
     """

Modified: python/branches/py3k-dtoa/Lib/email/feedparser.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/email/feedparser.py	(original)
+++ python/branches/py3k-dtoa/Lib/email/feedparser.py	Sun Aug  8 12:41:24 2010
@@ -104,6 +104,10 @@
         # data after the final RE.  In the case of a NL/CR terminated string,
         # this is the empty string.
         self._partial = parts.pop()
+        #GAN 29Mar09  bugs 1555570, 1721862  Confusion at 8K boundary ending with \r:
+        # is there a \n to follow later?
+        if not self._partial and parts and parts[-1].endswith('\r'):
+            self._partial = parts.pop(-2)+parts.pop()
         # parts is a list of strings, alternating between the line contents
         # and the eol character(s).  Gather up a list of lines after
         # re-attaching the newlines.

Modified: python/branches/py3k-dtoa/Lib/email/header.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/email/header.py	(original)
+++ python/branches/py3k-dtoa/Lib/email/header.py	Sun Aug  8 12:41:24 2010
@@ -94,6 +94,9 @@
             word = email.quoprimime.header_decode(encoded_string)
             decoded_words.append((word, charset))
         elif encoding == 'b':
+            paderr = len(encoded_string) % 4   # Postel's law: add missing padding
+            if paderr:
+                encoded_string += '==='[:4 - paderr]
             try:
                 word = email.base64mime.decode(encoded_string)
             except binascii.Error:

Modified: python/branches/py3k-dtoa/Lib/email/message.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/email/message.py	(original)
+++ python/branches/py3k-dtoa/Lib/email/message.py	Sun Aug  8 12:41:24 2010
@@ -198,17 +198,19 @@
             return None
         cte = self.get('content-transfer-encoding', '').lower()
         if cte == 'quoted-printable':
+            if isinstance(payload, str):
+                payload = payload.encode('ascii')
             return utils._qdecode(payload)
         elif cte == 'base64':
             try:
                 if isinstance(payload, str):
-                    payload = payload.encode('raw-unicode-escape')
+                    payload = payload.encode('ascii')
                 return base64.b64decode(payload)
             except binascii.Error:
                 # Incorrect padding
                 pass
         elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
-            in_file = BytesIO(payload.encode('raw-unicode-escape'))
+            in_file = BytesIO(payload.encode('ascii'))
             out_file = BytesIO()
             try:
                 uu.decode(in_file, out_file, quiet=True)

Modified: python/branches/py3k-dtoa/Lib/email/test/test_email.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/email/test/test_email.py	(original)
+++ python/branches/py3k-dtoa/Lib/email/test/test_email.py	Sun Aug  8 12:41:24 2010
@@ -1649,6 +1649,15 @@
                               (b'rg', None), (b'\xe5', 'iso-8859-1'),
                               (b'sbord', None)])
 
+    def test_rfc2047_B_bad_padding(self):
+        s = '=?iso-8859-1?B?%s?='
+        data = [                                # only test complete bytes
+            ('dm==', b'v'), ('dm=', b'v'), ('dm', b'v'),
+            ('dmk=', b'vi'), ('dmk', b'vi')
+          ]
+        for q, a in data:
+            dh = decode_header(s % q)
+            self.assertEqual(dh, [(a, 'iso-8859-1')])
 
 
 # Test the MIMEMessage class
@@ -2454,6 +2463,39 @@
 -Me
 """)
 
+    def test_pushCR_LF(self):
+        '''FeedParser BufferedSubFile.push() assumed it received complete
+           line endings.  A CR ending one push() followed by a LF starting
+           the next push() added an empty line.
+        '''
+        imt = [
+            ("a\r \n",  2),
+            ("b",       0),
+            ("c\n",     1),
+            ("",        0),
+            ("d\r\n",   1),
+            ("e\r",     0),
+            ("\nf",     1),
+            ("\r\n",    1),
+          ]
+        from email.feedparser import BufferedSubFile, NeedMoreData
+        bsf = BufferedSubFile()
+        om = []
+        nt = 0
+        for il, n in imt:
+            bsf.push(il)
+            nt += n
+            n1 = 0
+            while True:
+                ol = bsf.readline()
+                if ol == NeedMoreData:
+                    break
+                om.append(ol)
+                n1 += 1
+            self.assertTrue(n == n1)
+        self.assertTrue(len(om) == nt)
+        self.assertTrue(''.join([il for il, n in imt]) == ''.join(om))
+
 
 
 class TestParsers(TestEmailBase):
@@ -3143,7 +3185,7 @@
 
     def test_broken_base64_header(self):
         raises = self.assertRaises
-        s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3IQ?='
+        s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3I ?='
         raises(errors.HeaderParseError, decode_header, s)
 
 

Modified: python/branches/py3k-dtoa/Lib/fileinput.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/fileinput.py	(original)
+++ python/branches/py3k-dtoa/Lib/fileinput.py	Sun Aug  8 12:41:24 2010
@@ -238,6 +238,12 @@
         self.nextfile()
         self._files = ()
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self.close()
+
     def __iter__(self):
         return self
 

Modified: python/branches/py3k-dtoa/Lib/fnmatch.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/fnmatch.py	(original)
+++ python/branches/py3k-dtoa/Lib/fnmatch.py	Sun Aug  8 12:41:24 2010
@@ -9,13 +9,22 @@
 The function translate(PATTERN) returns a regular expression
 corresponding to PATTERN.  (It does not compile it.)
 """
-
+import os
+import posixpath
 import re
 
-__all__ = ["filter", "fnmatch","fnmatchcase","translate"]
+__all__ = ["filter", "fnmatch", "fnmatchcase", "purge", "translate"]
 
 _cache = {}  # Maps text patterns to compiled regexen.
 _cacheb = {}  # Ditto for bytes patterns.
+_MAXCACHE = 100  # Maximum size of caches.
+
+
+def purge():
+    """Clear the pattern cache."""
+    _cache.clear()
+    _cacheb.clear()
+
 
 def fnmatch(name, pat):
     """Test whether FILENAME matches PATTERN.
@@ -32,12 +41,11 @@
     if the operating system requires it.
     If you don't want this, use fnmatchcase(FILENAME, PATTERN).
     """
-
-    import os
     name = os.path.normcase(name)
     pat = os.path.normcase(pat)
     return fnmatchcase(name, pat)
 
+
 def _compile_pattern(pat):
     cache = _cacheb if isinstance(pat, bytes) else _cache
     regex = cache.get(pat)
@@ -48,12 +56,14 @@
             res = bytes(res_str, 'ISO-8859-1')
         else:
             res = translate(pat)
+        if len(cache) >= _MAXCACHE:
+            cache.clear()
         cache[pat] = regex = re.compile(res)
     return regex.match
 
+
 def filter(names, pat):
-    """Return the subset of the list NAMES that match PAT"""
-    import os,posixpath
+    """Return the subset of the list NAMES that match PAT."""
     result = []
     pat = os.path.normcase(pat)
     match = _compile_pattern(pat)
@@ -68,16 +78,17 @@
                 result.append(name)
     return result
 
+
 def fnmatchcase(name, pat):
     """Test whether FILENAME matches PATTERN, including case.
 
     This is a version of fnmatch() which doesn't case-normalize
     its arguments.
     """
-
     match = _compile_pattern(pat)
     return match(name) is not None
 
+
 def translate(pat):
     """Translate a shell PATTERN to a regular expression.
 

Modified: python/branches/py3k-dtoa/Lib/functools.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/functools.py	(original)
+++ python/branches/py3k-dtoa/Lib/functools.py	Sun Aug  8 12:41:24 2010
@@ -4,15 +4,22 @@
 # to allow utilities written in Python to be added
 # to the functools module.
 # Written by Nick Coghlan <ncoghlan at gmail.com>
-#   Copyright (C) 2006 Python Software Foundation.
+# and Raymond Hettinger <python at rcn.com>
+#   Copyright (C) 2006-2010 Python Software Foundation.
 # See C source code for _functools credits/copyright
 
+__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
+           'total_ordering', 'cmp_to_key', 'lfu_cache', 'lru_cache']
+
 from _functools import partial, reduce
+from collections import OrderedDict, Counter
+from heapq import nsmallest
+from operator import itemgetter
 
 # update_wrapper() and wraps() are tools to help write
 # wrapper functions that can handle naive introspection
 
-WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
+WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__')
 WRAPPER_UPDATES = ('__dict__',)
 def update_wrapper(wrapper,
                    wrapped,
@@ -30,7 +37,8 @@
        function (defaults to functools.WRAPPER_UPDATES)
     """
     for attr in assigned:
-        setattr(wrapper, attr, getattr(wrapped, attr))
+        if hasattr(wrapped, attr):
+            setattr(wrapper, attr, getattr(wrapped, attr))
     for attr in updated:
         getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
     # Return the wrapper so this can be used as a decorator via partial()
@@ -97,3 +105,88 @@
         def __hash__(self):
             raise TypeError('hash not implemented')
     return K
+
+def lfu_cache(maxsize=100):
+    '''Least-frequently-used cache decorator.
+
+    Arguments to the cached function must be hashable.
+    Cache performance statistics stored in f.hits and f.misses.
+    Clear the cache using f.clear().
+    http://en.wikipedia.org/wiki/Cache_algorithms#Least-Frequently_Used
+
+    '''
+    def decorating_function(user_function):
+        cache = {}                      # mapping of args to results
+        use_count = Counter()           # times each key has been accessed
+        kwd_mark = object()             # separate positional and keyword args
+
+        @wraps(user_function)
+        def wrapper(*args, **kwds):
+            key = args
+            if kwds:
+                key += (kwd_mark,) + tuple(sorted(kwds.items()))
+            use_count[key] += 1         # count a use of this key
+            try:
+                result = cache[key]
+                wrapper.hits += 1
+            except KeyError:
+                result = user_function(*args, **kwds)
+                cache[key] = result
+                wrapper.misses += 1
+                if len(cache) > maxsize:
+                    # purge the 10% least frequently used entries
+                    for key, _ in nsmallest(maxsize // 10,
+                                            use_count.items(),
+                                            key=itemgetter(1)):
+                        del cache[key], use_count[key]
+            return result
+
+        def clear():
+            'Clear the cache and cache statistics'
+            cache.clear()
+            use_count.clear()
+            wrapper.hits = wrapper.misses = 0
+
+        wrapper.hits = wrapper.misses = 0
+        wrapper.clear = clear
+        return wrapper
+    return decorating_function
+
+def lru_cache(maxsize=100):
+    '''Least-recently-used cache decorator.
+
+    Arguments to the cached function must be hashable.
+    Cache performance statistics stored in f.hits and f.misses.
+    Clear the cache using f.clear().
+    http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
+
+    '''
+    def decorating_function(user_function):
+        cache = OrderedDict()           # ordered least recent to most recent
+        kwd_mark = object()             # separate positional and keyword args
+
+        @wraps(user_function)
+        def wrapper(*args, **kwds):
+            key = args
+            if kwds:
+                key += (kwd_mark,) + tuple(sorted(kwds.items()))
+            try:
+                result = cache.pop(key)
+                wrapper.hits += 1
+            except KeyError:
+                result = user_function(*args, **kwds)
+                wrapper.misses += 1
+                if len(cache) >= maxsize:
+                    cache.popitem(0)    # purge least recently used cache entry
+            cache[key] = result         # record recent use of this key
+            return result
+
+        def clear():
+            'Clear the cache and cache statistics'
+            cache.clear()
+            wrapper.hits = wrapper.misses = 0
+
+        wrapper.hits = wrapper.misses = 0
+        wrapper.clear = clear
+        return wrapper
+    return decorating_function

Modified: python/branches/py3k-dtoa/Lib/getopt.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/getopt.py	(original)
+++ python/branches/py3k-dtoa/Lib/getopt.py	Sun Aug  8 12:41:24 2010
@@ -156,7 +156,7 @@
             if not args:
                 raise GetoptError('option --%s requires argument' % opt, opt)
             optarg, args = args[0], args[1:]
-    elif optarg:
+    elif optarg is not None:
         raise GetoptError('option --%s must not have an argument' % opt, opt)
     opts.append(('--' + opt, optarg or ''))
     return opts, args

Modified: python/branches/py3k-dtoa/Lib/http/client.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/http/client.py	(original)
+++ python/branches/py3k-dtoa/Lib/http/client.py	Sun Aug  8 12:41:24 2010
@@ -602,7 +602,11 @@
     def getheader(self, name, default=None):
         if self.headers is None:
             raise ResponseNotReady()
-        return ', '.join(self.headers.get_all(name, default))
+        headers = self.headers.get_all(name) or default
+        if isinstance(headers, str) or not hasattr(headers, '__iter__'):
+            return headers
+        else:
+            return ', '.join(headers)
 
     def getheaders(self):
         """Return list of (header, value) tuples."""
@@ -734,11 +738,6 @@
             else:
                 raise NotConnected()
 
-        # send the data to the server. if we get a broken pipe, then close
-        # the socket. we want to reconnect when somebody tries to send again.
-        #
-        # NOTE: we DO propagate the error, though, because we cannot simply
-        #       ignore the error... the caller will know if they can retry.
         if self.debuglevel > 0:
             print("send:", repr(str))
         blocksize = 8192

Modified: python/branches/py3k-dtoa/Lib/http/cookiejar.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/http/cookiejar.py	(original)
+++ python/branches/py3k-dtoa/Lib/http/cookiejar.py	Sun Aug  8 12:41:24 2010
@@ -609,17 +609,14 @@
     return req_host, erhn
 
 def request_path(request):
-    """request-URI, as defined by RFC 2965."""
+    """Path component of request-URI, as defined by RFC 2965."""
     url = request.get_full_url()
-    path, parameters, query, frag = urllib.parse.urlparse(url)[2:]
-    if parameters:
-        path = "%s;%s" % (path, parameters)
-    path = escape_path(path)
-    req_path = urllib.parse.urlunparse(("", "", path, "", query, frag))
-    if not req_path.startswith("/"):
+    parts = urllib.parse.urlsplit(url)
+    path = escape_path(parts.path)
+    if not path.startswith("/"):
         # fix bad RFC 2396 absoluteURI
-        req_path = "/"+req_path
-    return req_path
+        path = "/" + path
+    return path
 
 def request_port(request):
     host = request.get_host()
@@ -1977,9 +1974,9 @@
     """
     magic_re = re.compile("#( Netscape)? HTTP Cookie File")
     header = """\
-    # Netscape HTTP Cookie File
-    # http://www.netscape.com/newsref/std/cookie_spec.html
-    # This is a generated file!  Do not edit.
+# Netscape HTTP Cookie File
+# http://www.netscape.com/newsref/std/cookie_spec.html
+# This is a generated file!  Do not edit.
 
 """
 

Modified: python/branches/py3k-dtoa/Lib/http/cookies.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/http/cookies.py	(original)
+++ python/branches/py3k-dtoa/Lib/http/cookies.py	Sun Aug  8 12:41:24 2010
@@ -46,7 +46,7 @@
 The Basics
 ----------
 
-Importing is easy..
+Importing is easy...
 
    >>> from http import cookies
 
@@ -127,19 +127,14 @@
    'Set-Cookie: number=7\r\nSet-Cookie: string=seven'
 
 Finis.
-"""  #"
-#     ^
-#     |----helps out font-lock
+"""
 
 #
 # Import our required modules
 #
+import re
 import string
 
-from pickle import dumps, loads
-
-import re, warnings
-
 __all__ = ["CookieError", "BaseCookie", "SimpleCookie"]
 
 _nulljoin = ''.join
@@ -235,7 +230,7 @@
     if all(c in LegalChars for c in str):
         return str
     else:
-        return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
+        return '"' + _nulljoin(map(_Translator.get, str, str)) + '"'
 
 
 _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")
@@ -244,7 +239,7 @@
 def _unquote(str):
     # If there aren't any doublequotes,
     # then there can't be any special characters.  See RFC 2109.
-    if  len(str) < 2:
+    if len(str) < 2:
         return str
     if str[0] != '"' or str[-1] != '"':
         return str
@@ -263,31 +258,32 @@
     n = len(str)
     res = []
     while 0 <= i < n:
-        Omatch = _OctalPatt.search(str, i)
-        Qmatch = _QuotePatt.search(str, i)
-        if not Omatch and not Qmatch:              # Neither matched
+        o_match = _OctalPatt.search(str, i)
+        q_match = _QuotePatt.search(str, i)
+        if not o_match and not q_match:              # Neither matched
             res.append(str[i:])
             break
         # else:
         j = k = -1
-        if Omatch: j = Omatch.start(0)
-        if Qmatch: k = Qmatch.start(0)
-        if Qmatch and ( not Omatch or k < j ):     # QuotePatt matched
+        if o_match:
+            j = o_match.start(0)
+        if q_match:
+            k = q_match.start(0)
+        if q_match and (not o_match or k < j):     # QuotePatt matched
             res.append(str[i:k])
             res.append(str[k+1])
-            i = k+2
+            i = k + 2
         else:                                      # OctalPatt matched
             res.append(str[i:j])
-            res.append( chr( int(str[j+1:j+4], 8) ) )
-            i = j+4
+            res.append(chr(int(str[j+1:j+4], 8)))
+            i = j + 4
     return _nulljoin(res)
 
-# The _getdate() routine is used to set the expiration time in
-# the cookie's HTTP header.      By default, _getdate() returns the
-# current time in the appropriate "expires" format for a
-# Set-Cookie header.     The one optional argument is an offset from
-# now, in seconds.      For example, an offset of -3600 means "one hour ago".
-# The offset may be a floating point number.
+# The _getdate() routine is used to set the expiration time in the cookie's HTTP
+# header.  By default, _getdate() returns the current time in the appropriate
+# "expires" format for a Set-Cookie header.  The one optional argument is an
+# offset from now, in seconds.  For example, an offset of -3600 means "one hour
+# ago".  The offset may be a floating point number.
 #
 
 _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
@@ -305,7 +301,7 @@
 
 
 class Morsel(dict):
-    """A class to hold ONE key,value pair.
+    """A class to hold ONE (key, value) pair.
 
     In a cookie, each such pair may have several attributes, so this class is
     used to keep the attributes associated with the appropriate key,value pair.
@@ -326,23 +322,24 @@
     # This dictionary provides a mapping from the lowercase
     # variant on the left to the appropriate traditional
     # formatting on the right.
-    _reserved = { "expires" : "expires",
-                   "path"        : "Path",
-                   "comment" : "Comment",
-                   "domain"      : "Domain",
-                   "max-age" : "Max-Age",
-                   "secure"      : "secure",
-                   "httponly"  : "httponly",
-                   "version" : "Version",
-                   }
+    _reserved = {
+        "expires"  : "expires",
+        "path"     : "Path",
+        "comment"  : "Comment",
+        "domain"   : "Domain",
+        "max-age"  : "Max-Age",
+        "secure"   : "secure",
+        "httponly" : "httponly",
+        "version"  : "Version",
+    }
 
     def __init__(self):
         # Set defaults
         self.key = self.value = self.coded_value = None
 
         # Set default attributes
-        for K in self._reserved:
-            dict.__setitem__(self, K, "")
+        for key in self._reserved:
+            dict.__setitem__(self, key, "")
 
     def __setitem__(self, K, V):
         K = K.lower()
@@ -362,18 +359,18 @@
             raise CookieError("Illegal key value: %s" % key)
 
         # It's a good key, so save it.
-        self.key                 = key
-        self.value               = val
-        self.coded_value         = coded_val
+        self.key = key
+        self.value = val
+        self.coded_value = coded_val
 
-    def output(self, attrs=None, header = "Set-Cookie:"):
-        return "%s %s" % ( header, self.OutputString(attrs) )
+    def output(self, attrs=None, header="Set-Cookie:"):
+        return "%s %s" % (header, self.OutputString(attrs))
 
     __str__ = output
 
     def __repr__(self):
         return '<%s: %s=%s>' % (self.__class__.__name__,
-                                self.key, repr(self.value) )
+                                self.key, repr(self.value))
 
     def js_output(self, attrs=None):
         # Print javascript
@@ -383,34 +380,36 @@
         document.cookie = \"%s\";
         // end hiding -->
         </script>
-        """ % ( self.OutputString(attrs).replace('"',r'\"'))
+        """ % (self.OutputString(attrs).replace('"', r'\"'))
 
     def OutputString(self, attrs=None):
         # Build up our result
         #
         result = []
-        RA = result.append
+        append = result.append
 
         # First, the key=value pair
-        RA("%s=%s" % (self.key, self.coded_value))
+        append("%s=%s" % (self.key, self.coded_value))
 
         # Now add any defined attributes
         if attrs is None:
             attrs = self._reserved
         items = sorted(self.items())
-        for K,V in items:
-            if V == "": continue
-            if K not in attrs: continue
-            if K == "expires" and type(V) == type(1):
-                RA("%s=%s" % (self._reserved[K], _getdate(V)))
-            elif K == "max-age" and type(V) == type(1):
-                RA("%s=%d" % (self._reserved[K], V))
-            elif K == "secure":
-                RA(str(self._reserved[K]))
-            elif K == "httponly":
-                RA(str(self._reserved[K]))
+        for key, value in items:
+            if value == "":
+                continue
+            if key not in attrs:
+                continue
+            if key == "expires" and isinstance(value, int):
+                append("%s=%s" % (self._reserved[key], _getdate(value)))
+            elif key == "max-age" and isinstance(value, int):
+                append("%s=%d" % (self._reserved[key], value))
+            elif key == "secure":
+                append(str(self._reserved[key]))
+            elif key == "httponly":
+                append(str(self._reserved[key]))
             else:
-                RA("%s=%s" % (self._reserved[K], V))
+                append("%s=%s" % (self._reserved[key], value))
 
         # Return the result
         return _semispacejoin(result)
@@ -426,24 +425,25 @@
 #
 
 _LegalCharsPatt  = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]"
-_CookiePattern = re.compile(
-    r"(?x)"                       # This is a Verbose pattern
-    r"(?P<key>"                   # Start of group 'key'
-    ""+ _LegalCharsPatt +"+?"     # Any word of at least one letter, nongreedy
-    r")"                          # End of group 'key'
-    r"\s*=\s*"                    # Equal Sign
-    r"(?P<val>"                   # Start of group 'val'
-    r'"(?:[^\\"]|\\.)*"'            # Any doublequoted string
-    r"|"                            # or
-    ""+ _LegalCharsPatt +"*"        # Any word or empty string
-    r")"                          # End of group 'val'
-    r"\s*;?"                      # Probably ending in a semi-colon
-    , re.ASCII)                   # May be removed if safe.
-
-
-# At long last, here is the cookie class.
-#   Using this class is almost just like using a dictionary.
-# See this module's docstring for example usage.
+_CookiePattern = re.compile(r"""
+    (?x)                           # This is a verbose pattern
+    (?P<key>                       # Start of group 'key'
+    """ + _LegalCharsPatt + r"""+?   # Any word of at least one letter
+    )                              # End of group 'key'
+    \s*=\s*                        # Equal Sign
+    (?P<val>                       # Start of group 'val'
+    "(?:[^\\"]|\\.)*"                # Any doublequoted string
+    |                                # or
+    \w{3},\s[\w\d-]{9,11}\s[\d:]{8}\sGMT  # Special case for "expires" attr
+    |                                # or
+    """ + _LegalCharsPatt + r"""*    # Any word or empty string
+    )                              # End of group 'val'
+    \s*;?                          # Probably ending in a semi-colon
+    """, re.ASCII)                 # May be removed if safe.
+
+
+# At long last, here is the cookie class.  Using this class is almost just like
+# using a dictionary.  See this module's docstring for example usage.
 #
 class BaseCookie(dict):
     """A container class for a set of Morsels."""
@@ -467,7 +467,8 @@
         return strval, strval
 
     def __init__(self, input=None):
-        if input: self.load(input)
+        if input:
+            self.load(input)
 
     def __set(self, key, real_value, coded_value):
         """Private method for setting a cookie's value"""
@@ -484,25 +485,25 @@
         """Return a string suitable for HTTP."""
         result = []
         items = sorted(self.items())
-        for K,V in items:
-            result.append( V.output(attrs, header) )
+        for key, value in items:
+            result.append(value.output(attrs, header))
         return sep.join(result)
 
     __str__ = output
 
     def __repr__(self):
-        L = []
+        l = []
         items = sorted(self.items())
-        for K,V in items:
-            L.append( '%s=%s' % (K,repr(V.value) ) )
-        return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))
+        for key, value in items:
+            l.append('%s=%s' % (key, repr(value.value)))
+        return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l))
 
     def js_output(self, attrs=None):
         """Return a string suitable for JavaScript."""
         result = []
         items = sorted(self.items())
-        for K,V in items:
-            result.append( V.js_output(attrs) )
+        for key, value in items:
+            result.append(value.js_output(attrs))
         return _nulljoin(result)
 
     def load(self, rawdata):
@@ -511,15 +512,15 @@
         is equivalent to calling:
             map(Cookie.__setitem__, d.keys(), d.values())
         """
-        if type(rawdata) == type(""):
-            self.__ParseString(rawdata)
+        if isinstance(rawdata, str):
+            self.__parse_string(rawdata)
         else:
             # self.update() wouldn't call our custom __setitem__
-            for k, v in rawdata.items():
-                self[k] = v
+            for key, value in rawdata.items():
+                self[key] = value
         return
 
-    def __ParseString(self, str, patt=_CookiePattern):
+    def __parse_string(self, str, patt=_CookiePattern):
         i = 0            # Our starting point
         n = len(str)     # Length of string
         M = None         # current morsel
@@ -527,25 +528,27 @@
         while 0 <= i < n:
             # Start looking for a cookie
             match = patt.search(str, i)
-            if not match: break          # No more cookies
+            if not match:
+                # No more cookies
+                break
 
-            K,V = match.group("key"), match.group("val")
+            key, value = match.group("key"), match.group("val")
             i = match.end(0)
 
             # Parse the key, value in case it's metainfo
-            if K[0] == "$":
+            if key[0] == "$":
                 # We ignore attributes which pertain to the cookie
                 # mechanism as a whole.  See RFC 2109.
                 # (Does anyone care?)
                 if M:
-                    M[ K[1:] ] = V
-            elif K.lower() in Morsel._reserved:
+                    M[key[1:]] = value
+            elif key.lower() in Morsel._reserved:
                 if M:
-                    M[ K ] = _unquote(V)
+                    M[key] = _unquote(value)
             else:
-                rval, cval = self.value_decode(V)
-                self.__set(K, rval, cval)
-                M = self[K]
+                rval, cval = self.value_decode(value)
+                self.__set(key, rval, cval)
+                M = self[key]
 
 
 class SimpleCookie(BaseCookie):
@@ -556,16 +559,8 @@
     received from HTTP are kept as strings.
     """
     def value_decode(self, val):
-        return _unquote( val ), val
+        return _unquote(val), val
+
     def value_encode(self, val):
         strval = str(val)
-        return strval, _quote( strval )
-
-###########################################################
-
-def _test():
-    import doctest, http.cookies
-    return doctest.testmod(http.cookies)
-
-if __name__ == "__main__":
-    _test()
+        return strval, _quote(strval)

Modified: python/branches/py3k-dtoa/Lib/http/server.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/http/server.py	(original)
+++ python/branches/py3k-dtoa/Lib/http/server.py	Sun Aug  8 12:41:24 2010
@@ -1023,8 +1023,9 @@
         if ua:
             env['HTTP_USER_AGENT'] = ua
         co = filter(None, self.headers.get_all('cookie', []))
-        if co:
-            env['HTTP_COOKIE'] = ', '.join(co)
+        cookie_str = ', '.join(co)
+        if cookie_str:
+            env['HTTP_COOKIE'] = cookie_str
         # XXX Other HTTP_* headers
         # Since we're setting the env in the parent, provide empty
         # values to override previously set values

Modified: python/branches/py3k-dtoa/Lib/idlelib/NEWS.txt
==============================================================================
--- python/branches/py3k-dtoa/Lib/idlelib/NEWS.txt	(original)
+++ python/branches/py3k-dtoa/Lib/idlelib/NEWS.txt	Sun Aug  8 12:41:24 2010
@@ -1,7 +1,7 @@
-What's New in IDLE 3.1b1?
+What's New in IDLE 3.1?
 =========================
 
-*Release date: XX-XXX-09*
+*Release date: 27-Jun-09*
 
 - Use of 'filter' in keybindingDialog.py was causing custom key assignment to
   fail.  Patch 5707 amaury.forgeotdarc.

Modified: python/branches/py3k-dtoa/Lib/idlelib/PyShell.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/idlelib/PyShell.py	(original)
+++ python/branches/py3k-dtoa/Lib/idlelib/PyShell.py	Sun Aug  8 12:41:24 2010
@@ -548,7 +548,7 @@
         This method is called from the subprocess, and by returning from this
         method we allow the subprocess to unblock.  After a bit the shell
         requests the subprocess to open the remote stack viewer which returns a
-        static object looking at the last exceptiopn.  It is queried through
+        static object looking at the last exception.  It is queried through
         the RPC mechanism.
 
         """

Modified: python/branches/py3k-dtoa/Lib/idlelib/idlever.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/idlelib/idlever.py	(original)
+++ python/branches/py3k-dtoa/Lib/idlelib/idlever.py	Sun Aug  8 12:41:24 2010
@@ -1 +1 @@
-IDLE_VERSION = "3.2a0"
+IDLE_VERSION = "3.2a1"

Modified: python/branches/py3k-dtoa/Lib/imaplib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/imaplib.py	(original)
+++ python/branches/py3k-dtoa/Lib/imaplib.py	Sun Aug  8 12:41:24 2010
@@ -765,7 +765,7 @@
                               ', '.join(Commands[command])))
         name = 'UID'
         typ, dat = self._simple_command(name, command, *args)
-        if command in ('SEARCH', 'SORT'):
+        if command in ('SEARCH', 'SORT', 'THREAD'):
             name = command
         else:
             name = 'FETCH'

Modified: python/branches/py3k-dtoa/Lib/importlib/test/benchmark.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/importlib/test/benchmark.py	(original)
+++ python/branches/py3k-dtoa/Lib/importlib/test/benchmark.py	Sun Aug  8 12:41:24 2010
@@ -1,13 +1,16 @@
-"""Benchmark some basic import use-cases."""
-# XXX
-#    - Bench from source (turn off bytecode generation)
-#    - Bench from bytecode (remove existence of source)
-#    - Bench bytecode generation
-#    - Bench extensions
+"""Benchmark some basic import use-cases.
+
+The assumption is made that this benchmark is run in a fresh interpreter and
+thus has no external changes made to import-related attributes in sys.
+
+"""
 from . import util
 from .source import util as source_util
+import decimal
 import imp
 import importlib
+import os
+import py_compile
 import sys
 import timeit
 
@@ -30,9 +33,9 @@
             # One execution too far
             if total_time > seconds:
                 count -= 1
-        yield count
+        yield count // seconds
 
-def from_cache(repeat):
+def from_cache(seconds, repeat):
     """sys.modules"""
     name = '<benchmark import>'
     module = imp.new_module(name)
@@ -40,31 +43,117 @@
     module.__package__ = ''
     with util.uncache(name):
         sys.modules[name] = module
-        for result in bench(name, repeat=repeat):
+        for result in bench(name, repeat=repeat, seconds=seconds):
             yield result
 
 
-def builtin_mod(repeat):
+def builtin_mod(seconds, repeat):
     """Built-in module"""
     name = 'errno'
     if name in sys.modules:
         del sys.modules[name]
-    for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat):
+    # Relying on built-in importer being implicit.
+    for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
+                        seconds=seconds):
+        yield result
+
+
+def source_wo_bytecode(seconds, repeat):
+    """Source w/o bytecode: simple"""
+    sys.dont_write_bytecode = True
+    try:
+        name = '__importlib_test_benchmark__'
+        # Clears out sys.modules and puts an entry at the front of sys.path.
+        with source_util.create_modules(name) as mapping:
+            assert not os.path.exists(imp.cache_from_source(mapping[name]))
+            for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
+                                seconds=seconds):
+                yield result
+    finally:
+        sys.dont_write_bytecode = False
+
+
+def decimal_wo_bytecode(seconds, repeat):
+    """Source w/o bytecode: decimal"""
+    name = 'decimal'
+    decimal_bytecode = imp.cache_from_source(decimal.__file__)
+    if os.path.exists(decimal_bytecode):
+        os.unlink(decimal_bytecode)
+    sys.dont_write_bytecode = True
+    try:
+        for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
+                            seconds=seconds):
+            yield result
+    finally:
+        sys.dont_write_bytecode = False
+
+
+def source_writing_bytecode(seconds, repeat):
+    """Source writing bytecode: simple"""
+    assert not sys.dont_write_bytecode
+    name = '__importlib_test_benchmark__'
+    with source_util.create_modules(name) as mapping:
+        def cleanup():
+            sys.modules.pop(name)
+            os.unlink(imp.cache_from_source(mapping[name]))
+        for result in bench(name, cleanup, repeat=repeat, seconds=seconds):
+            assert not os.path.exists(imp.cache_from_source(mapping[name]))
+            yield result
+
+
+def decimal_writing_bytecode(seconds, repeat):
+    """Source writing bytecode: decimal"""
+    assert not sys.dont_write_bytecode
+    name = 'decimal'
+    def cleanup():
+        sys.modules.pop(name)
+        os.unlink(imp.cache_from_source(decimal.__file__))
+    for result in bench(name, cleanup, repeat=repeat, seconds=seconds):
+        yield result
+
+
+def source_using_bytecode(seconds, repeat):
+    """Bytecode w/ source: simple"""
+    name = '__importlib_test_benchmark__'
+    with source_util.create_modules(name) as mapping:
+        py_compile.compile(mapping[name])
+        assert os.path.exists(imp.cache_from_source(mapping[name]))
+        for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
+                            seconds=seconds):
+            yield result
+
+
+def decimal_using_bytecode(seconds, repeat):
+    """Bytecode w/ source: decimal"""
+    name = 'decimal'
+    py_compile.compile(decimal.__file__)
+    for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
+                        seconds=seconds):
         yield result
 
 
-def main(import_, repeat=3):
+def main(import_):
     __builtins__.__import__ = import_
-    benchmarks = from_cache, builtin_mod
+    benchmarks = (from_cache, builtin_mod,
+                  source_using_bytecode, source_wo_bytecode,
+                  source_writing_bytecode,
+                  decimal_using_bytecode, decimal_writing_bytecode,
+                  decimal_wo_bytecode,)
+    seconds = 1
+    seconds_plural = 's' if seconds > 1 else ''
+    repeat = 3
+    header = "Measuring imports/second over {} second{}, best out of {}\n"
+    print(header.format(seconds, seconds_plural, repeat))
     for benchmark in benchmarks:
         print(benchmark.__doc__, "[", end=' ')
         sys.stdout.flush()
         results = []
-        for result in benchmark(repeat):
+        for result in benchmark(seconds=seconds, repeat=repeat):
             results.append(result)
             print(result, end=' ')
             sys.stdout.flush()
-        print("]", "best is", max(results))
+        assert not sys.dont_write_bytecode
+        print("]", "best is", format(max(results), ',d'))
 
 
 if __name__ == '__main__':
@@ -75,7 +164,7 @@
                         default=False, help="use the built-in __import__")
     options, args = parser.parse_args()
     if args:
-        raise RuntimeError("unrecognized args: {0}".format(args))
+        raise RuntimeError("unrecognized args: {}".format(args))
     import_ = __import__
     if not options.builtin:
         import_ = importlib.__import__

Modified: python/branches/py3k-dtoa/Lib/json/__init__.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/json/__init__.py	(original)
+++ python/branches/py3k-dtoa/Lib/json/__init__.py	Sun Aug  8 12:41:24 2010
@@ -125,14 +125,12 @@
     ``.write()``-supporting file-like object).
 
     If ``skipkeys`` is true then ``dict`` keys that are not basic types
-    (``str``, ``unicode``, ``int``, ``float``, ``bool``, ``None``) will be
-    skipped instead of raising a ``TypeError``.
+    (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
+    instead of raising a ``TypeError``.
 
-    If ``ensure_ascii`` is false, then the some chunks written to ``fp``
-    may be ``unicode`` instances, subject to normal Python ``str`` to
-    ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
-    understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
-    to cause an error.
+    If ``ensure_ascii`` is false, then the strings written to ``fp`` can
+    contain non-ASCII characters if they appear in strings contained in
+    ``obj``. Otherwise, all such characters are escaped in JSON strings.
 
     If ``check_circular`` is false, then the circular reference check
     for container types will be skipped and a circular reference will
@@ -185,12 +183,12 @@
     """Serialize ``obj`` to a JSON formatted ``str``.
 
     If ``skipkeys`` is false then ``dict`` keys that are not basic types
-    (``str``, ``unicode``, ``int``, ``float``, ``bool``, ``None``) will be
-    skipped instead of raising a ``TypeError``.
+    (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
+    instead of raising a ``TypeError``.
 
-    If ``ensure_ascii`` is false, then the return value will be a
-    ``unicode`` instance subject to normal Python ``str`` to ``unicode``
-    coercion rules instead of being escaped to an ASCII ``str``.
+    If ``ensure_ascii`` is false, then the return value can contain non-ASCII
+    characters if they appear in strings contained in ``obj``. Otherwise, all
+    such characters are escaped in JSON strings.
 
     If ``check_circular`` is false, then the circular reference check
     for container types will be skipped and a circular reference will

Modified: python/branches/py3k-dtoa/Lib/json/decoder.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/json/decoder.py	(original)
+++ python/branches/py3k-dtoa/Lib/json/decoder.py	Sun Aug  8 12:41:24 2010
@@ -263,9 +263,9 @@
     +---------------+-------------------+
     | array         | list              |
     +---------------+-------------------+
-    | string        | unicode           |
+    | string        | str               |
     +---------------+-------------------+
-    | number (int)  | int, long         |
+    | number (int)  | int               |
     +---------------+-------------------+
     | number (real) | float             |
     +---------------+-------------------+
@@ -318,8 +318,8 @@
 
 
     def decode(self, s, _w=WHITESPACE.match):
-        """Return the Python representation of ``s`` (a ``str`` or ``unicode``
-        instance containing a JSON document)
+        """Return the Python representation of ``s`` (a ``str`` instance
+        containing a JSON document).
 
         """
         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
@@ -329,8 +329,8 @@
         return obj
 
     def raw_decode(self, s, idx=0):
-        """Decode a JSON document from ``s`` (a ``str`` or ``unicode``
-        beginning with a JSON document) and return a 2-tuple of the Python
+        """Decode a JSON document from ``s`` (a ``str`` beginning with
+        a JSON document) and return a 2-tuple of the Python
         representation and the index in ``s`` where the document ended.
 
         This can be used to decode a JSON document from a string that may

Modified: python/branches/py3k-dtoa/Lib/json/encoder.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/json/encoder.py	(original)
+++ python/branches/py3k-dtoa/Lib/json/encoder.py	Sun Aug  8 12:41:24 2010
@@ -77,9 +77,9 @@
     +-------------------+---------------+
     | list, tuple       | array         |
     +-------------------+---------------+
-    | str, unicode      | string        |
+    | str               | string        |
     +-------------------+---------------+
-    | int, long, float  | number        |
+    | int, float        | number        |
     +-------------------+---------------+
     | True              | true          |
     +-------------------+---------------+
@@ -102,12 +102,12 @@
         """Constructor for JSONEncoder, with sensible defaults.
 
         If skipkeys is false, then it is a TypeError to attempt
-        encoding of keys that are not str, int, long, float or None.  If
+        encoding of keys that are not str, int, float or None.  If
         skipkeys is True, such items are simply skipped.
 
         If ensure_ascii is true, the output is guaranteed to be str
-        objects with all incoming unicode characters escaped.  If
-        ensure_ascii is false, the output will be unicode object.
+        objects with all incoming non-ASCII characters escaped.  If
+        ensure_ascii is false, the output can contain non-ASCII characters.
 
         If check_circular is true, then lists, dicts, and custom encoded
         objects will be checked for circular references during encoding to
@@ -397,7 +397,7 @@
             yield 'true'
         elif o is False:
             yield 'false'
-        elif isinstance(o, (int, int)):
+        elif isinstance(o, int):
             yield str(o)
         elif isinstance(o, float):
             yield _floatstr(o)

Modified: python/branches/py3k-dtoa/Lib/json/tests/test_fail.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/json/tests/test_fail.py	(original)
+++ python/branches/py3k-dtoa/Lib/json/tests/test_fail.py	Sun Aug  8 12:41:24 2010
@@ -74,3 +74,12 @@
                 pass
             else:
                 self.fail("Expected failure for fail{0}.json: {1!r}".format(idx, doc))
+
+    def test_non_string_keys_dict(self):
+        data = {'a' : 1, (1, 2) : 2}
+
+        #This is for c encoder
+        self.assertRaises(TypeError, json.dumps, data)
+
+        #This is for python encoder
+        self.assertRaises(TypeError, json.dumps, data, indent=True)

Modified: python/branches/py3k-dtoa/Lib/multiprocessing/connection.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/multiprocessing/connection.py	(original)
+++ python/branches/py3k-dtoa/Lib/multiprocessing/connection.py	Sun Aug  8 12:41:24 2010
@@ -173,7 +173,7 @@
 
 else:
 
-    from ._multiprocessing import win32
+    from _multiprocessing import win32
 
     def Pipe(duplex=True):
         '''

Modified: python/branches/py3k-dtoa/Lib/multiprocessing/forking.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/multiprocessing/forking.py	(original)
+++ python/branches/py3k-dtoa/Lib/multiprocessing/forking.py	Sun Aug  8 12:41:24 2010
@@ -157,7 +157,7 @@
     import time
 
     from pickle import dump, load, HIGHEST_PROTOCOL
-    from ._multiprocessing import win32, Connection, PipeConnection
+    from _multiprocessing import win32, Connection, PipeConnection
     from .util import Finalize
 
     def dump(obj, file, protocol=None):

Modified: python/branches/py3k-dtoa/Lib/multiprocessing/heap.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/multiprocessing/heap.py	(original)
+++ python/branches/py3k-dtoa/Lib/multiprocessing/heap.py	Sun Aug  8 12:41:24 2010
@@ -26,7 +26,7 @@
 
 if sys.platform == 'win32':
 
-    from ._multiprocessing import win32
+    from _multiprocessing import win32
 
     class Arena(object):
 

Modified: python/branches/py3k-dtoa/Lib/multiprocessing/reduction.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/multiprocessing/reduction.py	(original)
+++ python/branches/py3k-dtoa/Lib/multiprocessing/reduction.py	Sun Aug  8 12:41:24 2010
@@ -34,7 +34,7 @@
 
 if sys.platform == 'win32':
     import _subprocess
-    from ._multiprocessing import win32
+    from _multiprocessing import win32
 
     def send_handle(conn, handle, destination_pid):
         process_handle = win32.OpenProcess(

Modified: python/branches/py3k-dtoa/Lib/ntpath.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/ntpath.py	(original)
+++ python/branches/py3k-dtoa/Lib/ntpath.py	Sun Aug  8 12:41:24 2010
@@ -16,7 +16,8 @@
            "getatime","getctime", "islink","exists","lexists","isdir","isfile",
            "ismount", "expanduser","expandvars","normpath","abspath",
            "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
-           "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
+           "extsep","devnull","realpath","supports_unicode_filenames","relpath",
+           "samefile",]
 
 # strings representing various path-related bits and pieces
 # These are primarily for export; internally, they are hardcoded.
@@ -70,6 +71,12 @@
     else:
         return ':'
 
+def _get_special(path):
+    if isinstance(path, bytes):
+        return (b'\\\\.\\', b'\\\\?\\')
+    else:
+        return ('\\\\.\\', '\\\\?\\')
+
 # Normalize the case of a pathname and map slashes to backslashes.
 # Other normalizations (such as optimizing '../' away) are not done
 # (this is done by normpath).
@@ -274,7 +281,7 @@
     # set i to index beyond p's last slash
     i = len(p)
     while i and p[i-1] not in seps:
-        i = i - 1
+        i -= 1
     head, tail = p[:i], p[i:]  # now tail has no slashes
     # remove trailing slashes from head, unless it's all slashes
     head2 = head
@@ -309,16 +316,28 @@
     return split(p)[0]
 
 # Is a path a symbolic link?
-# This will always return false on systems where posix.lstat doesn't exist.
+# This will always return false on systems where os.lstat doesn't exist.
 
 def islink(path):
-    """Test for symbolic link.
-    On WindowsNT/95 and OS/2 always returns false
+    """Test whether a path is a symbolic link.
+    This will always return false for Windows prior to 6.0
+    and for OS/2.
     """
-    return False
-
-# alias exists to lexists
-lexists = exists
+    try:
+        st = os.lstat(path)
+    except (os.error, AttributeError):
+        return False
+    return stat.S_ISLNK(st.st_mode)
+
+# Being true for dangling symbolic links is also useful.
+
+def lexists(path):
+    """Test whether a path exists.  Returns True for broken symbolic links"""
+    try:
+        st = os.lstat(path)
+    except (os.error, WindowsError):
+        return False
+    return True
 
 # 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.
@@ -353,7 +372,7 @@
         return path
     i, n = 1, len(path)
     while i < n and path[i] not in _get_bothseps(path):
-        i = i + 1
+        i += 1
 
     if 'HOME' in os.environ:
         userhome = os.environ['HOME']
@@ -422,21 +441,21 @@
             pathlen = len(path)
             try:
                 index = path.index(c)
-                res = res + c + path[:index + 1]
+                res += c + path[:index + 1]
             except ValueError:
-                res = res + path
+                res += path
                 index = pathlen - 1
         elif c == percent:  # variable or '%'
             if path[index + 1:index + 2] == percent:
-                res = res + c
-                index = index + 1
+                res += c
+                index += 1
             else:
                 path = path[index+1:]
                 pathlen = len(path)
                 try:
                     index = path.index(percent)
                 except ValueError:
-                    res = res + percent + path
+                    res += percent + path
                     index = pathlen - 1
                 else:
                     var = path[:index]
@@ -448,11 +467,11 @@
                         value = '%' + var + '%'
                     if isinstance(path, bytes):
                         value = value.encode('ascii')
-                    res = res + value
+                    res += value
         elif c == dollar:  # variable or '$$'
             if path[index + 1:index + 2] == dollar:
-                res = res + c
-                index = index + 1
+                res += c
+                index += 1
             elif path[index + 1:index + 2] == brace:
                 path = path[index+2:]
                 pathlen = len(path)
@@ -470,23 +489,23 @@
                         value = '${' + var + '}'
                     if isinstance(path, bytes):
                         value = value.encode('ascii')
-                    res = res + value
+                    res += value
                 except ValueError:
                     if isinstance(path, bytes):
-                        res = res + b'${' + path
+                        res += b'${' + path
                     else:
-                        res = res + '${' + path
+                        res += '${' + path
                     index = pathlen - 1
             else:
                 var = ''
-                index = index + 1
+                index += 1
                 c = path[index:index + 1]
                 while c and c in varchars:
                     if isinstance(path, bytes):
-                        var = var + c.decode('ascii')
+                        var += c.decode('ascii')
                     else:
-                        var = var + c
-                    index = index + 1
+                        var += c
+                    index += 1
                     c = path[index:index + 1]
                 if var in os.environ:
                     value = os.environ[var]
@@ -494,12 +513,12 @@
                     value = '$' + var
                 if isinstance(path, bytes):
                     value = value.encode('ascii')
-                res = res + value
+                res += value
                 if c:
-                    index = index - 1
+                    index -= 1
         else:
-            res = res + c
-        index = index + 1
+            res += c
+        index += 1
     return res
 
 
@@ -511,12 +530,19 @@
     """Normalize path, eliminating double slashes, etc."""
     sep = _get_sep(path)
     dotdot = _get_dot(path) * 2
+    special_prefixes = _get_special(path)
+    if path.startswith(special_prefixes):
+        # in the case of paths with these prefixes:
+        # \\.\ -> device names
+        # \\?\ -> literal paths
+        # do not do any normalization, but return the path unchanged
+        return path
     path = path.replace(_get_altsep(path), sep)
     prefix, path = splitdrive(path)
 
     # collapse initial backslashes
     if path.startswith(sep):
-        prefix = prefix + sep
+        prefix += sep
         path = path.lstrip(sep)
 
     comps = path.split(sep)
@@ -612,3 +638,17 @@
     if not rel_list:
         return _get_dot(path)
     return join(*rel_list)
+
+
+# determine if two files are in fact the same file
+def samefile(f1, f2):
+    "Test whether two pathnames reference the same actual file"
+    try:
+        from nt import _getfinalpathname
+        return _getfinalpathname(f1) == _getfinalpathname(f2)
+    except (NotImplementedError, ImportError):
+        # On Windows XP and earlier, two files are the same if their
+        #  absolute pathnames are the same.
+        # Also, on other operating systems, fake this method with a
+        #  Windows-XP approximation.
+        return abspath(f1) == abspath(f2)

Modified: python/branches/py3k-dtoa/Lib/os.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/os.py	(original)
+++ python/branches/py3k-dtoa/Lib/os.py	Sun Aug  8 12:41:24 2010
@@ -446,7 +446,9 @@
         return len(self.data)
 
     def __repr__(self):
-        return 'environ({!r})'.format(self.data)
+        return 'environ({{{}}})'.format(', '.join(
+            ('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value))
+            for key, value in self.data.items())))
 
     def copy(self):
         return dict(self)
@@ -531,7 +533,8 @@
         The optional second argument can specify an alternate default.
         key, default and the result are bytes."""
         return environb.get(key, default)
-    __all__.append("getenvb")
+
+    __all__.extend(("environb", "getenvb"))
 
 def fsencode(value):
     """Encode value for use in the file system, environment variables

Deleted: python/branches/py3k-dtoa/Lib/pdb.doc
==============================================================================
--- python/branches/py3k-dtoa/Lib/pdb.doc	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,202 +0,0 @@
-The Python Debugger Pdb
-=======================
-
-To use the debugger in its simplest form:
-
-        >>> import pdb
-        >>> pdb.run('<a statement>')
-
-The debugger's prompt is '(Pdb) '.  This will stop in the first
-function call in <a statement>.
-
-Alternatively, if a statement terminated with an unhandled exception,
-you can use pdb's post-mortem facility to inspect the contents of the
-traceback:
-
-        >>> <a statement>
-        <exception traceback>
-        >>> import pdb
-        >>> pdb.pm()
-
-The commands recognized by the debugger are listed in the next
-section.  Most can be abbreviated as indicated; e.g., h(elp) means
-that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
-nor as 'H' or 'Help' or 'HELP').  Optional arguments are enclosed in
-square brackets.
-
-A blank line repeats the previous command literally, except for
-'list', where it lists the next 11 lines.
-
-Commands that the debugger doesn't recognize are assumed to be Python
-statements and are executed in the context of the program being
-debugged.  Python statements can also be prefixed with an exclamation
-point ('!').  This is a powerful way to inspect the program being
-debugged; it is even possible to change variables.  When an exception
-occurs in such a statement, the exception name is printed but the
-debugger's state is not changed.
-
-The debugger supports aliases, which can save typing.  And aliases can
-have parameters (see the alias help entry) which allows one a certain
-level of adaptability to the context under examination.
-
-Multiple commands may be entered on a single line, separated by the
-pair ';;'.  No intelligence is applied to separating the commands; the
-input is split at the first ';;', even if it is in the middle of a
-quoted string.
-
-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.
-
-Aside from aliases, the debugger is not directly programmable; but it
-is implemented as a class from which you can derive your own debugger
-class, which you can make as fancy as you like.
-
-
-Debugger commands
-=================
-
-h(elp)
-        Without argument, print the list of available commands.  With
-        a command name as argument, print help about that command
-        (this is currently not implemented).
-
-w(here)
-        Print a stack trace, with the most recent frame at the bottom.
-        An arrow indicates the "current frame", which determines the
-        context of most commands.
-
-d(own) [ count ]
-        Move the current frame count (default one) levels down in the
-        stack trace (to a newer frame).
-
-u(p) [ count ]
-        Move the current frame count (default one) levels up in the
-        stack trace (to an older frame).
-
-b(reak) [ ([filename:]lineno | function) [, condition] ]
-        With a filename:line number argument, set a break there.  If
-        filename is omitted, use the current file.  With a function
-        name, set a break at the first executable line of that
-        function.  Without argument, list all breaks.  Each breakpoint
-        is assigned a number to which all the other breakpoint
-        commands refer.
-
-        The condition argument, if present, is a string which must
-        evaluate to true in order for the breakpoint to be honored.
-
-tbreak [ ([filename:]lineno | function) [, condition] ]
-        Temporary breakpoint, which is removed automatically when it
-        is first hit.  The arguments are the same as break.
-
-cl(ear) [bpnumber [bpnumber ...] ]
-        With a space separated list of breakpoint numbers, clear those
-        breakpoints.  Without argument, clear all breaks (but first
-        ask confirmation).
-
-disable bpnumber [bpnumber ...]
-        Disables the breakpoints given as a space separated list of
-        breakpoint numbers.  Disabling a breakpoint means it cannot
-        cause the program to stop execution, but unlike clearing a
-        breakpoint, it remains in the list of breakpoints and can be
-        (re-)enabled.
-
-enable bpnumber [bpnumber ...]
-        Enables the breakpoints specified.
-
-ignore bpnumber count
-        Sets the ignore count for the given breakpoint number.  If
-        count is omitted, the ignore count is set to 0.  A breakpoint
-        becomes active when the ignore count is zero.  When non-zero,
-        the count is decremented each time the breakpoint is reached
-        and the breakpoint is not disabled and any associated
-        condition evaluates to true.
-
-condition bpnumber condition
-        condition is an expression which must evaluate to true before
-        the breakpoint is honored.  If condition is absent, any
-        existing condition is removed; i.e., the breakpoint is made
-        unconditional.
-
-s(tep)
-        Execute the current line, stop at the first possible occasion
-        (either in a function that is called or in the current function).
-
-n(ext)
-        Continue execution until the next line in the current function
-        is reached or it returns.
-
-unt(il)
-        Continue execution until the line with a number greater than the 
-        current one is reached or until the current frame returns.
-
-r(eturn)
-        Continue execution until the current function returns.
-
-run [args...]
-        Restart the debugged python program. If a string is supplied it is
-        splitted with "shlex", and the result is used as the new sys.argv.
-        History, breakpoints, actions and debugger options are preserved.
-        "restart" is an alias for "run".
-
-c(ont(inue))
-        Continue execution, only stop when a breakpoint is encountered.
-
-l(ist) [first [,last]]
-        List source code for the current file.
-        Without arguments, list 11 lines around the current line
-        or continue the previous listing.
-        With one argument, list 11 lines starting at that line.
-        With two arguments, list the given range;
-        if the second argument is less than the first, it is a count.
-
-a(rgs)
-        Print the argument list of the current function.
-
-p expression
-        Print the value of the expression.
-
-(!) statement
-        Execute the (one-line) statement in the context of the current
-        stack frame.  The exclamation point can be omitted unless the
-        first word of the statement resembles a debugger command.  To
-        assign to a global variable you must always prefix the command
-        with a 'global' command, e.g.:
-        (Pdb) global list_options; list_options = ['-l']
-        (Pdb)
-
-
-whatis arg
-         Prints the type of the argument.
-
-alias [name [command]]
-        Creates an alias called 'name' that executes 'command'.  The
-        command must *not* be enclosed in quotes.  Replaceable
-        parameters can be indicated by %1, %2, and so on, while %* is
-        replaced by all the parameters.  If no command is given, the
-        current alias for name is shown. If no name is given, all
-        aliases are listed.
-
-        Aliases may be nested and can contain anything that can be
-        legally typed at the pdb prompt.  Note!  You *can* override
-        internal pdb commands with aliases!  Those internal commands
-        are then hidden until the alias is removed.  Aliasing is
-        recursively applied to the first word of the command line; all
-        other words in the line are left alone.
-
-        As an example, here are two useful aliases (especially when
-        placed in the .pdbrc file):
-
-        #Print instance variables (usage "pi classInst")
-        alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
-        #Print instance variables in self
-        alias ps pi self
-                
-unalias name
-        Deletes the specified alias.
-
-q(uit)
-        Quit from the debugger.
-        The program being executed is aborted.

Modified: python/branches/py3k-dtoa/Lib/pdb.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/pdb.py	(original)
+++ python/branches/py3k-dtoa/Lib/pdb.py	Sun Aug  8 12:41:24 2010
@@ -1,30 +1,89 @@
 #! /usr/bin/env python3
 
-"""A Python debugger."""
-
-# (See pdb.doc for documentation.)
+"""
+The Python Debugger Pdb
+=======================
+
+To use the debugger in its simplest form:
+
+        >>> import pdb
+        >>> pdb.run('<a statement>')
+
+The debugger's prompt is '(Pdb) '.  This will stop in the first
+function call in <a statement>.
+
+Alternatively, if a statement terminated with an unhandled exception,
+you can use pdb's post-mortem facility to inspect the contents of the
+traceback:
+
+        >>> <a statement>
+        <exception traceback>
+        >>> import pdb
+        >>> pdb.pm()
+
+The commands recognized by the debugger are listed in the next
+section.  Most can be abbreviated as indicated; e.g., h(elp) means
+that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
+nor as 'H' or 'Help' or 'HELP').  Optional arguments are enclosed in
+square brackets.  Alternatives in the command syntax are separated
+by a vertical bar (|).
+
+A blank line repeats the previous command literally, except for
+'list', where it lists the next 11 lines.
+
+Commands that the debugger doesn't recognize are assumed to be Python
+statements and are executed in the context of the program being
+debugged.  Python statements can also be prefixed with an exclamation
+point ('!').  This is a powerful way to inspect the program being
+debugged; it is even possible to change variables or call functions.
+When an exception occurs in such a statement, the exception name is
+printed but the debugger's state is not changed.
+
+The debugger supports aliases, which can save typing.  And aliases can
+have parameters (see the alias help entry) which allows one a certain
+level of adaptability to the context under examination.
+
+Multiple commands may be entered on a single line, separated by the
+pair ';;'.  No intelligence is applied to separating the commands; the
+input is split at the first ';;', even if it is in the middle of a
+quoted string.
+
+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.
+
+Aside from aliases, the debugger is not directly programmable; but it
+is implemented as a class from which you can derive your own debugger
+class, which you can make as fancy as you like.
+
+
+Debugger commands
+=================
+
+"""
+# NOTE: the actual command documentation is collected from docstrings of the
+# commands and is appended to __doc__ after the class has been defined.
 
 import sys
 import linecache
 import cmd
 import bdb
-from reprlib import Repr
+import dis
 import os
 import re
+import code
 import pprint
 import traceback
+import inspect
+import types
 
 
 class Restart(Exception):
     """Causes a debugger to be restarted for the debugged python program."""
     pass
 
-# Create a custom safe Repr instance and increase its maxstring.
-# The default of 30 truncates error messages too easily.
-_repr = Repr()
-_repr.maxstring = 200
-_saferepr = _repr.repr
-
 __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
            "post_mortem", "help"]
 
@@ -48,6 +107,23 @@
     fp.close()
     return answer
 
+def getsourcelines(obj):
+    lines, lineno = inspect.findsource(obj)
+    if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
+        # must be a module frame: do not try to cut a block out of it
+        return lines, 1
+    elif inspect.ismodule(obj):
+        return lines, 1
+    return inspect.getblock(lines[lineno:]), lineno+1
+
+def lasti2lineno(code, lasti):
+    linestarts = list(dis.findlinestarts(code))
+    linestarts.reverse()
+    for i, lineno in linestarts:
+        if lasti >= i:
+            return lineno
+    return 0
+
 
 # Interaction prompt line will separate file and call info from code
 # text using value of line_prefix string.  A newline and arrow may
@@ -67,6 +143,7 @@
         self.aliases = {}
         self.mainpyfile = ''
         self._wait_for_mainpyfile = 0
+        self.tb_lineno = {}
         # Try to load readline if it exists
         try:
             import readline
@@ -113,28 +190,43 @@
         self.stack = []
         self.curindex = 0
         self.curframe = None
+        self.tb_lineno.clear()
 
-    def setup(self, f, t):
+    def setup(self, f, tb):
         self.forget()
-        self.stack, self.curindex = self.get_stack(f, t)
+        self.stack, self.curindex = self.get_stack(f, tb)
+        while tb:
+            # when setting up post-mortem debugging with a traceback, save all
+            # the original line numbers to be displayed along the current line
+            # numbers (which can be different, e.g. due to finally clauses)
+            lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
+            self.tb_lineno[tb.tb_frame] = lineno
+            tb = tb.tb_next
         self.curframe = self.stack[self.curindex][0]
         # The f_locals dictionary is updated from the actual frame
         # locals whenever the .f_locals accessor is called, so we
         # cache it here to ensure that modifications are not overwritten.
         self.curframe_locals = self.curframe.f_locals
-        self.execRcLines()
+        return self.execRcLines()
 
     # Can be executed earlier than 'setup' if desired
     def execRcLines(self):
-        if self.rcLines:
-            # Make local copy because of recursion
-            rcLines = self.rcLines
-            # executed only once
-            self.rcLines = []
-            for line in rcLines:
-                line = line[:-1]
-                if len(line) > 0 and line[0] != '#':
-                    self.onecmd(line)
+        if not self.rcLines:
+            return
+        # local copy because of recursion
+        rcLines = self.rcLines
+        rcLines.reverse()
+        # execute every line only once
+        self.rcLines = []
+        while rcLines:
+            line = rcLines.pop().strip()
+            if line and line[0] != '#':
+                if self.onecmd(line):
+                    # if onecmd returns True, the command wants to exit
+                    # from the interaction, save leftover rc lines
+                    # to execute before next interaction
+                    self.rcLines += reversed(rcLines)
+                    return True
 
     # Override Bdb methods
 
@@ -144,7 +236,7 @@
         if self._wait_for_mainpyfile:
             return
         if self.stop_here(frame):
-            print('--Call--', file=self.stdout)
+            self.message('--Call--')
             self.interaction(frame, None)
 
     def user_line(self, frame):
@@ -157,7 +249,7 @@
         if self.bp_commands(frame):
             self.interaction(frame, None)
 
-    def bp_commands(self,frame):
+    def bp_commands(self, frame):
         """Call every command that was set for the current active breakpoint
         (if there is one).
 
@@ -183,23 +275,31 @@
 
     def user_return(self, frame, return_value):
         """This function is called when a return trap is set here."""
+        if self._wait_for_mainpyfile:
+            return
         frame.f_locals['__return__'] = return_value
-        print('--Return--', file=self.stdout)
+        self.message('--Return--')
         self.interaction(frame, None)
 
     def user_exception(self, frame, exc_info):
         """This function is called if an exception occurs,
         but only if we are to stop at or just below this level."""
+        if self._wait_for_mainpyfile:
+            return
         exc_type, exc_value, exc_traceback = exc_info
         frame.f_locals['__exception__'] = exc_type, exc_value
-        exc_type_name = exc_type.__name__
-        print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
+        self.message(traceback.format_exception_only(exc_type,
+                                                     exc_value)[-1].strip())
         self.interaction(frame, exc_traceback)
 
     # General interaction function
 
     def interaction(self, frame, traceback):
-        self.setup(frame, traceback)
+        if self.setup(frame, traceback):
+            # no interaction desired at this time (happens if .pdbrc contains
+            # a command like "continue")
+            self.forget()
+            return
         self.print_stack_entry(self.stack[self.curindex])
         self.cmdloop()
         self.forget()
@@ -210,7 +310,7 @@
         """
         # reproduce the behavior of the standard displayhook, not printing None
         if obj is not None:
-            print(repr(obj))
+            self.message(repr(obj))
 
     def default(self, line):
         if line[:1] == '!': line = line[1:]
@@ -231,11 +331,8 @@
                 sys.stdin = save_stdin
                 sys.displayhook = save_displayhook
         except:
-            t, v = sys.exc_info()[:2]
-            if type(t) == type(''):
-                exc_type_name = t
-            else: exc_type_name = t.__name__
-            print('***', exc_type_name + ':', v, file=self.stdout)
+            exc_info = sys.exc_info()[:2]
+            self.error(traceback.format_exception_only(*exc_info)[-1].strip())
 
     def precmd(self, line):
         """Handle alias expansion and ';;' separator."""
@@ -274,9 +371,11 @@
         else:
             return self.handle_command_def(line)
 
-    def handle_command_def(self,line):
-        """ Handles one command line during command list definition. """
+    def handle_command_def(self, line):
+        """Handles one command line during command list definition."""
         cmd, arg, line = self.parseline(line)
+        if not cmd:
+            return
         if cmd == 'silent':
             self.commands_silent[self.commands_bnum] = True
             return # continue to handle other cmd def in the cmd list
@@ -284,7 +383,7 @@
             self.cmdqueue = []
             return 1 # end of cmd list
         cmdlist = self.commands[self.commands_bnum]
-        if (arg):
+        if arg:
             cmdlist.append(cmd+' '+arg)
         else:
             cmdlist.append(cmd)
@@ -300,45 +399,116 @@
             return 1
         return
 
+    # interface abstraction functions
+
+    def message(self, msg):
+        print(msg, file=self.stdout)
+
+    def error(self, msg):
+        print('***', msg, file=self.stdout)
+
     # Command definitions, called by cmdloop()
     # The argument is the remaining string on the command line
     # Return true to exit from the command loop
 
-    do_h = cmd.Cmd.do_help
-
     def do_commands(self, arg):
-        """Defines a list of commands associated to a breakpoint.
-
-        Those commands will be executed whenever the breakpoint causes
-        the program to stop execution."""
+        """commands [bpnumber]
+        (com) ...
+        (com) end
+        (Pdb)
+
+        Specify a list of commands for breakpoint number bpnumber.
+        The commands themselves are entered on the following lines.
+        Type a line containing just 'end' to terminate the commands.
+        The commands are executed when the breakpoint is hit.
+
+        To remove all commands from a breakpoint, type commands and
+        follow it immediately with end; that is, give no commands.
+
+        With no bpnumber argument, commands refers to the last
+        breakpoint set.
+
+        You can use breakpoint commands to start your program up
+        again.  Simply use the continue command, or step, or any other
+        command that resumes execution.
+
+        Specifying any command resuming execution (currently continue,
+        step, next, return, jump, quit and their abbreviations)
+        terminates the command list (as if that command was
+        immediately followed by end).  This is because any time you
+        resume execution (even with a simple next or step), you may
+        encounter another breakpoint -- which could have its own
+        command list, leading to ambiguities about which list to
+        execute.
+
+        If you use the 'silent' command in the command list, the usual
+        message about stopping at a breakpoint is not printed.  This
+        may be desirable for breakpoints that are to print a specific
+        message and then continue.  If none of the other commands
+        print anything, you will see no sign that the breakpoint was
+        reached.
+        """
         if not arg:
-            bnum = len(bdb.Breakpoint.bpbynumber)-1
+            bnum = len(bdb.Breakpoint.bpbynumber) - 1
         else:
             try:
                 bnum = int(arg)
             except:
-                print("Usage : commands [bnum]\n        ...\n        end",
-                      file=self.stdout)
+                self.error("Usage: commands [bnum]\n        ...\n        end")
                 return
         self.commands_bnum = bnum
+        # Save old definitions for the case of a keyboard interrupt.
+        if bnum in self.commands:
+            old_command_defs = (self.commands[bnum],
+                                self.commands_doprompt[bnum],
+                                self.commands_silent[bnum])
+        else:
+            old_command_defs = None
         self.commands[bnum] = []
         self.commands_doprompt[bnum] = True
         self.commands_silent[bnum] = False
+
         prompt_back = self.prompt
         self.prompt = '(com) '
         self.commands_defining = True
-        self.cmdloop()
-        self.commands_defining = False
-        self.prompt = prompt_back
+        try:
+            self.cmdloop()
+        except KeyboardInterrupt:
+            # Restore old definitions.
+            if old_command_defs:
+                self.commands[bnum] = old_command_defs[0]
+                self.commands_doprompt[bnum] = old_command_defs[1]
+                self.commands_silent[bnum] = old_command_defs[2]
+            else:
+                del self.commands[bnum]
+                del self.commands_doprompt[bnum]
+                del self.commands_silent[bnum]
+            self.error('command definition aborted, old commands restored')
+        finally:
+            self.commands_defining = False
+            self.prompt = prompt_back
 
     def do_break(self, arg, temporary = 0):
-        # break [ ([filename:]lineno | function) [, "condition"] ]
+        """b(reak) [ ([filename:]lineno | function) [, condition] ]
+        Without argument, list all breaks.
+
+        With a line number argument, set a break at this line in the
+        current file.  With a function name, set a break at the first
+        executable line of that function.  If a second argument is
+        present, it is a string specifying an expression which must
+        evaluate to true before the breakpoint is honored.
+
+        The line number may be prefixed with a filename and a colon,
+        to specify a breakpoint in another file (probably one that
+        hasn't been loaded yet).  The file is searched for on
+        sys.path; the .py suffix may be omitted.
+        """
         if not arg:
             if self.breaks:  # There's at least one
-                print("Num Type         Disp Enb   Where", file=self.stdout)
+                self.message("Num Type         Disp Enb   Where")
                 for bp in bdb.Breakpoint.bpbynumber:
                     if bp:
-                        bp.bpprint(self.stdout)
+                        self.message(bp.bpformat())
             return
         # parse arguments; comma has lowest precedence
         # and cannot occur in filename
@@ -357,8 +527,7 @@
             filename = arg[:colon].rstrip()
             f = self.lookupmodule(filename)
             if not f:
-                print('*** ', repr(filename), end=' ', file=self.stdout)
-                print('not found from sys.path', file=self.stdout)
+                self.error('%r not found from sys.path' % filename)
                 return
             else:
                 filename = f
@@ -366,7 +535,7 @@
             try:
                 lineno = int(arg)
             except ValueError as msg:
-                print('*** Bad lineno:', arg, file=self.stdout)
+                self.error('Bad lineno: %s' % arg)
                 return
         else:
             # no colon; can be lineno or function
@@ -392,10 +561,8 @@
                     # last thing to try
                     (ok, filename, ln) = self.lineinfo(arg)
                     if not ok:
-                        print('*** The specified object', end=' ', file=self.stdout)
-                        print(repr(arg), end=' ', file=self.stdout)
-                        print('is not a function', file=self.stdout)
-                        print('or was not found along sys.path.', file=self.stdout)
+                        self.error('The specified object %r is not a function '
+                                   'or was not found along sys.path.' % arg)
                         return
                     funcname = ok # ok contains a function name
                     lineno = int(ln)
@@ -406,12 +573,12 @@
         if line:
             # now set the break point
             err = self.set_break(filename, line, temporary, cond, funcname)
-            if err: print('***', err, file=self.stdout)
+            if err:
+                self.error(err, file=self.stdout)
             else:
                 bp = self.get_breaks(filename, line)[-1]
-                print("Breakpoint %d at %s:%d" % (bp.number,
-                                                                 bp.file,
-                                                                 bp.line), file=self.stdout)
+                self.message("Breakpoint %d at %s:%d" %
+                             (bp.number, bp.file, bp.line))
 
     # To be overridden in derived debuggers
     def defaultFile(self):
@@ -424,6 +591,10 @@
     do_b = do_break
 
     def do_tbreak(self, arg):
+        """tbreak [ ([filename:]lineno | function) [, condition] ]
+        Same arguments as break, but sets a temporary breakpoint: it
+        is automatically deleted when first hit.
+        """
         self.do_break(arg, 1)
 
     def lineinfo(self, identifier):
@@ -465,114 +636,115 @@
         Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
         line or EOF). Warning: testing is not comprehensive.
         """
-        line = linecache.getline(filename, lineno, self.curframe.f_globals)
+        # this method should be callable before starting debugging, so default
+        # to "no globals" if there is no current frame
+        globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
+        line = linecache.getline(filename, lineno, globs)
         if not line:
-            print('End of file', file=self.stdout)
+            self.message('End of file')
             return 0
         line = line.strip()
         # Don't allow setting breakpoint at a blank line
         if (not line or (line[0] == '#') or
              (line[:3] == '"""') or line[:3] == "'''"):
-            print('*** Blank or comment', file=self.stdout)
+            self.error('Blank or comment')
             return 0
         return lineno
 
     def do_enable(self, arg):
+        """enable bpnumber [bpnumber ...]
+        Enables the breakpoints given as a space separated list of
+        breakpoint numbers.
+        """
         args = arg.split()
         for i in args:
             try:
-                i = int(i)
-            except ValueError:
-                print('Breakpoint index %r is not a number' % i, file=self.stdout)
-                continue
-
-            if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
-                print('No breakpoint numbered', i, file=self.stdout)
-                continue
-
-            bp = bdb.Breakpoint.bpbynumber[i]
-            if bp:
+                bp = self.get_bpbynumber(i)
+            except ValueError as err:
+                self.error(err)
+            else:
                 bp.enable()
+                self.message('Enabled %s' % bp)
 
     def do_disable(self, arg):
+        """disable bpnumber [bpnumber ...]
+        Disables the breakpoints given as a space separated list of
+        breakpoint numbers.  Disabling a breakpoint means it cannot
+        cause the program to stop execution, but unlike clearing a
+        breakpoint, it remains in the list of breakpoints and can be
+        (re-)enabled.
+        """
         args = arg.split()
         for i in args:
             try:
-                i = int(i)
-            except ValueError:
-                print('Breakpoint index %r is not a number' % i, file=self.stdout)
-                continue
-
-            if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
-                print('No breakpoint numbered', i, file=self.stdout)
-                continue
-
-            bp = bdb.Breakpoint.bpbynumber[i]
-            if bp:
+                bp = self.get_bpbynumber(i)
+            except ValueError as err:
+                self.error(err)
+            else:
                 bp.disable()
+                self.message('Disabled %s' % bp)
 
     def do_condition(self, arg):
-        # arg is breakpoint number and condition
+        """condition bpnumber [condition]
+        Set a new condition for the breakpoint, an expression which
+        must evaluate to true before the breakpoint is honored.  If
+        condition is absent, any existing condition is removed; i.e.,
+        the breakpoint is made unconditional.
+        """
         args = arg.split(' ', 1)
         try:
-            bpnum = int(args[0].strip())
-        except ValueError:
-            # something went wrong
-            print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
-            return
-        try:
             cond = args[1]
-        except:
+        except IndexError:
             cond = None
         try:
-            bp = bdb.Breakpoint.bpbynumber[bpnum]
-        except IndexError:
-            print('Breakpoint index %r is not valid' % args[0],
-                  file=self.stdout)
-            return
-        if bp:
+            bp = self.get_bpbynumber(args[0].strip())
+        except ValueError as err:
+            self.error(err)
+        else:
             bp.cond = cond
             if not cond:
-                print('Breakpoint', bpnum, end=' ', file=self.stdout)
-                print('is now unconditional.', file=self.stdout)
+                self.message('Breakpoint %d is now unconditional.' % bp.number)
+            else:
+                self.message('New condition set for breakpoint %d.' % bp.number)
 
-    def do_ignore(self,arg):
-        """arg is bp number followed by ignore count."""
+    def do_ignore(self, arg):
+        """ignore bpnumber [count]
+        Set the ignore count for the given breakpoint number.  If
+        count is omitted, the ignore count is set to 0.  A breakpoint
+        becomes active when the ignore count is zero.  When non-zero,
+        the count is decremented each time the breakpoint is reached
+        and the breakpoint is not disabled and any associated
+        condition evaluates to true.
+        """
         args = arg.split()
         try:
-            bpnum = int(args[0].strip())
-        except ValueError:
-            # something went wrong
-            print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
-            return
-        try:
             count = int(args[1].strip())
         except:
             count = 0
         try:
-            bp = bdb.Breakpoint.bpbynumber[bpnum]
-        except IndexError:
-            print('Breakpoint index %r is not valid' % args[0],
-                  file=self.stdout)
-            return
-        if bp:
+            bp = self.get_bpbynumber(args[0].strip())
+        except ValueError as err:
+            self.error(err)
+        else:
             bp.ignore = count
             if count > 0:
-                reply = 'Will ignore next '
                 if count > 1:
-                    reply = reply + '%d crossings' % count
+                    countstr = '%d crossings' % count
                 else:
-                    reply = reply + '1 crossing'
-                print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
+                    countstr = '1 crossing'
+                self.message('Will ignore next %s of breakpoint %d.' %
+                             (countstr, bp.number))
             else:
-                print('Will stop next time breakpoint', end=' ', file=self.stdout)
-                print(bpnum, 'is reached.', file=self.stdout)
+                self.message('Will stop next time breakpoint %d is reached.'
+                             % bp.number)
 
     def do_clear(self, arg):
-        """Three possibilities, tried in this order:
-        clear -> clear all breaks, ask for confirmation
-        clear file:lineno -> clear all breaks at file:lineno
-        clear bpno bpno ... -> clear breakpoints by number"""
+        """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]]
+        With a space separated list of breakpoint numbers, clear
+        those breakpoints.  Without argument, clear all breaks (but
+        first ask confirmation).  With a filename:lineno argument,
+        clear all breaks at that line in that file.
+        """
         if not arg:
             try:
                 reply = input('Clear all breaks? ')
@@ -580,7 +752,10 @@
                 reply = 'no'
             reply = reply.strip().lower()
             if reply in ('y', 'yes'):
+                bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp]
                 self.clear_all_breaks()
+                for bp in bplist:
+                    self.message('Deleted %s' % bp)
             return
         if ':' in arg:
             # Make sure it works for "clear C:\foo\bar.py:12"
@@ -592,28 +767,31 @@
             except ValueError:
                 err = "Invalid line number (%s)" % arg
             else:
+                bplist = self.get_breaks(filename, lineno)
                 err = self.clear_break(filename, lineno)
-            if err: print('***', err, file=self.stdout)
+            if err:
+                self.error(err)
+            else:
+                for bp in bplist:
+                    self.message('Deleted %s' % bp)
             return
         numberlist = arg.split()
         for i in numberlist:
             try:
-                i = int(i)
-            except ValueError:
-                print('Breakpoint index %r is not a number' % i, file=self.stdout)
-                continue
-
-            if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
-                print('No breakpoint numbered', i, file=self.stdout)
-                continue
-            err = self.clear_bpbynumber(i)
-            if err:
-                print('***', err, file=self.stdout)
+                bp = self.get_bpbynumber(i)
+            except ValueError as err:
+                self.error(err)
             else:
-                print('Deleted breakpoint', i, file=self.stdout)
+                self.clear_break(bp.file, bp.line)
+                self.message('Deleted %s' % bp)
     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
 
     def do_where(self, arg):
+        """w(here)
+        Print a stack trace, with the most recent frame at the bottom.
+        An arrow indicates the "current frame", which determines the
+        context of most commands.  'bt' is an alias for this command.
+        """
         self.print_stack_trace()
     do_w = do_where
     do_bt = do_where
@@ -627,13 +805,17 @@
         self.lineno = None
 
     def do_up(self, arg):
+        """u(p) [count]
+        Move the current frame count (default one) levels up in the
+        stack trace (to an older frame).
+        """
         if self.curindex == 0:
-            print('*** Oldest frame', file=self.stdout)
+            self.error('Oldest frame')
             return
         try:
             count = int(arg or 1)
         except ValueError:
-            print('*** Invalid frame count (%s)' % arg, file=self.stdout)
+            self.error('Invalid frame count (%s)' % arg)
             return
         if count < 0:
             newframe = 0
@@ -643,13 +825,17 @@
     do_u = do_up
 
     def do_down(self, arg):
+        """d(own) [count]
+        Move the current frame count (default one) levels down in the
+        stack trace (to a newer frame).
+        """
         if self.curindex + 1 == len(self.stack):
-            print('*** Newest frame', file=self.stdout)
+            self.error('Newest frame')
             return
         try:
             count = int(arg or 1)
         except ValueError:
-            print('*** Invalid frame count (%s)' % arg, file=self.stdout)
+            self.error('Invalid frame count (%s)' % arg)
             return
         if count < 0:
             newframe = len(self.stack) - 1
@@ -659,50 +845,99 @@
     do_d = do_down
 
     def do_until(self, arg):
-        self.set_until(self.curframe)
+        """unt(il) [lineno]
+        Without argument, continue execution until the line with a
+        number greater than the current one is reached.  With a line
+        number, continue execution until a line with a number greater
+        or equal to that is reached.  In both cases, also stop when
+        the current frame returns.
+        """
+        if arg:
+            try:
+                lineno = int(arg)
+            except ValueError:
+                self.error('Error in argument: %r' % arg)
+                return
+            if lineno <= self.curframe.f_lineno:
+                self.error('"until" line number is smaller than current '
+                           'line number')
+                return
+        else:
+            lineno = None
+        self.set_until(self.curframe, lineno)
         return 1
     do_unt = do_until
 
     def do_step(self, arg):
+        """s(tep)
+        Execute the current line, stop at the first possible occasion
+        (either in a function that is called or in the current
+        function).
+        """
         self.set_step()
         return 1
     do_s = do_step
 
     def do_next(self, arg):
+        """n(ext)
+        Continue execution until the next line in the current function
+        is reached or it returns.
+        """
         self.set_next(self.curframe)
         return 1
     do_n = do_next
 
     def do_run(self, arg):
-        """Restart program by raising an exception to be caught in the main
-        debugger loop.  If arguments were given, set them in sys.argv."""
+        """run [args...]
+        Restart the debugged python program. If a string is supplied
+        it is splitted with "shlex", and the result is used as the new
+        sys.argv.  History, breakpoints, actions and debugger options
+        are preserved.  "restart" is an alias for "run".
+        """
         if arg:
             import shlex
             argv0 = sys.argv[0:1]
             sys.argv = shlex.split(arg)
             sys.argv[:0] = argv0
+        # this is caught in the main debugger loop
         raise Restart
 
     do_restart = do_run
 
     def do_return(self, arg):
+        """r(eturn)
+        Continue execution until the current function returns.
+        """
         self.set_return(self.curframe)
         return 1
     do_r = do_return
 
     def do_continue(self, arg):
+        """c(ont(inue))
+        Continue execution, only stop when a breakpoint is encountered.
+        """
         self.set_continue()
         return 1
     do_c = do_cont = do_continue
 
     def do_jump(self, arg):
+        """j(ump) lineno
+        Set the next line that will be executed.  Only available in
+        the bottom-most frame.  This lets you jump back and execute
+        code again, or jump forward to skip code that you don't want
+        to run.
+
+        It should be noted that not all jumps are allowed -- for
+        instance it is not possible to jump into the middle of a
+        for loop or out of a finally clause.
+        """
         if self.curindex + 1 != len(self.stack):
-            print("*** You can only jump within the bottom frame", file=self.stdout)
+            self.error('You can only jump within the bottom frame')
             return
         try:
             arg = int(arg)
         except ValueError:
-            print("*** The 'jump' command requires a line number.", file=self.stdout)
+            self.error("The 'jump' command requires a line number")
         else:
             try:
                 # Do the jump, fix up our copy of the stack, and display the
@@ -711,22 +946,30 @@
                 self.stack[self.curindex] = self.stack[self.curindex][0], arg
                 self.print_stack_entry(self.stack[self.curindex])
             except ValueError as e:
-                print('*** Jump failed:', e, file=self.stdout)
+                self.error('Jump failed: %s' % e)
     do_j = do_jump
 
     def do_debug(self, arg):
+        """debug code
+        Enter a recursive debugger that steps through the code
+        argument (which is an arbitrary expression or statement to be
+        executed in the current environment).
+        """
         sys.settrace(None)
         globals = self.curframe.f_globals
         locals = self.curframe_locals
         p = Pdb(self.completekey, self.stdin, self.stdout)
         p.prompt = "(%s) " % self.prompt.strip()
-        print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
+        self.message("ENTERING RECURSIVE DEBUGGER")
         sys.call_tracing(p.run, (arg, globals, locals))
-        print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
+        self.message("LEAVING RECURSIVE DEBUGGER")
         sys.settrace(self.trace_dispatch)
         self.lastcmd = p.lastcmd
 
     def do_quit(self, arg):
+        """q(uit)\nexit
+        Quit from the debugger. The program being executed is aborted.
+        """
         self._user_requested_quit = 1
         self.set_quit()
         return 1
@@ -735,12 +978,18 @@
     do_exit = do_quit
 
     def do_EOF(self, arg):
-        print(file=self.stdout)
+        """EOF
+        Handles the receipt of EOF as a command.
+        """
+        self.message('')
         self._user_requested_quit = 1
         self.set_quit()
         return 1
 
     def do_args(self, arg):
+        """a(rgs)
+        Print the argument list of the current function.
+        """
         co = self.curframe.f_code
         dict = self.curframe_locals
         n = co.co_argcount
@@ -748,62 +997,83 @@
         if co.co_flags & 8: n = n+1
         for i in range(n):
             name = co.co_varnames[i]
-            print(name, '=', end=' ', file=self.stdout)
-            if name in dict: print(dict[name], file=self.stdout)
-            else: print("*** undefined ***", file=self.stdout)
+            if name in dict:
+                self.message('%s = %r' % (name, dict[name]))
+            else:
+                self.message('%s = *** undefined ***' % (name,))
     do_a = do_args
 
     def do_retval(self, arg):
+        """retval
+        Print the return value for the last return of a function.
+        """
         if '__return__' in self.curframe_locals:
-            print(self.curframe_locals['__return__'], file=self.stdout)
+            self.message(repr(self.curframe_locals['__return__']))
         else:
-            print('*** Not yet returned!', file=self.stdout)
+            self.error('Not yet returned!')
     do_rv = do_retval
 
     def _getval(self, arg):
         try:
             return eval(arg, self.curframe.f_globals, self.curframe_locals)
         except:
-            t, v = sys.exc_info()[:2]
-            if isinstance(t, str):
-                exc_type_name = t
-            else: exc_type_name = t.__name__
-            print('***', exc_type_name + ':', repr(v), file=self.stdout)
+            exc_info = sys.exc_info()[:2]
+            self.error(traceback.format_exception_only(*exc_info)[-1].strip())
             raise
 
     def do_p(self, arg):
+        """p(rint) expression
+        Print the value of the expression.
+        """
         try:
-            print(repr(self._getval(arg)), file=self.stdout)
+            self.message(repr(self._getval(arg)))
         except:
             pass
     # make "print" an alias of "p" since print isn't a Python statement anymore
     do_print = do_p
 
     def do_pp(self, arg):
+        """pp expression
+        Pretty-print the value of the expression.
+        """
         try:
-            pprint.pprint(self._getval(arg), self.stdout)
+            self.message(pprint.pformat(self._getval(arg)))
         except:
             pass
 
     def do_list(self, arg):
+        """l(ist) [first [,last] | .]
+
+        List source code for the current file.  Without arguments,
+        list 11 lines around the current line or continue the previous
+        listing.  With . as argument, list 11 lines around the current
+        line.  With one argument, list 11 lines starting at that line.
+        With two arguments, list the given range; if the second
+        argument is less than the first, it is a count.
+
+        The current line in the current frame is indicated by "->".
+        If an exception is being debugged, the line where the
+        exception was originally raised or propagated is indicated by
+        ">>", if it differs from the current line.
+        """
         self.lastcmd = 'list'
         last = None
-        if arg:
+        if arg and arg != '.':
             try:
-                x = eval(arg, {}, {})
-                if type(x) == type(()):
-                    first, last = x
-                    first = int(first)
-                    last = int(last)
+                if ',' in arg:
+                    first, last = arg.split(',')
+                    first = int(first.strip())
+                    last = int(last.strip())
                     if last < first:
-                        # Assume it's a count
+                        # assume it's a count
                         last = first + last
                 else:
-                    first = max(1, int(x) - 5)
-            except:
-                print('*** Error in argument:', repr(arg), file=self.stdout)
+                    first = int(arg.strip())
+                    first = max(1, first - 5)
+            except ValueError:
+                self.error('Error in argument: %r' % arg)
                 return
-        elif self.lineno is None:
+        elif self.lineno is None or arg == '.':
             first = max(1, self.curframe.f_lineno - 5)
         else:
             first = self.lineno + 1
@@ -812,71 +1082,144 @@
         filename = self.curframe.f_code.co_filename
         breaklist = self.get_file_breaks(filename)
         try:
-            for lineno in range(first, last+1):
-                line = linecache.getline(filename, lineno,
-                                         self.curframe.f_globals)
-                if not line:
-                    print('[EOF]', file=self.stdout)
-                    break
-                else:
-                    s = repr(lineno).rjust(3)
-                    if len(s) < 4: s = s + ' '
-                    if lineno in breaklist: s = s + 'B'
-                    else: s = s + ' '
-                    if lineno == self.curframe.f_lineno:
-                        s = s + '->'
-                    print(s + '\t' + line, end='', file=self.stdout)
-                    self.lineno = lineno
+            lines = linecache.getlines(filename, self.curframe.f_globals)
+            self._print_lines(lines[first-1:last], first, breaklist,
+                              self.curframe)
+            self.lineno = min(last, len(lines))
+            if len(lines) < last:
+                self.message('[EOF]')
         except KeyboardInterrupt:
             pass
     do_l = do_list
 
+    def do_longlist(self, arg):
+        """longlist | ll
+        List the whole source code for the current function or frame.
+        """
+        filename = self.curframe.f_code.co_filename
+        breaklist = self.get_file_breaks(filename)
+        try:
+            lines, lineno = getsourcelines(self.curframe)
+        except IOError as err:
+            self.error(err)
+            return
+        self._print_lines(lines, lineno, breaklist, self.curframe)
+    do_ll = do_longlist
+
+    def do_source(self, arg):
+        """source expression
+        Try to get source code for the given object and display it.
+        """
+        try:
+            obj = self._getval(arg)
+        except:
+            return
+        try:
+            lines, lineno = getsourcelines(obj)
+        except (IOError, TypeError) as err:
+            self.error(err)
+            return
+        self._print_lines(lines, lineno)
+
+    def _print_lines(self, lines, start, breaks=(), frame=None):
+        """Print a range of lines."""
+        if frame:
+            current_lineno = frame.f_lineno
+            exc_lineno = self.tb_lineno.get(frame, -1)
+        else:
+            current_lineno = exc_lineno = -1
+        for lineno, line in enumerate(lines, start):
+            s = str(lineno).rjust(3)
+            if len(s) < 4:
+                s += ' '
+            if lineno in breaks:
+                s += 'B'
+            else:
+                s += ' '
+            if lineno == current_lineno:
+                s += '->'
+            elif lineno == exc_lineno:
+                s += '>>'
+            self.message(s + '\t' + line.rstrip())
+
     def do_whatis(self, arg):
+        """whatis arg
+        Print the type of the argument.
+        """
         try:
-            value = eval(arg, self.curframe.f_globals,
-                            self.curframe_locals)
+            value = self._getval(arg)
         except:
-            t, v = sys.exc_info()[:2]
-            if type(t) == type(''):
-                exc_type_name = t
-            else: exc_type_name = t.__name__
-            print('***', exc_type_name + ':', repr(v), file=self.stdout)
+            # _getval() already printed the error
             return
         code = None
         # Is it a function?
-        try: code = value.__code__
-        except: pass
+        try:
+            code = value.__code__
+        except Exception:
+            pass
         if code:
-            print('Function', code.co_name, file=self.stdout)
+            self.message('Function %s' % code.co_name)
             return
         # Is it an instance method?
-        try: code = value.__func__.__code__
-        except: pass
+        try:
+            code = value.__func__.__code__
+        except Exception:
+            pass
         if code:
-            print('Method', code.co_name, file=self.stdout)
+            self.message('Method %s' % code.co_name)
+            return
+        # Is it a class?
+        if value.__class__ is type:
+            self.message('Class %s.%s' % (value.__module__, value.__name__))
             return
         # None of the above...
-        print(type(value), file=self.stdout)
+        self.message(type(value))
 
     def do_alias(self, arg):
+        """alias [name [command [parameter parameter ...] ]]
+        Create an alias called 'name' that executes 'command'.  The
+        command must *not* be enclosed in quotes.  Replaceable
+        parameters can be indicated by %1, %2, and so on, while %* is
+        replaced by all the parameters.  If no command is given, the
+        current alias for name is shown. If no name is given, all
+        aliases are listed.
+
+        Aliases may be nested and can contain anything that can be
+        legally typed at the pdb prompt.  Note!  You *can* override
+        internal pdb commands with aliases!  Those internal commands
+        are then hidden until the alias is removed.  Aliasing is
+        recursively applied to the first word of the command line; all
+        other words in the line are left alone.
+
+        As an example, here are two useful aliases (especially when
+        placed in the .pdbrc file):
+
+        # Print instance variables (usage "pi classInst")
+        alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
+        # Print instance variables in self
+        alias ps pi self
+        """
         args = arg.split()
         if len(args) == 0:
             keys = sorted(self.aliases.keys())
             for alias in keys:
-                print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
+                self.message("%s = %s" % (alias, self.aliases[alias]))
             return
         if args[0] in self.aliases and len(args) == 1:
-            print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
+            self.message("%s = %s" % (args[0], self.aliases[args[0]]))
         else:
             self.aliases[args[0]] = ' '.join(args[1:])
 
     def do_unalias(self, arg):
+        """unalias name
+        Delete the specified alias.
+        """
         args = arg.split()
         if len(args) == 0: return
         if args[0] in self.aliases:
             del self.aliases[args[0]]
 
-    #list of all the commands making the program resume execution.
+    # List of all the commands making the program resume execution.
     commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return',
                          'do_quit', 'do_jump']
 
@@ -898,292 +1241,53 @@
     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
         frame, lineno = frame_lineno
         if frame is self.curframe:
-            print('>', end=' ', file=self.stdout)
+            prefix = '> '
+        else:
+            prefix = '  '
+        self.message(prefix +
+                     self.format_stack_entry(frame_lineno, prompt_prefix))
+
+    # Provide help
+
+    def do_help(self, arg):
+        """h(elp)
+        Without argument, print the list of available commands.
+        With a command name as argument, print help about that command.
+        "help pdb" shows the full pdb documentation.
+        "help exec" gives help on the ! command.
+        """
+        if not arg:
+            return cmd.Cmd.do_help(self, arg)
+        try:
+            try:
+                topic = getattr(self, 'help_' + arg)
+                return topic()
+            except AttributeError:
+                command = getattr(self, 'do_' + arg)
+        except AttributeError:
+            self.error('No help for %r' % arg)
         else:
-            print(' ', end=' ', file=self.stdout)
-        print(self.format_stack_entry(frame_lineno,
-                                                     prompt_prefix), file=self.stdout)
-
-
-    # Help methods (derived from pdb.doc)
-
-    def help_help(self):
-        self.help_h()
-
-    def help_h(self):
-        print("""h(elp)
-Without argument, print the list of available commands.
-With a command name as argument, print help about that command
-"help pdb" pipes the full documentation file to the $PAGER
-"help exec" gives help on the ! command""", file=self.stdout)
-
-    def help_where(self):
-        self.help_w()
-
-    def help_w(self):
-        print("""w(here)
-Print a stack trace, with the most recent frame at the bottom.
-An arrow indicates the "current frame", which determines the
-context of most commands.  'bt' is an alias for this command.""", file=self.stdout)
-
-    help_bt = help_w
-
-    def help_down(self):
-        self.help_d()
-
-    def help_d(self):
-        print("""d(own)
-Move the current frame one level down in the stack trace
-(to a newer frame).""", file=self.stdout)
-
-    def help_up(self):
-        self.help_u()
-
-    def help_u(self):
-        print("""u(p)
-Move the current frame one level up in the stack trace
-(to an older frame).""", file=self.stdout)
-
-    def help_break(self):
-        self.help_b()
-
-    def help_b(self):
-        print("""b(reak) ([file:]lineno | function) [, condition]
-With a line number argument, set a break there in the current
-file.  With a function name, set a break at first executable line
-of that function.  Without argument, list all breaks.  If a second
-argument is present, it is a string specifying an expression
-which must evaluate to true before the breakpoint is honored.
-
-The line number may be prefixed with a filename and a colon,
-to specify a breakpoint in another file (probably one that
-hasn't been loaded yet).  The file is searched for on sys.path;
-the .py suffix may be omitted.""", file=self.stdout)
-
-    def help_clear(self):
-        self.help_cl()
-
-    def help_cl(self):
-        print("cl(ear) filename:lineno", file=self.stdout)
-        print("""cl(ear) [bpnumber [bpnumber...]]
-With a space separated list of breakpoint numbers, clear
-those breakpoints.  Without argument, clear all breaks (but
-first ask confirmation).  With a filename:lineno argument,
-clear all breaks at that line in that file.""", file=self.stdout)
-
-    def help_tbreak(self):
-        print("""tbreak  same arguments as break, but breakpoint is
-removed when first hit.""", file=self.stdout)
-
-    def help_enable(self):
-        print("""enable bpnumber [bpnumber ...]
-Enables the breakpoints given as a space separated list of
-bp numbers.""", file=self.stdout)
-
-    def help_disable(self):
-        print("""disable bpnumber [bpnumber ...]
-Disables the breakpoints given as a space separated list of
-bp numbers.""", file=self.stdout)
-
-    def help_ignore(self):
-        print("""ignore bpnumber count
-Sets the ignore count for the given breakpoint number.  A breakpoint
-becomes active when the ignore count is zero.  When non-zero, the
-count is decremented each time the breakpoint is reached and the
-breakpoint is not disabled and any associated condition evaluates
-to true.""", file=self.stdout)
-
-    def help_condition(self):
-        print("""condition bpnumber str_condition
-str_condition is a string specifying an expression which
-must evaluate to true before the breakpoint is honored.
-If str_condition is absent, any existing condition is removed;
-i.e., the breakpoint is made unconditional.""", file=self.stdout)
-
-    def help_step(self):
-        self.help_s()
-
-    def help_s(self):
-        print("""s(tep)
-Execute the current line, stop at the first possible occasion
-(either in a function that is called or in the current function).""", file=self.stdout)
-
-    def help_until(self):
-        self.help_unt()
-
-    def help_unt(self):
-        print("""unt(il)
-Continue execution until the line with a number greater than the current
-one is reached or until the current frame returns""")
-
-    def help_next(self):
-        self.help_n()
-
-    def help_n(self):
-        print("""n(ext)
-Continue execution until the next line in the current function
-is reached or it returns.""", file=self.stdout)
-
-    def help_return(self):
-        self.help_r()
-
-    def help_r(self):
-        print("""r(eturn)
-Continue execution until the current function returns.""", file=self.stdout)
-
-    def help_continue(self):
-        self.help_c()
-
-    def help_cont(self):
-        self.help_c()
-
-    def help_c(self):
-        print("""c(ont(inue))
-Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
-
-    def help_jump(self):
-        self.help_j()
-
-    def help_j(self):
-        print("""j(ump) lineno
-Set the next line that will be executed.""", file=self.stdout)
-
-    def help_debug(self):
-        print("""debug code
-Enter a recursive debugger that steps through the code argument
-(which is an arbitrary expression or statement to be executed
-in the current environment).""", file=self.stdout)
-
-    def help_list(self):
-        self.help_l()
-
-    def help_l(self):
-        print("""l(ist) [first [,last]]
-List source code for the current file.
-Without arguments, list 11 lines around the current line
-or continue the previous listing.
-With one argument, list 11 lines starting at that line.
-With two arguments, list the given range;
-if the second argument is less than the first, it is a count.""", file=self.stdout)
-
-    def help_args(self):
-        self.help_a()
-
-    def help_a(self):
-        print("""a(rgs)
-Print the arguments of the current function.""", file=self.stdout)
-
-    def help_p(self):
-        print("""p(rint) expression
-Print the value of the expression.""", file=self.stdout)
-
-    def help_pp(self):
-        print("""pp expression
-Pretty-print the value of the expression.""", file=self.stdout)
+            self.message(command.__doc__.rstrip())
+
+    do_h = do_help
 
     def help_exec(self):
-        print("""(!) statement
-Execute the (one-line) statement in the context of
-the current stack frame.
-The exclamation point can be omitted unless the first word
-of the statement resembles a debugger command.
-To assign to a global variable you must always prefix the
-command with a 'global' command, e.g.:
-(Pdb) global list_options; list_options = ['-l']
-(Pdb)""", file=self.stdout)
-
-    def help_run(self):
-        print("""run [args...]
-Restart the debugged python program. If a string is supplied, it is
-splitted with "shlex" and the result is used as the new sys.argv.
-History, breakpoints, actions and debugger options are preserved.
-"restart" is an alias for "run".""")
-
-    help_restart = help_run
-
-    def help_quit(self):
-        self.help_q()
-
-    def help_q(self):
-        print("""q(uit) or exit - Quit from the debugger.
-The program being executed is aborted.""", file=self.stdout)
-
-    help_exit = help_q
-
-    def help_whatis(self):
-        print("""whatis arg
-Prints the type of the argument.""", file=self.stdout)
-
-    def help_EOF(self):
-        print("""EOF
-Handles the receipt of EOF as a command.""", file=self.stdout)
-
-    def help_alias(self):
-        print("""alias [name [command [parameter parameter ...] ]]
-Creates an alias called 'name' the executes 'command'.  The command
-must *not* be enclosed in quotes.  Replaceable parameters are
-indicated by %1, %2, and so on, while %* is replaced by all the
-parameters.  If no command is given, the current alias for name
-is shown. If no name is given, all aliases are listed.
-
-Aliases may be nested and can contain anything that can be
-legally typed at the pdb prompt.  Note!  You *can* override
-internal pdb commands with aliases!  Those internal commands
-are then hidden until the alias is removed.  Aliasing is recursively
-applied to the first word of the command line; all other words
-in the line are left alone.
-
-Some useful aliases (especially when placed in the .pdbrc file) are:
-
-#Print instance variables (usage "pi classInst")
-alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
-
-#Print instance variables in self
-alias ps pi self
-""", file=self.stdout)
-
-    def help_unalias(self):
-        print("""unalias name
-Deletes the specified alias.""", file=self.stdout)
-
-    def help_commands(self):
-        print("""commands [bpnumber]
-(com) ...
-(com) end
-(Pdb)
-
-Specify a list of commands for breakpoint number bpnumber.  The
-commands themselves appear on the following lines.  Type a line
-containing just 'end' to terminate the commands.
-
-To remove all commands from a breakpoint, type commands and
-follow it immediately with  end; that is, give no commands.
-
-With no bpnumber argument, commands refers to the last
-breakpoint set.
-
-You can use breakpoint commands to start your program up again.
-Simply use the continue command, or step, or any other
-command that resumes execution.
-
-Specifying any command resuming execution (currently continue,
-step, next, return, jump, quit and their abbreviations) terminates
-the command list (as if that command was immediately followed by end).
-This is because any time you resume execution
-(even with a simple next or step), you may encounter
-another breakpoint--which could have its own command list, leading to
-ambiguities about which list to execute.
-
-   If you use the 'silent' command in the command list, the
-usual message about stopping at a breakpoint is not printed.  This may
-be desirable for breakpoints that are to print a specific message and
-then continue.  If none of the other commands print anything, you
-see no sign that the breakpoint was reached.
-""", file=self.stdout)
+        """(!) statement
+        Execute the (one-line) statement in the context of the current
+        stack frame.  The exclamation point can be omitted unless the
+        first word of the statement resembles a debugger command.  To
+        assign to a global variable you must always prefix the command
+        with a 'global' command, e.g.:
+        (Pdb) global list_options; list_options = ['-l']
+        (Pdb)
+        """
+        self.message(self.help_exec.__doc__.strip())
 
     def help_pdb(self):
         help()
 
+    # other helper functions
+
     def lookupmodule(self, filename):
         """Helper function for break/clear parsing -- may be overridden.
 
@@ -1234,6 +1338,24 @@
                         (fp.read(), self.mainpyfile)
         self.run(statement)
 
+# Collect all command help into docstring
+
+# unfortunately we can't guess this order from the class definition
+_help_order = [
+    'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
+    'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
+    'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
+    'args', 'print', 'pp', 'whatis', 'source', 'alias', 'unalias',
+    'debug', 'quit',
+]
+
+docs = set()
+for _command in _help_order:
+    __doc__ += getattr(Pdb, 'do_' + _command).__doc__.strip() + '\n\n'
+__doc__ += Pdb.help_exec.__doc__
+
+del _help_order, _command
+
 # Simplified interface
 
 def run(statement, globals=None, locals=None):
@@ -1260,9 +1382,9 @@
         # sys.exc_info() returns (type, value, traceback) if an exception is
         # being handled, otherwise it returns None
         t = sys.exc_info()[2]
-        if t is None:
-            raise ValueError("A valid traceback must be passed if no "
-                                               "exception is being handled")
+    if t is None:
+        raise ValueError("A valid traceback must be passed if no "
+                         "exception is being handled")
 
     p = Pdb()
     p.reset()
@@ -1281,27 +1403,45 @@
 
 # print help
 def help():
-    for dirname in sys.path:
-        fullname = os.path.join(dirname, 'pdb.doc')
-        if os.path.exists(fullname):
-            sts = os.system('${PAGER-more} '+fullname)
-            if sts: print('*** Pager exit status:', sts)
-            break
-    else:
-        print('Sorry, can\'t find the help file "pdb.doc"', end=' ')
-        print('along the Python search path')
+    import pydoc
+    pydoc.pager(__doc__)
+
+_usage = """\
+usage: pdb.py [-c command] ... pyfile [arg] ...
+
+Debug the Python program given by pyfile.
+
+Initial commands are read from .pdbrc files in your home directory
+and in the current directory, if they exist.  Commands supplied with
+-c are executed after commands from .pdbrc files.
+
+To let the script run until an exception occurs, use "-c continue".
+To let the script run up to a given line X in the debugged file, use
+"-c 'until X'"."""
 
 def main():
-    if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
-        print("usage: pdb.py scriptfile [arg] ...")
+    import getopt
+
+    opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])
+
+    if not args:
+        print(_usage)
         sys.exit(2)
 
-    mainpyfile =  sys.argv[1]     # Get script filename
+    commands = []
+    for opt, optarg in opts:
+        if opt in ['-h', '--help']:
+            print(_usage)
+            sys.exit()
+        elif opt in ['-c', '--command']:
+            commands.append(optarg)
+
+    mainpyfile = args[0]     # Get script filename
     if not os.path.exists(mainpyfile):
         print('Error:', mainpyfile, 'does not exist')
         sys.exit(1)
 
-    del sys.argv[0]         # Hide "pdb.py" from argument list
+    sys.argv[:] = args      # Hide "pdb.py" and pdb options from argument list
 
     # Replace pdb's dir with script's dir in front of module search path.
     sys.path[0] = os.path.dirname(mainpyfile)
@@ -1311,7 +1451,8 @@
     # changed by the user from the command line. There is a "restart" command
     # which allows explicit specification of command line arguments.
     pdb = Pdb()
-    while 1:
+    pdb.rcLines.extend(commands)
+    while True:
         try:
             pdb._runscript(mainpyfile)
             if pdb._user_requested_quit:
@@ -1319,10 +1460,10 @@
             print("The program finished and will be restarted")
         except Restart:
             print("Restarting", mainpyfile, "with arguments:")
-            print("\t" + " ".join(sys.argv[1:]))
+            print("\t" + " ".join(args))
         except SystemExit:
             # In most cases SystemExit does not warrant a post-mortem session.
-            print("The program exited via sys.exit(). Exit status: ", end=' ')
+            print("The program exited via sys.exit(). Exit status:", end=' ')
             print(sys.exc_info()[1])
         except:
             traceback.print_exc()

Modified: python/branches/py3k-dtoa/Lib/pickle.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/pickle.py	(original)
+++ python/branches/py3k-dtoa/Lib/pickle.py	Sun Aug  8 12:41:24 2010
@@ -1034,19 +1034,15 @@
     def _instantiate(self, klass, k):
         args = tuple(self.stack[k+1:])
         del self.stack[k:]
-        instantiated = False
-        if (not args and
-                isinstance(klass, type) and
-                not hasattr(klass, "__getinitargs__")):
-            value = _EmptyClass()
-            value.__class__ = klass
-            instantiated = True
-        if not instantiated:
+        if (args or not isinstance(klass, type) or
+            hasattr(klass, "__getinitargs__")):
             try:
                 value = klass(*args)
             except TypeError as err:
                 raise TypeError("in constructor for %s: %s" %
                                 (klass.__name__, str(err)), sys.exc_info()[2])
+        else:
+            value = klass.__new__(klass)
         self.append(value)
 
     def load_inst(self):
@@ -1239,14 +1235,7 @@
         raise _Stop(value)
     dispatch[STOP[0]] = load_stop
 
-# Helper class for load_inst/load_obj
-
-class _EmptyClass:
-    pass
-
-# Encode/decode longs in linear time.
-
-import binascii as _binascii
+# Encode/decode longs.
 
 def encode_long(x):
     r"""Encode a long to a two's complement little-endian binary string.
@@ -1333,4 +1322,26 @@
     return doctest.testmod()
 
 if __name__ == "__main__":
-    _test()
+    import sys, argparse
+    parser = argparse.ArgumentParser(
+        description='display contents of the pickle files')
+    parser.add_argument(
+        'pickle_file', type=argparse.FileType('br'),
+        nargs='*', help='the pickle file')
+    parser.add_argument(
+        '-t', '--test', action='store_true',
+        help='run self-test suite')
+    parser.add_argument(
+        '-v', action='store_true',
+        help='run verbosely; only affects self-test run')
+    args = parser.parse_args()
+    if args.test:
+        _test()
+    else:
+        if not args.pickle_file:
+            parser.print_help()
+        else:
+            import pprint
+            for f in args.pickle_file:
+                obj = load(f)
+                pprint.pprint(obj)

Modified: python/branches/py3k-dtoa/Lib/pickletools.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/pickletools.py	(original)
+++ python/branches/py3k-dtoa/Lib/pickletools.py	Sun Aug  8 12:41:24 2010
@@ -733,7 +733,7 @@
 
 pyinteger_or_bool = StackObject(
                         name='int_or_bool',
-                        obtype=(int, int, bool),
+                        obtype=(int, bool),
                         doc="A Python integer object (short or long), or "
                             "a Python bool.")
 
@@ -1250,10 +1250,11 @@
       stack_before=[anyobject],
       stack_after=[pytuple],
       proto=2,
-      doc="""One-tuple.
+      doc="""Build a one-tuple out of the topmost item on the stack.
 
       This code pops one value off the stack and pushes a tuple of
-      length 1 whose one item is that value back onto it.  IOW:
+      length 1 whose one item is that value back onto it.  In other
+      words:
 
           stack[-1] = tuple(stack[-1:])
       """),
@@ -1264,10 +1265,11 @@
       stack_before=[anyobject, anyobject],
       stack_after=[pytuple],
       proto=2,
-      doc="""One-tuple.
+      doc="""Build a two-tuple out of the top two items on the stack.
 
-      This code pops two values off the stack and pushes a tuple
-      of length 2 whose items are those values back onto it.  IOW:
+      This code pops two values off the stack and pushes a tuple of
+      length 2 whose items are those values back onto it.  In other
+      words:
 
           stack[-2:] = [tuple(stack[-2:])]
       """),
@@ -1278,10 +1280,11 @@
       stack_before=[anyobject, anyobject, anyobject],
       stack_after=[pytuple],
       proto=2,
-      doc="""One-tuple.
+      doc="""Build a three-tuple out of the top three items on the stack.
 
-      This code pops three values off the stack and pushes a tuple
-      of length 3 whose items are those values back onto it.  IOW:
+      This code pops three values off the stack and pushes a tuple of
+      length 3 whose items are those values back onto it.  In other
+      words:
 
           stack[-3:] = [tuple(stack[-3:])]
       """),
@@ -1904,7 +1907,7 @@
 ##############################################################################
 # A symbolic pickle disassembler.
 
-def dis(pickle, out=None, memo=None, indentlevel=4):
+def dis(pickle, out=None, memo=None, indentlevel=4, annotate=0):
     """Produce a symbolic disassembly of a pickle.
 
     'pickle' is a file-like object, or string, containing a (at least one)
@@ -1920,9 +1923,15 @@
     to proceed across multiple pickles that were all created by the same
     pickler with the same memo.  Ordinarily you don't need to worry about this.
 
-    Optional arg indentlevel is the number of blanks by which to indent
+    Optional arg 'indentlevel' is the number of blanks by which to indent
     a new MARK level.  It defaults to 4.
 
+    Optional arg 'annotate' if nonzero instructs dis() to add short
+    description of the opcode on each line of disassembled output.
+    The value given to 'annotate' must be an integer and is used as a
+    hint for the column where annotation should start.  The default
+    value is 0, meaning no annotations.
+
     In addition to printing the disassembly, some sanity checks are made:
 
     + All embedded opcode arguments "make sense".
@@ -1950,6 +1959,7 @@
     markstack = []      # bytecode positions of MARK opcodes
     indentchunk = ' ' * indentlevel
     errormsg = None
+    annocol = annotate  # columnt hint for annotations
     for opcode, arg, pos in genops(pickle):
         if pos is not None:
             print("%5d:" % pos, end=' ', file=out)
@@ -2017,6 +2027,13 @@
                 line += ' ' + repr(arg)
             if markmsg:
                 line += ' ' + markmsg
+        if annotate:
+            line += ' ' * (annocol - len(line))
+            # make a mild effort to align annotations
+            annocol = len(line)
+            if annocol > 50:
+                annocol = annotate
+            line += ' ' + opcode.doc.split('\n', 1)[0]
         print(line, file=out)
 
         if errormsg:
@@ -2290,6 +2307,22 @@
    12: h    BINGET     1
    14: .    STOP
 highest protocol among opcodes = 2
+
+Try protocol 3 with annotations:
+
+>>> dis(pickle.dumps(T, 3), annotate=1)
+    0: \x80 PROTO      3 Protocol version indicator.
+    2: ]    EMPTY_LIST   Push an empty list.
+    3: q    BINPUT     0 Store the stack top into the memo.  The stack is not popped.
+    5: h    BINGET     0 Read an object from the memo and push it on the stack.
+    7: \x85 TUPLE1       Build a one-tuple out of the topmost item on the stack.
+    8: q    BINPUT     1 Store the stack top into the memo.  The stack is not popped.
+   10: a    APPEND       Append an object to a list.
+   11: 0    POP          Discard the top stack item, shrinking the stack by one item.
+   12: h    BINGET     1 Read an object from the memo and push it on the stack.
+   14: .    STOP         Stop the unpickling machine.
+highest protocol among opcodes = 2
+
 """
 
 _memo_test = r"""
@@ -2346,6 +2379,9 @@
         '-l', '--indentlevel', default=4, type=int,
         help='the number of blanks by which to indent a new MARK level')
     parser.add_argument(
+        '-a', '--annotate',  action='store_true',
+        help='annotate each line with a short opcode description')
+    parser.add_argument(
         '-p', '--preamble', default="==> {name} <==",
         help='if more than one pickle file is specified, print this before'
         ' each disassembly')
@@ -2359,14 +2395,15 @@
     if args.test:
         _test()
     else:
+        annotate = 30 if args.annotate else 0
         if not args.pickle_file:
             parser.print_help()
         elif len(args.pickle_file) == 1:
-            dis(args.pickle_file[0], args.output,
-                indentlevel=args.indentlevel)
+            dis(args.pickle_file[0], args.output, None,
+                args.indentlevel, annotate)
         else:
             memo = {} if args.memo else None
             for f in args.pickle_file:
                 preamble = args.preamble.format(name=f.name)
                 args.output.write(preamble + '\n')
-                dis(f, args.output, memo, args.indentlevel)
+                dis(f, args.output, memo, args.indentlevel, annotate)

Modified: python/branches/py3k-dtoa/Lib/platform.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/platform.py	(original)
+++ python/branches/py3k-dtoa/Lib/platform.py	Sun Aug  8 12:41:24 2010
@@ -724,27 +724,19 @@
 
     return hex(bcd)[2:]
 
-def mac_ver(release='',versioninfo=('','',''),machine=''):
-
-    """ Get MacOS version information and return it as tuple (release,
-        versioninfo, machine) with versioninfo being a tuple (version,
-        dev_stage, non_release_version).
-
-        Entries which cannot be determined are set to the paramter values
-        which default to ''. All tuple entries are strings.
-
+def _mac_ver_gestalt():
+    """
         Thanks to Mark R. Levinson for mailing documentation links and
         code examples for this function. Documentation for the
         gestalt() API is available online at:
 
            http://www.rgaros.nl/gestalt/
-
     """
     # Check whether the version info module is available
     try:
         import _gestalt
     except ImportError:
-        return release,versioninfo,machine
+        return None
     # Get the infos
     sysv, sysa = _mac_ver_lookup(('sysv','sysa'))
     # Decode the infos
@@ -768,6 +760,53 @@
         machine = {0x1: '68k',
                    0x2: 'PowerPC',
                    0xa: 'i386'}.get(sysa,'')
+
+    return release,versioninfo,machine
+
+def _mac_ver_xml():
+    fn = '/System/Library/CoreServices/SystemVersion.plist'
+    if not os.path.exists(fn):
+        return None
+
+    try:
+        import plistlib
+    except ImportError:
+        return None
+
+    pl = plistlib.readPlist(fn)
+    release = pl['ProductVersion']
+    versioninfo=('', '', '')
+    machine = os.uname()[4]
+    if machine in ('ppc', 'Power Macintosh'):
+        # for compatibility with the gestalt based code
+        machine = 'PowerPC'
+
+    return release,versioninfo,machine
+
+
+def mac_ver(release='',versioninfo=('','',''),machine=''):
+
+    """ Get MacOS version information and return it as tuple (release,
+        versioninfo, machine) with versioninfo being a tuple (version,
+        dev_stage, non_release_version).
+
+        Entries which cannot be determined are set to the paramter values
+        which default to ''. All tuple entries are strings.
+    """
+
+    # First try reading the information from an XML file which should
+    # always be present
+    info = _mac_ver_xml()
+    if info is not None:
+        return info
+
+    # If that doesn't work for some reason fall back to reading the
+    # information using gestalt calls.
+    info = _mac_ver_gestalt()
+    if info is not None:
+        return info
+
+    # If that also doesn't work return the default values
     return release,versioninfo,machine
 
 def _java_getprop(name,default):
@@ -1098,7 +1137,7 @@
     except AttributeError:
         no_os_uname = 1
 
-    if no_os_uname or not filter(None, (system, node, release, version, machine)):
+    if no_os_uname or not list(filter(None, (system, node, release, version, machine))):
         # Hmm, no there is either no uname or uname has returned
         #'unknowns'... we'll have to poke around the system then.
         if no_os_uname:

Modified: python/branches/py3k-dtoa/Lib/posixpath.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/posixpath.py	(original)
+++ python/branches/py3k-dtoa/Lib/posixpath.py	Sun Aug  8 12:41:24 2010
@@ -200,6 +200,9 @@
 
 def ismount(path):
     """Test whether a path is a mount point"""
+    if islink(path):
+        # A symlink can never be a mount point
+        return False
     try:
         s1 = os.lstat(path)
         if isinstance(path, bytes):

Modified: python/branches/py3k-dtoa/Lib/profile.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/profile.py	(original)
+++ python/branches/py3k-dtoa/Lib/profile.py	Sun Aug  8 12:41:24 2010
@@ -75,7 +75,7 @@
     else:
         return prof.print_stats(sort)
 
-def runctx(statement, globals, locals, filename=None):
+def runctx(statement, globals, locals, filename=None, sort=-1):
     """Run statement under profiler, supplying your own globals and locals,
     optionally saving results in filename.
 
@@ -90,7 +90,7 @@
     if filename is not None:
         prof.dump_stats(filename)
     else:
-        return prof.print_stats()
+        return prof.print_stats(sort)
 
 if hasattr(os, "times"):
     def _get_time_times(timer=os.times):
@@ -582,20 +582,28 @@
     parser.add_option('-o', '--outfile', dest="outfile",
         help="Save stats to <outfile>", default=None)
     parser.add_option('-s', '--sort', dest="sort",
-        help="Sort order when printing to stdout, based on pstats.Stats class", default=-1)
+        help="Sort order when printing to stdout, based on pstats.Stats class",
+        default=-1)
 
     if not sys.argv[1:]:
         parser.print_usage()
         sys.exit(2)
 
     (options, args) = parser.parse_args()
+    sys.argv[:] = args
 
-    if (len(args) > 0):
-        sys.argv[:] = args
-        sys.path.insert(0, os.path.dirname(sys.argv[0]))
-        with open(sys.argv[0], 'rb') as fp:
-            script = fp.read()
-        run('exec(%r)' % script, options.outfile, options.sort)
+    if len(args) > 0:
+        progname = args[0]
+        sys.path.insert(0, os.path.dirname(progname))
+        with open(progname, 'rb') as fp:
+            code = compile(fp.read(), progname, 'exec')
+        globs = {
+            '__file__': progname,
+            '__name__': '__main__',
+            '__package__': None,
+            '__cached__': None,
+        }
+        runctx(code, globs, None, options.outfile, options.sort)
     else:
         parser.print_usage()
     return parser

Modified: python/branches/py3k-dtoa/Lib/pstats.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/pstats.py	(original)
+++ python/branches/py3k-dtoa/Lib/pstats.py	Sun Aug  8 12:41:24 2010
@@ -5,7 +5,7 @@
 # Based on prior profile module by Sjoerd Mullender...
 #   which was hacked somewhat by: Guido van Rossum
 #
-# see profile.doc and profile.py for more info.
+# see profile.py for more info.
 
 # Copyright 1994, by InfoSeek Corporation, all rights reserved.
 # Written by James Roskind
@@ -66,7 +66,7 @@
     minor key of 'the name of the function'.  Look at the two tables in
     sort_stats() and get_sort_arg_defs(self) for more examples.
 
-    All methods return self,  so you can string together commands like:
+    All methods return self, so you can string together commands like:
         Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
                             print_stats(5).print_callers(5)
     """
@@ -138,7 +138,7 @@
         if not arg_list: return self
         if len(arg_list) > 1: self.add(*arg_list[1:])
         other = arg_list[0]
-        if type(self) != type(other) or self.__class__ != other.__class__:
+        if type(self) != type(other):
             other = Stats(other)
         self.files += other.files
         self.total_calls += other.total_calls
@@ -206,12 +206,12 @@
         if not field:
             self.fcn_list = 0
             return self
-        if len(field) == 1 and type(field[0]) == type(1):
+        if len(field) == 1 and isinstance(field[0], int):
             # Be compatible with old profiler
             field = [ {-1: "stdname",
-                      0:"calls",
-                      1:"time",
-                      2: "cumulative" }  [ field[0] ] ]
+                       0:  "calls",
+                       1:  "time",
+                       2:  "cumulative"}[field[0]] ]
 
         sort_arg_defs = self.get_sort_arg_defs()
         sort_tuple = ()
@@ -288,48 +288,53 @@
 
     def eval_print_amount(self, sel, list, msg):
         new_list = list
-        if type(sel) == type(""):
+        if isinstance(sel, str):
+            try:
+                rex = re.compile(sel)
+            except re.error:
+                msg += "   <Invalid regular expression %r>\n" % sel
+                return new_list, msg
             new_list = []
             for func in list:
-                if re.search(sel, func_std_string(func)):
+                if rex.search(func_std_string(func)):
                     new_list.append(func)
         else:
             count = len(list)
-            if type(sel) == type(1.0) and 0.0 <= sel < 1.0:
+            if isinstance(sel, float) and 0.0 <= sel < 1.0:
                 count = int(count * sel + .5)
                 new_list = list[:count]
-            elif type(sel) == type(1) and 0 <= sel < count:
+            elif isinstance(sel, int) and 0 <= sel < count:
                 count = sel
                 new_list = list[:count]
         if len(list) != len(new_list):
-            msg = msg + "   List reduced from %r to %r due to restriction <%r>\n" % (
-                         len(list), len(new_list), sel)
+            msg += "   List reduced from %r to %r due to restriction <%r>\n" % (
+                len(list), len(new_list), sel)
 
         return new_list, msg
 
     def get_print_list(self, sel_list):
         width = self.max_name_len
         if self.fcn_list:
-            list = self.fcn_list[:]
+            stat_list = self.fcn_list[:]
             msg = "   Ordered by: " + self.sort_type + '\n'
         else:
-            list = self.stats.keys()
+            stat_list = list(self.stats.keys())
             msg = "   Random listing order was used\n"
 
         for selection in sel_list:
-            list, msg = self.eval_print_amount(selection, list, msg)
+            stat_list, msg = self.eval_print_amount(selection, stat_list, msg)
 
-        count = len(list)
+        count = len(stat_list)
 
-        if not list:
-            return 0, list
+        if not stat_list:
+            return 0, stat_list
         print(msg, file=self.stream)
         if count < len(self.stats):
             width = 0
-            for func in list:
+            for func in stat_list:
                 if  len(func_std_string(func)) > width:
                     width = len(func_std_string(func))
-        return width+2, list
+        return width+2, stat_list
 
     def print_stats(self, *amount):
         for filename in self.files:
@@ -501,8 +506,13 @@
         new_callers[func] = caller
     for func, caller in source.items():
         if func in new_callers:
-            new_callers[func] = tuple([i[0] + i[1] for i in
-                                       zip(caller, new_callers[func])])
+            if isinstance(caller, tuple):
+                # format used by cProfile
+                new_callers[func] = tuple([i[0] + i[1] for i in
+                                           zip(caller, new_callers[func])])
+            else:
+                # format used by profile
+                new_callers[func] += caller
         else:
             new_callers[func] = caller
     return new_callers
@@ -536,12 +546,10 @@
         def __init__(self, profile=None):
             cmd.Cmd.__init__(self)
             self.prompt = "% "
+            self.stats = None
+            self.stream = sys.stdout
             if profile is not None:
-                self.stats = Stats(profile)
-                self.stream = self.stats.stream
-            else:
-                self.stats = None
-                self.stream = sys.stdout
+                self.do_read(profile)
 
         def generic(self, fn, line):
             args = line.split()
@@ -576,7 +584,10 @@
             print("  that match it are printed.", file=self.stream)
 
         def do_add(self, line):
-            self.stats.add(line)
+            if self.stats:
+                self.stats.add(line)
+            else:
+                print("No statistics object is loaded.", file=self.stream)
             return 0
         def help_add(self):
             print("Add profile info from given file to current statistics object.", file=self.stream)
@@ -611,22 +622,33 @@
                 except IOError as err:
                     print(err.args[1], file=self.stream)
                     return
+                except Exception as err:
+                    print(err.__class__.__name__ + ':', err, file=self.stream)
+                    return
                 self.prompt = line + "% "
             elif len(self.prompt) > 2:
-                line = self.prompt[-2:]
+                line = self.prompt[:-2]
+                self.do_read(line)
             else:
                 print("No statistics object is current -- cannot reload.", file=self.stream)
             return 0
         def help_read(self):
             print("Read in profile data from a specified file.", file=self.stream)
+            print("Without argument, reload the current file.", file=self.stream)
 
         def do_reverse(self, line):
-            self.stats.reverse_order()
+            if self.stats:
+                self.stats.reverse_order()
+            else:
+                print("No statistics object is loaded.", file=self.stream)
             return 0
         def help_reverse(self):
             print("Reverse the sort order of the profiling report.", file=self.stream)
 
         def do_sort(self, line):
+            if not self.stats:
+                print("No statistics object is loaded.", file=self.stream)
+                return
             abbrevs = self.stats.get_sort_arg_defs()
             if line and all((x in abbrevs) for x in line.split()):
                 self.stats.sort_stats(*line.split())
@@ -648,11 +670,16 @@
             self.generic_help()
 
         def do_strip(self, line):
-            self.stats.strip_dirs()
-            return 0
+            if self.stats:
+                self.stats.strip_dirs()
+            else:
+                print("No statistics object is loaded.", file=self.stream)
         def help_strip(self):
             print("Strip leading path information from filenames in the report.", file=self.stream)
 
+        def help_help(self):
+            print("Show help for a given command.", file=self.stream)
+
         def postcmd(self, stop, line):
             if stop:
                 return stop

Modified: python/branches/py3k-dtoa/Lib/pydoc.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/pydoc.py	(original)
+++ python/branches/py3k-dtoa/Lib/pydoc.py	Sun Aug  8 12:41:24 2010
@@ -1695,9 +1695,12 @@
         'CONTEXTMANAGERS': ('context-managers', 'with'),
     }
 
-    def __init__(self, input, output):
-        self.input = input
-        self.output = output
+    def __init__(self, input=None, output=None):
+        self._input = input
+        self._output = output
+
+    input  = property(lambda self: self._input or sys.stdin)
+    output = property(lambda self: self._output or sys.stdout)
 
     def __repr__(self):
         if inspect.stack()[1][3] == '?':
@@ -1874,7 +1877,7 @@
 for modules whose descriptions contain the word "spam".
 ''')
 
-help = Helper(sys.stdin, sys.stdout)
+help = Helper()
 
 class Scanner:
     """A generic tree iterator."""

Modified: python/branches/py3k-dtoa/Lib/pydoc_data/topics.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/pydoc_data/topics.py	(original)
+++ python/branches/py3k-dtoa/Lib/pydoc_data/topics.py	Sun Aug  8 12:41:24 2010
@@ -1,78 +1,77 @@
-# Autogenerated by Sphinx on Fri Jun 26 08:03:32 2009
+# Autogenerated by Sphinx on Sat Jul 31 10:22:58 2010
 topics = {'assert': '\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n   assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n   if __debug__:\n      if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n   if __debug__:\n      if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names.  In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O).  The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime.  Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal.  The value for the built-in\nvariable is determined when the interpreter starts.\n',
- 'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n   assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n   target_list     ::= target ("," target)* [","]\n   target          ::= identifier\n              | "(" target_list ")"\n              | "[" target_list "]"\n              | attributeref\n              | subscription\n              | slicing\n              | "*" target\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable.  The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is a single target: The object is assigned to\n  that target.\n\n* If the target list is a comma-separated list of targets: The object\n  must be an iterable with the same number of items as there are\n  targets in the target list, and the items are assigned, from left to\n  right, to the corresponding targets. (This rule is relaxed as of\n  Python 1.5; in earlier versions, the object had to be a tuple.\n  Since strings are sequences, an assignment like ``a, b = "xy"`` is\n  now legal as long as the string has the right length.)\n\n  * If the target list contains one target prefixed with an asterisk,\n    called a "starred" target: The object must be a sequence with at\n    least as many items as there are targets in the target list, minus\n    one.  The first items of the sequence are assigned, from left to\n    right, to the targets before the starred target.  The final items\n    of the sequence are assigned to the targets after the starred\n    target.  A list of the remaining items in the sequence is then\n    assigned to the starred target (the list can be empty).\n\n  * Else: The object must be a sequence with the same number of items\n    as there are targets in the target list, and the items are\n    assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n  * If the name does not occur in a ``global`` or ``nonlocal``\n    statement in the current code block: the name is bound to the\n    object in the current local namespace.\n\n  * Otherwise: the name is bound to the object in the global namespace\n    or the outer namespace determined by ``nonlocal``, respectively.\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  zero, causing the object to be deallocated and its destructor (if it\n  has one) to be called.\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  zero, causing the object to be deallocated and its destructor (if it\n  has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n  brackets: The object must be an iterable with the same number of\n  items as there are targets in the target list, and its items are\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  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  an exception (usually but not necessarily ``AttributeError``).\n\n* If the target is a subscription: The primary expression in the\n  reference is evaluated.  It should yield either a mutable sequence\n  object (such as a list) or a mapping object (such as a dictionary).\n  Next, the subscript expression is evaluated.\n\n  If the primary is a mutable sequence object (such as a list), the\n  subscript must yield an integer.  If it is negative, the sequence\'s\n  length is added to it.  The resulting value must be a nonnegative\n  integer less than the sequence\'s length, and the sequence is asked\n  to assign the assigned object to its item with that index.  If the\n  index is out of range, ``IndexError`` is raised (assignment to a\n  subscripted sequence cannot add new items to a list).\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  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 a new\n  key/value pair (if no key with the same value existed).\n\n  For user-defined objects, the ``__setitem__()`` method is called\n  with appropriate arguments.\n\n* If the target is a slicing: The primary expression in the reference\n  is evaluated.  It should yield a mutable sequence object (such as a\n  list).  The assigned object should be a sequence object of the same\n  type.  Next, the lower and upper bound expressions are evaluated,\n  insofar they are present; defaults are zero and the sequence\'s\n  length.  The bounds should evaluate to integers. If either bound is\n  negative, the sequence\'s length is added to it.  The resulting\n  bounds are clipped to lie between zero and the sequence\'s length,\n  inclusive.  Finally, the sequence object is asked to replace the\n  slice with the items of the assigned sequence.  The length of the\n  slice may be different from the length of the assigned sequence,\n  thus changing the length of the target sequence, if the object\n  allows it.\n\n(In the current implementation, the syntax for targets is taken to be\nthe same as for expressions, and invalid syntax is rejected during the\ncode generation phase, causing less detailed error messages.)\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe!  For instance, the\nfollowing program prints ``[0, 2]``:\n\n   x = [0, 1]\n   i = 0\n   i, x[i] = 1, 2\n   print(x)\n\nSee also:\n\n   **PEP 3132** - Extended Iterable Unpacking\n      The specification for the ``*target`` feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n   augtarget                 ::= identifier | attributeref | subscription | slicing\n   augop                     ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n             | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the initial value is\nretrieved with a ``getattr()`` and the result is assigned with a\n``setattr()``.  Notice that the two methods do not necessarily refer\nto the same variable.  When ``getattr()`` refers to a class variable,\n``setattr()`` still writes to an instance variable. For example:\n\n   class A:\n       x = 3    # class variable\n   a = A()\n   a.x += 1     # writes a.x as 4 leaving A.x as 3\n',
+ 'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n   assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n   target_list     ::= target ("," target)* [","]\n   target          ::= identifier\n              | "(" target_list ")"\n              | "[" target_list "]"\n              | attributeref\n              | subscription\n              | slicing\n              | "*" target\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable.  The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is a single target: The object is assigned to\n  that target.\n\n* If the target list is a comma-separated list of targets: The object\n  must be an iterable with the same number of items as there are\n  targets in the target list, and the items are assigned, from left to\n  right, to the corresponding targets. (This rule is relaxed as of\n  Python 1.5; in earlier versions, the object had to be a tuple.\n  Since strings are sequences, an assignment like ``a, b = "xy"`` is\n  now legal as long as the string has the right length.)\n\n  * If the target list contains one target prefixed with an asterisk,\n    called a "starred" target: The object must be a sequence with at\n    least as many items as there are targets in the target list, minus\n    one.  The first items of the sequence are assigned, from left to\n    right, to the targets before the starred target.  The final items\n    of the sequence are assigned to the targets after the starred\n    target.  A list of the remaining items in the sequence is then\n    assigned to the starred target (the list can be empty).\n\n  * Else: The object must be a sequence with the same number of items\n    as there are targets in the target list, and the items are\n    assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n  * If the name does not occur in a ``global`` or ``nonlocal``\n    statement in the current code block: the name is bound to the\n    object in the current local namespace.\n\n  * Otherwise: the name is bound to the object in the global namespace\n    or the outer namespace determined by ``nonlocal``, respectively.\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  zero, causing the object to be deallocated and its destructor (if it\n  has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n  brackets: The object must be an iterable with the same number of\n  items as there are targets in the target list, and its items are\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  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  an exception (usually but not necessarily ``AttributeError``).\n\n  Note: If the object is a class instance and the attribute reference\n  occurs on both sides of the assignment operator, the RHS expression,\n  ``a.x`` can access either an instance attribute or (if no instance\n  attribute exists) a class attribute.  The LHS target ``a.x`` is\n  always set as an instance attribute, creating it if necessary.\n  Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n  same attribute: if the RHS expression refers to a class attribute,\n  the LHS creates a new instance attribute as the target of the\n  assignment:\n\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\n  This description does not necessarily apply to descriptor\n  attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n  reference is evaluated.  It should yield either a mutable sequence\n  object (such as a list) or a mapping object (such as a dictionary).\n  Next, the subscript expression is evaluated.\n\n  If the primary is a mutable sequence object (such as a list), the\n  subscript must yield an integer.  If it is negative, the sequence\'s\n  length is added to it.  The resulting value must be a nonnegative\n  integer less than the sequence\'s length, and the sequence is asked\n  to assign the assigned object to its item with that index.  If the\n  index is out of range, ``IndexError`` is raised (assignment to a\n  subscripted sequence cannot add new items to a list).\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  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 a new\n  key/value pair (if no key with the same value existed).\n\n  For user-defined objects, the ``__setitem__()`` method is called\n  with appropriate arguments.\n\n* If the target is a slicing: The primary expression in the reference\n  is evaluated.  It should yield a mutable sequence object (such as a\n  list).  The assigned object should be a sequence object of the same\n  type.  Next, the lower and upper bound expressions are evaluated,\n  insofar they are present; defaults are zero and the sequence\'s\n  length.  The bounds should evaluate to integers. If either bound is\n  negative, the sequence\'s length is added to it.  The resulting\n  bounds are clipped to lie between zero and the sequence\'s length,\n  inclusive.  Finally, the sequence object is asked to replace the\n  slice with the items of the assigned sequence.  The length of the\n  slice may be different from the length of the assigned sequence,\n  thus changing the length of the target sequence, if the object\n  allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe!  For instance, the\nfollowing program prints ``[0, 2]``:\n\n   x = [0, 1]\n   i = 0\n   i, x[i] = 1, 2\n   print(x)\n\nSee also:\n\n   **PEP 3132** - Extended Iterable Unpacking\n      The specification for the ``*target`` feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n   augtarget                 ::= identifier | attributeref | subscription | slicing\n   augop                     ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n             | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
  'atom-identifiers': '\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name.  See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them.  The transformation inserts the\nclass name in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name.  For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``.  This transformation is independent of\nthe syntactical context in which the identifier is used.  If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen.  If the class name\nconsists only of underscores, no transformation is done.\n',
  'atom-literals': "\nLiterals\n********\n\nPython supports string and bytes literals and various numeric\nliterals:\n\n   literal ::= stringliteral | bytesliteral\n               | integer | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\nbytes, integer, floating point number, complex number) with the given\nvalue.  The value may be approximated in the case of floating point\nand imaginary (complex) literals.  See section *Literals* for details.\n\nWith the exception of bytes literals, these all correspond to\nimmutable data types, and hence the object's identity is less\nimportant than its value. Multiple evaluations of literals with the\nsame value (either the same occurrence in the program text or a\ndifferent occurrence) may obtain the same object or a different object\nwith the same value.\n",
- 'attribute-access': '\nCustomizing attribute access\n****************************\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\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   in the class tree for ``self``).  ``name`` is the attribute name.\n   This method should return the (computed) attribute value or raise\n   an ``AttributeError`` exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   ``__getattr__()`` is not called.  (This is an intentional asymmetry\n   between ``__getattr__()`` and ``__setattr__()``.) This is done both\n   for efficiency reasons and because otherwise ``__getattr__()``\n   would have no way to access other attributes of the instance.  Note\n   that at least for instance variables, you can fake total control by\n   not 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   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines\n   ``__getattr__()``, the latter will not be called unless\n   ``__getattribute__()`` either calls it explicitly or raises an\n   ``AttributeError``. This method should return the (computed)\n   attribute value or raise an ``AttributeError`` exception. In order\n   to avoid infinite recursion in this method, its implementation\n   should always call the base class method with the same name to\n   access any attributes it needs, for example,\n   ``object.__getattribute__(self, name)``.\n\n   Note: This method may still be bypassed when looking up special methods\n     as the result of implicit invocation via language syntax or\n     builtin functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\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   value to be assigned to it.\n\n   If ``__setattr__()`` wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n   Like ``__setattr__()`` but for attribute deletion instead of\n   assignment.  This should only be implemented if ``del obj.name`` is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when ``dir()`` is called on the object.  A list must be\n   returned.\n\n\nImplementing Descriptors\n========================\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class.  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\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   return the (computed) attribute value or raise an\n   ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    ``x.__get__(a)``.\n\nInstance Binding\n   If binding to an object instance, ``a.x`` is transformed into the\n   call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n   If binding to a class, ``A.x`` is transformed into the call:\n   ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n   If ``a`` is an instance of ``super``, then the binding ``super(B,\n   obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n   ``A`` immediately preceding ``B`` and then invokes the descriptor\n   with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  Normally, data\ndescriptors define both ``__get__()`` and ``__set__()``, while non-\ndata descriptors have just the ``__get__()`` method.  Data descriptors\nalways override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances. [2]\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__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   class, *__slots__* reserves space for the declared variables and\n   prevents the automatic creation of *__dict__* and *__weakref__* for\n   each instance.\n\n\nNotes on using *__slots__*\n--------------------------\n\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 assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises ``AttributeError``. If\n  dynamic assignment of new variables is desired, then add\n  ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n  *__slots__* do not support weak references to its instances. If weak\n  reference support is needed, then add ``\'__weakref__\'`` to the\n  sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a 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* If a class defines a slot also defined in a base class, the instance\n  variable defined by the base class slot is inaccessible (except by\n  retrieving its descriptor directly from the base class). This\n  renders the meaning of the program undefined.  In the future, a\n  check may be added to prevent this.\n\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__*.\n\n* Nonempty *__slots__* does not work for classes derived from\n  "variable-length" built-in types such as ``int``, ``str`` and\n  ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n  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  *__slots__*.\n',
+ 'attribute-access': '\nCustomizing attribute access\n****************************\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\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   in the class tree for ``self``).  ``name`` is the attribute name.\n   This method should return the (computed) attribute value or raise\n   an ``AttributeError`` exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   ``__getattr__()`` is not called.  (This is an intentional asymmetry\n   between ``__getattr__()`` and ``__setattr__()``.) This is done both\n   for efficiency reasons and because otherwise ``__getattr__()``\n   would have no way to access other attributes of the instance.  Note\n   that at least for instance variables, you can fake total control by\n   not 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   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines\n   ``__getattr__()``, the latter will not be called unless\n   ``__getattribute__()`` either calls it explicitly or raises an\n   ``AttributeError``. This method should return the (computed)\n   attribute value or raise an ``AttributeError`` exception. In order\n   to avoid infinite recursion in this method, its implementation\n   should always call the base class method with the same name to\n   access any attributes it needs, for example,\n   ``object.__getattribute__(self, name)``.\n\n   Note: This method may still be bypassed when looking up special methods\n     as the result of implicit invocation via language syntax or\n     built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\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   value to be assigned to it.\n\n   If ``__setattr__()`` wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n   Like ``__setattr__()`` but for attribute deletion instead of\n   assignment.  This should only be implemented if ``del obj.name`` is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when ``dir()`` is called on the object.  A list must be\n   returned.\n\n\nImplementing Descriptors\n========================\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class.  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\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   return the (computed) attribute value or raise an\n   ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    ``x.__get__(a)``.\n\nInstance Binding\n   If binding to an object instance, ``a.x`` is transformed into the\n   call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n   If binding to a class, ``A.x`` is transformed into the call:\n   ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n   If ``a`` is an instance of ``super``, then the binding ``super(B,\n   obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n   ``A`` immediately preceding ``B`` and then invokes the descriptor\n   with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary.  If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor.  Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method.  Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary.  In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__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   class, *__slots__* reserves space for the declared variables and\n   prevents the automatic creation of *__dict__* and *__weakref__* for\n   each instance.\n\n\nNotes on using *__slots__*\n--------------------------\n\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 assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises ``AttributeError``. If\n  dynamic assignment of new variables is desired, then add\n  ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n  *__slots__* do not support weak references to its instances. If weak\n  reference support is needed, then add ``\'__weakref__\'`` to the\n  sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a 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  where it is defined.  As a result, subclasses will have a *__dict__*\n  unless they also define *__slots__* (which must only contain names\n  of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n  variable defined by the base class slot is inaccessible (except by\n  retrieving its descriptor directly from the base class). This\n  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 ``int``, ``str`` and\n  ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n  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  *__slots__*.\n',
  'attribute-references': '\nAttribute references\n********************\n\nAn attribute reference is a primary followed by a period and a name:\n\n   attributeref ::= primary "." identifier\n\nThe primary must evaluate to an object of a type that supports\nattribute references, which most objects do.  This object is then\nasked to produce the attribute whose name is the identifier (which can\nbe customized by overriding the ``__getattr__()`` method).  If this\nattribute is not available, the exception ``AttributeError`` is\nraised.  Otherwise, the type and value of the object produced is\ndetermined by the object.  Multiple evaluations of the same attribute\nreference may yield different objects.\n',
- 'augassign': '\nAugmented assignment statements\n*******************************\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n   augtarget                 ::= identifier | attributeref | subscription | slicing\n   augop                     ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n             | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the initial value is\nretrieved with a ``getattr()`` and the result is assigned with a\n``setattr()``.  Notice that the two methods do not necessarily refer\nto the same variable.  When ``getattr()`` refers to a class variable,\n``setattr()`` still writes to an instance variable. For example:\n\n   class A:\n       x = 3    # class variable\n   a = A()\n   a.x += 1     # writes a.x as 4 leaving A.x as 3\n',
+ 'augassign': '\nAugmented assignment statements\n*******************************\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n   augtarget                 ::= identifier | attributeref | subscription | slicing\n   augop                     ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n             | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
  'binary': '\nBinary arithmetic operations\n****************************\n\nThe binary arithmetic operations have the conventional priority\nlevels.  Note that some of these operations also apply to certain non-\nnumeric types.  Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n\n   m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n              | m_expr "%" u_expr\n   a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n\nThe ``*`` (multiplication) operator yields the product of its\narguments.  The arguments must either both be numbers, or one argument\nmust be an integer and the other must be a sequence. In the former\ncase, the numbers are converted to a common type and then multiplied\ntogether.  In the latter case, sequence repetition is performed; a\nnegative repetition factor yields an empty sequence.\n\nThe ``/`` (division) and ``//`` (floor division) operators yield the\nquotient of their arguments.  The numeric arguments are first\nconverted to a common type. Integer division yields a float, while\nfloor division of integers results in an integer; the result is that\nof mathematical division with the \'floor\' function applied to the\nresult.  Division by zero raises the ``ZeroDivisionError`` exception.\n\nThe ``%`` (modulo) operator yields the remainder from the division of\nthe first argument by the second.  The numeric arguments are first\nconverted to a common type.  A zero right argument raises the\n``ZeroDivisionError`` exception.  The arguments may be floating point\nnumbers, e.g., ``3.14%0.7`` equals ``0.34`` (since ``3.14`` equals\n``4*0.7 + 0.34``.)  The modulo operator always yields a result with\nthe same sign as its second operand (or zero); the absolute value of\nthe result is strictly smaller than the absolute value of the second\noperand [1].\n\nThe floor division and modulo operators are connected by the following\nidentity: ``x == (x//y)*y + (x%y)``.  Floor division and modulo are\nalso connected with the built-in function ``divmod()``: ``divmod(x, y)\n== (x//y, x%y)``. [2].\n\nIn addition to performing the modulo operation on numbers, the ``%``\noperator is also overloaded by string objects to perform old-style\nstring formatting (also known as interpolation).  The syntax for\nstring formatting is described in the Python Library Reference,\nsection *Old String Formatting Operations*.\n\nThe floor division operator, the modulo operator, and the ``divmod()``\nfunction are not defined for complex numbers.  Instead, convert to a\nfloating point number using the ``abs()`` function if appropriate.\n\nThe ``+`` (addition) operator yields the sum of its arguments.  The\narguments must either both be numbers or both sequences of the same\ntype.  In the former case, the numbers are converted to a common type\nand then added together.  In the latter case, the sequences are\nconcatenated.\n\nThe ``-`` (subtraction) operator yields the difference of its\narguments.  The numeric arguments are first converted to a common\ntype.\n',
  'bitwise': '\nBinary bitwise operations\n*************************\n\nEach of the three bitwise operations has a different priority level:\n\n   and_expr ::= shift_expr | and_expr "&" shift_expr\n   xor_expr ::= and_expr | xor_expr "^" and_expr\n   or_expr  ::= xor_expr | or_expr "|" xor_expr\n\nThe ``&`` operator yields the bitwise AND of its arguments, which must\nbe integers.\n\nThe ``^`` operator yields the bitwise XOR (exclusive OR) of its\narguments, which must be integers.\n\nThe ``|`` operator yields the bitwise (inclusive) OR of its arguments,\nwhich must be integers.\n',
  'bltin-code-objects': '\nCode Objects\n************\n\nCode objects are used by the implementation to represent "pseudo-\ncompiled" executable Python code such as a function body. They differ\nfrom function objects because they don\'t contain a reference to their\nglobal execution environment.  Code objects are returned by the built-\nin ``compile()`` function and can be extracted from function objects\nthrough their ``__code__`` attribute. See also the ``code`` module.\n\nA code object can be executed or evaluated by passing it (instead of a\nsource string) to the ``exec()`` or ``eval()``  built-in functions.\n\nSee *The standard type hierarchy* for more information.\n',
  'bltin-ellipsis-object': '\nThe Ellipsis Object\n*******************\n\nThis object is commonly used by slicing (see *Slicings*).  It supports\nno special operations.  There is exactly one ellipsis object, named\n``Ellipsis`` (a built-in name).\n\nIt is written as ``Ellipsis`` or ``...``.\n',
- 'bltin-file-objects': '\nFile Objects\n************\n\nFile objects are implemented using C\'s ``stdio`` package and can be\ncreated with the built-in ``open()`` function.  File objects are also\nreturned by some other built-in functions and methods, such as\n``os.popen()`` and ``os.fdopen()`` and the ``makefile()`` method of\nsocket objects. Temporary files can be created using the ``tempfile``\nmodule, and high-level file operations such as copying, moving, and\ndeleting files and directories can be achieved with the ``shutil``\nmodule.\n\nWhen a file operation fails for an I/O-related reason, the exception\n``IOError`` is raised.  This includes situations where the operation\nis not defined for some reason, like ``seek()`` on a tty device or\nwriting a file opened for reading.\n\nFiles have the following methods:\n\nfile.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   You can avoid having to call this method explicitly if you use the\n   ``with`` statement.  For example, the following code will\n   automatically close *f* when the ``with`` block 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 context\n     manager for the ``with`` statement.  If your code is intended to\n     work with any file-like object, you can use the function\n     ``contextlib.closing()`` instead of using the object directly.\n\nfile.flush()\n\n   Flush the internal buffer, like ``stdio``\'s ``fflush()``.  This may\n   be a no-op on some file-like objects.\n\n   Note: ``flush()`` does not necessarily write the file\'s data to disk.\n     Use ``flush()`` followed by ``os.fsync()`` to ensure this\n     behavior.\n\nfile.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\n   friends.\n\n   Note: File-like objects which do not have a real file descriptor should\n     *not* provide this method!\n\nfile.isatty()\n\n   Return ``True`` if the file is connected to a tty(-like) device,\n   else ``False``.\n\n   Note: If a file-like object is not associated with a real file, this\n     method should *not* be implemented.\n\nfile.__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:\n   print(line)``), the ``__next__()`` method is called repeatedly.\n   This method returns the next input line, or raises\n   ``StopIteration`` when EOF is hit when the file is open for reading\n   (behavior is undefined when the file is open for writing).  In\n   order to make a ``for`` loop the most efficient way of looping over\n   the lines of a file (a very common operation), the ``__next__()``\n   method uses a hidden read-ahead buffer.  As a consequence of using\n   a read-ahead buffer, combining ``__next__()`` with other file\n   methods (like ``readline()``) does not work right.  However, using\n   ``seek()`` to reposition the file to an absolute position will\n   flush the read-ahead buffer.\n\nfile.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\n   than once in an effort to acquire as close to *size* bytes as\n   possible. Also note that when in non-blocking mode, less data than\n   was requested may be returned, even if no *size* parameter was\n   given.\n\nfile.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). [5]  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. An empty string is\n   returned *only* when EOF is encountered immediately.\n\n   Note: Unlike ``stdio``\'s ``fgets()``, the returned string contains null\n     characters (``\'\\0\'``) if they occurred in the input.\n\nfile.readlines([sizehint])\n\n   Read until EOF using ``readline()`` and return a list containing\n   the lines thus read.  If the optional *sizehint* argument is\n   present, instead of reading up to EOF, whole lines totalling\n   approximately *sizehint* bytes (possibly after rounding up to an\n   internal buffer size) are read.  Objects implementing a file-like\n   interface may choose to ignore *sizehint* if it cannot be\n   implemented, or cannot be implemented efficiently.\n\nfile.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\n   ``0`` (absolute file positioning); other values are ``os.SEEK_CUR``\n   or ``1`` (seek relative to the current position) and\n   ``os.SEEK_END`` or ``2``  (seek relative to the file\'s end).  There\n   is no return value.\n\n   For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by\n   two and ``f.seek(-3, os.SEEK_END)`` sets the position to the third\n   to 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\n   write.  If the file is only opened for writing in append mode (mode\n   ``\'a\'``), this method is essentially a no-op, but it remains useful\n   for files opened in append mode with reading enabled (mode\n   ``\'a+\'``).  If the file is opened in text mode (without ``\'b\'``),\n   only offsets returned by ``tell()`` are legal.  Use of other\n   offsets causes undefined behavior.\n\n   Note that not all file objects are seekable.\n\nfile.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\nfile.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\nfile.write(str)\n\n   Write a string to the file.  Due to buffering, the string may not\n   actually show up in the file until the ``flush()`` or ``close()``\n   method is called.\n\n   The meaning of the return value is not defined for every file-like\n   object. Some (mostly low-level) file-like objects may return the\n   number of bytes actually written, others return ``None``.\n\nfile.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\nFiles support the iterator protocol.  Each iteration returns the same\nresult as ``file.readline()``, and iteration ends when the\n``readline()`` method returns an empty string.\n\nFile objects also offer a number of other interesting attributes.\nThese are not required for file-like objects, but should be\nimplemented if they make sense for the particular object.\n\nfile.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\n   may not be available on all file-like objects.\n\nfile.encoding\n\n   The encoding that this file uses. When strings are written to a\n   file, they will be converted to byte strings using this encoding.\n   In addition, when the file is connected to a terminal, the\n   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\n   the file uses the system default encoding for converting strings.\n\nfile.errors\n\n   The Unicode error handler used along with the encoding.\n\nfile.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\nfile.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\n   may not be present on all file-like objects.\n\nfile.newlines\n\n   If Python was built with the *--with-universal-newlines* option to\n   **configure** (the default) this read-only attribute exists, and\n   for files opened in universal newline read mode it keeps track of\n   the types of newlines encountered while reading the file. The\n   values it can take are ``\'\\r\'``, ``\'\\n\'``, ``\'\\r\\n\'``, ``None``\n   (unknown, no newlines read yet) or a tuple containing all the\n   newline types seen, to indicate that multiple newline conventions\n   were encountered. For files not opened in universal newline read\n   mode the value of this attribute will be ``None``.\n',
  'bltin-null-object': "\nThe Null Object\n***************\n\nThis object is returned by functions that don't explicitly return a\nvalue.  It supports no special operations.  There is exactly one null\nobject, named ``None`` (a built-in name).\n\nIt is written as ``None``.\n",
  'bltin-type-objects': "\nType Objects\n************\n\nType objects represent the various object types.  An object's type is\naccessed by the built-in function ``type()``.  There are no special\noperations on types.  The standard module ``types`` defines names for\nall standard built-in types.\n\nTypes are written like this: ``<class 'int'>``.\n",
- 'booleans': '\nBoolean operations\n******************\n\nBoolean operations have the lowest priority of all Python operations:\n\n   expression             ::= conditional_expression | lambda_form\n   expression_nocond      ::= or_test | lambda_form_nocond\n   conditional_expression ::= or_test ["if" or_test "else" expression]\n   or_test                ::= and_test | or_test "or" and_test\n   and_test               ::= not_test | and_test "and" not_test\n   not_test               ::= comparison | "not" not_test\n\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: ``False``, ``None``, numeric zero of all types, and empty\nstrings and containers (including strings, tuples, lists,\ndictionaries, sets and frozensets).  All other values are interpreted\nas true.  User-defined objects can customize their truth value by\nproviding a ``__bool__()`` method.\n\nThe operator ``not`` yields ``True`` if its argument is false,\n``False`` otherwise.\n\nThe expression ``x if C else y`` first evaluates *C* (*not* *x*); if\n*C* is true, *x* is evaluated and its value is returned; otherwise,\n*y* is evaluated and its value is returned.\n\nThe expression ``x and y`` first evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\nThe expression ``x or y`` first evaluates *x*; if *x* is true, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\n(Note that neither ``and`` nor ``or`` restrict the value and type they\nreturn to ``False`` and ``True``, but rather return the last evaluated\nargument.  This is sometimes useful, e.g., if ``s`` is a string that\nshould be replaced by a default value if it is empty, the expression\n``s or \'foo\'`` yields the desired value.  Because ``not`` has to\ninvent a value anyway, it does not bother to return a value of the\nsame type as its argument, so e.g., ``not \'foo\'`` yields ``False``,\nnot ``\'\'``.)\n',
+ 'booleans': '\nBoolean operations\n******************\n\n   or_test  ::= and_test | or_test "or" and_test\n   and_test ::= not_test | and_test "and" not_test\n   not_test ::= comparison | "not" not_test\n\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: ``False``, ``None``, numeric zero of all types, and empty\nstrings and containers (including strings, tuples, lists,\ndictionaries, sets and frozensets).  All other values are interpreted\nas true.  User-defined objects can customize their truth value by\nproviding a ``__bool__()`` method.\n\nThe operator ``not`` yields ``True`` if its argument is false,\n``False`` otherwise.\n\nThe expression ``x and y`` first evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\nThe expression ``x or y`` first evaluates *x*; if *x* is true, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\n(Note that neither ``and`` nor ``or`` restrict the value and type they\nreturn to ``False`` and ``True``, but rather return the last evaluated\nargument.  This is sometimes useful, e.g., if ``s`` is a string that\nshould be replaced by a default value if it is empty, the expression\n``s or \'foo\'`` yields the desired value.  Because ``not`` has to\ninvent a value anyway, it does not bother to return a value of the\nsame type as its argument, so e.g., ``not \'foo\'`` yields ``False``,\nnot ``\'\'``.)\n',
  'break': '\nThe ``break`` statement\n***********************\n\n   break_stmt ::= "break"\n\n``break`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition\nwithin that loop.\n\nIt terminates the nearest enclosing loop, skipping the optional\n``else`` clause if the loop has one.\n\nIf a ``for`` loop is terminated by ``break``, the loop control target\nkeeps its current value.\n\nWhen ``break`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the loop.\n',
  'callable-types': '\nEmulating callable objects\n**************************\n\nobject.__call__(self[, args...])\n\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': '\nCalls\n*****\n\nA call calls a callable object (e.g., a function) with a possibly\nempty series of arguments:\n\n   call                 ::= primary "(" [argument_list [","] | comprehension] ")"\n   argument_list        ::= positional_arguments ["," keyword_arguments]\n                       ["," "*" expression] ["," keyword_arguments]\n                       ["," "**" expression]\n                     | keyword_arguments ["," "*" expression]\n                       ["," keyword_arguments] ["," "**" expression]\n                     | "*" expression ["," keyword_arguments] ["," "**" expression]\n                     | "**" expression\n   positional_arguments ::= expression ("," expression)*\n   keyword_arguments    ::= keyword_item ("," keyword_item)*\n   keyword_item         ::= identifier "=" expression\n\nA trailing comma may be present after the positional and keyword\narguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and all objects having a\n``__call__()`` method are callable).  All argument expressions are\nevaluated before the call is attempted.  Please refer to section\n*Function definitions* for the syntax of formal parameter lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows.  First, a list of unfilled slots is\ncreated for the formal parameters.  If there are N positional\narguments, they are placed in the first N slots.  Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on).  If the slot is\nalready filled, a ``TypeError`` exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is ``None``, it fills the slot).  When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition.  (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.)  If there are any\nunfilled slots for which no default value is specified, a\n``TypeError`` exception is raised.  Otherwise, the list of filled\nslots is used as the argument list for the call.\n\nNote: An implementation may provide builtin functions whose positional\n  parameters do not have names, even if they are \'named\' for the\n  purpose of documentation, and which therefore cannot be supplied by\n  keyword.  In CPython, this is the case for functions implemented in\n  C that use ``PyArg_ParseTuple()`` to parse their arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``*identifier`` is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``**identifier`` is present; in this case, that\nformal parameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax ``*expression`` appears in the function call,\n``expression`` must evaluate to a sequence.  Elements from this\nsequence are treated as if they were additional positional arguments;\nif there are positional arguments *x1*,..., *xN*, and ``expression``\nevaluates to a sequence *y1*, ..., *yM*, this is equivalent to a call\nwith M+N positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n\nA consequence of this is that although the ``*expression`` syntax may\nappear *after* some keyword arguments, it is processed *before* the\nkeyword arguments (and the ``**expression`` argument, if any -- see\nbelow).  So:\n\n   >>> def f(a, b):\n   ...  print(a, b)\n   ...\n   >>> f(b=1, *(2,))\n   2 1\n   >>> f(a=1, *(2,))\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n   TypeError: f() got multiple values for keyword argument \'a\'\n   >>> f(1, *(2,))\n   1 2\n\nIt is unusual for both keyword arguments and the ``*expression``\nsyntax to be used in the same call, so in practice this confusion does\nnot arise.\n\nIf the syntax ``**expression`` appears in the function call,\n``expression`` must evaluate to a mapping, the contents of which are\ntreated as additional keyword arguments.  In the case of a keyword\nappearing in both ``expression`` and as an explicit keyword argument,\na ``TypeError`` exception is raised.\n\nFormal parameters using the syntax ``*identifier`` or ``**identifier``\ncannot be used as positional argument slots or as keyword argument\nnames.\n\nA call always returns some value, possibly ``None``, unless it raises\nan exception.  How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n   The code block for the function is executed, passing it the\n   argument list.  The first thing the code block will do is bind the\n   formal parameters to the arguments; this is described in section\n   *Function definitions*.  When the code block executes a ``return``\n   statement, this specifies the return value of the function call.\n\na built-in function or method:\n   The result is up to the interpreter; see *Built-in Functions* for\n   the descriptions of built-in functions and methods.\n\na class object:\n   A new instance of that class is returned.\n\na 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   instance becomes the first argument.\n\na class instance:\n   The class must define a ``__call__()`` method; the effect is then\n   the same as if that method was called.\n',
+ 'calls': '\nCalls\n*****\n\nA call calls a callable object (e.g., a function) with a possibly\nempty series of arguments:\n\n   call                 ::= primary "(" [argument_list [","] | comprehension] ")"\n   argument_list        ::= positional_arguments ["," keyword_arguments]\n                       ["," "*" expression] ["," keyword_arguments]\n                       ["," "**" expression]\n                     | keyword_arguments ["," "*" expression]\n                       ["," keyword_arguments] ["," "**" expression]\n                     | "*" expression ["," keyword_arguments] ["," "**" expression]\n                     | "**" expression\n   positional_arguments ::= expression ("," expression)*\n   keyword_arguments    ::= keyword_item ("," keyword_item)*\n   keyword_item         ::= identifier "=" expression\n\nA trailing comma may be present after the positional and keyword\narguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and all objects having a\n``__call__()`` method are callable).  All argument expressions are\nevaluated before the call is attempted.  Please refer to section\n*Function definitions* for the syntax of formal parameter lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows.  First, a list of unfilled slots is\ncreated for the formal parameters.  If there are N positional\narguments, they are placed in the first N slots.  Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on).  If the slot is\nalready filled, a ``TypeError`` exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is ``None``, it fills the slot).  When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition.  (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.)  If there are any\nunfilled slots for which no default value is specified, a\n``TypeError`` exception is raised.  Otherwise, the list of filled\nslots is used as the argument list for the call.\n\n**CPython implementation detail:** An implementation may provide\nbuilt-in functions whose positional parameters do not have names, even\nif they are \'named\' for the purpose of documentation, and which\ntherefore cannot be supplied by keyword.  In CPython, this is the case\nfor functions implemented in C that use ``PyArg_ParseTuple()`` to\nparse their arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``*identifier`` is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``**identifier`` is present; in this case, that\nformal parameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax ``*expression`` appears in the function call,\n``expression`` must evaluate to a sequence.  Elements from this\nsequence are treated as if they were additional positional arguments;\nif there are positional arguments *x1*,..., *xN*, and ``expression``\nevaluates to a sequence *y1*, ..., *yM*, this is equivalent to a call\nwith M+N positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n\nA consequence of this is that although the ``*expression`` syntax may\nappear *after* some keyword arguments, it is processed *before* the\nkeyword arguments (and the ``**expression`` argument, if any -- see\nbelow).  So:\n\n   >>> def f(a, b):\n   ...  print(a, b)\n   ...\n   >>> f(b=1, *(2,))\n   2 1\n   >>> f(a=1, *(2,))\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n   TypeError: f() got multiple values for keyword argument \'a\'\n   >>> f(1, *(2,))\n   1 2\n\nIt is unusual for both keyword arguments and the ``*expression``\nsyntax to be used in the same call, so in practice this confusion does\nnot arise.\n\nIf the syntax ``**expression`` appears in the function call,\n``expression`` must evaluate to a mapping, the contents of which are\ntreated as additional keyword arguments.  In the case of a keyword\nappearing in both ``expression`` and as an explicit keyword argument,\na ``TypeError`` exception is raised.\n\nFormal parameters using the syntax ``*identifier`` or ``**identifier``\ncannot be used as positional argument slots or as keyword argument\nnames.\n\nA call always returns some value, possibly ``None``, unless it raises\nan exception.  How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n   The code block for the function is executed, passing it the\n   argument list.  The first thing the code block will do is bind the\n   formal parameters to the arguments; this is described in section\n   *Function definitions*.  When the code block executes a ``return``\n   statement, this specifies the return value of the function call.\n\na built-in function or method:\n   The result is up to the interpreter; see *Built-in Functions* for\n   the descriptions of built-in functions and methods.\n\na class object:\n   A new instance of that class is returned.\n\na 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   instance becomes the first argument.\n\na class instance:\n   The class must define a ``__call__()`` method; the effect is then\n   the same as if that method was called.\n',
  'class': '\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\nClasses can also be decorated; as with functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by instances. Instance variables can\nbe set in a method with ``self.name = value``.  Both class and\ninstance variables are accessible through the notation\n"``self.name``", and an instance variable hides a class variable with\nthe same name when accessed in this way.  Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  Descriptors can be used to create\ninstance variables with different implementation details.\n\nSee also:\n\n   **PEP 3129** - Class Decorators\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    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 function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\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': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects.  The objects need not have the same type.\nIf both are numbers, they are converted to a common type.  Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes.  You can control comparison behavior of objects of non-builtin\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n  are identical to themselves, ``x is x`` but are not equal to\n  themselves, ``x != x``.  Additionally, comparing any value to a\n  not-a-number value will return ``False``.  For example, both ``3 <\n  float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n  values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n  (the result of the built-in function ``ord()``) of their characters.\n  [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n  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\n  If not equal, the sequences are ordered the same as their first\n  differing elements.  For example, ``[1,2,x] <= [1,2,y]`` has the\n  same value as ``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  ``(key, value)`` lists compare equal. [4] Outcomes other than\n  equality are resolved consistently, but are not otherwise defined.\n  [5]\n\n* Sets and frozensets define comparison operators to mean subset and\n  superset tests.  Those relations do not define total orderings (the\n  two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering.\n  For example, ``min()``, ``max()``, and ``sorted()`` produce\n  undefined results given a list of sets as inputs.\n\n* Most other objects of builtin types compare unequal unless they are\n  the same object; the choice whether one object is considered smaller\n  or larger than another one is made arbitrarily but consistently\n  within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison.  Most\nnumeric types can be compared with one another, but comparisons of\n``float`` and ``Decimal`` are not supported to avoid the inevitable\nconfusion arising from representation issues such as ``float(\'1.1\')``\nbeing inexactly represented and therefore not exactly equal to\n``Decimal(\'1.1\')`` which is.  When cross-type comparison is not\nsupported, the comparison method returns ``NotImplemented``.  This can\ncreate the illusion of non-transitivity between supported cross-type\ncomparisons and unsupported comparisons.  For example, ``Decimal(2) ==\n2`` and *2 == float(2)`* but ``Decimal(2) != float(2)``.\n\nThe operators ``in`` and ``not in`` test for membership.  ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise.  ``x\nnot in s`` returns the negation of ``x in s``.  All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for val\ne in y)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*.  An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` and do\ndefine ``__getitem__()``, ``x in y`` is true if and only if there is a\nnon-negative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception.  (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object.  ``x is\nnot y`` yields the inverse truth value. [6]\n',
- 'compound': '\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way.  In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe ``if``, ``while`` and ``for`` statements implement traditional\ncontrol flow constructs.  ``try`` specifies exception handlers and/or\ncleanup code for a group of statements, while the ``with`` statement\nallows the execution of initialization and finalization code around a\nblock of code.  Function and class definitions are also syntactically\ncompound statements.\n\nCompound statements consist of one or more \'clauses.\'  A clause\nconsists of a header and a \'suite.\'  The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon.  A suite is a group of statements controlled by a\nclause.  A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines.  Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which ``if`` clause a following ``else`` clause would belong:\n\n   if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n``print()`` calls are executed:\n\n   if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n   compound_stmt ::= if_stmt\n                     | while_stmt\n                     | for_stmt\n                     | try_stmt\n                     | with_stmt\n                     | funcdef\n                     | classdef\n   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n   statement     ::= stmt_list NEWLINE | compound_stmt\n   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a ``NEWLINE`` possibly followed by\na ``DEDENT``.  Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n``expression_list``.  The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop.  Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n  (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  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  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     for x in a[:]:\n         if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           N = None\n           del N\n\nThat means that you have to assign the exception to a different name\nif you want to be able to refer to it after the except clause.  The\nreason for this is that with the traceback attached to them,\nexceptions will form a reference cycle with the stack frame, keeping\nall locals in that frame alive until the next garbage collection\noccurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting\nof: ``exc_type``, the exception class; ``exc_value``, the exception\ninstance; ``exc_traceback``, a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. ``sys.exc_info()`` values are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__enter__()`` method is invoked.\n\n3. 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\n     be 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 5 below.\n\n4. The suite is executed.\n\n5. 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,\n   three ``None`` arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the ``__exit__()`` method was false, the exception is\n   reraised.  If the return value was true, the exception is\n   suppressed, and execution continues with the statement following\n   the ``with`` 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\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" [parameter] ("," defparameter)*\n                      [, "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more parameters have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding argument may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that that same "pre-computed" value is\nused for each call.  This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended.  A way around this is to use ``None`` as the\ndefault, 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           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple.  If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name.  Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``.  Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list.  These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code.  The presence of annotations does not change the\nsemantics of a function.  The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda forms,\ndescribed in section *Lambdas*.  Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form.  The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around.  Free variables used in the\nnested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\nClasses can also be decorated; as with functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by instances. Instance variables can\nbe set in a method with ``self.name = value``.  Both class and\ninstance variables are accessible through the notation\n"``self.name``", and an instance variable hides a class variable with\nthe same name when accessed in this way.  Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  Descriptors can be used to create\ninstance variables with different implementation details.\n\nSee also:\n\n   **PEP 3129** - Class Decorators\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    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 function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\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': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects.  The objects need not have the same type.\nIf both are numbers, they are converted to a common type.  Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes.  You can control comparison behavior of objects of non-built-in\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n  are identical to themselves, ``x is x`` but are not equal to\n  themselves, ``x != x``.  Additionally, comparing any value to a\n  not-a-number value will return ``False``.  For example, both ``3 <\n  float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n  values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n  (the result of the built-in function ``ord()``) of their characters.\n  [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n  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\n  If not equal, the sequences are ordered the same as their first\n  differing elements.  For example, ``[1,2,x] <= [1,2,y]`` has the\n  same value as ``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 they have the\n  same ``(key, value)`` pairs. Order comparisons ``(\'<\', \'<=\', \'>=\',\n  \'>\')`` raise ``TypeError``.\n\n* Sets and frozensets define comparison operators to mean subset and\n  superset tests.  Those relations do not define total orderings (the\n  two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering.\n  For example, ``min()``, ``max()``, and ``sorted()`` produce\n  undefined results given a list of sets as inputs.\n\n* Most other objects of built-in types compare unequal unless they are\n  the same object; the choice whether one object is considered smaller\n  or larger than another one is made arbitrarily but consistently\n  within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison.  Most\nnumeric types can be compared with one another, but comparisons of\n``float`` and ``Decimal`` are not supported to avoid the inevitable\nconfusion arising from representation issues such as ``float(\'1.1\')``\nbeing inexactly represented and therefore not exactly equal to\n``Decimal(\'1.1\')`` which is.  When cross-type comparison is not\nsupported, the comparison method returns ``NotImplemented``.  This can\ncreate the illusion of non-transitivity between supported cross-type\ncomparisons and unsupported comparisons.  For example, ``Decimal(2) ==\n2`` and *2 == float(2)`* but ``Decimal(2) != float(2)``.\n\nThe operators ``in`` and ``not in`` test for membership.  ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise.  ``x\nnot in s`` returns the negation of ``x in s``.  All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\ny)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*.  An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``.  If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, 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-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception.  (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object.  ``x is\nnot y`` yields the inverse truth value. [4]\n',
+ 'compound': '\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way.  In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe ``if``, ``while`` and ``for`` statements implement traditional\ncontrol flow constructs.  ``try`` specifies exception handlers and/or\ncleanup code for a group of statements, while the ``with`` statement\nallows the execution of initialization and finalization code around a\nblock of code.  Function and class definitions are also syntactically\ncompound statements.\n\nCompound statements consist of one or more \'clauses.\'  A clause\nconsists of a header and a \'suite.\'  The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon.  A suite is a group of statements controlled by a\nclause.  A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines.  Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which ``if`` clause a following ``else`` clause would belong:\n\n   if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n``print()`` calls are executed:\n\n   if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n   compound_stmt ::= if_stmt\n                     | while_stmt\n                     | for_stmt\n                     | try_stmt\n                     | with_stmt\n                     | funcdef\n                     | classdef\n   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n   statement     ::= stmt_list NEWLINE | compound_stmt\n   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a ``NEWLINE`` possibly followed by\na ``DEDENT``.  Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n``expression_list``.  The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop.  Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n  (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  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  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     for x in a[:]:\n         if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting\nof: ``exc_type``, the exception class; ``exc_value``, the exception\ninstance; ``exc_traceback``, a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. ``sys.exc_info()`` values are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. 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\n     be 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\n5. The suite is executed.\n\n6. 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,\n   three ``None`` arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the ``__exit__()`` method was false, the exception is\n   reraised.  If the return value was true, the exception is\n   suppressed, and execution continues with the statement following\n   the ``with`` 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\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" [parameter] ("," defparameter)*\n                      [, "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more parameters have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding argument may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that that same "pre-computed" value is\nused for each call.  This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended.  A way around this is to use ``None`` as the\ndefault, 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           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple.  If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name.  Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``.  Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list.  These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code.  The presence of annotations does not change the\nsemantics of a function.  The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda forms,\ndescribed in section *Lambdas*.  Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form.  The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around.  Free variables used in the\nnested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\nClasses can also be decorated; as with functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by instances. Instance variables can\nbe set in a method with ``self.name = value``.  Both class and\ninstance variables are accessible through the notation\n"``self.name``", and an instance variable hides a class variable with\nthe same name when accessed in this way.  Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  Descriptors can be used to create\ninstance variables with different implementation details.\n\nSee also:\n\n   **PEP 3129** - Class Decorators\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    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 function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\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',
  'context-managers': '\nWith Statement Context Managers\n*******************************\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code.  Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__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   specified in the ``as`` clause of the statement, if any.\n\nobject.__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   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   exception (i.e., prevent it from being propagated), it should\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   exception; this is the caller\'s responsibility.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n',
  'continue': '\nThe ``continue`` statement\n**************************\n\n   continue_stmt ::= "continue"\n\n``continue`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition or\n``finally`` clause within that loop.  It continues with the next cycle\nof the nearest enclosing loop.\n\nWhen ``continue`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nstarting the next loop cycle.\n',
  'conversions': '\nArithmetic conversions\n**********************\n\nWhen a description of an arithmetic operator below uses the phrase\n"the numeric arguments are converted to a common type," this means\nthat the operator implementation for built-in types works that way:\n\n* If either argument is a complex number, the other is converted to\n  complex;\n\n* otherwise, if either argument is a floating point number, the other\n  is converted to floating point;\n\n* otherwise, both must be integers and no conversion is necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator).  Extensions must define their own\nconversion behavior.\n',
- 'customization': '\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\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   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 (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\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   necessary before returning it.\n\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   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   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  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__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__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,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__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   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\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\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled 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.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     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 ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     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\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   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   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\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   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see the Total Ordering recipe in the ASPN cookbook.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\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   considered true if its result is nonzero. If a class defines\n   neither ``__len__()`` nor ``__bool__()``, all its instances are\n   considered true.\n',
- 'debugger': '\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs.  It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame.  It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible --- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source.  The extension interface uses the modules ``bdb``\n(undocumented) and ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> pdb.run(\'mymodule.test()\')\n   > <string>(0)?()\n   (Pdb) continue\n   > <string>(1)?()\n   (Pdb) continue\n   NameError: \'spam\'\n   > <string>(1)?()\n   (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n   python -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally. After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program. Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n   import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger.  You can then\nstep through the code following this statement, and continue running\nwithout debugger using the ``c`` command.\n\nThe typical usage to inspect a crashed program is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> mymodule.test()\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n     File "./mymodule.py", line 4, in test\n       test2()\n     File "./mymodule.py", line 3, in test2\n       print(spam)\n   NameError: spam\n   >>> pdb.pm()\n   > ./mymodule.py(3)test2()\n   -> print(spam)\n   (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement[, globals[, locals]])\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   statement using ``step`` or ``next`` (all these commands are\n   explained below).  The optional *globals* and *locals* arguments\n   specify the environment in which the code is executed; by default\n   the dictionary of the module ``__main__`` is used.  (See the\n   explanation of the built-in ``exec()`` or ``eval()`` functions.)\n\npdb.runeval(expression[, globals[, locals]])\n\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\npdb.runcall(function[, argument, ...])\n\n   Call the *function* (a function or method object, not a string)\n   with the given arguments.  When ``runcall()`` returns, it returns\n   whatever the function call returned.  The debugger prompt appears\n   as soon as the function is entered.\n\npdb.set_trace()\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   fails).\n\npdb.post_mortem([traceback])\n\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 if the\n   default is to be used).\n\npdb.pm()\n\n   Enter post-mortem debugging of the traceback found in\n   ``sys.last_traceback``.\n\nThe ``run_*`` functions and ``set_trace()`` are aliases for\ninstantiating the ``Pdb`` class and calling the method of the same\nname.  If you want to access further features, you have to do this\nyourself:\n\nclass 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   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   originate in a module that matches one of these patterns. [1]\n\n   Example call to enable tracing with *skip*:\n\n      import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n   New in version 3.1: The *skip* argument.\n\n   run(statement[, globals[, locals]])\n   runeval(expression[, globals[, locals]])\n   runcall(function[, argument, ...])\n   set_trace()\n\n      See the documentation for the functions explained above.\n',
+ 'customization': '\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\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   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 (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\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   necessary before returning it.\n\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   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   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  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__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__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,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__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   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\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\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled 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.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     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 ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     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\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   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   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\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   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   ``bool()``; should return ``False`` or ``True``.  When this method\n   is not defined, ``__len__()`` is called, if it is defined, and the\n   object is considered true if its result is nonzero.  If a class\n   defines neither ``__len__()`` nor ``__bool__()``, all its instances\n   are considered true.\n',
+ 'debugger': '\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs.  It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame.  It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible -- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source.  The extension interface uses the modules ``bdb``\nand ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> pdb.run(\'mymodule.test()\')\n   > <string>(0)?()\n   (Pdb) continue\n   > <string>(1)?()\n   (Pdb) continue\n   NameError: \'spam\'\n   > <string>(1)?()\n   (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n   python3 -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally.  After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program.  Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 3.2: ``pdb.py`` now accepts a ``-c`` option that\nexecutes commands as if given in a ``.pdbrc`` file, see *Debugger\nCommands*.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n   import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger.  You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the ``continue`` command.\n\nThe typical usage to inspect a crashed program is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> mymodule.test()\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n     File "./mymodule.py", line 4, in test\n       test2()\n     File "./mymodule.py", line 3, in test2\n       print(spam)\n   NameError: spam\n   >>> pdb.pm()\n   > ./mymodule.py(3)test2()\n   -> print(spam)\n   (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement, globals=None, locals=None)\n\n   Execute the *statement* (given as a string or a code object) under\n   debugger control.  The debugger prompt appears before any code is\n   executed; you can set breakpoints and type ``continue``, or you can\n   step through the statement using ``step`` or ``next`` (all these\n   commands are explained below).  The optional *globals* and *locals*\n   arguments specify the environment in which the code is executed; by\n   default the dictionary of the module ``__main__`` is used.  (See\n   the explanation of the built-in ``exec()`` or ``eval()``\n   functions.)\n\npdb.runeval(expression, globals=None, locals=None)\n\n   Evaluate the *expression* (given as a string or a code object)\n   under debugger control.  When ``runeval()`` returns, it returns the\n   value of the expression.  Otherwise this function is similar to\n   ``run()``.\n\npdb.runcall(function, *args, **kwds)\n\n   Call the *function* (a function or method object, not a string)\n   with the given arguments.  When ``runcall()`` returns, it returns\n   whatever the function call returned.  The debugger prompt appears\n   as soon as the function is entered.\n\npdb.set_trace()\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   fails).\n\npdb.post_mortem(traceback=None)\n\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 if the\n   default is to be used).\n\npdb.pm()\n\n   Enter post-mortem debugging of the traceback found in\n   ``sys.last_traceback``.\n\nThe ``run_*`` functions and ``set_trace()`` are aliases for\ninstantiating the ``Pdb`` class and calling the method of the same\nname.  If you want to access further features, you have to do this\nyourself:\n\nclass 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   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   originate in a module that matches one of these patterns. [1]\n\n   Example call to enable tracing with *skip*:\n\n      import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n   New in version 3.1: The *skip* argument.\n\n   run(statement, globals=None, locals=None)\n   runeval(expression, globals=None, locals=None)\n   runcall(function, *args, **kwds)\n   set_trace()\n\n      See the documentation for the functions explained above.\n',
  'del': '\nThe ``del`` statement\n*********************\n\n   del_stmt ::= "del" target_list\n\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather that spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a ``global``\nstatement in the same code block.  If the name is unbound, a\n``NameError`` exception will be raised.\n\nIt is illegal to delete a name from the local namespace if it occurs\nas a free variable in a nested block.\n\nDeletion of attribute references, subscriptions and slicings is passed\nto the primary object involved; deletion of a slicing is in general\nequivalent to assignment of an empty slice of the right type (but even\nthis is determined by the sliced object).\n',
  'dict': '\nDictionary displays\n*******************\n\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n\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\nA dictionary display yields a new dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is given, they are\nevaluated from left to right to define the entries of the dictionary:\neach key object is used as a key into the dictionary to store the\ncorresponding datum.  This means that you can specify the same key\nmultiple times in the key/datum list, and the final dictionary\'s value\nfor that key will be the last one given.\n\nA dict comprehension, in contrast to list and set comprehensions,\nneeds two expressions separated with a colon followed by the usual\n"for" and "if" clauses. When the comprehension is run, the resulting\nkey and value elements are inserted in the new dictionary in the order\nthey are produced.\n\nRestrictions on the types of the key values are listed earlier in\nsection *The standard type hierarchy*.  (To summarize, the key type\nshould be *hashable*, which excludes all mutable objects.)  Clashes\nbetween duplicate keys are not detected; the last datum (textually\nrightmost in the display) stored for a given key value prevails.\n',
  'dynamic-features': '\nInteraction with dynamic features\n*********************************\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n',
  'else': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n',
  'exceptions': '\nExceptions\n**********\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions.  An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero).  A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement.  The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop.  In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances.  The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof.  The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API.  Their contents\n  may change from one version of Python to the next without warning\n  and should not be relied on by code which will run under multiple\n  versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n    operations is not available at the time the module is compiled.\n',
- 'execmodel': '\nExecution model\n***************\n\n\nNaming and binding\n==================\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the \'**-c**\' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block\'s execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or :keyword.`except` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtin namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtin namespace\nis searched.  The global statement must precede all uses of the name.\n\nThe built-in namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\nNote: Users should not touch ``__builtins__``; it is strictly an\n  implementation detail.  Users wanting to override values in the\n  built-in namespace should ``import`` the ``builtins`` module and\n  modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe global statement has the same scope as a name binding operation in\nthe same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions.  An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero).  A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement.  The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop.  In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances.  The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof.  The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API.  Their contents\n  may change from one version of Python to the next without warning\n  and should not be relied on by code which will run under multiple\n  versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n    operations is not available at the time the module is compiled.\n',
+ 'execmodel': '\nExecution model\n***************\n\n\nNaming and binding\n==================\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the \'**-c**\' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block\'s execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or :keyword.`except` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtins\nnamespace is searched.  The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe global statement has the same scope as a name binding operation in\nthe same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions.  An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero).  A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement.  The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop.  In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances.  The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof.  The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API.  Their contents\n  may change from one version of Python to the next without warning\n  and should not be relied on by code which will run under multiple\n  versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n    operations is not available at the time the module is compiled.\n',
  'exprlists': '\nExpression lists\n****************\n\n   expression_list ::= expression ( "," expression )* [","]\n\nAn expression list containing at least one comma yields a tuple.  The\nlength of the tuple is the number of expressions in the list.  The\nexpressions are evaluated from left to right.\n\nThe trailing comma is required only to create a single tuple (a.k.a. a\n*singleton*); it is optional in all other cases.  A single expression\nwithout a trailing comma doesn\'t create a tuple, but rather yields the\nvalue of that expression. (To create an empty tuple, use an empty pair\nof parentheses: ``()``.)\n',
  'floating': '\nFloating point literals\n***********************\n\nFloating point literals are described by the following lexical\ndefinitions:\n\n   floatnumber   ::= pointfloat | exponentfloat\n   pointfloat    ::= [intpart] fraction | intpart "."\n   exponentfloat ::= (intpart | pointfloat) exponent\n   intpart       ::= digit+\n   fraction      ::= "." digit+\n   exponent      ::= ("e" | "E") ["+" | "-"] digit+\n\nNote that the integer and exponent parts are always interpreted using\nradix 10. For example, ``077e010`` is legal, and denotes the same\nnumber as ``77e10``. The allowed range of floating point literals is\nimplementation-dependent. Some examples of floating point literals:\n\n   3.14    10.    .001    1e100    3.14e-10    0e0\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator ``-`` and the\nliteral ``1``.\n',
  'for': '\nThe ``for`` statement\n*********************\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n``expression_list``.  The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop.  Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n  (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  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  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     for x in a[:]:\n         if x < 0: a.remove(x)\n',
- 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax.)\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output.  If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe 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      arg_name          ::= (identifier | integer)?\n      attribute_name    ::= identifier\n      element_index     ::= integer\n      conversion        ::= "r" | "s" | "a"\n      format_spec       ::= <described in the next section>\n\nIn less formal terms, the replacement field starts with a *field_name*\nthat specifies the object whose value is to be formatted and inserted\ninto the output instead of the replacement field. The *field_name* is\noptionally followed by a  *conversion* field, which is preceded by an\nexclamation point ``\'!\'``, and a *format_spec*, which is preceded by a\ncolon ``\':\'``.  These specify a non-default format for the replacement\nvalue.\n\nThe *field_name* itself begins with an *arg_name* that is either\neither a number or a keyword.  If it\'s a number, it refers to a\npositional argument, and if it\'s a keyword, it refers to a named\nkeyword argument.  If the numerical arg_names in a format string are\n0, 1, 2, ... in sequence, they can all be omitted (not just some) and\nthe numbers 0, 1, 2, ... will be automatically inserted in that order.\nThe *arg_name* can be followed by any number of index or attribute\nexpressions. An expression of the form ``\'.name\'`` selects the named\nattribute using ``getattr()``, while an expression of the form\n``\'[index]\'`` does an index lookup using ``__getitem__()``.\n\nSome simple format string examples:\n\n   "First, thou shalt count to {0}" # References first positional argument\n   "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 argument \'name\'\n   "Weight in tons {0.weight}"      # \'weight\' attribute of first positional arg\n   "Units destroyed: {players[0]}"  # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself.  However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting.  By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nThree conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, ``\'!r\'`` which calls ``repr()`` and ``\'!a\'``\nwhich calls ``ascii()``.\n\nSome examples:\n\n   "Harold\'s a clever {0!s}"        # Calls str() on the argument first\n   "Bring out the holy {name!r}"    # Calls repr() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on.  Each value type can define it\'s\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed.  The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nFor example, suppose you wanted to have a replacement field whose\nfield width is determined by another variable:\n\n   "A man with two {0:{1}}".format("noses", 10)\n\nThis would first evaluate the inner replacement field, making the\nformat string effectively:\n\n   "A man with two {0:10}"\n\nThen the outer replacement field would be evaluated, producing:\n\n   "noses     "\n\nWhich is substituted into the string, yielding:\n\n   "A man with two noses     "\n\n(The extra space is because we specified a field width of 10, and\nbecause left alignment is the default for strings.)\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*.)  They can also be passed directly to the\nbuiltin ``format()`` function.  Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value.\n\nThe general form of a *standard format specifier* is:\n\n   format_spec ::= [[fill]align][sign][#][0][width][.precision][type]\n   fill        ::= <a character other than \'}\'>\n   align       ::= "<" | ">" | "=" | "^"\n   sign        ::= "+" | "-" | " "\n   width       ::= integer\n   precision   ::= integer\n   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"\n\nThe *fill* character can be any character other than \'}\' (which\nsignifies the end of the field).  The presence of a fill character is\nsignaled by the *next* character, which must be one of the alignment\noptions. If the second character of *format_spec* is not a valid\nalignment option, then it is assumed that both the fill character and\nthe alignment option are absent.\n\nThe meaning of the various alignment options is as follows:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'<\'``   | Forces the field to be left-aligned within the available   |\n   |           | space (This is the default.)                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'>\'``   | Forces the field to be right-aligned within the available  |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n   | ``\'=\'``   | Forces the padding to be placed after the sign (if any)    |\n   |           | but before the digits.  This is used for printing fields   |\n   |           | in the form \'+000000120\'. This alignment option is only    |\n   |           | valid for numeric types.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'^\'``   | Forces the field to be centered within the available       |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'+\'``   | indicates that a sign should be used for both positive as  |\n   |           | well as negative numbers.                                  |\n   +-----------+------------------------------------------------------------+\n   | ``\'-\'``   | indicates that a sign should be used only for negative     |\n   |           | numbers (this is the default behavior).                    |\n   +-----------+------------------------------------------------------------+\n   | space     | indicates that a leading space should be used on positive  |\n   |           | numbers, and a minus sign on negative numbers.             |\n   +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output.  If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\n*width* is a decimal integer defining the minimum field width.  If not\nspecified, then the field width will be determined by the content.\n\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding.  This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available integer presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'b\'``   | Binary format. Outputs the number in base 2.               |\n   +-----------+------------------------------------------------------------+\n   | ``\'c\'``   | Character. Converts the integer to the corresponding       |\n   |           | unicode character before printing.                         |\n   +-----------+------------------------------------------------------------+\n   | ``\'d\'``   | Decimal Integer. Outputs the number in base 10.            |\n   +-----------+------------------------------------------------------------+\n   | ``\'o\'``   | Octal format. Outputs the number in base 8.                |\n   +-----------+------------------------------------------------------------+\n   | ``\'x\'``   | Hex format. Outputs the number in base 16, using lower-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'X\'``   | Hex format. Outputs the number in base 16, using upper-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'d\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'d\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nThe available presentation types for floating point and decimal values\nare:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'e\'``   | Exponent notation. Prints the number in scientific         |\n   |           | notation using the letter \'e\' to indicate the exponent.    |\n   +-----------+------------------------------------------------------------+\n   | ``\'E\'``   | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n   |           | case \'E\' as the separator character.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'f\'``   | Fixed point. Displays the number as a fixed-point number.  |\n   +-----------+------------------------------------------------------------+\n   | ``\'F\'``   | Fixed point. Same as ``\'f\'``, but converts ``nan`` to      |\n   |           | ``NAN`` and ``inf`` to ``INF``.                            |\n   +-----------+------------------------------------------------------------+\n   | ``\'g\'``   | General format. This prints the number as a fixed-point    |\n   |           | number, unless the number is too large, in which case it   |\n   |           | switches to ``\'e\'`` exponent notation. Infinity and NaN    |\n   |           | values are formatted as ``inf``, ``-inf`` and ``nan``,     |\n   |           | respectively.                                              |\n   +-----------+------------------------------------------------------------+\n   | ``\'G\'``   | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n   |           | if the number gets to large. The representations of        |\n   |           | infinity and NaN are uppercased, too.                      |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'g\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'%\'``   | Percentage. Multiplies the number by 100 and displays in   |\n   |           | fixed (``\'f\'``) format, followed by a percent sign.        |\n   +-----------+------------------------------------------------------------+\n   | None      | Similar to ``\'g\'``, except with at least one digit past    |\n   |           | the decimal point and a default precision of 12. This is   |\n   |           | intended to match ``str()``, except you can add the other  |\n   |           | format modifiers.                                          |\n   +-----------+------------------------------------------------------------+\n',
+ 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output.  If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe 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      arg_name          ::= [identifier | integer]\n      attribute_name    ::= identifier\n      element_index     ::= integer | index_string\n      index_string      ::= <any source character except "]"> +\n      conversion        ::= "r" | "s" | "a"\n      format_spec       ::= <described in the next section>\n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a  *conversion* field, which is\npreceded by an exclamation point ``\'!\'``, and a *format_spec*, which\nis preceded by a colon ``\':\'``.  These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either\neither a number or a keyword.  If it\'s a number, it refers to a\npositional argument, and if it\'s a keyword, it refers to a named\nkeyword argument.  If the numerical arg_names in a format string are\n0, 1, 2, ... in sequence, they can all be omitted (not just some) and\nthe numbers 0, 1, 2, ... will be automatically inserted in that order.\nThe *arg_name* can be followed by any number of index or attribute\nexpressions. An expression of the form ``\'.name\'`` selects the named\nattribute using ``getattr()``, while an expression of the form\n``\'[index]\'`` does an index lookup using ``__getitem__()``.\n\nChanged in version 3.1: The positional argument specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to ``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n   "First, thou shalt count to {0}" # References first positional argument\n   "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 argument \'name\'\n   "Weight in tons {0.weight}"      # \'weight\' attribute of first positional arg\n   "Units destroyed: {players[0]}"  # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself.  However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting.  By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nThree conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, ``\'!r\'`` which calls ``repr()`` and ``\'!a\'``\nwhich calls ``ascii()``.\n\nSome examples:\n\n   "Harold\'s a clever {0!s}"        # Calls str() on the argument first\n   "Bring out the holy {name!r}"    # Calls repr() on the argument first\n   "More {!a}"                      # Calls ascii() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on.  Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed.  The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*).  They can also be passed directly to the\nbuilt-in ``format()`` function.  Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value. A non-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n   format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n   fill        ::= <a character other than \'}\'>\n   align       ::= "<" | ">" | "=" | "^"\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\nThe *fill* character can be any character other than \'}\' (which\nsignifies the end of the field).  The presence of a fill character is\nsignaled by the *next* character, which must be one of the alignment\noptions. If the second character of *format_spec* is not a valid\nalignment option, then it is assumed that both the fill character and\nthe alignment option are absent.\n\nThe meaning of the various alignment options is as follows:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'<\'``   | Forces the field to be left-aligned within the available   |\n   |           | space (this is the default).                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'>\'``   | Forces the field to be right-aligned within the available  |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n   | ``\'=\'``   | Forces the padding to be placed after the sign (if any)    |\n   |           | but before the digits.  This is used for printing fields   |\n   |           | in the form \'+000000120\'. This alignment option is only    |\n   |           | valid for numeric types.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'^\'``   | Forces the field to be centered within the available       |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'+\'``   | indicates that a sign should be used for both positive as  |\n   |           | well as negative numbers.                                  |\n   +-----------+------------------------------------------------------------+\n   | ``\'-\'``   | indicates that a sign should be used only for negative     |\n   |           | numbers (this is the default behavior).                    |\n   +-----------+------------------------------------------------------------+\n   | space     | indicates that a leading space should be used on positive  |\n   |           | numbers, and a minus sign on negative numbers.             |\n   +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output.  If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 3.1: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width.  If not\nspecified, then the field width will be determined by the content.\n\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding.  This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'s\'``   | String format. This is the default type for strings and    |\n   |           | may be omitted.                                            |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'s\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'b\'``   | Binary format. Outputs the number in base 2.               |\n   +-----------+------------------------------------------------------------+\n   | ``\'c\'``   | Character. Converts the integer to the corresponding       |\n   |           | unicode character before printing.                         |\n   +-----------+------------------------------------------------------------+\n   | ``\'d\'``   | Decimal Integer. Outputs the number in base 10.            |\n   +-----------+------------------------------------------------------------+\n   | ``\'o\'``   | Octal format. Outputs the number in base 8.                |\n   +-----------+------------------------------------------------------------+\n   | ``\'x\'``   | Hex format. Outputs the number in base 16, using lower-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'X\'``   | Hex format. Outputs the number in base 16, using upper-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'d\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'d\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'e\'``   | Exponent notation. Prints the number in scientific         |\n   |           | notation using the letter \'e\' to indicate the exponent.    |\n   +-----------+------------------------------------------------------------+\n   | ``\'E\'``   | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n   |           | case \'E\' as the separator character.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'f\'``   | Fixed point. Displays the number as a fixed-point number.  |\n   +-----------+------------------------------------------------------------+\n   | ``\'F\'``   | Fixed point. Same as ``\'f\'``, but converts ``nan`` to      |\n   |           | ``NAN`` and ``inf`` to ``INF``.                            |\n   +-----------+------------------------------------------------------------+\n   | ``\'g\'``   | General format.  For a given precision ``p >= 1``, this    |\n   |           | rounds the number to ``p`` significant digits and then     |\n   |           | formats the result in either fixed-point format or in      |\n   |           | scientific notation, depending on its magnitude.  The      |\n   |           | precise rules are as follows: suppose that the result      |\n   |           | formatted with presentation type ``\'e\'`` and precision     |\n   |           | ``p-1`` would have exponent ``exp``.  Then if ``-4 <= exp  |\n   |           | < p``, the number is formatted with presentation type      |\n   |           | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number   |\n   |           | is formatted with presentation type ``\'e\'`` and precision  |\n   |           | ``p-1``. In both cases insignificant trailing zeros are    |\n   |           | removed from the significand, and the decimal point is     |\n   |           | also removed if there are no remaining digits following    |\n   |           | it.  Postive and negative infinity, positive and negative  |\n   |           | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n   |           | ``-0`` and ``nan`` respectively, regardless of the         |\n   |           | precision.  A precision of ``0`` is treated as equivalent  |\n   |           | to a precision of ``1``.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'G\'``   | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n   |           | if the number gets too large. The representations of       |\n   |           | infinity and NaN are uppercased, too.                      |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'g\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'%\'``   | Percentage. Multiplies the number by 100 and displays in   |\n   |           | fixed (``\'f\'``) format, followed by a percent sign.        |\n   +-----------+------------------------------------------------------------+\n   | None      | Similar to ``\'g\'``, except with at least one digit past    |\n   |           | the decimal point and a default precision of 12. This is   |\n   |           | intended to match ``str()``, except you can add the other  |\n   |           | format modifiers.                                          |\n   +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the new format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of the cases the syntax is similar to the old\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n   >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n   \'a, b, c\'\n   >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\')  # 3.1+ only\n   \'a, b, c\'\n   >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n   \'c, b, a\'\n   >>> \'{2}, {1}, {0}\'.format(*\'abc\')      # unpacking argument sequence\n   \'c, b, a\'\n   >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\')   # arguments\' indices can be repeated\n   \'abracadabra\'\n\nAccessing arguments by name:\n\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n   \'Coordinates: 37.24N, -115.81W\'\n   >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n   \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n   >>> c = 3-5j\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   >>> class Point:\n   ...     def __init__(self, x, y):\n   ...         self.x, self.y = x, y\n   ...     def __str__(self):\n   ...         return \'Point({self.x}, {self.y})\'.format(self=self)\n   ...\n   >>> str(Point(4, 2))\n   \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n   >>> coord = (3, 5)\n   >>> \'X: {0[0]};  Y: {0[1]}\'.format(coord)\n   \'X: 3;  Y: 5\'\n\nReplacing ``%s`` and ``%r``:\n\n   >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n   "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n   >>> \'{:<30}\'.format(\'left aligned\')\n   \'left aligned                  \'\n   >>> \'{:>30}\'.format(\'right aligned\')\n   \'                 right aligned\'\n   >>> \'{:^30}\'.format(\'centered\')\n   \'           centered           \'\n   >>> \'{:*^30}\'.format(\'centered\')  # use \'*\' as a fill char\n   \'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\n\n   >>> \'{:+f}; {:+f}\'.format(3.14, -3.14)  # show it always\n   \'+3.140000; -3.140000\'\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   \'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and converting the value to different\nbases:\n\n   >>> # format also supports binary numbers\n   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)\n   \'int: 42;  hex: 2a;  oct: 52;  bin: 101010\'\n   >>> # with 0x, 0o, or 0b as prefix:\n   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)\n   \'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n   >>> \'{:,}\'.format(1234567890)\n   \'1,234,567,890\'\n\nExpressing a percentage:\n\n   >>> points = 19\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}.\'.format(points/total)\n   \'Correct answers: 86.36%\'\n\nUsing type-specific formatting:\n\n   >>> import datetime\n   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n   >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n   \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n   >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n   ...     \'{0:{align}{fill}16}\'.format(text, fill=align, align=align)\n   ...\n   \'left<<<<<<<<<<<<\'\n   \'^^^^^center^^^^^\'\n   \'>>>>>>>>>>>right\'\n   >>>\n   >>> octets = [192, 168, 0, 1]\n   >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n   \'C0A80001\'\n   >>> int(_, 16)\n   3232235521\n   >>>\n   >>> width = 5\n   >>> for num in range(5,12):\n   ...     for base in \'dXob\':\n   ...         print(\'{0:{width}{base}}\'.format(num, base=base, width=width), end=\' \')\n   ...     print()\n   ...\n       5     5     5   101\n       6     6     6   110\n       7     7     7   111\n       8     8    10  1000\n       9     9    11  1001\n      10     A    12  1010\n      11     B    13  1011\n',
  'function': '\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" [parameter] ("," defparameter)*\n                      [, "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more parameters have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding argument may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that that same "pre-computed" value is\nused for each call.  This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended.  A way around this is to use ``None`` as the\ndefault, 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           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple.  If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name.  Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``.  Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list.  These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code.  The presence of annotations does not change the\nsemantics of a function.  The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda forms,\ndescribed in section *Lambdas*.  Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form.  The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around.  Free variables used in the\nnested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n',
- 'global': '\nThe ``global`` statement\n************************\n\n   global_stmt ::= "global" identifier ("," identifier)*\n\nThe ``global`` statement is a declaration which holds for the entire\ncurrent code block.  It means that the listed identifiers are to be\ninterpreted as globals.  It would be impossible to assign to a global\nvariable without ``global``, although free variables may refer to\nglobals without being declared global.\n\nNames listed in a ``global`` statement must not be used in the same\ncode block textually preceding that ``global`` statement.\n\nNames listed in a ``global`` statement must not be defined as formal\nparameters or in a ``for`` loop control target, ``class`` definition,\nfunction definition, or ``import`` statement.\n\n(The current implementation does not enforce the latter two\nrestrictions, but programs should not abuse this freedom, as future\nimplementations may enforce them or silently change the meaning of the\nprogram.)\n\n**Programmer\'s note:** the ``global`` is a directive to the parser.\nIt applies only to code parsed at the same time as the ``global``\nstatement. In particular, a ``global`` statement contained in a string\nor code object supplied to the builtin ``exec()`` function does not\naffect the code block *containing* the function call, and code\ncontained in such a string is unaffected by ``global`` statements in\nthe code containing the function call.  The same applies to the\n``eval()`` and ``compile()`` functions.\n',
+ 'global': '\nThe ``global`` statement\n************************\n\n   global_stmt ::= "global" identifier ("," identifier)*\n\nThe ``global`` statement is a declaration which holds for the entire\ncurrent code block.  It means that the listed identifiers are to be\ninterpreted as globals.  It would be impossible to assign to a global\nvariable without ``global``, although free variables may refer to\nglobals without being declared global.\n\nNames listed in a ``global`` statement must not be used in the same\ncode block textually preceding that ``global`` statement.\n\nNames listed in a ``global`` statement must not be defined as formal\nparameters or in a ``for`` loop control target, ``class`` definition,\nfunction definition, or ``import`` statement.\n\n**CPython implementation detail:** The current implementation does not\nenforce the latter two restrictions, but programs should not abuse\nthis freedom, as future implementations may enforce them or silently\nchange the meaning of the program.\n\n**Programmer\'s note:** the ``global`` is a directive to the parser.\nIt applies only to code parsed at the same time as the ``global``\nstatement. In particular, a ``global`` statement contained in a string\nor code object supplied to the built-in ``exec()`` function does not\naffect the code block *containing* the function call, and code\ncontained in such a string is unaffected by ``global`` statements in\nthe code containing the function call.  The same applies to the\n``eval()`` and ``compile()`` functions.\n',
  'id-classes': '\nReserved classes of identifiers\n*******************************\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n   Not imported by ``from module import *``.  The special identifier\n   ``_`` is used in the interactive interpreter to store the result of\n   the last evaluation; it is stored in the ``builtins`` 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     ``gettext`` module for more information on this convention.\n\n``__*__``\n   System-defined names.  These names are defined by the interpreter\n   and its implementation (including the standard library);\n   applications should not expect to define additional names using\n   this convention.  The set of names of this class defined by Python\n   may be extended in future versions. See section *Special method\n   names*.\n\n``__*``\n   Class-private names.  Names in this category, when used 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   derived classes. See section *Identifiers (Names)*.\n',
  'identifiers': '\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions.\n\nThe syntax of identifiers in Python is based on the Unicode standard\nannex UAX-31, with elaboration and changes as defined below; see also\n**PEP 3131** for further details.\n\nWithin the ASCII range (U+0001..U+007F), the valid characters for\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\nletters ``A`` through ``Z``, the underscore ``_`` and, except for the\nfirst character, the digits ``0`` through ``9``.\n\nPython 3.0 introduces additional characters from outside the ASCII\nrange (see **PEP 3131**).  For these characters, the classification\nuses the version of the Unicode Character Database as included in the\n``unicodedata`` module.\n\nIdentifiers are unlimited in length.  Case is significant.\n\n   identifier  ::= id_start id_continue*\n   id_start    ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>\n   id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>\n\nThe Unicode category codes mentioned above stand for:\n\n* *Lu* - uppercase letters\n\n* *Ll* - lowercase letters\n\n* *Lt* - titlecase letters\n\n* *Lm* - modifier letters\n\n* *Lo* - other letters\n\n* *Nl* - letter numbers\n\n* *Mn* - nonspacing marks\n\n* *Mc* - spacing combining marks\n\n* *Nd* - decimal numbers\n\n* *Pc* - connector punctuations\n\nAll identifiers are converted into the normal form NFC while parsing;\ncomparison of identifiers is based on NFC.\n\nA non-normative HTML file listing all valid identifier characters for\nUnicode 4.1 can be found at http://www.dcl.hpi.uni-\npotsdam.de/home/loewis/table-3131.html.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers.  They must\nbe spelled exactly as written here:\n\n   False      class      finally    is         return\n   None       continue   for        lambda     try\n   True       def        from       nonlocal   while\n   and        del        global     not        with\n   as         elif       if         or         yield\n   assert     else       import     pass\n   break      except     in         raise\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n   Not imported by ``from module import *``.  The special identifier\n   ``_`` is used in the interactive interpreter to store the result of\n   the last evaluation; it is stored in the ``builtins`` 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     ``gettext`` module for more information on this convention.\n\n``__*__``\n   System-defined names.  These names are defined by the interpreter\n   and its implementation (including the standard library);\n   applications should not expect to define additional names using\n   this convention.  The set of names of this class defined by Python\n   may be extended in future versions. See section *Special method\n   names*.\n\n``__*``\n   Class-private names.  Names in this category, when used 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   derived classes. See section *Identifiers (Names)*.\n',
  'if': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n',
  'imaginary': '\nImaginary literals\n******************\n\nImaginary literals are described by the following lexical definitions:\n\n   imagnumber ::= (floatnumber | intpart) ("j" | "J")\n\nAn imaginary literal yields a complex number with a real part of 0.0.\nComplex numbers are represented as a pair of floating point numbers\nand have the same restrictions on their range.  To create a complex\nnumber with a nonzero real part, add a floating point number to it,\ne.g., ``(3+4j)``.  Some examples of imaginary literals:\n\n   3.14j   10.j    10j     .001j   1e100j  3.14e-10j\n',
- 'import': '\nThe ``import`` statement\n************************\n\n   import_stmt     ::= "import" module ["as" name] ( "," module ["as" name] )*\n                   | "from" relative_module "import" identifier ["as" name]\n                   ( "," identifier ["as" name] )*\n                   | "from" relative_module "import" "(" identifier ["as" name]\n                   ( "," identifier ["as" name] )* [","] ")"\n                   | "from" module "import" "*"\n   module          ::= (identifier ".")* identifier\n   relative_module ::= "."* module | "."+\n   name            ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nstatement comes in two forms differing on whether it uses the ``from``\nkeyword. The first form (without ``from``) repeats these steps for\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and then performs step (2) repeatedly. For a reference\nimplementation of step (1), see the ``importlib`` module.\n\nTo understand how step (1) occurs, one must first understand how\nPython handles hierarchical naming of modules. To help organize\nmodules and provide a hierarchy in naming, Python has a concept of\npackages. A package can contain other packages and modules while\nmodules cannot contain other modules or packages. From a file system\nperspective, packages are directories and modules are files. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor 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\na single argument of the path, returning a finder or raises\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\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns ``None`` is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any.  If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound.  As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname".  If a name is not\nfound, ``ImportError`` is raised.  If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module.  The names given in ``__all__`` are all considered public\nand are required to exist.  If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope.  The\nwild card form of import --- ``import *`` --- is only allowed at the\nmodule level. Attempting to use it in class for function definitions\nwill raise a ``SyntaxError``.\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after ``from``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none 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\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimprt mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python.  The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language.  It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n   future_statement ::= "from" "__future__" "import" feature ["as" name]\n                        ("," feature ["as" name])*\n                        | "from" "__future__" "import" "(" feature ["as" name]\n                        ("," feature ["as" name])* [","] ")"\n   feature          ::= identifier\n   name             ::= identifier\n\nA future statement must appear near the top of the module.  The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``unicode_literals``,\n``print_function``, ``nested_scopes`` and ``with_statement``.  They\nare all redundant because they are always enabled, and only kept for\nbackwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code.  It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently.  Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n   import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the builtin functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement.  This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session.  If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also:\n\n   **PEP 236** - Back to the __future__\n      The original proposal for the __future__ mechanism.\n',
- 'in': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects.  The objects need not have the same type.\nIf both are numbers, they are converted to a common type.  Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes.  You can control comparison behavior of objects of non-builtin\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n  are identical to themselves, ``x is x`` but are not equal to\n  themselves, ``x != x``.  Additionally, comparing any value to a\n  not-a-number value will return ``False``.  For example, both ``3 <\n  float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n  values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n  (the result of the built-in function ``ord()``) of their characters.\n  [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n  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\n  If not equal, the sequences are ordered the same as their first\n  differing elements.  For example, ``[1,2,x] <= [1,2,y]`` has the\n  same value as ``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  ``(key, value)`` lists compare equal. [4] Outcomes other than\n  equality are resolved consistently, but are not otherwise defined.\n  [5]\n\n* Sets and frozensets define comparison operators to mean subset and\n  superset tests.  Those relations do not define total orderings (the\n  two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering.\n  For example, ``min()``, ``max()``, and ``sorted()`` produce\n  undefined results given a list of sets as inputs.\n\n* Most other objects of builtin types compare unequal unless they are\n  the same object; the choice whether one object is considered smaller\n  or larger than another one is made arbitrarily but consistently\n  within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison.  Most\nnumeric types can be compared with one another, but comparisons of\n``float`` and ``Decimal`` are not supported to avoid the inevitable\nconfusion arising from representation issues such as ``float(\'1.1\')``\nbeing inexactly represented and therefore not exactly equal to\n``Decimal(\'1.1\')`` which is.  When cross-type comparison is not\nsupported, the comparison method returns ``NotImplemented``.  This can\ncreate the illusion of non-transitivity between supported cross-type\ncomparisons and unsupported comparisons.  For example, ``Decimal(2) ==\n2`` and *2 == float(2)`* but ``Decimal(2) != float(2)``.\n\nThe operators ``in`` and ``not in`` test for membership.  ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise.  ``x\nnot in s`` returns the negation of ``x in s``.  All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for val\ne in y)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*.  An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` and do\ndefine ``__getitem__()``, ``x in y`` is true if and only if there is a\nnon-negative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception.  (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object.  ``x is\nnot y`` yields the inverse truth value. [6]\n',
+ 'import': '\nThe ``import`` statement\n************************\n\n   import_stmt     ::= "import" module ["as" name] ( "," module ["as" name] )*\n                   | "from" relative_module "import" identifier ["as" name]\n                   ( "," identifier ["as" name] )*\n                   | "from" relative_module "import" "(" identifier ["as" name]\n                   ( "," identifier ["as" name] )* [","] ")"\n                   | "from" module "import" "*"\n   module          ::= (identifier ".")* identifier\n   relative_module ::= "."* module | "."+\n   name            ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nstatement comes in two forms differing on whether it uses the ``from``\nkeyword. The first form (without ``from``) repeats these steps for\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and then performs step (2) repeatedly. For a reference\nimplementation of step (1), see the ``importlib`` module.\n\nTo understand how step (1) occurs, one must first understand how\nPython handles hierarchical naming of modules. To help organize\nmodules and provide a hierarchy in naming, Python has a concept of\npackages. A package can contain other packages and modules while\nmodules cannot contain other modules or packages. From a file system\nperspective, packages are directories and modules are files. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import unless ``None`` is found in ``sys.modules``, in which case\n``ImportError`` is raised.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor 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\na single argument of the path, returning a finder or raises\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\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns ``None`` is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any.  If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound.  As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname".  If a name is not\nfound, ``ImportError`` is raised.  If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module.  The names given in ``__all__`` are all considered public\nand are required to exist.  If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope.  The\nwild card form of import --- ``import *`` --- is only allowed at the\nmodule level. Attempting to use it in class or function definitions\nwill raise a ``SyntaxError``.\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after ``from``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none 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\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimprt mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python.  The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language.  It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n   future_statement ::= "from" "__future__" "import" feature ["as" name]\n                        ("," feature ["as" name])*\n                        | "from" "__future__" "import" "(" feature ["as" name]\n                        ("," feature ["as" name])* [","] ")"\n   feature          ::= identifier\n   name             ::= identifier\n\nA future statement must appear near the top of the module.  The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``unicode_literals``,\n``print_function``, ``nested_scopes`` and ``with_statement``.  They\nare all redundant because they are always enabled, and only kept for\nbackwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code.  It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently.  Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n   import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the built-in functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement.  This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session.  If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also:\n\n   **PEP 236** - Back to the __future__\n      The original proposal for the __future__ mechanism.\n',
+ 'in': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects.  The objects need not have the same type.\nIf both are numbers, they are converted to a common type.  Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes.  You can control comparison behavior of objects of non-built-in\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n  are identical to themselves, ``x is x`` but are not equal to\n  themselves, ``x != x``.  Additionally, comparing any value to a\n  not-a-number value will return ``False``.  For example, both ``3 <\n  float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n  values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n  (the result of the built-in function ``ord()``) of their characters.\n  [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n  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\n  If not equal, the sequences are ordered the same as their first\n  differing elements.  For example, ``[1,2,x] <= [1,2,y]`` has the\n  same value as ``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 they have the\n  same ``(key, value)`` pairs. Order comparisons ``(\'<\', \'<=\', \'>=\',\n  \'>\')`` raise ``TypeError``.\n\n* Sets and frozensets define comparison operators to mean subset and\n  superset tests.  Those relations do not define total orderings (the\n  two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering.\n  For example, ``min()``, ``max()``, and ``sorted()`` produce\n  undefined results given a list of sets as inputs.\n\n* Most other objects of built-in types compare unequal unless they are\n  the same object; the choice whether one object is considered smaller\n  or larger than another one is made arbitrarily but consistently\n  within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison.  Most\nnumeric types can be compared with one another, but comparisons of\n``float`` and ``Decimal`` are not supported to avoid the inevitable\nconfusion arising from representation issues such as ``float(\'1.1\')``\nbeing inexactly represented and therefore not exactly equal to\n``Decimal(\'1.1\')`` which is.  When cross-type comparison is not\nsupported, the comparison method returns ``NotImplemented``.  This can\ncreate the illusion of non-transitivity between supported cross-type\ncomparisons and unsupported comparisons.  For example, ``Decimal(2) ==\n2`` and *2 == float(2)`* but ``Decimal(2) != float(2)``.\n\nThe operators ``in`` and ``not in`` test for membership.  ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise.  ``x\nnot in s`` returns the negation of ``x in s``.  All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\ny)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*.  An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``.  If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, 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-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception.  (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object.  ``x is\nnot y`` yields the inverse truth value. [4]\n',
  'integers': '\nInteger literals\n****************\n\nInteger literals are described by the following lexical definitions:\n\n   integer        ::= decimalinteger | octinteger | hexinteger | bininteger\n   decimalinteger ::= nonzerodigit digit* | "0"+\n   nonzerodigit   ::= "1"..."9"\n   digit          ::= "0"..."9"\n   octinteger     ::= "0" ("o" | "O") octdigit+\n   hexinteger     ::= "0" ("x" | "X") hexdigit+\n   bininteger     ::= "0" ("b" | "B") bindigit+\n   octdigit       ::= "0"..."7"\n   hexdigit       ::= digit | "a"..."f" | "A"..."F"\n   bindigit       ::= "0" | "1"\n\nThere is no limit for the length of integer literals apart from what\ncan be stored in available memory.\n\nNote that leading zeros in a non-zero decimal number are not allowed.\nThis is for disambiguation with C-style octal literals, which Python\nused before version 3.0.\n\nSome examples of integer literals:\n\n   7     2147483647                        0o177    0b100110111\n   3     79228162514264337593543950336     0o377    0x100000000\n         79228162514264337593543950336              0xdeadbeef\n',
  'lambda': '\nLambdas\n*******\n\n   lambda_form        ::= "lambda" [parameter_list]: expression\n   lambda_form_nocond ::= "lambda" [parameter_list]: expression_nocond\n\nLambda forms (lambda expressions) have the same syntactic position as\nexpressions.  They are a shorthand to create anonymous functions; the\nexpression ``lambda arguments: expression`` yields a function object.\nThe unnamed object behaves like a function object defined with\n\n   def <lambda>(arguments):\n       return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda forms cannot contain\nstatements or annotations.\n',
  'lists': '\nList displays\n*************\n\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n   list_display ::= "[" [expression_list | comprehension] "]"\n\nA list display yields a new list object, the contents being specified\nby either a list of expressions or a comprehension.  When a comma-\nseparated list of expressions is supplied, its elements are evaluated\nfrom left to right and placed into the list object in that order.\nWhen a comprehension is supplied, the list is constructed from the\nelements resulting from the comprehension.\n',
- 'naming': "\nNaming and binding\n******************\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the '**-c**' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block's execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block's *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or :keyword.`except` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtin namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtin namespace\nis searched.  The global statement must precede all uses of the name.\n\nThe built-in namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\nNote: Users should not touch ``__builtins__``; it is strictly an\n  implementation detail.  Users wanting to override values in the\n  built-in namespace should ``import`` the ``builtins`` module and\n  modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe global statement has the same scope as a name binding operation in\nthe same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n",
+ 'naming': "\nNaming and binding\n******************\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the '**-c**' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block's execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block's *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or :keyword.`except` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtins\nnamespace is searched.  The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe global statement has the same scope as a name binding operation in\nthe same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n",
  'numbers': "\nNumeric literals\n****************\n\nThere are three types of numeric literals: integers, floating point\nnumbers, and imaginary numbers.  There are no complex literals\n(complex numbers can be formed by adding a real number and an\nimaginary number).\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator '``-``' and\nthe literal ``1``.\n",
- 'numeric-types': "\nEmulating numeric types\n***********************\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [3]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand's type is a subclass of the left operand's\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand's\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n",
- 'objects': '\nObjects, values and types\n*************************\n\n*Objects* are Python\'s abstraction for data.  All data in a Python\nprogram is represented by objects or by relations between objects. (In\na sense, and in conformance to Von Neumann\'s model of a "stored\nprogram computer," code is also represented by objects.)\n\nEvery 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\nas the object\'s address in memory.  The \'``is``\' operator compares the\nidentity of two objects; the ``id()`` function returns an integer\nrepresenting its identity (currently implemented as its address). An\nobject\'s *type* is also unchangeable. [1] An object\'s type determines\nthe operations that the object supports (e.g., "does it have a\nlength?") and also defines the possible values for objects of that\ntype.  The ``type()`` function returns an object\'s type (which is an\nobject itself).  The *value* of some objects can change.  Objects\nwhose value can change are said to be *mutable*; objects whose value\nis unchangeable once they are created are called *immutable*. (The\nvalue of an immutable container object that contains a reference to a\nmutable object can change when the latter\'s value is changed; however\nthe container is still considered immutable, because the collection of\nobjects it contains cannot be changed.  So, immutability is not\nstrictly the same as having an unchangeable value, it is more subtle.)\nAn object\'s mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\n\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected.  An implementation is\nallowed to postpone garbage collection or omit it altogether --- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable.  (Implementation note: CPython currently uses a reference-\ncounting scheme with (optional) delayed detection of cyclically linked\ngarbage, which collects most objects as soon as they become\nunreachable, but is not guaranteed to collect garbage containing\ncircular references.  See the documentation of the ``gc`` module for\ninformation on controlling the collection of cyclic garbage.  Other\nimplementations act differently and CPython may change.)\n\nNote that the use of the implementation\'s tracing or debugging\nfacilities may keep objects alive that would normally be collectable.\nAlso note that catching an exception with a \'``try``...``except``\'\nstatement may keep objects alive.\n\nSome objects contain references to "external" resources such as open\nfiles or windows.  It is understood that these resources are freed\nwhen the object is garbage-collected, but since garbage collection is\nnot guaranteed to happen, such objects also provide an explicit way to\nrelease the external resource, usually a ``close()`` method. Programs\nare strongly recommended to explicitly close such objects.  The\n\'``try``...``finally``\' statement and the \'``with``\' statement provide\nconvenient ways to do this.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries.  The references are part of a container\'s value.  In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied.  So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior.  Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed.  E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\nthe same object to both ``c`` and ``d``.)\n',
- 'operator-summary': '\nSummary\n*******\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding).  Operators in the same box have the same precedence.  Unless\nthe syntax is explicitly given, operators are binary.  Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator                                        | Description                           |\n+=================================================+=======================================+\n| ``lambda``                                      | Lambda expression                     |\n+-------------------------------------------------+---------------------------------------+\n| ``or``                                          | Boolean OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``and``                                         | Boolean AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` *x*                                     | Boolean NOT                           |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not`` ``in``, ``is``, ``is not``,     | Comparisons, including membership     |\n| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==``    | tests and identity tests,             |\n+-------------------------------------------------+---------------------------------------+\n| ``|``                                           | Bitwise OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``^``                                           | Bitwise XOR                           |\n+-------------------------------------------------+---------------------------------------+\n| ``&``                                           | Bitwise AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``<<``, ``>>``                                  | Shifts                                |\n+-------------------------------------------------+---------------------------------------+\n| ``+``, ``-``                                    | Addition and subtraction              |\n+-------------------------------------------------+---------------------------------------+\n| ``*``, ``/``, ``//``, ``%``                     | Multiplication, division, remainder   |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x``                          | Positive, negative, bitwise NOT       |\n+-------------------------------------------------+---------------------------------------+\n| ``**``                                          | Exponentiation [7]                    |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``,               | Subscription, slicing, call,          |\n| ``x(arguments...)``, ``x.attribute``            | attribute reference                   |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``,     | Binding or tuple display, list        |\n| ``{key:datum...}``,                             | display, dictionary display,          |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n    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`` have the same\n    sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n    which is numerically exactly equal to ``1e100``.  Function\n    ``fmod()`` in the ``math`` module returns a result whose sign\n    matches the sign of the first argument instead, and so returns\n    ``-1e-100`` in this case. Which approach is more appropriate\n    depends on the application.\n\n[2] If x is very close to an exact integer multiple of y, it\'s\n    possible for ``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\n    close to ``x``.\n\n[3] While comparisons between strings make sense at the byte level,\n    they may be counter-intuitive to users.  For example, the strings\n    ``"\\u00C7"`` and ``"\\u0327\\u0043"`` compare differently, even\n    though they both represent the same unicode character (LATIN\n    CAPITAL LETTER C WITH CEDILLA).  To compare strings in a human\n    recognizable way, compare using ``unicodedata.normalize()``.\n\n[4] The implementation computes this efficiently, without constructing\n    lists or sorting.\n\n[5] Earlier versions of Python used lexicographic comparison of the\n    sorted (key, value) lists, but this was very expensive for the\n    common case of comparing for equality.  An even 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    for emptiness by comparing it to ``{}``.\n\n[6] Due to automatic garbage-collection, free lists, and the dynamic\n    nature of descriptors, you may notice seemingly unusual behaviour\n    in certain uses of the ``is`` operator, like those involving\n    comparisons between instance methods, or constants.  Check their\n    documentation for more info.\n\n[7] The power operator ``**`` binds less tightly than an arithmetic or\n    bitwise unary operator on its right, that is, ``2**-1`` is\n    ``0.5``.\n',
+ 'numeric-types': "\nEmulating numeric types\n***********************\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [2]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand's type is a subclass of the left operand's\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand's\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n",
+ 'objects': '\nObjects, values and types\n*************************\n\n*Objects* are Python\'s abstraction for data.  All data in a Python\nprogram is represented by objects or by relations between objects. (In\na sense, and in conformance to Von Neumann\'s model of a "stored\nprogram computer," code is also represented by objects.)\n\nEvery 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\nas the object\'s address in memory.  The \'``is``\' operator compares the\nidentity of two objects; the ``id()`` function returns an integer\nrepresenting its identity (currently implemented as its address). An\nobject\'s *type* is also unchangeable. [1] An object\'s type determines\nthe operations that the object supports (e.g., "does it have a\nlength?") and also defines the possible values for objects of that\ntype.  The ``type()`` function returns an object\'s type (which is an\nobject itself).  The *value* of some objects can change.  Objects\nwhose value can change are said to be *mutable*; objects whose value\nis unchangeable once they are created are called *immutable*. (The\nvalue of an immutable container object that contains a reference to a\nmutable object can change when the latter\'s value is changed; however\nthe container is still considered immutable, because the collection of\nobjects it contains cannot be changed.  So, immutability is not\nstrictly the same as having an unchangeable value, it is more subtle.)\nAn object\'s mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\n\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected.  An implementation is\nallowed to postpone garbage collection or omit it altogether --- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable.\n\n**CPython implementation detail:** CPython currently uses a reference-\ncounting scheme with (optional) delayed detection of cyclically linked\ngarbage, which collects most objects as soon as they become\nunreachable, but is not guaranteed to collect garbage containing\ncircular references.  See the documentation of the ``gc`` module for\ninformation on controlling the collection of cyclic garbage. Other\nimplementations act differently and CPython may change.\n\nNote that the use of the implementation\'s tracing or debugging\nfacilities may keep objects alive that would normally be collectable.\nAlso note that catching an exception with a \'``try``...``except``\'\nstatement may keep objects alive.\n\nSome objects contain references to "external" resources such as open\nfiles or windows.  It is understood that these resources are freed\nwhen the object is garbage-collected, but since garbage collection is\nnot guaranteed to happen, such objects also provide an explicit way to\nrelease the external resource, usually a ``close()`` method. Programs\nare strongly recommended to explicitly close such objects.  The\n\'``try``...``finally``\' statement and the \'``with``\' statement provide\nconvenient ways to do this.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries.  The references are part of a container\'s value.  In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied.  So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior.  Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed.  E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\nthe same object to both ``c`` and ``d``.)\n',
+ 'operator-summary': '\nSummary\n*******\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding).  Operators in the same box have the same precedence.  Unless\nthe syntax is explicitly given, operators are binary.  Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator                                        | Description                           |\n+=================================================+=======================================+\n| ``lambda``                                      | Lambda expression                     |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else``                              | Conditional expression                |\n+-------------------------------------------------+---------------------------------------+\n| ``or``                                          | Boolean OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``and``                                         | Boolean AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` *x*                                     | Boolean NOT                           |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not`` ``in``, ``is``, ``is not``,     | Comparisons, including membership     |\n| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==``    | tests and identity tests,             |\n+-------------------------------------------------+---------------------------------------+\n| ``|``                                           | Bitwise OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``^``                                           | Bitwise XOR                           |\n+-------------------------------------------------+---------------------------------------+\n| ``&``                                           | Bitwise AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``<<``, ``>>``                                  | Shifts                                |\n+-------------------------------------------------+---------------------------------------+\n| ``+``, ``-``                                    | Addition and subtraction              |\n+-------------------------------------------------+---------------------------------------+\n| ``*``, ``/``, ``//``, ``%``                     | Multiplication, division, remainder   |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x``                          | Positive, negative, bitwise NOT       |\n+-------------------------------------------------+---------------------------------------+\n| ``**``                                          | Exponentiation [5]                    |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``,               | Subscription, slicing, call,          |\n| ``x(arguments...)``, ``x.attribute``            | attribute reference                   |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``,     | Binding or tuple display, list        |\n| ``{key:datum...}``,                             | display, dictionary display,          |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n    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`` have the same\n    sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n    which is numerically exactly equal to ``1e100``.  Function\n    ``fmod()`` in the ``math`` module returns a result whose sign\n    matches the sign of the first argument instead, and so returns\n    ``-1e-100`` in this case. Which approach is more appropriate\n    depends on the application.\n\n[2] If x is very close to an exact integer multiple of y, it\'s\n    possible for ``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\n    close to ``x``.\n\n[3] While comparisons between strings make sense at the byte level,\n    they may be counter-intuitive to users.  For example, the strings\n    ``"\\u00C7"`` and ``"\\u0327\\u0043"`` compare differently, even\n    though they both represent the same unicode character (LATIN\n    CAPITAL LETTER C WITH CEDILLA).  To compare strings in a human\n    recognizable way, compare using ``unicodedata.normalize()``.\n\n[4] Due to automatic garbage-collection, free lists, and the dynamic\n    nature of descriptors, you may notice seemingly unusual behaviour\n    in certain uses of the ``is`` operator, like those involving\n    comparisons between instance methods, or constants.  Check their\n    documentation for more info.\n\n[5] The power operator ``**`` binds less tightly than an arithmetic or\n    bitwise unary operator on its right, that is, ``2**-1`` is\n    ``0.5``.\n',
  'pass': '\nThe ``pass`` statement\n**********************\n\n   pass_stmt ::= "pass"\n\n``pass`` is a null operation --- when it is executed, nothing happens.\nIt is useful as a placeholder when a statement is required\nsyntactically, but no code needs to be executed, for example:\n\n   def f(arg): pass    # a function that does nothing (yet)\n\n   class C: pass       # a class with no methods (yet)\n',
  'power': '\nThe power operator\n******************\n\nThe power operator binds more tightly than unary operators on its\nleft; it binds less tightly than unary operators on its right.  The\nsyntax is:\n\n   power ::= primary ["**" u_expr]\n\nThus, in an unparenthesized sequence of power and unary operators, the\noperators are evaluated from right to left (this does not constrain\nthe evaluation order for the operands): ``-1**2`` results in ``-1``.\n\nThe power operator has the same semantics as the built-in ``pow()``\nfunction, when called with two arguments: it yields its left argument\nraised to the power of its right argument.  The numeric arguments are\nfirst converted to a common type, and the result is of that type.\n\nFor int operands, the result has the same type as the operands unless\nthe second argument is negative; in that case, all arguments are\nconverted to float and a float result is delivered. For example,\n``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``.\n\nRaising ``0.0`` to a negative power results in a\n``ZeroDivisionError``. Raising a negative number to a fractional power\nresults in a ``complex`` number. (In earlier versions it raised a\n``ValueError``.)\n',
  'raise': '\nThe ``raise`` statement\n***********************\n\n   raise_stmt ::= "raise" [expression ["from" expression]]\n\nIf no expressions are present, ``raise`` re-raises the last exception\nthat was active in the current scope.  If no exception is active in\nthe current scope, a ``TypeError`` exception is raised indicating that\nthis is an error (if running under IDLE, a ``queue.Empty`` exception\nis raised instead).\n\nOtherwise, ``raise`` evaluates the first expression as the exception\nobject.  It must be either a subclass or an instance of\n``BaseException``. If it is a class, the exception instance will be\nobtained when needed by instantiating the class with no arguments.\n\nThe *type* of the exception is the exception instance\'s class, the\n*value* is the instance itself.\n\nA traceback object is normally created automatically when an exception\nis raised and attached to it as the ``__traceback__`` attribute, which\nis writable. You can create an exception and set your own traceback in\none step using the ``with_traceback()`` exception method (which\nreturns the same exception instance, with its traceback set to its\nargument), like so:\n\n   raise Exception("foo occurred").with_traceback(tracebackobj)\n\nThe ``from`` clause is used for exception chaining: if given, the\nsecond *expression* must be another exception class or instance, which\nwill then be attached to the raised exception as the ``__cause__``\nattribute (which is writable).  If the raised exception is not\nhandled, both exceptions will be printed:\n\n   >>> try:\n   ...     print(1 / 0)\n   ... except Exception as exc:\n   ...     raise RuntimeError("Something bad happened") from exc\n   ...\n   Traceback (most recent call last):\n     File "<stdin>", line 2, in <module>\n   ZeroDivisionError: int division or modulo by zero\n\n   The above exception was the direct cause of the following exception:\n\n   Traceback (most recent call last):\n     File "<stdin>", line 4, in <module>\n   RuntimeError: Something bad happened\n\nA similar mechanism works implicitly if an exception is raised inside\nan exception handler: the previous exception is then attached as the\nnew exception\'s ``__context__`` attribute:\n\n   >>> try:\n   ...     print(1 / 0)\n   ... except:\n   ...     raise RuntimeError("Something bad happened")\n   ...\n   Traceback (most recent call last):\n     File "<stdin>", line 2, in <module>\n   ZeroDivisionError: int division or modulo by zero\n\n   During handling of the above exception, another exception occurred:\n\n   Traceback (most recent call last):\n     File "<stdin>", line 4, in <module>\n   RuntimeError: Something bad happened\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information about handling exceptions is in section\n*The try statement*.\n',
- 'return': '\nThe ``return`` statement\n************************\n\n   return_stmt ::= "return" [expression_list]\n\n``return`` may only occur syntactically nested in a function\ndefinition, not within a nested class definition.\n\nIf an expression list is present, it is evaluated, else ``None`` is\nsubstituted.\n\n``return`` leaves the current function call with the expression list\n(or ``None``) as return value.\n\nWhen ``return`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the function.\n\nIn a generator function, the ``return`` statement is not allowed to\ninclude an **expression_list**.  In that context, a bare ``return``\nindicates that the generator is done and will cause ``StopIteration``\nto be raised.\n',
- 'sequence-types': "\nEmulating container types\n*************************\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items.  It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python's standard\ndictionary objects.  The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects.  Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators.  It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping's keys; for\nsequences, it should search through the values.  It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function ``len()``.  Should return\n   the length of the object, an integer ``>=`` 0.  Also, an object\n   that doesn't define a ``__bool__()`` method and whose ``__len__()``\n   method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods.  A\n  call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with\n  ``None``.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of ``self[key]``. For sequence\n   types, the accepted keys should be integers and slice objects.\n   Note that the special interpretation of negative indexes (if the\n   class wishes to emulate a sequence type) is up to the\n   ``__getitem__()`` method. If *key* is of an inappropriate type,\n   ``TypeError`` may be raised; if of a value outside the set of\n   indexes for the sequence (after any special interpretation of\n   negative values), ``IndexError`` should be raised. For mapping\n   types, if *key* is missing (not in the container), ``KeyError``\n   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     sequence.\n\nobject.__setitem__(self, key, value)\n\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   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\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   raised for improper *key* values as for the ``__getitem__()``\n   method.\n\nobject.__iter__(self)\n\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   available as the method ``keys()``.\n\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\nobject.__reversed__(self)\n\n   Called (if present) by the ``reversed()`` builtin to 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\n   If the ``__reversed__()`` method is not provided, the\n   ``reversed()`` builtin will fall back to using the sequence\n   protocol (``__len__()`` and ``__getitem__()``).  Objects that\n   support the sequence protocol should only provide\n   ``__reversed__()`` if they can provide an implementation that is\n   more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\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   the key-item pairs.\n",
- 'shifting': '\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n   shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept integers as arguments.  They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by ``pow(2,n)``.  A\nleft shift by *n* bits is defined as multiplication with ``pow(2,n)``.\n',
+ 'return': '\nThe ``return`` statement\n************************\n\n   return_stmt ::= "return" [expression_list]\n\n``return`` may only occur syntactically nested in a function\ndefinition, not within a nested class definition.\n\nIf an expression list is present, it is evaluated, else ``None`` is\nsubstituted.\n\n``return`` leaves the current function call with the expression list\n(or ``None``) as return value.\n\nWhen ``return`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the function.\n\nIn a generator function, the ``return`` statement is not allowed to\ninclude an ``expression_list``.  In that context, a bare ``return``\nindicates that the generator is done and will cause ``StopIteration``\nto be raised.\n',
+ 'sequence-types': "\nEmulating container types\n*************************\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items.  It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python's standard\ndictionary objects.  The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects.  Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators.  It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping's keys; for\nsequences, it should search through the values.  It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function ``len()``.  Should return\n   the length of the object, an integer ``>=`` 0.  Also, an object\n   that doesn't define a ``__bool__()`` method and whose ``__len__()``\n   method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods.  A\n  call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with\n  ``None``.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of ``self[key]``. For sequence\n   types, the accepted keys should be integers and slice objects.\n   Note that the special interpretation of negative indexes (if the\n   class wishes to emulate a sequence type) is up to the\n   ``__getitem__()`` method. If *key* is of an inappropriate type,\n   ``TypeError`` may be raised; if of a value outside the set of\n   indexes for the sequence (after any special interpretation of\n   negative values), ``IndexError`` should be raised. For mapping\n   types, if *key* is missing (not in the container), ``KeyError``\n   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     sequence.\n\nobject.__setitem__(self, key, value)\n\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   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\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   raised for improper *key* values as for the ``__getitem__()``\n   method.\n\nobject.__iter__(self)\n\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   available as the method ``keys()``.\n\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\nobject.__reversed__(self)\n\n   Called (if present) by the ``reversed()`` built-in to 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\n   If the ``__reversed__()`` method is not provided, the\n   ``reversed()`` built-in will fall back to using the sequence\n   protocol (``__len__()`` and ``__getitem__()``).  Objects that\n   support the sequence protocol should only provide\n   ``__reversed__()`` if they can provide an implementation that is\n   more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\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   the key-item pairs.\n\n   For objects that don't define ``__contains__()``, the membership\n   test first tries iteration via ``__iter__()``, then the old\n   sequence iteration protocol via ``__getitem__()``, see *this\n   section in the language reference*.\n",
+ 'shifting': '\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n   shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept integers as arguments.  They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by ``pow(2,n)``.  A\nleft shift by *n* bits is defined as multiplication with ``pow(2,n)``.\n\nNote: In the current implementation, the right-hand operand is required to\n  be at most ``sys.maxsize``.  If the right-hand operand is larger\n  than ``sys.maxsize`` an ``OverflowError`` exception is raised.\n',
  'slicings': '\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list).  Slicings may be used as expressions or as\ntargets in assignment or ``del`` statements.  The syntax for a\nslicing:\n\n   slicing      ::= primary "[" slice_list "]"\n   slice_list   ::= slice_item ("," slice_item)* [","]\n   slice_item   ::= expression | proper_slice\n   proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]\n   lower_bound  ::= expression\n   upper_bound  ::= expression\n   stride       ::= expression\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing.  Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice).\n\nThe semantics for a slicing are as follows.  The primary must evaluate\nto a mapping object, and it is indexed (using the same\n``__getitem__()`` method as normal subscription) with a key that is\nconstructed from the slice list, as follows.  If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key.  The conversion of a slice item that is an\nexpression is that expression.  The conversion of a proper slice is a\nslice object (see section *The standard type hierarchy*) whose\n``start``, ``stop`` and ``step`` attributes are the values of the\nexpressions given as lower bound, upper bound and stride,\nrespectively, substituting ``None`` for missing expressions.\n',
- 'specialattrs': "\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant.  Some of these are not reported\nby the ``dir()`` built-in function.\n\nobject.__dict__\n\n   A dictionary or other mapping object used to store an object's\n   (writable) attributes.\n\ninstance.__class__\n\n   The class to which a class instance belongs.\n\nclass.__bases__\n\n   The tuple of base classes of a class object.  If there are no base\n   classes, this will be an empty tuple.\n\nclass.__name__\n\n   The name of the class or type.\n\nThe following attributes are only supported by *new-style class*es.\n\nclass.__mro__\n\n   This attribute is a tuple of classes that are considered when\n   looking for base classes during method resolution.\n\nclass.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   instantiation, and its result is stored in ``__mro__``.\n\nclass.__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   references still alive. Example:\n\n      >>> int.__subclasses__()\n      [<type 'bool'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found in\n    the Python Reference Manual (*Basic customization*).\n\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 the\n    operands.\n\n[4] To format only a tuple you should therefore provide a singleton\n    tuple whose only element is the tuple to be formatted.\n\n[5] The advantage of leaving the newline on is that returning an empty\n    string is then an unambiguous EOF indication.  It is also possible\n    (in cases where it might matter, for example, if you want to make\n    an exact copy of a file while scanning its lines) to tell whether\n    the last line of a file ended in a newline or not (yes this\n    happens!).\n",
- 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators.  For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``.  Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled.  For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense.  (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\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   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 (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\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   necessary before returning it.\n\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   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   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  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__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__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,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__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   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\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\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled 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.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     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 ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     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\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   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   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\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   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see the Total Ordering recipe in the ASPN cookbook.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\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   considered true if its result is nonzero. If a class defines\n   neither ``__len__()`` nor ``__bool__()``, all its instances are\n   considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\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   in the class tree for ``self``).  ``name`` is the attribute name.\n   This method should return the (computed) attribute value or raise\n   an ``AttributeError`` exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   ``__getattr__()`` is not called.  (This is an intentional asymmetry\n   between ``__getattr__()`` and ``__setattr__()``.) This is done both\n   for efficiency reasons and because otherwise ``__getattr__()``\n   would have no way to access other attributes of the instance.  Note\n   that at least for instance variables, you can fake total control by\n   not 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   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines\n   ``__getattr__()``, the latter will not be called unless\n   ``__getattribute__()`` either calls it explicitly or raises an\n   ``AttributeError``. This method should return the (computed)\n   attribute value or raise an ``AttributeError`` exception. In order\n   to avoid infinite recursion in this method, its implementation\n   should always call the base class method with the same name to\n   access any attributes it needs, for example,\n   ``object.__getattribute__(self, name)``.\n\n   Note: This method may still be bypassed when looking up special methods\n     as the result of implicit invocation via language syntax or\n     builtin functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\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   value to be assigned to it.\n\n   If ``__setattr__()`` wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n   Like ``__setattr__()`` but for attribute deletion instead of\n   assignment.  This should only be implemented if ``del obj.name`` is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when ``dir()`` is called on the object.  A list must be\n   returned.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class.  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\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   return the (computed) attribute value or raise an\n   ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    ``x.__get__(a)``.\n\nInstance Binding\n   If binding to an object instance, ``a.x`` is transformed into the\n   call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n   If binding to a class, ``A.x`` is transformed into the call:\n   ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n   If ``a`` is an instance of ``super``, then the binding ``super(B,\n   obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n   ``A`` immediately preceding ``B`` and then invokes the descriptor\n   with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  Normally, data\ndescriptors define both ``__get__()`` and ``__set__()``, while non-\ndata descriptors have just the ``__get__()`` method.  Data descriptors\nalways override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances. [2]\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__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   class, *__slots__* reserves space for the declared variables and\n   prevents the automatic creation of *__dict__* and *__weakref__* for\n   each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\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 assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises ``AttributeError``. If\n  dynamic assignment of new variables is desired, then add\n  ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n  *__slots__* do not support weak references to its instances. If weak\n  reference support is needed, then add ``\'__weakref__\'`` to the\n  sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a 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* If a class defines a slot also defined in a base class, the instance\n  variable defined by the base class slot is inaccessible (except by\n  retrieving its descriptor directly from the base class). This\n  renders the meaning of the program undefined.  In the future, a\n  check may be added to prevent this.\n\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__*.\n\n* Nonempty *__slots__* does not work for classes derived from\n  "variable-length" built-in types such as ``int``, ``str`` and\n  ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n  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  *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if a callable ``metaclass`` keyword\nargument is passed after the bases in the class definition, the\ncallable given will be called instead of ``type()``.  If other keyword\narguments are passed, they will also be passed to the metaclass.  This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n  role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties.  This example adds a new\nelement 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\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\nIf the metaclass has a ``__prepare__()`` attribute (usually\nimplemented as a class or static method), it is called before the\nclass body is evaluated with the name of the class and a tuple of its\nbases for arguments.  It should return an object that supports the\nmapping interface that will be used to store the namespace of the\nclass.  The default is a plain dictionary.  This could be used, for\nexample, to keep track of the order that class attributes are declared\nin by returning an ordered dictionary.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If the ``metaclass`` keyword argument is based with the bases, it is\n  used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n  used.\n\n* Otherwise, the default metaclass (``type``) is used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n``collections.OrderedDict`` to remember the order that class members\nwere defined:\n\n   class OrderedClass(type):\n\n        @classmethod\n        def __prepare__(metacls, name, bases, **kwds):\n           return collections.OrderedDict()\n\n        def __new__(cls, name, bases, classdict):\n           result = type.__new__(cls, name, bases, dict(classdict))\n           result.members = tuple(classdict)\n           return result\n\n   class A(metaclass=OrderedClass):\n       def one(self): pass\n       def two(self): pass\n       def three(self): pass\n       def four(self): pass\n\n   >>> A.members\n   (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s ``__prepare__()`` method which returns an\nempty ``collections.OrderedDict``.  That mapping records the methods\nand attributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s ``__new__()`` method gets\ninvoked.  That method builds the new type and it saves the ordered\ndictionary keys in an attribute called *members*.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\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\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items.  It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects.  The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects.  Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators.  It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values.  It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function ``len()``.  Should return\n   the length of the object, an integer ``>=`` 0.  Also, an object\n   that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n   method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods.  A\n  call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with\n  ``None``.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of ``self[key]``. For sequence\n   types, the accepted keys should be integers and slice objects.\n   Note that the special interpretation of negative indexes (if the\n   class wishes to emulate a sequence type) is up to the\n   ``__getitem__()`` method. If *key* is of an inappropriate type,\n   ``TypeError`` may be raised; if of a value outside the set of\n   indexes for the sequence (after any special interpretation of\n   negative values), ``IndexError`` should be raised. For mapping\n   types, if *key* is missing (not in the container), ``KeyError``\n   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     sequence.\n\nobject.__setitem__(self, key, value)\n\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   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\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   raised for improper *key* values as for the ``__getitem__()``\n   method.\n\nobject.__iter__(self)\n\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   available as the method ``keys()``.\n\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\nobject.__reversed__(self)\n\n   Called (if present) by the ``reversed()`` builtin to 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\n   If the ``__reversed__()`` method is not provided, the\n   ``reversed()`` builtin will fall back to using the sequence\n   protocol (``__len__()`` and ``__getitem__()``).  Objects that\n   support the sequence protocol should only provide\n   ``__reversed__()`` if they can provide an implementation that is\n   more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\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   the key-item pairs.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [3]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left operand\'s\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand\'s\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code.  Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__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   specified in the ``as`` clause of the statement, if any.\n\nobject.__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   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   exception (i.e., prevent it from being propagated), it should\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   exception; this is the caller\'s responsibility.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception:\n\n   >>> class C(object):\n   ...     pass\n   ...\n   >>> c = C()\n   >>> c.__len__ = lambda: 5\n   >>> len(c)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n   >>> 1 .__hash__() == hash(1)\n   True\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\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n   >>> type(1).__hash__(1) == hash(1)\n   True\n   >>> type(int).__hash__(int) == hash(int)\n   True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n   >>> class Meta(type):\n   ...    def __getattribute__(*args):\n   ...       print("Metaclass getattribute invoked")\n   ...       return type.__getattribute__(*args)\n   ...\n   >>> class C(object, metaclass=Meta):\n   ...     def __len__(self):\n   ...         return 10\n   ...     def __getattribute__(*args):\n   ...         print("Class getattribute invoked")\n   ...         return object.__getattribute__(*args)\n   ...\n   >>> c = C()\n   >>> c.__len__()                 # Explicit lookup via instance\n   Class getattribute invoked\n   10\n   >>> type(c).__len__(c)          # Explicit lookup via type\n   Metaclass getattribute invoked\n   10\n   >>> len(c)                      # Implicit lookup\n   10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n    certain controlled conditions. It generally isn\'t a good idea\n    though, since it can lead to some very strange behaviour if it is\n    handled incorrectly.\n\n[2] A descriptor can define any combination of ``__get__()``,\n    ``__set__()`` and ``__delete__()``.  If it does not define\n    ``__get__()``, then accessing the attribute even on an instance\n    will return the descriptor object itself.  If the descriptor\n    defines ``__set__()`` and/or ``__delete__()``, it is a data\n    descriptor; if it defines neither, it is a non-data descriptor.\n\n[3] For operands of the same type, it is assumed that if the non-\n    reflected method (such as ``__add__()``) fails the operation is\n    not supported, which is why the reflected method is not called.\n',
- 'string-methods': '\nString Methods\n**************\n\nString objects support the methods listed below.  Note that none of\nthese methods take keyword arguments.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with only its first character\n   capitalized.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\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\nstr.encode([encoding[, errors]])\n\n   Return an encoded version of the string as a bytes object.  Default\n   encoding is the current default string encoding.  *errors* may be\n   given to set a different error handling scheme.  The default for\n   *errors* is ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n   any other name registered via ``codecs.register_error()``, see\n   section *Codec Base Classes*. For a list of possible encodings, see\n   section *Standard Encodings*.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\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   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found, such that *sub* is contained in the range [*start*, *end*].\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The *format_string*\n   argument can contain literal text or replacement fields delimited\n   by braces ``{}``.  Each replacement field contains either the\n   numeric index of a positional argument, or the name of a keyword\n   argument.  Returns a copy of *format_string* where each replacement\n   field is replaced with the string value of the corresponding\n   argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\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\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters include digit characters, and all characters that that\n   can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n   INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.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\nstr.istitle()\n\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   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise.\n\nstr.join(seq)\n\n   Return a string which is the concatenation of the strings in the\n   sequence *seq*.  A ``TypeError`` will be raised if there are any\n   non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.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\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.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   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\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 is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\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   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within s[start,end].  Optional\n   arguments *start* and *end* are interpreted as in slice notation.\n   Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.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   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\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 is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.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   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\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   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([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*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\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*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no 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   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string: words start with\n   uppercase characters, all remaining cased characters are lowercase.\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\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 ``len(s)``.\n',
- 'strings': '\nString and Bytes literals\n*************************\n\nString literals are described by the following lexical definitions:\n\n   stringliteral   ::= [stringprefix](shortstring | longstring)\n   stringprefix    ::= "r" | "R"\n   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n   longstring      ::= "\'\'\'" longstringitem* "\'\'\'" | \'"""\' longstringitem* \'"""\'\n   shortstringitem ::= shortstringchar | stringescapeseq\n   longstringitem  ::= longstringchar | stringescapeseq\n   shortstringchar ::= <any source character except "\\" or newline or the quote>\n   longstringchar  ::= <any source character except "\\">\n   stringescapeseq ::= "\\" <any source character>\n\n   bytesliteral   ::= bytesprefix(shortbytes | longbytes)\n   bytesprefix    ::= "b" | "B"\n   shortbytes     ::= "\'" shortbytesitem* "\'" | \'"\' shortbytesitem* \'"\'\n   longbytes      ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' longbytesitem* \'"""\'\n   shortbytesitem ::= shortbyteschar | bytesescapeseq\n   longbytesitem  ::= longbyteschar | bytesescapeseq\n   shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>\n   longbyteschar  ::= <any ASCII character except "\\">\n   bytesescapeseq ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the **stringprefix** or\n**bytesprefix** and the rest of the literal. The source character set\nis defined by the encoding declaration; it is UTF-8 if no encoding\ndeclaration is given in the source file; see section *Encoding\ndeclarations*.\n\nIn plain English: Both types of literals can be enclosed in matching\nsingle quotes (``\'``) or double quotes (``"``).  They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as *triple-quoted strings*).  The backslash\n(``\\``) character is used to escape characters that otherwise have a\nspecial meaning, such as newline, backslash itself, or the quote\ncharacter.\n\nString literals may optionally be prefixed with a letter ``\'r\'`` or\n``\'R\'``; such strings are called *raw strings* and treat backslashes\nas literal characters.  As a result, ``\'\\U\'`` and ``\'\\u\'`` escapes in\nraw strings are not treated specially.\n\nBytes literals are always prefixed with ``\'b\'`` or ``\'B\'``; they\nproduce an instance of the ``bytes`` type instead of the ``str`` type.\nThey may only contain ASCII characters; bytes with a numeric value of\n128 or greater must be expressed with escapes.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string.  (A "quote" is the character used to open the\nstring, i.e. either ``\'`` or ``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C.  The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| ``\\newline``      | Backslash and newline ignored     |         |\n+-------------------+-----------------------------------+---------+\n| ``\\\\``            | Backslash (``\\``)                 |         |\n+-------------------+-----------------------------------+---------+\n| ``\\\'``            | Single quote (``\'``)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\"``            | Double quote (``"``)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\a``            | ASCII Bell (BEL)                  |         |\n+-------------------+-----------------------------------+---------+\n| ``\\b``            | ASCII Backspace (BS)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\f``            | ASCII Formfeed (FF)               |         |\n+-------------------+-----------------------------------+---------+\n| ``\\n``            | ASCII Linefeed (LF)               |         |\n+-------------------+-----------------------------------+---------+\n| ``\\r``            | ASCII Carriage Return (CR)        |         |\n+-------------------+-----------------------------------+---------+\n| ``\\t``            | ASCII Horizontal Tab (TAB)        |         |\n+-------------------+-----------------------------------+---------+\n| ``\\v``            | ASCII Vertical Tab (VT)           |         |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo``          | Character with octal value *ooo*  | (1,3)   |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh``          | Character with hex value *hh*     | (2,3)   |\n+-------------------+-----------------------------------+---------+\n\nEscape sequences only recognized in string literals are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| ``\\N{name}``      | Character named *name* in the     |         |\n|                   | Unicode database                  |         |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx``        | Character with 16-bit hex value   | (4)     |\n|                   | *xxxx*                            |         |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx``    | Character with 32-bit hex value   | (5)     |\n|                   | *xxxxxxxx*                        |         |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. As in Standard C, up to three octal digits are accepted.\n\n2. Unlike in Standard C, at most two hex digits are accepted.\n\n3. In a bytes literal, hexadecimal and octal escapes denote the byte\n   with the given value. In a string literal, these escapes denote a\n   Unicode character with the given value.\n\n4. Individual code units which form parts of a surrogate pair can be\n   encoded using this escape sequence. Unlike in Standard C, exactly\n   two hex digits are required.\n\n5. 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   default).  Individual code units which form parts of a surrogate\n   pair can be encoded using this escape sequence.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*.  (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.)  It is also\nimportant to note that the escape sequences only recognized in string\nliterals fall into the category of unrecognized escapes for bytes\nliterals.\n\nEven in a raw string, string quotes can be escaped with a backslash,\nbut the backslash remains in the string; for example, ``r"\\""`` is a\nvalid string literal consisting of two characters: a backslash and a\ndouble quote; ``r"\\"`` is not a valid string literal (even a raw\nstring cannot end in an odd number of backslashes).  Specifically, *a\nraw string cannot end in a single backslash* (since the backslash\nwould escape the following quote character).  Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n',
+ 'specialattrs': "\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant.  Some of these are not reported\nby the ``dir()`` built-in function.\n\nobject.__dict__\n\n   A dictionary or other mapping object used to store an object's\n   (writable) attributes.\n\ninstance.__class__\n\n   The class to which a class instance belongs.\n\nclass.__bases__\n\n   The tuple of base classes of a class object.\n\nclass.__name__\n\n   The name of the class or type.\n\nThe following attributes are only supported by *new-style class*es.\n\nclass.__mro__\n\n   This attribute is a tuple of classes that are considered when\n   looking for base classes during method resolution.\n\nclass.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   instantiation, and its result is stored in ``__mro__``.\n\nclass.__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   references still alive. Example:\n\n      >>> int.__subclasses__()\n      [<type 'bool'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found in\n    the Python Reference Manual (*Basic customization*).\n\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 the\n    operands.\n\n[4] To format only a tuple you should therefore provide a singleton\n    tuple whose only element is the tuple to be formatted.\n",
+ 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators.  For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``.  Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled.  For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense.  (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\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   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 (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\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   necessary before returning it.\n\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   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   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  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__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__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,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__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   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\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\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled 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.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     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 ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     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\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   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   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\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   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   ``bool()``; should return ``False`` or ``True``.  When this method\n   is not defined, ``__len__()`` is called, if it is defined, and the\n   object is considered true if its result is nonzero.  If a class\n   defines neither ``__len__()`` nor ``__bool__()``, all its instances\n   are considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\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   in the class tree for ``self``).  ``name`` is the attribute name.\n   This method should return the (computed) attribute value or raise\n   an ``AttributeError`` exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   ``__getattr__()`` is not called.  (This is an intentional asymmetry\n   between ``__getattr__()`` and ``__setattr__()``.) This is done both\n   for efficiency reasons and because otherwise ``__getattr__()``\n   would have no way to access other attributes of the instance.  Note\n   that at least for instance variables, you can fake total control by\n   not 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   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines\n   ``__getattr__()``, the latter will not be called unless\n   ``__getattribute__()`` either calls it explicitly or raises an\n   ``AttributeError``. This method should return the (computed)\n   attribute value or raise an ``AttributeError`` exception. In order\n   to avoid infinite recursion in this method, its implementation\n   should always call the base class method with the same name to\n   access any attributes it needs, for example,\n   ``object.__getattribute__(self, name)``.\n\n   Note: This method may still be bypassed when looking up special methods\n     as the result of implicit invocation via language syntax or\n     built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\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   value to be assigned to it.\n\n   If ``__setattr__()`` wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n   Like ``__setattr__()`` but for attribute deletion instead of\n   assignment.  This should only be implemented if ``del obj.name`` is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when ``dir()`` is called on the object.  A list must be\n   returned.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class.  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\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   return the (computed) attribute value or raise an\n   ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    ``x.__get__(a)``.\n\nInstance Binding\n   If binding to an object instance, ``a.x`` is transformed into the\n   call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n   If binding to a class, ``A.x`` is transformed into the call:\n   ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n   If ``a`` is an instance of ``super``, then the binding ``super(B,\n   obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n   ``A`` immediately preceding ``B`` and then invokes the descriptor\n   with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary.  If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor.  Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method.  Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary.  In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__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   class, *__slots__* reserves space for the declared variables and\n   prevents the automatic creation of *__dict__* and *__weakref__* for\n   each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\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 assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises ``AttributeError``. If\n  dynamic assignment of new variables is desired, then add\n  ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n  *__slots__* do not support weak references to its instances. If weak\n  reference support is needed, then add ``\'__weakref__\'`` to the\n  sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a 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  where it is defined.  As a result, subclasses will have a *__dict__*\n  unless they also define *__slots__* (which must only contain names\n  of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n  variable defined by the base class slot is inaccessible (except by\n  retrieving its descriptor directly from the base class). This\n  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 ``int``, ``str`` and\n  ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n  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  *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if a callable ``metaclass`` keyword\nargument is passed after the bases in the class definition, the\ncallable given will be called instead of ``type()``.  If other keyword\narguments are passed, they will also be passed to the metaclass.  This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n  role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties.  This example adds a new\nelement 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\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\nIf the metaclass has a ``__prepare__()`` attribute (usually\nimplemented as a class or static method), it is called before the\nclass body is evaluated with the name of the class and a tuple of its\nbases for arguments.  It should return an object that supports the\nmapping interface that will be used to store the namespace of the\nclass.  The default is a plain dictionary.  This could be used, for\nexample, to keep track of the order that class attributes are declared\nin by returning an ordered dictionary.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If the ``metaclass`` keyword argument is passed with the bases, it\n  is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n  used.\n\n* Otherwise, the default metaclass (``type``) is used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n``collections.OrderedDict`` to remember the order that class members\nwere defined:\n\n   class OrderedClass(type):\n\n        @classmethod\n        def __prepare__(metacls, name, bases, **kwds):\n           return collections.OrderedDict()\n\n        def __new__(cls, name, bases, classdict):\n           result = type.__new__(cls, name, bases, dict(classdict))\n           result.members = tuple(classdict)\n           return result\n\n   class A(metaclass=OrderedClass):\n       def one(self): pass\n       def two(self): pass\n       def three(self): pass\n       def four(self): pass\n\n   >>> A.members\n   (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s ``__prepare__()`` method which returns an\nempty ``collections.OrderedDict``.  That mapping records the methods\nand attributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s ``__new__()`` method gets\ninvoked.  That method builds the new type and it saves the ordered\ndictionary keys in an attribute called *members*.\n\n\nCustomizing instance and subclass checks\n========================================\n\nThe following methods are used to override the default behavior of the\n``isinstance()`` and ``issubclass()`` built-in functions.\n\nIn particular, the metaclass ``abc.ABCMeta`` implements these methods\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\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\nclass.__subclasscheck__(self, subclass)\n\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\nNote that these methods are looked up on the type (metaclass) of a\nclass.  They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n   **PEP 3119** - Introducing Abstract Base Classes\n      Includes the specification for customizing ``isinstance()`` and\n      ``issubclass()`` behavior through ``__instancecheck__()`` and\n      ``__subclasscheck__()``, with motivation for this functionality\n      in the context of adding Abstract Base Classes (see the ``abc``\n      module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\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\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items.  It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects.  The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects.  Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators.  It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values.  It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function ``len()``.  Should return\n   the length of the object, an integer ``>=`` 0.  Also, an object\n   that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n   method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods.  A\n  call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with\n  ``None``.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of ``self[key]``. For sequence\n   types, the accepted keys should be integers and slice objects.\n   Note that the special interpretation of negative indexes (if the\n   class wishes to emulate a sequence type) is up to the\n   ``__getitem__()`` method. If *key* is of an inappropriate type,\n   ``TypeError`` may be raised; if of a value outside the set of\n   indexes for the sequence (after any special interpretation of\n   negative values), ``IndexError`` should be raised. For mapping\n   types, if *key* is missing (not in the container), ``KeyError``\n   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     sequence.\n\nobject.__setitem__(self, key, value)\n\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   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\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   raised for improper *key* values as for the ``__getitem__()``\n   method.\n\nobject.__iter__(self)\n\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   available as the method ``keys()``.\n\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\nobject.__reversed__(self)\n\n   Called (if present) by the ``reversed()`` built-in to 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\n   If the ``__reversed__()`` method is not provided, the\n   ``reversed()`` built-in will fall back to using the sequence\n   protocol (``__len__()`` and ``__getitem__()``).  Objects that\n   support the sequence protocol should only provide\n   ``__reversed__()`` if they can provide an implementation that is\n   more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\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   the key-item pairs.\n\n   For objects that don\'t define ``__contains__()``, the membership\n   test first tries iteration via ``__iter__()``, then the old\n   sequence iteration protocol via ``__getitem__()``, see *this\n   section in the language reference*.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [2]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left operand\'s\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand\'s\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code.  Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__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   specified in the ``as`` clause of the statement, if any.\n\nobject.__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   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   exception (i.e., prevent it from being propagated), it should\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   exception; this is the caller\'s responsibility.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception:\n\n   >>> class C(object):\n   ...     pass\n   ...\n   >>> c = C()\n   >>> c.__len__ = lambda: 5\n   >>> len(c)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n   >>> 1 .__hash__() == hash(1)\n   True\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\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n   >>> type(1).__hash__(1) == hash(1)\n   True\n   >>> type(int).__hash__(int) == hash(int)\n   True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n   >>> class Meta(type):\n   ...    def __getattribute__(*args):\n   ...       print("Metaclass getattribute invoked")\n   ...       return type.__getattribute__(*args)\n   ...\n   >>> class C(object, metaclass=Meta):\n   ...     def __len__(self):\n   ...         return 10\n   ...     def __getattribute__(*args):\n   ...         print("Class getattribute invoked")\n   ...         return object.__getattribute__(*args)\n   ...\n   >>> c = C()\n   >>> c.__len__()                 # Explicit lookup via instance\n   Class getattribute invoked\n   10\n   >>> type(c).__len__(c)          # Explicit lookup via type\n   Metaclass getattribute invoked\n   10\n   >>> len(c)                      # Implicit lookup\n   10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n    certain controlled conditions. It generally isn\'t a good idea\n    though, since it can lead to some very strange behaviour if it is\n    handled incorrectly.\n\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\n    not supported, which is why the reflected method is not called.\n',
+ 'string-methods': '\nString Methods\n**************\n\nString objects support the methods listed below.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\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\nstr.encode(encoding=sys.getdefaultencoding(), errors="strict")\n\n   Return an encoded version of the string as a bytes object.  Default\n   encoding is the current default string encoding.  *errors* may be\n   given to set a different error handling scheme.  The default for\n   *errors* is ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n   any other name registered via ``codecs.register_error()``, see\n   section *Codec Base Classes*. For a list of possible encodings, see\n   section *Standard Encodings*.\n\n   Changed in version 3.1: Added support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\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   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\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\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or 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   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\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\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\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters include digit characters, and all characters that that\n   can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n   INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.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\nstr.istitle()\n\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   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A ``TypeError`` will be raised if there are\n   any non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.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\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.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   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\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 is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\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   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\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   notation.  Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.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   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\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 is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.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   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\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   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([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*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\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*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no 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   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   The algorithm uses a simple language-independent definition of a\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   result:\n\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 regular\n   expressions:\n\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                            s)\n\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\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   characters:\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\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 ``len(s)``.\n',
+ 'strings': '\nString and Bytes literals\n*************************\n\nString literals are described by the following lexical definitions:\n\n   stringliteral   ::= [stringprefix](shortstring | longstring)\n   stringprefix    ::= "r" | "R"\n   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n   longstring      ::= "\'\'\'" longstringitem* "\'\'\'" | \'"""\' longstringitem* \'"""\'\n   shortstringitem ::= shortstringchar | stringescapeseq\n   longstringitem  ::= longstringchar | stringescapeseq\n   shortstringchar ::= <any source character except "\\" or newline or the quote>\n   longstringchar  ::= <any source character except "\\">\n   stringescapeseq ::= "\\" <any source character>\n\n   bytesliteral   ::= bytesprefix(shortbytes | longbytes)\n   bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR"\n   shortbytes     ::= "\'" shortbytesitem* "\'" | \'"\' shortbytesitem* \'"\'\n   longbytes      ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' longbytesitem* \'"""\'\n   shortbytesitem ::= shortbyteschar | bytesescapeseq\n   longbytesitem  ::= longbyteschar | bytesescapeseq\n   shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>\n   longbyteschar  ::= <any ASCII character except "\\">\n   bytesescapeseq ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the ``stringprefix`` or\n``bytesprefix`` and the rest of the literal. The source character set\nis defined by the encoding declaration; it is UTF-8 if no encoding\ndeclaration is given in the source file; see section *Encoding\ndeclarations*.\n\nIn plain English: Both types of literals can be enclosed in matching\nsingle quotes (``\'``) or double quotes (``"``).  They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as *triple-quoted strings*).  The backslash\n(``\\``) character is used to escape characters that otherwise have a\nspecial meaning, such as newline, backslash itself, or the quote\ncharacter.\n\nBytes literals are always prefixed with ``\'b\'`` or ``\'B\'``; they\nproduce an instance of the ``bytes`` type instead of the ``str`` type.\nThey may only contain ASCII characters; bytes with a numeric value of\n128 or greater must be expressed with escapes.\n\nBoth string and bytes literals may optionally be prefixed with a\nletter ``\'r\'`` or ``\'R\'``; such strings are called *raw strings* and\ntreat backslashes as literal characters.  As a result, in string\nliterals, ``\'\\U\'`` and ``\'\\u\'`` escapes in raw strings are not treated\nspecially.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string.  (A "quote" is the character used to open the\nstring, i.e. either ``\'`` or ``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C.  The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| ``\\newline``      | Backslash and newline ignored     |         |\n+-------------------+-----------------------------------+---------+\n| ``\\\\``            | Backslash (``\\``)                 |         |\n+-------------------+-----------------------------------+---------+\n| ``\\\'``            | Single quote (``\'``)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\"``            | Double quote (``"``)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\a``            | ASCII Bell (BEL)                  |         |\n+-------------------+-----------------------------------+---------+\n| ``\\b``            | ASCII Backspace (BS)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\f``            | ASCII Formfeed (FF)               |         |\n+-------------------+-----------------------------------+---------+\n| ``\\n``            | ASCII Linefeed (LF)               |         |\n+-------------------+-----------------------------------+---------+\n| ``\\r``            | ASCII Carriage Return (CR)        |         |\n+-------------------+-----------------------------------+---------+\n| ``\\t``            | ASCII Horizontal Tab (TAB)        |         |\n+-------------------+-----------------------------------+---------+\n| ``\\v``            | ASCII Vertical Tab (VT)           |         |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo``          | Character with octal value *ooo*  | (1,3)   |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh``          | Character with hex value *hh*     | (2,3)   |\n+-------------------+-----------------------------------+---------+\n\nEscape sequences only recognized in string literals are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| ``\\N{name}``      | Character named *name* in the     |         |\n|                   | Unicode database                  |         |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx``        | Character with 16-bit hex value   | (4)     |\n|                   | *xxxx*                            |         |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx``    | Character with 32-bit hex value   | (5)     |\n|                   | *xxxxxxxx*                        |         |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. As in Standard C, up to three octal digits are accepted.\n\n2. Unlike in Standard C, exactly two hex digits are required.\n\n3. In a bytes literal, hexadecimal and octal escapes denote the byte\n   with the given value. In a string literal, these escapes denote a\n   Unicode character with the given value.\n\n4. Individual code units which form parts of a surrogate pair can be\n   encoded using this escape sequence.  Exactly four hex digits are\n   required.\n\n5. 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   default).  Exactly eight hex digits are required.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*.  (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.)  It is also\nimportant to note that the escape sequences only recognized in string\nliterals fall into the category of unrecognized escapes for bytes\nliterals.\n\nEven in a raw string, string quotes can be escaped with a backslash,\nbut the backslash remains in the string; for example, ``r"\\""`` is a\nvalid string literal consisting of two characters: a backslash and a\ndouble quote; ``r"\\"`` is not a valid string literal (even a raw\nstring cannot end in an odd number of backslashes).  Specifically, *a\nraw string cannot end in a single backslash* (since the backslash\nwould escape the following quote character).  Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n',
  'subscriptions': '\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n   subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object that supports subscription,\ne.g. a list or dictionary.  User-defined objects can support\nsubscription by defining a ``__getitem__()`` method.\n\nFor built-in objects, there are two types of objects that support\nsubscription:\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey.  (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to\nan integer. If this value is negative, the length of the sequence is\nadded to it (so that, e.g., ``x[-1]`` selects the last item of ``x``.)\nThe resulting value must be a nonnegative integer less than the number\nof items in the sequence, and the subscription selects the item whose\nindex is that value (counting from zero).\n\nA string\'s items are characters.  A character is not a separate data\ntype but a string of exactly one character.\n',
  'truth': "\nTruth Value Testing\n*******************\n\nAny object can be tested for truth value, for use in an ``if`` or\n``while`` condition or as operand of the Boolean operations below. The\nfollowing values are considered false:\n\n* ``None``\n\n* ``False``\n\n* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.\n\n* any empty sequence, for example, ``''``, ``()``, ``[]``.\n\n* any empty mapping, for example, ``{}``.\n\n* instances of user-defined classes, if the class defines a\n  ``__bool__()`` or ``__len__()`` method, when that method returns the\n  integer zero or ``bool`` value ``False``. [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\nunless otherwise stated. (Important exception: the Boolean operations\n``or`` and ``and`` always return one of their operands.)\n",
- 'try': '\nThe ``try`` statement\n*********************\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           N = None\n           del N\n\nThat means that you have to assign the exception to a different name\nif you want to be able to refer to it after the except clause.  The\nreason for this is that with the traceback attached to them,\nexceptions will form a reference cycle with the stack frame, keeping\nall locals in that frame alive until the next garbage collection\noccurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting\nof: ``exc_type``, the exception class; ``exc_value``, the exception\ninstance; ``exc_traceback``, a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. ``sys.exc_info()`` values are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n',
- 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python.  Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types.  Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\'  These are attributes that provide access to the\nimplementation and are not intended for general use.  Their definition\nmay change in the future.\n\nNone\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``.\n   It is used to signify the absence of a value in many situations,\n   e.g., it is returned from functions that don\'t explicitly return\n   anything. Its truth value is false.\n\nNotImplemented\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\n   ``NotImplemented``. Numeric methods and rich comparison methods may\n   return this value if they do not implement the operation for the\n   operands provided.  (The interpreter will then try the reflected\n   operation, or some other fallback, depending on the operator.)  Its\n   truth value is true.\n\nEllipsis\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the literal ``...`` or the\n   built-in name ``Ellipsis``.  Its truth value is true.\n\n``numbers.Number``\n   These are created by numeric literals and returned as results by\n   arithmetic operators and arithmetic built-in functions.  Numeric\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   in computers.\n\n   Python distinguishes between integers, floating point numbers, and\n   complex numbers:\n\n   ``numbers.Integral``\n      These represent elements from the mathematical set of integers\n      (positive and negative).\n\n      There are two types of integers:\n\n      Integers (``int``)\n\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         sign bits extending to the left.\n\n      Booleans (``bool``)\n         These represent the truth values False and True.  The two\n         objects representing the values False and True are the only\n         Boolean objects. The Boolean type is a subtype of the integer\n         type, 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      involving negative integers.\n\n   ``numbers.Real`` (``float``)\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      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 is\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\n   ``numbers.Complex`` (``complex``)\n      These represent complex numbers as a pair of machine-level\n      double precision floating point numbers.  The same caveats apply\n      as for floating point numbers. The real and imaginary parts of a\n      complex number ``z`` can be retrieved through the read-only\n      attributes ``z.real`` and ``z.imag``.\n\nSequences\n   These represent finite ordered sets indexed by non-negative\n   numbers. The built-in function ``len()`` returns the number of\n   items of a sequence. When the length of a sequence is *n*, the\n   index set contains the numbers 0, 1, ..., *n*-1.  Item *i* of\n   sequence *a* is selected by ``a[i]``.\n\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   that the index set is renumbered so that it starts at 0.\n\n   Some sequences also support "extended slicing" with a third "step"\n   parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n   where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n   *j*.\n\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      created.  (If the object contains references to other objects,\n      these other objects may be mutable and may be changed; however,\n      the collection of objects directly referenced by an immutable\n      object cannot change.)\n\n      The following types are immutable sequences:\n\n      Strings\n         The items of a string object are Unicode code units.  A\n         Unicode code unit is represented by a string 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         Python is configured at compile time).  Surrogate pairs may\n         be present in the Unicode object, and will be reported as two\n         separate items.  The built-in functions ``chr()`` 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         possible through the string method ``encode()``.\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 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\n      Bytes\n         A bytes object is an immutable array.  The items are 8-bit\n         bytes, represented by integers in the range 0 <= x < 256.\n         Bytes literals (like ``b\'abc\'`` and the built-in function\n         ``bytes()`` can be used to construct bytes objects.  Also,\n         bytes objects can be decoded to strings via the ``decode()``\n         method.\n\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      assignment and ``del`` (delete) statements.\n\n      There are currently two intrinsic mutable sequence types:\n\n      Lists\n         The items of a list are arbitrary Python objects.  Lists are\n         formed by placing a comma-separated list of expressions in\n         square brackets. (Note that there are no special cases needed\n         to form lists of length 0 or 1.)\n\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         mutable (and hence unhashable), byte arrays otherwise provide\n         the same interface and functionality as immutable bytes\n         objects.\n\n      The extension module ``array`` provides an additional example of\n      a mutable sequence type, as does the ``collections`` module.\n\nSet types\n   These represent unordered, finite sets of unique, immutable\n   objects. As such, they cannot be indexed by any subscript. However,\n   they can be iterated over, and the built-in function ``len()``\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   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   ``1.0``), only one of them can be contained in a set.\n\n   There are currently two intrinsic set types:\n\n   Sets\n      These represent a mutable set. They are created by the built-in\n      ``set()`` constructor and can be modified afterwards by several\n      methods, such as ``add()``.\n\n   Frozen sets\n      These represent an immutable set.  They are created by the\n      built-in ``frozenset()`` constructor.  As a frozenset is\n      immutable and *hashable*, it can be used again as an element of\n      another set, or as a dictionary key.\n\nMappings\n   These represent finite sets of objects indexed by arbitrary index\n   sets. The subscript notation ``a[k]`` selects the item indexed by\n   ``k`` from the mapping ``a``; this can be used in expressions and\n   as the target of assignments or ``del`` statements. The built-in\n   function ``len()`` returns the number of items in a mapping.\n\n   There is currently a single intrinsic mapping type:\n\n   Dictionaries\n      These represent finite sets of objects indexed by nearly\n      arbitrary values.  The only types of values not acceptable as\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      Numeric types used for keys obey the normal rules for numeric\n      comparison: if two numbers compare equal (e.g., ``1`` and\n      ``1.0``) 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      notation (see section *Dictionary displays*).\n\n      The extension modules ``dbm.ndbm`` and ``dbm.gnu`` provide\n      additional examples of mapping types, as does the\n      ``collections`` module.\n\nCallable types\n   These are the types to which the function call operation (see\n   section *Calls*) can be applied:\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      called with an argument list containing the same number of items\n      as the function\'s formal parameter list.\n\n      Special attributes:\n\n      +---------------------------+---------------------------------+-------------+\n      | Attribute                 | Meaning                         |             |\n      +===========================+=================================+=============+\n      | ``__doc__``               | The function\'s documentation    | Writable    |\n      |                           | string, or ``None`` if          |             |\n      |                           | unavailable                     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__name__``              | The function\'s name             | Writable    |\n      +---------------------------+---------------------------------+-------------+\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      |                           | argument values for those       |             |\n      |                           | arguments that have defaults,   |             |\n      |                           | or ``None`` if no arguments     |             |\n      |                           | have a default value            |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__code__``              | The code object representing    | Writable    |\n      |                           | the compiled function body.     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__globals__``           | A reference to the dictionary   | Read-only   |\n      |                           | that holds the function\'s       |             |\n      |                           | global variables --- the global |             |\n      |                           | namespace of the module in      |             |\n      |                           | which the function was defined. |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__dict__``              | The namespace supporting        | Writable    |\n      |                           | arbitrary function attributes.  |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__closure__``           | ``None`` or a tuple of cells    | Read-only   |\n      |                           | that contain bindings for the   |             |\n      |                           | function\'s free variables.      |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__annotations__``       | A dict containing annotations   | Writable    |\n      |                           | of parameters.  The keys of the |             |\n      |                           | dict are the parameter names,   |             |\n      |                           | or ``\'return\'`` for the return  |             |\n      |                           | annotation, if provided.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__kwdefaults__``        | A dict containing defaults for  | Writable    |\n      |                           | keyword-only parameters.        |             |\n      +---------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\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      set such attributes. *Note that the current implementation only\n      supports function attributes on user-defined functions. Function\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      retrieved from its code object; see the description of internal\n      types below.\n\n   Instance methods\n      An instance method object combines a class, a class instance and\n      any callable object (normally a user-defined function).\n\n      Special read-only attributes: ``__self__`` is the class instance\n      object, ``__func__`` is the function object; ``__doc__`` is the\n      method\'s documentation (same as ``__func__.__doc__``);\n      ``__name__`` is the method name (same as ``__func__.__name__``);\n      ``__module__`` is the name of the module the method was defined\n      in, or ``None`` if unavailable.\n\n      Methods also support accessing (but not setting) the arbitrary\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 or a class\n      method object.\n\n      When an instance method object is created by retrieving a user-\n      defined function object from a class via one of its instances,\n      its ``__self__`` attribute is the instance, and the method\n      object is said to be bound.  The new method\'s ``__func__``\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 ``__func__``\n      attribute of the new instance is not the original method object\n      but its ``__func__`` attribute.\n\n      When an instance method object is created by retrieving a class\n      method object from a class or instance, its ``__self__``\n      attribute is the class itself, and its ``__func__`` attribute is\n      the function object underlying the class method.\n\n      When an instance method object is called, the underlying\n      function (``__func__``) is called, inserting the class instance\n      (``__self__``) in front of the argument list.  For instance,\n      when ``C`` is a class which contains a definition for a function\n      ``f()``, and ``x`` is an instance of ``C``, calling ``x.f(1)``\n      is equivalent to calling ``C.f(x, 1)``.\n\n      When an instance method object is derived from a class method\n      object, the "class instance" stored in ``__self__`` will\n      actually be the class itself, so that calling either ``x.f(1)``\n      or ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n      the underlying function.\n\n      Note that the transformation from function object to instance\n      method object happens each time the attribute is retrieved from\n      the instance.  In some cases, a fruitful optimization is to\n      assign the attribute to a local variable and call that local\n      variable. Also notice that this transformation only happens for\n      user-defined functions; other callable objects (and all non-\n      callable objects) are retrieved without transformation.  It is\n      also important to note that user-defined functions which are\n      attributes of a class instance are not converted to bound\n      methods; this *only* happens when the function is an attribute\n      of the class.\n\n   Generator functions\n      A function or method which uses the ``yield`` statement (see\n      section *The yield statement*) is called a *generator function*.\n      Such a function, when called, always returns an iterator object\n      which can be used to execute the body of the function:  calling\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\n      the end, a ``StopIteration`` exception is raised and the\n      iterator will have reached the end of the set of values to be\n      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      (``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      string, or ``None`` if unavailable; ``__name__`` is the\n      function\'s name; ``__self__`` is set to ``None`` (but see the\n      next item); ``__module__`` is the name of the module the\n      function was defined in or ``None`` if unavailable.\n\n   Built-in methods\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      case, the special read-only attribute ``__self__`` is set to the\n      object denoted by *list*.\n\n   Classes\n      Classes are callable.  These objects normally act as factories\n      for new instances of themselves, but variations are possible for\n      class types that override ``__new__()``.  The arguments of the\n      call are passed to ``__new__()`` and, in the typical case, to\n      ``__init__()`` to initialize the new instance.\n\n   Class Instances\n      Instances of arbitrary classes can be made callable by defining\n      a ``__call__()`` method in their class.\n\nModules\n   Modules are imported by the ``import`` statement (see section *The\n   import statement*). A module object has a namespace implemented by\n   a dictionary object (this is the dictionary referenced by the\n   __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   (since it isn\'t needed once the initialization is done).\n\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 namespace\n   as a dictionary object.\n\n   Predefined (writable) attributes: ``__name__`` is the module\'s\n   name; ``__doc__`` is the module\'s documentation string, or ``None``\n   if unavailable; ``__file__`` is the pathname of the file from which\n   the module was loaded, if it was loaded from a file. The\n   ``__file__`` attribute is not present for C modules that are\n   statically linked into the interpreter; for extension modules\n   loaded dynamically from a shared library, it is the pathname of the\n   shared library file.\n\nCustom classes\n   Custon class types are typically created by class definitions (see\n   section *Class definitions*).  A class has a namespace implemented\n   by a dictionary object. Class attribute references are translated\n   to lookups in this dictionary, e.g., ``C.x`` is translated to\n   ``C.__dict__["x"]`` (although there are a number of hooks which\n   allow for other means of locating attributes). When the attribute\n   name is not found there, the attribute search continues in the base\n   classes. This search of the base classes uses the C3 method\n   resolution order which behaves correctly even in the presence of\n   \'diamond\' inheritance structures where there are multiple\n   inheritance paths leading back to a common ancestor. Additional\n   details on the C3 MRO used by Python can be found in the\n   documentation accompanying the 2.3 release at\n   http://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class ``C``, say) would yield\n   a class method object, it is transformed into an instance method\n   object whose ``__self__`` attributes is ``C``.  When it would yield\n   a static method object, it is transformed into the object wrapped\n   by the static method object. See section *Implementing Descriptors*\n   for another way in which attributes retrieved from a class may\n   differ from those actually contained in its ``__dict__``.\n\n   Class attribute assignments update the class\'s dictionary, never\n   the dictionary of a base class.\n\n   A class object can be called (see above) to yield a class instance\n   (see below).\n\n   Special attributes: ``__name__`` is the class name; ``__module__``\n   is the module name in which the class was defined; ``__dict__`` is\n   the dictionary containing the class\'s namespace; ``__bases__`` is a\n   tuple (possibly empty or a singleton) containing the base classes,\n   in the order of their occurrence in the base class list;\n   ``__doc__`` is the class\'s documentation string, or None if\n   undefined.\n\nClass instances\n   A class instance is created by calling a class object (see 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   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   attributes.  If a class attribute is found that is a user-defined\n   function object, it is transformed into an instance method object\n   whose ``__self__`` attribute is the instance.  Static method and\n   class method objects are also transformed; see above under\n   "Classes".  See section *Implementing Descriptors* for another way\n   in which attributes of a class retrieved via its instances may\n   differ from the objects actually stored in the class\'s\n   ``__dict__``.  If no class attribute is found, and the object\'s\n   class has a ``__getattr__()`` method, that is called to satisfy the\n   lookup.\n\n   Attribute assignments and deletions update the instance\'s\n   dictionary, never a class\'s dictionary.  If the class has a\n   ``__setattr__()`` or ``__delattr__()`` method, this is called\n   instead of updating the instance dictionary directly.\n\n   Class instances can pretend to be numbers, sequences, or mappings\n   if they have methods with certain special names.  See section\n   *Special method names*.\n\n   Special attributes: ``__dict__`` is the attribute dictionary;\n   ``__class__`` is the instance\'s class.\n\nFiles\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\n   (and perhaps by other functions or methods provided by extension\n   modules).  The objects ``sys.stdin``, ``sys.stdout`` and\n   ``sys.stderr`` are initialized to file objects corresponding to the\n   interpreter\'s standard input, output and error streams.  See *File\n   Objects* for complete documentation of file objects.\n\nInternal 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   interpreter, but they are mentioned here for completeness.\n\n   Code objects\n      Code objects represent *byte-compiled* executable Python code,\n      or *bytecode*. The difference between a code object and a\n      function object is that the function object contains an 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      default argument values are stored in the function object, not\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 mutable\n      objects.\n\n      Special read-only attributes: ``co_name`` gives the function\n      name; ``co_argcount`` is the number of positional arguments\n      (including arguments with default values); ``co_nlocals`` is the\n      number of local variables used by the function (including\n      arguments); ``co_varnames`` is a tuple containing the names of\n      the local variables (starting with the argument names);\n      ``co_cellvars`` is a tuple containing the names of local\n      variables that are referenced by nested functions;\n      ``co_freevars`` is a tuple containing the names of free\n      variables; ``co_code`` is a string representing the sequence of\n      bytecode instructions; ``co_consts`` is a tuple containing the\n      literals used by the bytecode; ``co_names`` is a tuple\n      containing the names used by the bytecode; ``co_filename`` is\n      the filename from which the code was compiled;\n      ``co_firstlineno`` is the first line number of the function;\n      ``co_lnotab`` is a string encoding the mapping from bytecode\n      offsets to line numbers (for details see the source code of the\n      interpreter); ``co_stacksize`` is the required stack size\n      (including local variables); ``co_flags`` is an integer encoding\n      a number of flags for the interpreter.\n\n      The following flag bits are defined for ``co_flags``: bit\n      ``0x04`` is set if the function uses the ``*arguments`` syntax\n      to accept an arbitrary number of positional arguments; bit\n      ``0x08`` is set if the function uses the ``**keywords`` syntax\n      to accept arbitrary keyword arguments; bit ``0x20`` is set if\n      the function is a generator.\n\n      Future feature declarations (``from __future__ import\n      division``) also use bits in ``co_flags`` to indicate whether a\n      code object was compiled with a particular feature enabled: bit\n      ``0x2000`` is set if the function was compiled with future\n      division enabled; bits ``0x10`` and ``0x1000`` were used in\n      earlier versions of Python.\n\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      ``None`` if undefined.\n\n   Frame objects\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\n      stack frame (towards the caller), or ``None`` if this is the\n      bottom stack frame; ``f_code`` is the code object being executed\n      in this frame; ``f_locals`` is the dictionary used to look up\n      local variables; ``f_globals`` is used for global variables;\n      ``f_builtins`` is used for built-in (intrinsic) names;\n      ``f_lasti`` gives the precise instruction (this is an index into\n      the bytecode string of the code object).\n\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_lineno`` is the current line number\n      of the frame --- writing to this from within a trace function\n      jumps to the given line (only for the bottom-most frame).  A\n      debugger can implement a Jump command (aka Set Next Statement)\n      by writing to f_lineno.\n\n   Traceback objects\n      Traceback objects represent a stack trace of an exception.  A\n      traceback object is created when an exception occurs.  When the\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 the third item of the\n      tuple returned by ``sys.exc_info()``. When the program contains\n      no suitable handler, the stack trace is written (nicely\n      formatted) to the standard error stream; if the interpreter is\n      interactive, it is also made available to the user as\n      ``sys.last_traceback``.\n\n      Special read-only attributes: ``tb_next`` is the next level in\n      the stack trace (towards the frame where the exception\n      occurred), or ``None`` if there is no next level; ``tb_frame``\n      points to the execution frame of the current level;\n      ``tb_lineno`` gives the line number where the exception\n      occurred; ``tb_lasti`` indicates the precise instruction.  The\n      line number and last instruction in the traceback may differ\n      from the line number of its frame object if the exception\n      occurred in a ``try`` statement with no matching except clause\n      or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices for ``__getitem__()``\n      methods.  They are also created by the built-in ``slice()``\n      function.\n\n      Special read-only attributes: ``start`` is the lower bound;\n      ``stop`` is the upper bound; ``step`` is the step value; each is\n      ``None`` if 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         computes information about the slice that the slice object\n         would describe if applied to a sequence of *length* items.\n         It returns a tuple of three integers; respectively these are\n         the *start* and *stop* indices and the *step* or stride\n         length of the slice. Missing or out-of-bounds indices are\n         handled in a manner consistent with regular slices.\n\n   Static method objects\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      not themselves callable, although the objects they wrap usually\n      are. Static method objects are created by the built-in\n      ``staticmethod()`` constructor.\n\n   Class method objects\n      A class method object, like a static method object, is a 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      under "User-defined methods". Class method objects are created\n      by the built-in ``classmethod()`` constructor.\n',
+ 'try': '\nThe ``try`` statement\n*********************\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting\nof: ``exc_type``, the exception class; ``exc_value``, the exception\ninstance; ``exc_traceback``, a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. ``sys.exc_info()`` values are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n',
+ 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python.  Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types.  Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\'  These are attributes that provide access to the\nimplementation and are not intended for general use.  Their definition\nmay change in the future.\n\nNone\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``.\n   It is used to signify the absence of a value in many situations,\n   e.g., it is returned from functions that don\'t explicitly return\n   anything. Its truth value is false.\n\nNotImplemented\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\n   ``NotImplemented``. Numeric methods and rich comparison methods may\n   return this value if they do not implement the operation for the\n   operands provided.  (The interpreter will then try the reflected\n   operation, or some other fallback, depending on the operator.)  Its\n   truth value is true.\n\nEllipsis\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the literal ``...`` or the\n   built-in name ``Ellipsis``.  Its truth value is true.\n\n``numbers.Number``\n   These are created by numeric literals and returned as results by\n   arithmetic operators and arithmetic built-in functions.  Numeric\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   in computers.\n\n   Python distinguishes between integers, floating point numbers, and\n   complex numbers:\n\n   ``numbers.Integral``\n      These represent elements from the mathematical set of integers\n      (positive and negative).\n\n      There are two types of integers:\n\n      Integers (``int``)\n\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         sign bits extending to the left.\n\n      Booleans (``bool``)\n         These represent the truth values False and True.  The two\n         objects representing the values False and True are the only\n         Boolean objects. The Boolean type is a subtype of the integer\n         type, 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      involving negative integers.\n\n   ``numbers.Real`` (``float``)\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      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 is\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\n   ``numbers.Complex`` (``complex``)\n      These represent complex numbers as a pair of machine-level\n      double precision floating point numbers.  The same caveats apply\n      as for floating point numbers. The real and imaginary parts of a\n      complex number ``z`` can be retrieved through the read-only\n      attributes ``z.real`` and ``z.imag``.\n\nSequences\n   These represent finite ordered sets indexed by non-negative\n   numbers. The built-in function ``len()`` returns the number of\n   items of a sequence. When the length of a sequence is *n*, the\n   index set contains the numbers 0, 1, ..., *n*-1.  Item *i* of\n   sequence *a* is selected by ``a[i]``.\n\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   that the index set is renumbered so that it starts at 0.\n\n   Some sequences also support "extended slicing" with a third "step"\n   parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n   where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n   *j*.\n\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      created.  (If the object contains references to other objects,\n      these other objects may be mutable and may be changed; however,\n      the collection of objects directly referenced by an immutable\n      object cannot change.)\n\n      The following types are immutable sequences:\n\n      Strings\n         The items of a string object are Unicode code units.  A\n         Unicode code unit is represented by a string 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         Python is configured at compile time).  Surrogate pairs may\n         be present in the Unicode object, and will be reported as two\n         separate items.  The built-in functions ``chr()`` 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         possible through the string method ``encode()``.\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 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\n      Bytes\n         A bytes object is an immutable array.  The items are 8-bit\n         bytes, represented by integers in the range 0 <= x < 256.\n         Bytes literals (like ``b\'abc\'`` and the built-in function\n         ``bytes()`` can be used to construct bytes objects.  Also,\n         bytes objects can be decoded to strings via the ``decode()``\n         method.\n\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      assignment and ``del`` (delete) statements.\n\n      There are currently two intrinsic mutable sequence types:\n\n      Lists\n         The items of a list are arbitrary Python objects.  Lists are\n         formed by placing a comma-separated list of expressions in\n         square brackets. (Note that there are no special cases needed\n         to form lists of length 0 or 1.)\n\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         mutable (and hence unhashable), byte arrays otherwise provide\n         the same interface and functionality as immutable bytes\n         objects.\n\n      The extension module ``array`` provides an additional example of\n      a mutable sequence type, as does the ``collections`` module.\n\nSet types\n   These represent unordered, finite sets of unique, immutable\n   objects. As such, they cannot be indexed by any subscript. However,\n   they can be iterated over, and the built-in function ``len()``\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   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   ``1.0``), only one of them can be contained in a set.\n\n   There are currently two intrinsic set types:\n\n   Sets\n      These represent a mutable set. They are created by the built-in\n      ``set()`` constructor and can be modified afterwards by several\n      methods, such as ``add()``.\n\n   Frozen sets\n      These represent an immutable set.  They are created by the\n      built-in ``frozenset()`` constructor.  As a frozenset is\n      immutable and *hashable*, it can be used again as an element of\n      another set, or as a dictionary key.\n\nMappings\n   These represent finite sets of objects indexed by arbitrary index\n   sets. The subscript notation ``a[k]`` selects the item indexed by\n   ``k`` from the mapping ``a``; this can be used in expressions and\n   as the target of assignments or ``del`` statements. The built-in\n   function ``len()`` returns the number of items in a mapping.\n\n   There is currently a single intrinsic mapping type:\n\n   Dictionaries\n      These represent finite sets of objects indexed by nearly\n      arbitrary values.  The only types of values not acceptable as\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      Numeric types used for keys obey the normal rules for numeric\n      comparison: if two numbers compare equal (e.g., ``1`` and\n      ``1.0``) 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      notation (see section *Dictionary displays*).\n\n      The extension modules ``dbm.ndbm`` and ``dbm.gnu`` provide\n      additional examples of mapping types, as does the\n      ``collections`` module.\n\nCallable types\n   These are the types to which the function call operation (see\n   section *Calls*) can be applied:\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      called with an argument list containing the same number of items\n      as the function\'s formal parameter list.\n\n      Special attributes:\n\n      +---------------------------+---------------------------------+-------------+\n      | Attribute                 | Meaning                         |             |\n      +===========================+=================================+=============+\n      | ``__doc__``               | The function\'s documentation    | Writable    |\n      |                           | string, or ``None`` if          |             |\n      |                           | unavailable                     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__name__``              | The function\'s name             | Writable    |\n      +---------------------------+---------------------------------+-------------+\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      |                           | argument values for those       |             |\n      |                           | arguments that have defaults,   |             |\n      |                           | or ``None`` if no arguments     |             |\n      |                           | have a default value            |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__code__``              | The code object representing    | Writable    |\n      |                           | the compiled function body.     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__globals__``           | A reference to the dictionary   | Read-only   |\n      |                           | that holds the function\'s       |             |\n      |                           | global variables --- the global |             |\n      |                           | namespace of the module in      |             |\n      |                           | which the function was defined. |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__dict__``              | The namespace supporting        | Writable    |\n      |                           | arbitrary function attributes.  |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__closure__``           | ``None`` or a tuple of cells    | Read-only   |\n      |                           | that contain bindings for the   |             |\n      |                           | function\'s free variables.      |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__annotations__``       | A dict containing annotations   | Writable    |\n      |                           | of parameters.  The keys of the |             |\n      |                           | dict are the parameter names,   |             |\n      |                           | or ``\'return\'`` for the return  |             |\n      |                           | annotation, if provided.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__kwdefaults__``        | A dict containing defaults for  | Writable    |\n      |                           | keyword-only parameters.        |             |\n      +---------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\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      set such attributes. *Note that the current implementation only\n      supports function attributes on user-defined functions. Function\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      retrieved from its code object; see the description of internal\n      types below.\n\n   Instance methods\n      An instance method object combines a class, a class instance and\n      any callable object (normally a user-defined function).\n\n      Special read-only attributes: ``__self__`` is the class instance\n      object, ``__func__`` is the function object; ``__doc__`` is the\n      method\'s documentation (same as ``__func__.__doc__``);\n      ``__name__`` is the method name (same as ``__func__.__name__``);\n      ``__module__`` is the name of the module the method was defined\n      in, or ``None`` if unavailable.\n\n      Methods also support accessing (but not setting) the arbitrary\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 or a class\n      method object.\n\n      When an instance method object is created by retrieving a user-\n      defined function object from a class via one of its instances,\n      its ``__self__`` attribute is the instance, and the method\n      object is said to be bound.  The new method\'s ``__func__``\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 ``__func__``\n      attribute of the new instance is not the original method object\n      but its ``__func__`` attribute.\n\n      When an instance method object is created by retrieving a class\n      method object from a class or instance, its ``__self__``\n      attribute is the class itself, and its ``__func__`` attribute is\n      the function object underlying the class method.\n\n      When an instance method object is called, the underlying\n      function (``__func__``) is called, inserting the class instance\n      (``__self__``) in front of the argument list.  For instance,\n      when ``C`` is a class which contains a definition for a function\n      ``f()``, and ``x`` is an instance of ``C``, calling ``x.f(1)``\n      is equivalent to calling ``C.f(x, 1)``.\n\n      When an instance method object is derived from a class method\n      object, the "class instance" stored in ``__self__`` will\n      actually be the class itself, so that calling either ``x.f(1)``\n      or ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n      the underlying function.\n\n      Note that the transformation from function object to instance\n      method object happens each time the attribute is retrieved from\n      the instance.  In some cases, a fruitful optimization is to\n      assign the attribute to a local variable and call that local\n      variable. Also notice that this transformation only happens for\n      user-defined functions; other callable objects (and all non-\n      callable objects) are retrieved without transformation.  It is\n      also important to note that user-defined functions which are\n      attributes of a class instance are not converted to bound\n      methods; this *only* happens when the function is an attribute\n      of the class.\n\n   Generator functions\n      A function or method which uses the ``yield`` statement (see\n      section *The yield statement*) is called a *generator function*.\n      Such a function, when called, always returns an iterator object\n      which can be used to execute the body of the function:  calling\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\n      the end, a ``StopIteration`` exception is raised and the\n      iterator will have reached the end of the set of values to be\n      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      (``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      string, or ``None`` if unavailable; ``__name__`` is the\n      function\'s name; ``__self__`` is set to ``None`` (but see the\n      next item); ``__module__`` is the name of the module the\n      function was defined in or ``None`` if unavailable.\n\n   Built-in methods\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      case, the special read-only attribute ``__self__`` is set to the\n      object denoted by *list*.\n\n   Classes\n      Classes are callable.  These objects normally act as factories\n      for new instances of themselves, but variations are possible for\n      class types that override ``__new__()``.  The arguments of the\n      call are passed to ``__new__()`` and, in the typical case, to\n      ``__init__()`` to initialize the new instance.\n\n   Class Instances\n      Instances of arbitrary classes can be made callable by defining\n      a ``__call__()`` method in their class.\n\nModules\n   Modules are imported by the ``import`` statement (see section *The\n   import statement*). A module object has a namespace implemented by\n   a dictionary object (this is the dictionary referenced by the\n   __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   (since it isn\'t needed once the initialization is done).\n\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 namespace\n   as a dictionary object.\n\n   Predefined (writable) attributes: ``__name__`` is the module\'s\n   name; ``__doc__`` is the module\'s documentation string, or ``None``\n   if unavailable; ``__file__`` is the pathname of the file from which\n   the module was loaded, if it was loaded from a file. The\n   ``__file__`` attribute is not present for C modules that are\n   statically linked into the interpreter; for extension modules\n   loaded dynamically from a shared library, it is the pathname of the\n   shared library file.\n\nCustom classes\n   Custom class types are typically created by class definitions (see\n   section *Class definitions*).  A class has a namespace implemented\n   by a dictionary object. Class attribute references are translated\n   to lookups in this dictionary, e.g., ``C.x`` is translated to\n   ``C.__dict__["x"]`` (although there are a number of hooks which\n   allow for other means of locating attributes). When the attribute\n   name is not found there, the attribute search continues in the base\n   classes. This search of the base classes uses the C3 method\n   resolution order which behaves correctly even in the presence of\n   \'diamond\' inheritance structures where there are multiple\n   inheritance paths leading back to a common ancestor. Additional\n   details on the C3 MRO used by Python can be found in the\n   documentation accompanying the 2.3 release at\n   http://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class ``C``, say) would yield\n   a class method object, it is transformed into an instance method\n   object whose ``__self__`` attributes is ``C``.  When it would yield\n   a static method object, it is transformed into the object wrapped\n   by the static method object. See section *Implementing Descriptors*\n   for another way in which attributes retrieved from a class may\n   differ from those actually contained in its ``__dict__``.\n\n   Class attribute assignments update the class\'s dictionary, never\n   the dictionary of a base class.\n\n   A class object can be called (see above) to yield a class instance\n   (see below).\n\n   Special attributes: ``__name__`` is the class name; ``__module__``\n   is the module name in which the class was defined; ``__dict__`` is\n   the dictionary containing the class\'s namespace; ``__bases__`` is a\n   tuple (possibly empty or a singleton) containing the base classes,\n   in the order of their occurrence in the base class list;\n   ``__doc__`` is the class\'s documentation string, or None if\n   undefined.\n\nClass instances\n   A class instance is created by calling a class object (see 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   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   attributes.  If a class attribute is found that is a user-defined\n   function object, it is transformed into an instance method object\n   whose ``__self__`` attribute is the instance.  Static method and\n   class method objects are also transformed; see above under\n   "Classes".  See section *Implementing Descriptors* for another way\n   in which attributes of a class retrieved via its instances may\n   differ from the objects actually stored in the class\'s\n   ``__dict__``.  If no class attribute is found, and the object\'s\n   class has a ``__getattr__()`` method, that is called to satisfy the\n   lookup.\n\n   Attribute assignments and deletions update the instance\'s\n   dictionary, never a class\'s dictionary.  If the class has a\n   ``__setattr__()`` or ``__delattr__()`` method, this is called\n   instead of updating the instance dictionary directly.\n\n   Class instances can pretend to be numbers, sequences, or mappings\n   if they have methods with certain special names.  See section\n   *Special method names*.\n\n   Special attributes: ``__dict__`` is the attribute dictionary;\n   ``__class__`` is the instance\'s class.\n\nI/O objects (also known as file objects)\n   A file object represents an open file.  Various shortcuts are\n   available to create file objects: the ``open()`` built-in function,\n   and also ``os.popen()``, ``os.fdopen()``, and the ``makefile()``\n   method of socket objects (and perhaps by other functions or methods\n   provided by extension modules).\n\n   The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are\n   initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams; they are all open in text\n   mode and therefore follow the interface defined by the\n   ``io.TextIOBase`` abstract class.\n\nInternal 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   interpreter, but they are mentioned here for completeness.\n\n   Code objects\n      Code objects represent *byte-compiled* executable Python code,\n      or *bytecode*. The difference between a code object and a\n      function object is that the function object contains an 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      default argument values are stored in the function object, not\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 mutable\n      objects.\n\n      Special read-only attributes: ``co_name`` gives the function\n      name; ``co_argcount`` is the number of positional arguments\n      (including arguments with default values); ``co_nlocals`` is the\n      number of local variables used by the function (including\n      arguments); ``co_varnames`` is a tuple containing the names of\n      the local variables (starting with the argument names);\n      ``co_cellvars`` is a tuple containing the names of local\n      variables that are referenced by nested functions;\n      ``co_freevars`` is a tuple containing the names of free\n      variables; ``co_code`` is a string representing the sequence of\n      bytecode instructions; ``co_consts`` is a tuple containing the\n      literals used by the bytecode; ``co_names`` is a tuple\n      containing the names used by the bytecode; ``co_filename`` is\n      the filename from which the code was compiled;\n      ``co_firstlineno`` is the first line number of the function;\n      ``co_lnotab`` is a string encoding the mapping from bytecode\n      offsets to line numbers (for details see the source code of the\n      interpreter); ``co_stacksize`` is the required stack size\n      (including local variables); ``co_flags`` is an integer encoding\n      a number of flags for the interpreter.\n\n      The following flag bits are defined for ``co_flags``: bit\n      ``0x04`` is set if the function uses the ``*arguments`` syntax\n      to accept an arbitrary number of positional arguments; bit\n      ``0x08`` is set if the function uses the ``**keywords`` syntax\n      to accept arbitrary keyword arguments; bit ``0x20`` is set if\n      the function is a generator.\n\n      Future feature declarations (``from __future__ import\n      division``) also use bits in ``co_flags`` to indicate whether a\n      code object was compiled with a particular feature enabled: bit\n      ``0x2000`` is set if the function was compiled with future\n      division enabled; bits ``0x10`` and ``0x1000`` were used in\n      earlier versions of Python.\n\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      ``None`` if undefined.\n\n   Frame objects\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\n      stack frame (towards the caller), or ``None`` if this is the\n      bottom stack frame; ``f_code`` is the code object being executed\n      in this frame; ``f_locals`` is the dictionary used to look up\n      local variables; ``f_globals`` is used for global variables;\n      ``f_builtins`` is used for built-in (intrinsic) names;\n      ``f_lasti`` gives the precise instruction (this is an index into\n      the bytecode string of the code object).\n\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_lineno`` is the current line number\n      of the frame --- writing to this from within a trace function\n      jumps to the given line (only for the bottom-most frame).  A\n      debugger can implement a Jump command (aka Set Next Statement)\n      by writing to f_lineno.\n\n   Traceback objects\n      Traceback objects represent a stack trace of an exception.  A\n      traceback object is created when an exception occurs.  When the\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 the third item of the\n      tuple returned by ``sys.exc_info()``. When the program contains\n      no suitable handler, the stack trace is written (nicely\n      formatted) to the standard error stream; if the interpreter is\n      interactive, it is also made available to the user as\n      ``sys.last_traceback``.\n\n      Special read-only attributes: ``tb_next`` is the next level in\n      the stack trace (towards the frame where the exception\n      occurred), or ``None`` if there is no next level; ``tb_frame``\n      points to the execution frame of the current level;\n      ``tb_lineno`` gives the line number where the exception\n      occurred; ``tb_lasti`` indicates the precise instruction.  The\n      line number and last instruction in the traceback may differ\n      from the line number of its frame object if the exception\n      occurred in a ``try`` statement with no matching except clause\n      or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices for ``__getitem__()``\n      methods.  They are also created by the built-in ``slice()``\n      function.\n\n      Special read-only attributes: ``start`` is the lower bound;\n      ``stop`` is the upper bound; ``step`` is the step value; each is\n      ``None`` if 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         computes information about the slice that the slice object\n         would describe if applied to a sequence of *length* items.\n         It returns a tuple of three integers; respectively these are\n         the *start* and *stop* indices and the *step* or stride\n         length of the slice. Missing or out-of-bounds indices are\n         handled in a manner consistent with regular slices.\n\n   Static method objects\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      not themselves callable, although the objects they wrap usually\n      are. Static method objects are created by the built-in\n      ``staticmethod()`` constructor.\n\n   Class method objects\n      A class method object, like a static method object, is a 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      under "User-defined methods". Class method objects are created\n      by the built-in ``classmethod()`` constructor.\n',
  'typesfunctions': '\nFunctions\n*********\n\nFunction objects are created by function definitions.  The only\noperation on a function object is to call it: ``func(argument-list)``.\n\nThere are really two flavors of function objects: built-in functions\nand user-defined functions.  Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\n\nSee *Function definitions* for more information.\n',
- 'typesmapping': '\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects.  There is currently only one standard\nmapping type, the *dictionary*.  (For other containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values.  Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys.  Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry.  (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n   Return a new dictionary initialized from an optional positional\n   argument or from a set of keyword arguments.  If no arguments are\n   given, return a new empty dictionary.  If the positional argument\n   *arg* is a mapping object, return a dictionary mapping the same\n   keys to the same values as does the mapping object.  Otherwise the\n   positional argument must be a sequence, a container that supports\n   iteration, or an iterator object.  The elements of the argument\n   must each also be of one of those kinds, and each must in turn\n   contain exactly two objects.  The first is used as a key in the new\n   dictionary, and the second as the key\'s value.  If a given key is\n   seen more than once, the last value associated with it is retained\n   in the new dictionary.\n\n   If keyword arguments are given, the keywords themselves with their\n   associated values are added as items to the dictionary.  If a key\n   is specified both in the positional argument and as a keyword\n   argument, the value associated with the keyword is retained in the\n   dictionary.  For example, these all return a dictionary equal to\n   ``{"one": 2, "two": 3}``:\n\n   * ``dict(one=2, two=3)``\n\n   * ``dict({\'one\': 2, \'two\': 3})``\n\n   * ``dict(zip((\'one\', \'two\'), (2, 3)))``\n\n   * ``dict([[\'two\', 3], [\'one\', 2]])``\n\n   The first example only works for keys that are valid Python\n   identifiers; the others work with any valid keys.\n\n   These are the operations that dictionaries support (and therefore,\n   custom mapping types should support too):\n\n   len(d)\n\n      Return the number of items in the dictionary *d*.\n\n   d[key]\n\n      Return the item of *d* with key *key*.  Raises a ``KeyError`` if\n      *key* is not in the map.\n\n      If a subclass of dict defines a method ``__missing__()``, if the\n      key *key* is not present, the ``d[key]`` operation calls that\n      method with the key *key* as argument.  The ``d[key]`` operation\n      then returns or raises whatever is returned or raised by the\n      ``__missing__(key)`` call if the key is not present. No other\n      operations or methods invoke ``__missing__()``. If\n      ``__missing__()`` is not defined, ``KeyError`` is raised.\n      ``__missing__()`` must be a method; it cannot be an instance\n      variable. For an example, see ``collections.defaultdict``.\n\n   d[key] = value\n\n      Set ``d[key]`` to *value*.\n\n   del d[key]\n\n      Remove ``d[key]`` from *d*.  Raises a ``KeyError`` if *key* is\n      not in the map.\n\n   key in d\n\n      Return ``True`` if *d* has a key *key*, else ``False``.\n\n   key not in d\n\n      Equivalent to ``not key in d``.\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for ``iterkeys()``.\n\n   clear()\n\n      Remove all items from the dictionary.\n\n   copy()\n\n      Return a shallow copy of the dictionary.\n\n   classmethod fromkeys(seq[, value])\n\n      Create a new dictionary with keys from *seq* and values set to\n      *value*.\n\n      ``fromkeys()`` is a class method that returns a new dictionary.\n      *value* defaults to ``None``.\n\n   get(key[, default])\n\n      Return the value for *key* if *key* is in the dictionary, else\n      *default*. If *default* is not given, it defaults to ``None``,\n      so that this method never raises a ``KeyError``.\n\n   items()\n\n      Return a new view of the dictionary\'s items (``(key, value)``\n      pairs).  See below for documentation of view objects.\n\n   keys()\n\n      Return a new view of the dictionary\'s keys.  See below for\n      documentation of view objects.\n\n   pop(key[, default])\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      not in the dictionary, a ``KeyError`` is raised.\n\n   popitem()\n\n      Remove and return an arbitrary ``(key, value)`` pair from the\n      dictionary.\n\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\n   setdefault(key[, default])\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      defaults to ``None``.\n\n   update([other])\n\n      Update the dictionary with the key/value pairs from *other*,\n      overwriting existing keys.  Return ``None``.\n\n         ``update()`` accepts either another dictionary object or an\n         iterable of key/value pairs (as a tuple or other iterable of\n         length two).  If keyword arguments are specified, the\n         dictionary is then is updated with those key/value pairs:\n         ``d.update(red=1, blue=2)``.\n\n   values()\n\n      Return a new view of the dictionary\'s values.  See below for\n      documentation of view objects.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.keys()``, ``dict.values()`` and\n``dict.items()`` are *view objects*.  They provide a dynamic view on\nthe dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n   Return the number of entries in the dictionary.\n\niter(dictview)\n\n   Return an iterator over the keys, values or items (represented as\n   tuples of ``(key, value)``) in the dictionary.\n\n   Keys and values are iterated over in an arbitrary order which is\n   non-random, varies across Python implementations, and depends on\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   correspond.  This allows the creation of ``(value, key)`` pairs\n   using ``zip()``: ``pairs = zip(d.values(), d.keys())``.  Another\n   way to create the same list is ``pairs = [(v, k) for (k, v) in\n   d.items()]``.\n\n   Iterating views while adding or deleting entries in the dictionary\n   may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n   Return ``True`` if *x* is in the underlying dictionary\'s keys,\n   values or items (in the latter case, *x* should be a ``(key,\n   value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like.  (Values views are not\ntreated as set-like since the entries are generally not unique.)  Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n   Return the intersection of the dictview and the other object as a\n   new set.\n\ndictview | other\n\n   Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n   Return the difference between the dictview and the other object\n   (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n   Return the symmetric difference (all elements either in *dictview*\n   or *other*, but not in both) of the dictview and the other object\n   as a new set.\n\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.keys()\n   >>> values = dishes.values()\n\n   >>> # iteration\n   >>> n = 0\n   >>> for val in values:\n   ...     n += val\n   >>> print(n)\n   504\n\n   >>> # keys and values are iterated over in the same order\n   >>> list(keys)\n   [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n   >>> list(values)\n   [2, 1, 1, 500]\n\n   >>> # view objects are dynamic and reflect dict changes\n   >>> del dishes[\'eggs\']\n   >>> del dishes[\'sausage\']\n   >>> list(keys)\n   [\'spam\', \'bacon\']\n\n   >>> # set operations\n   >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n   {\'bacon\'}\n',
+ 'typesmapping': '\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects.  There is currently only one standard\nmapping type, the *dictionary*.  (For other containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values.  Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys.  Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry.  (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n   Return a new dictionary initialized from an optional positional\n   argument or from a set of keyword arguments.  If no arguments are\n   given, return a new empty dictionary.  If the positional argument\n   *arg* is a mapping object, return a dictionary mapping the same\n   keys to the same values as does the mapping object.  Otherwise the\n   positional argument must be a sequence, a container that supports\n   iteration, or an iterator object.  The elements of the argument\n   must each also be of one of those kinds, and each must in turn\n   contain exactly two objects.  The first is used as a key in the new\n   dictionary, and the second as the key\'s value.  If a given key is\n   seen more than once, the last value associated with it is retained\n   in the new dictionary.\n\n   If keyword arguments are given, the keywords themselves with their\n   associated values are added as items to the dictionary.  If a key\n   is specified both in the positional argument and as a keyword\n   argument, the value associated with the keyword is retained in the\n   dictionary.  For example, these all return a dictionary equal to\n   ``{"one": 2, "two": 3}``:\n\n   * ``dict(one=2, two=3)``\n\n   * ``dict({\'one\': 2, \'two\': 3})``\n\n   * ``dict(zip((\'one\', \'two\'), (2, 3)))``\n\n   * ``dict([[\'two\', 3], [\'one\', 2]])``\n\n   The first example only works for keys that are valid Python\n   identifiers; the others work with any valid keys.\n\n   These are the operations that dictionaries support (and therefore,\n   custom mapping types should support too):\n\n   len(d)\n\n      Return the number of items in the dictionary *d*.\n\n   d[key]\n\n      Return the item of *d* with key *key*.  Raises a ``KeyError`` if\n      *key* is not in the map.\n\n      If a subclass of dict defines a method ``__missing__()``, if the\n      key *key* is not present, the ``d[key]`` operation calls that\n      method with the key *key* as argument.  The ``d[key]`` operation\n      then returns or raises whatever is returned or raised by the\n      ``__missing__(key)`` call if the key is not present. No other\n      operations or methods invoke ``__missing__()``. If\n      ``__missing__()`` is not defined, ``KeyError`` is raised.\n      ``__missing__()`` must be a method; it cannot be an instance\n      variable. For an example, see ``collections.defaultdict``.\n\n   d[key] = value\n\n      Set ``d[key]`` to *value*.\n\n   del d[key]\n\n      Remove ``d[key]`` from *d*.  Raises a ``KeyError`` if *key* is\n      not in the map.\n\n   key in d\n\n      Return ``True`` if *d* has a key *key*, else ``False``.\n\n   key not in d\n\n      Equivalent to ``not key in d``.\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for ``iter(d.keys())``.\n\n   clear()\n\n      Remove all items from the dictionary.\n\n   copy()\n\n      Return a shallow copy of the dictionary.\n\n   classmethod fromkeys(seq[, value])\n\n      Create a new dictionary with keys from *seq* and values set to\n      *value*.\n\n      ``fromkeys()`` is a class method that returns a new dictionary.\n      *value* defaults to ``None``.\n\n   get(key[, default])\n\n      Return the value for *key* if *key* is in the dictionary, else\n      *default*. If *default* is not given, it defaults to ``None``,\n      so that this method never raises a ``KeyError``.\n\n   items()\n\n      Return a new view of the dictionary\'s items (``(key, value)``\n      pairs).  See below for documentation of view objects.\n\n   keys()\n\n      Return a new view of the dictionary\'s keys.  See below for\n      documentation of view objects.\n\n   pop(key[, default])\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      not in the dictionary, a ``KeyError`` is raised.\n\n   popitem()\n\n      Remove and return an arbitrary ``(key, value)`` pair from the\n      dictionary.\n\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\n   setdefault(key[, default])\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      defaults to ``None``.\n\n   update([other])\n\n      Update the dictionary with the key/value pairs from *other*,\n      overwriting existing keys.  Return ``None``.\n\n         ``update()`` accepts either another dictionary object or an\n         iterable of key/value pairs (as a tuple or other iterable of\n         length two).  If keyword arguments are specified, the\n         dictionary is then updated with those key/value pairs:\n         ``d.update(red=1, blue=2)``.\n\n   values()\n\n      Return a new view of the dictionary\'s values.  See below for\n      documentation of view objects.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.keys()``, ``dict.values()`` and\n``dict.items()`` are *view objects*.  They provide a dynamic view on\nthe dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n   Return the number of entries in the dictionary.\n\niter(dictview)\n\n   Return an iterator over the keys, values or items (represented as\n   tuples of ``(key, value)``) in the dictionary.\n\n   Keys and values are iterated over in an arbitrary order which is\n   non-random, varies across Python implementations, and depends on\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   correspond.  This allows the creation of ``(value, key)`` pairs\n   using ``zip()``: ``pairs = zip(d.values(), d.keys())``.  Another\n   way to create the same list is ``pairs = [(v, k) for (k, v) in\n   d.items()]``.\n\n   Iterating views while adding or deleting entries in the dictionary\n   may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n   Return ``True`` if *x* is in the underlying dictionary\'s keys,\n   values or items (in the latter case, *x* should be a ``(key,\n   value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like.  (Values views are not\ntreated as set-like since the entries are generally not unique.)  Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n   Return the intersection of the dictview and the other object as a\n   new set.\n\ndictview | other\n\n   Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n   Return the difference between the dictview and the other object\n   (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n   Return the symmetric difference (all elements either in *dictview*\n   or *other*, but not in both) of the dictview and the other object\n   as a new set.\n\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.keys()\n   >>> values = dishes.values()\n\n   >>> # iteration\n   >>> n = 0\n   >>> for val in values:\n   ...     n += val\n   >>> print(n)\n   504\n\n   >>> # keys and values are iterated over in the same order\n   >>> list(keys)\n   [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n   >>> list(values)\n   [2, 1, 1, 500]\n\n   >>> # view objects are dynamic and reflect dict changes\n   >>> del dishes[\'eggs\']\n   >>> del dishes[\'sausage\']\n   >>> list(keys)\n   [\'spam\', \'bacon\']\n\n   >>> # set operations\n   >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n   {\'bacon\'}\n',
  'typesmethods': "\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as ``append()`` on\nlists) and class instance methods.  Built-in methods are described\nwith the types that support them.\n\nIf you access a method (a function defined in a class namespace)\nthrough an instance, you get a special object: a *bound method* (also\ncalled *instance method*) object. When called, it will add the\n``self`` argument to the argument list.  Bound methods have two\nspecial read-only attributes: ``m.__self__`` is the object on which\nthe method operates, and ``m.__func__`` is the function implementing\nthe method.  Calling ``m(arg-1, arg-2, ..., arg-n)`` is completely\nequivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,\narg-n)``.\n\nLike function objects, bound method objects support getting arbitrary\nattributes.  However, since method attributes are actually stored on\nthe underlying function object (``meth.__func__``), setting method\nattributes on bound methods is disallowed.  Attempting to set a method\nattribute results in a ``TypeError`` being raised.  In order to set a\nmethod attribute, you need to explicitly set it on the underlying\nfunction object:\n\n   class C:\n       def method(self):\n           pass\n\n   c = C()\n   c.method.__func__.whoami = 'my name is c'\n\nSee *The standard type hierarchy* for more information.\n",
  'typesmodules': "\nModules\n*******\n\nThe only special operation on a module is attribute access:\n``m.name``, where *m* is a module and *name* accesses a name defined\nin *m*'s symbol table. Module attributes can be assigned to.  (Note\nthat the ``import`` statement is not, strictly speaking, an operation\non a module object; ``import foo`` does not require a module object\nnamed *foo* to exist, rather it requires an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA special member of every module is ``__dict__``. This is the\ndictionary containing the module's symbol table. Modifying this\ndictionary will actually change the module's symbol table, but direct\nassignment to the ``__dict__`` attribute is not possible (you can\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\nyou can't write ``m.__dict__ = {}``).  Modifying ``__dict__`` directly\nis not recommended.\n\nModules built into the interpreter are written like this: ``<module\n'sys' (built-in)>``.  If loaded from a file, they are written as\n``<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>``.\n",
- 'typesseq': '\nSequence Types --- ``str``, ``bytes``, ``bytearray``, ``list``, ``tuple``, ``range``\n************************************************************************************\n\nThere are six sequence types: strings, byte sequences (``bytes``\nobjects), byte arrays (``bytearray`` objects), lists, tuples, and\nrange objects.  For other containers see the built in ``dict`` and\n``set`` classes, and the ``collections`` module.\n\nStrings contain Unicode characters.  Their literals are written in\nsingle or double quotes: ``\'xyzzy\'``, ``"frobozz"``.  See *String and\nBytes literals* for more about string literals.  In addition to the\nfunctionality described here, there are also string-specific methods\ndescribed in the *String Methods* section.\n\nBytes and bytearray objects contain single bytes -- the former is\nimmutable while the latter is a mutable sequence.  Bytes objects can\nbe constructed the constructor, ``bytes()``, and from literals; use a\n``b`` prefix with normal string syntax: ``b\'xyzzy\'``.  To construct\nbyte arrays, use the ``bytearray()`` function.\n\nWarning: While string objects are sequences of characters (represented by\n  strings of length 1), bytes and bytearray objects are sequences of\n  *integers* (between 0 and 255), representing the ASCII value of\n  single bytes.  That means that for a bytes or bytearray object *b*,\n  ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes or\n  bytearray object of length 1.  The representation of bytes objects\n  uses the literal format (``b\'...\'``) since it is generally more\n  useful than e.g. ``bytes([50, 19, 100])``.  You can always convert a\n  bytes object into a list of integers using ``list(b)``.Also, while\n  in previous Python versions, byte strings and Unicode strings could\n  be exchanged for each other rather freely (barring encoding issues),\n  strings and bytes are now completely separate concepts.  There\'s no\n  implicit en-/decoding if you pass and object of the wrong type.  A\n  string always compares unequal to a bytes or bytearray object.\n\nLists are constructed with square brackets, separating items with\ncommas: ``[a, b, c]``.  Tuples are constructed by the comma operator\n(not within square brackets), with or without enclosing parentheses,\nbut an empty tuple must have the enclosing parentheses, such as ``a,\nb, c`` or ``()``.  A single item tuple must have a trailing comma,\nsuch as ``(d,)``.\n\nObjects of type range are created using the ``range()`` function.\nThey don\'t support slicing, concatenation or repetition, and using\n``in``, ``not in``, ``min()`` or ``max()`` on them is inefficient.\n\nMost sequence types support the following operations.  The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations.  The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority).  In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation          | Result                           | Notes      |\n+====================+==================================+============+\n| ``x in s``         | ``True`` if an item of *s* is    | (1)        |\n|                    | equal to *x*, else ``False``     |            |\n+--------------------+----------------------------------+------------+\n| ``x not in s``     | ``False`` if an item of *s* is   | (1)        |\n|                    | equal to *x*, else ``True``      |            |\n+--------------------+----------------------------------+------------+\n| ``s + t``          | the concatenation of *s* and *t* | (6)        |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s``   | *n* shallow copies of *s*        | (2)        |\n|                    | concatenated                     |            |\n+--------------------+----------------------------------+------------+\n| ``s[i]``           | *i*\'th item of *s*, origin 0     | (3)        |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]``         | slice of *s* from *i* to *j*     | (3)(4)     |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]``       | slice of *s* from *i* to *j*     | (3)(5)     |\n|                    | with step *k*                    |            |\n+--------------------+----------------------------------+------------+\n| ``len(s)``         | length of *s*                    |            |\n+--------------------+----------------------------------+------------+\n| ``min(s)``         | smallest item of *s*             |            |\n+--------------------+----------------------------------+------------+\n| ``max(s)``         | largest item of *s*              |            |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons.  In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements.  This means that to compare equal, every element must\ncompare equal and the two sequences must be of the same type and have\nthe same length.  (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string object, the ``in`` and ``not in`` operations\n   act like a substring test.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n   empty sequence of the same type as *s*).  Note also that the copies\n   are shallow; nested structures are not copied.  This often haunts\n   new Python programmers; consider:\n\n   >>> lists = [[]] * 3\n   >>> lists\n   [[], [], []]\n   >>> lists[0].append(3)\n   >>> lists\n   [[3], [3], [3]]\n\n   What has happened is that ``[[]]`` is a one-element list containing\n   an empty list, so all three elements of ``[[]] * 3`` are (pointers\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   >>> lists[0].append(3)\n   >>> lists[1].append(5)\n   >>> lists[2].append(7)\n   >>> lists\n   [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n   string: ``len(s) + i`` or ``len(s) + j`` is substituted.  But note\n   that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n   items with index *k* such that ``i <= k < j``.  If *i* or *j* is\n   greater than ``len(s)``, use ``len(s)``.  If *i* is omitted or\n   ``None``, use ``0``.  If *j* is omitted or ``None``, use\n   ``len(s)``.  If *i* is greater than or equal to *j*, the slice is\n   empty.\n\n5. 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 <\n   (j-i)/k``.  In other words, the indices are ``i``, ``i+k``,\n   ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n   never including *j*).  If *i* or *j* is greater than ``len(s)``,\n   use ``len(s)``.  If *i* or *j* are omitted or ``None``, they become\n   "end" values (which end depends on the sign of *k*).  Note, *k*\n   cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. If *s* and *t* are both strings, some Python implementations such\n   as CPython can usually perform an in-place optimization for\n   assignments of the form ``s=s+t`` or ``s+=t``.  When applicable,\n   this optimization makes quadratic run-time much less likely.  This\n   optimization is both version and implementation dependent. For\n   performance sensitive code, it is preferable to use the\n   ``str.join()`` method which assures consistent linear concatenation\n   performance across versions and implementations.\n\n\nString Methods\n==============\n\nString objects support the methods listed below.  Note that none of\nthese methods take keyword arguments.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with only its first character\n   capitalized.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\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\nstr.encode([encoding[, errors]])\n\n   Return an encoded version of the string as a bytes object.  Default\n   encoding is the current default string encoding.  *errors* may be\n   given to set a different error handling scheme.  The default for\n   *errors* is ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n   any other name registered via ``codecs.register_error()``, see\n   section *Codec Base Classes*. For a list of possible encodings, see\n   section *Standard Encodings*.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\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   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found, such that *sub* is contained in the range [*start*, *end*].\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The *format_string*\n   argument can contain literal text or replacement fields delimited\n   by braces ``{}``.  Each replacement field contains either the\n   numeric index of a positional argument, or the name of a keyword\n   argument.  Returns a copy of *format_string* where each replacement\n   field is replaced with the string value of the corresponding\n   argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\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\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters include digit characters, and all characters that that\n   can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n   INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.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\nstr.istitle()\n\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   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise.\n\nstr.join(seq)\n\n   Return a string which is the concatenation of the strings in the\n   sequence *seq*.  A ``TypeError`` will be raised if there are any\n   non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.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\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.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   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\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 is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\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   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within s[start,end].  Optional\n   arguments *start* and *end* are interpreted as in slice notation.\n   Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.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   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\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 is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.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   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\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   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([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*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\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*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no 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   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string: words start with\n   uppercase characters, all remaining cased characters are lowercase.\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\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 ``len(s)``.\n\n\nOld String Formatting Operations\n================================\n\nNote: The formatting operations described here are obsolete and may go\n  away in future versions of Python.  Use the new *String Formatting*\n  in new code.\n\nString objects have one unique built-in operation: the ``%`` operator\n(modulo). This is also known as the string *formatting* or\n*interpolation* operator. Given ``format % values`` (where *format* is\na string), ``%`` conversion specifications in *format* are replaced\nwith zero or more elements of *values*. The effect is similar to the\nusing ``sprintf()`` in the C language.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4]  Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n   characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n   conversion types.\n\n4. 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\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\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\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print(\'%(language)s has %(#)03d quote types.\' % \\\n...       {\'language\': "Python", "#": 2})\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag      | Meaning                                                               |\n+===========+=======================================================================+\n| ``\'#\'``   | The value conversion will use the "alternate form" (where defined     |\n|           | below).                                                               |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'``   | The conversion will be zero padded for numeric values.                |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'``   | The converted value is left adjusted (overrides the ``\'0\'``           |\n|           | conversion if both are given).                                        |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'``   | (a space) A blank should be left before a positive number (or empty   |\n|           | string) produced by a signed conversion.                              |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'``   | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion     |\n|           | (overrides a "space" flag).                                           |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion   | Meaning                                               | Notes   |\n+==============+=======================================================+=========+\n| ``\'d\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'``      | Signed octal value.                                   | (1)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'``      | Obsolete type -- it is identical to ``\'d\'``.          | (7)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'``      | Signed hexadecimal (lowercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'``      | Signed hexadecimal (uppercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'``      | Floating point exponential format (lowercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'``      | Floating point exponential format (uppercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'``      | Floating point format. Uses lowercase exponential     | (4)     |\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|              | precision, decimal format otherwise.                  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'``      | Single character (accepts integer or single character |         |\n|              | string).                                              |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'``      | String (converts any python object using ``repr()``). | (5)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'``      | String (converts any python object using ``str()``).  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'``      | No argument is converted, results in a ``\'%\'``        |         |\n|              | character in the result.                              |         |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. 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   leading character of the result is not already a zero.\n\n2. 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   leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n   point, even if no digits follow it.\n\n   The precision determines the number of digits after the decimal\n   point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n   point, and trailing zeroes are not removed as they would otherwise\n   be.\n\n   The precision determines the number of significant digits before\n   and after the decimal point and defaults to 6.\n\n5. The precision determines the maximal number of characters used.\n\n1. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 3.1: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nRange Type\n==========\n\nThe ``range`` type is an immutable sequence which is commonly used for\nlooping.  The advantage of the ``range`` type is that an ``range``\nobject will always take the same amount of memory, no matter the size\nof the range it represents.  There are no consistent performance\nadvantages.\n\nRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\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)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``.\n\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   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   While a list is being sorted, the effect of attempting to mutate,\n   or even inspect, the list is undefined.  The C implementation makes\n   the list appear empty for the duration, and raises ``ValueError``\n   if it can detect that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n\n\nBytes and Byte Array Methods\n============================\n\nBytes and bytearray objects, being "strings of bytes", have all\nmethods found on strings, with the exception of ``encode()``,\n``format()`` and ``isidentifier()``, which do not make sense with\nthese types.  For converting the objects to strings, they have a\n``decode()`` method.\n\nWherever one of these methods needs to interpret the bytes as\ncharacters (e.g. the ``is...()`` methods), the ASCII character set is\nassumed.\n\nNote: The methods on bytes and bytearray objects don\'t accept strings as\n  their arguments, just as the methods on strings don\'t accept bytes\n  as their arguments.  For example, you have to write\n\n     a = "abc"\n     b = a.replace("a", "f")\n\n  and\n\n     a = b"abc"\n     b = a.replace(b"a", b"f")\n\nbytes.decode([encoding[, errors]])\nbytearray.decode([encoding[, errors]])\n\n   Return a string decoded from the given bytes.  Default encoding is\n   the current default string encoding.  *errors* may be given to set\n   a different error handling scheme.  The default for *errors* is\n   ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'`` and any other name registered via\n   ``codecs.register_error()``, see section *Codec Base Classes*. For\n   a list of possible encodings, see section *Standard Encodings*.\n\nThe bytes and bytearray types have an additional class method:\n\nclassmethod bytes.fromhex(string)\nclassmethod bytearray.fromhex(string)\n\n   This ``bytes`` class method returns a bytes or bytearray object,\n   decoding the given string object.  The string must contain two\n   hexadecimal digits per byte, spaces are ignored.\n\n   >>> bytes.fromhex(\'f0 f1f2  \')\n   b\'\\xf0\\xf1\\xf2\'\n\nThe maketrans and translate methods differ in semantics from the\nversions available on strings:\n\nbytes.translate(table[, delete])\nbytearray.translate(table[, delete])\n\n   Return a copy of the bytes or bytearray object where all bytes\n   occurring in the optional argument *delete* are removed, and the\n   remaining bytes have been mapped through the given translation\n   table, which must be a bytes object of length 256.\n\n   You can use the ``bytes.maketrans()`` method to create a\n   translation table.\n\n   Set the *table* argument to ``None`` for translations that only\n   delete characters:\n\n      >>> b\'read this short text\'.translate(None, b\'aeiou\')\n      b\'rd ths shrt txt\'\n\nstatic bytes.maketrans(from, to)\nstatic bytearray.maketrans(from, to)\n\n   This static method returns a translation table usable for\n   ``bytes.translate()`` that will map each character in *from* into\n   the character at the same position in *to*; *from* and *to* must be\n   bytes objects and have the same length.\n\n   New in version 3.1.\n',
- 'typesseq-mutable': '\nMutable Sequence Types\n**********************\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\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)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``.\n\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   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   While a list is being sorted, the effect of attempting to mutate,\n   or even inspect, the list is undefined.  The C implementation makes\n   the list appear empty for the duration, and raises ``ValueError``\n   if it can detect that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n',
+ 'typesseq': '\nSequence Types --- ``str``, ``bytes``, ``bytearray``, ``list``, ``tuple``, ``range``\n************************************************************************************\n\nThere are six sequence types: strings, byte sequences (``bytes``\nobjects), byte arrays (``bytearray`` objects), lists, tuples, and\nrange objects.  For other containers see the built in ``dict`` and\n``set`` classes, and the ``collections`` module.\n\nStrings contain Unicode characters.  Their literals are written in\nsingle or double quotes: ``\'xyzzy\'``, ``"frobozz"``.  See *String and\nBytes literals* for more about string literals.  In addition to the\nfunctionality described here, there are also string-specific methods\ndescribed in the *String Methods* section.\n\nBytes and bytearray objects contain single bytes -- the former is\nimmutable while the latter is a mutable sequence.  Bytes objects can\nbe constructed the constructor, ``bytes()``, and from literals; use a\n``b`` prefix with normal string syntax: ``b\'xyzzy\'``.  To construct\nbyte arrays, use the ``bytearray()`` function.\n\nWarning: While string objects are sequences of characters (represented by\n  strings of length 1), bytes and bytearray objects are sequences of\n  *integers* (between 0 and 255), representing the ASCII value of\n  single bytes.  That means that for a bytes or bytearray object *b*,\n  ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes or\n  bytearray object of length 1.  The representation of bytes objects\n  uses the literal format (``b\'...\'``) since it is generally more\n  useful than e.g. ``bytes([50, 19, 100])``.  You can always convert a\n  bytes object into a list of integers using ``list(b)``.Also, while\n  in previous Python versions, byte strings and Unicode strings could\n  be exchanged for each other rather freely (barring encoding issues),\n  strings and bytes are now completely separate concepts.  There\'s no\n  implicit en-/decoding if you pass an object of the wrong type.  A\n  string always compares unequal to a bytes or bytearray object.\n\nLists are constructed with square brackets, separating items with\ncommas: ``[a, b, c]``.  Tuples are constructed by the comma operator\n(not within square brackets), with or without enclosing parentheses,\nbut an empty tuple must have the enclosing parentheses, such as ``a,\nb, c`` or ``()``.  A single item tuple must have a trailing comma,\nsuch as ``(d,)``.\n\nObjects of type range are created using the ``range()`` function.\nThey don\'t support slicing, concatenation or repetition, and using\n``in``, ``not in``, ``min()`` or ``max()`` on them is inefficient.\n\nMost sequence types support the following operations.  The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations.  The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority).  In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation          | Result                           | Notes      |\n+====================+==================================+============+\n| ``x in s``         | ``True`` if an item of *s* is    | (1)        |\n|                    | equal to *x*, else ``False``     |            |\n+--------------------+----------------------------------+------------+\n| ``x not in s``     | ``False`` if an item of *s* is   | (1)        |\n|                    | equal to *x*, else ``True``      |            |\n+--------------------+----------------------------------+------------+\n| ``s + t``          | the concatenation of *s* and *t* | (6)        |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s``   | *n* shallow copies of *s*        | (2)        |\n|                    | concatenated                     |            |\n+--------------------+----------------------------------+------------+\n| ``s[i]``           | *i*\'th item of *s*, origin 0     | (3)        |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]``         | slice of *s* from *i* to *j*     | (3)(4)     |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]``       | slice of *s* from *i* to *j*     | (3)(5)     |\n|                    | with step *k*                    |            |\n+--------------------+----------------------------------+------------+\n| ``len(s)``         | length of *s*                    |            |\n+--------------------+----------------------------------+------------+\n| ``min(s)``         | smallest item of *s*             |            |\n+--------------------+----------------------------------+------------+\n| ``max(s)``         | largest item of *s*              |            |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons.  In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements.  This means that to compare equal, every element must\ncompare equal and the two sequences must be of the same type and have\nthe same length.  (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string object, the ``in`` and ``not in`` operations\n   act like a substring test.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n   empty sequence of the same type as *s*).  Note also that the copies\n   are shallow; nested structures are not copied.  This often haunts\n   new Python programmers; consider:\n\n   >>> lists = [[]] * 3\n   >>> lists\n   [[], [], []]\n   >>> lists[0].append(3)\n   >>> lists\n   [[3], [3], [3]]\n\n   What has happened is that ``[[]]`` is a one-element list containing\n   an empty list, so all three elements of ``[[]] * 3`` are (pointers\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   >>> lists[0].append(3)\n   >>> lists[1].append(5)\n   >>> lists[2].append(7)\n   >>> lists\n   [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n   string: ``len(s) + i`` or ``len(s) + j`` is substituted.  But note\n   that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n   items with index *k* such that ``i <= k < j``.  If *i* or *j* is\n   greater than ``len(s)``, use ``len(s)``.  If *i* is omitted or\n   ``None``, use ``0``.  If *j* is omitted or ``None``, use\n   ``len(s)``.  If *i* is greater than or equal to *j*, the slice is\n   empty.\n\n5. 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 <\n   (j-i)/k``.  In other words, the indices are ``i``, ``i+k``,\n   ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n   never including *j*).  If *i* or *j* is greater than ``len(s)``,\n   use ``len(s)``.  If *i* or *j* are omitted or ``None``, they become\n   "end" values (which end depends on the sign of *k*).  Note, *k*\n   cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n   some Python implementations such as CPython can usually perform an\n   in-place optimization for assignments of the form ``s = s + t`` or\n   ``s += t``.  When applicable, this optimization makes quadratic\n   run-time much less likely.  This optimization is both version and\n   implementation dependent.  For performance sensitive code, it is\n   preferable to use the ``str.join()`` method which assures\n   consistent linear concatenation performance across versions and\n   implementations.\n\n\nString Methods\n==============\n\nString objects support the methods listed below.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\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\nstr.encode(encoding=sys.getdefaultencoding(), errors="strict")\n\n   Return an encoded version of the string as a bytes object.  Default\n   encoding is the current default string encoding.  *errors* may be\n   given to set a different error handling scheme.  The default for\n   *errors* is ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n   any other name registered via ``codecs.register_error()``, see\n   section *Codec Base Classes*. For a list of possible encodings, see\n   section *Standard Encodings*.\n\n   Changed in version 3.1: Added support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\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   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\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\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or 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   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\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\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\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters include digit characters, and all characters that that\n   can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n   INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.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\nstr.istitle()\n\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   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A ``TypeError`` will be raised if there are\n   any non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.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\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.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   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\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 is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\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   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\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   notation.  Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.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   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\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 is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.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   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\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   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([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*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\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*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no 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   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   The algorithm uses a simple language-independent definition of a\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   result:\n\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 regular\n   expressions:\n\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                            s)\n\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\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   characters:\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\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 ``len(s)``.\n\n\nOld String Formatting Operations\n================================\n\nNote: The formatting operations described here are obsolete and may go\n  away in future versions of Python.  Use the new *String Formatting*\n  in new code.\n\nString objects have one unique built-in operation: the ``%`` operator\n(modulo). This is also known as the string *formatting* or\n*interpolation* operator. Given ``format % values`` (where *format* is\na string), ``%`` conversion specifications in *format* are replaced\nwith zero or more elements of *values*. The effect is similar to the\nusing ``sprintf()`` in the C language.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4]  Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n   characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n   conversion types.\n\n4. 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\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\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\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print(\'%(language)s has %(#)03d quote types.\' % \\\n...       {\'language\': "Python", "#": 2})\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag      | Meaning                                                               |\n+===========+=======================================================================+\n| ``\'#\'``   | The value conversion will use the "alternate form" (where defined     |\n|           | below).                                                               |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'``   | The conversion will be zero padded for numeric values.                |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'``   | The converted value is left adjusted (overrides the ``\'0\'``           |\n|           | conversion if both are given).                                        |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'``   | (a space) A blank should be left before a positive number (or empty   |\n|           | string) produced by a signed conversion.                              |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'``   | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion     |\n|           | (overrides a "space" flag).                                           |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion   | Meaning                                               | Notes   |\n+==============+=======================================================+=========+\n| ``\'d\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'``      | Signed octal value.                                   | (1)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'``      | Obsolete type -- it is identical to ``\'d\'``.          | (7)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'``      | Signed hexadecimal (lowercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'``      | Signed hexadecimal (uppercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'``      | Floating point exponential format (lowercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'``      | Floating point exponential format (uppercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'``      | Floating point format. Uses lowercase exponential     | (4)     |\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|              | precision, decimal format otherwise.                  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'``      | Single character (accepts integer or single character |         |\n|              | string).                                              |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'``      | String (converts any Python object using ``repr()``). | (5)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'``      | String (converts any Python object using ``str()``).  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'``      | No argument is converted, results in a ``\'%\'``        |         |\n|              | character in the result.                              |         |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. 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   leading character of the result is not already a zero.\n\n2. 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   leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n   point, even if no digits follow it.\n\n   The precision determines the number of digits after the decimal\n   point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n   point, and trailing zeroes are not removed as they would otherwise\n   be.\n\n   The precision determines the number of significant digits before\n   and after the decimal point and defaults to 6.\n\n5. The precision determines the maximal number of characters used.\n\n1. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 3.1: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nRange Type\n==========\n\nThe ``range`` type is an immutable sequence which is commonly used for\nlooping.  The advantage of the ``range`` type is that an ``range``\nobject will always take the same amount of memory, no matter the size\nof the range it represents.  There are no consistent performance\nadvantages.\n\nRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\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)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``. Use ``functools.cmp_to_key()`` to\n   convert an old-style *cmp* function to a *key* function.\n\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   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   **CPython implementation detail:** While a list is being sorted,\n   the effect of attempting to mutate, or even inspect, the list is\n   undefined.  The C implementation of Python makes the list appear\n   empty for the duration, and raises ``ValueError`` if it can detect\n   that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n\n\nBytes and Byte Array Methods\n============================\n\nBytes and bytearray objects, being "strings of bytes", have all\nmethods found on strings, with the exception of ``encode()``,\n``format()`` and ``isidentifier()``, which do not make sense with\nthese types.  For converting the objects to strings, they have a\n``decode()`` method.\n\nWherever one of these methods needs to interpret the bytes as\ncharacters (e.g. the ``is...()`` methods), the ASCII character set is\nassumed.\n\nNote: The methods on bytes and bytearray objects don\'t accept strings as\n  their arguments, just as the methods on strings don\'t accept bytes\n  as their arguments.  For example, you have to write\n\n     a = "abc"\n     b = a.replace("a", "f")\n\n  and\n\n     a = b"abc"\n     b = a.replace(b"a", b"f")\n\nbytes.decode(encoding=sys.getdefaultencoding(), errors="strict")\nbytearray.decode(encoding=sys.getdefaultencoding(), errors="strict")\n\n   Return a string decoded from the given bytes.  Default encoding is\n   the current default string encoding.  *errors* may be given to set\n   a different error handling scheme.  The default for *errors* is\n   ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'`` and any other name registered via\n   ``codecs.register_error()``, see section *Codec Base Classes*. For\n   a list of possible encodings, see section *Standard Encodings*.\n\n   Changed in version 3.1: Added support for keyword arguments.\n\nThe bytes and bytearray types have an additional class method:\n\nclassmethod bytes.fromhex(string)\nclassmethod bytearray.fromhex(string)\n\n   This ``bytes`` class method returns a bytes or bytearray object,\n   decoding the given string object.  The string must contain two\n   hexadecimal digits per byte, spaces are ignored.\n\n   >>> bytes.fromhex(\'f0 f1f2  \')\n   b\'\\xf0\\xf1\\xf2\'\n\nThe maketrans and translate methods differ in semantics from the\nversions available on strings:\n\nbytes.translate(table[, delete])\nbytearray.translate(table[, delete])\n\n   Return a copy of the bytes or bytearray object where all bytes\n   occurring in the optional argument *delete* are removed, and the\n   remaining bytes have been mapped through the given translation\n   table, which must be a bytes object of length 256.\n\n   You can use the ``bytes.maketrans()`` method to create a\n   translation table.\n\n   Set the *table* argument to ``None`` for translations that only\n   delete characters:\n\n      >>> b\'read this short text\'.translate(None, b\'aeiou\')\n      b\'rd ths shrt txt\'\n\nstatic bytes.maketrans(from, to)\nstatic bytearray.maketrans(from, to)\n\n   This static method returns a translation table usable for\n   ``bytes.translate()`` that will map each character in *from* into\n   the character at the same position in *to*; *from* and *to* must be\n   bytes objects and have the same length.\n\n   New in version 3.1.\n',
+ 'typesseq-mutable': '\nMutable Sequence Types\n**********************\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\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)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``. Use ``functools.cmp_to_key()`` to\n   convert an old-style *cmp* function to a *key* function.\n\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   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   **CPython implementation detail:** While a list is being sorted,\n   the effect of attempting to mutate, or even inspect, the list is\n   undefined.  The C implementation of Python makes the list appear\n   empty for the duration, and raises ``ValueError`` if it can detect\n   that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n',
  'unary': '\nUnary arithmetic and bitwise operations\n***************************************\n\nAll unary arithmetic and bitwise operations have the same priority:\n\n   u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n\nThe unary ``-`` (minus) operator yields the negation of its numeric\nargument.\n\nThe unary ``+`` (plus) operator yields its numeric argument unchanged.\n\nThe unary ``~`` (invert) operator yields the bitwise inversion of its\ninteger argument.  The bitwise inversion of ``x`` is defined as\n``-(x+1)``.  It only applies to integral numbers.\n\nIn all three cases, if the argument does not have the proper type, a\n``TypeError`` exception is raised.\n',
  'while': '\nThe ``while`` statement\n***********************\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n',
- 'with': '\nThe ``with`` statement\n**********************\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__enter__()`` method is invoked.\n\n3. 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\n     be 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 5 below.\n\n4. The suite is executed.\n\n5. 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,\n   three ``None`` arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the ``__exit__()`` method was false, the exception is\n   reraised.  If the return value was true, the exception is\n   suppressed, and execution continues with the statement following\n   the ``with`` 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\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n',
- 'yield': '\nThe ``yield`` statement\n***********************\n\n   yield_stmt ::= yield_expression\n\nThe ``yield`` statement is only used when defining a generator\nfunction, and is only used in the body of the generator function.\nUsing a ``yield`` statement in a function definition is sufficient to\ncause that definition to create a generator function instead of a\nnormal function. When a generator function is called, it returns an\niterator known as a generator iterator, or more commonly, a generator.\nThe body of the generator function is executed by calling the\n``next()`` function on the generator repeatedly until it raises an\nexception.\n\nWhen a ``yield`` statement is executed, the state of the generator is\nfrozen and the value of **expression_list** is returned to\n``next()``\'s caller.  By "frozen" we mean that all local state is\nretained, including the current bindings of local variables, the\ninstruction pointer, and the internal evaluation stack: enough\ninformation is saved so that the next time ``next()`` is invoked, the\nfunction can proceed exactly as if the ``yield`` statement were just\nanother external call.\n\nThe ``yield`` statement is allowed in the ``try`` clause of a ``try``\n...  ``finally`` construct.  If the generator is not resumed before it\nis finalized (by reaching a zero reference count or by being garbage\ncollected), the generator-iterator\'s ``close()`` method will be\ncalled, allowing any pending ``finally`` clauses to execute.\n\nSee also:\n\n   **PEP 0255** - Simple Generators\n      The proposal for adding generators and the ``yield`` statement\n      to Python.\n\n   **PEP 0342** - Coroutines via Enhanced Generators\n      The proposal that, among other generator enhancements, proposed\n      allowing ``yield`` to appear inside a ``try`` ... ``finally``\n      block.\n'}
+ 'with': '\nThe ``with`` statement\n**********************\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. 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\n     be 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\n5. The suite is executed.\n\n6. 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,\n   three ``None`` arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the ``__exit__()`` method was false, the exception is\n   reraised.  If the return value was true, the exception is\n   suppressed, and execution continues with the statement following\n   the ``with`` 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\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n',
+ 'yield': '\nThe ``yield`` statement\n***********************\n\n   yield_stmt ::= yield_expression\n\nThe ``yield`` statement is only used when defining a generator\nfunction, and is only used in the body of the generator function.\nUsing a ``yield`` statement in a function definition is sufficient to\ncause that definition to create a generator function instead of a\nnormal function. When a generator function is called, it returns an\niterator known as a generator iterator, or more commonly, a generator.\nThe body of the generator function is executed by calling the\n``next()`` function on the generator repeatedly until it raises an\nexception.\n\nWhen a ``yield`` statement is executed, the state of the generator is\nfrozen and the value of ``expression_list`` is returned to\n``next()``\'s caller.  By "frozen" we mean that all local state is\nretained, including the current bindings of local variables, the\ninstruction pointer, and the internal evaluation stack: enough\ninformation is saved so that the next time ``next()`` is invoked, the\nfunction can proceed exactly as if the ``yield`` statement were just\nanother external call.\n\nThe ``yield`` statement is allowed in the ``try`` clause of a ``try``\n...  ``finally`` construct.  If the generator is not resumed before it\nis finalized (by reaching a zero reference count or by being garbage\ncollected), the generator-iterator\'s ``close()`` method will be\ncalled, allowing any pending ``finally`` clauses to execute.\n\nSee also:\n\n   **PEP 0255** - Simple Generators\n      The proposal for adding generators and the ``yield`` statement\n      to Python.\n\n   **PEP 0342** - Coroutines via Enhanced Generators\n      The proposal that, among other generator enhancements, proposed\n      allowing ``yield`` to appear inside a ``try`` ... ``finally``\n      block.\n'}

Modified: python/branches/py3k-dtoa/Lib/re.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/re.py	(original)
+++ python/branches/py3k-dtoa/Lib/re.py	Sun Aug  8 12:41:24 2010
@@ -254,7 +254,40 @@
 
 _pattern_type = type(sre_compile.compile("", 0))
 
-_MAXCACHE = 100
+_MAXCACHE = 500
+
+def _shrink_cache(cache_dict, max_length, divisor=5):
+    """Make room in the given cache.
+
+    Args:
+        cache_dict: The cache dictionary to modify.
+        max_length: Maximum # of entries in cache_dict before it is shrunk.
+        divisor: Cache will shrink to max_length - 1/divisor*max_length items.
+    """
+    # Toss out a fraction of the entries at random to make room for new ones.
+    # A random algorithm was chosen as opposed to simply cache_dict.popitem()
+    # as popitem could penalize the same regular expression repeatedly based
+    # on its internal hash value.  Being random should spread the cache miss
+    # love around.
+    cache_keys = tuple(cache_dict.keys())
+    overage = len(cache_keys) - max_length
+    if overage < 0:
+        # Cache is already within limits.  Normally this should not happen
+        # but it could due to multithreading.
+        return
+    number_to_toss = max_length // divisor + overage
+    # The import is done here to avoid a circular depencency.
+    import random
+    if not hasattr(random, 'sample'):
+        # Do nothing while resolving the circular dependency:
+        #  re->random->warnings->tokenize->string->re
+        return
+    for doomed_key in random.sample(cache_keys, number_to_toss):
+        try:
+            del cache_dict[doomed_key]
+        except KeyError:
+            # Ignore problems if the cache changed from another thread.
+            pass
 
 def _compile(*key):
     # internal: compile pattern
@@ -272,7 +305,7 @@
         raise TypeError("first argument must be string or compiled pattern")
     p = sre_compile.compile(pattern, flags)
     if len(_cache) >= _MAXCACHE:
-        _cache.clear()
+        _shrink_cache(_cache, _MAXCACHE)
     _cache[cachekey] = p
     return p
 
@@ -284,7 +317,7 @@
     repl, pattern = key
     p = sre_parse.parse_template(repl, pattern)
     if len(_cache_repl) >= _MAXCACHE:
-        _cache_repl.clear()
+        _shrink_cache(_cache_repl, _MAXCACHE)
     _cache_repl[key] = p
     return p
 

Modified: python/branches/py3k-dtoa/Lib/site.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/site.py	(original)
+++ python/branches/py3k-dtoa/Lib/site.py	Sun Aug  8 12:41:24 2010
@@ -295,7 +295,7 @@
             # locations.
             from sysconfig import get_config_var
             framework = get_config_var("PYTHONFRAMEWORK")
-            if framework and "/%s.framework/"%(framework,) in prefix:
+            if framework:
                 sitepackages.append(
                         os.path.join("/Library", framework,
                             sys.version[:3], "site-packages"))

Modified: python/branches/py3k-dtoa/Lib/smtpd.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/smtpd.py	(original)
+++ python/branches/py3k-dtoa/Lib/smtpd.py	Sun Aug  8 12:41:24 2010
@@ -59,7 +59,6 @@
 #   gets forwarded to a real backend smtpd, as with PureProxy.  Again, errors
 #   are not handled correctly yet.
 #
-# Please note that this script requires Python 2.0
 #
 # Author: Barry Warsaw <barry at python.org>
 #
@@ -78,6 +77,7 @@
 import socket
 import asyncore
 import asynchat
+from warnings import warn
 
 __all__ = ["SMTPServer","DebuggingServer","PureProxy","MailmanProxy"]
 
@@ -111,35 +111,157 @@
 
     def __init__(self, server, conn, addr):
         asynchat.async_chat.__init__(self, conn)
-        self.__server = server
-        self.__conn = conn
-        self.__addr = addr
-        self.__line = []
-        self.__state = self.COMMAND
-        self.__greeting = 0
-        self.__mailfrom = None
-        self.__rcpttos = []
-        self.__data = ''
-        self.__fqdn = socket.getfqdn()
-        self.__peer = conn.getpeername()
-        print('Peer:', repr(self.__peer), file=DEBUGSTREAM)
-        self.push('220 %s %s' % (self.__fqdn, __version__))
+        self.smtp_server = server
+        self.conn = conn
+        self.addr = addr
+        self.received_lines = []
+        self.smtp_state = self.COMMAND
+        self.seen_greeting = ''
+        self.mailfrom = None
+        self.rcpttos = []
+        self.received_data = ''
+        self.fqdn = socket.getfqdn()
+        self.peer = conn.getpeername()
+        print('Peer:', repr(self.peer), file=DEBUGSTREAM)
+        self.push('220 %s %s' % (self.fqdn, __version__))
         self.set_terminator(b'\r\n')
 
+    # properties for backwards-compatibility
+    @property
+    def __server(self):
+        warn("Access to __server attribute on SMTPChannel is deprecated, "
+            "use 'smtp_server' instead", PendingDeprecationWarning, 2)
+        return self.smtp_server
+    @__server.setter
+    def __server(self, value):
+        warn("Setting __server attribute on SMTPChannel is deprecated, "
+            "set 'smtp_server' instead", PendingDeprecationWarning, 2)
+        self.smtp_server = value
+
+    @property
+    def __line(self):
+        warn("Access to __line attribute on SMTPChannel is deprecated, "
+            "use 'received_lines' instead", PendingDeprecationWarning, 2)
+        return self.received_lines
+    @__line.setter
+    def __line(self, value):
+        warn("Setting __line attribute on SMTPChannel is deprecated, "
+            "set 'received_lines' instead", PendingDeprecationWarning, 2)
+        self.received_lines = value
+
+    @property
+    def __state(self):
+        warn("Access to __state attribute on SMTPChannel is deprecated, "
+            "use 'smtp_state' instead", PendingDeprecationWarning, 2)
+        return self.smtp_state
+    @__state.setter
+    def __state(self, value):
+        warn("Setting __state attribute on SMTPChannel is deprecated, "
+            "set 'smtp_state' instead", PendingDeprecationWarning, 2)
+        self.smtp_state = value
+
+    @property
+    def __greeting(self):
+        warn("Access to __greeting attribute on SMTPChannel is deprecated, "
+            "use 'seen_greeting' instead", PendingDeprecationWarning, 2)
+        return self.seen_greeting
+    @__greeting.setter
+    def __greeting(self, value):
+        warn("Setting __greeting attribute on SMTPChannel is deprecated, "
+            "set 'seen_greeting' instead", PendingDeprecationWarning, 2)
+        self.seen_greeting = value
+
+    @property
+    def __mailfrom(self):
+        warn("Access to __mailfrom attribute on SMTPChannel is deprecated, "
+            "use 'mailfrom' instead", PendingDeprecationWarning, 2)
+        return self.mailfrom
+    @__mailfrom.setter
+    def __mailfrom(self, value):
+        warn("Setting __mailfrom attribute on SMTPChannel is deprecated, "
+            "set 'mailfrom' instead", PendingDeprecationWarning, 2)
+        self.mailfrom = value
+
+    @property
+    def __rcpttos(self):
+        warn("Access to __rcpttos attribute on SMTPChannel is deprecated, "
+            "use 'rcpttos' instead", PendingDeprecationWarning, 2)
+        return self.rcpttos
+    @__rcpttos.setter
+    def __rcpttos(self, value):
+        warn("Setting __rcpttos attribute on SMTPChannel is deprecated, "
+            "set 'rcpttos' instead", PendingDeprecationWarning, 2)
+        self.rcpttos = value
+
+    @property
+    def __data(self):
+        warn("Access to __data attribute on SMTPChannel is deprecated, "
+            "use 'received_data' instead", PendingDeprecationWarning, 2)
+        return self.received_data
+    @__data.setter
+    def __data(self, value):
+        warn("Setting __data attribute on SMTPChannel is deprecated, "
+            "set 'received_data' instead", PendingDeprecationWarning, 2)
+        self.received_data = value
+
+    @property
+    def __fqdn(self):
+        warn("Access to __fqdn attribute on SMTPChannel is deprecated, "
+            "use 'fqdn' instead", PendingDeprecationWarning, 2)
+        return self.fqdn
+    @__fqdn.setter
+    def __fqdn(self, value):
+        warn("Setting __fqdn attribute on SMTPChannel is deprecated, "
+            "set 'fqdn' instead", PendingDeprecationWarning, 2)
+        self.fqdn = value
+
+    @property
+    def __peer(self):
+        warn("Access to __peer attribute on SMTPChannel is deprecated, "
+            "use 'peer' instead", PendingDeprecationWarning, 2)
+        return self.peer
+    @__peer.setter
+    def __peer(self, value):
+        warn("Setting __peer attribute on SMTPChannel is deprecated, "
+            "set 'peer' instead", PendingDeprecationWarning, 2)
+        self.peer = value
+
+    @property
+    def __conn(self):
+        warn("Access to __conn attribute on SMTPChannel is deprecated, "
+            "use 'conn' instead", PendingDeprecationWarning, 2)
+        return self.conn
+    @__conn.setter
+    def __conn(self, value):
+        warn("Setting __conn attribute on SMTPChannel is deprecated, "
+            "set 'conn' instead", PendingDeprecationWarning, 2)
+        self.conn = value
+
+    @property
+    def __addr(self):
+        warn("Access to __addr attribute on SMTPChannel is deprecated, "
+            "use 'addr' instead", PendingDeprecationWarning, 2)
+        return self.addr
+    @__addr.setter
+    def __addr(self, value):
+        warn("Setting __addr attribute on SMTPChannel is deprecated, "
+            "set 'addr' instead", PendingDeprecationWarning, 2)
+        self.addr = value
+
     # Overrides base class for convenience
     def push(self, msg):
         asynchat.async_chat.push(self, bytes(msg + '\r\n', 'ascii'))
 
     # Implementation of base class abstract method
     def collect_incoming_data(self, data):
-        self.__line.append(str(data, "utf8"))
+        self.received_lines.append(str(data, "utf8"))
 
     # Implementation of base class abstract method
     def found_terminator(self):
-        line = EMPTYSTRING.join(self.__line)
+        line = EMPTYSTRING.join(self.received_lines)
         print('Data:', repr(line), file=DEBUGSTREAM)
-        self.__line = []
-        if self.__state == self.COMMAND:
+        self.received_lines = []
+        if self.smtp_state == self.COMMAND:
             if not line:
                 self.push('500 Error: bad syntax')
                 return
@@ -158,7 +280,7 @@
             method(arg)
             return
         else:
-            if self.__state != self.DATA:
+            if self.smtp_state != self.DATA:
                 self.push('451 Internal confusion')
                 return
             # Remove extraneous carriage returns and de-transparency according
@@ -169,14 +291,14 @@
                     data.append(text[1:])
                 else:
                     data.append(text)
-            self.__data = NEWLINE.join(data)
-            status = self.__server.process_message(self.__peer,
-                                                   self.__mailfrom,
-                                                   self.__rcpttos,
-                                                   self.__data)
-            self.__rcpttos = []
-            self.__mailfrom = None
-            self.__state = self.COMMAND
+            self.received_data = NEWLINE.join(data)
+            status = self.smtp_server.process_message(self.peer,
+                                                      self.mailfrom,
+                                                      self.rcpttos,
+                                                      self.received_data)
+            self.rcpttos = []
+            self.mailfrom = None
+            self.smtp_state = self.COMMAND
             self.set_terminator(b'\r\n')
             if not status:
                 self.push('250 Ok')
@@ -188,11 +310,11 @@
         if not arg:
             self.push('501 Syntax: HELO hostname')
             return
-        if self.__greeting:
+        if self.seen_greeting:
             self.push('503 Duplicate HELO/EHLO')
         else:
-            self.__greeting = arg
-            self.push('250 %s' % self.__fqdn)
+            self.seen_greeting = arg
+            self.push('250 %s' % self.fqdn)
 
     def smtp_NOOP(self, arg):
         if arg:
@@ -225,24 +347,24 @@
         if not address:
             self.push('501 Syntax: MAIL FROM:<address>')
             return
-        if self.__mailfrom:
+        if self.mailfrom:
             self.push('503 Error: nested MAIL command')
             return
-        self.__mailfrom = address
-        print('sender:', self.__mailfrom, file=DEBUGSTREAM)
+        self.mailfrom = address
+        print('sender:', self.mailfrom, file=DEBUGSTREAM)
         self.push('250 Ok')
 
     def smtp_RCPT(self, arg):
         print('===> RCPT', arg, file=DEBUGSTREAM)
-        if not self.__mailfrom:
+        if not self.mailfrom:
             self.push('503 Error: need MAIL command')
             return
         address = self.__getaddr('TO:', arg) if arg else None
         if not address:
             self.push('501 Syntax: RCPT TO: <address>')
             return
-        self.__rcpttos.append(address)
-        print('recips:', self.__rcpttos, file=DEBUGSTREAM)
+        self.rcpttos.append(address)
+        print('recips:', self.rcpttos, file=DEBUGSTREAM)
         self.push('250 Ok')
 
     def smtp_RSET(self, arg):
@@ -250,26 +372,29 @@
             self.push('501 Syntax: RSET')
             return
         # Resets the sender, recipients, and data, but not the greeting
-        self.__mailfrom = None
-        self.__rcpttos = []
-        self.__data = ''
-        self.__state = self.COMMAND
+        self.mailfrom = None
+        self.rcpttos = []
+        self.received_data = ''
+        self.smtp_state = self.COMMAND
         self.push('250 Ok')
 
     def smtp_DATA(self, arg):
-        if not self.__rcpttos:
+        if not self.rcpttos:
             self.push('503 Error: need RCPT command')
             return
         if arg:
             self.push('501 Syntax: DATA')
             return
-        self.__state = self.DATA
+        self.smtp_state = self.DATA
         self.set_terminator(b'\r\n.\r\n')
         self.push('354 End data with <CR><LF>.<CR><LF>')
 
 
 
 class SMTPServer(asyncore.dispatcher):
+    # SMTPChannel class to use for managing client connections
+    channel_class = SMTPChannel
+
     def __init__(self, localaddr, remoteaddr):
         self._localaddr = localaddr
         self._remoteaddr = remoteaddr
@@ -291,7 +416,7 @@
     def handle_accept(self):
         conn, addr = self.accept()
         print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM)
-        channel = SMTPChannel(self, conn, addr)
+        channel = self.channel_class(self, conn, addr)
 
     # API for "doing something useful with the message"
     def process_message(self, peer, mailfrom, rcpttos, data):

Modified: python/branches/py3k-dtoa/Lib/smtplib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/smtplib.py	(original)
+++ python/branches/py3k-dtoa/Lib/smtplib.py	Sun Aug  8 12:41:24 2010
@@ -559,43 +559,44 @@
         if not self.has_extn("auth"):
             raise SMTPException("SMTP AUTH extension not supported by server.")
 
-        # Authentication methods the server supports:
-        authlist = self.esmtp_features["auth"].split()
+        # Authentication methods the server claims to support
+        advertised_authlist = self.esmtp_features["auth"].split()
 
         # List of authentication methods we support: from preferred to
         # less preferred methods. Except for the purpose of testing the weaker
         # ones, we prefer stronger methods like CRAM-MD5:
         preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]
 
-        # Determine the authentication method we'll use
-        authmethod = None
-        for method in preferred_auths:
-            if method in authlist:
-                authmethod = method
-                break
-
-        if authmethod == AUTH_CRAM_MD5:
-            (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
-            if code == 503:
-                # 503 == 'Error: already authenticated'
-                return (code, resp)
-            (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
-        elif authmethod == AUTH_PLAIN:
-            (code, resp) = self.docmd("AUTH",
-                AUTH_PLAIN + " " + encode_plain(user, password))
-        elif authmethod == AUTH_LOGIN:
-            (code, resp) = self.docmd("AUTH",
-                "%s %s" % (AUTH_LOGIN, encode_base64(user.encode('ascii'), eol='')))
-            if code != 334:
-                raise SMTPAuthenticationError(code, resp)
-            (code, resp) = self.docmd(encode_base64(password.encode('ascii'), eol=''))
-        elif authmethod is None:
+        # We try the authentication methods the server advertises, but only the
+        # ones *we* support. And in our preferred order.
+        authlist = [auth for auth in preferred_auths if auth in advertised_authlist]
+        if not authlist:
             raise SMTPException("No suitable authentication method found.")
-        if code not in (235, 503):
+
+        # Some servers advertise authentication methods they don't really
+        # support, so if authentication fails, we continue until we've tried
+        # all methods.
+        for authmethod in authlist:
+            if authmethod == AUTH_CRAM_MD5:
+                (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
+                if code == 334:
+                    (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
+            elif authmethod == AUTH_PLAIN:
+                (code, resp) = self.docmd("AUTH",
+                    AUTH_PLAIN + " " + encode_plain(user, password))
+            elif authmethod == AUTH_LOGIN:
+                (code, resp) = self.docmd("AUTH",
+                    "%s %s" % (AUTH_LOGIN, encode_base64(user.encode('ascii'), eol='')))
+                if code == 334:
+                    (code, resp) = self.docmd(encode_base64(password.encode('ascii'), eol=''))
+
             # 235 == 'Authentication successful'
             # 503 == 'Error: already authenticated'
-            raise SMTPAuthenticationError(code, resp)
-        return (code, resp)
+            if code in (235, 503):
+                return (code, resp)
+
+        # We could not login sucessfully. Return result of last attempt.
+        raise SMTPAuthenticationError(code, resp)
 
     def starttls(self, keyfile = None, certfile = None):
         """Puts the connection to the SMTP server into TLS mode.

Modified: python/branches/py3k-dtoa/Lib/sndhdr.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/sndhdr.py	(original)
+++ python/branches/py3k-dtoa/Lib/sndhdr.py	Sun Aug  8 12:41:24 2010
@@ -57,12 +57,12 @@
 
 def test_aifc(h, f):
     import aifc
-    if h.startswith(b'FORM'):
+    if not h.startswith(b'FORM'):
         return None
     if h[8:12] == b'AIFC':
         fmt = 'aifc'
     elif h[8:12] == b'AIFF':
-        fmt = b'aiff'
+        fmt = 'aiff'
     else:
         return None
     f.seek(0)
@@ -123,7 +123,7 @@
 
 
 def test_voc(h, f):
-    if h.startswith(b'Creative Voice File\032'):
+    if not h.startswith(b'Creative Voice File\032'):
         return None
     sbseek = get_short_le(h[20:22])
     rate = 0
@@ -150,7 +150,7 @@
 
 
 def test_8svx(h, f):
-    if h.startswith(b'FORM') or h[8:12] != b'8SVX':
+    if not h.startswith(b'FORM') or h[8:12] != b'8SVX':
         return None
     # Should decode it to get #channels -- assume always 1
     return '8svx', 0, 1, 0, 8

Modified: python/branches/py3k-dtoa/Lib/socket.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/socket.py	(original)
+++ python/branches/py3k-dtoa/Lib/socket.py	Sun Aug  8 12:41:24 2010
@@ -252,10 +252,6 @@
         self._sock._decref_socketios()
         self._sock = None
 
-    def __del__(self):
-        if not self.closed:
-            self._sock._decref_socketios()
-
 
 def getfqdn(name=''):
     """Get fully qualified domain name from name.

Modified: python/branches/py3k-dtoa/Lib/string.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/string.py	(original)
+++ python/branches/py3k-dtoa/Lib/string.py	Sun Aug  8 12:41:24 2010
@@ -81,7 +81,7 @@
                 'delim' : _re.escape(cls.delimiter),
                 'id'    : cls.idpattern,
                 }
-        cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
+        cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE)
 
 
 class Template(metaclass=_TemplateMetaclass):
@@ -89,6 +89,7 @@
 
     delimiter = '$'
     idpattern = r'[_a-z][_a-z0-9]*'
+    flags = _re.IGNORECASE
 
     def __init__(self, template):
         self.template = template

Modified: python/branches/py3k-dtoa/Lib/subprocess.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/subprocess.py	(original)
+++ python/branches/py3k-dtoa/Lib/subprocess.py	Sun Aug  8 12:41:24 2010
@@ -1073,6 +1073,8 @@
 
             if shell:
                 args = ["/bin/sh", "-c"] + args
+                if executable:
+                    args[0] = executable
 
             if executable is None:
                 executable = args[0]

Modified: python/branches/py3k-dtoa/Lib/sysconfig.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/sysconfig.py	(original)
+++ python/branches/py3k-dtoa/Lib/sysconfig.py	Sun Aug  8 12:41:24 2010
@@ -173,7 +173,7 @@
     if sys.platform == "darwin":
         framework = get_config_var("PYTHONFRAMEWORK")
         if framework:
-            return joinuser("~", "Library", framework, "%d.%d"%(
+            return env_base if env_base else joinuser("~", "Library", framework, "%d.%d"%(
                 sys.version_info[:2]))
 
     return env_base if env_base else joinuser("~", ".local")
@@ -225,6 +225,12 @@
     # do variable interpolation here
     variables = list(notdone.keys())
 
+    # Variables with a 'PY_' prefix in the makefile. These need to
+    # be made available without that prefix through sysconfig.
+    # Special care is needed to ensure that variable expansion works, even
+    # if the expansion uses the name without a prefix.
+    renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
+
     while len(variables) > 0:
         for name in tuple(variables):
             value = notdone[name]
@@ -240,8 +246,20 @@
                 elif n in os.environ:
                     # do it like make: fall back to environment
                     item = os.environ[n]
+
+                elif n in renamed_variables:
+                    if name.startswith('PY_') and name[3:] in renamed_variables:
+                        item = ""
+
+                    elif 'PY_' + n in notdone:
+                        found = False
+
+                    else:
+                        item = str(done['PY_' + n])
+
                 else:
                     done[n] = item = ""
+
                 if found:
                     after = value[m.end():]
                     value = value[:m.start()] + item + after
@@ -255,6 +273,15 @@
                         else:
                             done[name] = value
                         variables.remove(name)
+
+                        if name.startswith('PY_') \
+                                and name[3:] in renamed_variables:
+
+                            name = name[3:]
+                            if name not in done:
+                                done[name] = value
+
+
             else:
                 # bogus variable reference; just drop it since we can't deal
                 variables.remove(name)
@@ -653,8 +680,7 @@
                 cflags = get_config_vars().get('CFLAGS')
 
                 archs = re.findall('-arch\s+(\S+)', cflags)
-                archs.sort()
-                archs = tuple(archs)
+                archs = tuple(sorted(set(archs)))
 
                 if len(archs) == 1:
                     machine = archs[0]

Modified: python/branches/py3k-dtoa/Lib/tarfile.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/tarfile.py	(original)
+++ python/branches/py3k-dtoa/Lib/tarfile.py	Sun Aug  8 12:41:24 2010
@@ -55,6 +55,15 @@
 except ImportError:
     grp = pwd = None
 
+# os.symlink on Windows prior to 6.0 raises NotImplementedError
+symlink_exception = (AttributeError, NotImplementedError)
+try:
+    # WindowsError (1314) will be raised if the caller does not hold the
+    # SeCreateSymbolicLinkPrivilege privilege
+    symlink_exception += (WindowsError,)
+except NameError:
+    pass
+
 # from tarfile import *
 __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"]
 
@@ -2273,7 +2282,7 @@
           (platform limitation), we try to make a copy of the referenced file
           instead of a link.
         """
-        if hasattr(os, "symlink") and hasattr(os, "link"):
+        try:
             # For systems that support symbolic and hard links.
             if tarinfo.issym():
                 os.symlink(tarinfo.linkname, targetpath)
@@ -2282,10 +2291,17 @@
                 if os.path.exists(tarinfo._link_target):
                     os.link(tarinfo._link_target, targetpath)
                 else:
-                    self._extract_member(self._find_link_target(tarinfo), targetpath)
+                    self._extract_mem
+        except symlink_exception:
+            if tarinfo.issym():
+                linkpath = os.path.join(os.path.dirname(tarinfo.name),
+                                        tarinfo.linkname)
+            else:
+                linkpath = tarinfo.linkname
         else:
             try:
-                self._extract_member(self._find_link_target(tarinfo), targetpath)
+                self._extract_member(self._find_link_target(tarinfo),
+                                     targetpath)
             except KeyError:
                 raise ExtractError("unable to resolve link inside archive")
 

Modified: python/branches/py3k-dtoa/Lib/test/decimaltestdata/extra.decTest
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/decimaltestdata/extra.decTest	(original)
+++ python/branches/py3k-dtoa/Lib/test/decimaltestdata/extra.decTest	Sun Aug  8 12:41:24 2010
@@ -213,7 +213,20 @@
 extr1659 shift 1234567 4 -> 0
 extr1660 shift 1234567 5 -> NaN Invalid_operation
 
+-- Cases where the power function was impossibly slow to determine that the
+-- result is inexact.  Thanks Stefan Krah for identifying this problem.
+precision: 16
+maxExponent: 999999999
+minExponent: -999999999
+extr1700 power 10 1e-999999999 -> 1.000000000000000 Inexact Rounded
+extr1701 power 100.0 -557.71e-742888888 -> 1.000000000000000 Inexact Rounded
+extr1702 power 10 1e-100 -> 1.000000000000000 Inexact Rounded
 
+-- A couple of interesting exact cases for power.  Note that the specification
+-- requires these to be reported as Inexact.
+extr1710 power 1e375 56e-3 -> 1.000000000000000E+21 Inexact Rounded
+extr1711 power 10000 0.75 -> 1000.000000000000 Inexact Rounded
+extr1712 power 1e-24 0.875 -> 1.000000000000000E-21 Inexact Rounded
 
 -- Tests for the is_* boolean operations
 precision: 9

Modified: python/branches/py3k-dtoa/Lib/test/formatfloat_testcases.txt
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/formatfloat_testcases.txt	(original)
+++ python/branches/py3k-dtoa/Lib/test/formatfloat_testcases.txt	Sun Aug  8 12:41:24 2010
@@ -314,43 +314,37 @@
 %#.5g 234.56 -> 234.56
 %#.6g 234.56 -> 234.560
 
--- for repr formatting see the separate test_short_repr test in
--- test_float.py.  Not all platforms use short repr for floats.
-
--- str formatting.  Result always includes decimal point and at
+-- repr formatting.  Result always includes decimal point and at
 -- least one digit after the point, or an exponent.
-%s 0 -> 0.0
-%s 1 -> 1.0
-
-%s 0.01 -> 0.01
-%s 0.02 -> 0.02
-%s 0.03 -> 0.03
-%s 0.04 -> 0.04
-%s 0.05 -> 0.05
-
--- str truncates to 12 significant digits
-%s 1.234123412341 -> 1.23412341234
-%s 1.23412341234 -> 1.23412341234
-%s 1.2341234123 -> 1.2341234123
+%r 0 -> 0.0
+%r 1 -> 1.0
 
--- values >= 1e11 get an exponent
-%s 10 -> 10.0
-%s 100 -> 100.0
-%s 1e10 -> 10000000000.0
-%s 9.999e10 -> 99990000000.0
-%s 99999999999 -> 99999999999.0
-%s 99999999999.9 -> 99999999999.9
-%s 99999999999.99 -> 1e+11
-%s 1e11 -> 1e+11
-%s 1e12 -> 1e+12
+%r 0.01 -> 0.01
+%r 0.02 -> 0.02
+%r 0.03 -> 0.03
+%r 0.04 -> 0.04
+%r 0.05 -> 0.05
+
+-- values >= 1e16 get an exponent
+%r 10 -> 10.0
+%r 100 -> 100.0
+%r 1e15 -> 1000000000000000.0
+%r 9.999e15 -> 9999000000000000.0
+%r 9999999999999998 -> 9999999999999998.0
+%r 9999999999999999 -> 1e+16
+%r 1e16 -> 1e+16
+%r 1e17 -> 1e+17
 
 -- as do values < 1e-4
-%s 1e-3 -> 0.001
-%s 1.001e-4 -> 0.0001001
-%s 1.000000000001e-4 -> 0.0001
-%s 1.00000000001e-4 -> 0.000100000000001
-%s 1.0000000001e-4 -> 0.00010000000001
-%s 1e-4 -> 0.0001
-%s 0.999999999999e-4 -> 9.99999999999e-05
-%s 0.999e-4 -> 9.99e-05
-%s 1e-5 -> 1e-05
+%r 1e-3 -> 0.001
+%r 1.001e-4 -> 0.0001001
+%r 1.0000000000000001e-4 -> 0.0001
+%r 1.000000000000001e-4 -> 0.0001000000000000001
+%r 1.00000000001e-4 -> 0.000100000000001
+%r 1.0000000001e-4 -> 0.00010000000001
+%r 1e-4 -> 0.0001
+%r 0.99999999999999999e-4 -> 0.0001
+%r 0.9999999999999999e-4 -> 9.999999999999999e-05
+%r 0.999999999999e-4 -> 9.99999999999e-05
+%r 0.999e-4 -> 9.99e-05
+%r 1e-5 -> 1e-05

Modified: python/branches/py3k-dtoa/Lib/test/math_testcases.txt
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/math_testcases.txt	(original)
+++ python/branches/py3k-dtoa/Lib/test/math_testcases.txt	Sun Aug  8 12:41:24 2010
@@ -371,6 +371,78 @@
 
 
 -----------------------------------------------------------
+-- log1p: log(1 + x), without precision loss for small x --
+-----------------------------------------------------------
+
+-- special values
+log1p0000 log1p 0.0 -> 0.0
+log1p0001 log1p -0.0 -> -0.0
+log1p0002 log1p inf -> inf
+log1p0003 log1p -inf -> nan             invalid
+log1p0004 log1p nan -> nan
+
+-- singularity at -1.0
+log1p0010 log1p -1.0 -> -inf            divide-by-zero
+log1p0011 log1p -0.9999999999999999 -> -36.736800569677101
+
+-- finite values < 1.0 are invalid
+log1p0020 log1p -1.0000000000000002 -> nan invalid
+log1p0021 log1p -1.1 -> nan invalid
+log1p0022 log1p -2.0 -> nan invalid
+log1p0023 log1p -1e300 -> nan invalid
+
+-- tiny x: log1p(x) ~ x
+log1p0110 log1p 5e-324 -> 5e-324
+log1p0111 log1p 1e-320 -> 1e-320
+log1p0112 log1p 1e-300 -> 1e-300
+log1p0113 log1p 1e-150 -> 1e-150
+log1p0114 log1p 1e-20 -> 1e-20
+
+log1p0120 log1p -5e-324 -> -5e-324
+log1p0121 log1p -1e-320 -> -1e-320
+log1p0122 log1p -1e-300 -> -1e-300
+log1p0123 log1p -1e-150 -> -1e-150
+log1p0124 log1p -1e-20 -> -1e-20
+
+-- some (mostly) random small and moderate-sized values
+log1p0200 log1p -0.89156889782277482 -> -2.2216403106762863
+log1p0201 log1p -0.23858496047770464 -> -0.27257668276980057
+log1p0202 log1p -0.011641726191307515 -> -0.011710021654495657
+log1p0203 log1p -0.0090126398571693817 -> -0.0090534993825007650
+log1p0204 log1p -0.00023442805985712781 -> -0.00023445554240995693
+log1p0205 log1p -1.5672870980936349e-5 -> -1.5672993801662046e-5
+log1p0206 log1p -7.9650013274825295e-6 -> -7.9650330482740401e-6
+log1p0207 log1p -2.5202948343227410e-7 -> -2.5202951519170971e-7
+log1p0208 log1p -8.2446372820745855e-11 -> -8.2446372824144559e-11
+log1p0209 log1p -8.1663670046490789e-12 -> -8.1663670046824230e-12
+log1p0210 log1p 7.0351735084656292e-18 -> 7.0351735084656292e-18
+log1p0211 log1p 5.2732161907375226e-12 -> 5.2732161907236188e-12
+log1p0212 log1p 1.0000000000000000e-10 -> 9.9999999995000007e-11
+log1p0213 log1p 2.1401273266000197e-9 -> 2.1401273243099470e-9
+log1p0214 log1p 1.2668914653979560e-8 -> 1.2668914573728861e-8
+log1p0215 log1p 1.6250007816299069e-6 -> 1.6249994613175672e-6
+log1p0216 log1p 8.3740495645839399e-6 -> 8.3740145024266269e-6
+log1p0217 log1p 3.0000000000000001e-5 -> 2.9999550008999799e-5
+log1p0218 log1p 0.0070000000000000001 -> 0.0069756137364252423
+log1p0219 log1p 0.013026235315053002 -> 0.012942123564008787
+log1p0220 log1p 0.013497160797236184 -> 0.013406885521915038
+log1p0221 log1p 0.027625599078135284 -> 0.027250897463483054
+log1p0222 log1p 0.14179687245544870 -> 0.13260322540908789
+
+-- large values
+log1p0300 log1p 1.7976931348623157e+308 -> 709.78271289338397
+log1p0301 log1p 1.0000000000000001e+300 -> 690.77552789821368
+log1p0302 log1p 1.0000000000000001e+70 -> 161.18095650958321
+log1p0303 log1p 10000000000.000000 -> 23.025850930040455
+
+-- other values transferred from testLog1p in test_math
+log1p0400 log1p -0.63212055882855767 -> -1.0000000000000000
+log1p0401 log1p 1.7182818284590451 -> 1.0000000000000000
+log1p0402 log1p 1.0000000000000000 -> 0.69314718055994529
+log1p0403 log1p 1.2379400392853803e+27 -> 62.383246250395075
+
+
+-----------------------------------------------------------
 -- expm1: exp(x) - 1, without precision loss for small x --
 -----------------------------------------------------------
 

Modified: python/branches/py3k-dtoa/Lib/test/pickletester.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/pickletester.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/pickletester.py	Sun Aug  8 12:41:24 2010
@@ -65,9 +65,21 @@
     def __eq__(self, other):
         return self.__dict__ == other.__dict__
 
+class D(C):
+    def __init__(self, arg):
+        pass
+
+class E(C):
+    def __getinitargs__(self):
+        return ()
+
 import __main__
 __main__.C = C
 C.__module__ = "__main__"
+__main__.D = D
+D.__module__ = "__main__"
+__main__.E = E
+E.__module__ = "__main__"
 
 class myint(int):
     def __init__(self, x):
@@ -425,6 +437,63 @@
     def test_load_from_data2(self):
         self.assertEqual(self._testdata, self.loads(DATA2))
 
+    def test_load_classic_instance(self):
+        # See issue5180.  Test loading 2.x pickles that
+        # contain an instance of old style class.
+        for X, args in [(C, ()), (D, ('x',)), (E, ())]:
+            xname = X.__name__.encode('ascii')
+            # Protocol 0 (text mode pickle):
+            """
+            0: (    MARK
+            1: i        INST       '__main__ X' (MARK at 0)
+            15: p    PUT        0
+            18: (    MARK
+            19: d        DICT       (MARK at 18)
+            20: p    PUT        1
+            23: b    BUILD
+            24: .    STOP
+            """
+            pickle0 = (b"(i__main__\n"
+                       b"X\n"
+                       b"p0\n"
+                       b"(dp1\nb.").replace(b'X', xname)
+            self.assertEqual(X(*args), self.loads(pickle0))
+
+            # Protocol 1 (binary mode pickle)
+            """
+            0: (    MARK
+            1: c        GLOBAL     '__main__ X'
+            15: q        BINPUT     0
+            17: o        OBJ        (MARK at 0)
+            18: q    BINPUT     1
+            20: }    EMPTY_DICT
+            21: q    BINPUT     2
+            23: b    BUILD
+            24: .    STOP
+            """
+            pickle1 = (b'(c__main__\n'
+                       b'X\n'
+                       b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
+            self.assertEqual(X(*args), self.loads(pickle1))
+
+            # Protocol 2 (pickle2 = b'\x80\x02' + pickle1)
+            """
+            0: \x80 PROTO      2
+            2: (    MARK
+            3: c        GLOBAL     '__main__ X'
+            17: q        BINPUT     0
+            19: o        OBJ        (MARK at 2)
+            20: q    BINPUT     1
+            22: }    EMPTY_DICT
+            23: q    BINPUT     2
+            25: b    BUILD
+            26: .    STOP
+            """
+            pickle2 = (b'\x80\x02(c__main__\n'
+                       b'X\n'
+                       b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
+            self.assertEqual(X(*args), self.loads(pickle2))
+
     # There are gratuitous differences between pickles produced by
     # pickle and cPickle, largely because cPickle starts PUT indices at
     # 1 and pickle starts them at 0.  See XXX comment in cPickle's put2() --

Modified: python/branches/py3k-dtoa/Lib/test/regrtest.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/regrtest.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/regrtest.py	Sun Aug  8 12:41:24 2010
@@ -390,7 +390,7 @@
             sys.exit(0)
         else:
             print(("No handler for option {}.  Please report this as a bug "
-                  "at http://bugs.python.org.").format(o), file=sys.stderr)
+                   "at http://bugs.python.org.").format(o), file=sys.stderr)
             sys.exit(1)
     if single and fromfile:
         usage("-s and -f don't go together!")
@@ -514,8 +514,12 @@
                     if bad:
                         return
         tests = test_forever()
+        test_count = ''
+        test_count_width = 3
     else:
         tests = iter(selected)
+        test_count = '/{}'.format(len(selected))
+        test_count_width = len(test_count) - 1
 
     if use_mp:
         try:
@@ -559,8 +563,6 @@
                         output.put((None, None, None, None))
                         return
                     result = json.loads(result)
-                    if not quiet:
-                        stdout = test+'\n'+stdout
                     output.put((test, stdout.rstrip(), stderr.rstrip(), result))
             except BaseException:
                 output.put((None, None, None, None))
@@ -569,12 +571,16 @@
         for worker in workers:
             worker.start()
         finished = 0
+        test_index = 1
         try:
             while finished < use_mp:
                 test, stdout, stderr, result = output.get()
                 if test is None:
                     finished += 1
                     continue
+                if not quiet:
+                    print("[{1:{0}}{2}] {3}".format(
+                        test_count_width, test_index, test_count, test))
                 if stdout:
                     print(stdout)
                 if stderr:
@@ -583,15 +589,17 @@
                     assert result[1] == 'KeyboardInterrupt'
                     raise KeyboardInterrupt   # What else?
                 accumulate_result(test, result)
+                test_index += 1
         except KeyboardInterrupt:
             interrupted = True
             pending.close()
         for worker in workers:
             worker.join()
     else:
-        for test in tests:
+        for test_index, test in enumerate(tests, 1):
             if not quiet:
-                print(test)
+                print("[{1:{0}}{2}] {3}".format(
+                    test_count_width, test_index, test_count, test))
                 sys.stdout.flush()
             if trace:
                 # If we're tracing code coverage, then we don't exit with status

Modified: python/branches/py3k-dtoa/Lib/test/script_helper.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/script_helper.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/script_helper.py	Sun Aug  8 12:41:24 2010
@@ -79,7 +79,7 @@
             name_in_zip = os.path.basename(script_name)
     zip_file.write(script_name, name_in_zip)
     zip_file.close()
-    #if test.test_support.verbose:
+    #if test.support.verbose:
     #    zip_file = zipfile.ZipFile(zip_name, 'r')
     #    print 'Contents of %r:' % zip_name
     #    zip_file.printdir()
@@ -114,7 +114,7 @@
     zip_file.close()
     for name in unlink:
         os.unlink(name)
-    #if test.test_support.verbose:
+    #if test.support.verbose:
     #    zip_file = zipfile.ZipFile(zip_name, 'r')
     #    print 'Contents of %r:' % zip_name
     #    zip_file.printdir()

Modified: python/branches/py3k-dtoa/Lib/test/sortperf.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/sortperf.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/sortperf.py	Sun Aug  8 12:41:24 2010
@@ -118,12 +118,12 @@
             L = L * (n // 4)
             # Force the elements to be distinct objects, else timings can be
             # artificially low.
-            L = map(lambda x: --x, L)
+            L = list(map(lambda x: --x, L))
         doit(L) # ~sort
         del L
 
         # All equal.  Again, force the elements to be distinct objects.
-        L = map(abs, [-0.5] * n)
+        L = list(map(abs, [-0.5] * n))
         doit(L) # =sort
         del L
 
@@ -131,11 +131,11 @@
         # for an older implementation of quicksort, which used the median
         # of the first, last and middle elements as the pivot.
         half = n // 2
-        L = range(half - 1, -1, -1)
+        L = list(range(half - 1, -1, -1))
         L.extend(range(half))
         # Force to float, so that the timings are comparable.  This is
         # significantly faster if we leave tham as ints.
-        L = map(float, L)
+        L = list(map(float, L))
         doit(L) # !sort
         print()
 

Modified: python/branches/py3k-dtoa/Lib/test/support.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/support.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/support.py	Sun Aug  8 12:41:24 2010
@@ -17,6 +17,7 @@
 import importlib
 import collections
 import re
+import subprocess
 import imp
 import time
 try:
@@ -38,8 +39,7 @@
     "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
     "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
     "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
-    "swap_item", "swap_attr",
-    ]
+    "swap_item", "swap_attr", "can_symlink", "skip_unless_symlink"]
 
 
 class Error(Exception):
@@ -109,7 +109,7 @@
         orig_modules[name] = sys.modules[name]
     except KeyError:
         saved = False
-    sys.modules[name] = 0
+    sys.modules[name] = None
     return saved
 
 
@@ -1169,6 +1169,27 @@
             except:
                 break
 
+try:
+    from .symlink_support import enable_symlink_privilege
+except:
+    enable_symlink_privilege = lambda: True
+
+def can_symlink():
+    """It's no longer sufficient to test for the presence of symlink in the
+    os module - on Windows XP and earlier, os.symlink exists but a
+    NotImplementedError is thrown.
+    """
+    has_symlink = hasattr(os, 'symlink')
+    is_old_windows = sys.platform == "win32" and sys.getwindowsversion().major < 6
+    has_privilege = False if is_old_windows else enable_symlink_privilege()
+    return has_symlink and (not is_old_windows) and has_privilege
+
+def skip_unless_symlink(test):
+    """Skip decorator for tests that require functional symlink"""
+    selector = can_symlink()
+    msg = "Requires functional symlink implementation"
+    return [unittest.skip(msg)(test), test][selector]
+
 @contextlib.contextmanager
 def swap_attr(obj, attr, new_val):
     """Temporary swap out an attribute with a new object.
@@ -1222,3 +1243,13 @@
             yield
         finally:
             del obj[item]
+
+def strip_python_stderr(stderr):
+    """Strip the stderr of a Python process from potential debug output
+    emitted by the interpreter.
+
+    This will typically be run on the result of the communicate() method
+    of a subprocess.Popen object.
+    """
+    stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
+    return stderr

Deleted: python/branches/py3k-dtoa/Lib/test/test_SimpleHTTPServer.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_SimpleHTTPServer.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,41 +0,0 @@
-"""
-These tests only check url parsing for now.
-We don't want to require the 'network' resource.
-"""
-
-import os, unittest
-from http.server import SimpleHTTPRequestHandler
-from test import support
-
-
-class SocketlessRequestHandler(SimpleHTTPRequestHandler):
-    def __init__(self):
-        pass
-
-class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
-    """ Test url parsing """
-    def setUp (self):
-        self.translated = os.getcwd()
-        self.translated = os.path.join(self.translated, 'filename')
-        self.handler = SocketlessRequestHandler ()
-
-    def test_queryArguments (self):
-        path = self.handler.translate_path ('/filename')
-        self.assertEquals (path, self.translated)
-        path = self.handler.translate_path ('/filename?foo=bar')
-        self.assertEquals (path, self.translated)
-        path = self.handler.translate_path ('/filename?a=b&spam=eggs#zot')
-        self.assertEquals (path, self.translated)
-
-    def test_startWithDoubleSlash (self):
-        path = self.handler.translate_path ('//filename')
-        self.assertEquals (path, self.translated)
-        path = self.handler.translate_path ('//filename?foo=bar')
-        self.assertEquals (path, self.translated)
-
-
-def test_main():
-    support.run_unittest(SimpleHTTPRequestHandlerTestCase)
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/py3k-dtoa/Lib/test/test_argparse.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_argparse.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_argparse.py	Sun Aug  8 12:41:24 2010
@@ -417,7 +417,7 @@
 
 
 class TestOptionalsAlternatePrefixChars(ParserTestCase):
-    """Test an Optional with a double-dash option string"""
+    """Test an Optional with option strings with custom prefixes"""
 
     parser_signature = Sig(prefix_chars='+:/', add_help=False)
     argument_signatures = [
@@ -425,7 +425,7 @@
         Sig('::bar'),
         Sig('/baz', action='store_const', const=42),
     ]
-    failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
+    failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']
     successes = [
         ('', NS(f=False, bar=None, baz=None)),
         ('+f', NS(f=True, bar=None, baz=None)),
@@ -436,6 +436,27 @@
     ]
 
 
+class TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase):
+    """When ``-`` not in prefix_chars, default operators created for help
+       should use the prefix_chars in use rather than - or --
+       http://bugs.python.org/issue9444"""
+
+    parser_signature = Sig(prefix_chars='+:/', add_help=True)
+    argument_signatures = [
+        Sig('+f', action='store_true'),
+        Sig('::bar'),
+        Sig('/baz', action='store_const', const=42),
+    ]
+    failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz']
+    successes = [
+        ('', NS(f=False, bar=None, baz=None)),
+        ('+f', NS(f=True, bar=None, baz=None)),
+        ('::ba B', NS(f=False, bar='B', baz=None)),
+        ('+f ::bar B', NS(f=True, bar='B', baz=None)),
+        ('+f /b', NS(f=True, bar=None, baz=42)),
+        ('/ba +f', NS(f=True, bar=None, baz=42))
+    ]
+
 class TestOptionalsShortLong(ParserTestCase):
     """Test a combination of single- and double-dash option strings"""
 
@@ -1655,12 +1676,18 @@
     def assertArgumentParserError(self, *args, **kwargs):
         self.assertRaises(ArgumentParserError, *args, **kwargs)
 
-    def _get_parser(self, subparser_help=False):
+    def _get_parser(self, subparser_help=False, prefix_chars=None):
         # create a parser with a subparsers argument
-        parser = ErrorRaisingArgumentParser(
-            prog='PROG', description='main description')
-        parser.add_argument(
-            '--foo', action='store_true', help='foo help')
+        if prefix_chars:
+            parser = ErrorRaisingArgumentParser(
+                prog='PROG', description='main description', prefix_chars=prefix_chars)
+            parser.add_argument(
+                prefix_chars[0] * 2 + 'foo', action='store_true', help='foo help')
+        else:
+            parser = ErrorRaisingArgumentParser(
+                prog='PROG', description='main description')
+            parser.add_argument(
+                '--foo', action='store_true', help='foo help')
         parser.add_argument(
             'bar', type=float, help='bar help')
 
@@ -1739,6 +1766,44 @@
               --foo       foo help
             '''))
 
+    def test_help_extra_prefix_chars(self):
+        # Make sure - is still used for help if it is a non-first prefix char
+        parser = self._get_parser(prefix_chars='+:-')
+        self.assertEqual(parser.format_usage(),
+                         'usage: PROG [-h] [++foo] bar {1,2} ...\n')
+        self.assertEqual(parser.format_help(), textwrap.dedent('''\
+            usage: PROG [-h] [++foo] bar {1,2} ...
+
+            main description
+
+            positional arguments:
+              bar         bar help
+              {1,2}       command help
+
+            optional arguments:
+              -h, --help  show this help message and exit
+              ++foo       foo help
+            '''))
+
+
+    def test_help_alternate_prefix_chars(self):
+        parser = self._get_parser(prefix_chars='+:/')
+        self.assertEqual(parser.format_usage(),
+                         'usage: PROG [+h] [++foo] bar {1,2} ...\n')
+        self.assertEqual(parser.format_help(), textwrap.dedent('''\
+            usage: PROG [+h] [++foo] bar {1,2} ...
+
+            main description
+
+            positional arguments:
+              bar         bar help
+              {1,2}       command help
+
+            optional arguments:
+              +h, ++help  show this help message and exit
+              ++foo       foo help
+            '''))
+
     def test_parser_command_help(self):
         self.assertEqual(self.command_help_parser.format_usage(),
                          'usage: PROG [-h] [--foo] bar {1,2} ...\n')

Modified: python/branches/py3k-dtoa/Lib/test/test_array.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_array.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_array.py	Sun Aug  8 12:41:24 2010
@@ -326,6 +326,17 @@
                 f.close()
             support.unlink(support.TESTFN)
 
+    def test_fromfile_ioerror(self):
+        # Issue #5395: Check if fromfile raises a proper IOError
+        # instead of EOFError.
+        a = array.array(self.typecode)
+        f = open(support.TESTFN, 'wb')
+        try:
+            self.assertRaises(IOError, a.fromfile, f, len(self.example))
+        finally:
+            f.close()
+            support.unlink(support.TESTFN)
+
     def test_filewrite(self):
         a = array.array(self.typecode, 2*self.example)
         f = open(support.TESTFN, 'wb')

Modified: python/branches/py3k-dtoa/Lib/test/test_ast.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_ast.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_ast.py	Sun Aug  8 12:41:24 2010
@@ -285,6 +285,8 @@
         self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
         self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
         self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
+        self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
+        self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
         self.assertRaises(ValueError, ast.literal_eval, 'foo()')
 
     def test_literal_eval_issue4907(self):

Modified: python/branches/py3k-dtoa/Lib/test/test_asyncore.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_asyncore.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_asyncore.py	Sun Aug  8 12:41:24 2010
@@ -118,65 +118,65 @@
     # http://mail.python.org/pipermail/python-list/2001-October/109973.html)
     # These constants should be present as long as poll is available
 
-    if hasattr(select, 'poll'):
-        def test_readwrite(self):
-            # Check that correct methods are called by readwrite()
-
-            attributes = ('read', 'expt', 'write', 'closed', 'error_handled')
-
-            expected = (
-                (select.POLLIN, 'read'),
-                (select.POLLPRI, 'expt'),
-                (select.POLLOUT, 'write'),
-                (select.POLLERR, 'closed'),
-                (select.POLLHUP, 'closed'),
-                (select.POLLNVAL, 'closed'),
-                )
-
-            class testobj:
-                def __init__(self):
-                    self.read = False
-                    self.write = False
-                    self.closed = False
-                    self.expt = False
-                    self.error_handled = False
-
-                def handle_read_event(self):
-                    self.read = True
-
-                def handle_write_event(self):
-                    self.write = True
-
-                def handle_close(self):
-                    self.closed = True
-
-                def handle_expt_event(self):
-                    self.expt = True
-
-                def handle_error(self):
-                    self.error_handled = True
-
-            for flag, expectedattr in expected:
-                tobj = testobj()
-                self.assertEqual(getattr(tobj, expectedattr), False)
-                asyncore.readwrite(tobj, flag)
-
-                # Only the attribute modified by the routine we expect to be
-                # called should be True.
-                for attr in attributes:
-                    self.assertEqual(getattr(tobj, attr), attr==expectedattr)
-
-                # check that ExitNow exceptions in the object handler method
-                # bubbles all the way up through asyncore readwrite call
-                tr1 = exitingdummy()
-                self.assertRaises(asyncore.ExitNow, asyncore.readwrite, tr1, flag)
-
-                # check that an exception other than ExitNow in the object handler
-                # method causes the handle_error method to get called
-                tr2 = crashingdummy()
-                self.assertEqual(tr2.error_handled, False)
-                asyncore.readwrite(tr2, flag)
-                self.assertEqual(tr2.error_handled, True)
+    @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
+    def test_readwrite(self):
+        # Check that correct methods are called by readwrite()
+
+        attributes = ('read', 'expt', 'write', 'closed', 'error_handled')
+
+        expected = (
+            (select.POLLIN, 'read'),
+            (select.POLLPRI, 'expt'),
+            (select.POLLOUT, 'write'),
+            (select.POLLERR, 'closed'),
+            (select.POLLHUP, 'closed'),
+            (select.POLLNVAL, 'closed'),
+            )
+
+        class testobj:
+            def __init__(self):
+                self.read = False
+                self.write = False
+                self.closed = False
+                self.expt = False
+                self.error_handled = False
+
+            def handle_read_event(self):
+                self.read = True
+
+            def handle_write_event(self):
+                self.write = True
+
+            def handle_close(self):
+                self.closed = True
+
+            def handle_expt_event(self):
+                self.expt = True
+
+            def handle_error(self):
+                self.error_handled = True
+
+        for flag, expectedattr in expected:
+            tobj = testobj()
+            self.assertEqual(getattr(tobj, expectedattr), False)
+            asyncore.readwrite(tobj, flag)
+
+            # Only the attribute modified by the routine we expect to be
+            # called should be True.
+            for attr in attributes:
+                self.assertEqual(getattr(tobj, attr), attr==expectedattr)
+
+            # check that ExitNow exceptions in the object handler method
+            # bubbles all the way up through asyncore readwrite call
+            tr1 = exitingdummy()
+            self.assertRaises(asyncore.ExitNow, asyncore.readwrite, tr1, flag)
+
+            # check that an exception other than ExitNow in the object handler
+            # method causes the handle_error method to get called
+            tr2 = crashingdummy()
+            self.assertEqual(tr2.error_handled, False)
+            asyncore.readwrite(tr2, flag)
+            self.assertEqual(tr2.error_handled, True)
 
     def test_closeall(self):
         self.closeall_check(False)
@@ -259,7 +259,7 @@
             sys.stderr = stderr
 
         lines = fp.getvalue().splitlines()
-        self.assertEquals(lines, ['log: %s' % l1, 'log: %s' % l2])
+        self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2])
 
     def test_log_info(self):
         d = asyncore.dispatcher()
@@ -281,7 +281,7 @@
         lines = fp.getvalue().splitlines()
         expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3]
 
-        self.assertEquals(lines, expected)
+        self.assertEqual(lines, expected)
 
     def test_unhandled(self):
         d = asyncore.dispatcher()
@@ -306,7 +306,7 @@
                     'warning: unhandled write event',
                     'warning: unhandled connect event',
                     'warning: unhandled accept event']
-        self.assertEquals(lines, expected)
+        self.assertEqual(lines, expected)
 
     def test_issue_8594(self):
         # XXX - this test is supposed to be removed in next major Python
@@ -322,7 +322,7 @@
             warnings.simplefilter("always")
             family = d.family
             self.assertEqual(family, socket.AF_INET)
-            self.assertTrue(len(w) == 1)
+            self.assertEqual(len(w), 1)
             self.assertTrue(issubclass(w[0].category, DeprecationWarning))
 
     def test_strerror(self):
@@ -331,7 +331,7 @@
         if hasattr(os, 'strerror'):
             self.assertEqual(err, os.strerror(errno.EPERM))
         err = asyncore._strerror(-1)
-        self.assertTrue("unknown error" in err.lower())
+        self.assertIn("unknown error", err.lower())
 
 
 class dispatcherwithsend_noread(asyncore.dispatcher_with_send):
@@ -394,38 +394,52 @@
 class DispatcherWithSendTests_UsePoll(DispatcherWithSendTests):
     usepoll = True
 
-if hasattr(asyncore, 'file_wrapper'):
-    class FileWrapperTest(unittest.TestCase):
-        def setUp(self):
-            self.d = b"It's not dead, it's sleeping!"
-            open(TESTFN, 'wb').write(self.d)
-
-        def tearDown(self):
-            unlink(TESTFN)
-
-        def test_recv(self):
-            fd = os.open(TESTFN, os.O_RDONLY)
-            w = asyncore.file_wrapper(fd)
-            os.close(fd)
-
-            self.assertNotEqual(w.fd, fd)
-            self.assertNotEqual(w.fileno(), fd)
-            self.assertEqual(w.recv(13), b"It's not dead")
-            self.assertEqual(w.read(6), b", it's")
-            w.close()
-            self.assertRaises(OSError, w.read, 1)
-
-        def test_send(self):
-            d1 = b"Come again?"
-            d2 = b"I want to buy some cheese."
-            fd = os.open(TESTFN, os.O_WRONLY | os.O_APPEND)
-            w = asyncore.file_wrapper(fd)
-            os.close(fd)
-
-            w.write(d1)
-            w.send(d2)
-            w.close()
-            self.assertEqual(open(TESTFN, 'rb').read(), self.d + d1 + d2)
+ at unittest.skipUnless(hasattr(asyncore, 'file_wrapper'),
+                     'asyncore.file_wrapper required')
+class FileWrapperTest(unittest.TestCase):
+    def setUp(self):
+        self.d = b"It's not dead, it's sleeping!"
+        open(TESTFN, 'wb').write(self.d)
+
+    def tearDown(self):
+        unlink(TESTFN)
+
+    def test_recv(self):
+        fd = os.open(TESTFN, os.O_RDONLY)
+        w = asyncore.file_wrapper(fd)
+        os.close(fd)
+
+        self.assertNotEqual(w.fd, fd)
+        self.assertNotEqual(w.fileno(), fd)
+        self.assertEqual(w.recv(13), b"It's not dead")
+        self.assertEqual(w.read(6), b", it's")
+        w.close()
+        self.assertRaises(OSError, w.read, 1)
+
+    def test_send(self):
+        d1 = b"Come again?"
+        d2 = b"I want to buy some cheese."
+        fd = os.open(TESTFN, os.O_WRONLY | os.O_APPEND)
+        w = asyncore.file_wrapper(fd)
+        os.close(fd)
+
+        w.write(d1)
+        w.send(d2)
+        w.close()
+        self.assertEqual(open(TESTFN, 'rb').read(), self.d + d1 + d2)
+
+    @unittest.skipUnless(hasattr(asyncore, 'file_dispatcher'),
+                         'asyncore.file_dispatcher required')
+    def test_dispatcher(self):
+        fd = os.open(TESTFN, os.O_RDONLY)
+        data = []
+        class FileDispatcher(asyncore.file_dispatcher):
+            def handle_read(self):
+                data.append(self.recv(29))
+        s = FileDispatcher(fd)
+        os.close(fd)
+        asyncore.loop(timeout=0.01, use_poll=True, count=2)
+        self.assertEqual(b"".join(data), self.d)
 
 
 class BaseTestHandler(asyncore.dispatcher):
@@ -692,18 +706,15 @@
 class TestAPI_UseSelect(BaseTestAPI):
     use_poll = False
 
+ at unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
 class TestAPI_UsePoll(BaseTestAPI):
     use_poll = True
 
 
 def test_main():
     tests = [HelperFunctionTests, DispatcherTests, DispatcherWithSendTests,
-             DispatcherWithSendTests_UsePoll, TestAPI_UseSelect]
-    if hasattr(asyncore, 'file_wrapper'):
-        tests.append(FileWrapperTest)
-    if hasattr(select, 'poll'):
-        tests.append(TestAPI_UsePoll)
-
+             DispatcherWithSendTests_UsePoll, TestAPI_UseSelect,
+             TestAPI_UsePoll, FileWrapperTest]
     run_unittest(*tests)
 
 if __name__ == "__main__":

Modified: python/branches/py3k-dtoa/Lib/test/test_binascii.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_binascii.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_binascii.py	Sun Aug  8 12:41:24 2010
@@ -55,7 +55,7 @@
                              "{!r} != {!r}".format(fb, fa, res, raw))
             self.assertIsInstance(res, bytes)
             self.assertIsInstance(a, bytes)
-            self.assertLess(max(c for c in a), 128)
+            self.assertLess(max(a), 128)
         self.assertIsInstance(binascii.crc_hqx(raw, 0), int)
         self.assertIsInstance(binascii.crc32(raw), int)
 
@@ -167,7 +167,7 @@
     def test_qp(self):
         # A test for SF bug 534347 (segfaults without the proper fix)
         try:
-            binascii.a2b_qp("", **{1:1})
+            binascii.a2b_qp(b"", **{1:1})
         except TypeError:
             pass
         else:
@@ -179,12 +179,10 @@
         self.assertEqual(binascii.a2b_qp(b"=00\r\n=00"), b"\x00\r\n\x00")
         self.assertEqual(
             binascii.b2a_qp(b"\xff\r\n\xff\n\xff"),
-            b"=FF\r\n=FF\r\n=FF"
-        )
+            b"=FF\r\n=FF\r\n=FF")
         self.assertEqual(
             binascii.b2a_qp(b"0"*75+b"\xff\r\n\xff\r\n\xff"),
-            b"0"*75+b"=\r\n=FF\r\n=FF\r\n=FF"
-        )
+            b"0"*75+b"=\r\n=FF\r\n=FF\r\n=FF")
 
         self.assertEqual(binascii.b2a_qp(b'\0\n'), b'=00\n')
         self.assertEqual(binascii.b2a_qp(b'\0\n', quotetabs=True), b'=00\n')
@@ -210,13 +208,15 @@
             except Exception as err:
                 self.fail("{}({!r}) raises {!r}".format(func, empty, err))
 
-    def test_no_binary_strings(self):
-        # b2a_ must not accept strings
-        for f in (binascii.b2a_uu, binascii.b2a_base64,
-                  binascii.b2a_hqx, binascii.b2a_qp,
-                  binascii.hexlify, binascii.rlecode_hqx,
-                  binascii.crc_hqx, binascii.crc32):
-            self.assertRaises(TypeError, f, "test")
+    def test_unicode_strings(self):
+        # Unicode strings are not accepted.
+        for func in all_functions:
+            try:
+                self.assertRaises(TypeError, getattr(binascii, func), "test")
+            except Exception as err:
+                self.fail('{}("test") raises {!r}'.format(func, err))
+        # crc_hqx needs 2 arguments
+        self.assertRaises(TypeError, binascii.crc_hqx, "test", 0)
 
 
 class ArrayBinASCIITest(BinASCIITest):

Modified: python/branches/py3k-dtoa/Lib/test/test_binop.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_binop.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_binop.py	Sun Aug  8 12:41:24 2010
@@ -16,7 +16,7 @@
 
 def isnum(x):
     """Test whether an object is an instance of a built-in numeric type."""
-    for T in int, int, float, complex:
+    for T in int, float, complex:
         if isinstance(x, T):
             return 1
     return 0

Modified: python/branches/py3k-dtoa/Lib/test/test_bz2.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_bz2.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_bz2.py	Sun Aug  8 12:41:24 2010
@@ -304,6 +304,24 @@
         finally:
             f.close()
 
+    def testMixedIterationReads(self):
+        # Issue #8397: mixed iteration and reads should be forbidden.
+        f = bz2.BZ2File(self.filename, 'wb')
+        try:
+            # The internal buffer size is hard-wired to 8192 bytes, we must
+            # write out more than that for the test to stop half through
+            # the buffer.
+            f.write(self.TEXT * 100)
+        finally:
+            f.close()
+        f = bz2.BZ2File(self.filename, 'rb')
+        try:
+            next(f)
+            self.assertRaises(ValueError, f.read)
+            self.assertRaises(ValueError, f.readline)
+            self.assertRaises(ValueError, f.readlines)
+        finally:
+            f.close()
 
 class BZ2CompressorTest(BaseTest):
     def testCompress(self):

Modified: python/branches/py3k-dtoa/Lib/test/test_calendar.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_calendar.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_calendar.py	Sun Aug  8 12:41:24 2010
@@ -389,6 +389,34 @@
             tuple = time.gmtime(secs)
             self.assertEqual(secs, calendar.timegm(tuple))
 
+class MonthRangeTestCase(unittest.TestCase):
+    def test_january(self):
+        # Tests valid lower boundary case.
+        self.assertEqual(calendar.monthrange(2004,1), (3,31))
+
+    def test_february_leap(self):
+        # Tests February during leap year.
+        self.assertEqual(calendar.monthrange(2004,2), (6,29))
+
+    def test_february_nonleap(self):
+        # Tests February in non-leap year.
+        self.assertEqual(calendar.monthrange(2010,2), (0,28))
+
+    def test_december(self):
+        # Tests valid upper boundary case.
+        self.assertEqual(calendar.monthrange(2004,12), (2,31))
+
+    def test_zeroth_month(self):
+        # Tests low invalid boundary case.
+        with self.assertRaises(calendar.IllegalMonthError):
+            calendar.monthrange(2004, 0)
+
+    def test_thirteenth_month(self):
+        # Tests high invalid boundary case.
+        with self.assertRaises(calendar.IllegalMonthError):
+            calendar.monthrange(2004, 13)
+
+
 def test_main():
     support.run_unittest(
         OutputTestCase,
@@ -396,6 +424,7 @@
         MondayTestCase,
         SundayTestCase,
         TimegmTestCase,
+        MonthRangeTestCase,
     )
 
 

Modified: python/branches/py3k-dtoa/Lib/test/test_cfgparser.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_cfgparser.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_cfgparser.py	Sun Aug  8 12:41:24 2010
@@ -1,7 +1,9 @@
+import collections
 import configparser
 import io
+import os
 import unittest
-import collections
+import textwrap
 
 from test import support
 
@@ -22,15 +24,26 @@
     def itervalues(self): return iter(self.values())
 
 
-class TestCaseBase(unittest.TestCase):
+class CfgParserTestCaseClass(unittest.TestCase):
     allow_no_value = False
+    delimiters = ('=', ':')
+    comment_prefixes = (';', '#')
+    empty_lines_in_values = True
+    dict_type = configparser._default_dict
 
     def newconfig(self, defaults=None):
+        arguments = dict(
+            allow_no_value=self.allow_no_value,
+            delimiters=self.delimiters,
+            comment_prefixes=self.comment_prefixes,
+            empty_lines_in_values=self.empty_lines_in_values,
+            dict_type=self.dict_type,
+        )
         if defaults is None:
-            self.cf = self.config_class(allow_no_value=self.allow_no_value)
+            self.cf = self.config_class(**arguments)
         else:
             self.cf = self.config_class(defaults,
-                                        allow_no_value=self.allow_no_value)
+                                        **arguments)
         return self.cf
 
     def fromstring(self, string, defaults=None):
@@ -39,27 +52,33 @@
         cf.readfp(sio)
         return cf
 
+class BasicTestCase(CfgParserTestCaseClass):
+
     def test_basic(self):
-        config_string = (
-            "[Foo Bar]\n"
-            "foo=bar\n"
-            "[Spacey Bar]\n"
-            "foo = bar\n"
-            "[Commented Bar]\n"
-            "foo: bar ; comment\n"
-            "[Long Line]\n"
-            "foo: this line is much, much longer than my editor\n"
-            "   likes it.\n"
-            "[Section\\with$weird%characters[\t]\n"
-            "[Internationalized Stuff]\n"
-            "foo[bg]: Bulgarian\n"
-            "foo=Default\n"
-            "foo[en]=English\n"
-            "foo[de]=Deutsch\n"
-            "[Spaces]\n"
-            "key with spaces : value\n"
-            "another with spaces = splat!\n"
-            )
+        config_string = """\
+[Foo Bar]
+foo{0[0]}bar
+[Spacey Bar]
+foo {0[0]} bar
+[Spacey Bar From The Beginning]
+  foo {0[0]} bar
+  baz {0[0]} qwe
+[Commented Bar]
+foo{0[1]} bar {1[1]} comment
+baz{0[0]}qwe {1[0]}another one
+[Long Line]
+foo{0[1]} this line is much, much longer than my editor
+   likes it.
+[Section\\with$weird%characters[\t]
+[Internationalized Stuff]
+foo[bg]{0[1]} Bulgarian
+foo{0[0]}Default
+foo[en]{0[0]}English
+foo[de]{0[0]}Deutsch
+[Spaces]
+key with spaces {0[1]} value
+another with spaces {0[0]} splat!
+""".format(self.delimiters, self.comment_prefixes)
         if self.allow_no_value:
             config_string += (
                 "[NoValue]\n"
@@ -69,13 +88,14 @@
         cf = self.fromstring(config_string)
         L = cf.sections()
         L.sort()
-        E = [r'Commented Bar',
-             r'Foo Bar',
-             r'Internationalized Stuff',
-             r'Long Line',
-             r'Section\with$weird%characters[' '\t',
-             r'Spaces',
-             r'Spacey Bar',
+        E = ['Commented Bar',
+             'Foo Bar',
+             'Internationalized Stuff',
+             'Long Line',
+             'Section\\with$weird%characters[\t',
+             'Spaces',
+             'Spacey Bar',
+             'Spacey Bar From The Beginning',
              ]
         if self.allow_no_value:
             E.append(r'NoValue')
@@ -88,7 +108,10 @@
         # http://www.python.org/sf/583248
         eq(cf.get('Foo Bar', 'foo'), 'bar')
         eq(cf.get('Spacey Bar', 'foo'), 'bar')
+        eq(cf.get('Spacey Bar From The Beginning', 'foo'), 'bar')
+        eq(cf.get('Spacey Bar From The Beginning', 'baz'), 'qwe')
         eq(cf.get('Commented Bar', 'foo'), 'bar')
+        eq(cf.get('Commented Bar', 'baz'), 'qwe')
         eq(cf.get('Spaces', 'key with spaces'), 'value')
         eq(cf.get('Spaces', 'another with spaces'), 'splat!')
         if self.allow_no_value:
@@ -107,8 +130,9 @@
                     "remove_option() failed to report non-existence of option"
                     " that was removed")
 
-        self.assertRaises(configparser.NoSectionError,
-                          cf.remove_option, 'No Such Section', 'foo')
+        with self.assertRaises(configparser.NoSectionError) as cm:
+            cf.remove_option('No Such Section', 'foo')
+        self.assertEqual(cm.exception.args, ('No Such Section',))
 
         eq(cf.get('Long Line', 'foo'),
            'this line is much, much longer than my editor\nlikes it.')
@@ -138,12 +162,14 @@
 
         # SF bug #432369:
         cf = self.fromstring(
-            "[MySection]\nOption: first line\n\tsecond line\n")
+            "[MySection]\nOption{} first line\n\tsecond line\n".format(
+                self.delimiters[0]))
         eq(cf.options("MySection"), ["option"])
         eq(cf.get("MySection", "Option"), "first line\nsecond line")
 
         # SF bug #561822:
-        cf = self.fromstring("[section]\nnekey=nevalue\n",
+        cf = self.fromstring("[section]\n"
+                             "nekey{}nevalue\n".format(self.delimiters[0]),
                              defaults={"key":"value"})
         self.assertTrue(cf.has_option("section", "Key"))
 
@@ -161,33 +187,41 @@
     def test_parse_errors(self):
         self.newconfig()
         self.parse_error(configparser.ParsingError,
-                         "[Foo]\n  extra-spaces: splat\n")
+                         "[Foo]\n"
+                         "{}val-without-opt-name\n".format(self.delimiters[0]))
         self.parse_error(configparser.ParsingError,
-                         "[Foo]\n  extra-spaces= splat\n")
-        self.parse_error(configparser.ParsingError,
-                         "[Foo]\n:value-without-option-name\n")
-        self.parse_error(configparser.ParsingError,
-                         "[Foo]\n=value-without-option-name\n")
-        self.parse_error(configparser.MissingSectionHeaderError,
-                         "No Section!\n")
+                         "[Foo]\n"
+                         "{}val-without-opt-name\n".format(self.delimiters[1]))
+        e = self.parse_error(configparser.MissingSectionHeaderError,
+                             "No Section!\n")
+        self.assertEqual(e.args, ('<???>', 1, "No Section!\n"))
+        if not self.allow_no_value:
+            e = self.parse_error(configparser.ParsingError,
+                                "[Foo]\n  wrong-indent\n")
+            self.assertEqual(e.args, ('<???>',))
 
     def parse_error(self, exc, src):
         sio = io.StringIO(src)
-        self.assertRaises(exc, self.cf.readfp, sio)
+        with self.assertRaises(exc) as cm:
+            self.cf.readfp(sio)
+        return cm.exception
 
     def test_query_errors(self):
         cf = self.newconfig()
         self.assertEqual(cf.sections(), [],
                          "new ConfigParser should have no defined sections")
         self.assertFalse(cf.has_section("Foo"),
-                    "new ConfigParser should have no acknowledged sections")
-        self.assertRaises(configparser.NoSectionError,
-                          cf.options, "Foo")
-        self.assertRaises(configparser.NoSectionError,
-                          cf.set, "foo", "bar", "value")
-        self.get_error(configparser.NoSectionError, "foo", "bar")
+                         "new ConfigParser should have no acknowledged "
+                         "sections")
+        with self.assertRaises(configparser.NoSectionError):
+            cf.options("Foo")
+        with self.assertRaises(configparser.NoSectionError):
+            cf.set("foo", "bar", "value")
+        e = self.get_error(configparser.NoSectionError, "foo", "bar")
+        self.assertEqual(e.args, ("foo",))
         cf.add_section("foo")
-        self.get_error(configparser.NoOptionError, "foo", "bar")
+        e = self.get_error(configparser.NoOptionError, "foo", "bar")
+        self.assertEqual(e.args, ("bar", "foo"))
 
     def get_error(self, exc, section, option):
         try:
@@ -201,21 +235,21 @@
     def test_boolean(self):
         cf = self.fromstring(
             "[BOOLTEST]\n"
-            "T1=1\n"
-            "T2=TRUE\n"
-            "T3=True\n"
-            "T4=oN\n"
-            "T5=yes\n"
-            "F1=0\n"
-            "F2=FALSE\n"
-            "F3=False\n"
-            "F4=oFF\n"
-            "F5=nO\n"
-            "E1=2\n"
-            "E2=foo\n"
-            "E3=-1\n"
-            "E4=0.1\n"
-            "E5=FALSE AND MORE"
+            "T1{equals}1\n"
+            "T2{equals}TRUE\n"
+            "T3{equals}True\n"
+            "T4{equals}oN\n"
+            "T5{equals}yes\n"
+            "F1{equals}0\n"
+            "F2{equals}FALSE\n"
+            "F3{equals}False\n"
+            "F4{equals}oFF\n"
+            "F5{equals}nO\n"
+            "E1{equals}2\n"
+            "E2{equals}foo\n"
+            "E3{equals}-1\n"
+            "E4{equals}0.1\n"
+            "E5{equals}FALSE AND MORE".format(equals=self.delimiters[0])
             )
         for x in range(1, 5):
             self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
@@ -226,17 +260,24 @@
     def test_weird_errors(self):
         cf = self.newconfig()
         cf.add_section("Foo")
-        self.assertRaises(configparser.DuplicateSectionError,
-                          cf.add_section, "Foo")
+        with self.assertRaises(configparser.DuplicateSectionError) as cm:
+            cf.add_section("Foo")
+        self.assertEqual(cm.exception.args, ("Foo",))
 
     def test_write(self):
         config_string = (
             "[Long Line]\n"
-            "foo: this line is much, much longer than my editor\n"
+            "foo{0[0]} this line is much, much longer than my editor\n"
             "   likes it.\n"
             "[DEFAULT]\n"
-            "foo: another very\n"
+            "foo{0[1]} another very\n"
             " long line\n"
+            "[Long Line - With Comments!]\n"
+            "test {0[1]} we        {comment} can\n"
+            "            also      {comment} place\n"
+            "            comments  {comment} in\n"
+            "            multiline {comment} values"
+            "\n".format(self.delimiters, comment=self.comment_prefixes[0])
             )
         if self.allow_no_value:
             config_string += (
@@ -249,13 +290,19 @@
         cf.write(output)
         expect_string = (
             "[DEFAULT]\n"
-            "foo = another very\n"
+            "foo {equals} another very\n"
             "\tlong line\n"
             "\n"
             "[Long Line]\n"
-            "foo = this line is much, much longer than my editor\n"
+            "foo {equals} this line is much, much longer than my editor\n"
             "\tlikes it.\n"
             "\n"
+            "[Long Line - With Comments!]\n"
+            "test {equals} we\n"
+            "\talso\n"
+            "\tcomments\n"
+            "\tmultiline\n"
+            "\n".format(equals=self.delimiters[0])
             )
         if self.allow_no_value:
             expect_string += (
@@ -267,7 +314,7 @@
 
     def test_set_string_types(self):
         cf = self.fromstring("[sect]\n"
-                             "option1=foo\n")
+                             "option1{eq}foo\n".format(eq=self.delimiters[0]))
         # Check that we don't get an exception when setting values in
         # an existing section using strings:
         class mystr(str):
@@ -280,6 +327,9 @@
         cf.set("sect", "option2", "splat")
 
     def test_read_returns_file_list(self):
+        if self.delimiters[0] != '=':
+            # skip reading the file if we're using an incompatible format
+            return
         file1 = support.findfile("cfgparser.1")
         # check when we pass a mix of readable and non-readable files:
         cf = self.newconfig()
@@ -304,48 +354,53 @@
     def get_interpolation_config(self):
         return self.fromstring(
             "[Foo]\n"
-            "bar=something %(with1)s interpolation (1 step)\n"
-            "bar9=something %(with9)s lots of interpolation (9 steps)\n"
-            "bar10=something %(with10)s lots of interpolation (10 steps)\n"
-            "bar11=something %(with11)s lots of interpolation (11 steps)\n"
-            "with11=%(with10)s\n"
-            "with10=%(with9)s\n"
-            "with9=%(with8)s\n"
-            "with8=%(With7)s\n"
-            "with7=%(WITH6)s\n"
-            "with6=%(with5)s\n"
-            "With5=%(with4)s\n"
-            "WITH4=%(with3)s\n"
-            "with3=%(with2)s\n"
-            "with2=%(with1)s\n"
-            "with1=with\n"
+            "bar{equals}something %(with1)s interpolation (1 step)\n"
+            "bar9{equals}something %(with9)s lots of interpolation (9 steps)\n"
+            "bar10{equals}something %(with10)s lots of interpolation (10 steps)\n"
+            "bar11{equals}something %(with11)s lots of interpolation (11 steps)\n"
+            "with11{equals}%(with10)s\n"
+            "with10{equals}%(with9)s\n"
+            "with9{equals}%(with8)s\n"
+            "with8{equals}%(With7)s\n"
+            "with7{equals}%(WITH6)s\n"
+            "with6{equals}%(with5)s\n"
+            "With5{equals}%(with4)s\n"
+            "WITH4{equals}%(with3)s\n"
+            "with3{equals}%(with2)s\n"
+            "with2{equals}%(with1)s\n"
+            "with1{equals}with\n"
             "\n"
             "[Mutual Recursion]\n"
-            "foo=%(bar)s\n"
-            "bar=%(foo)s\n"
+            "foo{equals}%(bar)s\n"
+            "bar{equals}%(foo)s\n"
             "\n"
             "[Interpolation Error]\n"
-            "name=%(reference)s\n",
+            "name{equals}%(reference)s\n".format(equals=self.delimiters[0]),
             # no definition for 'reference'
             defaults={"getname": "%(__name__)s"})
 
     def check_items_config(self, expected):
         cf = self.fromstring(
             "[section]\n"
-            "name = value\n"
-            "key: |%(name)s| \n"
-            "getdefault: |%(default)s|\n"
-            "getname: |%(__name__)s|",
+            "name {0[0]} value\n"
+            "key{0[1]} |%(name)s| \n"
+            "getdefault{0[1]} |%(default)s|\n"
+            "getname{0[1]} |%(__name__)s|".format(self.delimiters),
             defaults={"default": "<default>"})
         L = list(cf.items("section"))
         L.sort()
         self.assertEqual(L, expected)
 
 
-class ConfigParserTestCase(TestCaseBase):
+class ConfigParserTestCase(BasicTestCase):
     config_class = configparser.ConfigParser
 
     def test_interpolation(self):
+        rawval = {
+            configparser.ConfigParser: ("something %(with11)s "
+                                        "lots of interpolation (11 steps)"),
+            configparser.SafeConfigParser: "%(with1)s",
+        }
         cf = self.get_interpolation_config()
         eq = self.assertEqual
         eq(cf.get("Foo", "getname"), "Foo")
@@ -354,15 +409,22 @@
            "something with lots of interpolation (9 steps)")
         eq(cf.get("Foo", "bar10"),
            "something with lots of interpolation (10 steps)")
-        self.get_error(configparser.InterpolationDepthError, "Foo", "bar11")
+        e = self.get_error(configparser.InterpolationDepthError, "Foo", "bar11")
+        self.assertEqual(e.args, ("bar11", "Foo", rawval[self.config_class]))
 
     def test_interpolation_missing_value(self):
+        rawval = {
+            configparser.ConfigParser: '%(reference)s',
+            configparser.SafeConfigParser: '',
+        }
         self.get_interpolation_config()
-        e = self.get_error(configparser.InterpolationError,
+        e = self.get_error(configparser.InterpolationMissingOptionError,
                            "Interpolation Error", "name")
         self.assertEqual(e.reference, "reference")
         self.assertEqual(e.section, "Interpolation Error")
         self.assertEqual(e.option, "name")
+        self.assertEqual(e.args, ('name', 'Interpolation Error',
+                                  rawval[self.config_class], 'reference'))
 
     def test_items(self):
         self.check_items_config([('default', '<default>'),
@@ -392,8 +454,39 @@
         self.assertRaises(ValueError, cf.get, 'non-string',
                           'string_with_interpolation', raw=False)
 
+class ConfigParserTestCaseNonStandardDelimiters(ConfigParserTestCase):
+    delimiters = (':=', '$')
+    comment_prefixes = ('//', '"')
+
+class MultilineValuesTestCase(BasicTestCase):
+    config_class = configparser.ConfigParser
+    wonderful_spam = ("I'm having spam spam spam spam "
+                      "spam spam spam beaked beans spam "
+                      "spam spam and spam!").replace(' ', '\t\n')
+
+    def setUp(self):
+        cf = self.newconfig()
+        for i in range(100):
+            s = 'section{}'.format(i)
+            cf.add_section(s)
+            for j in range(10):
+                cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
+        with open(support.TESTFN, 'w') as f:
+            cf.write(f)
+
+    def tearDown(self):
+        os.unlink(support.TESTFN)
+
+    def test_dominating_multiline_values(self):
+        # We're reading from file because this is where the code changed
+        # during performance updates in Python 3.2
+        cf_from_file = self.newconfig()
+        with open(support.TESTFN) as f:
+            cf_from_file.readfp(f)
+        self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
+                         self.wonderful_spam.replace('\t\n', '\n'))
 
-class RawConfigParserTestCase(TestCaseBase):
+class RawConfigParserTestCase(BasicTestCase):
     config_class = configparser.RawConfigParser
 
     def test_interpolation(self):
@@ -427,6 +520,28 @@
                          [0, 1, 1, 2, 3, 5, 8, 13])
         self.assertEqual(cf.get('non-string', 'dict'), {'pi': 3.14159})
 
+class RawConfigParserTestCaseNonStandardDelimiters(RawConfigParserTestCase):
+    delimiters = (':=', '$')
+    comment_prefixes = ('//', '"')
+
+class RawConfigParserTestSambaConf(BasicTestCase):
+    config_class = configparser.RawConfigParser
+    comment_prefixes = ('#', ';', '//', '----')
+    empty_lines_in_values = False
+
+    def test_reading(self):
+        smbconf = support.findfile("cfgparser.2")
+        # check when we pass a mix of readable and non-readable files:
+        cf = self.newconfig()
+        parsed_files = cf.read([smbconf, "nonexistent-file"], encoding='utf-8')
+        self.assertEqual(parsed_files, [smbconf])
+        sections = ['global', 'homes', 'printers',
+                    'print$', 'pdf-generator', 'tmp', 'Agustin']
+        self.assertEqual(cf.sections(), sections)
+        self.assertEqual(cf.get("global", "workgroup"), "MDKGROUP")
+        self.assertEqual(cf.getint("global", "max log size"), 50)
+        self.assertEqual(cf.get("global", "hosts allow"), "127.")
+        self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s")
 
 class SafeConfigParserTestCase(ConfigParserTestCase):
     config_class = configparser.SafeConfigParser
@@ -434,16 +549,17 @@
     def test_safe_interpolation(self):
         # See http://www.python.org/sf/511737
         cf = self.fromstring("[section]\n"
-                             "option1=xxx\n"
-                             "option2=%(option1)s/xxx\n"
-                             "ok=%(option1)s/%%s\n"
-                             "not_ok=%(option2)s/%%s")
+                             "option1{eq}xxx\n"
+                             "option2{eq}%(option1)s/xxx\n"
+                             "ok{eq}%(option1)s/%%s\n"
+                             "not_ok{eq}%(option2)s/%%s".format(
+                                 eq=self.delimiters[0]))
         self.assertEqual(cf.get("section", "ok"), "xxx/%s")
         self.assertEqual(cf.get("section", "not_ok"), "xxx/xxx/%s")
 
     def test_set_malformatted_interpolation(self):
         cf = self.fromstring("[sect]\n"
-                             "option1=foo\n")
+                             "option1{eq}foo\n".format(eq=self.delimiters[0]))
 
         self.assertEqual(cf.get('sect', "option1"), "foo")
 
@@ -459,7 +575,7 @@
 
     def test_set_nonstring_types(self):
         cf = self.fromstring("[sect]\n"
-                             "option1=foo\n")
+                             "option1{eq}foo\n".format(eq=self.delimiters[0]))
         # Check that we get a TypeError when setting non-string values
         # in an existing section:
         self.assertRaises(TypeError, cf.set, "sect", "option1", 1)
@@ -477,15 +593,56 @@
         cf = self.newconfig()
         self.assertRaises(ValueError, cf.add_section, "DEFAULT")
 
+class SafeConfigParserTestCaseNonStandardDelimiters(SafeConfigParserTestCase):
+    delimiters = (':=', '$')
+    comment_prefixes = ('//', '"')
 
 class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):
     allow_no_value = True
 
+class SafeConfigParserTestCaseTrickyFile(CfgParserTestCaseClass):
+    config_class = configparser.SafeConfigParser
+    delimiters = {'='}
+    comment_prefixes = {'#'}
+    allow_no_value = True
+
+    def test_cfgparser_dot_3(self):
+        tricky = support.findfile("cfgparser.3")
+        cf = self.newconfig()
+        self.assertEqual(len(cf.read(tricky, encoding='utf-8')), 1)
+        self.assertEqual(cf.sections(), ['strange',
+                                         'corruption',
+                                         'yeah, sections can be '
+                                         'indented as well',
+                                         'another one!',
+                                         'no values here',
+                                         'tricky interpolation',
+                                         'more interpolation'])
+        #self.assertEqual(cf.getint('DEFAULT', 'go', vars={'interpolate': '-1'}),
+        #                 -1)
+        self.assertEqual(len(cf.get('strange', 'other').split('\n')), 4)
+        self.assertEqual(len(cf.get('corruption', 'value').split('\n')), 10)
+        longname = 'yeah, sections can be indented as well'
+        self.assertFalse(cf.getboolean(longname, 'are they subsections'))
+        self.assertEquals(cf.get(longname, 'lets use some Unicode'),
+                                           '片仮名')
+        self.assertEqual(len(cf.items('another one!')), 5) # 4 in section and
+                                                           # `go` from DEFAULT
+        with self.assertRaises(configparser.InterpolationMissingOptionError):
+            cf.items('no values here')
+        self.assertEqual(cf.get('tricky interpolation', 'lets'), 'do this')
+        self.assertEqual(cf.get('tricky interpolation', 'lets'),
+                         cf.get('tricky interpolation', 'go'))
+        self.assertEqual(cf.get('more interpolation', 'lets'), 'go shopping')
+
+    def test_unicode_failure(self):
+        tricky = support.findfile("cfgparser.3")
+        cf = self.newconfig()
+        with self.assertRaises(UnicodeDecodeError):
+            cf.read(tricky, encoding='ascii')
 
 class SortedTestCase(RawConfigParserTestCase):
-    def newconfig(self, defaults=None):
-        self.cf = self.config_class(defaults=defaults, dict_type=SortedDict)
-        return self.cf
+    dict_type = SortedDict
 
     def test_sorted(self):
         self.fromstring("[b]\n"
@@ -507,13 +664,40 @@
                           "o4 = 1\n\n")
 
 
+class CompatibleTestCase(CfgParserTestCaseClass):
+    config_class = configparser.RawConfigParser
+    comment_prefixes = configparser.RawConfigParser._COMPATIBLE
+
+    def test_comment_handling(self):
+        config_string = textwrap.dedent("""\
+        [Commented Bar]
+        baz=qwe ; a comment
+        foo: bar # not a comment!
+        # but this is a comment
+        ; another comment
+        quirk: this;is not a comment
+        ; a space must precede an inline comment
+        """)
+        cf = self.fromstring(config_string)
+        self.assertEqual(cf.get('Commented Bar', 'foo'), 'bar # not a comment!')
+        self.assertEqual(cf.get('Commented Bar', 'baz'), 'qwe')
+        self.assertEqual(cf.get('Commented Bar', 'quirk'), 'this;is not a comment')
+
+
 def test_main():
     support.run_unittest(
         ConfigParserTestCase,
+        ConfigParserTestCaseNonStandardDelimiters,
+        MultilineValuesTestCase,
         RawConfigParserTestCase,
+        RawConfigParserTestCaseNonStandardDelimiters,
+        RawConfigParserTestSambaConf,
         SafeConfigParserTestCase,
-        SortedTestCase,
+        SafeConfigParserTestCaseNonStandardDelimiters,
         SafeConfigParserTestCaseNoValue,
+        SafeConfigParserTestCaseTrickyFile,
+        SortedTestCase,
+        CompatibleTestCase,
         )
 
 

Modified: python/branches/py3k-dtoa/Lib/test/test_cmath.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_cmath.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_cmath.py	Sun Aug  8 12:41:24 2010
@@ -442,6 +442,15 @@
         self.assertCEqual(rect(1, pi/2), (0, 1.))
         self.assertCEqual(rect(1, -pi/2), (0, -1.))
 
+    def test_isfinite(self):
+        real_vals = [float('-inf'), -2.3, -0.0,
+                     0.0, 2.3, float('inf'), float('nan')]
+        for x in real_vals:
+            for y in real_vals:
+                z = complex(x, y)
+                self.assertEqual(cmath.isfinite(z),
+                                  math.isfinite(x) and math.isfinite(y))
+
     def test_isnan(self):
         self.assertFalse(cmath.isnan(1))
         self.assertFalse(cmath.isnan(1j))

Modified: python/branches/py3k-dtoa/Lib/test/test_cmd.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_cmd.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_cmd.py	Sun Aug  8 12:41:24 2010
@@ -8,7 +8,8 @@
 import cmd
 import sys
 import re
-from io import StringIO
+import unittest
+import io
 from test import support
 
 class samplecmdclass(cmd.Cmd):
@@ -168,9 +169,33 @@
     def do_exit(self, arg):
         return True
 
+
+class TestAlternateInput(unittest.TestCase):
+
+    class simplecmd(cmd.Cmd):
+
+        def do_print(self, args):
+            print(args, file=self.stdout)
+
+        def do_EOF(self, args):
+            return True
+
+    def test_file_with_missing_final_nl(self):
+        input = io.StringIO("print test\nprint test2")
+        output = io.StringIO()
+        cmd = self.simplecmd(stdin=input, stdout=output)
+        cmd.use_rawinput = False
+        cmd.cmdloop()
+        self.assertMultiLineEqual(output.getvalue(),
+            ("(Cmd) test\n"
+             "(Cmd) test2\n"
+             "(Cmd) "))
+
+
 def test_main(verbose=None):
     from test import test_cmd
     support.run_doctest(test_cmd, verbose)
+    support.run_unittest(TestAlternateInput)
 
 def test_coverage(coverdir):
     trace = support.import_module('trace')

Modified: python/branches/py3k-dtoa/Lib/test/test_collections.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_collections.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_collections.py	Sun Aug  8 12:41:24 2010
@@ -218,6 +218,16 @@
         # test __getnewargs__
         self.assertEqual(t.__getnewargs__(), values)
 
+    def test_repr(self):
+        with support.captured_stdout() as template:
+            A = namedtuple('A', 'x', verbose=True)
+        self.assertEqual(repr(A(1)), 'A(x=1)')
+        # repr should show the name of the subclass
+        class B(A):
+            pass
+        self.assertEqual(repr(B(1)), 'B(x=1)')
+
+
 class ABCTestCase(unittest.TestCase):
 
     def validate_abstract_methods(self, abc, *names):
@@ -758,6 +768,19 @@
         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)])

Modified: python/branches/py3k-dtoa/Lib/test/test_complex.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_complex.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_complex.py	Sun Aug  8 12:41:24 2010
@@ -506,6 +506,16 @@
         self.assertEqual(format(z, '-'), str(z))
         self.assertEqual(format(z, '<'), str(z))
         self.assertEqual(format(z, '10'), str(z))
+        z = complex(0.0, 3.0)
+        self.assertEqual(format(z, ''), str(z))
+        self.assertEqual(format(z, '-'), str(z))
+        self.assertEqual(format(z, '<'), str(z))
+        self.assertEqual(format(z, '2'), str(z))
+        z = complex(-0.0, 2.0)
+        self.assertEqual(format(z, ''), str(z))
+        self.assertEqual(format(z, '-'), str(z))
+        self.assertEqual(format(z, '<'), str(z))
+        self.assertEqual(format(z, '3'), str(z))
 
         self.assertEqual(format(1+3j, 'g'), '1+3j')
         self.assertEqual(format(3j, 'g'), '0+3j')

Modified: python/branches/py3k-dtoa/Lib/test/test_curses.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_curses.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_curses.py	Sun Aug  8 12:41:24 2010
@@ -220,8 +220,8 @@
         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()
-            curses.ungetmouse(*m)
 
     if hasattr(curses, 'is_term_resized'):
         curses.is_term_resized(*stdscr.getmaxyx())

Modified: python/branches/py3k-dtoa/Lib/test/test_datetime.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_datetime.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_datetime.py	Sun Aug  8 12:41:24 2010
@@ -1,3659 +1,42 @@
-"""Test date/time type.
-
-See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
-"""
-
-import sys
-import pickle
 import unittest
-
-from operator import lt, le, gt, ge, eq, ne, truediv, floordiv, mod
-
-from test import support
-
-from datetime import MINYEAR, MAXYEAR
-from datetime import timedelta
-from datetime import tzinfo
-from datetime import time
-from datetime import timezone
-from datetime import date, datetime
-import time as _time
-
-pickle_choices = [(pickle, pickle, proto)
-                  for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
-assert len(pickle_choices) == pickle.HIGHEST_PROTOCOL + 1
-
-# An arbitrary collection of objects of non-datetime types, for testing
-# mixed-type comparisons.
-OTHERSTUFF = (10, 34.5, "abc", {}, [], ())
-
-
-# XXX Copied from test_float.
-INF = float("inf")
-NAN = float("nan")
-
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
-
-
-#############################################################################
-# module tests
-
-class TestModule(unittest.TestCase):
-
-    def test_constants(self):
-        import datetime
-        self.assertEqual(datetime.MINYEAR, 1)
-        self.assertEqual(datetime.MAXYEAR, 9999)
-
-#############################################################################
-# tzinfo tests
-
-class FixedOffset(tzinfo):
-
-    def __init__(self, offset, name, dstoffset=42):
-        if isinstance(offset, int):
-            offset = timedelta(minutes=offset)
-        if isinstance(dstoffset, int):
-            dstoffset = timedelta(minutes=dstoffset)
-        self.__offset = offset
-        self.__name = name
-        self.__dstoffset = dstoffset
-    def __repr__(self):
-        return self.__name.lower()
-    def utcoffset(self, dt):
-        return self.__offset
-    def tzname(self, dt):
-        return self.__name
-    def dst(self, dt):
-        return self.__dstoffset
-
-class PicklableFixedOffset(FixedOffset):
-
-    def __init__(self, offset=None, name=None, dstoffset=None):
-        FixedOffset.__init__(self, offset, name, dstoffset)
-
-class TestTZInfo(unittest.TestCase):
-
-    def test_non_abstractness(self):
-        # In order to allow subclasses to get pickled, the C implementation
-        # wasn't able to get away with having __init__ raise
-        # NotImplementedError.
-        useless = tzinfo()
-        dt = datetime.max
-        self.assertRaises(NotImplementedError, useless.tzname, dt)
-        self.assertRaises(NotImplementedError, useless.utcoffset, dt)
-        self.assertRaises(NotImplementedError, useless.dst, dt)
-
-    def test_subclass_must_override(self):
-        class NotEnough(tzinfo):
-            def __init__(self, offset, name):
-                self.__offset = offset
-                self.__name = name
-        self.assertTrue(issubclass(NotEnough, tzinfo))
-        ne = NotEnough(3, "NotByALongShot")
-        self.assertIsInstance(ne, tzinfo)
-
-        dt = datetime.now()
-        self.assertRaises(NotImplementedError, ne.tzname, dt)
-        self.assertRaises(NotImplementedError, ne.utcoffset, dt)
-        self.assertRaises(NotImplementedError, ne.dst, dt)
-
-    def test_normal(self):
-        fo = FixedOffset(3, "Three")
-        self.assertIsInstance(fo, tzinfo)
-        for dt in datetime.now(), None:
-            self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
-            self.assertEqual(fo.tzname(dt), "Three")
-            self.assertEqual(fo.dst(dt), timedelta(minutes=42))
-
-    def test_pickling_base(self):
-        # There's no point to pickling tzinfo objects on their own (they
-        # carry no data), but they need to be picklable anyway else
-        # concrete subclasses can't be pickled.
-        orig = tzinfo.__new__(tzinfo)
-        self.assertTrue(type(orig) is tzinfo)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertTrue(type(derived) is tzinfo)
-
-    def test_pickling_subclass(self):
-        # Make sure we can pickle/unpickle an instance of a subclass.
-        offset = timedelta(minutes=-300)
-        for otype, args in [
-            (PicklableFixedOffset, (offset, 'cookie')),
-            (timezone, (offset,)),
-            (timezone, (offset, "EST"))]:
-            orig = otype(*args)
-            oname = orig.tzname(None)
-            self.assertIsInstance(orig, tzinfo)
-            self.assertIs(type(orig), otype)
-            self.assertEqual(orig.utcoffset(None), offset)
-            self.assertEqual(orig.tzname(None), oname)
-            for pickler, unpickler, proto in pickle_choices:
-                green = pickler.dumps(orig, proto)
-                derived = unpickler.loads(green)
-                self.assertIsInstance(derived, tzinfo)
-                self.assertIs(type(derived), otype)
-                self.assertEqual(derived.utcoffset(None), offset)
-                self.assertEqual(derived.tzname(None), oname)
-
-class TestTimeZone(unittest.TestCase):
-
-    def setUp(self):
-        self.ACDT = timezone(timedelta(hours=9.5), 'ACDT')
-        self.EST = timezone(-timedelta(hours=5), 'EST')
-        self.DT = datetime(2010, 1, 1)
-
-    def test_str(self):
-        for tz in [self.ACDT, self.EST, timezone.utc,
-                   timezone.min, timezone.max]:
-            self.assertEqual(str(tz), tz.tzname(None))
-
-    def test_class_members(self):
-        limit = timedelta(hours=23, minutes=59)
-        self.assertEqual(timezone.utc.utcoffset(None), ZERO)
-        self.assertEqual(timezone.min.utcoffset(None), -limit)
-        self.assertEqual(timezone.max.utcoffset(None), limit)
-
-
-    def test_constructor(self):
-        self.assertEqual(timezone.utc, timezone(timedelta(0)))
-        # invalid offsets
-        for invalid in [timedelta(microseconds=1), timedelta(1, 1),
-                        timedelta(seconds=1), timedelta(1), -timedelta(1)]:
-            self.assertRaises(ValueError, timezone, invalid)
-            self.assertRaises(ValueError, timezone, -invalid)
-
-        with self.assertRaises(TypeError): timezone(None)
-        with self.assertRaises(TypeError): timezone(42)
-        with self.assertRaises(TypeError): timezone(ZERO, None)
-        with self.assertRaises(TypeError): timezone(ZERO, 42)
-        with self.assertRaises(TypeError): timezone(ZERO, 'ABC', 'extra')
-
-    def test_inheritance(self):
-        self.assertIsInstance(timezone.utc, tzinfo)
-        self.assertIsInstance(self.EST, tzinfo)
-
-    def test_utcoffset(self):
-        dummy = self.DT
-        for h in [0, 1.5, 12]:
-            offset = h * HOUR
-            self.assertEqual(offset, timezone(offset).utcoffset(dummy))
-            self.assertEqual(-offset, timezone(-offset).utcoffset(dummy))
-
-        with self.assertRaises(TypeError): self.EST.utcoffset('')
-        with self.assertRaises(TypeError): self.EST.utcoffset(5)
-
-
-    def test_dst(self):
-        self.assertEqual(None, timezone.utc.dst(self.DT))
-
-        with self.assertRaises(TypeError): self.EST.dst('')
-        with self.assertRaises(TypeError): self.EST.dst(5)
-
-    def test_tzname(self):
-        self.assertEqual('UTC+00:00', timezone(ZERO).tzname(None))
-        self.assertEqual('UTC-05:00', timezone(-5 * HOUR).tzname(None))
-        self.assertEqual('UTC+09:30', timezone(9.5 * HOUR).tzname(None))
-        self.assertEqual('UTC-00:01', timezone(timedelta(minutes=-1)).tzname(None))
-        self.assertEqual('XYZ', timezone(-5 * HOUR, 'XYZ').tzname(None))
-
-        with self.assertRaises(TypeError): self.EST.tzname('')
-        with self.assertRaises(TypeError): self.EST.tzname(5)
-
-    def test_fromutc(self):
-        with self.assertRaises(ValueError):
-            timezone.utc.fromutc(self.DT)
-        with self.assertRaises(TypeError):
-            timezone.utc.fromutc('not datetime')
-        for tz in [self.EST, self.ACDT, Eastern]:
-            utctime = self.DT.replace(tzinfo=tz)
-            local = tz.fromutc(utctime)
-            self.assertEqual(local - utctime, tz.utcoffset(local))
-            self.assertEqual(local,
-                             self.DT.replace(tzinfo=timezone.utc))
-
-    def test_comparison(self):
-        self.assertNotEqual(timezone(ZERO), timezone(HOUR))
-        self.assertEqual(timezone(HOUR), timezone(HOUR))
-        self.assertEqual(timezone(-5 * HOUR), timezone(-5 * HOUR, 'EST'))
-        with self.assertRaises(TypeError): timezone(ZERO) < timezone(ZERO)
-        self.assertIn(timezone(ZERO), {timezone(ZERO)})
-
-    def test_aware_datetime(self):
-        # test that timezone instances can be used by datetime
-        t = datetime(1, 1, 1)
-        for tz in [timezone.min, timezone.max, timezone.utc]:
-            self.assertEqual(tz.tzname(t),
-                             t.replace(tzinfo=tz).tzname())
-            self.assertEqual(tz.utcoffset(t),
-                             t.replace(tzinfo=tz).utcoffset())
-            self.assertEqual(tz.dst(t),
-                             t.replace(tzinfo=tz).dst())
-
-#############################################################################
-# Base clase for testing a particular aspect of timedelta, time, date and
-# datetime comparisons.
-
-class HarmlessMixedComparison:
-    # Test that __eq__ and __ne__ don't complain for mixed-type comparisons.
-
-    # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a
-    # legit constructor.
-
-    def test_harmless_mixed_comparison(self):
-        me = self.theclass(1, 1, 1)
-
-        self.assertFalse(me == ())
-        self.assertTrue(me != ())
-        self.assertFalse(() == me)
-        self.assertTrue(() != me)
-
-        self.assertIn(me, [1, 20, [], me])
-        self.assertIn([], [me, 1, 20, []])
-
-    def test_harmful_mixed_comparison(self):
-        me = self.theclass(1, 1, 1)
-
-        self.assertRaises(TypeError, lambda: me < ())
-        self.assertRaises(TypeError, lambda: me <= ())
-        self.assertRaises(TypeError, lambda: me > ())
-        self.assertRaises(TypeError, lambda: me >= ())
-
-        self.assertRaises(TypeError, lambda: () < me)
-        self.assertRaises(TypeError, lambda: () <= me)
-        self.assertRaises(TypeError, lambda: () > me)
-        self.assertRaises(TypeError, lambda: () >= me)
-
-#############################################################################
-# timedelta tests
-
-class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
-
-    theclass = timedelta
-
-    def test_constructor(self):
-        eq = self.assertEqual
-        td = timedelta
-
-        # Check keyword args to constructor
-        eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0,
-                    milliseconds=0, microseconds=0))
-        eq(td(1), td(days=1))
-        eq(td(0, 1), td(seconds=1))
-        eq(td(0, 0, 1), td(microseconds=1))
-        eq(td(weeks=1), td(days=7))
-        eq(td(days=1), td(hours=24))
-        eq(td(hours=1), td(minutes=60))
-        eq(td(minutes=1), td(seconds=60))
-        eq(td(seconds=1), td(milliseconds=1000))
-        eq(td(milliseconds=1), td(microseconds=1000))
-
-        # Check float args to constructor
-        eq(td(weeks=1.0/7), td(days=1))
-        eq(td(days=1.0/24), td(hours=1))
-        eq(td(hours=1.0/60), td(minutes=1))
-        eq(td(minutes=1.0/60), td(seconds=1))
-        eq(td(seconds=0.001), td(milliseconds=1))
-        eq(td(milliseconds=0.001), td(microseconds=1))
-
-    def test_computations(self):
-        eq = self.assertEqual
-        td = timedelta
-
-        a = td(7) # One week
-        b = td(0, 60) # One minute
-        c = td(0, 0, 1000) # One millisecond
-        eq(a+b+c, td(7, 60, 1000))
-        eq(a-b, td(6, 24*3600 - 60))
-        eq(b.__rsub__(a), td(6, 24*3600 - 60))
-        eq(-a, td(-7))
-        eq(+a, td(7))
-        eq(-b, td(-1, 24*3600 - 60))
-        eq(-c, td(-1, 24*3600 - 1, 999000))
-        eq(abs(a), a)
-        eq(abs(-a), a)
-        eq(td(6, 24*3600), a)
-        eq(td(0, 0, 60*1000000), b)
-        eq(a*10, td(70))
-        eq(a*10, 10*a)
-        eq(a*10, 10*a)
-        eq(b*10, td(0, 600))
-        eq(10*b, td(0, 600))
-        eq(b*10, td(0, 600))
-        eq(c*10, td(0, 0, 10000))
-        eq(10*c, td(0, 0, 10000))
-        eq(c*10, td(0, 0, 10000))
-        eq(a*-1, -a)
-        eq(b*-2, -b-b)
-        eq(c*-2, -c+-c)
-        eq(b*(60*24), (b*60)*24)
-        eq(b*(60*24), (60*b)*24)
-        eq(c*1000, td(0, 1))
-        eq(1000*c, td(0, 1))
-        eq(a//7, td(1))
-        eq(b//10, td(0, 6))
-        eq(c//1000, td(0, 0, 1))
-        eq(a//10, td(0, 7*24*360))
-        eq(a//3600000, td(0, 0, 7*24*1000))
-        eq(a/0.5, td(14))
-        eq(b/0.5, td(0, 120))
-        eq(a/7, td(1))
-        eq(b/10, td(0, 6))
-        eq(c/1000, td(0, 0, 1))
-        eq(a/10, td(0, 7*24*360))
-        eq(a/3600000, td(0, 0, 7*24*1000))
-
-        # Multiplication by float
-        us = td(microseconds=1)
-        eq((3*us) * 0.5, 2*us)
-        eq((5*us) * 0.5, 2*us)
-        eq(0.5 * (3*us), 2*us)
-        eq(0.5 * (5*us), 2*us)
-        eq((-3*us) * 0.5, -2*us)
-        eq((-5*us) * 0.5, -2*us)
-
-        # Division by int and float
-        eq((3*us) / 2, 2*us)
-        eq((5*us) / 2, 2*us)
-        eq((-3*us) / 2.0, -2*us)
-        eq((-5*us) / 2.0, -2*us)
-        eq((3*us) / -2, -2*us)
-        eq((5*us) / -2, -2*us)
-        eq((3*us) / -2.0, -2*us)
-        eq((5*us) / -2.0, -2*us)
-        for i in range(-10, 10):
-            eq((i*us/3)//us, round(i/3))
-        for i in range(-10, 10):
-            eq((i*us/-3)//us, round(i/-3))
-
-    def test_disallowed_computations(self):
-        a = timedelta(42)
-
-        # Add/sub ints or floats should be illegal
-        for i in 1, 1.0:
-            self.assertRaises(TypeError, lambda: a+i)
-            self.assertRaises(TypeError, lambda: a-i)
-            self.assertRaises(TypeError, lambda: i+a)
-            self.assertRaises(TypeError, lambda: i-a)
-
-        # Division of int by timedelta doesn't make sense.
-        # Division by zero doesn't make sense.
-        zero = 0
-        self.assertRaises(TypeError, lambda: zero // a)
-        self.assertRaises(ZeroDivisionError, lambda: a // zero)
-        self.assertRaises(ZeroDivisionError, lambda: a / zero)
-        self.assertRaises(ZeroDivisionError, lambda: a / 0.0)
-        self.assertRaises(TypeError, lambda: a / '')
-
-    @requires_IEEE_754
-    def test_disallowed_special(self):
-        a = timedelta(42)
-        self.assertRaises(ValueError, a.__mul__, NAN)
-        self.assertRaises(ValueError, a.__truediv__, NAN)
-
-    def test_basic_attributes(self):
-        days, seconds, us = 1, 7, 31
-        td = timedelta(days, seconds, us)
-        self.assertEqual(td.days, days)
-        self.assertEqual(td.seconds, seconds)
-        self.assertEqual(td.microseconds, us)
-
-    def test_total_seconds(self):
-        td = timedelta(days=365)
-        self.assertEqual(td.total_seconds(), 31536000.0)
-        for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]:
-            td = timedelta(seconds=total_seconds)
-            self.assertEqual(td.total_seconds(), total_seconds)
-        # Issue8644: Test that td.total_seconds() has the same
-        # accuracy as td / timedelta(seconds=1).
-        for ms in [-1, -2, -123]:
-            td = timedelta(microseconds=ms)
-            self.assertEqual(td.total_seconds(), td / timedelta(seconds=1))
-
-    def test_carries(self):
-        t1 = timedelta(days=100,
-                       weeks=-7,
-                       hours=-24*(100-49),
-                       minutes=-3,
-                       seconds=12,
-                       microseconds=(3*60 - 12) * 1e6 + 1)
-        t2 = timedelta(microseconds=1)
-        self.assertEqual(t1, t2)
-
-    def test_hash_equality(self):
-        t1 = timedelta(days=100,
-                       weeks=-7,
-                       hours=-24*(100-49),
-                       minutes=-3,
-                       seconds=12,
-                       microseconds=(3*60 - 12) * 1000000)
-        t2 = timedelta()
-        self.assertEqual(hash(t1), hash(t2))
-
-        t1 += timedelta(weeks=7)
-        t2 += timedelta(days=7*7)
-        self.assertEqual(t1, t2)
-        self.assertEqual(hash(t1), hash(t2))
-
-        d = {t1: 1}
-        d[t2] = 2
-        self.assertEqual(len(d), 1)
-        self.assertEqual(d[t1], 2)
-
-    def test_pickling(self):
-        args = 12, 34, 56
-        orig = timedelta(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_compare(self):
-        t1 = timedelta(2, 3, 4)
-        t2 = timedelta(2, 3, 4)
-        self.assertEqual(t1, t2)
-        self.assertTrue(t1 <= t2)
-        self.assertTrue(t1 >= t2)
-        self.assertTrue(not t1 != t2)
-        self.assertTrue(not t1 < t2)
-        self.assertTrue(not t1 > t2)
-
-        for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
-            t2 = timedelta(*args)   # this is larger than t1
-            self.assertTrue(t1 < t2)
-            self.assertTrue(t2 > t1)
-            self.assertTrue(t1 <= t2)
-            self.assertTrue(t2 >= t1)
-            self.assertTrue(t1 != t2)
-            self.assertTrue(t2 != t1)
-            self.assertTrue(not t1 == t2)
-            self.assertTrue(not t2 == t1)
-            self.assertTrue(not t1 > t2)
-            self.assertTrue(not t2 < t1)
-            self.assertTrue(not t1 >= t2)
-            self.assertTrue(not t2 <= t1)
-
-        for badarg in OTHERSTUFF:
-            self.assertEqual(t1 == badarg, False)
-            self.assertEqual(t1 != badarg, True)
-            self.assertEqual(badarg == t1, False)
-            self.assertEqual(badarg != t1, True)
-
-            self.assertRaises(TypeError, lambda: t1 <= badarg)
-            self.assertRaises(TypeError, lambda: t1 < badarg)
-            self.assertRaises(TypeError, lambda: t1 > badarg)
-            self.assertRaises(TypeError, lambda: t1 >= badarg)
-            self.assertRaises(TypeError, lambda: badarg <= t1)
-            self.assertRaises(TypeError, lambda: badarg < t1)
-            self.assertRaises(TypeError, lambda: badarg > t1)
-            self.assertRaises(TypeError, lambda: badarg >= t1)
-
-    def test_str(self):
-        td = timedelta
-        eq = self.assertEqual
-
-        eq(str(td(1)), "1 day, 0:00:00")
-        eq(str(td(-1)), "-1 day, 0:00:00")
-        eq(str(td(2)), "2 days, 0:00:00")
-        eq(str(td(-2)), "-2 days, 0:00:00")
-
-        eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59")
-        eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04")
-        eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)),
-           "-210 days, 23:12:34")
-
-        eq(str(td(milliseconds=1)), "0:00:00.001000")
-        eq(str(td(microseconds=3)), "0:00:00.000003")
-
-        eq(str(td(days=999999999, hours=23, minutes=59, seconds=59,
-                   microseconds=999999)),
-           "999999999 days, 23:59:59.999999")
-
-    def test_repr(self):
-        name = 'datetime.' + self.theclass.__name__
-        self.assertEqual(repr(self.theclass(1)),
-                         "%s(1)" % name)
-        self.assertEqual(repr(self.theclass(10, 2)),
-                         "%s(10, 2)" % name)
-        self.assertEqual(repr(self.theclass(-10, 2, 400000)),
-                         "%s(-10, 2, 400000)" % name)
-
-    def test_roundtrip(self):
-        for td in (timedelta(days=999999999, hours=23, minutes=59,
-                             seconds=59, microseconds=999999),
-                   timedelta(days=-999999999),
-                   timedelta(days=-999999999, seconds=1),
-                   timedelta(days=1, seconds=2, microseconds=3)):
-
-            # Verify td -> string -> td identity.
-            s = repr(td)
-            self.assertTrue(s.startswith('datetime.'))
-            s = s[9:]
-            td2 = eval(s)
-            self.assertEqual(td, td2)
-
-            # Verify identity via reconstructing from pieces.
-            td2 = timedelta(td.days, td.seconds, td.microseconds)
-            self.assertEqual(td, td2)
-
-    def test_resolution_info(self):
-        self.assertIsInstance(timedelta.min, timedelta)
-        self.assertIsInstance(timedelta.max, timedelta)
-        self.assertIsInstance(timedelta.resolution, timedelta)
-        self.assertTrue(timedelta.max > timedelta.min)
-        self.assertEqual(timedelta.min, timedelta(-999999999))
-        self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
-        self.assertEqual(timedelta.resolution, timedelta(0, 0, 1))
-
-    def test_overflow(self):
-        tiny = timedelta.resolution
-
-        td = timedelta.min + tiny
-        td -= tiny  # no problem
-        self.assertRaises(OverflowError, td.__sub__, tiny)
-        self.assertRaises(OverflowError, td.__add__, -tiny)
-
-        td = timedelta.max - tiny
-        td += tiny  # no problem
-        self.assertRaises(OverflowError, td.__add__, tiny)
-        self.assertRaises(OverflowError, td.__sub__, -tiny)
-
-        self.assertRaises(OverflowError, lambda: -timedelta.max)
-
-        day = timedelta(1)
-        self.assertRaises(OverflowError, day.__mul__, 10**9)
-        self.assertRaises(OverflowError, day.__mul__, 1e9)
-        self.assertRaises(OverflowError, day.__truediv__, 1e-20)
-        self.assertRaises(OverflowError, day.__truediv__, 1e-10)
-        self.assertRaises(OverflowError, day.__truediv__, 9e-10)
-
-    @requires_IEEE_754
-    def _test_overflow_special(self):
-        day = timedelta(1)
-        self.assertRaises(OverflowError, day.__mul__, INF)
-        self.assertRaises(OverflowError, day.__mul__, -INF)
-
-    def test_microsecond_rounding(self):
-        td = timedelta
-        eq = self.assertEqual
-
-        # Single-field rounding.
-        eq(td(milliseconds=0.4/1000), td(0))    # rounds to 0
-        eq(td(milliseconds=-0.4/1000), td(0))    # rounds to 0
-        eq(td(milliseconds=0.6/1000), td(microseconds=1))
-        eq(td(milliseconds=-0.6/1000), td(microseconds=-1))
-
-        # Rounding due to contributions from more than one field.
-        us_per_hour = 3600e6
-        us_per_day = us_per_hour * 24
-        eq(td(days=.4/us_per_day), td(0))
-        eq(td(hours=.2/us_per_hour), td(0))
-        eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1))
-
-        eq(td(days=-.4/us_per_day), td(0))
-        eq(td(hours=-.2/us_per_hour), td(0))
-        eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1))
-
-    def test_massive_normalization(self):
-        td = timedelta(microseconds=-1)
-        self.assertEqual((td.days, td.seconds, td.microseconds),
-                         (-1, 24*3600-1, 999999))
-
-    def test_bool(self):
-        self.assertTrue(timedelta(1))
-        self.assertTrue(timedelta(0, 1))
-        self.assertTrue(timedelta(0, 0, 1))
-        self.assertTrue(timedelta(microseconds=1))
-        self.assertTrue(not timedelta(0))
-
-    def test_subclass_timedelta(self):
-
-        class T(timedelta):
-            @staticmethod
-            def from_td(td):
-                return T(td.days, td.seconds, td.microseconds)
-
-            def as_hours(self):
-                sum = (self.days * 24 +
-                       self.seconds / 3600.0 +
-                       self.microseconds / 3600e6)
-                return round(sum)
-
-        t1 = T(days=1)
-        self.assertTrue(type(t1) is T)
-        self.assertEqual(t1.as_hours(), 24)
-
-        t2 = T(days=-1, seconds=-3600)
-        self.assertTrue(type(t2) is T)
-        self.assertEqual(t2.as_hours(), -25)
-
-        t3 = t1 + t2
-        self.assertTrue(type(t3) is timedelta)
-        t4 = T.from_td(t3)
-        self.assertTrue(type(t4) is T)
-        self.assertEqual(t3.days, t4.days)
-        self.assertEqual(t3.seconds, t4.seconds)
-        self.assertEqual(t3.microseconds, t4.microseconds)
-        self.assertEqual(str(t3), str(t4))
-        self.assertEqual(t4.as_hours(), -1)
-
-    def test_division(self):
-        t = timedelta(hours=1, minutes=24, seconds=19)
-        second = timedelta(seconds=1)
-        self.assertEqual(t / second, 5059.0)
-        self.assertEqual(t // second, 5059)
-
-        t = timedelta(minutes=2, seconds=30)
-        minute = timedelta(minutes=1)
-        self.assertEqual(t / minute, 2.5)
-        self.assertEqual(t // minute, 2)
-
-        zerotd = timedelta(0)
-        self.assertRaises(ZeroDivisionError, truediv, t, zerotd)
-        self.assertRaises(ZeroDivisionError, floordiv, t, zerotd)
-
-        # self.assertRaises(TypeError, truediv, t, 2)
-        # note: floor division of a timedelta by an integer *is*
-        # currently permitted.
-
-    def test_remainder(self):
-        t = timedelta(minutes=2, seconds=30)
-        minute = timedelta(minutes=1)
-        r = t % minute
-        self.assertEqual(r, timedelta(seconds=30))
-
-        t = timedelta(minutes=-2, seconds=30)
-        r = t %  minute
-        self.assertEqual(r, timedelta(seconds=30))
-
-        zerotd = timedelta(0)
-        self.assertRaises(ZeroDivisionError, mod, t, zerotd)
-
-        self.assertRaises(TypeError, mod, t, 10)
-
-    def test_divmod(self):
-        t = timedelta(minutes=2, seconds=30)
-        minute = timedelta(minutes=1)
-        q, r = divmod(t, minute)
-        self.assertEqual(q, 2)
-        self.assertEqual(r, timedelta(seconds=30))
-
-        t = timedelta(minutes=-2, seconds=30)
-        q, r = divmod(t, minute)
-        self.assertEqual(q, -2)
-        self.assertEqual(r, timedelta(seconds=30))
-
-        zerotd = timedelta(0)
-        self.assertRaises(ZeroDivisionError, divmod, t, zerotd)
-
-        self.assertRaises(TypeError, divmod, t, 10)
-
-
-#############################################################################
-# date tests
-
-class TestDateOnly(unittest.TestCase):
-    # Tests here won't pass if also run on datetime objects, so don't
-    # subclass this to test datetimes too.
-
-    def test_delta_non_days_ignored(self):
-        dt = date(2000, 1, 2)
-        delta = timedelta(days=1, hours=2, minutes=3, seconds=4,
-                          microseconds=5)
-        days = timedelta(delta.days)
-        self.assertEqual(days, timedelta(1))
-
-        dt2 = dt + delta
-        self.assertEqual(dt2, dt + days)
-
-        dt2 = delta + dt
-        self.assertEqual(dt2, dt + days)
-
-        dt2 = dt - delta
-        self.assertEqual(dt2, dt - days)
-
-        delta = -delta
-        days = timedelta(delta.days)
-        self.assertEqual(days, timedelta(-2))
-
-        dt2 = dt + delta
-        self.assertEqual(dt2, dt + days)
-
-        dt2 = delta + dt
-        self.assertEqual(dt2, dt + days)
-
-        dt2 = dt - delta
-        self.assertEqual(dt2, dt - days)
-
-class SubclassDate(date):
-    sub_var = 1
-
-class TestDate(HarmlessMixedComparison, unittest.TestCase):
-    # Tests here should pass for both dates and datetimes, except for a
-    # few tests that TestDateTime overrides.
-
-    theclass = date
-
-    def test_basic_attributes(self):
-        dt = self.theclass(2002, 3, 1)
-        self.assertEqual(dt.year, 2002)
-        self.assertEqual(dt.month, 3)
-        self.assertEqual(dt.day, 1)
-
-    def test_roundtrip(self):
-        for dt in (self.theclass(1, 2, 3),
-                   self.theclass.today()):
-            # Verify dt -> string -> date identity.
-            s = repr(dt)
-            self.assertTrue(s.startswith('datetime.'))
-            s = s[9:]
-            dt2 = eval(s)
-            self.assertEqual(dt, dt2)
-
-            # Verify identity via reconstructing from pieces.
-            dt2 = self.theclass(dt.year, dt.month, dt.day)
-            self.assertEqual(dt, dt2)
-
-    def test_ordinal_conversions(self):
-        # Check some fixed values.
-        for y, m, d, n in [(1, 1, 1, 1),      # calendar origin
-                           (1, 12, 31, 365),
-                           (2, 1, 1, 366),
-                           # first example from "Calendrical Calculations"
-                           (1945, 11, 12, 710347)]:
-            d = self.theclass(y, m, d)
-            self.assertEqual(n, d.toordinal())
-            fromord = self.theclass.fromordinal(n)
-            self.assertEqual(d, fromord)
-            if hasattr(fromord, "hour"):
-            # if we're checking something fancier than a date, verify
-            # the extra fields have been zeroed out
-                self.assertEqual(fromord.hour, 0)
-                self.assertEqual(fromord.minute, 0)
-                self.assertEqual(fromord.second, 0)
-                self.assertEqual(fromord.microsecond, 0)
-
-        # Check first and last days of year spottily across the whole
-        # range of years supported.
-        for year in range(MINYEAR, MAXYEAR+1, 7):
-            # Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
-            d = self.theclass(year, 1, 1)
-            n = d.toordinal()
-            d2 = self.theclass.fromordinal(n)
-            self.assertEqual(d, d2)
-            # Verify that moving back a day gets to the end of year-1.
-            if year > 1:
-                d = self.theclass.fromordinal(n-1)
-                d2 = self.theclass(year-1, 12, 31)
-                self.assertEqual(d, d2)
-                self.assertEqual(d2.toordinal(), n-1)
-
-        # Test every day in a leap-year and a non-leap year.
-        dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-        for year, isleap in (2000, True), (2002, False):
-            n = self.theclass(year, 1, 1).toordinal()
-            for month, maxday in zip(range(1, 13), dim):
-                if month == 2 and isleap:
-                    maxday += 1
-                for day in range(1, maxday+1):
-                    d = self.theclass(year, month, day)
-                    self.assertEqual(d.toordinal(), n)
-                    self.assertEqual(d, self.theclass.fromordinal(n))
-                    n += 1
-
-    def test_extreme_ordinals(self):
-        a = self.theclass.min
-        a = self.theclass(a.year, a.month, a.day)  # get rid of time parts
-        aord = a.toordinal()
-        b = a.fromordinal(aord)
-        self.assertEqual(a, b)
-
-        self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1))
-
-        b = a + timedelta(days=1)
-        self.assertEqual(b.toordinal(), aord + 1)
-        self.assertEqual(b, self.theclass.fromordinal(aord + 1))
-
-        a = self.theclass.max
-        a = self.theclass(a.year, a.month, a.day)  # get rid of time parts
-        aord = a.toordinal()
-        b = a.fromordinal(aord)
-        self.assertEqual(a, b)
-
-        self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))
-
-        b = a - timedelta(days=1)
-        self.assertEqual(b.toordinal(), aord - 1)
-        self.assertEqual(b, self.theclass.fromordinal(aord - 1))
-
-    def test_bad_constructor_arguments(self):
-        # bad years
-        self.theclass(MINYEAR, 1, 1)  # no exception
-        self.theclass(MAXYEAR, 1, 1)  # no exception
-        self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
-        self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
-        # bad months
-        self.theclass(2000, 1, 1)    # no exception
-        self.theclass(2000, 12, 1)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
-        self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
-        # bad days
-        self.theclass(2000, 2, 29)   # no exception
-        self.theclass(2004, 2, 29)   # no exception
-        self.theclass(2400, 2, 29)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
-        self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
-        self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
-        self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
-
-    def test_hash_equality(self):
-        d = self.theclass(2000, 12, 31)
-        # same thing
-        e = self.theclass(2000, 12, 31)
-        self.assertEqual(d, e)
-        self.assertEqual(hash(d), hash(e))
-
-        dic = {d: 1}
-        dic[e] = 2
-        self.assertEqual(len(dic), 1)
-        self.assertEqual(dic[d], 2)
-        self.assertEqual(dic[e], 2)
-
-        d = self.theclass(2001,  1,  1)
-        # same thing
-        e = self.theclass(2001,  1,  1)
-        self.assertEqual(d, e)
-        self.assertEqual(hash(d), hash(e))
-
-        dic = {d: 1}
-        dic[e] = 2
-        self.assertEqual(len(dic), 1)
-        self.assertEqual(dic[d], 2)
-        self.assertEqual(dic[e], 2)
-
-    def test_computations(self):
-        a = self.theclass(2002, 1, 31)
-        b = self.theclass(1956, 1, 31)
-        c = self.theclass(2001,2,1)
-
-        diff = a-b
-        self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
-        self.assertEqual(diff.seconds, 0)
-        self.assertEqual(diff.microseconds, 0)
-
-        day = timedelta(1)
-        week = timedelta(7)
-        a = self.theclass(2002, 3, 2)
-        self.assertEqual(a + day, self.theclass(2002, 3, 3))
-        self.assertEqual(day + a, self.theclass(2002, 3, 3))
-        self.assertEqual(a - day, self.theclass(2002, 3, 1))
-        self.assertEqual(-day + a, self.theclass(2002, 3, 1))
-        self.assertEqual(a + week, self.theclass(2002, 3, 9))
-        self.assertEqual(a - week, self.theclass(2002, 2, 23))
-        self.assertEqual(a + 52*week, self.theclass(2003, 3, 1))
-        self.assertEqual(a - 52*week, self.theclass(2001, 3, 3))
-        self.assertEqual((a + week) - a, week)
-        self.assertEqual((a + day) - a, day)
-        self.assertEqual((a - week) - a, -week)
-        self.assertEqual((a - day) - a, -day)
-        self.assertEqual(a - (a + week), -week)
-        self.assertEqual(a - (a + day), -day)
-        self.assertEqual(a - (a - week), week)
-        self.assertEqual(a - (a - day), day)
-        self.assertEqual(c - (c - day), day)
-
-        # Add/sub ints or floats should be illegal
-        for i in 1, 1.0:
-            self.assertRaises(TypeError, lambda: a+i)
-            self.assertRaises(TypeError, lambda: a-i)
-            self.assertRaises(TypeError, lambda: i+a)
-            self.assertRaises(TypeError, lambda: i-a)
-
-        # delta - date is senseless.
-        self.assertRaises(TypeError, lambda: day - a)
-        # mixing date and (delta or date) via * or // is senseless
-        self.assertRaises(TypeError, lambda: day * a)
-        self.assertRaises(TypeError, lambda: a * day)
-        self.assertRaises(TypeError, lambda: day // a)
-        self.assertRaises(TypeError, lambda: a // day)
-        self.assertRaises(TypeError, lambda: a * a)
-        self.assertRaises(TypeError, lambda: a // a)
-        # date + date is senseless
-        self.assertRaises(TypeError, lambda: a + a)
-
-    def test_overflow(self):
-        tiny = self.theclass.resolution
-
-        for delta in [tiny, timedelta(1), timedelta(2)]:
-            dt = self.theclass.min + delta
-            dt -= delta  # no problem
-            self.assertRaises(OverflowError, dt.__sub__, delta)
-            self.assertRaises(OverflowError, dt.__add__, -delta)
-
-            dt = self.theclass.max - delta
-            dt += delta  # no problem
-            self.assertRaises(OverflowError, dt.__add__, delta)
-            self.assertRaises(OverflowError, dt.__sub__, -delta)
-
-    def test_fromtimestamp(self):
-        import time
-
-        # Try an arbitrary fixed value.
-        year, month, day = 1999, 9, 19
-        ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
-        d = self.theclass.fromtimestamp(ts)
-        self.assertEqual(d.year, year)
-        self.assertEqual(d.month, month)
-        self.assertEqual(d.day, day)
-
-    def test_insane_fromtimestamp(self):
-        # It's possible that some platform maps time_t to double,
-        # and that this test will fail there.  This test should
-        # exempt such platforms (provided they return reasonable
-        # results!).
-        for insane in -1e200, 1e200:
-            self.assertRaises(ValueError, self.theclass.fromtimestamp,
-                              insane)
-
-    def test_today(self):
-        import time
-
-        # We claim that today() is like fromtimestamp(time.time()), so
-        # prove it.
-        for dummy in range(3):
-            today = self.theclass.today()
-            ts = time.time()
-            todayagain = self.theclass.fromtimestamp(ts)
-            if today == todayagain:
-                break
-            # There are several legit reasons that could fail:
-            # 1. It recently became midnight, between the today() and the
-            #    time() calls.
-            # 2. The platform time() has such fine resolution that we'll
-            #    never get the same value twice.
-            # 3. The platform time() has poor resolution, and we just
-            #    happened to call today() right before a resolution quantum
-            #    boundary.
-            # 4. The system clock got fiddled between calls.
-            # In any case, wait a little while and try again.
-            time.sleep(0.1)
-
-        # It worked or it didn't.  If it didn't, assume it's reason #2, and
-        # let the test pass if they're within half a second of each other.
-        self.assertTrue(today == todayagain or
-                        abs(todayagain - today) < timedelta(seconds=0.5))
-
-    def test_weekday(self):
-        for i in range(7):
-            # March 4, 2002 is a Monday
-            self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i)
-            self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1)
-            # January 2, 1956 is a Monday
-            self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i)
-            self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1)
-
-    def test_isocalendar(self):
-        # Check examples from
-        # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
-        for i in range(7):
-            d = self.theclass(2003, 12, 22+i)
-            self.assertEqual(d.isocalendar(), (2003, 52, i+1))
-            d = self.theclass(2003, 12, 29) + timedelta(i)
-            self.assertEqual(d.isocalendar(), (2004, 1, i+1))
-            d = self.theclass(2004, 1, 5+i)
-            self.assertEqual(d.isocalendar(), (2004, 2, i+1))
-            d = self.theclass(2009, 12, 21+i)
-            self.assertEqual(d.isocalendar(), (2009, 52, i+1))
-            d = self.theclass(2009, 12, 28) + timedelta(i)
-            self.assertEqual(d.isocalendar(), (2009, 53, i+1))
-            d = self.theclass(2010, 1, 4+i)
-            self.assertEqual(d.isocalendar(), (2010, 1, i+1))
-
-    def test_iso_long_years(self):
-        # Calculate long ISO years and compare to table from
-        # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
-        ISO_LONG_YEARS_TABLE = """
-              4   32   60   88
-              9   37   65   93
-             15   43   71   99
-             20   48   76
-             26   54   82
-
-            105  133  161  189
-            111  139  167  195
-            116  144  172
-            122  150  178
-            128  156  184
-
-            201  229  257  285
-            207  235  263  291
-            212  240  268  296
-            218  246  274
-            224  252  280
-
-            303  331  359  387
-            308  336  364  392
-            314  342  370  398
-            320  348  376
-            325  353  381
-        """
-        iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split()))
-        L = []
-        for i in range(400):
-            d = self.theclass(2000+i, 12, 31)
-            d1 = self.theclass(1600+i, 12, 31)
-            self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:])
-            if d.isocalendar()[1] == 53:
-                L.append(i)
-        self.assertEqual(L, iso_long_years)
-
-    def test_isoformat(self):
-        t = self.theclass(2, 3, 2)
-        self.assertEqual(t.isoformat(), "0002-03-02")
-
-    def test_ctime(self):
-        t = self.theclass(2002, 3, 2)
-        self.assertEqual(t.ctime(), "Sat Mar  2 00:00:00 2002")
-
-    def test_strftime(self):
-        t = self.theclass(2005, 3, 2)
-        self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05")
-        self.assertEqual(t.strftime(""), "") # SF bug #761337
-        self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784
-
-        self.assertRaises(TypeError, t.strftime) # needs an arg
-        self.assertRaises(TypeError, t.strftime, "one", "two") # too many args
-        self.assertRaises(TypeError, t.strftime, 42) # arg wrong type
-
-        # test that unicode input is allowed (issue 2782)
-        self.assertEqual(t.strftime("%m"), "03")
-
-        # A naive object replaces %z and %Z w/ empty strings.
-        self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
-
-        #make sure that invalid format specifiers are handled correctly
-        #self.assertRaises(ValueError, t.strftime, "%e")
-        #self.assertRaises(ValueError, t.strftime, "%")
-        #self.assertRaises(ValueError, t.strftime, "%#")
-
-        #oh well, some systems just ignore those invalid ones.
-        #at least, excercise them to make sure that no crashes
-        #are generated
-        for f in ["%e", "%", "%#"]:
-            try:
-                t.strftime(f)
-            except ValueError:
-                pass
-
-        #check that this standard extension works
-        t.strftime("%f")
-
-
-    def test_format(self):
-        dt = self.theclass(2007, 9, 10)
-        self.assertEqual(dt.__format__(''), str(dt))
-
-        # check that a derived class's __str__() gets called
-        class A(self.theclass):
-            def __str__(self):
-                return 'A'
-        a = A(2007, 9, 10)
-        self.assertEqual(a.__format__(''), 'A')
-
-        # check that a derived class's strftime gets called
-        class B(self.theclass):
-            def strftime(self, format_spec):
-                return 'B'
-        b = B(2007, 9, 10)
-        self.assertEqual(b.__format__(''), str(dt))
-
-        for fmt in ["m:%m d:%d y:%y",
-                    "m:%m d:%d y:%y H:%H M:%M S:%S",
-                    "%z %Z",
-                    ]:
-            self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
-            self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
-            self.assertEqual(b.__format__(fmt), 'B')
-
-    def test_resolution_info(self):
-        # XXX: Should min and max respect subclassing?
-        if issubclass(self.theclass, datetime):
-            expected_class = datetime
-        else:
-            expected_class = date
-        self.assertIsInstance(self.theclass.min, expected_class)
-        self.assertIsInstance(self.theclass.max, expected_class)
-        self.assertIsInstance(self.theclass.resolution, timedelta)
-        self.assertTrue(self.theclass.max > self.theclass.min)
-
-    def test_extreme_timedelta(self):
-        big = self.theclass.max - self.theclass.min
-        # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
-        n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
-        # n == 315537897599999999 ~= 2**58.13
-        justasbig = timedelta(0, 0, n)
-        self.assertEqual(big, justasbig)
-        self.assertEqual(self.theclass.min + big, self.theclass.max)
-        self.assertEqual(self.theclass.max - big, self.theclass.min)
-
-    def test_timetuple(self):
-        for i in range(7):
-            # January 2, 1956 is a Monday (0)
-            d = self.theclass(1956, 1, 2+i)
-            t = d.timetuple()
-            self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1))
-            # February 1, 1956 is a Wednesday (2)
-            d = self.theclass(1956, 2, 1+i)
-            t = d.timetuple()
-            self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1))
-            # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day
-            # of the year.
-            d = self.theclass(1956, 3, 1+i)
-            t = d.timetuple()
-            self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1))
-            self.assertEqual(t.tm_year, 1956)
-            self.assertEqual(t.tm_mon, 3)
-            self.assertEqual(t.tm_mday, 1+i)
-            self.assertEqual(t.tm_hour, 0)
-            self.assertEqual(t.tm_min, 0)
-            self.assertEqual(t.tm_sec, 0)
-            self.assertEqual(t.tm_wday, (3+i)%7)
-            self.assertEqual(t.tm_yday, 61+i)
-            self.assertEqual(t.tm_isdst, -1)
-
-    def test_pickling(self):
-        args = 6, 7, 23
-        orig = self.theclass(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_compare(self):
-        t1 = self.theclass(2, 3, 4)
-        t2 = self.theclass(2, 3, 4)
-        self.assertEqual(t1, t2)
-        self.assertTrue(t1 <= t2)
-        self.assertTrue(t1 >= t2)
-        self.assertTrue(not t1 != t2)
-        self.assertTrue(not t1 < t2)
-        self.assertTrue(not t1 > t2)
-
-        for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
-            t2 = self.theclass(*args)   # this is larger than t1
-            self.assertTrue(t1 < t2)
-            self.assertTrue(t2 > t1)
-            self.assertTrue(t1 <= t2)
-            self.assertTrue(t2 >= t1)
-            self.assertTrue(t1 != t2)
-            self.assertTrue(t2 != t1)
-            self.assertTrue(not t1 == t2)
-            self.assertTrue(not t2 == t1)
-            self.assertTrue(not t1 > t2)
-            self.assertTrue(not t2 < t1)
-            self.assertTrue(not t1 >= t2)
-            self.assertTrue(not t2 <= t1)
-
-        for badarg in OTHERSTUFF:
-            self.assertEqual(t1 == badarg, False)
-            self.assertEqual(t1 != badarg, True)
-            self.assertEqual(badarg == t1, False)
-            self.assertEqual(badarg != t1, True)
-
-            self.assertRaises(TypeError, lambda: t1 < badarg)
-            self.assertRaises(TypeError, lambda: t1 > badarg)
-            self.assertRaises(TypeError, lambda: t1 >= badarg)
-            self.assertRaises(TypeError, lambda: badarg <= t1)
-            self.assertRaises(TypeError, lambda: badarg < t1)
-            self.assertRaises(TypeError, lambda: badarg > t1)
-            self.assertRaises(TypeError, lambda: badarg >= t1)
-
-    def test_mixed_compare(self):
-        our = self.theclass(2000, 4, 5)
-
-        # Our class can be compared for equality to other classes
-        self.assertEqual(our == 1, False)
-        self.assertEqual(1 == our, False)
-        self.assertEqual(our != 1, True)
-        self.assertEqual(1 != our, True)
-
-        # But the ordering is undefined
-        self.assertRaises(TypeError, lambda: our < 1)
-        self.assertRaises(TypeError, lambda: 1 < our)
-
-        # Repeat those tests with a different class
-
-        class SomeClass:
-            pass
-
-        their = SomeClass()
-        self.assertEqual(our == their, False)
-        self.assertEqual(their == our, False)
-        self.assertEqual(our != their, True)
-        self.assertEqual(their != our, True)
-        self.assertRaises(TypeError, lambda: our < their)
-        self.assertRaises(TypeError, lambda: their < our)
-
-        # However, if the other class explicitly defines ordering
-        # relative to our class, it is allowed to do so
-
-        class LargerThanAnything:
-            def __lt__(self, other):
-                return False
-            def __le__(self, other):
-                return isinstance(other, LargerThanAnything)
-            def __eq__(self, other):
-                return isinstance(other, LargerThanAnything)
-            def __ne__(self, other):
-                return not isinstance(other, LargerThanAnything)
-            def __gt__(self, other):
-                return not isinstance(other, LargerThanAnything)
-            def __ge__(self, other):
-                return True
-
-        their = LargerThanAnything()
-        self.assertEqual(our == their, False)
-        self.assertEqual(their == our, False)
-        self.assertEqual(our != their, True)
-        self.assertEqual(their != our, True)
-        self.assertEqual(our < their, True)
-        self.assertEqual(their < our, False)
-
-    def test_bool(self):
-        # All dates are considered true.
-        self.assertTrue(self.theclass.min)
-        self.assertTrue(self.theclass.max)
-
-    def test_strftime_out_of_range(self):
-        # For nasty technical reasons, we can't handle years before 1900.
-        cls = self.theclass
-        self.assertEqual(cls(1900, 1, 1).strftime("%Y"), "1900")
-        for y in 1, 49, 51, 99, 100, 1000, 1899:
-            self.assertRaises(ValueError, cls(y, 1, 1).strftime, "%Y")
-
-    def test_replace(self):
-        cls = self.theclass
-        args = [1, 2, 3]
-        base = cls(*args)
-        self.assertEqual(base, base.replace())
-
-        i = 0
-        for name, newval in (("year", 2),
-                             ("month", 3),
-                             ("day", 4)):
-            newargs = args[:]
-            newargs[i] = newval
-            expected = cls(*newargs)
-            got = base.replace(**{name: newval})
-            self.assertEqual(expected, got)
-            i += 1
-
-        # Out of bounds.
-        base = cls(2000, 2, 29)
-        self.assertRaises(ValueError, base.replace, year=2001)
-
-    def test_subclass_date(self):
-
-        class C(self.theclass):
-            theAnswer = 42
-
-            def __new__(cls, *args, **kws):
-                temp = kws.copy()
-                extra = temp.pop('extra')
-                result = self.theclass.__new__(cls, *args, **temp)
-                result.extra = extra
-                return result
-
-            def newmeth(self, start):
-                return start + self.year + self.month
-
-        args = 2003, 4, 14
-
-        dt1 = self.theclass(*args)
-        dt2 = C(*args, **{'extra': 7})
-
-        self.assertEqual(dt2.__class__, C)
-        self.assertEqual(dt2.theAnswer, 42)
-        self.assertEqual(dt2.extra, 7)
-        self.assertEqual(dt1.toordinal(), dt2.toordinal())
-        self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month - 7)
-
-    def test_pickling_subclass_date(self):
-
-        args = 6, 7, 23
-        orig = SubclassDate(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_backdoor_resistance(self):
-        # For fast unpickling, the constructor accepts a pickle byte string.
-        # This is a low-overhead backdoor.  A user can (by intent or
-        # mistake) pass a string directly, which (if it's the right length)
-        # will get treated like a pickle, and bypass the normal sanity
-        # checks in the constructor.  This can create insane objects.
-        # The constructor doesn't want to burn the time to validate all
-        # fields, but does check the month field.  This stops, e.g.,
-        # datetime.datetime('1995-03-25') from yielding an insane object.
-        base = b'1995-03-25'
-        if not issubclass(self.theclass, datetime):
-            base = base[:4]
-        for month_byte in b'9', b'\0', b'\r', b'\xff':
-            self.assertRaises(TypeError, self.theclass,
-                                         base[:2] + month_byte + base[3:])
-        # Good bytes, but bad tzinfo:
-        self.assertRaises(TypeError, self.theclass,
-                          bytes([1] * len(base)), 'EST')
-
-        for ord_byte in range(1, 13):
-            # This shouldn't blow up because of the month byte alone.  If
-            # the implementation changes to do more-careful checking, it may
-            # blow up because other fields are insane.
-            self.theclass(base[:2] + bytes([ord_byte]) + base[3:])
-
-#############################################################################
-# datetime tests
-
-class SubclassDatetime(datetime):
-    sub_var = 1
-
-class TestDateTime(TestDate):
-
-    theclass = datetime
-
-    def test_basic_attributes(self):
-        dt = self.theclass(2002, 3, 1, 12, 0)
-        self.assertEqual(dt.year, 2002)
-        self.assertEqual(dt.month, 3)
-        self.assertEqual(dt.day, 1)
-        self.assertEqual(dt.hour, 12)
-        self.assertEqual(dt.minute, 0)
-        self.assertEqual(dt.second, 0)
-        self.assertEqual(dt.microsecond, 0)
-
-    def test_basic_attributes_nonzero(self):
-        # Make sure all attributes are non-zero so bugs in
-        # bit-shifting access show up.
-        dt = self.theclass(2002, 3, 1, 12, 59, 59, 8000)
-        self.assertEqual(dt.year, 2002)
-        self.assertEqual(dt.month, 3)
-        self.assertEqual(dt.day, 1)
-        self.assertEqual(dt.hour, 12)
-        self.assertEqual(dt.minute, 59)
-        self.assertEqual(dt.second, 59)
-        self.assertEqual(dt.microsecond, 8000)
-
-    def test_roundtrip(self):
-        for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
-                   self.theclass.now()):
-            # Verify dt -> string -> datetime identity.
-            s = repr(dt)
-            self.assertTrue(s.startswith('datetime.'))
-            s = s[9:]
-            dt2 = eval(s)
-            self.assertEqual(dt, dt2)
-
-            # Verify identity via reconstructing from pieces.
-            dt2 = self.theclass(dt.year, dt.month, dt.day,
-                                dt.hour, dt.minute, dt.second,
-                                dt.microsecond)
-            self.assertEqual(dt, dt2)
-
-    def test_isoformat(self):
-        t = self.theclass(2, 3, 2, 4, 5, 1, 123)
-        self.assertEqual(t.isoformat(),    "0002-03-02T04:05:01.000123")
-        self.assertEqual(t.isoformat('T'), "0002-03-02T04:05:01.000123")
-        self.assertEqual(t.isoformat(' '), "0002-03-02 04:05:01.000123")
-        self.assertEqual(t.isoformat('\x00'), "0002-03-02\x0004:05:01.000123")
-        # str is ISO format with the separator forced to a blank.
-        self.assertEqual(str(t), "0002-03-02 04:05:01.000123")
-
-        t = self.theclass(2, 3, 2)
-        self.assertEqual(t.isoformat(),    "0002-03-02T00:00:00")
-        self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00")
-        self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00")
-        # str is ISO format with the separator forced to a blank.
-        self.assertEqual(str(t), "0002-03-02 00:00:00")
-
-    def test_format(self):
-        dt = self.theclass(2007, 9, 10, 4, 5, 1, 123)
-        self.assertEqual(dt.__format__(''), str(dt))
-
-        # check that a derived class's __str__() gets called
-        class A(self.theclass):
-            def __str__(self):
-                return 'A'
-        a = A(2007, 9, 10, 4, 5, 1, 123)
-        self.assertEqual(a.__format__(''), 'A')
-
-        # check that a derived class's strftime gets called
-        class B(self.theclass):
-            def strftime(self, format_spec):
-                return 'B'
-        b = B(2007, 9, 10, 4, 5, 1, 123)
-        self.assertEqual(b.__format__(''), str(dt))
-
-        for fmt in ["m:%m d:%d y:%y",
-                    "m:%m d:%d y:%y H:%H M:%M S:%S",
-                    "%z %Z",
-                    ]:
-            self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
-            self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
-            self.assertEqual(b.__format__(fmt), 'B')
-
-    def test_more_ctime(self):
-        # Test fields that TestDate doesn't touch.
-        import time
-
-        t = self.theclass(2002, 3, 2, 18, 3, 5, 123)
-        self.assertEqual(t.ctime(), "Sat Mar  2 18:03:05 2002")
-        # Oops!  The next line fails on Win2K under MSVC 6, so it's commented
-        # out.  The difference is that t.ctime() produces " 2" for the day,
-        # but platform ctime() produces "02" for the day.  According to
-        # C99, t.ctime() is correct here.
-        # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
-
-        # So test a case where that difference doesn't matter.
-        t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
-        self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
-
-    def test_tz_independent_comparing(self):
-        dt1 = self.theclass(2002, 3, 1, 9, 0, 0)
-        dt2 = self.theclass(2002, 3, 1, 10, 0, 0)
-        dt3 = self.theclass(2002, 3, 1, 9, 0, 0)
-        self.assertEqual(dt1, dt3)
-        self.assertTrue(dt2 > dt3)
-
-        # Make sure comparison doesn't forget microseconds, and isn't done
-        # via comparing a float timestamp (an IEEE double doesn't have enough
-        # precision to span microsecond resolution across years 1 thru 9999,
-        # so comparing via timestamp necessarily calls some distinct values
-        # equal).
-        dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998)
-        us = timedelta(microseconds=1)
-        dt2 = dt1 + us
-        self.assertEqual(dt2 - dt1, us)
-        self.assertTrue(dt1 < dt2)
-
-    def test_strftime_with_bad_tzname_replace(self):
-        # verify ok if tzinfo.tzname().replace() returns a non-string
-        class MyTzInfo(FixedOffset):
-            def tzname(self, dt):
-                class MyStr(str):
-                    def replace(self, *args):
-                        return None
-                return MyStr('name')
-        t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
-        self.assertRaises(TypeError, t.strftime, '%Z')
-
-    def test_bad_constructor_arguments(self):
-        # bad years
-        self.theclass(MINYEAR, 1, 1)  # no exception
-        self.theclass(MAXYEAR, 1, 1)  # no exception
-        self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
-        self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
-        # bad months
-        self.theclass(2000, 1, 1)    # no exception
-        self.theclass(2000, 12, 1)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
-        self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
-        # bad days
-        self.theclass(2000, 2, 29)   # no exception
-        self.theclass(2004, 2, 29)   # no exception
-        self.theclass(2400, 2, 29)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
-        self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
-        self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
-        self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
-        # bad hours
-        self.theclass(2000, 1, 31, 0)    # no exception
-        self.theclass(2000, 1, 31, 23)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24)
-        # bad minutes
-        self.theclass(2000, 1, 31, 23, 0)    # no exception
-        self.theclass(2000, 1, 31, 23, 59)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60)
-        # bad seconds
-        self.theclass(2000, 1, 31, 23, 59, 0)    # no exception
-        self.theclass(2000, 1, 31, 23, 59, 59)   # no exception
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1)
-        self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60)
-        # bad microseconds
-        self.theclass(2000, 1, 31, 23, 59, 59, 0)    # no exception
-        self.theclass(2000, 1, 31, 23, 59, 59, 999999)   # no exception
-        self.assertRaises(ValueError, self.theclass,
-                          2000, 1, 31, 23, 59, 59, -1)
-        self.assertRaises(ValueError, self.theclass,
-                          2000, 1, 31, 23, 59, 59,
-                          1000000)
-
-    def test_hash_equality(self):
-        d = self.theclass(2000, 12, 31, 23, 30, 17)
-        e = self.theclass(2000, 12, 31, 23, 30, 17)
-        self.assertEqual(d, e)
-        self.assertEqual(hash(d), hash(e))
-
-        dic = {d: 1}
-        dic[e] = 2
-        self.assertEqual(len(dic), 1)
-        self.assertEqual(dic[d], 2)
-        self.assertEqual(dic[e], 2)
-
-        d = self.theclass(2001,  1,  1,  0,  5, 17)
-        e = self.theclass(2001,  1,  1,  0,  5, 17)
-        self.assertEqual(d, e)
-        self.assertEqual(hash(d), hash(e))
-
-        dic = {d: 1}
-        dic[e] = 2
-        self.assertEqual(len(dic), 1)
-        self.assertEqual(dic[d], 2)
-        self.assertEqual(dic[e], 2)
-
-    def test_computations(self):
-        a = self.theclass(2002, 1, 31)
-        b = self.theclass(1956, 1, 31)
-        diff = a-b
-        self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
-        self.assertEqual(diff.seconds, 0)
-        self.assertEqual(diff.microseconds, 0)
-        a = self.theclass(2002, 3, 2, 17, 6)
-        millisec = timedelta(0, 0, 1000)
-        hour = timedelta(0, 3600)
-        day = timedelta(1)
-        week = timedelta(7)
-        self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
-        self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
-        self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
-        self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
-        self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
-        self.assertEqual(a - hour, a + -hour)
-        self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
-        self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
-        self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
-        self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
-        self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
-        self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
-        self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
-        self.assertEqual((a + week) - a, week)
-        self.assertEqual((a + day) - a, day)
-        self.assertEqual((a + hour) - a, hour)
-        self.assertEqual((a + millisec) - a, millisec)
-        self.assertEqual((a - week) - a, -week)
-        self.assertEqual((a - day) - a, -day)
-        self.assertEqual((a - hour) - a, -hour)
-        self.assertEqual((a - millisec) - a, -millisec)
-        self.assertEqual(a - (a + week), -week)
-        self.assertEqual(a - (a + day), -day)
-        self.assertEqual(a - (a + hour), -hour)
-        self.assertEqual(a - (a + millisec), -millisec)
-        self.assertEqual(a - (a - week), week)
-        self.assertEqual(a - (a - day), day)
-        self.assertEqual(a - (a - hour), hour)
-        self.assertEqual(a - (a - millisec), millisec)
-        self.assertEqual(a + (week + day + hour + millisec),
-                         self.theclass(2002, 3, 10, 18, 6, 0, 1000))
-        self.assertEqual(a + (week + day + hour + millisec),
-                         (((a + week) + day) + hour) + millisec)
-        self.assertEqual(a - (week + day + hour + millisec),
-                         self.theclass(2002, 2, 22, 16, 5, 59, 999000))
-        self.assertEqual(a - (week + day + hour + millisec),
-                         (((a - week) - day) - hour) - millisec)
-        # Add/sub ints or floats should be illegal
-        for i in 1, 1.0:
-            self.assertRaises(TypeError, lambda: a+i)
-            self.assertRaises(TypeError, lambda: a-i)
-            self.assertRaises(TypeError, lambda: i+a)
-            self.assertRaises(TypeError, lambda: i-a)
-
-        # delta - datetime is senseless.
-        self.assertRaises(TypeError, lambda: day - a)
-        # mixing datetime and (delta or datetime) via * or // is senseless
-        self.assertRaises(TypeError, lambda: day * a)
-        self.assertRaises(TypeError, lambda: a * day)
-        self.assertRaises(TypeError, lambda: day // a)
-        self.assertRaises(TypeError, lambda: a // day)
-        self.assertRaises(TypeError, lambda: a * a)
-        self.assertRaises(TypeError, lambda: a // a)
-        # datetime + datetime is senseless
-        self.assertRaises(TypeError, lambda: a + a)
-
-    def test_pickling(self):
-        args = 6, 7, 23, 20, 59, 1, 64**2
-        orig = self.theclass(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_more_pickling(self):
-        a = self.theclass(2003, 2, 7, 16, 48, 37, 444116)
-        s = pickle.dumps(a)
-        b = pickle.loads(s)
-        self.assertEqual(b.year, 2003)
-        self.assertEqual(b.month, 2)
-        self.assertEqual(b.day, 7)
-
-    def test_pickling_subclass_datetime(self):
-        args = 6, 7, 23, 20, 59, 1, 64**2
-        orig = SubclassDatetime(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_more_compare(self):
-        # The test_compare() inherited from TestDate covers the error cases.
-        # We just want to test lexicographic ordering on the members datetime
-        # has that date lacks.
-        args = [2000, 11, 29, 20, 58, 16, 999998]
-        t1 = self.theclass(*args)
-        t2 = self.theclass(*args)
-        self.assertEqual(t1, t2)
-        self.assertTrue(t1 <= t2)
-        self.assertTrue(t1 >= t2)
-        self.assertTrue(not t1 != t2)
-        self.assertTrue(not t1 < t2)
-        self.assertTrue(not t1 > t2)
-
-        for i in range(len(args)):
-            newargs = args[:]
-            newargs[i] = args[i] + 1
-            t2 = self.theclass(*newargs)   # this is larger than t1
-            self.assertTrue(t1 < t2)
-            self.assertTrue(t2 > t1)
-            self.assertTrue(t1 <= t2)
-            self.assertTrue(t2 >= t1)
-            self.assertTrue(t1 != t2)
-            self.assertTrue(t2 != t1)
-            self.assertTrue(not t1 == t2)
-            self.assertTrue(not t2 == t1)
-            self.assertTrue(not t1 > t2)
-            self.assertTrue(not t2 < t1)
-            self.assertTrue(not t1 >= t2)
-            self.assertTrue(not t2 <= t1)
-
-
-    # A helper for timestamp constructor tests.
-    def verify_field_equality(self, expected, got):
-        self.assertEqual(expected.tm_year, got.year)
-        self.assertEqual(expected.tm_mon, got.month)
-        self.assertEqual(expected.tm_mday, got.day)
-        self.assertEqual(expected.tm_hour, got.hour)
-        self.assertEqual(expected.tm_min, got.minute)
-        self.assertEqual(expected.tm_sec, got.second)
-
-    def test_fromtimestamp(self):
-        import time
-
-        ts = time.time()
-        expected = time.localtime(ts)
-        got = self.theclass.fromtimestamp(ts)
-        self.verify_field_equality(expected, got)
-
-    def test_utcfromtimestamp(self):
-        import time
-
-        ts = time.time()
-        expected = time.gmtime(ts)
-        got = self.theclass.utcfromtimestamp(ts)
-        self.verify_field_equality(expected, got)
-
-    def test_microsecond_rounding(self):
-        # Test whether fromtimestamp "rounds up" floats that are less
-        # than one microsecond smaller than an integer.
-        self.assertEqual(self.theclass.fromtimestamp(0.9999999),
-                         self.theclass.fromtimestamp(1))
-
-    def test_insane_fromtimestamp(self):
-        # It's possible that some platform maps time_t to double,
-        # and that this test will fail there.  This test should
-        # exempt such platforms (provided they return reasonable
-        # results!).
-        for insane in -1e200, 1e200:
-            self.assertRaises(ValueError, self.theclass.fromtimestamp,
-                              insane)
-
-    def test_insane_utcfromtimestamp(self):
-        # It's possible that some platform maps time_t to double,
-        # and that this test will fail there.  This test should
-        # exempt such platforms (provided they return reasonable
-        # results!).
-        for insane in -1e200, 1e200:
-            self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
-                              insane)
-    @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
-    def test_negative_float_fromtimestamp(self):
-        # The result is tz-dependent; at least test that this doesn't
-        # fail (like it did before bug 1646728 was fixed).
-        self.theclass.fromtimestamp(-1.05)
-
-    @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
-    def test_negative_float_utcfromtimestamp(self):
-        d = self.theclass.utcfromtimestamp(-1.05)
-        self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
-
-    def test_utcnow(self):
-        import time
-
-        # Call it a success if utcnow() and utcfromtimestamp() are within
-        # a second of each other.
-        tolerance = timedelta(seconds=1)
-        for dummy in range(3):
-            from_now = self.theclass.utcnow()
-            from_timestamp = self.theclass.utcfromtimestamp(time.time())
-            if abs(from_timestamp - from_now) <= tolerance:
-                break
-            # Else try again a few times.
-        self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
-
-    def test_strptime(self):
-        import _strptime
-
-        string = '2004-12-01 13:02:47.197'
-        format = '%Y-%m-%d %H:%M:%S.%f'
-        expected = _strptime._strptime_datetime(self.theclass, string, format)
-        got = self.theclass.strptime(string, format)
-        self.assertEqual(expected, got)
-        self.assertIs(type(expected), self.theclass)
-        self.assertIs(type(got), self.theclass)
-
-        strptime = self.theclass.strptime
-        self.assertEqual(strptime("+0002", "%z").utcoffset(), 2 * MINUTE)
-        self.assertEqual(strptime("-0002", "%z").utcoffset(), -2 * MINUTE)
-        # Only local timezone and UTC are supported
-        for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'),
-                                 (-_time.timezone, _time.tzname[0])):
-            if tzseconds < 0:
-                sign = '-'
-                seconds = -tzseconds
-            else:
-                sign ='+'
-                seconds = tzseconds
-            hours, minutes = divmod(seconds//60, 60)
-            dtstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname)
-            dt = strptime(dtstr, "%z %Z")
-            self.assertEqual(dt.utcoffset(), timedelta(seconds=tzseconds))
-            self.assertEqual(dt.tzname(), tzname)
-        # Can produce inconsistent datetime
-        dtstr, fmt = "+1234 UTC", "%z %Z"
-        dt = strptime(dtstr, fmt)
-        self.assertEqual(dt.utcoffset(), 12 * HOUR + 34 * MINUTE)
-        self.assertEqual(dt.tzname(), 'UTC')
-        # yet will roundtrip
-        self.assertEqual(dt.strftime(fmt), dtstr)
-
-        # Produce naive datetime if no %z is provided
-        self.assertEqual(strptime("UTC", "%Z").tzinfo, None)
-
-        with self.assertRaises(ValueError): strptime("-2400", "%z")
-        with self.assertRaises(ValueError): strptime("-000", "%z")
-
-    def test_more_timetuple(self):
-        # This tests fields beyond those tested by the TestDate.test_timetuple.
-        t = self.theclass(2004, 12, 31, 6, 22, 33)
-        self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1))
-        self.assertEqual(t.timetuple(),
-                         (t.year, t.month, t.day,
-                          t.hour, t.minute, t.second,
-                          t.weekday(),
-                          t.toordinal() - date(t.year, 1, 1).toordinal() + 1,
-                          -1))
-        tt = t.timetuple()
-        self.assertEqual(tt.tm_year, t.year)
-        self.assertEqual(tt.tm_mon, t.month)
-        self.assertEqual(tt.tm_mday, t.day)
-        self.assertEqual(tt.tm_hour, t.hour)
-        self.assertEqual(tt.tm_min, t.minute)
-        self.assertEqual(tt.tm_sec, t.second)
-        self.assertEqual(tt.tm_wday, t.weekday())
-        self.assertEqual(tt.tm_yday, t.toordinal() -
-                                     date(t.year, 1, 1).toordinal() + 1)
-        self.assertEqual(tt.tm_isdst, -1)
-
-    def test_more_strftime(self):
-        # This tests fields beyond those tested by the TestDate.test_strftime.
-        t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
-        self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"),
-                                    "12 31 04 000047 33 22 06 366")
-
-    def test_extract(self):
-        dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
-        self.assertEqual(dt.date(), date(2002, 3, 4))
-        self.assertEqual(dt.time(), time(18, 45, 3, 1234))
-
-    def test_combine(self):
-        d = date(2002, 3, 4)
-        t = time(18, 45, 3, 1234)
-        expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
-        combine = self.theclass.combine
-        dt = combine(d, t)
-        self.assertEqual(dt, expected)
-
-        dt = combine(time=t, date=d)
-        self.assertEqual(dt, expected)
-
-        self.assertEqual(d, dt.date())
-        self.assertEqual(t, dt.time())
-        self.assertEqual(dt, combine(dt.date(), dt.time()))
-
-        self.assertRaises(TypeError, combine) # need an arg
-        self.assertRaises(TypeError, combine, d) # need two args
-        self.assertRaises(TypeError, combine, t, d) # args reversed
-        self.assertRaises(TypeError, combine, d, t, 1) # too many args
-        self.assertRaises(TypeError, combine, "date", "time") # wrong types
-        self.assertRaises(TypeError, combine, d, "time") # wrong type
-        self.assertRaises(TypeError, combine, "date", t) # wrong type
-
-    def test_replace(self):
-        cls = self.theclass
-        args = [1, 2, 3, 4, 5, 6, 7]
-        base = cls(*args)
-        self.assertEqual(base, base.replace())
-
-        i = 0
-        for name, newval in (("year", 2),
-                             ("month", 3),
-                             ("day", 4),
-                             ("hour", 5),
-                             ("minute", 6),
-                             ("second", 7),
-                             ("microsecond", 8)):
-            newargs = args[:]
-            newargs[i] = newval
-            expected = cls(*newargs)
-            got = base.replace(**{name: newval})
-            self.assertEqual(expected, got)
-            i += 1
-
-        # Out of bounds.
-        base = cls(2000, 2, 29)
-        self.assertRaises(ValueError, base.replace, year=2001)
-
-    def test_astimezone(self):
-        # Pretty boring!  The TZ test is more interesting here.  astimezone()
-        # simply can't be applied to a naive object.
-        dt = self.theclass.now()
-        f = FixedOffset(44, "")
-        self.assertRaises(TypeError, dt.astimezone) # not enough args
-        self.assertRaises(TypeError, dt.astimezone, f, f) # too many args
-        self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type
-        self.assertRaises(ValueError, dt.astimezone, f) # naive
-        self.assertRaises(ValueError, dt.astimezone, tz=f)  # naive
-
-        class Bogus(tzinfo):
-            def utcoffset(self, dt): return None
-            def dst(self, dt): return timedelta(0)
-        bog = Bogus()
-        self.assertRaises(ValueError, dt.astimezone, bog)   # naive
-        self.assertRaises(ValueError,
-                          dt.replace(tzinfo=bog).astimezone, f)
-
-        class AlsoBogus(tzinfo):
-            def utcoffset(self, dt): return timedelta(0)
-            def dst(self, dt): return None
-        alsobog = AlsoBogus()
-        self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
-
-    def test_subclass_datetime(self):
-
-        class C(self.theclass):
-            theAnswer = 42
-
-            def __new__(cls, *args, **kws):
-                temp = kws.copy()
-                extra = temp.pop('extra')
-                result = self.theclass.__new__(cls, *args, **temp)
-                result.extra = extra
-                return result
-
-            def newmeth(self, start):
-                return start + self.year + self.month + self.second
-
-        args = 2003, 4, 14, 12, 13, 41
-
-        dt1 = self.theclass(*args)
-        dt2 = C(*args, **{'extra': 7})
-
-        self.assertEqual(dt2.__class__, C)
-        self.assertEqual(dt2.theAnswer, 42)
-        self.assertEqual(dt2.extra, 7)
-        self.assertEqual(dt1.toordinal(), dt2.toordinal())
-        self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month +
-                                          dt1.second - 7)
-
-class TestSubclassDateTime(TestDateTime):
-    theclass = SubclassDatetime
-    # Override tests not designed for subclass
-    def test_roundtrip(self):
-        pass
-
-class SubclassTime(time):
-    sub_var = 1
-
-class TestTime(HarmlessMixedComparison, unittest.TestCase):
-
-    theclass = time
-
-    def test_basic_attributes(self):
-        t = self.theclass(12, 0)
-        self.assertEqual(t.hour, 12)
-        self.assertEqual(t.minute, 0)
-        self.assertEqual(t.second, 0)
-        self.assertEqual(t.microsecond, 0)
-
-    def test_basic_attributes_nonzero(self):
-        # Make sure all attributes are non-zero so bugs in
-        # bit-shifting access show up.
-        t = self.theclass(12, 59, 59, 8000)
-        self.assertEqual(t.hour, 12)
-        self.assertEqual(t.minute, 59)
-        self.assertEqual(t.second, 59)
-        self.assertEqual(t.microsecond, 8000)
-
-    def test_roundtrip(self):
-        t = self.theclass(1, 2, 3, 4)
-
-        # Verify t -> string -> time identity.
-        s = repr(t)
-        self.assertTrue(s.startswith('datetime.'))
-        s = s[9:]
-        t2 = eval(s)
-        self.assertEqual(t, t2)
-
-        # Verify identity via reconstructing from pieces.
-        t2 = self.theclass(t.hour, t.minute, t.second,
-                           t.microsecond)
-        self.assertEqual(t, t2)
-
-    def test_comparing(self):
-        args = [1, 2, 3, 4]
-        t1 = self.theclass(*args)
-        t2 = self.theclass(*args)
-        self.assertEqual(t1, t2)
-        self.assertTrue(t1 <= t2)
-        self.assertTrue(t1 >= t2)
-        self.assertTrue(not t1 != t2)
-        self.assertTrue(not t1 < t2)
-        self.assertTrue(not t1 > t2)
-
-        for i in range(len(args)):
-            newargs = args[:]
-            newargs[i] = args[i] + 1
-            t2 = self.theclass(*newargs)   # this is larger than t1
-            self.assertTrue(t1 < t2)
-            self.assertTrue(t2 > t1)
-            self.assertTrue(t1 <= t2)
-            self.assertTrue(t2 >= t1)
-            self.assertTrue(t1 != t2)
-            self.assertTrue(t2 != t1)
-            self.assertTrue(not t1 == t2)
-            self.assertTrue(not t2 == t1)
-            self.assertTrue(not t1 > t2)
-            self.assertTrue(not t2 < t1)
-            self.assertTrue(not t1 >= t2)
-            self.assertTrue(not t2 <= t1)
-
-        for badarg in OTHERSTUFF:
-            self.assertEqual(t1 == badarg, False)
-            self.assertEqual(t1 != badarg, True)
-            self.assertEqual(badarg == t1, False)
-            self.assertEqual(badarg != t1, True)
-
-            self.assertRaises(TypeError, lambda: t1 <= badarg)
-            self.assertRaises(TypeError, lambda: t1 < badarg)
-            self.assertRaises(TypeError, lambda: t1 > badarg)
-            self.assertRaises(TypeError, lambda: t1 >= badarg)
-            self.assertRaises(TypeError, lambda: badarg <= t1)
-            self.assertRaises(TypeError, lambda: badarg < t1)
-            self.assertRaises(TypeError, lambda: badarg > t1)
-            self.assertRaises(TypeError, lambda: badarg >= t1)
-
-    def test_bad_constructor_arguments(self):
-        # bad hours
-        self.theclass(0, 0)    # no exception
-        self.theclass(23, 0)   # no exception
-        self.assertRaises(ValueError, self.theclass, -1, 0)
-        self.assertRaises(ValueError, self.theclass, 24, 0)
-        # bad minutes
-        self.theclass(23, 0)    # no exception
-        self.theclass(23, 59)   # no exception
-        self.assertRaises(ValueError, self.theclass, 23, -1)
-        self.assertRaises(ValueError, self.theclass, 23, 60)
-        # bad seconds
-        self.theclass(23, 59, 0)    # no exception
-        self.theclass(23, 59, 59)   # no exception
-        self.assertRaises(ValueError, self.theclass, 23, 59, -1)
-        self.assertRaises(ValueError, self.theclass, 23, 59, 60)
-        # bad microseconds
-        self.theclass(23, 59, 59, 0)        # no exception
-        self.theclass(23, 59, 59, 999999)   # no exception
-        self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1)
-        self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000)
-
-    def test_hash_equality(self):
-        d = self.theclass(23, 30, 17)
-        e = self.theclass(23, 30, 17)
-        self.assertEqual(d, e)
-        self.assertEqual(hash(d), hash(e))
-
-        dic = {d: 1}
-        dic[e] = 2
-        self.assertEqual(len(dic), 1)
-        self.assertEqual(dic[d], 2)
-        self.assertEqual(dic[e], 2)
-
-        d = self.theclass(0,  5, 17)
-        e = self.theclass(0,  5, 17)
-        self.assertEqual(d, e)
-        self.assertEqual(hash(d), hash(e))
-
-        dic = {d: 1}
-        dic[e] = 2
-        self.assertEqual(len(dic), 1)
-        self.assertEqual(dic[d], 2)
-        self.assertEqual(dic[e], 2)
-
-    def test_isoformat(self):
-        t = self.theclass(4, 5, 1, 123)
-        self.assertEqual(t.isoformat(), "04:05:01.000123")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass()
-        self.assertEqual(t.isoformat(), "00:00:00")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass(microsecond=1)
-        self.assertEqual(t.isoformat(), "00:00:00.000001")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass(microsecond=10)
-        self.assertEqual(t.isoformat(), "00:00:00.000010")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass(microsecond=100)
-        self.assertEqual(t.isoformat(), "00:00:00.000100")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass(microsecond=1000)
-        self.assertEqual(t.isoformat(), "00:00:00.001000")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass(microsecond=10000)
-        self.assertEqual(t.isoformat(), "00:00:00.010000")
-        self.assertEqual(t.isoformat(), str(t))
-
-        t = self.theclass(microsecond=100000)
-        self.assertEqual(t.isoformat(), "00:00:00.100000")
-        self.assertEqual(t.isoformat(), str(t))
-
-    def test_1653736(self):
-        # verify it doesn't accept extra keyword arguments
-        t = self.theclass(second=1)
-        self.assertRaises(TypeError, t.isoformat, foo=3)
-
-    def test_strftime(self):
-        t = self.theclass(1, 2, 3, 4)
-        self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004")
-        # A naive object replaces %z and %Z with empty strings.
-        self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
-
-    def test_format(self):
-        t = self.theclass(1, 2, 3, 4)
-        self.assertEqual(t.__format__(''), str(t))
-
-        # check that a derived class's __str__() gets called
-        class A(self.theclass):
-            def __str__(self):
-                return 'A'
-        a = A(1, 2, 3, 4)
-        self.assertEqual(a.__format__(''), 'A')
-
-        # check that a derived class's strftime gets called
-        class B(self.theclass):
-            def strftime(self, format_spec):
-                return 'B'
-        b = B(1, 2, 3, 4)
-        self.assertEqual(b.__format__(''), str(t))
-
-        for fmt in ['%H %M %S',
-                    ]:
-            self.assertEqual(t.__format__(fmt), t.strftime(fmt))
-            self.assertEqual(a.__format__(fmt), t.strftime(fmt))
-            self.assertEqual(b.__format__(fmt), 'B')
-
-    def test_str(self):
-        self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004")
-        self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000")
-        self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000")
-        self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03")
-        self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00")
-
-    def test_repr(self):
-        name = 'datetime.' + self.theclass.__name__
-        self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
-                         "%s(1, 2, 3, 4)" % name)
-        self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
-                         "%s(10, 2, 3, 4000)" % name)
-        self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
-                         "%s(0, 2, 3, 400000)" % name)
-        self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
-                         "%s(12, 2, 3)" % name)
-        self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
-                         "%s(23, 15)" % name)
-
-    def test_resolution_info(self):
-        self.assertIsInstance(self.theclass.min, self.theclass)
-        self.assertIsInstance(self.theclass.max, self.theclass)
-        self.assertIsInstance(self.theclass.resolution, timedelta)
-        self.assertTrue(self.theclass.max > self.theclass.min)
-
-    def test_pickling(self):
-        args = 20, 59, 16, 64**2
-        orig = self.theclass(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_pickling_subclass_time(self):
-        args = 20, 59, 16, 64**2
-        orig = SubclassTime(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-    def test_bool(self):
-        cls = self.theclass
-        self.assertTrue(cls(1))
-        self.assertTrue(cls(0, 1))
-        self.assertTrue(cls(0, 0, 1))
-        self.assertTrue(cls(0, 0, 0, 1))
-        self.assertTrue(not cls(0))
-        self.assertTrue(not cls())
-
-    def test_replace(self):
-        cls = self.theclass
-        args = [1, 2, 3, 4]
-        base = cls(*args)
-        self.assertEqual(base, base.replace())
-
-        i = 0
-        for name, newval in (("hour", 5),
-                             ("minute", 6),
-                             ("second", 7),
-                             ("microsecond", 8)):
-            newargs = args[:]
-            newargs[i] = newval
-            expected = cls(*newargs)
-            got = base.replace(**{name: newval})
-            self.assertEqual(expected, got)
-            i += 1
-
-        # Out of bounds.
-        base = cls(1)
-        self.assertRaises(ValueError, base.replace, hour=24)
-        self.assertRaises(ValueError, base.replace, minute=-1)
-        self.assertRaises(ValueError, base.replace, second=100)
-        self.assertRaises(ValueError, base.replace, microsecond=1000000)
-
-    def test_subclass_time(self):
-
-        class C(self.theclass):
-            theAnswer = 42
-
-            def __new__(cls, *args, **kws):
-                temp = kws.copy()
-                extra = temp.pop('extra')
-                result = self.theclass.__new__(cls, *args, **temp)
-                result.extra = extra
-                return result
-
-            def newmeth(self, start):
-                return start + self.hour + self.second
-
-        args = 4, 5, 6
-
-        dt1 = self.theclass(*args)
-        dt2 = C(*args, **{'extra': 7})
-
-        self.assertEqual(dt2.__class__, C)
-        self.assertEqual(dt2.theAnswer, 42)
-        self.assertEqual(dt2.extra, 7)
-        self.assertEqual(dt1.isoformat(), dt2.isoformat())
-        self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
-
-    def test_backdoor_resistance(self):
-        # see TestDate.test_backdoor_resistance().
-        base = '2:59.0'
-        for hour_byte in ' ', '9', chr(24), '\xff':
-            self.assertRaises(TypeError, self.theclass,
-                                         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)
-# must be legit (which is true for time and datetime).
-class TZInfoBase:
-
-    def test_argument_passing(self):
-        cls = self.theclass
-        # A datetime passes itself on, a time passes None.
-        class introspective(tzinfo):
-            def tzname(self, dt):    return dt and "real" or "none"
-            def utcoffset(self, dt):
-                return timedelta(minutes = dt and 42 or -42)
-            dst = utcoffset
-
-        obj = cls(1, 2, 3, tzinfo=introspective())
-
-        expected = cls is time and "none" or "real"
-        self.assertEqual(obj.tzname(), expected)
-
-        expected = timedelta(minutes=(cls is time and -42 or 42))
-        self.assertEqual(obj.utcoffset(), expected)
-        self.assertEqual(obj.dst(), expected)
-
-    def test_bad_tzinfo_classes(self):
-        cls = self.theclass
-        self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12)
-
-        class NiceTry(object):
-            def __init__(self): pass
-            def utcoffset(self, dt): pass
-        self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry)
-
-        class BetterTry(tzinfo):
-            def __init__(self): pass
-            def utcoffset(self, dt): pass
-        b = BetterTry()
-        t = cls(1, 1, 1, tzinfo=b)
-        self.assertTrue(t.tzinfo is b)
-
-    def test_utc_offset_out_of_bounds(self):
-        class Edgy(tzinfo):
-            def __init__(self, offset):
-                self.offset = timedelta(minutes=offset)
-            def utcoffset(self, dt):
-                return self.offset
-
-        cls = self.theclass
-        for offset, legit in ((-1440, False),
-                              (-1439, True),
-                              (1439, True),
-                              (1440, False)):
-            if cls is time:
-                t = cls(1, 2, 3, tzinfo=Edgy(offset))
-            elif cls is datetime:
-                t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
-            else:
-                assert 0, "impossible"
-            if legit:
-                aofs = abs(offset)
-                h, m = divmod(aofs, 60)
-                tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
-                if isinstance(t, datetime):
-                    t = t.timetz()
-                self.assertEqual(str(t), "01:02:03" + tag)
-            else:
-                self.assertRaises(ValueError, str, t)
-
-    def test_tzinfo_classes(self):
-        cls = self.theclass
-        class C1(tzinfo):
-            def utcoffset(self, dt): return None
-            def dst(self, dt): return None
-            def tzname(self, dt): return None
-        for t in (cls(1, 1, 1),
-                  cls(1, 1, 1, tzinfo=None),
-                  cls(1, 1, 1, tzinfo=C1())):
-            self.assertTrue(t.utcoffset() is None)
-            self.assertTrue(t.dst() is None)
-            self.assertTrue(t.tzname() is None)
-
-        class C3(tzinfo):
-            def utcoffset(self, dt): return timedelta(minutes=-1439)
-            def dst(self, dt): return timedelta(minutes=1439)
-            def tzname(self, dt): return "aname"
-        t = cls(1, 1, 1, tzinfo=C3())
-        self.assertEqual(t.utcoffset(), timedelta(minutes=-1439))
-        self.assertEqual(t.dst(), timedelta(minutes=1439))
-        self.assertEqual(t.tzname(), "aname")
-
-        # Wrong types.
-        class C4(tzinfo):
-            def utcoffset(self, dt): return "aname"
-            def dst(self, dt): return 7
-            def tzname(self, dt): return 0
-        t = cls(1, 1, 1, tzinfo=C4())
-        self.assertRaises(TypeError, t.utcoffset)
-        self.assertRaises(TypeError, t.dst)
-        self.assertRaises(TypeError, t.tzname)
-
-        # Offset out of range.
-        class C6(tzinfo):
-            def utcoffset(self, dt): return timedelta(hours=-24)
-            def dst(self, dt): return timedelta(hours=24)
-        t = cls(1, 1, 1, tzinfo=C6())
-        self.assertRaises(ValueError, t.utcoffset)
-        self.assertRaises(ValueError, t.dst)
-
-        # Not a whole number of minutes.
-        class C7(tzinfo):
-            def utcoffset(self, dt): return timedelta(seconds=61)
-            def dst(self, dt): return timedelta(microseconds=-81)
-        t = cls(1, 1, 1, tzinfo=C7())
-        self.assertRaises(ValueError, t.utcoffset)
-        self.assertRaises(ValueError, t.dst)
-
-    def test_aware_compare(self):
-        cls = self.theclass
-
-        # Ensure that utcoffset() gets ignored if the comparands have
-        # the same tzinfo member.
-        class OperandDependentOffset(tzinfo):
-            def utcoffset(self, t):
-                if t.minute < 10:
-                    # d0 and d1 equal after adjustment
-                    return timedelta(minutes=t.minute)
-                else:
-                    # d2 off in the weeds
-                    return timedelta(minutes=59)
-
-        base = cls(8, 9, 10, tzinfo=OperandDependentOffset())
-        d0 = base.replace(minute=3)
-        d1 = base.replace(minute=9)
-        d2 = base.replace(minute=11)
-        for x in d0, d1, d2:
-            for y in d0, d1, d2:
-                for op in lt, le, gt, ge, eq, ne:
-                    got = op(x, y)
-                    expected = op(x.minute, y.minute)
-                    self.assertEqual(got, expected)
-
-        # However, if they're different members, uctoffset is not ignored.
-        # Note that a time can't actually have an operand-depedent offset,
-        # though (and time.utcoffset() passes None to tzinfo.utcoffset()),
-        # so skip this test for time.
-        if cls is not time:
-            d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
-            d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
-            d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
-            for x in d0, d1, d2:
-                for y in d0, d1, d2:
-                    got = (x > y) - (x < y)
-                    if (x is d0 or x is d1) and (y is d0 or y is d1):
-                        expected = 0
-                    elif x is y is d2:
-                        expected = 0
-                    elif x is d2:
-                        expected = -1
-                    else:
-                        assert y is d2
-                        expected = 1
-                    self.assertEqual(got, expected)
-
-
-# Testing time objects with a non-None tzinfo.
-class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
-    theclass = time
-
-    def test_empty(self):
-        t = self.theclass()
-        self.assertEqual(t.hour, 0)
-        self.assertEqual(t.minute, 0)
-        self.assertEqual(t.second, 0)
-        self.assertEqual(t.microsecond, 0)
-        self.assertTrue(t.tzinfo is None)
-
-    def test_zones(self):
-        est = FixedOffset(-300, "EST", 1)
-        utc = FixedOffset(0, "UTC", -2)
-        met = FixedOffset(60, "MET", 3)
-        t1 = time( 7, 47, tzinfo=est)
-        t2 = time(12, 47, tzinfo=utc)
-        t3 = time(13, 47, tzinfo=met)
-        t4 = time(microsecond=40)
-        t5 = time(microsecond=40, tzinfo=utc)
-
-        self.assertEqual(t1.tzinfo, est)
-        self.assertEqual(t2.tzinfo, utc)
-        self.assertEqual(t3.tzinfo, met)
-        self.assertTrue(t4.tzinfo is None)
-        self.assertEqual(t5.tzinfo, utc)
-
-        self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
-        self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
-        self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
-        self.assertTrue(t4.utcoffset() is None)
-        self.assertRaises(TypeError, t1.utcoffset, "no args")
-
-        self.assertEqual(t1.tzname(), "EST")
-        self.assertEqual(t2.tzname(), "UTC")
-        self.assertEqual(t3.tzname(), "MET")
-        self.assertTrue(t4.tzname() is None)
-        self.assertRaises(TypeError, t1.tzname, "no args")
-
-        self.assertEqual(t1.dst(), timedelta(minutes=1))
-        self.assertEqual(t2.dst(), timedelta(minutes=-2))
-        self.assertEqual(t3.dst(), timedelta(minutes=3))
-        self.assertTrue(t4.dst() is None)
-        self.assertRaises(TypeError, t1.dst, "no args")
-
-        self.assertEqual(hash(t1), hash(t2))
-        self.assertEqual(hash(t1), hash(t3))
-        self.assertEqual(hash(t2), hash(t3))
-
-        self.assertEqual(t1, t2)
-        self.assertEqual(t1, t3)
-        self.assertEqual(t2, t3)
-        self.assertRaises(TypeError, lambda: t4 == t5) # mixed tz-aware & naive
-        self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive
-        self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive
-
-        self.assertEqual(str(t1), "07:47:00-05:00")
-        self.assertEqual(str(t2), "12:47:00+00:00")
-        self.assertEqual(str(t3), "13:47:00+01:00")
-        self.assertEqual(str(t4), "00:00:00.000040")
-        self.assertEqual(str(t5), "00:00:00.000040+00:00")
-
-        self.assertEqual(t1.isoformat(), "07:47:00-05:00")
-        self.assertEqual(t2.isoformat(), "12:47:00+00:00")
-        self.assertEqual(t3.isoformat(), "13:47:00+01:00")
-        self.assertEqual(t4.isoformat(), "00:00:00.000040")
-        self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00")
-
-        d = 'datetime.time'
-        self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)")
-        self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)")
-        self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)")
-        self.assertEqual(repr(t4), d + "(0, 0, 0, 40)")
-        self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)")
-
-        self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"),
-                                     "07:47:00 %Z=EST %z=-0500")
-        self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000")
-        self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100")
-
-        yuck = FixedOffset(-1439, "%z %Z %%z%%Z")
-        t1 = time(23, 59, tzinfo=yuck)
-        self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"),
-                                     "23:59 %Z='%z %Z %%z%%Z' %z='-2359'")
-
-        # Check that an invalid tzname result raises an exception.
-        class Badtzname(tzinfo):
-            def tzname(self, dt): return 42
-        t = time(2, 3, 4, tzinfo=Badtzname())
-        self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04")
-        self.assertRaises(TypeError, t.strftime, "%Z")
-
-    def test_hash_edge_cases(self):
-        # Offsets that overflow a basic time.
-        t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, ""))
-        t2 = self.theclass(0, 0, 2, 3, tzinfo=FixedOffset(1438, ""))
-        self.assertEqual(hash(t1), hash(t2))
-
-        t1 = self.theclass(23, 58, 6, 100, tzinfo=FixedOffset(-1000, ""))
-        t2 = self.theclass(23, 48, 6, 100, tzinfo=FixedOffset(-1010, ""))
-        self.assertEqual(hash(t1), hash(t2))
-
-    def test_pickling(self):
-        # Try one without a tzinfo.
-        args = 20, 59, 16, 64**2
-        orig = self.theclass(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-        # Try one with a tzinfo.
-        tinfo = PicklableFixedOffset(-300, 'cookie')
-        orig = self.theclass(5, 6, 7, tzinfo=tinfo)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-            self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
-            self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
-            self.assertEqual(derived.tzname(), 'cookie')
-
-    def test_more_bool(self):
-        # Test cases with non-None tzinfo.
-        cls = self.theclass
-
-        t = cls(0, tzinfo=FixedOffset(-300, ""))
-        self.assertTrue(t)
-
-        t = cls(5, tzinfo=FixedOffset(-300, ""))
-        self.assertTrue(t)
-
-        t = cls(5, tzinfo=FixedOffset(300, ""))
-        self.assertTrue(not t)
-
-        t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
-        self.assertTrue(not t)
-
-        # Mostly ensuring this doesn't overflow internally.
-        t = cls(0, tzinfo=FixedOffset(23*60 + 59, ""))
-        self.assertTrue(t)
-
-        # But this should yield a value error -- the utcoffset is bogus.
-        t = cls(0, tzinfo=FixedOffset(24*60, ""))
-        self.assertRaises(ValueError, lambda: bool(t))
-
-        # Likewise.
-        t = cls(0, tzinfo=FixedOffset(-24*60, ""))
-        self.assertRaises(ValueError, lambda: bool(t))
-
-    def test_replace(self):
-        cls = self.theclass
-        z100 = FixedOffset(100, "+100")
-        zm200 = FixedOffset(timedelta(minutes=-200), "-200")
-        args = [1, 2, 3, 4, z100]
-        base = cls(*args)
-        self.assertEqual(base, base.replace())
-
-        i = 0
-        for name, newval in (("hour", 5),
-                             ("minute", 6),
-                             ("second", 7),
-                             ("microsecond", 8),
-                             ("tzinfo", zm200)):
-            newargs = args[:]
-            newargs[i] = newval
-            expected = cls(*newargs)
-            got = base.replace(**{name: newval})
-            self.assertEqual(expected, got)
-            i += 1
-
-        # Ensure we can get rid of a tzinfo.
-        self.assertEqual(base.tzname(), "+100")
-        base2 = base.replace(tzinfo=None)
-        self.assertTrue(base2.tzinfo is None)
-        self.assertTrue(base2.tzname() is None)
-
-        # Ensure we can add one.
-        base3 = base2.replace(tzinfo=z100)
-        self.assertEqual(base, base3)
-        self.assertTrue(base.tzinfo is base3.tzinfo)
-
-        # Out of bounds.
-        base = cls(1)
-        self.assertRaises(ValueError, base.replace, hour=24)
-        self.assertRaises(ValueError, base.replace, minute=-1)
-        self.assertRaises(ValueError, base.replace, second=100)
-        self.assertRaises(ValueError, base.replace, microsecond=1000000)
-
-    def test_mixed_compare(self):
-        t1 = time(1, 2, 3)
-        t2 = time(1, 2, 3)
-        self.assertEqual(t1, t2)
-        t2 = t2.replace(tzinfo=None)
-        self.assertEqual(t1, t2)
-        t2 = t2.replace(tzinfo=FixedOffset(None, ""))
-        self.assertEqual(t1, t2)
-        t2 = t2.replace(tzinfo=FixedOffset(0, ""))
-        self.assertRaises(TypeError, lambda: t1 == t2)
-
-        # In time w/ identical tzinfo objects, utcoffset is ignored.
-        class Varies(tzinfo):
-            def __init__(self):
-                self.offset = timedelta(minutes=22)
-            def utcoffset(self, t):
-                self.offset += timedelta(minutes=1)
-                return self.offset
-
-        v = Varies()
-        t1 = t2.replace(tzinfo=v)
-        t2 = t2.replace(tzinfo=v)
-        self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
-        self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
-        self.assertEqual(t1, t2)
-
-        # But if they're not identical, it isn't ignored.
-        t2 = t2.replace(tzinfo=Varies())
-        self.assertTrue(t1 < t2)  # t1's offset counter still going up
-
-    def test_subclass_timetz(self):
-
-        class C(self.theclass):
-            theAnswer = 42
-
-            def __new__(cls, *args, **kws):
-                temp = kws.copy()
-                extra = temp.pop('extra')
-                result = self.theclass.__new__(cls, *args, **temp)
-                result.extra = extra
-                return result
-
-            def newmeth(self, start):
-                return start + self.hour + self.second
-
-        args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
-
-        dt1 = self.theclass(*args)
-        dt2 = C(*args, **{'extra': 7})
-
-        self.assertEqual(dt2.__class__, C)
-        self.assertEqual(dt2.theAnswer, 42)
-        self.assertEqual(dt2.extra, 7)
-        self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
-        self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
-
-
-# Testing datetime objects with a non-None tzinfo.
-
-class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
-    theclass = datetime
-
-    def test_trivial(self):
-        dt = self.theclass(1, 2, 3, 4, 5, 6, 7)
-        self.assertEqual(dt.year, 1)
-        self.assertEqual(dt.month, 2)
-        self.assertEqual(dt.day, 3)
-        self.assertEqual(dt.hour, 4)
-        self.assertEqual(dt.minute, 5)
-        self.assertEqual(dt.second, 6)
-        self.assertEqual(dt.microsecond, 7)
-        self.assertEqual(dt.tzinfo, None)
-
-    def test_even_more_compare(self):
-        # The test_compare() and test_more_compare() inherited from TestDate
-        # and TestDateTime covered non-tzinfo cases.
-
-        # Smallest possible after UTC adjustment.
-        t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
-        # Largest possible after UTC adjustment.
-        t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
-                           tzinfo=FixedOffset(-1439, ""))
-
-        # Make sure those compare correctly, and w/o overflow.
-        self.assertTrue(t1 < t2)
-        self.assertTrue(t1 != t2)
-        self.assertTrue(t2 > t1)
-
-        self.assertEqual(t1, t1)
-        self.assertEqual(t2, t2)
-
-        # Equal afer adjustment.
-        t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""))
-        t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, ""))
-        self.assertEqual(t1, t2)
-
-        # Change t1 not to subtract a minute, and t1 should be larger.
-        t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, ""))
-        self.assertTrue(t1 > t2)
-
-        # Change t1 to subtract 2 minutes, and t1 should be smaller.
-        t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, ""))
-        self.assertTrue(t1 < t2)
-
-        # Back to the original t1, but make seconds resolve it.
-        t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
-                           second=1)
-        self.assertTrue(t1 > t2)
-
-        # Likewise, but make microseconds resolve it.
-        t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
-                           microsecond=1)
-        self.assertTrue(t1 > t2)
-
-        # Make t2 naive and it should fail.
-        t2 = self.theclass.min
-        self.assertRaises(TypeError, lambda: t1 == t2)
-        self.assertEqual(t2, t2)
-
-        # It's also naive if it has tzinfo but tzinfo.utcoffset() is None.
-        class Naive(tzinfo):
-            def utcoffset(self, dt): return None
-        t2 = self.theclass(5, 6, 7, tzinfo=Naive())
-        self.assertRaises(TypeError, lambda: t1 == t2)
-        self.assertEqual(t2, t2)
-
-        # OTOH, it's OK to compare two of these mixing the two ways of being
-        # naive.
-        t1 = self.theclass(5, 6, 7)
-        self.assertEqual(t1, t2)
-
-        # Try a bogus uctoffset.
-        class Bogus(tzinfo):
-            def utcoffset(self, dt):
-                return timedelta(minutes=1440) # out of bounds
-        t1 = self.theclass(2, 2, 2, tzinfo=Bogus())
-        t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, ""))
-        self.assertRaises(ValueError, lambda: t1 == t2)
-
-    def test_pickling(self):
-        # Try one without a tzinfo.
-        args = 6, 7, 23, 20, 59, 1, 64**2
-        orig = self.theclass(*args)
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-
-        # Try one with a tzinfo.
-        tinfo = PicklableFixedOffset(-300, 'cookie')
-        orig = self.theclass(*args, **{'tzinfo': tinfo})
-        derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0))
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertEqual(orig, derived)
-            self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
-            self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
-            self.assertEqual(derived.tzname(), 'cookie')
-
-    def test_extreme_hashes(self):
-        # If an attempt is made to hash these via subtracting the offset
-        # then hashing a datetime object, OverflowError results.  The
-        # Python implementation used to blow up here.
-        t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
-        hash(t)
-        t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
-                          tzinfo=FixedOffset(-1439, ""))
-        hash(t)
-
-        # OTOH, an OOB offset should blow up.
-        t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
-        self.assertRaises(ValueError, hash, t)
-
-    def test_zones(self):
-        est = FixedOffset(-300, "EST")
-        utc = FixedOffset(0, "UTC")
-        met = FixedOffset(60, "MET")
-        t1 = datetime(2002, 3, 19,  7, 47, tzinfo=est)
-        t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
-        t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
-        self.assertEqual(t1.tzinfo, est)
-        self.assertEqual(t2.tzinfo, utc)
-        self.assertEqual(t3.tzinfo, met)
-        self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
-        self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
-        self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
-        self.assertEqual(t1.tzname(), "EST")
-        self.assertEqual(t2.tzname(), "UTC")
-        self.assertEqual(t3.tzname(), "MET")
-        self.assertEqual(hash(t1), hash(t2))
-        self.assertEqual(hash(t1), hash(t3))
-        self.assertEqual(hash(t2), hash(t3))
-        self.assertEqual(t1, t2)
-        self.assertEqual(t1, t3)
-        self.assertEqual(t2, t3)
-        self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
-        self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
-        self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
-        d = 'datetime.datetime(2002, 3, 19, '
-        self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
-        self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
-        self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)")
-
-    def test_combine(self):
-        met = FixedOffset(60, "MET")
-        d = date(2002, 3, 4)
-        tz = time(18, 45, 3, 1234, tzinfo=met)
-        dt = datetime.combine(d, tz)
-        self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234,
-                                        tzinfo=met))
-
-    def test_extract(self):
-        met = FixedOffset(60, "MET")
-        dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)
-        self.assertEqual(dt.date(), date(2002, 3, 4))
-        self.assertEqual(dt.time(), time(18, 45, 3, 1234))
-        self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met))
-
-    def test_tz_aware_arithmetic(self):
-        import random
-
-        now = self.theclass.now()
-        tz55 = FixedOffset(-330, "west 5:30")
-        timeaware = now.time().replace(tzinfo=tz55)
-        nowaware = self.theclass.combine(now.date(), timeaware)
-        self.assertTrue(nowaware.tzinfo is tz55)
-        self.assertEqual(nowaware.timetz(), timeaware)
-
-        # Can't mix aware and non-aware.
-        self.assertRaises(TypeError, lambda: now - nowaware)
-        self.assertRaises(TypeError, lambda: nowaware - now)
-
-        # And adding datetime's doesn't make sense, aware or not.
-        self.assertRaises(TypeError, lambda: now + nowaware)
-        self.assertRaises(TypeError, lambda: nowaware + now)
-        self.assertRaises(TypeError, lambda: nowaware + nowaware)
-
-        # Subtracting should yield 0.
-        self.assertEqual(now - now, timedelta(0))
-        self.assertEqual(nowaware - nowaware, timedelta(0))
-
-        # Adding a delta should preserve tzinfo.
-        delta = timedelta(weeks=1, minutes=12, microseconds=5678)
-        nowawareplus = nowaware + delta
-        self.assertTrue(nowaware.tzinfo is tz55)
-        nowawareplus2 = delta + nowaware
-        self.assertTrue(nowawareplus2.tzinfo is tz55)
-        self.assertEqual(nowawareplus, nowawareplus2)
-
-        # that - delta should be what we started with, and that - what we
-        # started with should be delta.
-        diff = nowawareplus - delta
-        self.assertTrue(diff.tzinfo is tz55)
-        self.assertEqual(nowaware, diff)
-        self.assertRaises(TypeError, lambda: delta - nowawareplus)
-        self.assertEqual(nowawareplus - nowaware, delta)
-
-        # Make up a random timezone.
-        tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
-        # Attach it to nowawareplus.
-        nowawareplus = nowawareplus.replace(tzinfo=tzr)
-        self.assertTrue(nowawareplus.tzinfo is tzr)
-        # Make sure the difference takes the timezone adjustments into account.
-        got = nowaware - nowawareplus
-        # Expected:  (nowaware base - nowaware offset) -
-        #            (nowawareplus base - nowawareplus offset) =
-        #            (nowaware base - nowawareplus base) +
-        #            (nowawareplus offset - nowaware offset) =
-        #            -delta + nowawareplus offset - nowaware offset
-        expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
-        self.assertEqual(got, expected)
-
-        # Try max possible difference.
-        min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
-        max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
-                            tzinfo=FixedOffset(-1439, "max"))
-        maxdiff = max - min
-        self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
-                                  timedelta(minutes=2*1439))
-        # Different tzinfo, but the same offset
-        tza = timezone(HOUR, 'A')
-        tzb = timezone(HOUR, 'B')
-        delta = min.replace(tzinfo=tza) - max.replace(tzinfo=tzb)
-        self.assertEqual(delta, self.theclass.min - self.theclass.max)
-
-    def test_tzinfo_now(self):
-        meth = self.theclass.now
-        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
-        base = meth()
-        # Try with and without naming the keyword.
-        off42 = FixedOffset(42, "42")
-        another = meth(off42)
-        again = meth(tz=off42)
-        self.assertTrue(another.tzinfo is again.tzinfo)
-        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
-        # Bad argument with and w/o naming the keyword.
-        self.assertRaises(TypeError, meth, 16)
-        self.assertRaises(TypeError, meth, tzinfo=16)
-        # Bad keyword name.
-        self.assertRaises(TypeError, meth, tinfo=off42)
-        # Too many args.
-        self.assertRaises(TypeError, meth, off42, off42)
-
-        # We don't know which time zone we're in, and don't have a tzinfo
-        # class to represent it, so seeing whether a tz argument actually
-        # does a conversion is tricky.
-        utc = FixedOffset(0, "utc", 0)
-        for weirdtz in [FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0),
-                        timezone(timedelta(hours=15, minutes=58), "weirdtz"),]:
-            for dummy in range(3):
-                now = datetime.now(weirdtz)
-                self.assertTrue(now.tzinfo is weirdtz)
-                utcnow = datetime.utcnow().replace(tzinfo=utc)
-                now2 = utcnow.astimezone(weirdtz)
-                if abs(now - now2) < timedelta(seconds=30):
-                    break
-                # Else the code is broken, or more than 30 seconds passed between
-                # calls; assuming the latter, just try again.
-            else:
-                # Three strikes and we're out.
-                self.fail("utcnow(), now(tz), or astimezone() may be broken")
-
-    def test_tzinfo_fromtimestamp(self):
-        import time
-        meth = self.theclass.fromtimestamp
-        ts = time.time()
-        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
-        base = meth(ts)
-        # Try with and without naming the keyword.
-        off42 = FixedOffset(42, "42")
-        another = meth(ts, off42)
-        again = meth(ts, tz=off42)
-        self.assertTrue(another.tzinfo is again.tzinfo)
-        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
-        # Bad argument with and w/o naming the keyword.
-        self.assertRaises(TypeError, meth, ts, 16)
-        self.assertRaises(TypeError, meth, ts, tzinfo=16)
-        # Bad keyword name.
-        self.assertRaises(TypeError, meth, ts, tinfo=off42)
-        # Too many args.
-        self.assertRaises(TypeError, meth, ts, off42, off42)
-        # Too few args.
-        self.assertRaises(TypeError, meth)
-
-        # Try to make sure tz= actually does some conversion.
-        timestamp = 1000000000
-        utcdatetime = datetime.utcfromtimestamp(timestamp)
-        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
-        # But on some flavor of Mac, it's nowhere near that.  So we can't have
-        # any idea here what time that actually is, we can only test that
-        # relative changes match.
-        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
-        tz = FixedOffset(utcoffset, "tz", 0)
-        expected = utcdatetime + utcoffset
-        got = datetime.fromtimestamp(timestamp, tz)
-        self.assertEqual(expected, got.replace(tzinfo=None))
-
-    def test_tzinfo_utcnow(self):
-        meth = self.theclass.utcnow
-        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
-        base = meth()
-        # Try with and without naming the keyword; for whatever reason,
-        # utcnow() doesn't accept a tzinfo argument.
-        off42 = FixedOffset(42, "42")
-        self.assertRaises(TypeError, meth, off42)
-        self.assertRaises(TypeError, meth, tzinfo=off42)
-
-    def test_tzinfo_utcfromtimestamp(self):
-        import time
-        meth = self.theclass.utcfromtimestamp
-        ts = time.time()
-        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
-        base = meth(ts)
-        # Try with and without naming the keyword; for whatever reason,
-        # utcfromtimestamp() doesn't accept a tzinfo argument.
-        off42 = FixedOffset(42, "42")
-        self.assertRaises(TypeError, meth, ts, off42)
-        self.assertRaises(TypeError, meth, ts, tzinfo=off42)
-
-    def test_tzinfo_timetuple(self):
-        # TestDateTime tested most of this.  datetime adds a twist to the
-        # DST flag.
-        class DST(tzinfo):
-            def __init__(self, dstvalue):
-                if isinstance(dstvalue, int):
-                    dstvalue = timedelta(minutes=dstvalue)
-                self.dstvalue = dstvalue
-            def dst(self, dt):
-                return self.dstvalue
-
-        cls = self.theclass
-        for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
-            d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
-            t = d.timetuple()
-            self.assertEqual(1, t.tm_year)
-            self.assertEqual(1, t.tm_mon)
-            self.assertEqual(1, t.tm_mday)
-            self.assertEqual(10, t.tm_hour)
-            self.assertEqual(20, t.tm_min)
-            self.assertEqual(30, t.tm_sec)
-            self.assertEqual(0, t.tm_wday)
-            self.assertEqual(1, t.tm_yday)
-            self.assertEqual(flag, t.tm_isdst)
-
-        # dst() returns wrong type.
-        self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)
-
-        # dst() at the edge.
-        self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
-        self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)
-
-        # dst() out of range.
-        self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
-        self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple)
-
-    def test_utctimetuple(self):
-        class DST(tzinfo):
-            def __init__(self, dstvalue=0):
-                if isinstance(dstvalue, int):
-                    dstvalue = timedelta(minutes=dstvalue)
-                self.dstvalue = dstvalue
-            def dst(self, dt):
-                return self.dstvalue
-
-        cls = self.theclass
-        # This can't work:  DST didn't implement utcoffset.
-        self.assertRaises(NotImplementedError,
-                          cls(1, 1, 1, tzinfo=DST(0)).utcoffset)
-
-        class UOFS(DST):
-            def __init__(self, uofs, dofs=None):
-                DST.__init__(self, dofs)
-                self.uofs = timedelta(minutes=uofs)
-            def utcoffset(self, dt):
-                return self.uofs
-
-        for dstvalue in -33, 33, 0, None:
-            d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue))
-            t = d.utctimetuple()
-            self.assertEqual(d.year, t.tm_year)
-            self.assertEqual(d.month, t.tm_mon)
-            self.assertEqual(d.day, t.tm_mday)
-            self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm
-            self.assertEqual(13, t.tm_min)
-            self.assertEqual(d.second, t.tm_sec)
-            self.assertEqual(d.weekday(), t.tm_wday)
-            self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1,
-                             t.tm_yday)
-            # Ensure tm_isdst is 0 regardless of what dst() says: DST
-            # is never in effect for a UTC time.
-            self.assertEqual(0, t.tm_isdst)
-
-        # For naive datetime, utctimetuple == timetuple except for isdst
-        d = cls(1, 2, 3, 10, 20, 30, 40)
-        t = d.utctimetuple()
-        self.assertEqual(t[:-1], d.timetuple()[:-1])
-        self.assertEqual(0, t.tm_isdst)
-        # Same if utcoffset is None
-        class NOFS(DST):
-            def utcoffset(self, dt):
-                return None
-        d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=NOFS())
-        t = d.utctimetuple()
-        self.assertEqual(t[:-1], d.timetuple()[:-1])
-        self.assertEqual(0, t.tm_isdst)
-        # Check that bad tzinfo is detected
-        class BOFS(DST):
-            def utcoffset(self, dt):
-                return "EST"
-        d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=BOFS())
-        self.assertRaises(TypeError, d.utctimetuple)
-
-        # Check that utctimetuple() is the same as
-        # astimezone(utc).timetuple()
-        d = cls(2010, 11, 13, 14, 15, 16, 171819)
-        for tz in [timezone.min, timezone.utc, timezone.max]:
-            dtz = d.replace(tzinfo=tz)
-            self.assertEqual(dtz.utctimetuple()[:-1],
-                             dtz.astimezone(timezone.utc).timetuple()[:-1])
-        # At the edges, UTC adjustment can produce years out-of-range
-        # for a datetime object.  Ensure that an OverflowError is
-        # raised.
-        tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439))
-        # That goes back 1 minute less than a full day.
-        self.assertRaises(OverflowError, tiny.utctimetuple)
-
-        huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439))
-        # That goes forward 1 minute less than a full day.
-        self.assertRaises(OverflowError, huge.utctimetuple)
-        # More overflow cases
-        tiny = cls.min.replace(tzinfo=timezone(MINUTE))
-        self.assertRaises(OverflowError, tiny.utctimetuple)
-        huge = cls.max.replace(tzinfo=timezone(-MINUTE))
-        self.assertRaises(OverflowError, huge.utctimetuple)
-
-    def test_tzinfo_isoformat(self):
-        zero = FixedOffset(0, "+00:00")
-        plus = FixedOffset(220, "+03:40")
-        minus = FixedOffset(-231, "-03:51")
-        unknown = FixedOffset(None, "")
-
-        cls = self.theclass
-        datestr = '0001-02-03'
-        for ofs in None, zero, plus, minus, unknown:
-            for us in 0, 987001:
-                d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs)
-                timestr = '04:05:59' + (us and '.987001' or '')
-                ofsstr = ofs is not None and d.tzname() or ''
-                tailstr = timestr + ofsstr
-                iso = d.isoformat()
-                self.assertEqual(iso, datestr + 'T' + tailstr)
-                self.assertEqual(iso, d.isoformat('T'))
-                self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr)
-                self.assertEqual(d.isoformat('\u1234'), datestr + '\u1234' + tailstr)
-                self.assertEqual(str(d), datestr + ' ' + tailstr)
-
-    def test_replace(self):
-        cls = self.theclass
-        z100 = FixedOffset(100, "+100")
-        zm200 = FixedOffset(timedelta(minutes=-200), "-200")
-        args = [1, 2, 3, 4, 5, 6, 7, z100]
-        base = cls(*args)
-        self.assertEqual(base, base.replace())
-
-        i = 0
-        for name, newval in (("year", 2),
-                             ("month", 3),
-                             ("day", 4),
-                             ("hour", 5),
-                             ("minute", 6),
-                             ("second", 7),
-                             ("microsecond", 8),
-                             ("tzinfo", zm200)):
-            newargs = args[:]
-            newargs[i] = newval
-            expected = cls(*newargs)
-            got = base.replace(**{name: newval})
-            self.assertEqual(expected, got)
-            i += 1
-
-        # Ensure we can get rid of a tzinfo.
-        self.assertEqual(base.tzname(), "+100")
-        base2 = base.replace(tzinfo=None)
-        self.assertTrue(base2.tzinfo is None)
-        self.assertTrue(base2.tzname() is None)
-
-        # Ensure we can add one.
-        base3 = base2.replace(tzinfo=z100)
-        self.assertEqual(base, base3)
-        self.assertTrue(base.tzinfo is base3.tzinfo)
-
-        # Out of bounds.
-        base = cls(2000, 2, 29)
-        self.assertRaises(ValueError, base.replace, year=2001)
-
-    def test_more_astimezone(self):
-        # The inherited test_astimezone covered some trivial and error cases.
-        fnone = FixedOffset(None, "None")
-        f44m = FixedOffset(44, "44")
-        fm5h = FixedOffset(-timedelta(hours=5), "m300")
-
-        dt = self.theclass.now(tz=f44m)
-        self.assertTrue(dt.tzinfo is f44m)
-        # Replacing with degenerate tzinfo raises an exception.
-        self.assertRaises(ValueError, dt.astimezone, fnone)
-        # Ditto with None tz.
-        self.assertRaises(TypeError, dt.astimezone, None)
-        # Replacing with same tzinfo makes no change.
-        x = dt.astimezone(dt.tzinfo)
-        self.assertTrue(x.tzinfo is f44m)
-        self.assertEqual(x.date(), dt.date())
-        self.assertEqual(x.time(), dt.time())
-
-        # Replacing with different tzinfo does adjust.
-        got = dt.astimezone(fm5h)
-        self.assertTrue(got.tzinfo is fm5h)
-        self.assertEqual(got.utcoffset(), timedelta(hours=-5))
-        expected = dt - dt.utcoffset()  # in effect, convert to UTC
-        expected += fm5h.utcoffset(dt)  # and from there to local time
-        expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
-        self.assertEqual(got.date(), expected.date())
-        self.assertEqual(got.time(), expected.time())
-        self.assertEqual(got.timetz(), expected.timetz())
-        self.assertTrue(got.tzinfo is expected.tzinfo)
-        self.assertEqual(got, expected)
-
-    def test_aware_subtract(self):
-        cls = self.theclass
-
-        # Ensure that utcoffset() is ignored when the operands have the
-        # same tzinfo member.
-        class OperandDependentOffset(tzinfo):
-            def utcoffset(self, t):
-                if t.minute < 10:
-                    # d0 and d1 equal after adjustment
-                    return timedelta(minutes=t.minute)
-                else:
-                    # d2 off in the weeds
-                    return timedelta(minutes=59)
-
-        base = cls(8, 9, 10, 11, 12, 13, 14, tzinfo=OperandDependentOffset())
-        d0 = base.replace(minute=3)
-        d1 = base.replace(minute=9)
-        d2 = base.replace(minute=11)
-        for x in d0, d1, d2:
-            for y in d0, d1, d2:
-                got = x - y
-                expected = timedelta(minutes=x.minute - y.minute)
-                self.assertEqual(got, expected)
-
-        # OTOH, if the tzinfo members are distinct, utcoffsets aren't
-        # ignored.
-        base = cls(8, 9, 10, 11, 12, 13, 14)
-        d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
-        d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
-        d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
-        for x in d0, d1, d2:
-            for y in d0, d1, d2:
-                got = x - y
-                if (x is d0 or x is d1) and (y is d0 or y is d1):
-                    expected = timedelta(0)
-                elif x is y is d2:
-                    expected = timedelta(0)
-                elif x is d2:
-                    expected = timedelta(minutes=(11-59)-0)
-                else:
-                    assert y is d2
-                    expected = timedelta(minutes=0-(11-59))
-                self.assertEqual(got, expected)
-
-    def test_mixed_compare(self):
-        t1 = datetime(1, 2, 3, 4, 5, 6, 7)
-        t2 = datetime(1, 2, 3, 4, 5, 6, 7)
-        self.assertEqual(t1, t2)
-        t2 = t2.replace(tzinfo=None)
-        self.assertEqual(t1, t2)
-        t2 = t2.replace(tzinfo=FixedOffset(None, ""))
-        self.assertEqual(t1, t2)
-        t2 = t2.replace(tzinfo=FixedOffset(0, ""))
-        self.assertRaises(TypeError, lambda: t1 == t2)
-
-        # In datetime w/ identical tzinfo objects, utcoffset is ignored.
-        class Varies(tzinfo):
-            def __init__(self):
-                self.offset = timedelta(minutes=22)
-            def utcoffset(self, t):
-                self.offset += timedelta(minutes=1)
-                return self.offset
-
-        v = Varies()
-        t1 = t2.replace(tzinfo=v)
-        t2 = t2.replace(tzinfo=v)
-        self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
-        self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
-        self.assertEqual(t1, t2)
-
-        # But if they're not identical, it isn't ignored.
-        t2 = t2.replace(tzinfo=Varies())
-        self.assertTrue(t1 < t2)  # t1's offset counter still going up
-
-    def test_subclass_datetimetz(self):
-
-        class C(self.theclass):
-            theAnswer = 42
-
-            def __new__(cls, *args, **kws):
-                temp = kws.copy()
-                extra = temp.pop('extra')
-                result = self.theclass.__new__(cls, *args, **temp)
-                result.extra = extra
-                return result
-
-            def newmeth(self, start):
-                return start + self.hour + self.year
-
-        args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
-
-        dt1 = self.theclass(*args)
-        dt2 = C(*args, **{'extra': 7})
-
-        self.assertEqual(dt2.__class__, C)
-        self.assertEqual(dt2.theAnswer, 42)
-        self.assertEqual(dt2.extra, 7)
-        self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
-        self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7)
-
-# Pain to set up DST-aware tzinfo classes.
-
-def first_sunday_on_or_after(dt):
-    days_to_go = 6 - dt.weekday()
-    if days_to_go:
-        dt += timedelta(days_to_go)
-    return dt
-
-ZERO = timedelta(0)
-MINUTE = timedelta(minutes=1)
-HOUR = timedelta(hours=1)
-DAY = timedelta(days=1)
-# In the US, DST starts at 2am (standard time) on the first Sunday in April.
-DSTSTART = datetime(1, 4, 1, 2)
-# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct,
-# which is the first Sunday on or after Oct 25.  Because we view 1:MM as
-# being standard time on that day, there is no spelling in local time of
-# the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time).
-DSTEND = datetime(1, 10, 25, 1)
-
-class USTimeZone(tzinfo):
-
-    def __init__(self, hours, reprname, stdname, dstname):
-        self.stdoffset = timedelta(hours=hours)
-        self.reprname = reprname
-        self.stdname = stdname
-        self.dstname = dstname
-
-    def __repr__(self):
-        return self.reprname
-
-    def tzname(self, dt):
-        if self.dst(dt):
-            return self.dstname
-        else:
-            return self.stdname
-
-    def utcoffset(self, dt):
-        return self.stdoffset + self.dst(dt)
-
-    def dst(self, dt):
-        if dt is None or dt.tzinfo is None:
-            # An exception instead may be sensible here, in one or more of
-            # the cases.
-            return ZERO
-        assert dt.tzinfo is self
-
-        # Find first Sunday in April.
-        start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
-        assert start.weekday() == 6 and start.month == 4 and start.day <= 7
-
-        # Find last Sunday in October.
-        end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
-        assert end.weekday() == 6 and end.month == 10 and end.day >= 25
-
-        # Can't compare naive to aware objects, so strip the timezone from
-        # dt first.
-        if start <= dt.replace(tzinfo=None) < end:
-            return HOUR
-        else:
-            return ZERO
-
-Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
-Central  = USTimeZone(-6, "Central",  "CST", "CDT")
-Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
-Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")
-utc_real = FixedOffset(0, "UTC", 0)
-# For better test coverage, we want another flavor of UTC that's west of
-# the Eastern and Pacific timezones.
-utc_fake = FixedOffset(-12*60, "UTCfake", 0)
-
-class TestTimezoneConversions(unittest.TestCase):
-    # The DST switch times for 2002, in std time.
-    dston = datetime(2002, 4, 7, 2)
-    dstoff = datetime(2002, 10, 27, 1)
-
-    theclass = datetime
-
-    # Check a time that's inside DST.
-    def checkinside(self, dt, tz, utc, dston, dstoff):
-        self.assertEqual(dt.dst(), HOUR)
-
-        # Conversion to our own timezone is always an identity.
-        self.assertEqual(dt.astimezone(tz), dt)
-
-        asutc = dt.astimezone(utc)
-        there_and_back = asutc.astimezone(tz)
-
-        # Conversion to UTC and back isn't always an identity here,
-        # because there are redundant spellings (in local time) of
-        # UTC time when DST begins:  the clock jumps from 1:59:59
-        # to 3:00:00, and a local time of 2:MM:SS doesn't really
-        # make sense then.  The classes above treat 2:MM:SS as
-        # daylight time then (it's "after 2am"), really an alias
-        # for 1:MM:SS standard time.  The latter form is what
-        # conversion back from UTC produces.
-        if dt.date() == dston.date() and dt.hour == 2:
-            # We're in the redundant hour, and coming back from
-            # UTC gives the 1:MM:SS standard-time spelling.
-            self.assertEqual(there_and_back + HOUR, dt)
-            # Although during was considered to be in daylight
-            # time, there_and_back is not.
-            self.assertEqual(there_and_back.dst(), ZERO)
-            # They're the same times in UTC.
-            self.assertEqual(there_and_back.astimezone(utc),
-                             dt.astimezone(utc))
-        else:
-            # We're not in the redundant hour.
-            self.assertEqual(dt, there_and_back)
-
-        # Because we have a redundant spelling when DST begins, there is
-        # (unforunately) an hour when DST ends that can't be spelled at all in
-        # local time.  When DST ends, the clock jumps from 1:59 back to 1:00
-        # again.  The hour 1:MM DST has no spelling then:  1:MM is taken to be
-        # standard time.  1:MM DST == 0:MM EST, but 0:MM is taken to be
-        # daylight time.  The hour 1:MM daylight == 0:MM standard can't be
-        # expressed in local time.  Nevertheless, we want conversion back
-        # from UTC to mimic the local clock's "repeat an hour" behavior.
-        nexthour_utc = asutc + HOUR
-        nexthour_tz = nexthour_utc.astimezone(tz)
-        if dt.date() == dstoff.date() and dt.hour == 0:
-            # We're in the hour before the last DST hour.  The last DST hour
-            # is ineffable.  We want the conversion back to repeat 1:MM.
-            self.assertEqual(nexthour_tz, dt.replace(hour=1))
-            nexthour_utc += HOUR
-            nexthour_tz = nexthour_utc.astimezone(tz)
-            self.assertEqual(nexthour_tz, dt.replace(hour=1))
-        else:
-            self.assertEqual(nexthour_tz - dt, HOUR)
-
-    # Check a time that's outside DST.
-    def checkoutside(self, dt, tz, utc):
-        self.assertEqual(dt.dst(), ZERO)
-
-        # Conversion to our own timezone is always an identity.
-        self.assertEqual(dt.astimezone(tz), dt)
-
-        # Converting to UTC and back is an identity too.
-        asutc = dt.astimezone(utc)
-        there_and_back = asutc.astimezone(tz)
-        self.assertEqual(dt, there_and_back)
-
-    def convert_between_tz_and_utc(self, tz, utc):
-        dston = self.dston.replace(tzinfo=tz)
-        # Because 1:MM on the day DST ends is taken as being standard time,
-        # there is no spelling in tz for the last hour of daylight time.
-        # For purposes of the test, the last hour of DST is 0:MM, which is
-        # taken as being daylight time (and 1:MM is taken as being standard
-        # time).
-        dstoff = self.dstoff.replace(tzinfo=tz)
-        for delta in (timedelta(weeks=13),
-                      DAY,
-                      HOUR,
-                      timedelta(minutes=1),
-                      timedelta(microseconds=1)):
-
-            self.checkinside(dston, tz, utc, dston, dstoff)
-            for during in dston + delta, dstoff - delta:
-                self.checkinside(during, tz, utc, dston, dstoff)
-
-            self.checkoutside(dstoff, tz, utc)
-            for outside in dston - delta, dstoff + delta:
-                self.checkoutside(outside, tz, utc)
-
-    def test_easy(self):
-        # Despite the name of this test, the endcases are excruciating.
-        self.convert_between_tz_and_utc(Eastern, utc_real)
-        self.convert_between_tz_and_utc(Pacific, utc_real)
-        self.convert_between_tz_and_utc(Eastern, utc_fake)
-        self.convert_between_tz_and_utc(Pacific, utc_fake)
-        # The next is really dancing near the edge.  It works because
-        # Pacific and Eastern are far enough apart that their "problem
-        # hours" don't overlap.
-        self.convert_between_tz_and_utc(Eastern, Pacific)
-        self.convert_between_tz_and_utc(Pacific, Eastern)
-        # OTOH, these fail!  Don't enable them.  The difficulty is that
-        # the edge case tests assume that every hour is representable in
-        # the "utc" class.  This is always true for a fixed-offset tzinfo
-        # class (lke utc_real and utc_fake), but not for Eastern or Central.
-        # For these adjacent DST-aware time zones, the range of time offsets
-        # tested ends up creating hours in the one that aren't representable
-        # in the other.  For the same reason, we would see failures in the
-        # Eastern vs Pacific tests too if we added 3*HOUR to the list of
-        # offset deltas in convert_between_tz_and_utc().
-        #
-        # self.convert_between_tz_and_utc(Eastern, Central)  # can't work
-        # self.convert_between_tz_and_utc(Central, Eastern)  # can't work
-
-    def test_tricky(self):
-        # 22:00 on day before daylight starts.
-        fourback = self.dston - timedelta(hours=4)
-        ninewest = FixedOffset(-9*60, "-0900", 0)
-        fourback = fourback.replace(tzinfo=ninewest)
-        # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST.  Since it's "after
-        # 2", we should get the 3 spelling.
-        # If we plug 22:00 the day before into Eastern, it "looks like std
-        # time", so its offset is returned as -5, and -5 - -9 = 4.  Adding 4
-        # to 22:00 lands on 2:00, which makes no sense in local time (the
-        # local clock jumps from 1 to 3).  The point here is to make sure we
-        # get the 3 spelling.
-        expected = self.dston.replace(hour=3)
-        got = fourback.astimezone(Eastern).replace(tzinfo=None)
-        self.assertEqual(expected, got)
-
-        # Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST.  In that
-        # case we want the 1:00 spelling.
-        sixutc = self.dston.replace(hour=6, tzinfo=utc_real)
-        # Now 6:00 "looks like daylight", so the offset wrt Eastern is -4,
-        # and adding -4-0 == -4 gives the 2:00 spelling.  We want the 1:00 EST
-        # spelling.
-        expected = self.dston.replace(hour=1)
-        got = sixutc.astimezone(Eastern).replace(tzinfo=None)
-        self.assertEqual(expected, got)
-
-        # Now on the day DST ends, we want "repeat an hour" behavior.
-        #  UTC  4:MM  5:MM  6:MM  7:MM  checking these
-        #  EST 23:MM  0:MM  1:MM  2:MM
-        #  EDT  0:MM  1:MM  2:MM  3:MM
-        # wall  0:MM  1:MM  1:MM  2:MM  against these
-        for utc in utc_real, utc_fake:
-            for tz in Eastern, Pacific:
-                first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM
-                # Convert that to UTC.
-                first_std_hour -= tz.utcoffset(None)
-                # Adjust for possibly fake UTC.
-                asutc = first_std_hour + utc.utcoffset(None)
-                # First UTC hour to convert; this is 4:00 when utc=utc_real &
-                # tz=Eastern.
-                asutcbase = asutc.replace(tzinfo=utc)
-                for tzhour in (0, 1, 1, 2):
-                    expectedbase = self.dstoff.replace(hour=tzhour)
-                    for minute in 0, 30, 59:
-                        expected = expectedbase.replace(minute=minute)
-                        asutc = asutcbase.replace(minute=minute)
-                        astz = asutc.astimezone(tz)
-                        self.assertEqual(astz.replace(tzinfo=None), expected)
-                    asutcbase += HOUR
-
-
-    def test_bogus_dst(self):
-        class ok(tzinfo):
-            def utcoffset(self, dt): return HOUR
-            def dst(self, dt): return HOUR
-
-        now = self.theclass.now().replace(tzinfo=utc_real)
-        # Doesn't blow up.
-        now.astimezone(ok())
-
-        # Does blow up.
-        class notok(ok):
-            def dst(self, dt): return None
-        self.assertRaises(ValueError, now.astimezone, notok())
-
-        # Sometimes blow up. In the following, tzinfo.dst()
-        # implementation may return None or not None depending on
-        # whether DST is assumed to be in effect.  In this situation,
-        # a ValueError should be raised by astimezone().
-        class tricky_notok(ok):
-            def dst(self, dt):
-                if dt.year == 2000:
-                    return None
-                else:
-                    return 10*HOUR
-        dt = self.theclass(2001, 1, 1).replace(tzinfo=utc_real)
-        self.assertRaises(ValueError, dt.astimezone, tricky_notok())
-
-    def test_fromutc(self):
-        self.assertRaises(TypeError, Eastern.fromutc)   # not enough args
-        now = datetime.utcnow().replace(tzinfo=utc_real)
-        self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo
-        now = now.replace(tzinfo=Eastern)   # insert correct tzinfo
-        enow = Eastern.fromutc(now)         # doesn't blow up
-        self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member
-        self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args
-        self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type
-
-        # Always converts UTC to standard time.
-        class FauxUSTimeZone(USTimeZone):
-            def fromutc(self, dt):
-                return dt + self.stdoffset
-        FEastern  = FauxUSTimeZone(-5, "FEastern",  "FEST", "FEDT")
-
-        #  UTC  4:MM  5:MM  6:MM  7:MM  8:MM  9:MM
-        #  EST 23:MM  0:MM  1:MM  2:MM  3:MM  4:MM
-        #  EDT  0:MM  1:MM  2:MM  3:MM  4:MM  5:MM
-
-        # Check around DST start.
-        start = self.dston.replace(hour=4, tzinfo=Eastern)
-        fstart = start.replace(tzinfo=FEastern)
-        for wall in 23, 0, 1, 3, 4, 5:
-            expected = start.replace(hour=wall)
-            if wall == 23:
-                expected -= timedelta(days=1)
-            got = Eastern.fromutc(start)
-            self.assertEqual(expected, got)
-
-            expected = fstart + FEastern.stdoffset
-            got = FEastern.fromutc(fstart)
-            self.assertEqual(expected, got)
-
-            # Ensure astimezone() calls fromutc() too.
-            got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
-            self.assertEqual(expected, got)
-
-            start += HOUR
-            fstart += HOUR
-
-        # Check around DST end.
-        start = self.dstoff.replace(hour=4, tzinfo=Eastern)
-        fstart = start.replace(tzinfo=FEastern)
-        for wall in 0, 1, 1, 2, 3, 4:
-            expected = start.replace(hour=wall)
-            got = Eastern.fromutc(start)
-            self.assertEqual(expected, got)
-
-            expected = fstart + FEastern.stdoffset
-            got = FEastern.fromutc(fstart)
-            self.assertEqual(expected, got)
-
-            # Ensure astimezone() calls fromutc() too.
-            got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
-            self.assertEqual(expected, got)
-
-            start += HOUR
-            fstart += HOUR
-
-
-#############################################################################
-# oddballs
-
-class Oddballs(unittest.TestCase):
-
-    def test_bug_1028306(self):
-        # Trying to compare a date to a datetime should act like a mixed-
-        # type comparison, despite that datetime is a subclass of date.
-        as_date = date.today()
-        as_datetime = datetime.combine(as_date, time())
-        self.assertTrue(as_date != as_datetime)
-        self.assertTrue(as_datetime != as_date)
-        self.assertTrue(not as_date == as_datetime)
-        self.assertTrue(not as_datetime == as_date)
-        self.assertRaises(TypeError, lambda: as_date < as_datetime)
-        self.assertRaises(TypeError, lambda: as_datetime < as_date)
-        self.assertRaises(TypeError, lambda: as_date <= as_datetime)
-        self.assertRaises(TypeError, lambda: as_datetime <= as_date)
-        self.assertRaises(TypeError, lambda: as_date > as_datetime)
-        self.assertRaises(TypeError, lambda: as_datetime > as_date)
-        self.assertRaises(TypeError, lambda: as_date >= as_datetime)
-        self.assertRaises(TypeError, lambda: as_datetime >= as_date)
-
-        # Neverthelss, comparison should work with the base-class (date)
-        # projection if use of a date method is forced.
-        self.assertEqual(as_date.__eq__(as_datetime), True)
-        different_day = (as_date.day + 1) % 20 + 1
-        as_different = as_datetime.replace(day= different_day)
-        self.assertEqual(as_date.__eq__(as_different), False)
-
-        # And date should compare with other subclasses of date.  If a
-        # subclass wants to stop this, it's up to the subclass to do so.
-        date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
-        self.assertEqual(as_date, date_sc)
-        self.assertEqual(date_sc, as_date)
-
-        # Ditto for datetimes.
-        datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month,
-                                       as_date.day, 0, 0, 0)
-        self.assertEqual(as_datetime, datetime_sc)
-        self.assertEqual(datetime_sc, as_datetime)
+import sys
+from test.support import import_fresh_module, run_unittest
+TESTS = 'test.datetimetester'
+# XXX: import_fresh_module() is supposed to leave sys.module cache untouched,
+# XXX: but it does not, so we have to save and restore it ourselves.
+save_sys_modules = sys.modules.copy()
+try:
+    pure_tests = import_fresh_module(TESTS, fresh=['datetime', '_strptime'],
+                                     blocked=['_datetime'])
+    fast_tests = import_fresh_module(TESTS, fresh=['datetime',
+                                                   '_datetime', '_strptime'])
+finally:
+    sys.modules.clear()
+    sys.modules.update(save_sys_modules)
+test_modules = [pure_tests, fast_tests]
+test_suffixes = ["_Pure", "_Fast"]
+
+for module, suffix in zip(test_modules, test_suffixes):
+    for name, cls in module.__dict__.items():
+        if isinstance(cls, type) and issubclass(cls, unittest.TestCase):
+            name += suffix
+            cls.__name__ = name
+            globals()[name] = cls
+            def setUp(self, module=module, setup=cls.setUp):
+                self._save_sys_modules = sys.modules.copy()
+                sys.modules[TESTS] = module
+                sys.modules['datetime'] = module.datetime_module
+                sys.modules['_strptime'] = module._strptime
+                setup(self)
+            def tearDown(self, teardown=cls.tearDown):
+                teardown(self)
+                sys.modules.clear()
+                sys.modules.update(self._save_sys_modules)
+            cls.setUp = setUp
+            cls.tearDown = tearDown
 
 def test_main():
-    support.run_unittest(__name__)
+    run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/py3k-dtoa/Lib/test/test_decimal.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_decimal.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_decimal.py	Sun Aug  8 12:41:24 2010
@@ -78,10 +78,41 @@
 
 # list of individual .decTest test ids that correspond to tests that
 # we're skipping for one reason or another.
-skipped_test_ids = [
-    'scbx164',  # skipping apparently implementation-specific scaleb
-    'scbx165',  # tests, pending clarification of scaleb rules.
-]
+skipped_test_ids = set([
+    # Skip implementation-specific scaleb tests.
+    'scbx164',
+    'scbx165',
+
+    # For some operations (currently exp, ln, log10, power), the decNumber
+    # reference implementation imposes additional restrictions on the context
+    # and operands.  These restrictions are not part of the specification;
+    # however, the effect of these restrictions does show up in some of the
+    # testcases.  We skip testcases that violate these restrictions, since
+    # Decimal behaves differently from decNumber for these testcases so these
+    # testcases would otherwise fail.
+    'expx901',
+    'expx902',
+    'expx903',
+    'expx905',
+    'lnx901',
+    'lnx902',
+    'lnx903',
+    'lnx905',
+    'logx901',
+    'logx902',
+    'logx903',
+    'logx905',
+    'powx1183',
+    'powx1184',
+    'powx4001',
+    'powx4002',
+    'powx4003',
+    'powx4005',
+    'powx4008',
+    'powx4010',
+    'powx4012',
+    'powx4014',
+    ])
 
 # Make sure it actually raises errors when not expected and caught in flags
 # Slower, since it runs some things several times.
@@ -172,27 +203,6 @@
     'same_quantum',
     )
 
-# For some operations (currently exp, ln, log10, power), the decNumber
-# reference implementation imposes additional restrictions on the
-# context and operands.  These restrictions are not part of the
-# specification; however, the effect of these restrictions does show
-# up in some of the testcases.  We skip testcases that violate these
-# restrictions, since Decimal behaves differently from decNumber for
-# these testcases so these testcases would otherwise fail.
-
-decNumberRestricted = ('power', 'ln', 'log10', 'exp')
-DEC_MAX_MATH = 999999
-def outside_decNumber_bounds(v, context):
-    if (context.prec > DEC_MAX_MATH or
-        context.Emax > DEC_MAX_MATH or
-        -context.Emin > DEC_MAX_MATH):
-        return True
-    if not v._is_special and v and (
-        v.adjusted() > DEC_MAX_MATH or
-        v.adjusted() < 1-2*DEC_MAX_MATH):
-        return True
-    return False
-
 class DecimalTest(unittest.TestCase):
     """Class which tests the Decimal class against the test cases.
 
@@ -330,22 +340,6 @@
 
         ans = FixQuotes(ans)
 
-        # skip tests that are related to bounds imposed in the decNumber
-        # reference implementation
-        if fname in decNumberRestricted:
-            if fname == 'power':
-                if not (vals[1]._isinteger() and
-                        -1999999997 <= vals[1] <= 999999999):
-                    if outside_decNumber_bounds(vals[0], self.context) or \
-                            outside_decNumber_bounds(vals[1], self.context):
-                        #print "Skipping test %s" % s
-                        return
-            else:
-                if outside_decNumber_bounds(vals[0], self.context):
-                    #print "Skipping test %s" % s
-                    return
-
-
         if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'):
             for error in theirexceptions:
                 self.context.traps[error] = 1

Modified: python/branches/py3k-dtoa/Lib/test/test_doctest.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_doctest.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_doctest.py	Sun Aug  8 12:41:24 2010
@@ -980,6 +980,35 @@
         ZeroDivisionError: integer division or modulo by zero
     TestResults(failed=1, attempted=1)
 """
+    def displayhook(): r"""
+Test that changing sys.displayhook doesn't matter for doctest.
+
+    >>> import sys
+    >>> orig_displayhook = sys.displayhook
+    >>> def my_displayhook(x):
+    ...     print('hi!')
+    >>> sys.displayhook = my_displayhook
+    >>> def f():
+    ...     '''
+    ...     >>> 3
+    ...     3
+    ...     '''
+    >>> test = doctest.DocTestFinder().find(f)[0]
+    >>> r = doctest.DocTestRunner(verbose=False).run(test)
+    >>> post_displayhook = sys.displayhook
+
+    We need to restore sys.displayhook now, so that we'll be able to test
+    results.
+
+    >>> sys.displayhook = orig_displayhook
+
+    Ok, now we can check that everything is ok.
+
+    >>> r
+    TestResults(failed=0, attempted=1)
+    >>> post_displayhook is my_displayhook
+    True
+"""
     def optionflags(): r"""
 Tests of `DocTestRunner`'s option flag handling.
 
@@ -1869,7 +1898,7 @@
     > <doctest foo[1]>(1)<module>()
     -> calls_set_trace()
     (Pdb) print(foo)
-    *** NameError: NameError("name 'foo' is not defined",)
+    *** NameError: name 'foo' is not defined
     (Pdb) continue
     TestResults(failed=0, attempted=2)
 """

Modified: python/branches/py3k-dtoa/Lib/test/test_fileinput.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_fileinput.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_fileinput.py	Sun Aug  8 12:41:24 2010
@@ -231,6 +231,30 @@
 ##         finally:
 ##             remove_tempfiles(t1)
 
+    def test_context_manager(self):
+        try:
+            t1 = writeTmp(1, ["A\nB\nC"])
+            t2 = writeTmp(2, ["D\nE\nF"])
+            with FileInput(files=(t1, t2)) as fi:
+                lines = list(fi)
+            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
+            self.assertEqual(fi.filelineno(), 3)
+            self.assertEqual(fi.lineno(), 6)
+            self.assertEqual(fi._files, ())
+        finally:
+            remove_tempfiles(t1, t2)
+
+    def test_close_on_exception(self):
+        try:
+            t1 = writeTmp(1, [""])
+            with FileInput(files=t1) as fi:
+                raise IOError
+        except IOError:
+            self.assertEqual(fi._files, ())
+        finally:
+            remove_tempfiles(t1)
+
+
 def test_main():
     run_unittest(BufferSizesTests, FileInputTests)
 

Modified: python/branches/py3k-dtoa/Lib/test/test_float.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_float.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_float.py	Sun Aug  8 12:41:24 2010
@@ -635,7 +635,9 @@
             negs = '-'+s
             self.assertEqual(s, repr(float(s)))
             self.assertEqual(negs, repr(float(negs)))
-
+            # Since Python 3.2, repr and str are identical
+            self.assertEqual(repr(float(s)), str(float(s)))
+            self.assertEqual(repr(float(negs)), str(float(negs)))
 
 @requires_IEEE_754
 class RoundTestCase(unittest.TestCase):

Modified: python/branches/py3k-dtoa/Lib/test/test_fnmatch.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_fnmatch.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_fnmatch.py	Sun Aug  8 12:41:24 2010
@@ -3,10 +3,15 @@
 from test import support
 import unittest
 
-from fnmatch import fnmatch, fnmatchcase
+from fnmatch import (fnmatch, fnmatchcase, _MAXCACHE, _cache, _cacheb, purge,
+                        translate, filter)
 
 
 class FnmatchTestCase(unittest.TestCase):
+
+    def tearDown(self):
+        purge()
+
     def check_match(self, filename, pattern, should_match=1, fn=fnmatch):
         if should_match:
             self.assertTrue(fn(filename, pattern),
@@ -60,9 +65,45 @@
         self.check_match(b'test\xff', b'te*\xff')
         self.check_match(b'foo\nbar', b'foo*')
 
+    def test_cache_clearing(self):
+        # check that caches do not grow too large
+        # http://bugs.python.org/issue7846
+
+        # string pattern cache
+        for i in range(_MAXCACHE + 1):
+            fnmatch('foo', '?' * i)
+
+        self.assertLessEqual(len(_cache), _MAXCACHE)
+
+        # bytes pattern cache
+        for i in range(_MAXCACHE + 1):
+            fnmatch(b'foo', b'?' * i)
+        self.assertLessEqual(len(_cacheb), _MAXCACHE)
+
+
+class TranslateTestCase(unittest.TestCase):
+
+    def test_translate(self):
+        self.assertEqual(translate('*'), '.*\Z(?ms)')
+        self.assertEqual(translate('?'), '.\Z(?ms)')
+        self.assertEqual(translate('a?b*'), 'a.b.*\Z(?ms)')
+        self.assertEqual(translate('[abc]'), '[abc]\Z(?ms)')
+        self.assertEqual(translate('[]]'), '[]]\Z(?ms)')
+        self.assertEqual(translate('[!x]'), '[^x]\Z(?ms)')
+        self.assertEqual(translate('[^x]'), '[\\^x]\Z(?ms)')
+        self.assertEqual(translate('[x'), '\\[x\Z(?ms)')
+
+
+class FilterTestCase(unittest.TestCase):
+
+    def test_filter(self):
+        self.assertEqual(filter(['a', 'b'], 'a'), ['a'])
+
 
 def test_main():
-    support.run_unittest(FnmatchTestCase)
+    support.run_unittest(FnmatchTestCase,
+                         TranslateTestCase,
+                         FilterTestCase)
 
 
 if __name__ == "__main__":

Modified: python/branches/py3k-dtoa/Lib/test/test_functools.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_functools.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_functools.py	Sun Aug  8 12:41:24 2010
@@ -4,6 +4,7 @@
 from test import support
 from weakref import proxy
 import pickle
+from random import choice
 
 @staticmethod
 def PythonPartial(func, *args, **keywords):
@@ -181,11 +182,11 @@
                 self.assertTrue(wrapped_attr[key] is wrapper_attr[key])
 
     def _default_update(self):
-        def f():
+        def f(a:'This is a new annotation'):
             """This is a test"""
             pass
         f.attr = 'This is also a test'
-        def wrapper():
+        def wrapper(b:'This is the prior annotation'):
             pass
         functools.update_wrapper(wrapper, f)
         return wrapper, f
@@ -195,6 +196,8 @@
         self.check_wrapper(wrapper, f)
         self.assertEqual(wrapper.__name__, 'f')
         self.assertEqual(wrapper.attr, 'This is also a test')
+        self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation')
+        self.assertNotIn('b', wrapper.__annotations__)
 
     @unittest.skipIf(sys.flags.optimize >= 2,
                      "Docstrings are omitted with -O2 and above")
@@ -213,6 +216,7 @@
         self.check_wrapper(wrapper, f, (), ())
         self.assertEqual(wrapper.__name__, 'wrapper')
         self.assertEqual(wrapper.__doc__, None)
+        self.assertEqual(wrapper.__annotations__, {})
         self.assertFalse(hasattr(wrapper, 'attr'))
 
     def test_selective_update(self):
@@ -239,6 +243,7 @@
         functools.update_wrapper(wrapper, max)
         self.assertEqual(wrapper.__name__, 'max')
         self.assertTrue(wrapper.__doc__.startswith('max('))
+        self.assertEqual(wrapper.__annotations__, {})
 
 class TestWraps(TestUpdateWrapper):
 
@@ -454,6 +459,50 @@
             class A:
                 pass
 
+class TestLRU(unittest.TestCase):
+
+    def test_lru(self):
+        def orig(x, y):
+            return 3*x+y
+        f = functools.lru_cache(maxsize=20)(orig)
+
+        domain = range(5)
+        for i in range(1000):
+            x, y = choice(domain), choice(domain)
+            actual = f(x, y)
+            expected = orig(x, y)
+            self.assertEquals(actual, expected)
+        self.assert_(f.hits > f.misses)
+        self.assertEquals(f.hits + f.misses, 1000)
+
+        f.clear()   # test clearing
+        self.assertEqual(f.hits, 0)
+        self.assertEqual(f.misses, 0)
+        f(x, y)
+        self.assertEqual(f.hits, 0)
+        self.assertEqual(f.misses, 1)
+
+    def test_lfu(self):
+        def orig(x, y):
+            return 3*x+y
+        f = functools.lfu_cache(maxsize=20)(orig)
+
+        domain = range(5)
+        for i in range(1000):
+            x, y = choice(domain), choice(domain)
+            actual = f(x, y)
+            expected = orig(x, y)
+            self.assertEquals(actual, expected)
+        self.assert_(f.hits > f.misses)
+        self.assertEquals(f.hits + f.misses, 1000)
+
+        f.clear()   # test clearing
+        self.assertEqual(f.hits, 0)
+        self.assertEqual(f.misses, 0)
+        f(x, y)
+        self.assertEqual(f.hits, 0)
+        self.assertEqual(f.misses, 1)
+
 def test_main(verbose=None):
     test_classes = (
         TestPartial,
@@ -461,7 +510,8 @@
         TestPythonPartial,
         TestUpdateWrapper,
         TestWraps,
-        TestReduce
+        TestReduce,
+        TestLRU,
     )
     support.run_unittest(*test_classes)
 

Modified: python/branches/py3k-dtoa/Lib/test/test_gdb.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_gdb.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_gdb.py	Sun Aug  8 12:41:24 2010
@@ -9,6 +9,7 @@
 import sys
 import unittest
 import locale
+import sysconfig
 
 from test.support import run_unittest, findfile
 
@@ -664,6 +665,15 @@
                                     r".*\na = 1\nb = 2\nc = 3\n.*")
 
 def test_main():
+    cflags = sysconfig.get_config_vars()['PY_CFLAGS']
+    final_opt = ""
+    for opt in cflags.split():
+        if opt.startswith('-O'):
+            final_opt = opt
+    if final_opt and final_opt != '-O0':
+        raise unittest.SkipTest("Python was built with compiler optimizations, "
+                                "tests can't reliably succeed")
+
     run_unittest(PrettyPrintTests,
                  PyListTests,
                  StackNavigationTests,

Modified: python/branches/py3k-dtoa/Lib/test/test_getopt.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_getopt.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_getopt.py	Sun Aug  8 12:41:24 2010
@@ -173,6 +173,12 @@
         m = types.ModuleType("libreftest", s)
         run_doctest(m, verbose)
 
+    def test_issue4629(self):
+        longopts, shortopts = getopt.getopt(['--help='], '', ['help='])
+        self.assertEquals(longopts, [('--help', '')])
+        longopts, shortopts = getopt.getopt(['--help=x'], '', ['help='])
+        self.assertEquals(longopts, [('--help', 'x')])
+        self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help'])
 
 def test_main():
     run_unittest(GetoptTests)

Modified: python/branches/py3k-dtoa/Lib/test/test_glob.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_glob.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_glob.py	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 import unittest
-from test.support import run_unittest, TESTFN
+from test.support import run_unittest, TESTFN, skip_unless_symlink, can_symlink
 import glob
 import os
 import shutil
@@ -25,7 +25,7 @@
         self.mktemp('ZZZ')
         self.mktemp('a', 'bcd', 'EF')
         self.mktemp('a', 'bcd', 'efg', 'ha')
-        if hasattr(os, 'symlink'):
+        if can_symlink():
             os.symlink(self.norm('broken'), self.norm('sym1'))
             os.symlink(self.norm('broken'), self.norm('sym2'))
 
@@ -98,12 +98,12 @@
         # either of these results are reasonable
         self.assertIn(res[0], [self.tempdir, self.tempdir + os.sep])
 
+    @skip_unless_symlink
     def test_glob_broken_symlinks(self):
-        if hasattr(os, 'symlink'):
-            eq = self.assertSequencesEqual_noorder
-            eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2')])
-            eq(self.glob('sym1'), [self.norm('sym1')])
-            eq(self.glob('sym2'), [self.norm('sym2')])
+        eq = self.assertSequencesEqual_noorder
+        eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2')])
+        eq(self.glob('sym1'), [self.norm('sym1')])
+        eq(self.glob('sym2'), [self.norm('sym2')])
 
 
 def test_main():

Modified: python/branches/py3k-dtoa/Lib/test/test_http_cookiejar.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_http_cookiejar.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_http_cookiejar.py	Sun Aug  8 12:41:24 2010
@@ -1,18 +1,21 @@
 """Tests for http/cookiejar.py."""
 
-import re, os, time, urllib.request
-from unittest import TestCase
+import os
+import re
+import test.support
+import time
+import unittest
+import urllib.request
+
+from http.cookiejar import (time2isoz, http2time, time2netscape,
+     parse_ns_headers, join_header_words, split_header_words, Cookie,
+     CookieJar, DefaultCookiePolicy, LWPCookieJar, MozillaCookieJar,
+     LoadError, lwp_cookie_str, DEFAULT_HTTP_PORT, escape_path,
+     reach, is_HDN, domain_match, user_domain_match, request_path,
+     request_port, request_host)
 
-from test import support
 
-from http.cookiejar import time2isoz, http2time, time2netscape, \
-     parse_ns_headers, join_header_words, split_header_words, Cookie, \
-     CookieJar, DefaultCookiePolicy, LWPCookieJar, MozillaCookieJar, \
-     LoadError, lwp_cookie_str, DEFAULT_HTTP_PORT, escape_path, \
-     reach, is_HDN, domain_match, user_domain_match, request_path, \
-     request_port, request_host
-
-class DateTimeTests(TestCase):
+class DateTimeTests(unittest.TestCase):
 
     def test_time2isoz(self):
         base = 1019227000
@@ -96,7 +99,7 @@
                          )
 
 
-class HeaderTests(TestCase):
+class HeaderTests(unittest.TestCase):
 
     def test_parse_ns_headers(self):
         # quotes should be stripped
@@ -228,10 +231,10 @@
     return cookie_hdr
 
 
-class FileCookieJarTests(TestCase):
+class FileCookieJarTests(unittest.TestCase):
     def test_lwp_valueless_cookie(self):
         # cookies with no value should be saved and loaded consistently
-        filename = support.TESTFN
+        filename = test.support.TESTFN
         c = LWPCookieJar()
         interact_netscape(c, "http://www.acme.com/", 'boo')
         self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
@@ -246,7 +249,7 @@
 
     def test_bad_magic(self):
         # IOErrors (eg. file doesn't exist) are allowed to propagate
-        filename = support.TESTFN
+        filename = test.support.TESTFN
         for cookiejar_class in LWPCookieJar, MozillaCookieJar:
             c = cookiejar_class()
             try:
@@ -269,7 +272,7 @@
             try: os.unlink(filename)
             except OSError: pass
 
-class CookieTests(TestCase):
+class CookieTests(unittest.TestCase):
     # XXX
     # Get rid of string comparisons where not actually testing str / repr.
     # .clear() etc.
@@ -349,7 +352,7 @@
     def test_missing_value(self):
         # missing = sign in Cookie: header is regarded by Mozilla as a missing
         # name, and by http.cookiejar as a missing value
-        filename = support.TESTFN
+        filename = test.support.TESTFN
         c = MozillaCookieJar(filename)
         interact_netscape(c, "http://www.acme.com/", 'eggs')
         interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
@@ -534,6 +537,16 @@
         interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
         self.assertIn("/blah/rhubarb", c._cookies["www.acme.com"])
 
+    def test_default_path_with_query(self):
+        cj = CookieJar()
+        uri = "http://example.com/?spam/eggs"
+        value = 'eggs="bar"'
+        interact_netscape(cj, uri, value)
+        # Default path does not include query, so is "/", not "/?spam".
+        self.assertIn("/", cj._cookies["example.com"])
+        # Cookie is sent back to the same URI.
+        self.assertEquals(interact_netscape(cj, uri), value)
+
     def test_escape_path(self):
         cases = [
             # quoted safe
@@ -562,16 +575,15 @@
     def test_request_path(self):
         # with parameters
         req = urllib.request.Request(
-            "http://www.example.com/rheum/rhaponicum;"
+            "http://www.example.com/rheum/rhaponticum;"
             "foo=bar;sing=song?apples=pears&spam=eggs#ni")
-        self.assertEquals(request_path(req), "/rheum/rhaponicum;"
-                     "foo=bar;sing=song?apples=pears&spam=eggs#ni")
+        self.assertEquals(request_path(req),
+                          "/rheum/rhaponticum;foo=bar;sing=song")
         # without parameters
         req = urllib.request.Request(
-            "http://www.example.com/rheum/rhaponicum?"
+            "http://www.example.com/rheum/rhaponticum?"
             "apples=pears&spam=eggs#ni")
-        self.assertEquals(request_path(req), "/rheum/rhaponicum?"
-                     "apples=pears&spam=eggs#ni")
+        self.assertEquals(request_path(req), "/rheum/rhaponticum")
         # missing final slash
         req = urllib.request.Request("http://www.example.com")
         self.assertEquals(request_path(req), "/")
@@ -1045,7 +1057,7 @@
         self.assertTrue(cookie.expires is None)
 
 
-class LWPCookieTests(TestCase):
+class LWPCookieTests(unittest.TestCase):
     # Tests taken from libwww-perl, with a few modifications and additions.
 
     def test_netscape_example_1(self):
@@ -1435,7 +1447,7 @@
         self.assertEquals(len(c), 6)
 
         # save and restore
-        filename = support.TESTFN
+        filename = test.support.TESTFN
 
         try:
             c.save(filename, ignore_discard=True)
@@ -1475,7 +1487,7 @@
         # Save / load Mozilla/Netscape cookie file format.
         year_plus_one = time.localtime()[0] + 1
 
-        filename = support.TESTFN
+        filename = test.support.TESTFN
 
         c = MozillaCookieJar(filename,
                              policy=DefaultCookiePolicy(rfc2965=True))
@@ -1637,7 +1649,7 @@
 
 
 def test_main(verbose=None):
-    support.run_unittest(
+    test.support.run_unittest(
         DateTimeTests,
         HeaderTests,
         CookieTests,

Modified: python/branches/py3k-dtoa/Lib/test/test_http_cookies.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_http_cookies.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_http_cookies.py	Sun Aug  8 12:41:24 2010
@@ -19,24 +19,21 @@
 
     def test_basic(self):
         cases = [
-            { 'data': 'chips=ahoy; vienna=finger',
-              'dict': {'chips':'ahoy', 'vienna':'finger'},
-              'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
-              'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger',
-            },
-
-            { 'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
-              'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
-              'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
-              'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
-            },
+            {'data': 'chips=ahoy; vienna=finger',
+             'dict': {'chips':'ahoy', 'vienna':'finger'},
+             'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
+             'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'},
+
+            {'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
+             'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
+             'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
+             'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'},
 
             # Check illegal cookies that have an '=' char in an unquoted value
-            { 'data': 'keebler=E=mc2',
-              'dict': {'keebler' : 'E=mc2'},
-              'repr': "<SimpleCookie: keebler='E=mc2'>",
-              'output': 'Set-Cookie: keebler=E=mc2',
-            }
+            {'data': 'keebler=E=mc2',
+             'dict': {'keebler' : 'E=mc2'},
+             'repr': "<SimpleCookie: keebler='E=mc2'>",
+             'output': 'Set-Cookie: keebler=E=mc2'},
         ]
 
         for case in cases:
@@ -72,6 +69,36 @@
         </script>
         """)
 
+    def test_special_attrs(self):
+        # 'expires'
+        C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
+        C['Customer']['expires'] = 0
+        # can't test exact output, it always depends on current date/time
+        self.assertTrue(C.output().endswith('GMT'))
+
+        # loading 'expires'
+        C = cookies.SimpleCookie()
+        C.load('Customer="W"; expires=Wed, 01-Jan-2010 00:00:00 GMT')
+        self.assertEqual(C['Customer']['expires'],
+                         'Wed, 01-Jan-2010 00:00:00 GMT')
+        C = cookies.SimpleCookie()
+        C.load('Customer="W"; expires=Wed, 01-Jan-98 00:00:00 GMT')
+        self.assertEqual(C['Customer']['expires'],
+                         'Wed, 01-Jan-98 00:00:00 GMT')
+
+        # 'max-age'
+        C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
+        C['Customer']['max-age'] = 10
+        self.assertEqual(C.output(),
+                         'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
+
+        # others
+        C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
+        C['Customer']['secure'] = True
+        C['Customer']['httponly'] = True
+        self.assertEqual(C.output(),
+            'Set-Cookie: Customer="WILE_E_COYOTE"; httponly; secure')
+
     def test_quoted_meta(self):
         # Try cookie with quoted meta-data
         C = cookies.SimpleCookie()
@@ -80,8 +107,72 @@
         self.assertEqual(C['Customer']['version'], '1')
         self.assertEqual(C['Customer']['path'], '/acme')
 
+        self.assertEqual(C.output(['path']),
+                         'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
+        self.assertEqual(C.js_output(), r"""
+        <script type="text/javascript">
+        <!-- begin hiding
+        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
+        // end hiding -->
+        </script>
+        """)
+        self.assertEqual(C.js_output(['path']), r"""
+        <script type="text/javascript">
+        <!-- begin hiding
+        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
+        // end hiding -->
+        </script>
+        """)
+
+class MorselTests(unittest.TestCase):
+    """Tests for the Morsel object."""
+
+    def test_reserved_keys(self):
+        M = cookies.Morsel()
+        # tests valid and invalid reserved keys for Morsels
+        for i in M._reserved:
+            # Test that all valid keys are reported as reserved and set them
+            self.assertTrue(M.isReservedKey(i))
+            M[i] = '%s_value' % i
+        for i in M._reserved:
+            # Test that valid key values come out fine
+            self.assertEqual(M[i], '%s_value' % i)
+        for i in "the holy hand grenade".split():
+            # Test that invalid keys raise CookieError
+            self.assertRaises(cookies.CookieError,
+                              M.__setitem__, i, '%s_value' % i)
+
+    def test_setter(self):
+        M = cookies.Morsel()
+        # tests the .set method to set keys and their values
+        for i in M._reserved:
+            # Makes sure that all reserved keys can't be set this way
+            self.assertRaises(cookies.CookieError,
+                              M.set, i, '%s_value' % i, '%s_value' % i)
+        for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
+            # Try typical use case. Setting decent values.
+            # Check output and js_output.
+            M['path'] = '/foo' # Try a reserved key as well
+            M.set(i, "%s_val" % i, "%s_coded_val" % i)
+            self.assertEqual(
+                M.output(),
+                "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
+            expected_js_output = """
+        <script type="text/javascript">
+        <!-- begin hiding
+        document.cookie = "%s=%s; Path=/foo";
+        // end hiding -->
+        </script>
+        """ % (i, "%s_coded_val" % i)
+            self.assertEqual(M.js_output(), expected_js_output)
+        for i in ["foo bar", "foo at bar"]:
+            # Try some illegal characters
+            self.assertRaises(cookies.CookieError,
+                              M.set, i, '%s_value' % i, '%s_value' % i)
+
+
 def test_main():
-    run_unittest(CookieTests)
+    run_unittest(CookieTests, MorselTests)
     run_doctest(cookies)
 
 if __name__ == '__main__':

Modified: python/branches/py3k-dtoa/Lib/test/test_httplib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_httplib.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_httplib.py	Sun Aug  8 12:41:24 2010
@@ -442,9 +442,46 @@
         self.assertEqual("5", message.get("content-length"))
         self.assertEqual(b'body\xc1', f.read())
 
+
+class HTTPResponseTest(TestCase):
+
+    def setUp(self):
+        body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
+                second-value\r\n\r\nText"
+        sock = FakeSocket(body)
+        self.resp = client.HTTPResponse(sock)
+        self.resp.begin()
+
+    def test_getting_header(self):
+        header = self.resp.getheader('My-Header')
+        self.assertEqual(header, 'first-value, second-value')
+
+        header = self.resp.getheader('My-Header', 'some default')
+        self.assertEqual(header, 'first-value, second-value')
+
+    def test_getting_nonexistent_header_with_string_default(self):
+        header = self.resp.getheader('No-Such-Header', 'default-value')
+        self.assertEqual(header, 'default-value')
+
+    def test_getting_nonexistent_header_with_iterable_default(self):
+        header = self.resp.getheader('No-Such-Header', ['default', 'values'])
+        self.assertEqual(header, 'default, values')
+
+        header = self.resp.getheader('No-Such-Header', ('default', 'values'))
+        self.assertEqual(header, 'default, values')
+
+    def test_getting_nonexistent_header_without_default(self):
+        header = self.resp.getheader('No-Such-Header')
+        self.assertEqual(header, None)
+
+    def test_getting_header_defaultint(self):
+        header = self.resp.getheader('No-Such-Header',default=42)
+        self.assertEqual(header, 42)
+
 def test_main(verbose=None):
     support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
-                         HTTPSTimeoutTest, RequestBodyTest, SourceAddressTest)
+                         HTTPSTimeoutTest, RequestBodyTest, SourceAddressTest,
+                         HTTPResponseTest)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/py3k-dtoa/Lib/test/test_httpservers.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_httpservers.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_httpservers.py	Sun Aug  8 12:41:24 2010
@@ -299,7 +299,7 @@
 
         # The shebang line should be pure ASCII: use symlink if possible.
         # See issue #7668.
-        if hasattr(os, 'symlink'):
+        if support.can_symlink():
             self.pythonexe = os.path.join(self.parent_dir, 'python')
             os.symlink(sys.executable, self.pythonexe)
         else:
@@ -401,13 +401,41 @@
              (res.read(), res.getheader('Content-type'), res.status))
 
 
+class SocketlessRequestHandler(SimpleHTTPRequestHandler):
+    def __init__(self):
+        pass
+
+class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
+    """ Test url parsing """
+    def setUp(self):
+        self.translated = os.getcwd()
+        self.translated = os.path.join(self.translated, 'filename')
+        self.handler = SocketlessRequestHandler()
+
+    def test_query_arguments(self):
+        path = self.handler.translate_path('/filename')
+        self.assertEqual(path, self.translated)
+        path = self.handler.translate_path('/filename?foo=bar')
+        self.assertEqual(path, self.translated)
+        path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
+        self.assertEqual(path, self.translated)
+
+    def test_start_with_double_slash(self):
+        path = self.handler.translate_path('//filename')
+        self.assertEqual(path, self.translated)
+        path = self.handler.translate_path('//filename?foo=bar')
+        self.assertEqual(path, self.translated)
+
+
 def test_main(verbose=None):
+    cwd = os.getcwd()
     try:
-        cwd = os.getcwd()
-        support.run_unittest(BaseHTTPServerTestCase,
-                             SimpleHTTPServerTestCase,
-                             CGIHTTPServerTestCase
-                             )
+        support.run_unittest(
+            BaseHTTPServerTestCase,
+            SimpleHTTPServerTestCase,
+            CGIHTTPServerTestCase,
+            SimpleHTTPRequestHandlerTestCase,
+        )
     finally:
         os.chdir(cwd)
 

Modified: python/branches/py3k-dtoa/Lib/test/test_import.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_import.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_import.py	Sun Aug  8 12:41:24 2010
@@ -1,6 +1,8 @@
 import builtins
 import errno
 import imp
+from importlib.test.import_ import test_relative_imports
+from importlib.test.import_ import util as importlib_util
 import marshal
 import os
 import py_compile
@@ -289,6 +291,11 @@
 
     def test_import_by_filename(self):
         path = os.path.abspath(TESTFN)
+        encoding = sys.getfilesystemencoding()
+        try:
+            path.encode(encoding)
+        except UnicodeEncodeError:
+            self.skipTest('path is not encodable to {}'.format(encoding))
         with self.assertRaises(ImportError) as c:
             __import__(path)
         self.assertEqual("Import by filename is not supported.",
@@ -633,10 +640,21 @@
                          os.path.join(os.curdir, foo_pyc))
 
 
+class RelativeImportFromImportlibTests(test_relative_imports.RelativeImports):
+
+    def setUp(self):
+        self._importlib_util_flag = importlib_util.using___import__
+        importlib_util.using___import__ = True
+
+    def tearDown(self):
+        importlib_util.using___import__ = self._importlib_util_flag
+
+
 def test_main(verbose=None):
     run_unittest(ImportTests, PycacheTests,
                  PycRewritingTests, PathsTests, RelativeImportTests,
-                 OverridingImportBuiltinTests)
+                 OverridingImportBuiltinTests,
+                 RelativeImportFromImportlibTests)
 
 
 if __name__ == '__main__':

Modified: python/branches/py3k-dtoa/Lib/test/test_math.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_math.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_math.py	Sun Aug  8 12:41:24 2010
@@ -647,15 +647,7 @@
 
     def testLog1p(self):
         self.assertRaises(TypeError, math.log1p)
-        self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1)
-        self.ftest('log1p(0)', math.log1p(0), 0)
-        self.ftest('log1p(e-1)', math.log1p(math.e-1), 1)
-        self.ftest('log1p(1)', math.log1p(1), math.log(2))
-        self.assertEquals(math.log1p(INF), INF)
-        self.assertRaises(ValueError, math.log1p, NINF)
-        self.assertTrue(math.isnan(math.log1p(NAN)))
         n= 2**90
-        self.assertAlmostEquals(math.log1p(n), 62.383246250395075)
         self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
 
     def testLog10(self):
@@ -923,6 +915,15 @@
         self.assertRaises(TypeError, math.trunc, 1, 2)
         self.assertRaises(TypeError, math.trunc, TestNoTrunc())
 
+    def testIsfinite(self):
+        self.assertTrue(math.isfinite(0.0))
+        self.assertTrue(math.isfinite(-0.0))
+        self.assertTrue(math.isfinite(1.0))
+        self.assertTrue(math.isfinite(-1.0))
+        self.assertFalse(math.isfinite(float("nan")))
+        self.assertFalse(math.isfinite(float("inf")))
+        self.assertFalse(math.isfinite(float("-inf")))
+
     def testIsnan(self):
         self.assertTrue(math.isnan(float("nan")))
         self.assertTrue(math.isnan(float("inf")* 0.))

Modified: python/branches/py3k-dtoa/Lib/test/test_minidom.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_minidom.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_minidom.py	Sun Aug  8 12:41:24 2010
@@ -951,6 +951,14 @@
         doc.unlink()
 
 
+    def testBug0777884(self):
+        doc = parseString("<o>text</o>")
+        text = doc.documentElement.childNodes[0]
+        self.assertEquals(text.nodeType, Node.TEXT_NODE)
+        # Should run quietly, doing nothing.
+        text.normalize()
+        doc.unlink()
+
     def testBug1433694(self):
         doc = parseString("<o><i/>t</o>")
         node = doc.documentElement

Modified: python/branches/py3k-dtoa/Lib/test/test_mmap.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_mmap.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_mmap.py	Sun Aug  8 12:41:24 2010
@@ -1,6 +1,6 @@
 from test.support import TESTFN, run_unittest, import_module
 import unittest
-import os, re, itertools
+import os, re, itertools, socket
 
 # Skip test if we can't import mmap.
 mmap = import_module('mmap')
@@ -586,6 +586,31 @@
                 pass
             m.close()
 
+        def test_invalid_descriptor(self):
+            # socket file descriptors are valid, but out of range
+            # for _get_osfhandle, causing a crash when validating the
+            # parameters to _get_osfhandle.
+            s = socket.socket()
+            try:
+                with self.assertRaises(mmap.error):
+                    m = mmap.mmap(s.fileno(), 10)
+            finally:
+                s.close()
+
+    def test_context_manager(self):
+        with mmap.mmap(-1, 10) as m:
+            self.assertFalse(m.closed)
+        self.assertTrue(m.closed)
+
+    def test_context_manager_exception(self):
+        # Test that the IOError gets passed through
+        with self.assertRaises(Exception) as exc:
+            with mmap.mmap(-1, 10) as m:
+                raise IOError
+        self.assertIsInstance(exc.exception, IOError,
+                              "wrong exception raised in context manager")
+        self.assertTrue(m.closed, "context manager failed")
+
 
 def test_main():
     run_unittest(MmapTests)

Modified: python/branches/py3k-dtoa/Lib/test/test_ntpath.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_ntpath.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_ntpath.py	Sun Aug  8 12:41:24 2010
@@ -174,6 +174,9 @@
         tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
         tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')
 
+        tester("ntpath.normpath('\\\\.\\NUL')", r'\\.\NUL')
+        tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r'\\?\D:/XY\Z')
+
     def test_expandvars(self):
         with support.EnvironmentVarGuard() as env:
             env.clear()

Modified: python/branches/py3k-dtoa/Lib/test/test_optparse.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_optparse.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_optparse.py	Sun Aug  8 12:41:24 2010
@@ -781,15 +781,13 @@
         (options, args) = self.assertParseOK(["-q"],
                                              {'verbose': 0},
                                              [])
-        if hasattr(__builtins__, 'False'):
-            self.assertTrue(options.verbose is False)
+        self.assertTrue(options.verbose is False)
 
     def test_bool_true(self):
         (options, args) = self.assertParseOK(["-v"],
                                              {'verbose': 1},
                                              [])
-        if hasattr(__builtins__, 'True'):
-            self.assertTrue(options.verbose is True)
+        self.assertTrue(options.verbose is True)
 
     def test_bool_flicker_on_and_off(self):
         self.assertParseOK(["-qvq", "-q", "-v"],

Modified: python/branches/py3k-dtoa/Lib/test/test_os.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_os.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_os.py	Sun Aug  8 12:41:24 2010
@@ -423,7 +423,9 @@
         """Check that the repr() of os.environ looks like environ({...})."""
         env = os.environ
         self.assertTrue(isinstance(env.data, dict))
-        self.assertEqual(repr(env), 'environ({!r})'.format(env.data))
+        self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
+            '{!r}: {!r}'.format(key, value)
+            for key, value in env.items())))
 
     def test_get_exec_path(self):
         defpath_list = os.defpath.split(os.pathsep)
@@ -520,7 +522,7 @@
             f = open(path, "w")
             f.write("I'm " + path + " and proud of it.  Blame test_os.\n")
             f.close()
-        if hasattr(os, "symlink"):
+        if support.can_symlink():
             os.symlink(os.path.abspath(t2_path), link_path)
             sub2_tree = (sub2_path, ["link"], ["tmp3"])
         else:
@@ -564,7 +566,7 @@
         self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
         self.assertEqual(all[2 - 2 * flipped], sub2_tree)
 
-        if hasattr(os, "symlink"):
+        if support.can_symlink():
             # Walk, following symlinks.
             for root, dirs, files in os.walk(walk_path, followlinks=True):
                 if root == link_path:
@@ -1033,6 +1035,84 @@
         self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
 
 
+def skipUnlessWindows6(test):
+    if (hasattr(sys, 'getwindowsversion')
+        and sys.getwindowsversion().major >= 6):
+        return test
+    return unittest.skip("Requires Windows Vista or later")(test)
+
+ at unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
+ at support.skip_unless_symlink
+class Win32SymlinkTests(unittest.TestCase):
+    filelink = 'filelinktest'
+    filelink_target = os.path.abspath(__file__)
+    dirlink = 'dirlinktest'
+    dirlink_target = os.path.dirname(filelink_target)
+    missing_link = 'missing link'
+
+    def setUp(self):
+        assert os.path.exists(self.dirlink_target)
+        assert os.path.exists(self.filelink_target)
+        assert not os.path.exists(self.dirlink)
+        assert not os.path.exists(self.filelink)
+        assert not os.path.exists(self.missing_link)
+
+    def tearDown(self):
+        if os.path.exists(self.filelink):
+            os.remove(self.filelink)
+        if os.path.exists(self.dirlink):
+            os.rmdir(self.dirlink)
+        if os.path.lexists(self.missing_link):
+            os.remove(self.missing_link)
+
+    def test_directory_link(self):
+        os.symlink(self.dirlink_target, self.dirlink)
+        self.assertTrue(os.path.exists(self.dirlink))
+        self.assertTrue(os.path.isdir(self.dirlink))
+        self.assertTrue(os.path.islink(self.dirlink))
+        self.check_stat(self.dirlink, self.dirlink_target)
+
+    def test_file_link(self):
+        os.symlink(self.filelink_target, self.filelink)
+        self.assertTrue(os.path.exists(self.filelink))
+        self.assertTrue(os.path.isfile(self.filelink))
+        self.assertTrue(os.path.islink(self.filelink))
+        self.check_stat(self.filelink, self.filelink_target)
+
+    def _create_missing_dir_link(self):
+        'Create a "directory" link to a non-existent target'
+        linkname = self.missing_link
+        if os.path.lexists(linkname):
+            os.remove(linkname)
+        target = r'c:\\target does not exist.29r3c740'
+        assert not os.path.exists(target)
+        target_is_dir = True
+        os.symlink(target, linkname, target_is_dir)
+
+    def test_remove_directory_link_to_missing_target(self):
+        self._create_missing_dir_link()
+        # For compatibility with Unix, os.remove will check the
+        #  directory status and call RemoveDirectory if the symlink
+        #  was created with target_is_dir==True.
+        os.remove(self.missing_link)
+
+    @unittest.skip("currently fails; consider for improvement")
+    def test_isdir_on_directory_link_to_missing_target(self):
+        self._create_missing_dir_link()
+        # consider having isdir return true for directory links
+        self.assertTrue(os.path.isdir(self.missing_link))
+
+    @unittest.skip("currently fails; consider for improvement")
+    def test_rmdir_on_directory_link_to_missing_target(self):
+        self._create_missing_dir_link()
+        # consider allowing rmdir to remove directory links
+        os.rmdir(self.missing_link)
+
+    def check_stat(self, link, target):
+        self.assertEqual(os.stat(link), os.stat(target))
+        self.assertNotEqual(os.lstat(link), os.stat(link))
+
+
 class MiscTests(unittest.TestCase):
 
     @unittest.skipIf(os.name == "nt", "POSIX specific test")
@@ -1056,6 +1136,7 @@
         PosixUidGidTests,
         Pep383Tests,
         Win32KillTests,
+        Win32SymlinkTests,
         MiscTests,
     )
 

Modified: python/branches/py3k-dtoa/Lib/test/test_osx_env.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_osx_env.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_osx_env.py	Sun Aug  8 12:41:24 2010
@@ -8,7 +8,7 @@
 import unittest
 
 class OSXEnvironmentVariableTestCase(unittest.TestCase):
-    def _check_sys(self, ev, cond, sv, val = '/some/path/to/python'):
+    def _check_sys(self, ev, cond, sv, val = sys.executable + 'dummy'):
         with EnvironmentVarGuard() as evg:
             subpc = [str(sys.executable), '-c',
                 'import sys; sys.exit(2 if "%s" %s %s else 3)' % (val, cond, sv)]

Modified: python/branches/py3k-dtoa/Lib/test/test_pdb.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_pdb.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_pdb.py	Sun Aug  8 12:41:24 2010
@@ -1,8 +1,10 @@
-# A test suite for pdb; at the moment, this only validates skipping of
-# specified test modules (RFE #5142).
+# A test suite for pdb; not very comprehensive at the moment.
 
 import imp
+import pdb
 import sys
+import unittest
+import subprocess
 
 from test import support
 # This little helper class is essential for testing pdb under doctest.
@@ -52,6 +54,373 @@
     """
 
 
+def test_pdb_basic_commands():
+    """Test the basic commands of pdb.
+
+    >>> def test_function_2(foo, bar='default'):
+    ...     print(foo)
+    ...     for i in range(5):
+    ...         print(i)
+    ...     print(bar)
+    ...     for i in range(10):
+    ...         never_executed
+    ...     print('after for')
+    ...     print('...')
+    ...     return foo.upper()
+
+    >>> def test_function():
+    ...     import pdb; pdb.Pdb().set_trace()
+    ...     ret = test_function_2('baz')
+    ...     print(ret)
+
+    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+    ...     'step',       # entering the function call
+    ...     'args',       # display function args
+    ...     'list',       # list function source
+    ...     'bt',         # display backtrace
+    ...     'up',         # step up to test_function()
+    ...     'down',       # step down to test_function_2() again
+    ...     'next',       # stepping to print(foo)
+    ...     'next',       # stepping to the for loop
+    ...     'step',       # stepping into the for loop
+    ...     'until',      # continuing until out of the for loop
+    ...     'next',       # executing the print(bar)
+    ...     'jump 8',     # jump over second for loop
+    ...     'return',     # return out of function
+    ...     'retval',     # display return value
+    ...     'continue',
+    ... ]):
+    ...    test_function()
+    > <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function()
+    -> ret = test_function_2('baz')
+    (Pdb) step
+    --Call--
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
+    -> def test_function_2(foo, bar='default'):
+    (Pdb) args
+    foo = 'baz'
+    bar = 'default'
+    (Pdb) list
+      1  ->     def test_function_2(foo, bar='default'):
+      2             print(foo)
+      3             for i in range(5):
+      4                 print(i)
+      5             print(bar)
+      6             for i in range(10):
+      7                 never_executed
+      8             print('after for')
+      9             print('...')
+     10             return foo.upper()
+    [EOF]
+    (Pdb) bt
+    ...
+      <doctest test.test_pdb.test_pdb_basic_commands[2]>(18)<module>()
+    -> test_function()
+      <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function()
+    -> ret = test_function_2('baz')
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
+    -> def test_function_2(foo, bar='default'):
+    (Pdb) up
+    > <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function()
+    -> ret = test_function_2('baz')
+    (Pdb) down
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2()
+    -> def test_function_2(foo, bar='default'):
+    (Pdb) next
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2()
+    -> print(foo)
+    (Pdb) next
+    baz
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2()
+    -> for i in range(5):
+    (Pdb) step
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2()
+    -> print(i)
+    (Pdb) until
+    0
+    1
+    2
+    3
+    4
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2()
+    -> print(bar)
+    (Pdb) next
+    default
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2()
+    -> for i in range(10):
+    (Pdb) jump 8
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2()
+    -> print('after for')
+    (Pdb) return
+    after for
+    ...
+    --Return--
+    > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ'
+    -> return foo.upper()
+    (Pdb) retval
+    'BAZ'
+    (Pdb) continue
+    BAZ
+    """
+
+
+def test_pdb_breakpoint_commands():
+    """Test basic commands related to breakpoints.
+
+    >>> def test_function():
+    ...     import pdb; pdb.Pdb().set_trace()
+    ...     print(1)
+    ...     print(2)
+    ...     print(3)
+    ...     print(4)
+
+    First, need to clear bdb state that might be left over from previous tests.
+    Otherwise, the new breakpoints might get assigned different numbers.
+
+    >>> from bdb import Breakpoint
+    >>> Breakpoint.next = 1
+    >>> Breakpoint.bplist = {}
+    >>> Breakpoint.bpbynumber = [None]
+
+    Now test the breakpoint commands.  NORMALIZE_WHITESPACE is needed because
+    the breakpoint list outputs a tab for the "stop only" and "ignore next"
+    lines, which we don't want to put in here.
+
+    >>> with PdbTestInput([  # doctest: +NORMALIZE_WHITESPACE
+    ...     'break 3',
+    ...     'disable 1',
+    ...     'ignore 1 10',
+    ...     'condition 1 1 < 2',
+    ...     'break 4',
+    ...     'break',
+    ...     'condition 1',
+    ...     'enable 1',
+    ...     'clear 1',
+    ...     'commands 2',
+    ...     'print 42',
+    ...     'end',
+    ...     'continue',  # will stop at breakpoint 2 (line 4)
+    ...     'clear',     # clear all!
+    ...     'y',
+    ...     'tbreak 5',
+    ...     'continue',  # will stop at temporary breakpoint
+    ...     'break',     # make sure breakpoint is gone
+    ...     'continue',
+    ... ]):
+    ...    test_function()
+    > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function()
+    -> print(1)
+    (Pdb) break 3
+    Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
+    (Pdb) disable 1
+    Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
+    (Pdb) ignore 1 10
+    Will ignore next 10 crossings of breakpoint 1.
+    (Pdb) condition 1 1 < 2
+    New condition set for breakpoint 1.
+    (Pdb) break 4
+    Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    (Pdb) break
+    Num Type         Disp Enb   Where
+    1   breakpoint   keep no    at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
+            stop only if 1 < 2
+            ignore next 10 hits
+    2   breakpoint   keep yes   at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    (Pdb) condition 1
+    Breakpoint 1 is now unconditional.
+    (Pdb) enable 1
+    Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
+    (Pdb) clear 1
+    Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
+    (Pdb) commands 2
+    (com) print 42
+    (com) end
+    (Pdb) continue
+    1
+    42
+    > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function()
+    -> print(2)
+    (Pdb) clear
+    Clear all breaks? y
+    Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    (Pdb) tbreak 5
+    Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
+    (Pdb) continue
+    2
+    Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
+    > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
+    -> print(3)
+    (Pdb) break
+    (Pdb) continue
+    3
+    4
+    """
+
+
+def do_nothing():
+    pass
+
+def do_something():
+    print(42)
+
+def test_list_commands():
+    """Test the list and source commands of pdb.
+
+    >>> def test_function_2(foo):
+    ...     import test.test_pdb
+    ...     test.test_pdb.do_nothing()
+    ...     'some...'
+    ...     'more...'
+    ...     'code...'
+    ...     'to...'
+    ...     'make...'
+    ...     'a...'
+    ...     'long...'
+    ...     'listing...'
+    ...     'useful...'
+    ...     '...'
+    ...     '...'
+    ...     return foo
+
+    >>> def test_function():
+    ...     import pdb; pdb.Pdb().set_trace()
+    ...     ret = test_function_2('baz')
+
+    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+    ...     'list',      # list first function
+    ...     'step',      # step into second function
+    ...     'list',      # list second function
+    ...     'list',      # continue listing to EOF
+    ...     'list 1,3',  # list specific lines
+    ...     'list x',    # invalid argument
+    ...     'next',      # step to import
+    ...     'next',      # step over import
+    ...     'step',      # step into do_nothing
+    ...     'longlist',  # list all lines
+    ...     'source do_something',  # list all lines of function
+    ...     'source fooxxx',        # something that doesn't exit
+    ...     'continue',
+    ... ]):
+    ...    test_function()
+    > <doctest test.test_pdb.test_list_commands[1]>(3)test_function()
+    -> ret = test_function_2('baz')
+    (Pdb) list
+      1         def test_function():
+      2             import pdb; pdb.Pdb().set_trace()
+      3  ->         ret = test_function_2('baz')
+    [EOF]
+    (Pdb) step
+    --Call--
+    > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2()
+    -> def test_function_2(foo):
+    (Pdb) list
+      1  ->     def test_function_2(foo):
+      2             import test.test_pdb
+      3             test.test_pdb.do_nothing()
+      4             'some...'
+      5             'more...'
+      6             'code...'
+      7             'to...'
+      8             'make...'
+      9             'a...'
+     10             'long...'
+     11             'listing...'
+    (Pdb) list
+     12             'useful...'
+     13             '...'
+     14             '...'
+     15             return foo
+    [EOF]
+    (Pdb) list 1,3
+      1  ->     def test_function_2(foo):
+      2             import test.test_pdb
+      3             test.test_pdb.do_nothing()
+    (Pdb) list x
+    *** ...
+    (Pdb) next
+    > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2()
+    -> import test.test_pdb
+    (Pdb) next
+    > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2()
+    -> test.test_pdb.do_nothing()
+    (Pdb) step
+    --Call--
+    > ...test_pdb.py(...)do_nothing()
+    -> def do_nothing():
+    (Pdb) longlist
+    ...  ->     def do_nothing():
+    ...             pass
+    (Pdb) source do_something
+    ...         def do_something():
+    ...             print(42)
+    (Pdb) source fooxxx
+    *** ...
+    (Pdb) continue
+    """
+
+
+def test_post_mortem():
+    """Test post mortem traceback debugging.
+
+    >>> def test_function_2():
+    ...     try:
+    ...         1/0
+    ...     finally:
+    ...         print('Exception!')
+
+    >>> def test_function():
+    ...     import pdb; pdb.Pdb().set_trace()
+    ...     test_function_2()
+    ...     print('Not reached.')
+
+    >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+    ...     'next',      # step over exception-raising call
+    ...     'bt',        # get a backtrace
+    ...     'list',      # list code of test_function()
+    ...     'down',      # step into test_function_2()
+    ...     'list',      # list code of test_function_2()
+    ...     'continue',
+    ... ]):
+    ...    try:
+    ...        test_function()
+    ...    except ZeroDivisionError:
+    ...        print('Correctly reraised.')
+    > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
+    -> test_function_2()
+    (Pdb) next
+    Exception!
+    ZeroDivisionError: division by zero
+    > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
+    -> test_function_2()
+    (Pdb) bt
+    ...
+      <doctest test.test_pdb.test_post_mortem[2]>(10)<module>()
+    -> test_function()
+    > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function()
+    -> test_function_2()
+      <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
+    -> 1/0
+    (Pdb) list
+      1         def test_function():
+      2             import pdb; pdb.Pdb().set_trace()
+      3  ->         test_function_2()
+      4             print('Not reached.')
+    [EOF]
+    (Pdb) down
+    > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2()
+    -> 1/0
+    (Pdb) list
+      1         def test_function_2():
+      2             try:
+      3  >>             1/0
+      4             finally:
+      5  ->             print('Exception!')
+    [EOF]
+    (Pdb) continue
+    Correctly reraised.
+    """
+
+
 def test_pdb_skip_modules():
     """This illustrates the simple case of module skipping.
 
@@ -123,9 +492,116 @@
     """
 
 
+def test_pdb_continue_in_bottomframe():
+    """Test that "continue" and "next" work properly in bottom frame (issue #5294).
+
+    >>> def test_function():
+    ...     import pdb, sys; inst = pdb.Pdb()
+    ...     inst.set_trace()
+    ...     inst.botframe = sys._getframe()  # hackery to get the right botframe
+    ...     print(1)
+    ...     print(2)
+    ...     print(3)
+    ...     print(4)
+
+    >>> with PdbTestInput([  # doctest: +ELLIPSIS
+    ...     'next',
+    ...     'break 7',
+    ...     'continue',
+    ...     'next',
+    ...     'continue',
+    ...     'continue',
+    ... ]):
+    ...    test_function()
+    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function()
+    -> inst.botframe = sys._getframe()  # hackery to get the right botframe
+    (Pdb) next
+    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function()
+    -> print(1)
+    (Pdb) break 7
+    Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7
+    (Pdb) continue
+    1
+    2
+    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function()
+    -> print(3)
+    (Pdb) next
+    3
+    > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function()
+    -> print(4)
+    (Pdb) continue
+    4
+    """
+
+
+def pdb_invoke(method, arg):
+    """Run pdb.method(arg)."""
+    import pdb; getattr(pdb, method)(arg)
+
+
+def test_pdb_run_with_incorrect_argument():
+    """Testing run and runeval with incorrect first argument.
+
+    >>> pti = PdbTestInput(['continue',])
+    >>> with pti:
+    ...     pdb_invoke('run', lambda x: x)
+    Traceback (most recent call last):
+    TypeError: exec() arg 1 must be a string, bytes or code object
+
+    >>> with pti:
+    ...     pdb_invoke('runeval', lambda x: x)
+    Traceback (most recent call last):
+    TypeError: eval() arg 1 must be a string, bytes or code object
+    """
+
+
+def test_pdb_run_with_code_object():
+    """Testing run and runeval with code object as a first argument.
+
+    >>> with PdbTestInput(['step','x', 'continue']):  # doctest: +ELLIPSIS
+    ...     pdb_invoke('run', compile('x=1', '<string>', 'exec'))
+    > <string>(1)<module>()...
+    (Pdb) step
+    --Return--
+    > <string>(1)<module>()->None
+    (Pdb) x
+    1
+    (Pdb) continue
+
+    >>> with PdbTestInput(['x', 'continue']):
+    ...     x=0
+    ...     pdb_invoke('runeval', compile('x+1', '<string>', 'eval'))
+    > <string>(1)<module>()->None
+    (Pdb) x
+    1
+    (Pdb) continue
+    """
+
+
+class PdbTestCase(unittest.TestCase):
+
+    def test_issue7964(self):
+        # open the file as binary so we can force \r\n newline
+        with open(support.TESTFN, 'wb') as f:
+            f.write(b'print("testing my pdb")\r\n')
+        cmd = [sys.executable, '-m', 'pdb', support.TESTFN]
+        proc = subprocess.Popen(cmd,
+            stdout=subprocess.PIPE,
+            stdin=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            )
+        stdout, stderr = proc.communicate(b'quit\n')
+        self.assertNotIn(b'SyntaxError', stdout,
+                         "Got a syntax error running test script under PDB")
+
+    def tearDown(self):
+        support.unlink(support.TESTFN)
+
+
 def test_main():
     from test import test_pdb
     support.run_doctest(test_pdb, verbosity=True)
+    support.run_unittest(PdbTestCase)
 
 
 if __name__ == '__main__':

Modified: python/branches/py3k-dtoa/Lib/test/test_platform.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_platform.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_platform.py	Sun Aug  8 12:41:24 2010
@@ -10,20 +10,26 @@
     def test_architecture(self):
         res = platform.architecture()
 
-    if hasattr(os, "symlink"):
-        def test_architecture_via_symlink(self): # issue3762
-            def get(python):
-                cmd = [python, '-c',
-                    'import platform; print(platform.architecture())']
-                p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
-                return p.communicate()
-            real = os.path.realpath(sys.executable)
-            link = os.path.abspath(support.TESTFN)
-            os.symlink(real, link)
-            try:
-                self.assertEqual(get(real), get(link))
-            finally:
-                os.remove(link)
+    @support.skip_unless_symlink
+    def test_architecture_via_symlink(self): # issue3762
+        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
+        # to add the directory to the path.
+        if sys.platform == "win32":
+            os.environ["Path"] = "{};{}".format(
+                os.path.dirname(sys.executable), os.environ["Path"])
+
+        def get(python):
+            cmd = [python, '-c',
+                'import platform; print(platform.architecture())']
+            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+            return p.communicate()
+        real = os.path.realpath(sys.executable)
+        link = os.path.abspath(support.TESTFN)
+        os.symlink(real, link)
+        try:
+            self.assertEqual(get(real), get(link))
+        finally:
+            os.remove(link)
 
     def test_platform(self):
         for aliased in (False, True):
@@ -188,6 +194,25 @@
             else:
                 self.assertEquals(res[2], 'PowerPC')
 
+
+    @unittest.skipUnless(sys.platform == 'darwin', "OSX only test")
+    def test_mac_ver_with_fork(self):
+        # Issue7895: platform.mac_ver() crashes when using fork without exec
+        #
+        # This test checks that the fix for that issue works.
+        #
+        pid = os.fork()
+        if pid == 0:
+            # child
+            info = platform.mac_ver()
+            os._exit(0)
+
+        else:
+            # parent
+            cpid, sts = os.waitpid(pid, 0)
+            self.assertEquals(cpid, pid)
+            self.assertEquals(sts, 0)
+
     def test_dist(self):
         res = platform.dist()
 

Modified: python/branches/py3k-dtoa/Lib/test/test_posix.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_posix.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_posix.py	Sun Aug  8 12:41:24 2010
@@ -6,6 +6,7 @@
 posix = support.import_module('posix')
 
 import errno
+import sys
 import time
 import os
 import pwd
@@ -252,9 +253,14 @@
             posix.chdir(os.curdir)
             self.assertRaises(OSError, posix.chdir, support.TESTFN)
 
-    def test_lsdir(self):
-        if hasattr(posix, 'lsdir'):
-            self.assertIn(support.TESTFN, posix.lsdir(os.curdir))
+    def test_listdir(self):
+        if hasattr(posix, 'listdir'):
+            self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
+
+    def test_listdir_default(self):
+        # When listdir is called without argument, it's the same as listdir(os.curdir)
+        if hasattr(posix, 'listdir'):
+            self.assertTrue(support.TESTFN in posix.listdir())
 
     def test_access(self):
         if hasattr(posix, 'access'):
@@ -344,9 +350,63 @@
                 os.chdir(curdir)
                 support.rmtree(base_path)
 
+    def test_getgroups(self):
+        with os.popen('id -G') as idg:
+            groups = idg.read().strip()
+
+        if not groups:
+            raise unittest.SkipTest("need working 'id -G'")
+
+        # 'id -G' and 'os.getgroups()' should return the same
+        # groups, ignoring order and duplicates.
+        self.assertEqual(
+                set([int(x) for x in groups.split()]),
+                set(posix.getgroups()))
+
+class PosixGroupsTester(unittest.TestCase):
+
+    def setUp(self):
+        if posix.getuid() != 0:
+            raise unittest.SkipTest("not enough privileges")
+        if not hasattr(posix, 'getgroups'):
+            raise unittest.SkipTest("need posix.getgroups")
+        if sys.platform == 'darwin':
+            raise unittest.SkipTest("getgroups(2) is broken on OSX")
+        self.saved_groups = posix.getgroups()
+
+    def tearDown(self):
+        if hasattr(posix, 'setgroups'):
+            posix.setgroups(self.saved_groups)
+        elif hasattr(posix, 'initgroups'):
+            name = pwd.getpwuid(posix.getuid()).pw_name
+            posix.initgroups(name, self.saved_groups[0])
+
+    @unittest.skipUnless(hasattr(posix, 'initgroups'),
+                         "test needs posix.initgroups()")
+    def test_initgroups(self):
+        # find missing group
+
+        groups = sorted(self.saved_groups)
+        for g1,g2 in zip(groups[:-1], groups[1:]):
+            g = g1 + 1
+            if g < g2:
+                break
+        else:
+            g = g2 + 1
+        name = pwd.getpwuid(posix.getuid()).pw_name
+        posix.initgroups(name, g)
+        self.assertIn(g, posix.getgroups())
+
+    @unittest.skipUnless(hasattr(posix, 'setgroups'),
+                         "test needs posix.setgroups()")
+    def test_setgroups(self):
+        for groups in [[0], range(16)]:
+            posix.setgroups(groups)
+            self.assertListEqual(groups, posix.getgroups())
+
 
 def test_main():
-    support.run_unittest(PosixTester)
+    support.run_unittest(PosixTester, PosixGroupsTester)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/py3k-dtoa/Lib/test/test_posixpath.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_posixpath.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_posixpath.py	Sun Aug  8 12:41:24 2010
@@ -1,7 +1,9 @@
 import unittest
 from test import support, test_genericpath
 
-import posixpath, os
+import posixpath
+import os
+import sys
 from posixpath import realpath, abspath, dirname, basename
 
 # An absolute path to a temporary filename for testing. We can't rely on TESTFN
@@ -9,6 +11,16 @@
 
 ABSTFN = abspath(support.TESTFN)
 
+def skip_if_ABSTFN_contains_backslash(test):
+    """
+    On Windows, posixpath.abspath still returns paths with backslashes
+    instead of posix forward slashes. If this is the case, several tests
+    fail, so skip them.
+    """
+    found_backslash = '\\' in ABSTFN
+    msg = "ABSTFN is not a posix path - tests fail"
+    return [test, unittest.skip(msg)(test)][found_backslash]
+
 def safe_rmdir(dirname):
     try:
         os.rmdir(dirname)
@@ -143,7 +155,7 @@
             f.write(b"foo")
             f.close()
             self.assertIs(posixpath.islink(support.TESTFN + "1"), False)
-            if hasattr(os, "symlink"):
+            if support.can_symlink():
                 os.symlink(support.TESTFN + "1", support.TESTFN + "2")
                 self.assertIs(posixpath.islink(support.TESTFN + "2"), True)
                 os.remove(support.TESTFN + "1")
@@ -154,85 +166,60 @@
             if not f.close():
                 f.close()
 
+    @staticmethod
+    def _create_file(filename):
+        with open(filename, 'wb') as f:
+            f.write(b'foo')
+
     def test_samefile(self):
-        f = open(support.TESTFN + "1", "wb")
-        try:
-            f.write(b"foo")
-            f.close()
-            self.assertIs(
-                posixpath.samefile(
-                    support.TESTFN + "1",
-                    support.TESTFN + "1"
-                ),
-                True
-            )
-            # If we don't have links, assume that os.stat doesn't return resonable
-            # inode information and thus, that samefile() doesn't work
-            if hasattr(os, "symlink"):
-                os.symlink(
-                    support.TESTFN + "1",
-                    support.TESTFN + "2"
-                )
-                self.assertIs(
-                    posixpath.samefile(
-                        support.TESTFN + "1",
-                        support.TESTFN + "2"
-                    ),
-                    True
-                )
-                os.remove(support.TESTFN + "2")
-                f = open(support.TESTFN + "2", "wb")
-                f.write(b"bar")
-                f.close()
-                self.assertIs(
-                    posixpath.samefile(
-                        support.TESTFN + "1",
-                        support.TESTFN + "2"
-                    ),
-                    False
-                )
-        finally:
-            if not f.close():
-                f.close()
+        test_fn = support.TESTFN + "1"
+        self._create_file(test_fn)
+        self.assertTrue(posixpath.samefile(test_fn, test_fn))
+        self.assertRaises(TypeError, posixpath.samefile)
+
+    @unittest.skipIf(
+        sys.platform.startswith('win'),
+        "posixpath.samefile does not work on links in Windows")
+    @support.skip_unless_symlink
+    def test_samefile_on_links(self):
+        test_fn1 = support.TESTFN + "1"
+        test_fn2 = support.TESTFN + "2"
+        self._create_file(test_fn1)
+
+        os.symlink(test_fn1, test_fn2)
+        self.assertTrue(posixpath.samefile(test_fn1, test_fn2))
+        os.remove(test_fn2)
+
+        self._create_file(test_fn2)
+        self.assertFalse(posixpath.samefile(test_fn1, test_fn2))
+
 
     def test_samestat(self):
-        f = open(support.TESTFN + "1", "wb")
-        try:
-            f.write(b"foo")
-            f.close()
-            self.assertIs(
-                posixpath.samestat(
-                    os.stat(support.TESTFN + "1"),
-                    os.stat(support.TESTFN + "1")
-                ),
-                True
-            )
-            # If we don't have links, assume that os.stat() doesn't return resonable
-            # inode information and thus, that samefile() doesn't work
-            if hasattr(os, "symlink"):
-                if hasattr(os, "symlink"):
-                    os.symlink(support.TESTFN + "1", support.TESTFN + "2")
-                    self.assertIs(
-                        posixpath.samestat(
-                            os.stat(support.TESTFN + "1"),
-                            os.stat(support.TESTFN + "2")
-                        ),
-                        True
-                    )
-                    os.remove(support.TESTFN + "2")
-                f = open(support.TESTFN + "2", "wb")
-                f.write(b"bar")
-                f.close()
-                self.assertIs(
-                    posixpath.samestat(
-                        os.stat(support.TESTFN + "1"),
-                        os.stat(support.TESTFN + "2")
-                    ),
-                    False
-                )
-        finally:
-            if not f.close():
-                f.close()
+        test_fn = support.TESTFN + "1"
+        self._create_file(test_fn)
+        test_fns = [test_fn]*2
+        stats = map(os.stat, test_fns)
+        self.assertTrue(posixpath.samestat(*stats))
+
+    @unittest.skipIf(
+        sys.platform.startswith('win'),
+        "posixpath.samestat does not work on links in Windows")
+    @support.skip_unless_symlink
+    def test_samestat_on_links(self):
+        test_fn1 = support.TESTFN + "1"
+        test_fn2 = support.TESTFN + "2"
+        self._create_file(test_fn1)
+        test_fns = (test_fn1, test_fn2)
+        os.symlink(*test_fns)
+        stats = map(os.stat, test_fns)
+        self.assertTrue(posixpath.samestat(*stats))
+        os.remove(test_fn2)
+
+        self._create_file(test_fn2)
+        stats = map(os.stat, test_fns)
+        self.assertFalse(posixpath.samestat(*stats))
+
+        self.assertRaises(TypeError, posixpath.samestat)
 
     def test_ismount(self):
         self.assertIs(posixpath.ismount("/"), True)
@@ -286,103 +273,112 @@
         self.assertEqual(posixpath.normpath(b"///..//./foo/.//bar"),
                          b"/foo/bar")
 
-    if hasattr(os, "symlink"):
-        def test_realpath_basic(self):
-            # Basic operation.
-            try:
-                os.symlink(ABSTFN+"1", ABSTFN)
-                self.assertEqual(realpath(ABSTFN), ABSTFN+"1")
-            finally:
-                support.unlink(ABSTFN)
-
-        def test_realpath_symlink_loops(self):
-            # Bug #930024, return the path unchanged if we get into an infinite
-            # symlink loop.
-            try:
-                old_path = abspath('.')
-                os.symlink(ABSTFN, ABSTFN)
-                self.assertEqual(realpath(ABSTFN), ABSTFN)
-
-                os.symlink(ABSTFN+"1", ABSTFN+"2")
-                os.symlink(ABSTFN+"2", ABSTFN+"1")
-                self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1")
-                self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2")
-
-                # Test using relative path as well.
-                os.chdir(dirname(ABSTFN))
-                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
-            finally:
-                os.chdir(old_path)
-                support.unlink(ABSTFN)
-                support.unlink(ABSTFN+"1")
-                support.unlink(ABSTFN+"2")
-
-        def test_realpath_resolve_parents(self):
-            # We also need to resolve any symlinks in the parents of a relative
-            # path passed to realpath. E.g.: current working directory is
-            # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
-            # realpath("a"). This should return /usr/share/doc/a/.
-            try:
-                old_path = abspath('.')
-                os.mkdir(ABSTFN)
-                os.mkdir(ABSTFN + "/y")
-                os.symlink(ABSTFN + "/y", ABSTFN + "/k")
-
-                os.chdir(ABSTFN + "/k")
-                self.assertEqual(realpath("a"), ABSTFN + "/y/a")
-            finally:
-                os.chdir(old_path)
-                support.unlink(ABSTFN + "/k")
-                safe_rmdir(ABSTFN + "/y")
-                safe_rmdir(ABSTFN)
-
-        def test_realpath_resolve_before_normalizing(self):
-            # Bug #990669: Symbolic links should be resolved before we
-            # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
-            # in the following hierarchy:
-            # a/k/y
-            #
-            # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
-            # then realpath("link-y/..") should return 'k', not 'a'.
-            try:
-                old_path = abspath('.')
-                os.mkdir(ABSTFN)
-                os.mkdir(ABSTFN + "/k")
-                os.mkdir(ABSTFN + "/k/y")
-                os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")
-
-                # Absolute path.
-                self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
-                # Relative path.
-                os.chdir(dirname(ABSTFN))
-                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
-                                 ABSTFN + "/k")
-            finally:
-                os.chdir(old_path)
-                support.unlink(ABSTFN + "/link-y")
-                safe_rmdir(ABSTFN + "/k/y")
-                safe_rmdir(ABSTFN + "/k")
-                safe_rmdir(ABSTFN)
-
-        def test_realpath_resolve_first(self):
-            # Bug #1213894: The first component of the path, if not absolute,
-            # must be resolved too.
-
-            try:
-                old_path = abspath('.')
-                os.mkdir(ABSTFN)
-                os.mkdir(ABSTFN + "/k")
-                os.symlink(ABSTFN, ABSTFN + "link")
-                os.chdir(dirname(ABSTFN))
-
-                base = basename(ABSTFN)
-                self.assertEqual(realpath(base + "link"), ABSTFN)
-                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
-            finally:
-                os.chdir(old_path)
-                support.unlink(ABSTFN + "link")
-                safe_rmdir(ABSTFN + "/k")
-                safe_rmdir(ABSTFN)
+    @support.skip_unless_symlink
+    @skip_if_ABSTFN_contains_backslash
+    def test_realpath_basic(self):
+        # Basic operation.
+        try:
+            os.symlink(ABSTFN+"1", ABSTFN)
+            self.assertEqual(realpath(ABSTFN), ABSTFN+"1")
+        finally:
+            support.unlink(ABSTFN)
+
+    @support.skip_unless_symlink
+    @skip_if_ABSTFN_contains_backslash
+    def test_realpath_symlink_loops(self):
+        # Bug #930024, return the path unchanged if we get into an infinite
+        # symlink loop.
+        try:
+            old_path = abspath('.')
+            os.symlink(ABSTFN, ABSTFN)
+            self.assertEqual(realpath(ABSTFN), ABSTFN)
+
+            os.symlink(ABSTFN+"1", ABSTFN+"2")
+            os.symlink(ABSTFN+"2", ABSTFN+"1")
+            self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1")
+            self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2")
+
+            # Test using relative path as well.
+            os.chdir(dirname(ABSTFN))
+            self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
+        finally:
+            os.chdir(old_path)
+            support.unlink(ABSTFN)
+            support.unlink(ABSTFN+"1")
+            support.unlink(ABSTFN+"2")
+
+    @support.skip_unless_symlink
+    @skip_if_ABSTFN_contains_backslash
+    def test_realpath_resolve_parents(self):
+        # We also need to resolve any symlinks in the parents of a relative
+        # path passed to realpath. E.g.: current working directory is
+        # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
+        # realpath("a"). This should return /usr/share/doc/a/.
+        try:
+            old_path = abspath('.')
+            os.mkdir(ABSTFN)
+            os.mkdir(ABSTFN + "/y")
+            os.symlink(ABSTFN + "/y", ABSTFN + "/k")
+
+            os.chdir(ABSTFN + "/k")
+            self.assertEqual(realpath("a"), ABSTFN + "/y/a")
+        finally:
+            os.chdir(old_path)
+            support.unlink(ABSTFN + "/k")
+            safe_rmdir(ABSTFN + "/y")
+            safe_rmdir(ABSTFN)
+
+    @support.skip_unless_symlink
+    @skip_if_ABSTFN_contains_backslash
+    def test_realpath_resolve_before_normalizing(self):
+        # Bug #990669: Symbolic links should be resolved before we
+        # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
+        # in the following hierarchy:
+        # a/k/y
+        #
+        # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
+        # then realpath("link-y/..") should return 'k', not 'a'.
+        try:
+            old_path = abspath('.')
+            os.mkdir(ABSTFN)
+            os.mkdir(ABSTFN + "/k")
+            os.mkdir(ABSTFN + "/k/y")
+            os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")
+
+            # Absolute path.
+            self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
+            # Relative path.
+            os.chdir(dirname(ABSTFN))
+            self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
+                             ABSTFN + "/k")
+        finally:
+            os.chdir(old_path)
+            support.unlink(ABSTFN + "/link-y")
+            safe_rmdir(ABSTFN + "/k/y")
+            safe_rmdir(ABSTFN + "/k")
+            safe_rmdir(ABSTFN)
+
+    @support.skip_unless_symlink
+    @skip_if_ABSTFN_contains_backslash
+    def test_realpath_resolve_first(self):
+        # Bug #1213894: The first component of the path, if not absolute,
+        # must be resolved too.
+
+        try:
+            old_path = abspath('.')
+            os.mkdir(ABSTFN)
+            os.mkdir(ABSTFN + "/k")
+            os.symlink(ABSTFN, ABSTFN + "link")
+            os.chdir(dirname(ABSTFN))
+
+            base = basename(ABSTFN)
+            self.assertEqual(realpath(base + "link"), ABSTFN)
+            self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
+        finally:
+            os.chdir(old_path)
+            support.unlink(ABSTFN + "link")
+            safe_rmdir(ABSTFN + "/k")
+            safe_rmdir(ABSTFN)
 
     def test_relpath(self):
         (real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar")

Modified: python/branches/py3k-dtoa/Lib/test/test_pow.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_pow.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_pow.py	Sun Aug  8 12:41:24 2010
@@ -18,14 +18,14 @@
                 self.assertEquals(pow(2, i), pow2)
                 if i != 30 : pow2 = pow2*2
 
-            for othertype in int, int:
+            for othertype in (int,):
                 for i in list(range(-10, 0)) + list(range(1, 10)):
                     ii = type(i)
                     for j in range(1, 11):
                         jj = -othertype(j)
                         pow(ii, jj)
 
-        for othertype in int, int, float:
+        for othertype in int, float:
             for i in range(1, 100):
                 zero = type(0)
                 exp = -othertype(i/10.0)

Deleted: python/branches/py3k-dtoa/Lib/test/test_profilehooks.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_profilehooks.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,385 +0,0 @@
-import pprint
-import sys
-import unittest
-
-from test import support
-
-class TestGetProfile(unittest.TestCase):
-    def setUp(self):
-        sys.setprofile(None)
-
-    def tearDown(self):
-        sys.setprofile(None)
-
-    def test_empty(self):
-        assert sys.getprofile() is None
-
-    def test_setget(self):
-        def fn(*args):
-            pass
-
-        sys.setprofile(fn)
-        assert sys.getprofile() == fn
-
-class HookWatcher:
-    def __init__(self):
-        self.frames = []
-        self.events = []
-
-    def callback(self, frame, event, arg):
-        if (event == "call"
-            or event == "return"
-            or event == "exception"):
-            self.add_event(event, frame)
-
-    def add_event(self, event, frame=None):
-        """Add an event to the log."""
-        if frame is None:
-            frame = sys._getframe(1)
-
-        try:
-            frameno = self.frames.index(frame)
-        except ValueError:
-            frameno = len(self.frames)
-            self.frames.append(frame)
-
-        self.events.append((frameno, event, ident(frame)))
-
-    def get_events(self):
-        """Remove calls to add_event()."""
-        disallowed = [ident(self.add_event.__func__), ident(ident)]
-        self.frames = None
-
-        return [item for item in self.events if item[2] not in disallowed]
-
-
-class ProfileSimulator(HookWatcher):
-    def __init__(self, testcase):
-        self.testcase = testcase
-        self.stack = []
-        HookWatcher.__init__(self)
-
-    def callback(self, frame, event, arg):
-        # Callback registered with sys.setprofile()/sys.settrace()
-        self.dispatch[event](self, frame)
-
-    def trace_call(self, frame):
-        self.add_event('call', frame)
-        self.stack.append(frame)
-
-    def trace_return(self, frame):
-        self.add_event('return', frame)
-        self.stack.pop()
-
-    def trace_exception(self, frame):
-        self.testcase.fail(
-            "the profiler should never receive exception events")
-
-    def trace_pass(self, frame):
-        pass
-
-    dispatch = {
-        'call': trace_call,
-        'exception': trace_exception,
-        'return': trace_return,
-        'c_call': trace_pass,
-        'c_return': trace_pass,
-        'c_exception': trace_pass,
-        }
-
-
-class TestCaseBase(unittest.TestCase):
-    def check_events(self, callable, expected):
-        events = capture_events(callable, self.new_watcher())
-        if events != expected:
-            self.fail("Expected events:\n%s\nReceived events:\n%s"
-                      % (pprint.pformat(expected), pprint.pformat(events)))
-
-
-class ProfileHookTestCase(TestCaseBase):
-    def new_watcher(self):
-        return HookWatcher()
-
-    def test_simple(self):
-        def f(p):
-            pass
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_exception(self):
-        def f(p):
-            1/0
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_caught_exception(self):
-        def f(p):
-            try: 1/0
-            except: pass
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_caught_nested_exception(self):
-        def f(p):
-            try: 1/0
-            except: pass
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_nested_exception(self):
-        def f(p):
-            1/0
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              # This isn't what I expected:
-                              # (0, 'exception', protect_ident),
-                              # I expected this again:
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_exception_in_except_clause(self):
-        def f(p):
-            1/0
-        def g(p):
-            try:
-                f(p)
-            except:
-                try: f(p)
-                except: pass
-        f_ident = ident(f)
-        g_ident = ident(g)
-        self.check_events(g, [(1, 'call', g_ident),
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              (3, 'call', f_ident),
-                              (3, 'return', f_ident),
-                              (1, 'return', g_ident),
-                              ])
-
-    def test_exception_propogation(self):
-        def f(p):
-            1/0
-        def g(p):
-            try: f(p)
-            finally: p.add_event("falling through")
-        f_ident = ident(f)
-        g_ident = ident(g)
-        self.check_events(g, [(1, 'call', g_ident),
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              (1, 'falling through', g_ident),
-                              (1, 'return', g_ident),
-                              ])
-
-    def test_raise_twice(self):
-        def f(p):
-            try: 1/0
-            except: 1/0
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_raise_reraise(self):
-        def f(p):
-            try: 1/0
-            except: raise
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_raise(self):
-        def f(p):
-            raise Exception()
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_distant_exception(self):
-        def f():
-            1/0
-        def g():
-            f()
-        def h():
-            g()
-        def i():
-            h()
-        def j(p):
-            i()
-        f_ident = ident(f)
-        g_ident = ident(g)
-        h_ident = ident(h)
-        i_ident = ident(i)
-        j_ident = ident(j)
-        self.check_events(j, [(1, 'call', j_ident),
-                              (2, 'call', i_ident),
-                              (3, 'call', h_ident),
-                              (4, 'call', g_ident),
-                              (5, 'call', f_ident),
-                              (5, 'return', f_ident),
-                              (4, 'return', g_ident),
-                              (3, 'return', h_ident),
-                              (2, 'return', i_ident),
-                              (1, 'return', j_ident),
-                              ])
-
-    def test_generator(self):
-        def f():
-            for i in range(2):
-                yield i
-        def g(p):
-            for i in f():
-                pass
-        f_ident = ident(f)
-        g_ident = ident(g)
-        self.check_events(g, [(1, 'call', g_ident),
-                              # call the iterator twice to generate values
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              # once more; returns end-of-iteration with
-                              # actually raising an exception
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              (1, 'return', g_ident),
-                              ])
-
-    def test_stop_iteration(self):
-        def f():
-            for i in range(2):
-                yield i
-            raise StopIteration
-        def g(p):
-            for i in f():
-                pass
-        f_ident = ident(f)
-        g_ident = ident(g)
-        self.check_events(g, [(1, 'call', g_ident),
-                              # call the iterator twice to generate values
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              # once more to hit the raise:
-                              (2, 'call', f_ident),
-                              (2, 'return', f_ident),
-                              (1, 'return', g_ident),
-                              ])
-
-
-class ProfileSimulatorTestCase(TestCaseBase):
-    def new_watcher(self):
-        return ProfileSimulator(self)
-
-    def test_simple(self):
-        def f(p):
-            pass
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_basic_exception(self):
-        def f(p):
-            1/0
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_caught_exception(self):
-        def f(p):
-            try: 1/0
-            except: pass
-        f_ident = ident(f)
-        self.check_events(f, [(1, 'call', f_ident),
-                              (1, 'return', f_ident),
-                              ])
-
-    def test_distant_exception(self):
-        def f():
-            1/0
-        def g():
-            f()
-        def h():
-            g()
-        def i():
-            h()
-        def j(p):
-            i()
-        f_ident = ident(f)
-        g_ident = ident(g)
-        h_ident = ident(h)
-        i_ident = ident(i)
-        j_ident = ident(j)
-        self.check_events(j, [(1, 'call', j_ident),
-                              (2, 'call', i_ident),
-                              (3, 'call', h_ident),
-                              (4, 'call', g_ident),
-                              (5, 'call', f_ident),
-                              (5, 'return', f_ident),
-                              (4, 'return', g_ident),
-                              (3, 'return', h_ident),
-                              (2, 'return', i_ident),
-                              (1, 'return', j_ident),
-                              ])
-
-
-def ident(function):
-    if hasattr(function, "f_code"):
-        code = function.f_code
-    else:
-        code = function.__code__
-    return code.co_firstlineno, code.co_name
-
-
-def protect(f, p):
-    try: f(p)
-    except: pass
-
-protect_ident = ident(protect)
-
-
-def capture_events(callable, p=None):
-    try:
-        sys.setprofile()
-    except TypeError:
-        pass
-    else:
-        raise support.TestFailed(
-            'sys.setprofile() did not raise TypeError')
-
-    if p is None:
-        p = HookWatcher()
-    sys.setprofile(p.callback)
-    protect(callable, p)
-    sys.setprofile(None)
-    return p.get_events()[1:-1]
-
-
-def show_events(callable):
-    import pprint
-    pprint.pprint(capture_events(callable))
-
-
-def test_main():
-    support.run_unittest(
-        TestGetProfile,
-        ProfileHookTestCase,
-        ProfileSimulatorTestCase
-    )
-
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/py3k-dtoa/Lib/test/test_pstats.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_pstats.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_pstats.py	Sun Aug  8 12:41:24 2010
@@ -10,10 +10,16 @@
     def test_combine_results(self):
         """pstats.add_callers should combine the call results of both target
         and source by adding the call time. See issue1269."""
+        # new format: used by the cProfile module
         target = {"a": (1, 2, 3, 4)}
         source = {"a": (1, 2, 3, 4), "b": (5, 6, 7, 8)}
         new_callers = pstats.add_callers(target, source)
         self.assertEqual(new_callers, {'a': (2, 4, 6, 8), 'b': (5, 6, 7, 8)})
+        # old format: used by the profile module
+        target = {"a": 1}
+        source = {"a": 1, "b": 5}
+        new_callers = pstats.add_callers(target, source)
+        self.assertEqual(new_callers, {'a': 2, 'b': 5})
 
 
 def test_main():

Modified: python/branches/py3k-dtoa/Lib/test/test_queue.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_queue.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_queue.py	Sun Aug  8 12:41:24 2010
@@ -90,6 +90,8 @@
     def simple_queue_test(self, q):
         if q.qsize():
             raise RuntimeError("Call this function with an empty queue")
+        self.assertTrue(q.empty())
+        self.assertFalse(q.full())
         # I guess we better check things actually queue correctly a little :)
         q.put(111)
         q.put(333)
@@ -108,6 +110,8 @@
         full = 3 * 2 * QUEUE_SIZE
         q.put(last)
         self.assertTrue(qfull(q), "Queue should be full")
+        self.assertFalse(q.empty())
+        self.assertTrue(q.full())
         try:
             q.put(full, block=0)
             self.fail("Didn't appear to block with a full queue")
@@ -193,6 +197,25 @@
         self.simple_queue_test(q)
         self.simple_queue_test(q)
 
+    def test_negative_timeout_raises_exception(self):
+        q = self.type2test(QUEUE_SIZE)
+        with self.assertRaises(ValueError):
+            q.put(1, timeout=-1)
+        with self.assertRaises(ValueError):
+            q.get(1, timeout=-1)
+
+    def test_nowait(self):
+        q = self.type2test(QUEUE_SIZE)
+        for i in range(QUEUE_SIZE):
+            q.put_nowait(1)
+        with self.assertRaises(queue.Full):
+            q.put_nowait(1)
+
+        for i in range(QUEUE_SIZE):
+            q.get_nowait()
+        with self.assertRaises(queue.Empty):
+            q.get_nowait()
+
 
 class QueueTest(BaseQueueTest):
     type2test = queue.Queue

Modified: python/branches/py3k-dtoa/Lib/test/test_re.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_re.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_re.py	Sun Aug  8 12:41:24 2010
@@ -874,8 +874,71 @@
                 if result is None:
                     print('=== Fails on unicode-sensitive match', t)
 
+
+class ReCacheTests(unittest.TestCase):
+    """These tests are specific to the re._shrink_cache implementation."""
+
+    def setUp(self):
+        self._orig_maxcache = re._MAXCACHE
+
+    def tearDown(self):
+        re._MAXCACHE = self._orig_maxcache
+
+    def test_compile_cache_overflow(self):
+        # NOTE: If a profiler or debugger is tracing code and compiling
+        # regular expressions while tracing through this test... expect
+        # the test to fail.  This test is not concurrency safe.
+
+        # Explicitly fill the caches.
+        re._MAXCACHE = 20
+        max_cache = re._MAXCACHE
+        unique_chars = tuple(chr(char_num) for char_num in
+                             range(b'a'[0], b'a'[0]+max_cache))
+        re._cache.clear()
+        for char in unique_chars:
+            re._compile(char, 0)
+        self.assertEqual(max_cache, len(re._cache))
+        re._cache_repl.clear()
+        for char in unique_chars:
+            re._compile_repl(char*2, char)
+        self.assertEqual(max_cache, len(re._cache_repl))
+
+        # Overflow both caches and make sure they have extra room left
+        # afterwards as well as having more than a single entry.
+        re._compile('A', 0)
+        self.assertLess(len(re._cache), max_cache)
+        self.assertGreater(len(re._cache), 1)
+        re._compile_repl('A', 'A')
+        self.assertLess(len(re._cache_repl), max_cache)
+        self.assertGreater(len(re._cache_repl), 1)
+
+    def test_shrink_cache_at_limit(self):
+        cache = dict(zip(range(6), range(6)))
+        re._shrink_cache(cache, 6, divisor=3)
+        self.assertEqual(4, len(cache))
+
+    def test_shrink_cache_empty(self):
+        cache = {}
+        re._shrink_cache(cache, 6, divisor=3)
+        # Cache was empty, make sure we didn't raise an exception.
+        self.assertEqual(0, len(cache))
+
+    def test_shrink_cache_overflowing(self):
+        cache = dict(zip(range(6), range(6)))
+        re._shrink_cache(cache, 4, divisor=2)
+        # Cache was larger than the maximum, be sure we shrunk to smaller.
+        self.assertEqual(2, len(cache))
+
+    def test_shrink_cache_underflow(self):
+        cache = dict(zip(range(6), range(6)))
+        # No shrinking to do.
+        re._shrink_cache(cache, 9, divisor=3)
+        self.assertEqual(6, len(cache))
+
+
 def test_main():
     run_unittest(ReTests)
+    run_unittest(ReCacheTests)
     run_re_tests()
 
 if __name__ == "__main__":

Modified: python/branches/py3k-dtoa/Lib/test/test_robotparser.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_robotparser.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_robotparser.py	Sun Aug  8 12:41:24 2010
@@ -205,6 +205,31 @@
 RobotTest(13, doc, good, bad, agent="googlebot")
 
 
+# 14. For issue #6325 (query string support)
+doc = """
+User-agent: *
+Disallow: /some/path?name=value
+"""
+
+good = ['/some/path']
+bad = ['/some/path?name=value']
+
+RobotTest(14, doc, good, bad)
+
+# 15. For issue #4108 (obey first * entry)
+doc = """
+User-agent: *
+Disallow: /some/path
+
+User-agent: *
+Disallow: /another/path
+"""
+
+good = ['/another/path']
+bad = ['/some/path']
+
+RobotTest(15, doc, good, bad)
+
 
 class NetworkTestCase(unittest.TestCase):
 

Modified: python/branches/py3k-dtoa/Lib/test/test_sax.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_sax.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_sax.py	Sun Aug  8 12:41:24 2010
@@ -18,6 +18,11 @@
 
 TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata")
 TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata")
+try:
+    TEST_XMLFILE.encode("utf8")
+    TEST_XMLFILE_OUT.encode("utf8")
+except UnicodeEncodeError:
+    raise unittest.SkipTest("filename is not encodable to utf8")
 
 ns_uri = "http://www.python.org/xml-ns/saxtest/"
 

Modified: python/branches/py3k-dtoa/Lib/test/test_set.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_set.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_set.py	Sun Aug  8 12:41:24 2010
@@ -796,7 +796,7 @@
         result = self.set ^ self.set
         self.assertEqual(result, empty_set)
 
-    def checkempty_symmetric_difference(self):
+    def test_empty_symmetric_difference(self):
         result = self.set ^ empty_set
         self.assertEqual(result, self.set)
 

Modified: python/branches/py3k-dtoa/Lib/test/test_shutil.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_shutil.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_shutil.py	Sun Aug  8 12:41:24 2010
@@ -271,7 +271,7 @@
             shutil.rmtree(src_dir)
             shutil.rmtree(os.path.dirname(dst_dir))
 
-    @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
+    @support.skip_unless_symlink
     def test_dont_copy_file_onto_link_to_itself(self):
         # bug 851123.
         os.mkdir(TESTFN)
@@ -282,10 +282,11 @@
             f.write('cheddar')
             f.close()
 
-            os.link(src, dst)
-            self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
-            self.assertEqual(open(src,'r').read(), 'cheddar')
-            os.remove(dst)
+            if hasattr(os, "link"):
+                os.link(src, dst)
+                self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
+                self.assertEqual(open(src,'r').read(), 'cheddar')
+                os.remove(dst)
 
             # Using `src` here would mean we end up with a symlink pointing
             # to TESTFN/TESTFN/cheese, while it should point at
@@ -300,30 +301,30 @@
             except OSError:
                 pass
 
-        @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
-        def test_rmtree_on_symlink(self):
-            # bug 1669.
-            os.mkdir(TESTFN)
+    @support.skip_unless_symlink
+    def test_rmtree_on_symlink(self):
+        # bug 1669.
+        os.mkdir(TESTFN)
+        try:
+            src = os.path.join(TESTFN, 'cheese')
+            dst = os.path.join(TESTFN, 'shop')
+            os.mkdir(src)
+            os.symlink(src, dst)
+            self.assertRaises(OSError, shutil.rmtree, dst)
+        finally:
+            shutil.rmtree(TESTFN, ignore_errors=True)
+
+    if hasattr(os, "mkfifo"):
+        # Issue #3002: copyfile and copytree block indefinitely on named pipes
+        def test_copyfile_named_pipe(self):
+            os.mkfifo(TESTFN)
             try:
-                src = os.path.join(TESTFN, 'cheese')
-                dst = os.path.join(TESTFN, 'shop')
-                os.mkdir(src)
-                os.symlink(src, dst)
-                self.assertRaises(OSError, shutil.rmtree, dst)
+                self.assertRaises(shutil.SpecialFileError,
+                                  shutil.copyfile, TESTFN, TESTFN2)
+                self.assertRaises(shutil.SpecialFileError,
+                                  shutil.copyfile, __file__, TESTFN)
             finally:
-                shutil.rmtree(TESTFN, ignore_errors=True)
-
-    @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo')
-    # Issue #3002: copyfile and copytree block indefinitely on named pipes
-    def test_copyfile_named_pipe(self):
-        os.mkfifo(TESTFN)
-        try:
-            self.assertRaises(shutil.SpecialFileError,
-                                shutil.copyfile, TESTFN, TESTFN2)
-            self.assertRaises(shutil.SpecialFileError,
-                                shutil.copyfile, __file__, TESTFN)
-        finally:
-            os.remove(TESTFN)
+                os.remove(TESTFN)
 
     @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo')
     def test_copytree_named_pipe(self):
@@ -361,7 +362,7 @@
         shutil.copytree(src_dir, dst_dir, copy_function=_copy)
         self.assertEquals(len(copied), 2)
 
-    @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink')
+    @support.skip_unless_symlink
     def test_copytree_dangling_symlinks(self):
 
         # a dangling symlink raises an error at the end

Modified: python/branches/py3k-dtoa/Lib/test/test_signal.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_signal.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_signal.py	Sun Aug  8 12:41:24 2010
@@ -9,7 +9,7 @@
 import traceback
 import sys, os, time, errno
 
-if sys.platform[:3] in ('win', 'os2') or sys.platform == 'riscos':
+if sys.platform == 'os2' or sys.platform == 'riscos':
     raise unittest.SkipTest("Can't test signal on %s" % \
                                    sys.platform)
 
@@ -37,6 +37,7 @@
         return None
 
 
+ at unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
 class InterProcessSignalTests(unittest.TestCase):
     MAX_DURATION = 20   # Entire test should last at most 20 sec.
 
@@ -186,6 +187,7 @@
                           self.MAX_DURATION)
 
 
+ at unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
 class BasicSignalTests(unittest.TestCase):
     def trivial_signal_handler(self, *args):
         pass
@@ -208,6 +210,25 @@
         self.assertEquals(signal.getsignal(signal.SIGHUP), hup)
 
 
+ at unittest.skipUnless(sys.platform == "win32", "Windows specific")
+class WindowsSignalTests(unittest.TestCase):
+    def test_issue9324(self):
+        handler = lambda x, y: None
+        signal.signal(signal.SIGABRT, handler)
+        signal.signal(signal.SIGFPE, handler)
+        signal.signal(signal.SIGILL, handler)
+        signal.signal(signal.SIGINT, handler)
+        signal.signal(signal.SIGSEGV, handler)
+        signal.signal(signal.SIGTERM, handler)
+
+        with self.assertRaises(ValueError):
+            signal.signal(-1, handler)
+
+        with self.assertRaises(ValueError):
+            signal.signal(7, handler)
+
+
+ at unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
 class WakeupSignalTests(unittest.TestCase):
     TIMEOUT_FULL = 10
     TIMEOUT_HALF = 5
@@ -253,14 +274,15 @@
         os.close(self.write)
         signal.signal(signal.SIGALRM, self.alrm)
 
+ at unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
 class SiginterruptTest(unittest.TestCase):
-    signum = signal.SIGUSR1
 
     def setUp(self):
         """Install a no-op signal handler that can be set to allow
         interrupts or not, and arrange for the original signal handler to be
         re-installed when the test is finished.
         """
+        self.signum = signal.SIGUSR1
         oldhandler = signal.signal(self.signum, lambda x,y: None)
         self.addCleanup(signal.signal, self.signum, oldhandler)
 
@@ -354,7 +376,7 @@
         self.assertFalse(i)
 
 
-
+ at unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
 class ItimerTest(unittest.TestCase):
     def setUp(self):
         self.hndl_called = False
@@ -464,7 +486,8 @@
 
 def test_main():
     support.run_unittest(BasicSignalTests, InterProcessSignalTests,
-        WakeupSignalTests, SiginterruptTest, ItimerTest)
+                         WakeupSignalTests, SiginterruptTest,
+                         ItimerTest, WindowsSignalTests)
 
 
 if __name__ == "__main__":

Modified: python/branches/py3k-dtoa/Lib/test/test_site.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_site.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_site.py	Sun Aug  8 12:41:24 2010
@@ -185,13 +185,10 @@
             sysconfig.get_config_var("PYTHONFRAMEWORK")):
             site.PREFIXES = ['Python.framework']
             dirs = site.getsitepackages()
-            self.assertEqual(len(dirs), 4)
-            wanted = os.path.join('~', 'Library', 'Python',
-                                  sys.version[:3], 'site-packages')
-            self.assertEquals(dirs[2], os.path.expanduser(wanted))
+            self.assertEqual(len(dirs), 3)
             wanted = os.path.join('/Library', 'Python', sys.version[:3],
                                   'site-packages')
-            self.assertEquals(dirs[3], wanted)
+            self.assertEquals(dirs[2], wanted)
 
 class PthFile(object):
     """Helper class for handling testing of .pth files"""

Modified: python/branches/py3k-dtoa/Lib/test/test_smtplib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_smtplib.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_smtplib.py	Sun Aug  8 12:41:24 2010
@@ -9,7 +9,7 @@
 import select
 
 import unittest
-from test import support
+from test import support, mock_socket
 
 try:
     import threading
@@ -48,53 +48,48 @@
         serv.close()
         evt.set()
 
- at unittest.skipUnless(threading, 'Threading required for this test.')
 class GeneralTests(unittest.TestCase):
 
     def setUp(self):
-        self._threads = support.threading_setup()
-        self.evt = threading.Event()
-        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self.sock.settimeout(15)
-        self.port = support.bind_port(self.sock)
-        servargs = (self.evt, b"220 Hola mundo\n", self.sock)
-        self.thread = threading.Thread(target=server, args=servargs)
-        self.thread.start()
-        self.evt.wait()
-        self.evt.clear()
+        smtplib.socket = mock_socket
+        self.port = 25
 
     def tearDown(self):
-        self.evt.wait()
-        self.thread.join()
-        support.threading_cleanup(*self._threads)
+        smtplib.socket = socket
 
     def testBasic1(self):
+        mock_socket.reply_with(b"220 Hola mundo")
         # connects
         smtp = smtplib.SMTP(HOST, self.port)
         smtp.close()
 
     def testBasic2(self):
+        mock_socket.reply_with(b"220 Hola mundo")
         # connects, include port in host name
         smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
         smtp.close()
 
     def testLocalHostName(self):
+        mock_socket.reply_with(b"220 Hola mundo")
         # check that supplied local_hostname is used
         smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
         self.assertEqual(smtp.local_hostname, "testhost")
         smtp.close()
 
     def testTimeoutDefault(self):
-        self.assertTrue(socket.getdefaulttimeout() is None)
-        socket.setdefaulttimeout(30)
+        mock_socket.reply_with(b"220 Hola mundo")
+        self.assertTrue(mock_socket.getdefaulttimeout() is None)
+        mock_socket.setdefaulttimeout(30)
+        self.assertEqual(mock_socket.getdefaulttimeout(), 30)
         try:
             smtp = smtplib.SMTP(HOST, self.port)
         finally:
-            socket.setdefaulttimeout(None)
+            mock_socket.setdefaulttimeout(None)
         self.assertEqual(smtp.sock.gettimeout(), 30)
         smtp.close()
 
     def testTimeoutNone(self):
+        mock_socket.reply_with(b"220 Hola mundo")
         self.assertTrue(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(30)
         try:
@@ -105,6 +100,7 @@
         smtp.close()
 
     def testTimeoutValue(self):
+        mock_socket.reply_with(b"220 Hola mundo")
         smtp = smtplib.SMTP(HOST, self.port, timeout=30)
         self.assertEqual(smtp.sock.gettimeout(), 30)
         smtp.close()
@@ -155,6 +151,8 @@
 class DebuggingServerTests(unittest.TestCase):
 
     def setUp(self):
+        self.real_getfqdn = socket.getfqdn
+        socket.getfqdn = mock_socket.getfqdn
         # temporarily replace sys.stdout to capture DebuggingServer output
         self.old_stdout = sys.stdout
         self.output = io.StringIO()
@@ -176,6 +174,7 @@
         self.serv_evt.clear()
 
     def tearDown(self):
+        socket.getfqdn = self.real_getfqdn
         # indicate that the client is finished
         self.client_evt.set()
         # wait for the server thread to terminate
@@ -251,6 +250,12 @@
 
 class NonConnectingTests(unittest.TestCase):
 
+    def setUp(self):
+        smtplib.socket = mock_socket
+
+    def tearDown(self):
+        smtplib.socket = socket
+
     def testNotConnected(self):
         # Test various operations on an unconnected SMTP object that
         # should raise exceptions (at present the attempt in SMTP.send
@@ -263,9 +268,9 @@
 
     def testNonnumericPort(self):
         # check that non-numeric port raises socket.error
-        self.assertRaises(socket.error, smtplib.SMTP,
+        self.assertRaises(mock_socket.error, smtplib.SMTP,
                           "localhost", "bogus")
-        self.assertRaises(socket.error, smtplib.SMTP,
+        self.assertRaises(mock_socket.error, smtplib.SMTP,
                           "localhost:bogus")
 
 
@@ -274,25 +279,15 @@
 class BadHELOServerTests(unittest.TestCase):
 
     def setUp(self):
+        smtplib.socket = mock_socket
+        mock_socket.reply_with(b"199 no hello for you!")
         self.old_stdout = sys.stdout
         self.output = io.StringIO()
         sys.stdout = self.output
-
-        self._threads = support.threading_setup()
-        self.evt = threading.Event()
-        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self.sock.settimeout(15)
-        self.port = support.bind_port(self.sock)
-        servargs = (self.evt, b"199 no hello for you!\n", self.sock)
-        self.thread = threading.Thread(target=server, args=servargs)
-        self.thread.start()
-        self.evt.wait()
-        self.evt.clear()
+        self.port = 25
 
     def tearDown(self):
-        self.evt.wait()
-        self.thread.join()
-        support.threading_cleanup(*self._threads)
+        smtplib.socket = socket
         sys.stdout = self.old_stdout
 
     def testFailingHELO(self):
@@ -405,6 +400,8 @@
 class SMTPSimTests(unittest.TestCase):
 
     def setUp(self):
+        self.real_getfqdn = socket.getfqdn
+        socket.getfqdn = mock_socket.getfqdn
         self._threads = support.threading_setup()
         self.serv_evt = threading.Event()
         self.client_evt = threading.Event()
@@ -421,6 +418,7 @@
         self.serv_evt.clear()
 
     def tearDown(self):
+        socket.getfqdn = self.real_getfqdn
         # indicate that the client is finished
         self.client_evt.set()
         # wait for the server thread to terminate

Modified: python/branches/py3k-dtoa/Lib/test/test_ssl.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_ssl.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_ssl.py	Sun Aug  8 12:41:24 2010
@@ -15,6 +15,8 @@
 import traceback
 import asyncore
 import weakref
+import platform
+import functools
 
 from http.server import HTTPServer, SimpleHTTPRequestHandler
 
@@ -65,6 +67,20 @@
     return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15)
 
 
+# Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2
+def skip_if_broken_ubuntu_ssl(func):
+    @functools.wraps(func)
+    def f(*args, **kwargs):
+        try:
+            ssl.SSLContext(ssl.PROTOCOL_SSLv2)
+        except ssl.SSLError:
+            if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
+                platform.linux_distribution() == ('debian', 'squeeze/sid', '')):
+                raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
+        return func(*args, **kwargs)
+    return f
+
+
 class BasicSocketTests(unittest.TestCase):
 
     def test_constants(self):
@@ -175,6 +191,7 @@
 
 class ContextTests(unittest.TestCase):
 
+    @skip_if_broken_ubuntu_ssl
     def test_constructor(self):
         ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2)
         ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
@@ -184,6 +201,7 @@
         self.assertRaises(ValueError, ssl.SSLContext, -1)
         self.assertRaises(ValueError, ssl.SSLContext, 42)
 
+    @skip_if_broken_ubuntu_ssl
     def test_protocol(self):
         for proto in PROTOCOLS:
             ctx = ssl.SSLContext(proto)
@@ -196,6 +214,7 @@
         with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
             ctx.set_ciphers("^$:,;?*'dorothyx")
 
+    @skip_if_broken_ubuntu_ssl
     def test_options(self):
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         # OP_ALL is the default value
@@ -937,6 +956,7 @@
 
     class ThreadedTests(unittest.TestCase):
 
+        @skip_if_broken_ubuntu_ssl
         def test_echo(self):
             """Basic test of an SSL client connecting to a server"""
             if support.verbose:
@@ -1039,6 +1059,7 @@
             finally:
                 t.join()
 
+        @skip_if_broken_ubuntu_ssl
         def test_protocol_sslv2(self):
             """Connecting to an SSLv2 server with various client options"""
             if support.verbose:
@@ -1059,6 +1080,7 @@
             try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True,
                                client_options=ssl.OP_NO_TLSv1)
 
+        @skip_if_broken_ubuntu_ssl
         def test_protocol_sslv23(self):
             """Connecting to an SSLv23 server with various client options"""
             if support.verbose:
@@ -1093,6 +1115,7 @@
                                server_options=ssl.OP_NO_TLSv1)
 
 
+        @skip_if_broken_ubuntu_ssl
         def test_protocol_sslv3(self):
             """Connecting to an SSLv3 server with various client options"""
             if support.verbose:
@@ -1108,6 +1131,7 @@
                 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True,
                                    client_options=ssl.OP_NO_SSLv2)
 
+        @skip_if_broken_ubuntu_ssl
         def test_protocol_tlsv1(self):
             """Connecting to a TLSv1 server with various client options"""
             if support.verbose:
@@ -1424,6 +1448,23 @@
     if skip_expected:
         raise unittest.SkipTest("No SSL support")
 
+    if support.verbose:
+        plats = {
+            'Linux': platform.linux_distribution,
+            'Mac': platform.mac_ver,
+            'Windows': platform.win32_ver,
+        }
+        for name, func in plats.items():
+            plat = func()
+            if plat and plat[0]:
+                plat = '%s %r' % (name, plat)
+                break
+        else:
+            plat = repr(platform.platform())
+        print("test_ssl: testing with %r %r" %
+            (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
+        print("          under %s" % plat)
+
     for filename in [
         CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE,
         ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,

Modified: python/branches/py3k-dtoa/Lib/test/test_struct.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_struct.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_struct.py	Sun Aug  8 12:41:24 2010
@@ -47,8 +47,8 @@
 
         self.assertRaises(struct.error, struct.pack, 'iii', 3)
         self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
-        self.assertRaises(struct.error, struct.pack, 'i', 'foo')
-        self.assertRaises(struct.error, struct.pack, 'P', 'foo')
+        self.assertRaises((TypeError, struct.error), struct.pack, 'i', 'foo')
+        self.assertRaises((TypeError, struct.error), struct.pack, 'P', 'foo')
         self.assertRaises(struct.error, struct.unpack, 'd', b'flap')
         s = struct.pack('ii', 1, 2)
         self.assertRaises(struct.error, struct.unpack, 'iii', s)
@@ -213,6 +213,7 @@
                     expected = '%x' % expected
                     if len(expected) & 1:
                         expected = "0" + expected
+                    expected = expected.encode('ascii')
                     expected = unhexlify(expected)
                     expected = (b"\x00" * (self.bytesize - len(expected)) +
                                 expected)
@@ -234,7 +235,8 @@
                                                                  b'\x01' + got)
                 else:
                     # x is out of range -- verify pack realizes that.
-                    self.assertRaises(struct.error, pack, format, x)
+                    self.assertRaises((OverflowError, ValueError, struct.error),
+                                      pack, format, x)
 
             def run(self):
                 from random import randrange
@@ -438,12 +440,15 @@
 
         # Go beyond boundaries.
         small_buf = array.array('b', b' '*10)
-        self.assertRaises(struct.error, s.pack_into, small_buf, 0, test_string)
-        self.assertRaises(struct.error, s.pack_into, small_buf, 2, test_string)
+        self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0,
+                          test_string)
+        self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2,
+                          test_string)
 
         # Test bogus offset (issue 3694)
         sb = small_buf
-        self.assertRaises(TypeError, struct.pack_into, b'', sb, None)
+        self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb,
+                          None)
 
     def test_pack_into_fn(self):
         test_string = b'Reykjavik rocks, eow!'
@@ -463,8 +468,10 @@
 
         # Go beyond boundaries.
         small_buf = array.array('b', b' '*10)
-        self.assertRaises(struct.error, pack_into, small_buf, 0, test_string)
-        self.assertRaises(struct.error, pack_into, small_buf, 2, test_string)
+        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
+                          test_string)
+        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
+                          test_string)
 
     def test_unpack_with_buffer(self):
         # SF bug 1563759: struct.unpack doens't support buffer protocol objects
@@ -475,6 +482,9 @@
             self.assertEqual(value, 0x12345678)
 
     def test_bool(self):
+        class ExplodingBool(object):
+            def __bool__(self):
+                raise IOError
         for prefix in tuple("<>!=")+('',):
             false = (), [], [], '', 0
             true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2
@@ -503,8 +513,16 @@
                 self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
                                              %packed)
 
-            for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
-                self.assertTrue(struct.unpack('>?', c)[0])
+            try:
+                struct.pack(prefix + '?', ExplodingBool())
+            except IOError:
+                pass
+            else:
+                self.fail("Expected IOError: struct.pack(%r, "
+                          "ExplodingBool())" % (prefix + '?'))
+
+        for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
+            self.assertTrue(struct.unpack('>?', c)[0])
 
     def test_count_overflow(self):
         hugecount = '{}b'.format(sys.maxsize+1)
@@ -542,7 +560,12 @@
                           'spam and eggs')
         self.assertRaises(struct.error, struct.unpack_from, '14s42', store, 0)
 
-
+    def test_Struct_reinitialization(self):
+        # Issue 9422: there was a memory leak when reinitializing a
+        # Struct instance.  This test can be used to detect the leak
+        # when running with regrtest -L.
+        s = struct.Struct('i')
+        s.__init__('ii')
 
 def test_main():
     run_unittest(StructTest)

Modified: python/branches/py3k-dtoa/Lib/test/test_structseq.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_structseq.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_structseq.py	Sun Aug  8 12:41:24 2010
@@ -1,12 +1,14 @@
+import os
+import time
 import unittest
 from test import support
 
-import time
 
 class StructSeqTest(unittest.TestCase):
 
     def test_tuple(self):
         t = time.gmtime()
+        self.assertIsInstance(t, tuple)
         astuple = tuple(t)
         self.assertEqual(len(t), len(astuple))
         self.assertEqual(t, astuple)
@@ -33,6 +35,13 @@
         self.assertEqual(repr(t),
             "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, "
             "tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)")
+        # os.stat() gives a complicated struct sequence.
+        st = os.stat(__file__)
+        rep = repr(st)
+        self.assertTrue(rep.startswith(os.name + ".stat_result"))
+        self.assertIn("st_mode=", rep)
+        self.assertIn("st_ino=", rep)
+        self.assertIn("st_dev=", rep)
 
     def test_concat(self):
         t1 = time.gmtime()

Modified: python/branches/py3k-dtoa/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_subprocess.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_subprocess.py	Sun Aug  8 12:41:24 2010
@@ -53,7 +53,7 @@
         # In a debug build, stuff like "[6580 refs]" is printed to stderr at
         # shutdown time.  That frustrates tests trying to check stderr produced
         # from a spawned Python process.
-        actual = re.sub("\[\d+ refs\]\r?\n?$", "", stderr.decode()).encode()
+        actual = support.strip_python_stderr(stderr)
         self.assertEqual(actual, expected, msg)
 
 
@@ -544,6 +544,26 @@
         output = subprocess.check_output([sys.executable, '-c', code])
         self.assert_(output.startswith(b'Hello World!'), ascii(output))
 
+    def test_handles_closed_on_exception(self):
+        # If CreateProcess exits with an error, ensure the
+        # duplicate output handles are released
+        ifhandle, ifname = mkstemp()
+        ofhandle, ofname = mkstemp()
+        efhandle, efname = mkstemp()
+        try:
+            subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
+              stderr=efhandle)
+        except OSError:
+            os.close(ifhandle)
+            os.remove(ifname)
+            os.close(ofhandle)
+            os.remove(ofname)
+            os.close(efhandle)
+            os.remove(efname)
+        self.assertFalse(os.path.exists(ifname))
+        self.assertFalse(os.path.exists(ofname))
+        self.assertFalse(os.path.exists(efname))
+
 
 # context manager
 class _SuppressCoreFiles(object):
@@ -559,6 +579,21 @@
         except (ImportError, ValueError, resource.error):
             pass
 
+        if sys.platform == 'darwin':
+            # Check if the 'Crash Reporter' on OSX was configured
+            # in 'Developer' mode and warn that it will get triggered
+            # when it is.
+            #
+            # This assumes that this context manager is used in tests
+            # that might trigger the next manager.
+            value = subprocess.Popen(['/usr/bin/defaults', 'read',
+                    'com.apple.CrashReporter', 'DialogType'],
+                    stdout=subprocess.PIPE).communicate()[0]
+            if value.strip() == b'developer':
+                print("this tests triggers the Crash Reporter, "
+                      "that is intentional", end='')
+                sys.stdout.flush()
+
     def __exit__(self, *args):
         """Return core file behavior to default."""
         if self.old_limit is None:
@@ -750,6 +785,25 @@
         os.remove(fname)
         self.assertEqual(rc, 47)
 
+    def test_specific_shell(self):
+        # Issue #9265: Incorrect name passed as arg[0].
+        shells = []
+        for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
+            for name in ['bash', 'ksh']:
+                sh = os.path.join(prefix, name)
+                if os.path.isfile(sh):
+                    shells.append(sh)
+        if not shells: # Will probably work for any shell but csh.
+            self.skipTest("bash or ksh required for this test")
+        sh = '/bin/sh'
+        if os.path.isfile(sh) and not os.path.islink(sh):
+            # Test will fail if /bin/sh is a symlink to csh.
+            shells.append(sh)
+        for sh in shells:
+            p = subprocess.Popen("echo $0", executable=sh, shell=True,
+                                 stdout=subprocess.PIPE)
+            self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
+
     def _kill_process(self, method, *args):
         # Do not inherit file handles from the parent.
         # It should fix failures on some platforms.

Modified: python/branches/py3k-dtoa/Lib/test/test_sundry.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_sundry.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_sundry.py	Sun Aug  8 12:41:24 2010
@@ -54,11 +54,8 @@
             import nturl2path
             import opcode
             import os2emxpath
-            import pdb
             import pstats
             import py_compile
-            import rlcompleter
-            import sched
             import sndhdr
             import symbol
             import tabnanny

Modified: python/branches/py3k-dtoa/Lib/test/test_sys.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_sys.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_sys.py	Sun Aug  8 12:41:24 2010
@@ -86,7 +86,6 @@
     # Python/pythonrun.c::PyErr_PrintEx() is tricky.
 
     def test_exit(self):
-        import subprocess
 
         self.assertRaises(TypeError, sys.exit, 42, 42)
 
@@ -179,8 +178,8 @@
         # can't check more than the type, as the user might have changed it
         self.assertIsInstance(sys.getdefaultencoding(), str)
 
-    # testing sys.settrace() is done in test_trace.py
-    # testing sys.setprofile() is done in test_profile.py
+    # testing sys.settrace() is done in test_sys_settrace.py
+    # testing sys.setprofile() is done in test_sys_setprofile.py
 
     def test_setcheckinterval(self):
         with warnings.catch_warnings():
@@ -510,8 +509,10 @@
         p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE)
         stdout, stderr = p.communicate()
         self.assertEqual(p.returncode, 1)
-        self.assert_(b"UnicodeEncodeError:" in stderr,
-            "%r not in %s" % (b"UniodeEncodeError:", ascii(stderr)))
+        self.assertIn(
+            br"UnicodeEncodeError: 'utf-8' codec can't encode character "
+            br"'\udcff' in position 7: surrogates not allowed",
+            stderr)
 
     def test_sys_flags(self):
         self.assertTrue(sys.flags)
@@ -529,7 +530,6 @@
         sys._clear_type_cache()
 
     def test_ioencoding(self):
-        import subprocess
         env = dict(os.environ)
 
         # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
@@ -551,7 +551,7 @@
         # 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
         # retrieve the real program name
-        import subprocess
+
         # For a normal installation, it should work without 'cwd'
         # argument. For test runs in the build directory, see #7774.
         python_dir = os.path.dirname(os.path.realpath(sys.executable))

Modified: python/branches/py3k-dtoa/Lib/test/test_sysconfig.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_sysconfig.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_sysconfig.py	Sun Aug  8 12:41:24 2010
@@ -12,7 +12,7 @@
 from copy import copy, deepcopy
 
 from test.support import (run_unittest, TESTFN, unlink, get_attribute,
-                          captured_stdout)
+                          captured_stdout, skip_unless_symlink)
 
 import sysconfig
 from sysconfig import (get_paths, get_platform, get_config_vars,
@@ -239,17 +239,23 @@
                   'posix_home', 'posix_prefix', 'posix_user')
         self.assertEquals(get_scheme_names(), wanted)
 
+    @skip_unless_symlink
     def test_symlink(self):
+        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
+        # to add the directory to the path.
+        if sys.platform == "win32":
+            os.environ["Path"] = "{};{}".format(
+                os.path.dirname(sys.executable), os.environ["Path"])
+
         # Issue 7880
-        symlink = get_attribute(os, "symlink")
         def get(python):
             cmd = [python, '-c',
                    'import sysconfig; print(sysconfig.get_platform())']
-            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=os.environ)
             return p.communicate()
         real = os.path.realpath(sys.executable)
         link = os.path.abspath(TESTFN)
-        symlink(real, link)
+        os.symlink(real, link)
         try:
             self.assertEqual(get(real), get(link))
         finally:
@@ -271,6 +277,13 @@
             _main()
         self.assertTrue(len(output.getvalue().split('\n')) > 0)
 
+    @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
+    def test_ldshared_value(self):
+        ldflags = sysconfig.get_config_var('LDFLAGS')
+        ldshared = sysconfig.get_config_var('LDSHARED')
+
+        self.assertIn(ldflags, ldshared)
+
 
 def test_main():
     run_unittest(TestSysConfig)

Modified: python/branches/py3k-dtoa/Lib/test/test_tarfile.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_tarfile.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_tarfile.py	Sun Aug  8 12:41:24 2010
@@ -291,6 +291,9 @@
         self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
                 "could not find all members")
 
+    @unittest.skipUnless(hasattr(os, "link"),
+                         "Missing hardlink implementation")
+    @support.skip_unless_symlink
     def test_extract_hardlink(self):
         # Test hardlink extraction (e.g. bug #857297).
         tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
@@ -695,16 +698,16 @@
                 os.remove(target)
                 os.remove(link)
 
+    @support.skip_unless_symlink
     def test_symlink_size(self):
-        if hasattr(os, "symlink"):
-            path = os.path.join(TEMPDIR, "symlink")
-            os.symlink("link_target", path)
-            try:
-                tar = tarfile.open(tmpname, self.mode)
-                tarinfo = tar.gettarinfo(path)
-                self.assertEqual(tarinfo.size, 0)
-            finally:
-                os.remove(path)
+        path = os.path.join(TEMPDIR, "symlink")
+        os.symlink("link_target", path)
+        try:
+            tar = tarfile.open(tmpname, self.mode)
+            tarinfo = tar.gettarinfo(path)
+            self.assertEqual(tarinfo.size, 0)
+        finally:
+            os.remove(path)
 
     def test_add_self(self):
         # Test for #1257255.
@@ -1408,15 +1411,26 @@
         data = open(os.path.join(TEMPDIR, name), "rb").read()
         self.assertEqual(md5sum(data), md5_regtype)
 
+    # When 8879 gets fixed, this will need to change. Currently on Windows
+    # we have os.path.islink but no os.link, so these tests fail without the
+    # following skip until link is completed.
+    @unittest.skipIf(hasattr(os.path, "islink"),
+                     "Skip emulation - has os.path.islink but not os.link")
     def test_hardlink_extraction1(self):
         self._test_link_extraction("ustar/lnktype")
 
+    @unittest.skipIf(hasattr(os.path, "islink"),
+                     "Skip emulation - has os.path.islink but not os.link")
     def test_hardlink_extraction2(self):
         self._test_link_extraction("./ustar/linktest2/lnktype")
 
+    @unittest.skipIf(hasattr(os, "symlink"),
+                     "Skip emulation if symlink exists")
     def test_symlink_extraction1(self):
         self._test_link_extraction("ustar/symtype")
 
+    @unittest.skipIf(hasattr(os, "symlink"),
+                     "Skip emulation if symlink exists")
     def test_symlink_extraction2(self):
         self._test_link_extraction("./ustar/linktest2/symtype")
 

Modified: python/branches/py3k-dtoa/Lib/test/test_tcl.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_tcl.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_tcl.py	Sun Aug  8 12:41:24 2010
@@ -143,7 +143,7 @@
                                     fullname[0],
                                     fullname[3:])
 
-        with test_support.EnvironmentVarGuard() as env:
+        with support.EnvironmentVarGuard() as env:
             env.unset("TCL_LIBRARY")
             f = os.popen('%s -c "import Tkinter; print Tkinter"' % (unc_name,))
 

Modified: python/branches/py3k-dtoa/Lib/test/test_threaded_import.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_threaded_import.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_threaded_import.py	Sun Aug  8 12:41:24 2010
@@ -5,72 +5,77 @@
 # complains several times about module random having no attribute
 # randrange, and then Python hangs.
 
+import imp
+import sys
 import unittest
-from test.support import verbose, TestFailed, import_module
+from test.support import verbose, TestFailed, import_module, run_unittest
 thread = import_module('_thread')
 
-critical_section = thread.allocate_lock()
-done = thread.allocate_lock()
+def task(N, done, done_tasks, errors):
+    try:
+        import random
+        # This will fail if random is not completely initialized
+        x = random.randrange(1, 3)
+    except Exception as e:
+        errors.append(e.with_traceback(None))
+    finally:
+        done_tasks.append(thread.get_ident())
+        finished = len(done_tasks) == N
+        if finished:
+            done.release()
+
+
+class ThreadedImportTests(unittest.TestCase):
+
+    def setUp(self):
+        self.old_random = sys.modules.pop('random', None)
+
+    def tearDown(self):
+        # If the `random` module was already initialized, we restore the
+        # old module at the end so that pickling tests don't fail.
+        # See http://bugs.python.org/issue3657#msg110461
+        if self.old_random is not None:
+            sys.modules['random'] = self.old_random
+
+    def test_parallel_module_init(self):
+        if imp.lock_held():
+            # This triggers on, e.g., from test import autotest.
+            raise unittest.SkipTest("can't run when import lock is held")
 
-def task():
-    global N, critical_section, done
-    import random
-    x = random.randrange(1, 3)
-    critical_section.acquire()
-    N -= 1
-    # Must release critical_section before releasing done, else the main
-    # thread can exit and set critical_section to None as part of global
-    # teardown; then critical_section.release() raises AttributeError.
-    finished = N == 0
-    critical_section.release()
-    if finished:
+        done = thread.allocate_lock()
+        done.acquire()
+        for N in (20, 50) * 3:
+            if verbose:
+                print("Trying", N, "threads ...", end=' ')
+            # Make sure that random gets reimported freshly
+            try:
+                del sys.modules['random']
+            except KeyError:
+                pass
+            errors = []
+            done_tasks = []
+            for i in range(N):
+                thread.start_new_thread(task, (N, done, done_tasks, errors,))
+            done.acquire()
+            self.assertFalse(errors)
+            if verbose:
+                print("OK.")
         done.release()
 
-def test_import_hangers():
-    import sys
-    if verbose:
-        print("testing import hangers ...", end=' ')
-
-    import test.threaded_import_hangers
-    try:
-        if test.threaded_import_hangers.errors:
-            raise TestFailed(test.threaded_import_hangers.errors)
-        elif verbose:
-            print("OK.")
-    finally:
+    def test_import_hangers(self):
         # In case this test is run again, make sure the helper module
         # gets loaded from scratch again.
-        del sys.modules['test.threaded_import_hangers']
+        try:
+            del sys.modules['test.threaded_import_hangers']
+        except KeyError:
+            pass
+        import test.threaded_import_hangers
+        self.assertFalse(test.threaded_import_hangers.errors)
 
-# Tricky:  When regrtest imports this module, the thread running regrtest
-# grabs the import lock and won't let go of it until this module returns.
-# All other threads attempting an import hang for the duration.  Since
-# this test spawns threads that do little *but* import, we can't do that
-# successfully until after this module finishes importing and regrtest
-# regains control.  To make this work, a special case was added to
-# regrtest to invoke a module's "test_main" function (if any) after
-# importing it.
-
-def test_main():        # magic name!  see above
-    global N, done
-
-    import imp
-    if imp.lock_held():
-        # This triggers on, e.g., from test import autotest.
-        raise unittest.SkipTest("can't run when import lock is held")
-
-    done.acquire()
-    for N in (20, 50) * 3:
-        if verbose:
-            print("Trying", N, "threads ...", end=' ')
-        for i in range(N):
-            thread.start_new_thread(task, ())
-        done.acquire()
-        if verbose:
-            print("OK.")
-    done.release()
 
-    test_import_hangers()
+def test_main():
+    run_unittest(ThreadedImportTests)
+
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/py3k-dtoa/Lib/test/test_threading.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_threading.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_threading.py	Sun Aug  8 12:41:24 2010
@@ -1,7 +1,7 @@
 # Very rudimentary test of threading module
 
 import test.support
-from test.support import verbose
+from test.support import verbose, strip_python_stderr
 import random
 import re
 import sys
@@ -97,7 +97,8 @@
             self.assertTrue(not t.is_alive())
             self.assertNotEqual(t.ident, 0)
             self.assertFalse(t.ident is None)
-            self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
+            self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
+                                     repr(t)))
         if verbose:
             print('all tasks done')
         self.assertEqual(numrunning.get(), 0)
@@ -349,7 +350,7 @@
         stdout, stderr = p.communicate()
         self.assertEqual(stdout.strip(),
             b"Woke up, sleep function is: <built-in function sleep>")
-        stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip()
+        stderr = strip_python_stderr(stderr)
         self.assertEqual(stderr, b"")
 
     def test_enumerate_after_join(self):
@@ -413,6 +414,12 @@
         e.isSet()
         threading.activeCount()
 
+    def test_repr_daemon(self):
+        t = threading.Thread()
+        self.assertFalse('daemon' in repr(t))
+        t.daemon = True
+        self.assertTrue('daemon' in repr(t))
+
 
 class ThreadJoinOnShutdown(BaseTestCase):
 

Modified: python/branches/py3k-dtoa/Lib/test/test_threading_local.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_threading_local.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_threading_local.py	Sun Aug  8 12:41:24 2010
@@ -1,10 +1,15 @@
 import unittest
 from doctest import DocTestSuite
 from test import support
-threading = support.import_module('threading')
 import weakref
 import gc
 
+# Modules under test
+_thread = support.import_module('_thread')
+threading = support.import_module('threading')
+import _threading_local
+
+
 class Weak(object):
     pass
 
@@ -13,7 +18,8 @@
     local.weak = weak
     weaklist.append(weakref.ref(weak))
 
-class ThreadingLocalTest(unittest.TestCase):
+
+class BaseLocalTest:
 
     def test_local_refs(self):
         self._local_refs(20)
@@ -21,7 +27,7 @@
         self._local_refs(100)
 
     def _local_refs(self, n):
-        local = threading.local()
+        local = self._local()
         weaklist = []
         for i in range(n):
             t = threading.Thread(target=target, args=(local, weaklist))
@@ -48,7 +54,7 @@
         # is created but not correctly set on the object.
         # The first member set may be bogus.
         import time
-        class Local(threading.local):
+        class Local(self._local):
             def __init__(self):
                 time.sleep(0.01)
         local = Local()
@@ -69,7 +75,7 @@
 
     def test_derived_cycle_dealloc(self):
         # http://bugs.python.org/issue6990
-        class Local(threading.local):
+        class Local(self._local):
             pass
         locals = None
         passed = False
@@ -108,39 +114,37 @@
 
     def test_arguments(self):
         # Issue 1522237
-        from _thread import _local as local
-        from _threading_local import local as py_local
+        class MyLocal(self._local):
+            def __init__(self, *args, **kwargs):
+                pass
+
+        MyLocal(a=1)
+        MyLocal(1)
+        self.assertRaises(TypeError, self._local, a=1)
+        self.assertRaises(TypeError, self._local, 1)
+
+
+class ThreadLocalTest(unittest.TestCase, BaseLocalTest):
+    _local = _thread._local
 
-        for cls in (local, py_local):
-            class MyLocal(cls):
-                def __init__(self, *args, **kwargs):
-                    pass
-
-            MyLocal(a=1)
-            MyLocal(1)
-            self.assertRaises(TypeError, cls, a=1)
-            self.assertRaises(TypeError, cls, 1)
+class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest):
+    _local = _threading_local.local
 
 
 def test_main():
     suite = unittest.TestSuite()
     suite.addTest(DocTestSuite('_threading_local'))
-    suite.addTest(unittest.makeSuite(ThreadingLocalTest))
+    suite.addTest(unittest.makeSuite(ThreadLocalTest))
+    suite.addTest(unittest.makeSuite(PyThreadingLocalTest))
 
-    try:
-        from thread import _local
-    except ImportError:
-        pass
-    else:
-        import _threading_local
-        local_orig = _threading_local.local
-        def setUp(test):
-            _threading_local.local = _local
-        def tearDown(test):
-            _threading_local.local = local_orig
-        suite.addTest(DocTestSuite('_threading_local',
-                                   setUp=setUp, tearDown=tearDown)
-                      )
+    local_orig = _threading_local.local
+    def setUp(test):
+        _threading_local.local = _thread._local
+    def tearDown(test):
+        _threading_local.local = local_orig
+    suite.addTest(DocTestSuite('_threading_local',
+                               setUp=setUp, tearDown=tearDown)
+                  )
 
     support.run_unittest(suite)
 

Modified: python/branches/py3k-dtoa/Lib/test/test_tokenize.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_tokenize.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_tokenize.py	Sun Aug  8 12:41:24 2010
@@ -598,11 +598,11 @@
 
     The format of the exponent is inherited from the platform C library.
     Known cases are "e-007" (Windows) and "e-07" (not Windows).  Since
-    we're only showing 12 digits, and the 13th isn't close to 5, the
+    we're only showing 11 digits, and the 12th isn't close to 5, the
     rest of the output should be platform-independent.
 
     >>> exec(s) #doctest: +ELLIPSIS
-    -3.21716034272e-0...7
+    -3.2171603427...e-0...7
 
     Output from calculations with Decimal should be identical across all
     platforms.

Modified: python/branches/py3k-dtoa/Lib/test/test_unicode.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_unicode.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_unicode.py	Sun Aug  8 12:41:24 2010
@@ -757,6 +757,7 @@
         self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
         self.assertEqual('%c' % '\U00021483', '\U00021483')
         self.assertRaises(TypeError, "%c".__mod__, "aa")
+        self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
 
         # formatting jobs delegated from the string implementation:
         self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')

Modified: python/branches/py3k-dtoa/Lib/test/test_unicodedata.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_unicodedata.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_unicodedata.py	Sun Aug  8 12:41:24 2010
@@ -80,8 +80,7 @@
 class UnicodeFunctionsTest(UnicodeDatabaseTest):
 
     # update this, if the database changes
-    expectedchecksum = '6ccf1b1a36460d2694f9b0b0f0324942fe70ede6'
-
+    expectedchecksum = 'e89a6380093a00a7685ac7b92e7367d737fcb79b'
     def test_function_checksum(self):
         data = []
         h = hashlib.sha1()
@@ -90,9 +89,9 @@
             char = chr(i)
             data = [
                 # Properties
-                str(self.db.digit(char, -1)),
-                str(self.db.numeric(char, -1)),
-                str(self.db.decimal(char, -1)),
+                format(self.db.digit(char, -1), '.12g'),
+                format(self.db.numeric(char, -1), '.12g'),
+                format(self.db.decimal(char, -1), '.12g'),
                 self.db.category(char),
                 self.db.bidirectional(char),
                 self.db.decomposition(char),

Modified: python/branches/py3k-dtoa/Lib/test/test_unpack.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_unpack.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_unpack.py	Sun Aug  8 12:41:24 2010
@@ -62,14 +62,14 @@
     >>> a, b = t
     Traceback (most recent call last):
       ...
-    ValueError: too many values to unpack
+    ValueError: too many values to unpack (expected 2)
 
 Unpacking tuple of wrong size
 
     >>> a, b = l
     Traceback (most recent call last):
       ...
-    ValueError: too many values to unpack
+    ValueError: too many values to unpack (expected 2)
 
 Unpacking sequence too short
 
@@ -83,7 +83,7 @@
     >>> a, b = Seq()
     Traceback (most recent call last):
       ...
-    ValueError: too many values to unpack
+    ValueError: too many values to unpack (expected 2)
 
 Unpacking a sequence where the test for too long raises a different kind of
 error

Modified: python/branches/py3k-dtoa/Lib/test/test_urllib.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_urllib.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_urllib.py	Sun Aug  8 12:41:24 2010
@@ -190,6 +190,17 @@
         finally:
             self.unfakehttp()
 
+    def test_userpass_inurl(self):
+        self.fakehttp(b"Hello!")
+        try:
+            fp = urlopen("http://user:pass@python.org/")
+            self.assertEqual(fp.readline(), b"Hello!")
+            self.assertEqual(fp.readline(), b"")
+            self.assertEqual(fp.geturl(), 'http://user:pass@python.org/')
+            self.assertEqual(fp.getcode(), 200)
+        finally:
+            self.unfakehttp()
+
 class urlretrieve_FileTests(unittest.TestCase):
     """Test urllib.urlretrieve() on local files"""
 
@@ -221,8 +232,12 @@
             except: pass
 
     def constructLocalFileUrl(self, filePath):
-        return "file://%s" % urllib.request.pathname2url(
-            os.path.abspath(filePath))
+        filePath = os.path.abspath(filePath)
+        try:
+            filePath.encode("utf8")
+        except UnicodeEncodeError:
+            raise unittest.SkipTest("filePath is not encodable to utf8")
+        return "file://%s" % urllib.request.pathname2url(filePath)
 
     def createNewTempFile(self, data=b""):
         """Creates a new temporary file containing the specified data,
@@ -527,6 +542,7 @@
         self.assertEqual(expect, result,
                          "using quote_plus(): %r != %r" % (expect, result))
 
+
 class UnquotingTests(unittest.TestCase):
     """Tests for unquote() and unquote_plus()
 
@@ -554,6 +570,9 @@
         self.assertEqual(result.count('%'), 1,
                          "using unquote(): not all characters escaped: "
                          "%s" % result)
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, b'')
 
     def test_unquoting_badpercent(self):
         # Test unquoting on bad percent-escapes
@@ -588,6 +607,8 @@
         result = urllib.parse.unquote_to_bytes(given)
         self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
                          % (expect, result))
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None)
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ())
 
     def test_unquoting_mixed_case(self):
         # Test unquoting on mixed-case hex digits in the percent-escapes

Modified: python/branches/py3k-dtoa/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_urllib2.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_urllib2.py	Sun Aug  8 12:41:24 2010
@@ -597,6 +597,10 @@
 
 
 def sanepathname2url(path):
+    try:
+        path.encode("utf8")
+    except UnicodeEncodeError:
+        raise unittest.SkipTest("path is not encodable to utf8")
     urlpath = urllib.request.pathname2url(path)
     if os.name == "nt" and urlpath.startswith("///"):
         urlpath = urlpath[2:]
@@ -731,6 +735,8 @@
             ("file://ftp.example.com///foo.txt", False),
 # XXXX bug: fails with OSError, should be URLError
             ("file://ftp.example.com/foo.txt", False),
+            ("file://somehost//foo/something.txt", True),
+            ("file://localhost//foo/something.txt", False),
             ]:
             req = Request(url)
             try:
@@ -741,6 +747,7 @@
             else:
                 self.assertTrue(o.req is req)
                 self.assertEqual(req.type, "ftp")
+            self.assertEqual(req.type is "ftp", ftp)
 
     def test_http(self):
 

Modified: python/branches/py3k-dtoa/Lib/test/test_urlparse.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_urlparse.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_urlparse.py	Sun Aug  8 12:41:24 2010
@@ -7,6 +7,7 @@
 RFC1808_BASE = "http://a/b/c/d;p?q#f"
 RFC2396_BASE = "http://a/b/c/d;p?q"
 RFC3986_BASE = 'http://a/b/c/d;p?q'
+SIMPLE_BASE  = 'http://a/b/c/d'
 
 # A list of test cases.  Each test case is a a two-tuple that contains
 # a string with the query and a dictionary with the expected result.
@@ -295,6 +296,37 @@
         #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser
         self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser
 
+    def test_urljoins(self):
+        self.checkJoin(SIMPLE_BASE, 'g:h','g:h')
+        self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
+        self.checkJoin(SIMPLE_BASE, 'g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, './g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, 'g/','http://a/b/c/g/')
+        self.checkJoin(SIMPLE_BASE, '/g','http://a/g')
+        self.checkJoin(SIMPLE_BASE, '//g','http://g')
+        self.checkJoin(SIMPLE_BASE, '?y','http://a/b/c/d?y')
+        self.checkJoin(SIMPLE_BASE, 'g?y','http://a/b/c/g?y')
+        self.checkJoin(SIMPLE_BASE, 'g?y/./x','http://a/b/c/g?y/./x')
+        self.checkJoin(SIMPLE_BASE, '.','http://a/b/c/')
+        self.checkJoin(SIMPLE_BASE, './','http://a/b/c/')
+        self.checkJoin(SIMPLE_BASE, '..','http://a/b/')
+        self.checkJoin(SIMPLE_BASE, '../','http://a/b/')
+        self.checkJoin(SIMPLE_BASE, '../g','http://a/b/g')
+        self.checkJoin(SIMPLE_BASE, '../..','http://a/')
+        self.checkJoin(SIMPLE_BASE, '../../g','http://a/g')
+        self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g')
+        self.checkJoin(SIMPLE_BASE, './../g','http://a/b/g')
+        self.checkJoin(SIMPLE_BASE, './g/.','http://a/b/c/g/')
+        self.checkJoin(SIMPLE_BASE, '/./g','http://a/./g')
+        self.checkJoin(SIMPLE_BASE, 'g/./h','http://a/b/c/g/h')
+        self.checkJoin(SIMPLE_BASE, 'g/../h','http://a/b/c/h')
+        self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
+        self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y')
+        self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y')
+        self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x')
+
     def test_RFC2732(self):
         for url, hostname, port in [
             ('http://Test.python.org:5432/foo/', 'test.python.org', 5432),
@@ -429,6 +461,27 @@
         self.assertEqual(urllib.parse.urlparse("http://example.com?blahblah=/foo"),
                          ('http', 'example.com', '', '', 'blahblah=/foo', ''))
 
+    def test_withoutscheme(self):
+        # Test urlparse without scheme
+        # Issue 754016: urlparse goes wrong with IP:port without scheme
+        # RFC 1808 specifies that netloc should start with //, urlparse expects
+        # the same, otherwise it classifies the portion of url as path.
+        self.assertEqual(urllib.parse.urlparse("path"),
+                ('','','path','','',''))
+        self.assertEqual(urllib.parse.urlparse("//www.python.org:80"),
+                ('','www.python.org:80','','','',''))
+        self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
+                ('http','www.python.org:80','','','',''))
+
+    def test_portseparator(self):
+        # Issue 754016 makes changes for port separator ':' from scheme separator
+        self.assertEqual(urllib.parse.urlparse("path:80"),
+                ('','','path:80','','',''))
+        self.assertEqual(urllib.parse.urlparse("http:"),('http','','','','',''))
+        self.assertEqual(urllib.parse.urlparse("https:"),('https','','','','',''))
+        self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
+                ('http','www.python.org:80','','','',''))
+
     def test_usingsys(self):
         # Issue 3314: sys module is used in the error
         self.assertRaises(TypeError, urllib.parse.urlencode, "foo")

Modified: python/branches/py3k-dtoa/Lib/test/test_xml_etree.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/test/test_xml_etree.py	(original)
+++ python/branches/py3k-dtoa/Lib/test/test_xml_etree.py	Sun Aug  8 12:41:24 2010
@@ -13,6 +13,7 @@
 
 import sys
 import cgi
+import unittest
 
 from test import support
 from test.support import findfile
@@ -20,6 +21,10 @@
 from xml.etree import ElementTree as ET
 
 SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata")
+try:
+    SIMPLE_XMLFILE.encode("utf8")
+except UnicodeEncodeError:
+    raise unittest.SkipTest("filename is not encodable to utf8")
 SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata")
 
 SAMPLE_XML = """\

Modified: python/branches/py3k-dtoa/Lib/threading.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/threading.py	(original)
+++ python/branches/py3k-dtoa/Lib/threading.py	Sun Aug  8 12:41:24 2010
@@ -871,91 +871,3 @@
         _active.clear()
         _active.update(new_active)
         assert len(_active) == 1
-
-
-# Self-test code
-
-def _test():
-
-    class BoundedQueue(_Verbose):
-
-        def __init__(self, limit):
-            _Verbose.__init__(self)
-            self.mon = RLock()
-            self.rc = Condition(self.mon)
-            self.wc = Condition(self.mon)
-            self.limit = limit
-            self.queue = deque()
-
-        def put(self, item):
-            self.mon.acquire()
-            while len(self.queue) >= self.limit:
-                self._note("put(%s): queue full", item)
-                self.wc.wait()
-            self.queue.append(item)
-            self._note("put(%s): appended, length now %d",
-                       item, len(self.queue))
-            self.rc.notify()
-            self.mon.release()
-
-        def get(self):
-            self.mon.acquire()
-            while not self.queue:
-                self._note("get(): queue empty")
-                self.rc.wait()
-            item = self.queue.popleft()
-            self._note("get(): got %s, %d left", item, len(self.queue))
-            self.wc.notify()
-            self.mon.release()
-            return item
-
-    class ProducerThread(Thread):
-
-        def __init__(self, queue, quota):
-            Thread.__init__(self, name="Producer")
-            self.queue = queue
-            self.quota = quota
-
-        def run(self):
-            from random import random
-            counter = 0
-            while counter < self.quota:
-                counter = counter + 1
-                self.queue.put("%s.%d" % (self.name, counter))
-                _sleep(random() * 0.00001)
-
-
-    class ConsumerThread(Thread):
-
-        def __init__(self, queue, count):
-            Thread.__init__(self, name="Consumer")
-            self.queue = queue
-            self.count = count
-
-        def run(self):
-            while self.count > 0:
-                item = self.queue.get()
-                print(item)
-                self.count = self.count - 1
-
-    NP = 3
-    QL = 4
-    NI = 5
-
-    Q = BoundedQueue(QL)
-    P = []
-    for i in range(NP):
-        t = ProducerThread(Q, NI)
-        t.name = "Producer-%d" % (i+1)
-        P.append(t)
-    C = ConsumerThread(Q, NI*NP)
-    for t in P:
-        t.start()
-        _sleep(0.000001)
-    C.start()
-    for t in P:
-        t.join()
-    C.join()
-
-if __name__ == '__main__':
-    _test()

Modified: python/branches/py3k-dtoa/Lib/timeit.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/timeit.py	(original)
+++ python/branches/py3k-dtoa/Lib/timeit.py	Sun Aug  8 12:41:24 2010
@@ -9,7 +9,7 @@
 Library usage: see the Timer class.
 
 Command line usage:
-    python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement]
+    python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [--] [statement]
 
 Options:
   -n/--number N: how many times to execute 'statement' (default: see below)
@@ -19,6 +19,7 @@
   -c/--clock: use time.clock() (default on Windows)
   -v/--verbose: print raw timing results; repeat for more digits precision
   -h/--help: print this usage message and exit
+  --: separate options from statement, use when statement starts with -
   statement: statement to be timed (default 'pass')
 
 A multi-line statement may be given by specifying each line as a

Modified: python/branches/py3k-dtoa/Lib/trace.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/trace.py	(original)
+++ python/branches/py3k-dtoa/Lib/trace.py	Sun Aug  8 12:41:24 2010
@@ -192,11 +192,13 @@
         base = path[len(longest) + 1:]
     else:
         base = path
+    # the drive letter is never part of the module name
+    drive, base = os.path.splitdrive(base)
     base = base.replace(os.sep, ".")
     if os.altsep:
         base = base.replace(os.altsep, ".")
     filename, ext = os.path.splitext(base)
-    return filename
+    return filename.lstrip(".")
 
 class CoverageResults:
     def __init__(self, counts=None, calledfuncs=None, infile=None,
@@ -257,7 +259,8 @@
         if self.calledfuncs:
             print()
             print("functions called:")
-            for filename, modulename, funcname in sorted(calls.keys()):
+            calls = self.calledfuncs.keys()
+            for filename, modulename, funcname in sorted(calls):
                 print(("filename: %s, modulename: %s, funcname: %s"
                        % (filename, modulename, funcname)))
 
@@ -490,8 +493,8 @@
         import __main__
         dict = __main__.__dict__
         if not self.donothing:
-            sys.settrace(self.globaltrace)
             threading.settrace(self.globaltrace)
+            sys.settrace(self.globaltrace)
         try:
             exec(cmd, dict, dict)
         finally:
@@ -503,8 +506,8 @@
         if globals is None: globals = {}
         if locals is None: locals = {}
         if not self.donothing:
-            sys.settrace(self.globaltrace)
             threading.settrace(self.globaltrace)
+            sys.settrace(self.globaltrace)
         try:
             exec(cmd, globals, locals)
         finally:
@@ -623,7 +626,7 @@
                 print('%.2f' % (time.time() - self.start_time), end=' ')
             bname = os.path.basename(filename)
             print("%s(%d): %s" % (bname, lineno,
-                                  linecache.getline(filename, lineno)), end=' ')
+                                  linecache.getline(filename, lineno)), end='')
         return self.localtrace
 
     def localtrace_trace(self, frame, why, arg):
@@ -636,7 +639,7 @@
                 print('%.2f' % (time.time() - self.start_time), end=' ')
             bname = os.path.basename(filename)
             print("%s(%d): %s" % (bname, lineno,
-                                  linecache.getline(filename, lineno)), end=' ')
+                                  linecache.getline(filename, lineno)), end='')
         return self.localtrace
 
     def localtrace_count(self, frame, why, arg):
@@ -796,12 +799,16 @@
                   ignoredirs=ignore_dirs, infile=counts_file,
                   outfile=counts_file, timing=timing)
         try:
-            fp = open(progname)
-            try:
-                script = fp.read()
-            finally:
-                fp.close()
-            t.run('exec(%r)' % (script,))
+            with open(progname) as fp:
+                code = compile(fp.read(), progname, 'exec')
+            # try to emulate __main__ namespace as much as possible
+            globs = {
+                '__file__': progname,
+                '__name__': '__main__',
+                '__package__': None,
+                '__cached__': None,
+            }
+            t.runctx(code, globs, globs)
         except IOError as err:
             _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
         except SystemExit:

Modified: python/branches/py3k-dtoa/Lib/unittest/case.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/unittest/case.py	(original)
+++ python/branches/py3k-dtoa/Lib/unittest/case.py	Sun Aug  8 12:41:24 2010
@@ -940,9 +940,14 @@
                 'Second argument is not a string'))
 
         if first != second:
-            standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True))
-            diff = '\n' + ''.join(difflib.ndiff(first.splitlines(True),
-                                                       second.splitlines(True)))
+            firstlines = first.splitlines(True)
+            secondlines = second.splitlines(True)
+            if len(firstlines) == 1 and first.strip('\r\n') == first:
+                firstlines = [first + '\n']
+                secondlines = [second + '\n']
+            standardMsg = '%s != %s' % (safe_repr(first, True),
+                                        safe_repr(second, True))
+            diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
             standardMsg = self._truncateMessage(standardMsg, diff)
             self.fail(self._formatMessage(msg, standardMsg))
 

Modified: python/branches/py3k-dtoa/Lib/unittest/test/test_case.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/unittest/test/test_case.py	(original)
+++ python/branches/py3k-dtoa/Lib/unittest/test/test_case.py	Sun Aug  8 12:41:24 2010
@@ -841,6 +841,21 @@
             # so can't use assertEqual either. Just use assertTrue.
             self.assertTrue(sample_text_error == error)
 
+    def testAsertEqualSingleLine(self):
+        sample_text = "laden swallows fly slowly"
+        revised_sample_text = "unladen swallows fly quickly"
+        sample_text_error = """\
+- laden swallows fly slowly
+?                    ^^^^
++ unladen swallows fly quickly
+? ++                   ^^^^^
+"""
+        try:
+            self.assertEqual(sample_text, revised_sample_text)
+        except self.failureException as e:
+            error = str(e).split('\n', 1)[1]
+            self.assertTrue(sample_text_error == error)
+
     def testAssertIsNone(self):
         self.assertIsNone(None)
         self.assertRaises(self.failureException, self.assertIsNone, False)

Modified: python/branches/py3k-dtoa/Lib/urllib/parse.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/urllib/parse.py	(original)
+++ python/branches/py3k-dtoa/Lib/urllib/parse.py	Sun Aug  8 12:41:24 2010
@@ -192,11 +192,12 @@
             v = SplitResult(scheme, netloc, url, query, fragment)
             _parse_cache[key] = v
             return v
-        for c in url[:i]:
-            if c not in scheme_chars:
-                break
-        else:
-            scheme, url = url[:i].lower(), url[i+1:]
+        if url.endswith(':') or not url[i+1].isdigit():
+            for c in url[:i]:
+                if c not in scheme_chars:
+                    break
+            else:
+                scheme, url = url[:i].lower(), url[i+1:]
     if url[:2] == '//':
         netloc, url = _splitnetloc(url, 2)
         if (('[' in netloc and ']' not in netloc) or
@@ -313,7 +314,7 @@
     """unquote_to_bytes('abc%20def') -> b'abc def'."""
     # Note: strings are encoded as UTF-8. This is only an issue if it contains
     # unescaped non-ASCII characters, which URIs should not.
-    if not string:
+    if string in (b'', ''):
         return b''
     if isinstance(string, str):
         string = string.encode('utf-8')
@@ -338,7 +339,7 @@
 
     unquote('abc%20def') -> 'abc def'.
     """
-    if not string:
+    if string == '':
         return string
     res = string.split('%')
     if len(res) == 1:
@@ -799,67 +800,3 @@
     match = _valueprog.match(attr)
     if match: return match.group(1, 2)
     return attr, None
-
-test_input = """
-      http://a/b/c/d
-
-      g:h        = <URL:g:h>
-      http:g     = <URL:http://a/b/c/g>
-      http:      = <URL:http://a/b/c/d>
-      g          = <URL:http://a/b/c/g>
-      ./g        = <URL:http://a/b/c/g>
-      g/         = <URL:http://a/b/c/g/>
-      /g         = <URL:http://a/g>
-      //g        = <URL:http://g>
-      ?y         = <URL:http://a/b/c/d?y>
-      g?y        = <URL:http://a/b/c/g?y>
-      g?y/./x    = <URL:http://a/b/c/g?y/./x>
-      .          = <URL:http://a/b/c/>
-      ./         = <URL:http://a/b/c/>
-      ..         = <URL:http://a/b/>
-      ../        = <URL:http://a/b/>
-      ../g       = <URL:http://a/b/g>
-      ../..      = <URL:http://a/>
-      ../../g    = <URL:http://a/g>
-      ../../../g = <URL:http://a/../g>
-      ./../g     = <URL:http://a/b/g>
-      ./g/.      = <URL:http://a/b/c/g/>
-      /./g       = <URL:http://a/./g>
-      g/./h      = <URL:http://a/b/c/g/h>
-      g/../h     = <URL:http://a/b/c/h>
-      http:g     = <URL:http://a/b/c/g>
-      http:      = <URL:http://a/b/c/d>
-      http:?y         = <URL:http://a/b/c/d?y>
-      http:g?y        = <URL:http://a/b/c/g?y>
-      http:g?y/./x    = <URL:http://a/b/c/g?y/./x>
-"""
-
-def test():
-    base = ''
-    if sys.argv[1:]:
-        fn = sys.argv[1]
-        if fn == '-':
-            fp = sys.stdin
-        else:
-            fp = open(fn)
-    else:
-        from io import StringIO
-        fp = StringIO(test_input)
-    for line in fp:
-        words = line.split()
-        if not words:
-            continue
-        url = words[0]
-        parts = urlparse(url)
-        print('%-10s : %s' % (url, parts))
-        abs = urljoin(base, url)
-        if not base:
-            base = abs
-        wrapped = '<URL:%s>' % abs
-        print('%-10s = %s' % (url, wrapped))
-        if len(words) == 3 and words[1] == '=':
-            if wrapped != words[2]:
-                print('EXPECTED', words[2], '!!!!!!!!!!')
-
-if __name__ == '__main__':
-    test()

Modified: python/branches/py3k-dtoa/Lib/urllib/request.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/urllib/request.py	(original)
+++ python/branches/py3k-dtoa/Lib/urllib/request.py	Sun Aug  8 12:41:24 2010
@@ -1188,7 +1188,8 @@
     # Use local file or FTP depending on form of URL
     def file_open(self, req):
         url = req.selector
-        if url[:2] == '//' and url[2:3] != '/':
+        if url[:2] == '//' and url[2:3] != '/' and (req.host and
+                req.host != 'localhost'):
             req.type = 'ftp'
             return self.parent.open(req)
         else:
@@ -1590,13 +1591,13 @@
 
         if proxy_passwd:
             import base64
-            proxy_auth = base64.b64encode(proxy_passwd).strip()
+            proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
         else:
             proxy_auth = None
 
         if user_passwd:
             import base64
-            auth = base64.b64encode(user_passwd).strip()
+            auth = base64.b64encode(user_passwd.encode()).decode('ascii')
         else:
             auth = None
         http_conn = connection_factory(host)
@@ -2278,6 +2279,7 @@
                         proxies['http'] = proxyServer
                     else:
                         proxies['http'] = 'http://%s' % proxyServer
+                        proxies['https'] = 'https://%s' % proxyServer
                         proxies['ftp'] = 'ftp://%s' % proxyServer
             internetSettings.Close()
         except (WindowsError, ValueError, TypeError):

Modified: python/branches/py3k-dtoa/Lib/urllib/robotparser.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/urllib/robotparser.py	(original)
+++ python/branches/py3k-dtoa/Lib/urllib/robotparser.py	Sun Aug  8 12:41:24 2010
@@ -66,7 +66,9 @@
     def _add_entry(self, entry):
         if "*" in entry.useragents:
             # the default entry is considered last
-            self.default_entry = entry
+            if self.default_entry is None:
+                # the first default entry wins
+                self.default_entry = entry
         else:
             self.entries.append(entry)
 
@@ -118,7 +120,7 @@
                         entry.rulelines.append(RuleLine(line[1], True))
                         state = 2
         if state == 2:
-            self.entries.append(entry)
+            self._add_entry(entry)
 
 
     def can_fetch(self, useragent, url):
@@ -129,8 +131,10 @@
             return True
         # search for given user agent matches
         # the first match counts
-        url = urllib.parse.quote(
-            urllib.parse.urlparse(urllib.parse.unquote(url))[2])
+        parsed_url = urllib.parse.urlparse(urllib.parse.unquote(url))
+        url = urllib.parse.urlunparse(('','',parsed_url.path,
+            parsed_url.params,parsed_url.query, parsed_url.fragment))
+        url = urllib.parse.quote(url)
         if not url:
             url = "/"
         for entry in self.entries:

Modified: python/branches/py3k-dtoa/Lib/xml/dom/expatbuilder.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/xml/dom/expatbuilder.py	(original)
+++ python/branches/py3k-dtoa/Lib/xml/dom/expatbuilder.py	Sun Aug  8 12:41:24 2010
@@ -242,7 +242,7 @@
         doctype = self.document.implementation.createDocumentType(
             doctypeName, publicId, systemId)
         doctype.ownerDocument = self.document
-        self.document.childNodes.append(doctype)
+        _append_child(self.document, doctype)
         self.document.doctype = doctype
         if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT:
             self.document.doctype = None

Modified: python/branches/py3k-dtoa/Lib/xml/dom/minidom.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/xml/dom/minidom.py	(original)
+++ python/branches/py3k-dtoa/Lib/xml/dom/minidom.py	Sun Aug  8 12:41:24 2010
@@ -920,6 +920,10 @@
         raise xml.dom.NotFoundErr(
             self.nodeName + " nodes do not have children")
 
+    def normalize(self):
+        # For childless nodes, normalize() has nothing to do.
+        pass
+
     def replaceChild(self, newChild, oldChild):
         raise xml.dom.HierarchyRequestErr(
             self.nodeName + " nodes do not have children")

Modified: python/branches/py3k-dtoa/Lib/xmlrpc/client.py
==============================================================================
--- python/branches/py3k-dtoa/Lib/xmlrpc/client.py	(original)
+++ python/branches/py3k-dtoa/Lib/xmlrpc/client.py	Sun Aug  8 12:41:24 2010
@@ -1135,7 +1135,7 @@
             try:
                 return self.single_request(host, handler, request_body, verbose)
             except socket.error as e:
-                if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED):
+                if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
                     raise
             except http.client.BadStatusLine: #close after we sent request
                 if i:

Modified: python/branches/py3k-dtoa/Makefile.pre.in
==============================================================================
--- python/branches/py3k-dtoa/Makefile.pre.in	(original)
+++ python/branches/py3k-dtoa/Makefile.pre.in	Sun Aug  8 12:41:24 2010
@@ -59,12 +59,18 @@
 # Compiler options
 OPT=		@OPT@
 BASECFLAGS=	@BASECFLAGS@
-CFLAGS=		$(BASECFLAGS) @CFLAGS@ $(OPT) $(EXTRA_CFLAGS)
+CONFIGURE_CFLAGS=	@CFLAGS@
+CONFIGURE_CPPFLAGS=	@CPPFLAGS@
+CONFIGURE_LDFLAGS=	@LDFLAGS@
+# Avoid assigning CFLAGS, LDFLAGS, etc. so users can use them on the
+# command line to append to these values without stomping the pre-set
+# values.
+PY_CFLAGS=	$(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS)
 # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to
 # be able to build extension modules using the directories specified in the
 # environment variables
-CPPFLAGS=	-I. -IInclude -I$(srcdir)/Include @CPPFLAGS@
-LDFLAGS=	@LDFLAGS@
+PY_CPPFLAGS=	-I. -IInclude -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS)
+PY_LDFLAGS=	$(CONFIGURE_LDFLAGS) $(LDFLAGS)
 LDLAST=		@LDLAST@
 SGI_ABI=	@SGI_ABI@
 CCSHARED=	@CCSHARED@
@@ -73,7 +79,7 @@
 # Extra C flags added for building the interpreter object files.
 CFLAGSFORSHARED=@CFLAGSFORSHARED@
 # C flags used for building the interpreter object files
-PY_CFLAGS=	$(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE
+PY_CORE_CFLAGS=	$(PY_CFLAGS) $(PY_CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE
 
 
 # Machine-dependent subdirectories
@@ -308,6 +314,7 @@
 		Python/pymath.o \
 		Python/pystate.o \
 		Python/pythonrun.o \
+		Python/pytime.o \
 		Python/structmember.o \
 		Python/symtable.o \
 		Python/sysmodule.o \
@@ -411,9 +418,7 @@
 
 # Build the interpreter
 $(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY)
-		$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \
-			Modules/python.o \
-			$(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
+	$(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ Modules/python.o $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
 
 platform: $(BUILDPYTHON)
 	$(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from sysconfig import get_platform ; print(get_platform()+"-"+sys.version[0:3])' >platform
@@ -422,8 +427,8 @@
 # Build the shared modules
 sharedmods: $(BUILDPYTHON)
 	@case $$MAKEFLAGS in \
-	*s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \
-	*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \
+	*s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \
+	*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \
 	esac
 
 # Build static library
@@ -440,18 +445,18 @@
 
 libpython$(VERSION).so: $(LIBRARY_OBJS)
 	if test $(INSTSONAME) != $(LDLIBRARY); then \
-		$(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+		$(LDSHARED) $(PY_LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 		$(LN) -f $(INSTSONAME) $@; \
 	else \
-		$(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+		$(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 	fi
 
 libpython$(VERSION).dylib: $(LIBRARY_OBJS)
-	 $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+	 $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 		 
 
 libpython$(VERSION).sl: $(LIBRARY_OBJS)
-	$(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST)
+	$(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST)
 
 # Copy up the gdb python hooks into a position where they can be automatically
 # loaded by gdb during Lib/test/test_gdb.py
@@ -497,7 +502,7 @@
 # for a shared core library; otherwise, this rule is a noop.
 $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS)
 	if test -n "$(DLLLIBRARY)"; then \
-		$(LDSHARED) $(LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \
+		$(LDSHARED) $(PY_LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \
 			$(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST); \
 	else true; \
 	fi
@@ -541,10 +546,10 @@
 		$(SIGNAL_OBJS) \
 		$(MODOBJS) \
 		$(srcdir)/Modules/getbuildinfo.c
-	$(CC) -c $(PY_CFLAGS) -DSVNVERSION="\"`LC_ALL=C $(SVNVERSION)`\"" -o $@ $(srcdir)/Modules/getbuildinfo.c
+	$(CC) -c $(PY_CORE_CFLAGS) -DSVNVERSION="\"`LC_ALL=C $(SVNVERSION)`\"" -o $@ $(srcdir)/Modules/getbuildinfo.c
 
 Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile
-	$(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \
+	$(CC) -c $(PY_CORE_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \
 		-DPREFIX='"$(prefix)"' \
 		-DEXEC_PREFIX='"$(exec_prefix)"' \
 		-DVERSION='"$(VERSION)"' \
@@ -552,7 +557,7 @@
 		-o $@ $(srcdir)/Modules/getpath.c
 
 Modules/python.o: $(srcdir)/Modules/python.c
-	$(MAINCC) -c $(PY_CFLAGS) -o $@ $(srcdir)/Modules/python.c
+	$(MAINCC) -c $(PY_CORE_CFLAGS) -o $@ $(srcdir)/Modules/python.c
 
 $(IO_OBJS): $(IO_H)
 
@@ -561,7 +566,7 @@
 		-$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
 
 $(PGEN):	$(PGENOBJS)
-		$(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
+		$(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
 
 Parser/grammar.o:	$(srcdir)/Parser/grammar.c \
 				$(srcdir)/Include/token.h \
@@ -581,10 +586,10 @@
 Python/compile.o Python/symtable.o Python/ast.o: $(GRAMMAR_H) $(AST_H)
 
 Python/getplatform.o: $(srcdir)/Python/getplatform.c
-		$(CC) -c $(PY_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c
+		$(CC) -c $(PY_CORE_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c
 
 Python/importdl.o: $(srcdir)/Python/importdl.c
-		$(CC) -c $(PY_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c
+		$(CC) -c $(PY_CORE_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c
 
 Objects/unicodectype.o:	$(srcdir)/Objects/unicodectype.c \
 				$(srcdir)/Objects/unicodetype_db.h
@@ -692,6 +697,7 @@
 		Include/pystrtod.h \
 		Include/pythonrun.h \
 		Include/pythread.h \
+		Include/pytime.h \
 		Include/rangeobject.h \
 		Include/setobject.h \
 		Include/sliceobject.h \
@@ -1039,7 +1045,7 @@
 
 # Install the dynamically loadable modules
 # This goes into $(exec_prefix)
-sharedinstall:
+sharedinstall: sharedmods
 	$(RUNSHARED) ./$(BUILDPYTHON) -E $(srcdir)/setup.py install \
 	   	--prefix=$(prefix) \
 		--install-scripts=$(BINDIR) \
@@ -1130,7 +1136,7 @@
 
 # Some make's put the object file in the current directory
 .c.o:
-	$(CC) -c $(PY_CFLAGS) -o $@ $<
+	$(CC) -c $(PY_CORE_CFLAGS) -o $@ $<
 
 # Run reindent on the library
 reindent:
@@ -1179,8 +1185,9 @@
 	-rm -rf Doc/tools/sphinx Doc/tools/pygments Doc/tools/docutils
 
 clean: pycremoval
-	find . -name '*.o' -exec rm -f {} ';'
+	find . -name '*.[oa]' -exec rm -f {} ';'
 	find . -name '*.s[ol]' -exec rm -f {} ';'
+	find . -name '*.so.[0-9]*.[0-9]*' -exec rm -f {} ';'
 	find build -name 'fficonfig.h' -exec rm -f {} ';' || true
 	find build -name 'fficonfig.py' -exec rm -f {} ';' || true
 	-rm -f Lib/lib2to3/*Grammar*.pickle
@@ -1199,7 +1206,9 @@
 # remove all generated files, even Makefile[.pre]
 # Keep configure and Python-ast.[ch], it's possible they can't be generated
 distclean: clobber
-	-rm -f Lib/test/data/*
+	for file in Lib/test/data/* ; do \
+	    if test "$$file" != "Lib/test/data/README"; then rm "$$file"; fi; \
+	done
 	-rm -f core Makefile Makefile.pre config.status \
 		Modules/Setup Modules/Setup.local Modules/Setup.config \
 		Misc/python.pc

Modified: python/branches/py3k-dtoa/Misc/ACKS
==============================================================================
--- python/branches/py3k-dtoa/Misc/ACKS	(original)
+++ python/branches/py3k-dtoa/Misc/ACKS	Sun Aug  8 12:41:24 2010
@@ -63,6 +63,7 @@
 Ben Bell
 Thomas Bellman
 Alexander Belopolsky
+Eli Bendersky
 Andrew Bennetts
 Andy Bensky
 Michel Van den Bergh
@@ -97,6 +98,7 @@
 Georg Brandl
 Christopher Brannon
 Terrence Brannon
+Brian Brazil
 Dave Brennan
 Tom Bridgman
 Richard Brodie
@@ -128,6 +130,7 @@
 Per Cederqvist
 Octavian Cerna
 Pascal Chambon
+John Chandler
 Hye-Shik Chang
 Jeffrey Chang
 Mitch Chapman
@@ -145,11 +148,13 @@
 Vadim Chugunov
 David Cinege
 Mike Clarkson
+Andrew Clegg
 Brad Clements
 Steve Clift
 Nick Coghlan
 Josh Cogliati
 Dave Cole
+Terrence Cole
 Benjamin Collar
 Jeffery Collins
 Robert Collins
@@ -158,6 +163,7 @@
 Juan José Conti
 Matt Conway
 David M. Cooke
+Jason R. Coombs
 Greg Copeland
 Aldo Cortesi
 David Costanzo
@@ -175,6 +181,7 @@
 Joaquin Cuenca Abela
 John Cugini
 Tom Culliton
+Antonio Cuni
 Brian Curtin
 Lisandro Dalcin
 Andrew Dalke
@@ -191,6 +198,7 @@
 Roger Dev
 Raghuram Devarakonda
 Caleb Deveraux
+Catherine Devlin
 Toby Dickenson
 Mark Dickinson
 Jack Diederich
@@ -443,6 +451,7 @@
 Vladimir Kushnir
 Cameron Laird
 Torsten Landschoff
+Łukasz Langa
 Tino Lange
 Andrew Langmead
 Detlef Lannert
@@ -452,6 +461,7 @@
 Simon Law
 Chris Lawrence
 Brian Leair
+James Lee
 John J. Lee
 Inyeol Lee
 Thomas Lee
@@ -472,6 +482,7 @@
 Ross Light
 Shawn Ligocki
 Martin Ligr
+Grant Limberg
 Christopher Lindblad
 Bjorn Lindqvist
 Per Lindqvist
@@ -581,6 +592,7 @@
 Piet van Oostrum
 Jason Orendorff
 Douglas Orr
+Michele Orrù
 Denis S. Otkidach
 Michael Otteneder
 R. M. Oudkerk
@@ -792,6 +804,7 @@
 Jason Trowbridge
 Anthony Tuininga
 Stephen Turner
+Theodore Turocy
 Bill Tutt
 Doobee R. Tzeck
 Eren Türkay
@@ -843,6 +856,7 @@
 Gerry Wiener
 Frank Wierzbicki
 Bryce "Zooko" Wilcox-O'Hearn
+Jason Williams
 John Williams
 Sue Williams
 Gerald S. Williams
@@ -883,3 +897,4 @@
 Uwe Zessin
 Tarek Ziadé
 Peter Ã…strand
+Alexander Shigin

Modified: python/branches/py3k-dtoa/Misc/NEWS
==============================================================================
--- python/branches/py3k-dtoa/Misc/NEWS	(original)
+++ python/branches/py3k-dtoa/Misc/NEWS	Sun Aug  8 12:41:24 2010
@@ -4,25 +4,164 @@
 
 (editors: check NEWS.help for information about editing NEWS using ReST.)
 
+What's New in Python 3.2 Alpha 2?
+=================================
+
+*Release date: XX-Sep-2010*
+
+Core and Builtins
+-----------------
+
+- Issue #9337: The str() of a float or complex number is now identical
+  to its repr().
+
+- Issue #9416: Fix some issues with complex formatting where the
+  output with no type specifier failed to match the str output:
+
+    - format(complex(-0.0, 2.0), '-') omitted the real part from the output,
+    - format(complex(0.0, 2.0), '-') included a sign and parentheses.
+
+Extensions
+----------
+
+- Issue #9507:  Named tuple repr will now automatically display the right
+  name in a tuple subclass.
+
+- Issue #9324: Add parameter validation to signal.signal on Windows in order
+  to prevent crashes.
+
+- Issue #9526: Remove some outdated (int) casts that were preventing
+  the array module from working correctly with arrays of more than
+  2**31 elements.
+
+- Fix memory leak in ssl._ssl._test_decode_cert.
+
+- Issue #8065: Fix memory leak in readline module (from failure to
+  free the result of history_get_history_state()).
+
+- Issue #9450: Fix memory leak in readline.replace_history_item and
+  readline.remove_history_item for readline version >= 5.0.
+
+- Issue #8105: Validate file descriptor passed to mmap.mmap on Windows.
+
+- Issue #8046: Add context manager protocol support and .closed property
+  to mmap objects.
+
+Library
+-------
+
+- Issue #6683: For SMTP logins we now try all authentication methods advertised
+  by the server. Many servers are buggy and advertise authentication methods they
+  o not support in reality.
+
+- Issue #8814: function annotations (the ``__annotations__`` attribute)
+  are now included in the set of attributes copied by default by
+  functools.wraps and functools.update_wrapper.  Patch by Terrence Cole.
+
+- Issue #2944: asyncore doesn't handle connection refused correctly.
+
+- Issue #4184: Private attributes on smtpd.SMTPChannel made public and
+  deprecate the private attributes. Add tests for smtpd module.
+
+- Issue #3196: email header decoding is now forgiving if an RFC2047
+  encoded word encoded in base64 is lacking padding.
+
+- Issue #9444: Argparse now uses the first element of prefix_chars as
+  the option character for the added 'h/help' option if prefix_chars
+  does not contain a '-', instead of raising an error.
+
+- Issue #7372: Fix pstats regression when stripping paths from profile
+  data generated with the profile module.
+
+- Issue #9428: Fix running scripts with the profile/cProfile modules from
+  the command line.
+
+- Issue #7781: Fix restricting stats by entry counts in the pstats
+  interactive browser.
+
+- Issue #9209: Do not crash in the pstats interactive browser on invalid
+  regular expressions.
+
+- Update collections.OrderedDict to match the implementation in Py2.7
+  (based on lists instead of weakly referenced Link objects).
+
+- Issue #8397: Raise an error when attempting to mix iteration and regular
+  reads on a BZ2File object, rather than returning incorrect results.
+
+- Issue #9448: Fix a leak of OS resources (mutexes or semaphores) when
+  re-initializing a buffered IO object by calling its ``__init__`` method.
+
+- Issue #1713: Fix os.path.ismount(), which returned true for symbolic links
+  across devices.
+
+- Issue #8826: Properly load old-style "expires" attribute in http.cookies.
+
+- Issue #1690103: Fix initial namespace for code run with trace.main().
+
+- Issue #7395: Fix tracebacks in pstats interactive browser.
+
+- Issue #8230: Fix Lib/test/sortperf.py.
+
+- Issue #8620: when a Cmd is fed input that reaches EOF without a final
+  newline, it no longer truncates the last character of the last command line.
+
+- Issue #5146: Handle UID THREAD command correctly in imaplib.
+
+- Issue #5147: Fix the header generated for cookie files written by
+  http.cookiejar.MozillaCookieJar.
+
+- Issue #8198: In pydoc, output all help text to the correct stream
+  when sys.stdout is reassigned.
+
+- Issue #7909: Do not touch paths with the special prefixes ``\\.\``
+  or ``\\?\`` in ntpath.normpath().
+
+- Issue #1286: Allow using fileinput.FileInput as a context manager.
+
+- Add lfu_cache() and lru_cache() decorators to the functools module.
+
+Tools/Demos
+-----------
+
+- Issue #8867: Fix ``Tools/scripts/serve.py`` to work with files containing
+  non-ASCII content.
+
+Tests
+-----
+
+- Issue #8433: Fix test_curses failure with newer versions of ncurses.
+
+- Issue #9496: Provide a test suite for the rlcompleter module.  Patch by
+  Michele Orrù.
+
+- Issue #8687: provide a test suite for sched.py module.
+
+
 What's New in Python 3.2 Alpha 1?
 =================================
 
-*Release date: XX-XXX-XXX*
+*Release date: 01-Aug-2010*
 
 Core and Builtins
 -----------------
 
+- Issue #8991: convertbuffer() rejects discontigious buffers.
+
+- Issue #7616: Fix copying of overlapping memoryview slices with the Intel
+  compiler.
+
+- Issue #8413: structsequence now subclasses tuple.
+
 - Issue #8271: during the decoding of an invalid UTF-8 byte sequence, only the
-  start byte and the continuation byte(s) are now considered invalid, instead
-  of the number of bytes specified by the start byte.
-  E.g.: '\xf1\x80AB'.decode('utf-8', 'replace') now returns u'\ufffdAB' and
-  replaces with U+FFFD only the start byte ('\xf1') and the continuation byte
-  ('\x80') even if '\xf1' is the start byte of a 4-bytes sequence.
-  Previous versions returned a single u'\ufffd'.
-
-- Issue #9011: A negated imaginary literal (e.g., "-7j") now has real
-  part -0.0 rather than 0.0.  So "-7j" is now exactly equivalent to
-  "-(7j)".
+  start byte and the continuation byte(s) are now considered invalid, instead of
+  the number of bytes specified by the start byte.  E.g.:
+  '\xf1\x80AB'.decode('utf-8', 'replace') now returns u'\ufffdAB' and replaces
+  with U+FFFD only the start byte ('\xf1') and the continuation byte ('\x80')
+  even if '\xf1' is the start byte of a 4-bytes sequence.  Previous versions
+  returned a single u'\ufffd'.
+
+- Issue #9011: A negated imaginary literal (e.g., "-7j") now has real part -0.0
+  rather than 0.0.  So "-7j" is now exactly equivalent to "-(7j)".
 
 - Be more specific in error messages about positional arguments.
 
@@ -30,27 +169,26 @@
   objects, as described in the documentation.
 
 - Issue #6543: Write the traceback in the terminal encoding instead of utf-8.
-  Fix the encoding of the modules filename. Patch written by Amaury Forgeot
+  Fix the encoding of the modules filename.  Patch written by Amaury Forgeot
   d'Arc.
 
-- Issue #9011: Remove buggy and unnecessary (in 3.x) ST->AST
-  compilation code dealing with unary minus applied to a constant.
-  The removed code was mutating the ST, causing a second compilation
-  to fail.
+- Issue #9011: Remove buggy and unnecessary (in 3.x) ST->AST compilation code
+  dealing with unary minus applied to a constant.  The removed code was mutating
+  the ST, causing a second compilation to fail.
 
 - Issue #850997: mbcs encoding (Windows only) handles errors argument: strict
-  mode raises unicode errors. The encoder only supports "strict" and "replace"
+  mode raises unicode errors.  The encoder only supports "strict" and "replace"
   error handlers, the decoder only supports "strict" and "ignore" error
-  handlers. Patch written by Mark Hammond.
+  handlers.  Patch written by Mark Hammond.
 
 - Issue #8850: Remove "w" and "w#" formats from PyArg_Parse*() functions, use
   "w*" format instead. Add tests for "w*" format.
 
 - Issue #8592: PyArg_Parse*() functions raise a TypeError for "y", "u" and "Z"
-  formats if the string contains a null byte/character. Write unit tests for
+  formats if the string contains a null byte/character.  Write unit tests for
   string formats.
 
-- Issue #7490: to facilitate sharing of doctests between 2.x and 3.x test
+- Issue #7490: To facilitate sharing of doctests between 2.x and 3.x test
   suites, the IGNORE_EXCEPTION_DETAIL directive now also ignores the module
   location of the raised exception.
 
@@ -59,94 +197,93 @@
 
 - Issue #9058: Remove assertions about INT_MAX in UnicodeDecodeError.
 
-- Issue #8941: decoding big endian UTF-32 data in UCS-2 builds could crash
-  the interpreter with characters outside the Basic Multilingual Plane
-  (higher than 0x10000).
-
-- Issue #8950: (See also issue #5080).  Py_ArgParse*() functions now
-  raise TypeError instead of giving a DeprecationWarning when a float
-  is parsed using the 'L' code (for long long).  (All other integer
-  codes already raise TypeError in this case.)
+- Issue #8941: Decoding big endian UTF-32 data in UCS-2 builds could crash the
+  interpreter with characters outside the Basic Multilingual Plane (higher than
+  0x10000).
+
+- Issue #8950: (See also issue #5080).  Py_ArgParse*() functions now raise
+  TypeError instead of giving a DeprecationWarning when a float is parsed using
+  the 'L' code (for long long).  (All other integer codes already raise
+  TypeError in this case.)
 
 - Issue #8922: Normalize the encoding name in PyUnicode_AsEncodedString() to
   enable shortcuts for upper case encoding name. Add also a shortcut for
   "iso-8859-1" in PyUnicode_AsEncodedString() and PyUnicode_Decode().
 
-- Issue #8838: Remove codecs.charbuffer_encode() function. The buffer protocol
-  doesn't support "char buffer" anymore in Python3.
+- Issue #8838: Remove codecs.charbuffer_encode() function.  The buffer protocol
+  doesn't support "char buffer" anymore in Python 3.
 
 - Issue #8339: Remove "t#" format of PyArg_Parse*() functions, use "s#" or "s*"
-  instead. codecs.charbuffer_encode() now accepts modifiable buffer objects
+  instead.  codecs.charbuffer_encode() now accepts modifiable buffer objects
   like bytearray.
 
-- Issue #8837: Remove "O?" format of PyArg_Parse*() functions. The format is no
+- Issue #8837: Remove "O?" format of PyArg_Parse*() functions.  The format is no
   used anymore and it was never documented.
 
-- In the str.format(), raise a ValueError when indexes to arguments are too
-  large.
+- In str.format(), raise a ValueError when indexes to arguments are too large.
 
-- Issue #2844: Make int('42', n) consistently raise ValueError for
-  invalid integers n (including n = -909).
+- Issue #2844: Make int('42', n) consistently raise ValueError for invalid
+  integers n (including n = -909).
 
-- Issue #8188: Introduce a new scheme for computing hashes of numbers
-  (instances of int, float, complex, decimal.Decimal and
-  fractions.Fraction) that makes it easy to maintain the invariant
-  that hash(x) == hash(y) whenever x and y have equal value.
+- Issue #8188: Introduce a new scheme for computing hashes of numbers (instances
+  of int, float, complex, decimal.Decimal and fractions.Fraction) that makes it
+  easy to maintain the invariant that hash(x) == hash(y) whenever x and y have
+  equal value.
 
 - Issue #8748: Fix two issues with comparisons between complex and integer
   objects.  (1) The comparison could incorrectly return True in some cases
-  (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality.
-  (2) The comparison raised an OverflowError for large integers, leading
-  to unpredictable exceptions when combining integers and complex objects
-  in sets or dicts.
+  (2**53+1 == complex(2**53) == 2**53), breaking transitivity of equality.
+  (2) The comparison raised an OverflowError for large integers, leading to
+  unpredictable exceptions when combining integers and complex objects in sets
+  or dicts.
 
 - Issue #8766: Initialize _warnings module before importing the first module.
   Fix a crash if an empty directory called "encodings" exists in sys.path.
 
 - Issue #8589: Decode PYTHONWARNINGS environment variable with the file system
   encoding and surrogateespace error handler instead of the locale encoding to
-  be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function.
+  be consistent with os.environ.  Add PySys_AddWarnOptionUnicode() function.
 
-- PyObject_Dump() encodes unicode objects to utf8 with backslashreplace
-  (instead of strict) error handler to escape surrogates
+- PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead
+  of strict) error handler to escape surrogates.
 
 - Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode
   object to Py_FileSystemDefaultEncoding with the "surrogateescape" error
-  handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall
+  handler, and return bytes.  If Py_FileSystemDefaultEncoding is not set, fall
   back to UTF-8.
 
 - Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any
-  error handler, not only the default error handler (strict)
+  error handler, not only the default error handler (strict).
 
 - Issue #8610: Load file system codec at startup, and display a fatal error on
-  failure. Set the file system encoding to utf-8 (instead of None) if getting
+  failure.  Set the file system encoding to utf-8 (instead of None) if getting
   the locale encoding failed, or if nl_langinfo(CODESET) function is missing.
 
 - PyFile_FromFd() uses PyUnicode_DecodeFSDefault() instead of
-  PyUnicode_FromString() to support surrogates in the filename and use the
-  right encoding
+  PyUnicode_FromString() to support surrogates in the filename and use the right
+  encoding.
 
 - Issue #7507: Quote "!" in pipes.quote(); it is special to some shells.
 
-- PyUnicode_DecodeFSDefaultAndSize() uses surrogateescape error handler
+- PyUnicode_DecodeFSDefaultAndSize() uses surrogateescape error handler.
 
 - Issue #8419: Prevent the dict constructor from accepting non-string keyword
   arguments.
 
 - Issue #8124: PySys_WriteStdout() and PySys_WriteStderr() don't execute
-  indirectly Python signal handlers anymore because mywrite() ignores
-  exceptions (KeyboardInterrupt)
+  indirectly Python signal handlers anymore because mywrite() ignores exceptions
+  (KeyboardInterrupt).
 
 - Issue #8092: Fix PyUnicode_EncodeUTF8() to support error handler producing
-  unicode string (eg. backslashreplace)
+  unicode string (eg. backslashreplace).
 
-- Issue #8485: PyUnicode_FSConverter() doesn't accept bytearray object anymore,
-  you have to convert your bytearray filenames to bytes
+- Issue #8485: PyUnicode_FSConverter() doesn't accept byteearray objects
+  anymore, you have to convert your bytearray filenames to bytes.
 
 - Issue #7332: Remove the 16KB stack-based buffer in
-  PyMarshal_ReadLastObjectFromFile, which doesn't bring any noticeable
-  benefit compared to the dynamic memory allocation fallback.  Patch by
-  Charles-François Natali.
+  PyMarshal_ReadLastObjectFromFile, which doesn't bring any noticeable benefit
+  compared to the dynamic memory allocation fallback.  Patch by Charles-François
+  Natali.
 
 - Issue #8417: Raise an OverflowError when an integer larger than sys.maxsize is
   passed to bytes or bytearray.
@@ -156,9 +293,9 @@
 - Issue #8329: Don't return the same lists from select.select when no fds are
   changed.
 
-- Issue #8259: 1L << (2**31) no longer produces an 'outrageous shift error'
-  on 64-bit machines.  The shift count for either left or right shift is
-  permitted to be up to sys.maxsize.
+- Issue #8259: 1L << (2**31) no longer produces an 'outrageous shift error' on
+  64-bit machines.  The shift count for either left or right shift is permitted
+  to be up to sys.maxsize.
 
 - Ensure that tokenization of identifiers is not affected by locale.
 
@@ -166,16 +303,16 @@
 
 - Raise a TypeError when trying to delete a T_STRING_INPLACE struct member.
 
-- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in
-  case it is set.
+- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in case it
+  is set.
 
 - Issue #8226: sys.setfilesystemencoding() raises a LookupError if the encoding
-  is unknown
+  is unknown.
 
-- Issue #1583863: An str subclass can now override the __str__ method
+- Issue #1583863: A str subclass can now override the __str__ method.
 
 - Issue #8014: Setting a T_UINT or T_PYSSIZET attribute of an object with
-  PyMemberDefs could produce an internal error;  raise TypeError instead.
+  PyMemberDefs could produce an internal error; raise TypeError instead.
 
 - Issue #7845: Rich comparison methods on the complex type now return
   NotImplemented rather than raising a TypeError when comparing with an
@@ -184,72 +321,66 @@
 
 - Issue #3137: Don't ignore errors at startup, especially a keyboard interrupt
   (SIGINT). If an error occurs while importing the site module, the error is
-  printed and Python exits. Initialize the GIL before importing the site
-  module.
+  printed and Python exits. Initialize the GIL before importing the site module.
 
 - Issue #7173: Generator finalization could invalidate sys.exc_info().
 
-- Issue #7544: Preallocate thread memory before creating the thread to avoid
-  a fatal error in low memory condition.
+- Issue #7544: Preallocate thread memory before creating the thread to avoid a
+  fatal error in low memory condition.
 
-- Issue #7820: The parser tokenizer restores all bytes in the right if
-  the BOM check fails.
+- Issue #7820: The parser tokenizer restores all bytes in the right if the BOM
+  check fails.
 
 - Handle errors from looking up __prepare__ correctly.
 
-- Issue #5939: Add additional runtime checking to ensure a valid capsule
-  in Modules/_ctypes/callproc.c.
+- Issue #5939: Add additional runtime checking to ensure a valid capsule in
+  Modules/_ctypes/callproc.c.
 
 - Issue #7309: Fix unchecked attribute access when converting
-  UnicodeEncodeError, UnicodeDecodeError, and UnicodeTranslateError to
-  strings.
+  UnicodeEncodeError, UnicodeDecodeError, and UnicodeTranslateError to strings.
 
-- Issue #6902: Fix problem with built-in types format incorrectly with
-  0 padding.
+- Issue #6902: Fix problem with built-in types format incorrectly with 0
+  padding.
 
-- Issue #7988: Fix default alignment to be right aligned for
-  complex.__format__. Now it matches other numeric types.
+- Issue #7988: Fix default alignment to be right aligned for complex.__format__.
+  Now it matches other numeric types.
 
 - Issue #5988: Remove deprecated functions PyOS_ascii_formatd,
-  PyOS_ascii_strtod, and PyOS_ascii_atof. Use PyOS_double_to_string
-  and PyOS_string_to_double instead. See issue #5835 for the original
-  deprecations.
-
-- Issue #7385: Fix a crash in `MemoryView_FromObject` when
-  `PyObject_GetBuffer` fails.  Patch by Florent Xicluna.
-
-- Issue #7788: Fix an interpreter crash produced by deleting a list
-  slice with very large step value.
-
-- Issue #7766: Change sys.getwindowsversion() return value to a named
-  tuple and add the additional members returned in an OSVERSIONINFOEX
-  structure. The new members are service_pack_major, service_pack_minor,
-  suite_mask, and product_type.
-
-- Issue #7561: Operations on empty bytearrays (such as `int(bytearray())`)
-  could crash in many places because of the PyByteArray_AS_STRING() macro
-  returning NULL.  The macro now returns a statically allocated empty
-  string instead.
+  PyOS_ascii_strtod, and PyOS_ascii_atof.  Use PyOS_double_to_string and
+  PyOS_string_to_double instead.  See issue #5835 for the original deprecations.
+
+- Issue #7385: Fix a crash in `MemoryView_FromObject` when `PyObject_GetBuffer`
+  fails.  Patch by Florent Xicluna.
+
+- Issue #7788: Fix an interpreter crash produced by deleting a list slice with
+  very large step value.
+
+- Issue #7766: Change sys.getwindowsversion() return value to a named tuple and
+  add the additional members returned in an OSVERSIONINFOEX structure.  The new
+  members are service_pack_major, service_pack_minor, suite_mask, and
+  product_type.
+
+- Issue #7561: Operations on empty bytearrays (such as `int(bytearray())`) could
+  crash in many places because of the PyByteArray_AS_STRING() macro returning
+  NULL.  The macro now returns a statically allocated empty string instead.
 
 - Issue #6690: Optimize the bytecode for expressions such as `x in {1, 2, 3}`,
-  where the right hand operand is a set of constants, by turning the set into
-  a frozenset and pre-building it as a constant.  The comparison operation
-  is made against the constant instead of building a new set each time it is
-  executed (a similar optimization already existed which turned a list of
-  constants into a pre-built tuple).  Patch and additional tests by Dave
-  Malcolm.
-
-- Issue #7622: Improve the split(), rsplit(), splitlines() and replace()
-  methods of bytes, bytearray and unicode objects by using a common
-  implementation based on stringlib's fast search.  Patch by Florent Xicluna.
-
-- Issue #7632: Fix various str -> float conversion bugs present in 2.7
-  alpha 2, including: (1) a serious 'wrong output' bug that could
-  occur for long (> 40 digit) input strings, (2) a crash in dtoa.c
-  that occurred in debug builds when parsing certain long numeric
-  strings corresponding to subnormal values, (3) a memory leak for
-  some values large enough to cause overflow, and (4) a number of
-  flaws that could lead to incorrectly rounded results.
+  where the right hand operand is a set of constants, by turning the set into a
+  frozenset and pre-building it as a constant.  The comparison operation is made
+  against the constant instead of building a new set each time it is executed (a
+  similar optimization already existed which turned a list of constants into a
+  pre-built tuple).  Patch and additional tests by Dave Malcolm.
+
+- Issue #7622: Improve the split(), rsplit(), splitlines() and replace() methods
+  of bytes, bytearray and unicode objects by using a common implementation based
+  on stringlib's fast search.  Patch by Florent Xicluna.
+
+- Issue #7632: Fix various str -> float conversion bugs present in 2.7 alpha 2,
+  including: (1) a serious 'wrong output' bug that could occur for long (> 40
+  digit) input strings, (2) a crash in dtoa.c that occurred in debug builds when
+  parsing certain long numeric strings corresponding to subnormal values, (3) a
+  memory leak for some values large enough to cause overflow, and (4) a number
+  of flaws that could lead to incorrectly rounded results.
 
 - The __complex__ method is now looked up on the class of instances to make it
   consistent with other special methods.
@@ -260,24 +391,23 @@
 - Issue #7604: Deleting an unset slotted attribute did not raise an
   AttributeError.
 
-- Issue #7534: Fix handling of IEEE specials (infinities, nans,
-  negative zero) in ** operator.  The behaviour now conforms to that
-  described in C99 Annex F.
-
-- Issue #1811: improve accuracy and cross-platform consistency for
-  true division of integers: the result of a/b is now correctly
-  rounded for ints a and b (at least on IEEE 754 platforms), and in
-  particular does not depend on the internal representation of an int.
+- Issue #7534: Fix handling of IEEE specials (infinities, nans, negative zero)
+  in ** operator.  The behaviour now conforms to that described in C99 Annex F.
+
+- Issue #1811: improve accuracy and cross-platform consistency for true division
+  of integers: the result of a/b is now correctly rounded for ints a and b (at
+  least on IEEE 754 platforms), and in particular does not depend on the
+  internal representation of an int.
 
 - Issue #6834: replace the implementation for the 'python' and 'pythonw'
   executables on OSX.
 
-  These executables now work properly with the arch(1) command:
-  ``arch -ppc python`` will start a universal binary version of python
-  in PPC mode (unlike previous releases).
+  These executables now work properly with the arch(1) command: ``arch -ppc
+  python`` will start a universal binary version of python in PPC mode (unlike
+  previous releases).
 
-- Issue #7466: segmentation fault when the garbage collector is called
-  in the middle of populating a tuple.  Patch by Florent Xicluna.
+- Issue #7466: Segmentation fault when the garbage collector is called in the
+  middle of populating a tuple.  Patch by Florent Xicluna.
 
 - Issue #7419: setlocale() could crash the interpreter on Windows when called
   with invalid values.
@@ -285,22 +415,22 @@
 - Issue #6077: On Windows, files opened with tempfile.TemporaryFile in "wt+"
   mode would appear truncated on the first '0x1a' byte (aka. Ctrl+Z).
 
-- Issue #7085: Fix crash when importing some extensions in a thread
-  on MacOSX 10.6.
+- Issue #7085: Fix crash when importing some extensions in a thread on MacOSX
+  10.6.
 
 - Issue #1757126: Fix the cyrillic-asian alias for the ptcp154 encoding.
 
 - Issue #6970: Remove redundant calls when comparing objects that don't
   implement the relevant rich comparison methods.
 
-- Issue #7298: fixes for range and reversed(range(...)).  Iteration
-  over range(a, b, c) incorrectly gave an empty iterator when a, b and
-  c fit in C long but the length of the range did not.  Also fix
-  several cases where reversed(range(a, b, c)) gave wrong results, and
-  fix a refleak for reversed(range(a, b, c)) with large arguments.
+- Issue #7298: Fixes for range and reversed(range(...)).  Iteration over
+  range(a, b, c) incorrectly gave an empty iterator when a, b and c fit in C
+  long but the length of the range did not.  Also fix several cases where
+  reversed(range(a, b, c)) gave wrong results, and fix a refleak for
+  reversed(range(a, b, c)) with large arguments.
 
-- Issue #7244: itertools.izip_longest() no longer ignores exceptions
-  raised during the formation of an output tuple.
+- Issue #7244: itertools.izip_longest() no longer ignores exceptions raised
+  during the formation of an output tuple.
 
 - Issue #3297: On wide unicode builds, do not split unicode characters into
   surrogates.
@@ -317,7 +447,7 @@
   will be entirely removed in 3.3.
 
 - Support for OSF* has been disabled. If nobody stands up, support will be
-  removed in 3.3. See http://bugs.python.org/issue8606 .
+  removed in 3.3. See <http://bugs.python.org/issue8606>.
 
 - Peephole constant folding had missed UNARY_POSITIVE.
 
@@ -328,26 +458,26 @@
 - Issue #7147: Remove support for compiling Python without complex number
   support.
 
-- Issue #7120: logging: Removed import of multiprocessing which is causing
-  crash in GAE.
+- Issue #7120: logging: Removed import of multiprocessing which is causing crash
+  in GAE.
 
-- Issue #1754094: Improve the stack depth calculation in the compiler.
-  There should be no other effect than a small decrease in memory use.
-  Patch by Christopher Tur Lesniewski-Laas.
+- Issue #1754094: Improve the stack depth calculation in the compiler.  There
+  should be no other effect than a small decrease in memory use.  Patch by
+  Christopher Tur Lesniewski-Laas.
 
-- Issue #7065: Fix a crash in bytes.maketrans and bytearray.maketrans when
-  using byte values greater than 127.  Patch by Derk Drukker.
+- Issue #7065: Fix a crash in bytes.maketrans and bytearray.maketrans when using
+  byte values greater than 127.  Patch by Derk Drukker.
 
 - Issue #1571184: The Unicode database contains properties for more characters.
   The tables for code points representing numeric values, white spaces or line
   breaks are now generated from the official Unicode Character Database files,
   and include information from the Unihan.txt file.
 
-- Issue #7019: Raise ValueError when unmarshalling bad long data, instead
-  of producing internally inconsistent Python longs.
+- Issue #7019: Raise ValueError when unmarshalling bad long data, instead of
+  producing internally inconsistent Python longs.
 
-- Issue #6990: Fix threading.local subclasses leaving old state around
-  after a reference cycle GC which could be recycled by new locals.
+- Issue #6990: Fix threading.local subclasses leaving old state around after a
+  reference cycle GC which could be recycled by new locals.
 
 - Issue #5460: Fix an ambiguity in the grammar.
 
@@ -357,8 +487,8 @@
 
 - Issue #6846: Fix bug where bytearray.pop() returns negative integers.
 
-- Issue #6750: A text file opened with io.open() could duplicate its output
-  when writing from multiple threads at the same time.
+- Issue #6750: A text file opened with io.open() could duplicate its output when
+  writing from multiple threads at the same time.
 
 - Issue #6707: dir() on an uninitialized module caused a crash.
 
@@ -367,85 +497,85 @@
 - Issue #6573: set.union() stopped processing inputs if an instance of self
   occurred in the argument chain.
 
-- Issue #6070: On posix platforms import no longer copies the execute bit
-  from the .py file to the .pyc file if it is set.
+- Issue #6070: On posix platforms import no longer copies the execute bit from
+  the .py file to the .pyc file if it is set.
 
 - Issue #1616979: Added the cp720 (Arabic DOS) encoding.
 
-- Issue #6428: Since Python 3.0, the __bool__ method must return a bool
-  object, and not an int.  Fix the corresponding error message, and the
-  documentation.
+- Issue #6428: Since Python 3.0, the __bool__ method must return a bool object,
+  and not an int.  Fix the corresponding error message, and the documentation.
 
 - The deprecated PyCObject has been removed.
 
-- Issue #6347: Include inttypes.h as well as stdint.h in pyport.h.
-  This fixes a build failure on HP-UX: int32_t and uint32_t are
-  defined in inttypes.h instead of stdint.h on that platform.
+- Issue #6347: Include inttypes.h as well as stdint.h in pyport.h.  This fixes a
+  build failure on HP-UX: int32_t and uint32_t are defined in inttypes.h instead
+  of stdint.h on that platform.
 
-- Issue #6373: Fixed a SystemError when encoding with the latin-1 codec and
-  the 'surrogateescape' error handler, a string which contains unpaired
-  surrogates.
+- Issue #6373: Fixed a SystemError when encoding with the latin-1 codec and the
+  'surrogateescape' error handler, a string which contains unpaired surrogates.
 
 - Issue #4856: Remove checks for win NT.
 
-- Issue #6687: PyBytes_FromObject() no longer accepts an integer as its
-  argument to construct a null-initialized bytes object.
+- Issue #6687: PyBytes_FromObject() no longer accepts an integer as its argument
+  to construct a null-initialized bytes object.
 
-- Issue #1023290: Add from_bytes() and to_bytes() methods to integers.
-  These methods allow the conversion of integers to bytes, and vice-versa.
+- Issue #1023290: Add from_bytes() and to_bytes() methods to integers.  These
+  methods allow the conversion of integers to bytes, and vice-versa.
 
-- Issue #7382: Fix bug in bytes.__getnewargs__ that prevented bytes
-  instances from being copied with copy.copy(), and bytes subclasses
-  from being pickled properly.
+- Issue #7382: Fix bug in bytes.__getnewargs__ that prevented bytes instances
+  from being copied with copy.copy(), and bytes subclasses from being pickled
+  properly.
 
 - Code objects now support weak references.
 
-- Issue #7072: isspace(0xa0) is true on Mac OS X
+- Issue #7072: isspace(0xa0) is true on Mac OS X.
 
-- Issue #8084: PEP 370 now conforms to system conventions for framework
-  builds on MacOS X. That is, "python setup.py install --user" will install
+- Issue #8084: PEP 370 now conforms to system conventions for framework builds
+  on MacOS X. That is, "python setup.py install --user" will install
     into "~/Library/Python/2.7" instead of "~/.local".
 
 C-API
 -----
 
-- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows
-  embedders of the interpreter to set sys.argv without also modifying
-  sys.path.  This helps fix `CVE-2008-5983
+- PySlice_GetIndicesEx now clips the step to [-PY_SSIZE_T_MAX, PY_SSIZE_T_MAX]
+  instead of [-PY_SSIZE_T_MAX-1, PY_SSIZE_T_MAX].  This makes it safe to do
+  "step = -step" when reversing a slice.
+
+- Issue #5753: A new C API function, `PySys_SetArgvEx`, allows embedders of the
+  interpreter to set sys.argv without also modifying sys.path.  This helps fix
+  `CVE-2008-5983
   <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
 
 - Add PyArg_ValidateKeywordArguments, which checks if all keyword arguments are
   strings in an efficient manner.
 
 - Issue #8276: PyEval_CallObject() is now only available in macro form.  The
-  function declaration, which was kept for backwards compatibility reasons,
-  is now removed (the macro was introduced in 1997!).
+  function declaration, which was kept for backwards compatibility reasons, is
+  now removed (the macro was introduced in 1997!).
 
-- Issue #7767: New function PyLong_AsLongLongAndOverflow added,
-  analogous to PyLong_AsLongAndOverflow.
+- Issue #7767: New function PyLong_AsLongLongAndOverflow added, analogous to
+  PyLong_AsLongAndOverflow.
 
 - Make PyUnicode_CompareWithASCIIString return not equal if the Python string
   has '\0' at the end.
 
 - Issue #5080: The argument parsing functions PyArg_ParseTuple,
-  PyArg_ParseTupleAndKeywords, PyArg_VaParse,
-  PyArg_VaParseTupleAndKeywords and PyArg_Parse now raise a
-  DeprecationWarning for float arguments passed with the 'L' format
-  code.  This will become a TypeError in a future version of Python,
+  PyArg_ParseTupleAndKeywords, PyArg_VaParse, PyArg_VaParseTupleAndKeywords and
+  PyArg_Parse now raise a DeprecationWarning for float arguments passed with the
+  'L' format code.  This will become a TypeError in a future version of Python,
   to match the behaviour of the other integer format codes.
 
-- Issue #7033: function ``PyErr_NewExceptionWithDoc()`` added.
+- Issue #7033: Function ``PyErr_NewExceptionWithDoc()`` added.
 
-- Issue #7414: 'C' code wasn't being skipped properly (for keyword arguments)
-  in PyArg_ParseTupleAndKeywords.
+- Issue #7414: 'C' code wasn't being skipped properly (for keyword arguments) in
+  PyArg_ParseTupleAndKeywords.
 
-- Issue #7228: Add '%lld' and '%llu' support to PyString_FromFormat(V)
-  and PyErr_Format, on machines with HAVE_LONG_LONG defined.
+- Issue #7228: Add '%lld' and '%llu' support to PyString_FromFormat(V) and
+  PyErr_Format, on machines with HAVE_LONG_LONG defined.
 
-- Issue #6151: Made PyDescr_COMMON conform to standard C (like PyObject_HEAD
-  in PEP 3123).  The PyDescr_TYPE and PyDescr_NAME macros should be
-  should used for accessing the d_type and d_name members of structures
-  using PyDescr_COMMON.
+- Issue #6151: Made PyDescr_COMMON conform to standard C (like PyObject_HEAD in
+  PEP 3123).  The PyDescr_TYPE and PyDescr_NAME macros should be should used for
+  accessing the d_type and d_name members of structures using PyDescr_COMMON.
 
 - Issue #6405: Remove duplicate type declarations in descrobject.h.
 
@@ -460,30 +590,162 @@
 - Issue #1419652: Change the first argument to PyImport_AppendInittab() to
   ``const char *`` as the string is stored beyond the call.
 
-- Issue #2422: When compiled with the ``--with-valgrind`` option, the
-  pymalloc allocator will be automatically disabled when running under
-  Valgrind.  This gives improved memory leak detection when running
-  under Valgrind, while taking advantage of pymalloc at other times.
+- Issue #2422: When compiled with the ``--with-valgrind`` option, the pymalloc
+  allocator will be automatically disabled when running under Valgrind.  This
+  gives improved memory leak detection when running under Valgrind, while taking
+  advantage of pymalloc at other times.
 
 Library
 -------
 
+- In pdb, when Ctrl-C is entered while defining commands for a breakpoint, the
+  old commands are restored.
+
+- For traceback debugging, the pdb listing now also shows the locations where
+  the exception was originally (re)raised, if it differs from the last line
+  executed (e.g. in case of finally clauses).
+
+- The pdb command "source" has been added.  It displays the source code for a
+  given object, if possible.
+
+- The pdb command "longlist" has been added.  It displays the whole source code
+  for the current function.
+
+- Issue #1503502: Make pdb.Pdb easier to subclass by putting message and error
+  output into methods.
+
+- Issue #809887: Make the output of pdb's breakpoint deletions more consistent;
+  emit a message when a breakpoint is enabled or disabled.
+
+- Issue #5294: Fix the behavior of pdb's "continue" command when called in the
+  top-level debugged frame.
+
+- Issue #5727: Restore the ability to use readline when calling into pdb in
+  doctests.
+
+- Issue #6719: In pdb, do not stop somewhere in the encodings machinery if the
+  source file to be debugged is in a non-builtin encoding.
+
+- Issue #8048: Prevent doctests from failing when sys.displayhook has been
+  reassigned.
+
+- Issue #8015: In pdb, do not crash when an empty line is entered as a
+  breakpoint command.
+
+- In pdb, allow giving a line number to the "until" command.
+
+- Issue #1437051: For pdb, allow "continue" and related commands in .pdbrc
+  files.  Also, add a command-line option "-c" that runs a command as if given
+  in .pdbrc.
+
+- Issue #4179: In pdb, allow "list ." as a command to return to the currently
+  debugged line.
+
+- Issue #4108: In urllib.robotparser, if there are multiple 'User-agent: *'
+  entries, consider the first one.
+
+- Issue #6630: Allow customizing regex flags when subclassing the
+  string.Template class.
+
+- Issue #9411: Allow specifying an encoding for config files in the configparser
+  module.
+
+- Issue #1682942: Improvements to configparser: support alternate delimiters,
+  alternate comment prefixes and empty lines in values.
+
+- Issue #9354: Provide getsockopt() in asyncore's file_wrapper.
+
+- Issue #8966: ctypes: Remove implicit bytes-unicode conversion.
+
+- Issue #9378: python -m pickle <pickle file> will now load and display the
+  first object in the pickle file.
+
+- Issue #4770: Restrict binascii module to accept only bytes (as specified).
+  And fix the email package to encode to ASCII instead of ``raw-unicode-escape``
+  before ASCII-to-binary decoding.
+
+- Issue #9384: ``python -m tkinter`` will now display a simple demo applet.
+
+- The default size of the re module's compiled regular expression cache has been
+  increased from 100 to 500 and the cache replacement policy has changed from
+  simply clearing the entire cache on overflow to randomly forgetting 20% of the
+  existing cached compiled regular expressions.  This is a performance win for
+  applications that use a lot of regular expressions and limits the impact of
+  the performance hit anytime the cache is exceeded.
+
+- Issue #7113: Speed up loading in configparser. Patch by Łukasz Langa.
+
+- Issue #9032: XML-RPC client retries the request on EPIPE error.  The EPIPE
+  error occurs when the server closes the socket and the client sends a big
+  XML-RPC request.
+
+- Issue #4629: getopt raises an error if an argument ends with "=", whereas
+  getopt doesn't accept a value (eg. --help= is rejected if getopt uses
+  ['help='] long options).
+
+- Issue #7989: Added pure python implementation of the `datetime` module.  The C
+  module is renamed to `_datetime` and if available, overrides all classes
+  defined in datetime with fast C impementation.  Python implementation is based
+  on the original python prototype for the datetime module by Tim Peters with
+  minor modifications by the PyPy project.  The test suite now tests `datetime`
+  module with and without `_datetime` acceleration using the same test cases.
+
+- Issue #7895: platform.mac_ver() no longer crashes after calling os.fork().
+
+- Issue #9323: Fixed a bug in trace.py that resulted in loosing the name of the
+  script being traced.  Patch by Eli Bendersky.
+
+- Issue #9282: Fixed --listfuncs option of trace.py.  Thanks Eli Bendersky for
+  the patch.
+
+- Issue #3704: http.cookiejar was not properly handling URLs with a / in the
+  parameters.
+
+- Issue #9268: ``pickletools.dis()`` now has an optional *annotate* argument
+  which controls printing of opcode descriptions in ``dis()`` output.
+
+- Issue #1555570: email no longer inserts extra blank lines when a \r\n combo
+  crosses an 8192 byte boundary.
+
+- Issue #9243: Fix sndhdr module and add unit tests, contributed by James Lee.
+
+- ``ast.literal_eval()`` now allows byte literals.
+
+- Issue #9137: Fix issue in MutableMapping.update, which incorrectly treated
+  keyword arguments called 'self' or 'other' specially.
+
+- ``ast.literal_eval()`` now allows set literals.
+
+- Issue #9164: Ensure that sysconfig handles duplicate -arch flags in CFLAGS.
+
+- Issue #7646: The fnmatch pattern cache no longer grows without bound.
+
+- Issue #9136: Fix 'dictionary changed size during iteration' RuntimeError
+  produced when profiling the decimal module.  This was due to a dangerous
+  iteration over 'locals()' in Context.__init__.
+
+- Fix extreme speed issue in Decimal.pow when the base is an exact power of 10
+  and the exponent is tiny (for example, ``Decimal(10) **
+  Decimal('1e-999999999')``).
+
+- Issue #9186: Fix math.log1p(-1.0) to raise ValueError, not OverflowError.
+
 - Issue #9130: Fix validation of relative imports in parser module.
 
 - Issue #9128: Fix validation of class decorators in parser module.
 
-- Issue #9094: python -m pickletools will now disassemble pickle files
-  listed in the command line arguments.  See output of python -m
-  pickletools -h for more details.
+- Issue #9094: python -m pickletools will now disassemble pickle files listed in
+  the command line arguments.  See output of python -m pickletools -h for more
+  details.
 
 - Issue #5468: urlencode to handle bytes type and other encodings in its query
   parameter. Patch by Dan Mahn.
 
-- Issue #7673: Fix security vulnerability (CVE-2010-2089) in the audioop
-  module, ensure that the input string length is a multiple of the frame size
+- Issue #7673: Fix security vulnerability (CVE-2010-2089) in the audioop module,
+  ensure that the input string length is a multiple of the frame size.
 
-- Issue #6507: Accept source strings in dis.dis(). Original patch by
-  Daniel Urban.
+- Issue #6507: Accept source strings in dis.dis().  Original patch by Daniel
+  Urban.
 
 - Issue #7829: Clearly document that the dis module is exposing an
   implementation detail that is not stable between Python VMs or releases.
@@ -492,73 +754,72 @@
   raises an exception.
 
 - Issue #9110: Addition of ContextDecorator to contextlib, for creating APIs
-  that act as both context managers and decorators. contextmanager changes
-  to use ContextDecorator.
+  that act as both context managers and decorators. contextmanager changes to
+  use ContextDecorator.
 
 - Implement importlib.abc.SourceLoader and deprecate PyLoader and PyPycLoader
   for removal in Python 3.4.
 
-- Issue #9064: pdb's "up" and "down" commands now accept an optional argument.
+- Issue #9064: pdb's "up" and "down" commands now accept an optional argument
+  giving the number of frames to go.
 
-- Issue #9018: os.path.normcase() now raises a TypeError if the argument is
-  not ``str`` or ``bytes``.
+- Issue #9018: os.path.normcase() now raises a TypeError if the argument is not
+  ``str`` or ``bytes``.
 
-- Issue #9075: In the ssl module, remove the setting of a ``debug`` flag
-  on an OpenSSL structure.
+- Issue #9075: In the ssl module, remove the setting of a ``debug`` flag on an
+  OpenSSL structure.
 
-- Issue #8682: The ssl module now temporary increments the reference count of
-  a socket object got through ``PyWeakref_GetObject``, so as to avoid possible
+- Issue #8682: The ssl module now temporary increments the reference count of a
+  socket object got through ``PyWeakref_GetObject``, so as to avoid possible
   deallocation while the object is still being used.
 
 - Issue #1368368: FancyURLOpener class changed to throw an Exception on wrong
-  password instead of presenting an interactive prompt. Older behavior can be
+  password instead of presenting an interactive prompt.  Older behavior can be
   obtained by passing retry=True to http_error_xxx methods of FancyURLOpener.
 
-- Issue #8720: fix regression caused by fix for #4050 by making getsourcefile
+- Issue #8720: Fix regression caused by fix for #4050 by making getsourcefile
   smart enough to find source files in the linecache.
 
-- Issue #5610: feedparser no longer eats extra characters at the end of
-  a body part if the body part ends with a \r\n.
+- Issue #5610: feedparser no longer eats extra characters at the end of a body
+  part if the body part ends with a ``\r\n``.
 
-- Issue #8986: math.erfc was incorrectly raising OverflowError for
-  values between -27.3 and -30.0 on some platforms.
+- Issue #8986: math.erfc was incorrectly raising OverflowError for values
+  between -27.3 and -30.0 on some platforms.
 
 - Issue #8784: Set tarfile default encoding to 'utf-8' on Windows.
 
 - Issue #8966: If a ctypes structure field is an array of c_char, convert its
   value to bytes instead of str (as done for c_char and c_char_p).
 
-- Issue #8188: Comparisons between Decimal and Fraction objects are
-  now permitted, returning a result based on the exact numerical
-  values of the operands.  This builds on issue #2531, which allowed
-  Decimal-to-float comparisons;  all comparisons involving numeric
-  types (bool, int, float, complex, Decimal, Fraction) should now
-  act as expected.
+- Issue #8188: Comparisons between Decimal and Fraction objects are now
+  permitted, returning a result based on the exact numerical values of the
+  operands.  This builds on issue #2531, which allowed Decimal-to-float
+  comparisons; all comparisons involving numeric types (bool, int, float,
+  complex, Decimal, Fraction) should now act as expected.
 
-- Issue #8897: Fix sunau module, use bytes to write the header. Patch written
-  by Thomas Jollans.
+- Issue #8897: Fix sunau module, use bytes to write the header. Patch written by
+  Thomas Jollans.
 
 - Issue #8899: time.struct_time now has class and atribute docstrings.
 
 - Issue #6470: Drop UNC prefix in FixTk.
 
-- Issue #4768: base64 encoded email body parts were incorrectly stored as
-  binary strings.  They are now correctly converted to strings.
+- Issue #4768: base64 encoded email body parts were incorrectly stored as binary
+  strings.  They are now correctly converted to strings.
 
 - Issue #8833: tarfile created hard link entries with a size field != 0 by
   mistake.
 
-- Charset.body_encode now correctly handles base64 encoding by encoding
-  with the output_charset before calling base64mime.encode.  Passes the
-  tests from 2.x issue 1368247.
+- Charset.body_encode now correctly handles base64 encoding by encoding with the
+  output_charset before calling base64mime.encode.  Passes the tests from 2.x
+  issue #1368247.
 
 - Issue #8845: sqlite3 Connection objects now have a read-only in_transaction
   attribute that is True iff there are uncommitted changes.
 
-- Issue #1289118: datetime.timedelta objects can now be multiplied by float
-  and divided by float and int objects.  Results are rounded to the nearest
-  multiple of timedelta.resolution with ties resolved using round-half-to-even
-  method.
+- Issue #1289118: datetime.timedelta objects can now be multiplied by float and
+  divided by float and int objects.  Results are rounded to the nearest multiple
+  of timedelta.resolution with ties resolved using round-half-to-even method.
 
 - Issue #7150: Raise OverflowError if the result of adding or subtracting
   timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range.
@@ -567,25 +828,24 @@
 
 - Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer
   and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes
-  API
+  API.
 
-- Issue #8770: now sysconfig displays information when it's called as
-  a script. Initial idea by Sridhar Ratnakumar.
+- Issue #8770: Now sysconfig displays information when it's called as a script.
+  Initial idea by Sridhar Ratnakumar.
 
 - Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by
-  Fredrik Håård
+  Fredrik Håård.
 
 - Issue #8540: Decimal module: rename the Context._clamp attribute to
-  Context.clamp and make it public.  This is useful in creating
-  contexts that correspond to the decimal interchange formats
-  specified in IEEE 754.
+  Context.clamp and make it public.  This is useful in creating contexts that
+  correspond to the decimal interchange formats specified in IEEE 754.
 
 - Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM
   twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and
   StreamWriter classes.
 
 - Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead
-  of the C file stderr, to use stderr encoding and error handler
+  of the C file stderr, to use stderr encoding and error handler.
 
 - Issue #8782: Add a trailing newline in linecache.updatecache to the last line
   of files without one.
@@ -594,11 +854,11 @@
   comparing to a non-mapping.
 
 - Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the
-  correct encoding
+  correct encoding.
 
-- Issue #4870: Add an `options` attribute to SSL contexts, as well as
-  several ``OP_*`` constants to the `ssl` module.  This allows to selectively
-  disable protocol versions, when used in combination with `PROTOCOL_SSLv23`.
+- Issue #4870: Add an `options` attribute to SSL contexts, as well as several
+  ``OP_*`` constants to the `ssl` module.  This allows to selectively disable
+  protocol versions, when used in combination with `PROTOCOL_SSLv23`.
 
 - Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes.
 
@@ -620,15 +880,15 @@
 - Issue #8688: Distutils now recalculates MANIFEST everytime.
 
 - Issue #8477: ssl.RAND_egd() and ssl._test_decode_cert() support str with
-  surrogates and bytes for the filename
+  surrogates and bytes for the filename.
 
 - Issue #8550: Add first class ``SSLContext`` objects to the ssl module.
 
-- Issue #8681: Make the zlib module's error messages more informative when
-  the zlib itself doesn't give any detailed explanation.
+- Issue #8681: Make the zlib module's error messages more informative when the
+  zlib itself doesn't give any detailed explanation.
 
-- The audioop module now supports sound fragments of length greater
-  than 2**31 bytes on 64-bit machines, and is PY_SSIZE_T_CLEAN.
+- The audioop module now supports sound fragments of length greater than 2**31
+  bytes on 64-bit machines, and is PY_SSIZE_T_CLEAN.
 
 - Issue #4972: Add support for the context manager protocol to the ftplib.FTP
   class.
@@ -639,9 +899,8 @@
 - Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes
   for use in the file system, environment variables or the command line.
 
-- Issue #8571: Fix an internal error when compressing or decompressing a
-  chunk larger than 1GB with the zlib module's compressor and decompressor
-  objects.
+- Issue #8571: Fix an internal error when compressing or decompressing a chunk
+  larger than 1GB with the zlib module's compressor and decompressor objects.
 
 - Issue #8603: Support bytes environmental variables on Unix: Add os.environb
   mapping and os.getenvb() function. os.unsetenv() encodes str argument to the
@@ -650,46 +909,46 @@
 
 - Issue #8573: asyncore _strerror() function might throw ValueError.
 
-- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing
-  error messages when accessing undefined class attributes because of the cheap
-  inheritance with the underlying socket object.
-  The cheap inheritance has been deprecated.
+- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing error
+  messages when accessing undefined class attributes because of the cheap
+  inheritance with the underlying socket object.  The cheap inheritance has been
+  deprecated.
 
 - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills.
   Patch by Tres Seaver.
 
 - Issue #8390: tarfile uses surrogateespace as the default error handler
-  (instead of replace in read mode or strict in write mode)
+  (instead of replace in read mode or strict in write mode).
 
 - Issue #7755: Use an unencumbered audio file for tests.
 
-- Issue #8621: uuid.uuid4() returned the same sequence of values in the
-  parent and any children created using ``os.fork`` on MacOS X 10.6.
+- Issue #8621: uuid.uuid4() returned the same sequence of values in the parent
+  and any children created using ``os.fork`` on MacOS X 10.6.
 
-- Issue #8567: Fix precedence of signals in Decimal module: when a
-  Decimal operation raises multiple signals and more than one of those
-  signals is trapped, the specification determines the order in which
-  the signals should be handled.  In many cases this order wasn't
-  being followed, leading to the wrong Python exception being raised.
+- Issue #8567: Fix precedence of signals in Decimal module: when a Decimal
+  operation raises multiple signals and more than one of those signals is
+  trapped, the specification determines the order in which the signals should be
+  handled.  In many cases this order wasn't being followed, leading to the wrong
+  Python exception being raised.
 
 - Issue #7865: The close() method of :mod:`io` objects should not swallow
-  exceptions raised by the implicit flush().  Also ensure that calling
-  close() several times is supported.  Patch by Pascal Chambon.
+  exceptions raised by the implicit flush().  Also qensure that calling close()
+  several times is supported.  Patch by Pascal Chambon.
 
 - Issue #4687: Fix accuracy of garbage collection runtimes displayed with
   gc.DEBUG_STATS.
 
-- Issue #8354: The siginterrupt setting is now preserved for all signals,
-  not just SIGCHLD.
+- Issue #8354: The siginterrupt setting is now preserved for all signals, not
+  just SIGCHLD.
 
 - Issue #7192: webbrowser.get("firefox") now works on Mac OS X, as does
   webbrowser.get("safari").
 
-- Issue #8464: tarfile no longer creates files with execute permissions set
-  when mode="w|" is used.
+- Issue #8464: tarfile no longer creates files with execute permissions set when
+  mode="w|" is used.
 
-- Issue #7834: Fix connect() of Bluetooth L2CAP sockets with recent versions
-  of the Linux kernel.  Patch by Yaniv Aknin.
+- Issue #7834: Fix connect() of Bluetooth L2CAP sockets with recent versions of
+  the Linux kernel.  Patch by Yaniv Aknin.
 
 - Issue #8295: Added shutil.unpack_archive.
 
@@ -704,36 +963,36 @@
 - Issue #6656: fix locale.format_string to handle escaped percents
   and mappings.
 
-- Issue #2302: Fix a race condition in SocketServer.BaseServer.shutdown,
-  where the method could block indefinitely if called just before the
-  event loop started running.  This also fixes the occasional freezes
-  witnessed in test_httpservers.
-
-- Issue #8524: When creating an SSL socket, the timeout value of the
-  original socket wasn't retained (instead, a socket with a positive timeout
-  would be turned into a non-blocking SSL socket).
+- Issue #2302: Fix a race condition in SocketServer.BaseServer.shutdown, where
+  the method could block indefinitely if called just before the event loop
+  started running.  This also fixes the occasional freezes witnessed in
+  test_httpservers.
+
+- Issue #8524: When creating an SSL socket, the timeout value of the original
+  socket wasn't retained (instead, a socket with a positive timeout would be
+  turned into a non-blocking SSL socket).
 
 - Issue #5103: SSL handshake would ignore the socket timeout and block
   indefinitely if the other end didn't respond.
 
-- The do_handshake() method of SSL objects now adjusts the blocking mode of
-  the SSL structure if necessary (as other methods already do).
+- The do_handshake() method of SSL objects now adjusts the blocking mode of the
+  SSL structure if necessary (as other methods already do).
 
-- Issue #8391: os.execvpe() and os.getenv() supports unicode with surrogates
-  and bytes strings for environment keys and values
+- Issue #8391: os.execvpe() and os.getenv() supports unicode with surrogates and
+  bytes strings for environment keys and values.
 
 - Issue #8467: Pure Python implementation of subprocess encodes the error
   message using surrogatepass error handler to support surrogates in the
-  message
+  message.
 
-- Issue #8468: bz2.BZ2File() accepts str with surrogates and bytes filenames
+- Issue #8468: bz2.BZ2File() accepts str with surrogates and bytes filenames.
 
-- Issue #8451: Syslog module now uses basename(sys.argv[0]) instead of
-  the string "python" as the *ident*.  openlog() arguments are all optional
-  and keywords.
+- Issue #8451: Syslog module now uses basename(sys.argv[0]) instead of the
+  string "python" as the *ident*.  openlog() arguments are all optional and
+  keywords.
 
-- Issue #8108: Fix the unwrap() method of SSL objects when the socket has
-  a non-infinite timeout.  Also make that method friendlier with applications
+- Issue #8108: Fix the unwrap() method of SSL objects when the socket has a
+  non-infinite timeout.  Also make that method friendlier with applications
   wanting to continue using the socket in clear-text mode, by disabling
   OpenSSL's internal readahead.  Thanks to Darryl Miles for guidance.
 
@@ -743,25 +1002,24 @@
 - Issue #8195: Fix a crash in sqlite Connection.create_collation() if the
   collation name contains a surrogate character.
 
-- Issue #8484: Load all ciphers and digest algorithms when initializing
-  the _ssl extension, such that verification of some SSL certificates
-  doesn't fail because of an "unknown algorithm".
+- Issue #8484: Load all ciphers and digest algorithms when initializing the _ssl
+  extension, such that verification of some SSL certificates doesn't fail
+  because of an "unknown algorithm".
 
 - Issue #6547: Added the ignore_dangling_symlinks option to shutil.copytree.
 
-- Issue #1540112: Now allowing the choice of a copy function in
-  shutil.copytree.
+- Issue #1540112: Now allowing the choice of a copy function in shutil.copytree.
 
 - Issue #4814: timeout parameter is now applied also for connections resulting
   from PORT/EPRT commands.
 
 - Issue #8463: added missing reference to bztar in shutil's documentation.
 
-- Issue #7154: urllib.request can now detect the proxy settings on OSX 10.6
-  (as long as the user didn't specify 'automatic proxy configuration').
+- Issue #7154: urllib.request can now detect the proxy settings on OSX 10.6 (as
+  long as the user didn't specify 'automatic proxy configuration').
 
-- Issue #3817: ftplib.FTP.abort() method now considers 225 a valid response
-  code as stated in RFC-959 at chapter 5.4.
+- Issue #3817: ftplib.FTP.abort() method now considers 225 a valid response code
+  as stated in RFC-959 at chapter 5.4.
 
 - Issue #8394: _ctypes.dlopen() accepts bytes, bytearray and str with
   surrogates.
@@ -776,95 +1034,92 @@
   the current working directory.
 
 - Issue #7606: XML-RPC traceback stored in X-traceback is now encoded to ASCII
-  using backslashreplace error handler
+  using backslashreplace error handler.
 
-- Issue #8412: os.system() now accepts bytes, bytearray and str with
-  surrogates.
+- Issue #8412: os.system() now accepts bytes, bytearray and str with surrogates.
 
 - Issue #2987: RFC2732 support for urlparse (IPv6 addresses). Patch by Tony
   Locke and Hans Ulrich Niedermann.
 
 - Issue #5277: Fix quote counting when parsing RFC 2231 encoded parameters.
 
-- Issue #7316: the acquire() method of lock objects in the :mod:`threading`
+- Issue #7316: The acquire() method of lock objects in the :mod:`threading`
   module now takes an optional timeout argument in seconds.  Timeout support
-  relies on the system threading library, so as to avoid a semi-busy wait
-  loop.
+  relies on the system threading library, so as to avoid a semi-busy wait loop.
 
 - Issue #8383: pickle and pickletools use surrogatepass error handler when
   encoding unicode as utf8 to support lone surrogates and stay compatible with
-  Python 2.x and 3.0
+  Python 2.x and 3.x.
 
 - Issue #7585: difflib context and unified diffs now place a tab between
-  filename and date, conforming to the 'standards' they were originally
-  designed to follow.  This improves compatibility with patch tools.
+  filename and date, conforming to the 'standards' they were originally designed
+  to follow.  This improves compatibility with patch tools.
 
 - Issue #7472: Fixed typo in email.encoders module; messages using ISO-2022
-  character sets will now consistently use a Content-Transfer-Encoding of
-  7bit rather than sometimes being marked as 8bit.
+  character sets will now consistently use a Content-Transfer-Encoding of 7bit
+  rather than sometimes being marked as 8bit.
 
 - Issue #8375: test_distutils now checks if the temporary directory are still
   present before it cleans them.
 
-- Issue #8374: Update the internal alias table in the :mod:`locale` module
-  to cover recent locale changes and additions.
+- Issue #8374: Update the internal alias table in the :mod:`locale` module to
+  cover recent locale changes and additions.
 
 - Issue #8321: Give access to OpenSSL version numbers from the `ssl` module,
-  using the new attributes `ssl.OPENSSL_VERSION`, `ssl.OPENSSL_VERSION_INFO`
-  and `ssl.OPENSSL_VERSION_NUMBER`.
+  using the new attributes `ssl.OPENSSL_VERSION`, `ssl.OPENSSL_VERSION_INFO` and
+  `ssl.OPENSSL_VERSION_NUMBER`.
 
 - Add functools.total_ordering() and functools.cmp_to_key().
 
-- Issue #8257: The Decimal construct now accepts a float instance
-  directly, converting that float to a Decimal of equal value:
+- Issue #8257: The Decimal construct now accepts a float instance directly,
+  converting that float to a Decimal of equal value:
 
      >>> Decimal(1.1)
      Decimal('1.100000000000000088817841970012523233890533447265625')
 
-- Issue #8294: The Fraction constructor now accepts Decimal and float
-  instances directly.
+- Issue #8294: The Fraction constructor now accepts Decimal and float instances
+  directly.
 
-- Issue #7279: Comparisons involving a Decimal signaling NaN now
-  signal InvalidOperation instead of returning False.  (Comparisons
-  involving a quiet NaN are unchanged.)  Also, Decimal quiet NaNs
-  are now hashable;  Decimal signaling NaNs remain unhashable.
-
-- Issue #2531: Comparison operations between floats and Decimal
-  instances now return a result based on the numeric values of the
-  operands;  previously they returned an arbitrary result based on
-  the relative ordering of id(float) and id(Decimal).  See also
-  issue #8188, which adds Decimal-to-Fraction comparisons.
+- Issue #7279: Comparisons involving a Decimal signaling NaN now signal
+  InvalidOperation instead of returning False.  (Comparisons involving a quiet
+  NaN are unchanged.)  Also, Decimal quiet NaNs are now hashable; Decimal
+  signaling NaNs remain unhashable.
+
+- Issue #2531: Comparison operations between floats and Decimal instances now
+  return a result based on the numeric values of the operands; previously they
+  returned an arbitrary result based on the relative ordering of id(float) and
+  id(Decimal).  See also issue #8188, which adds Decimal-to-Fraction
+  comparisons.
 
 - Added a subtract() method to collections.Counter().
 
 - Issue #8233: When run as a script, py_compile.py optionally takes a single
-  argument `-` which tells it to read files to compile from stdin.  Each line
-  is read on demand and the named file is compiled immediately.  (Original
-  patch by Piotr Ożarowski).
+  argument `-` which tells it to read files to compile from stdin.  Each line is
+  read on demand and the named file is compiled immediately.  (Original patch by
+  Piotr Ożarowski).
 
 - Backwards incompatible change: Unicode codepoints line tabulation (0x0B) and
   form feed (0x0C) are now considered linebreaks, as specified in Unicode
-  Standard Annex #14.  See issue #7643.
-  http://www.unicode.org/reports/tr14/
+  Standard Annex #14.  See issue #7643.  http://www.unicode.org/reports/tr14/
 
-- Comparisons using one of <, <=, >, >= between a complex instance and
-  a Fractions instance now raise TypeError instead of returning
-  True/False.  This makes Fraction <=> complex comparisons consistent with
-  int <=> complex, float <=> complex, and complex <=> complex comparisons.
-
-- Issue #8139: ossaudiodev didn't initialize its types properly, therefore
-  some methods (such as oss_mixer_device.fileno()) were not available.
-  Initial patch by Bertrand Janin.
+- Comparisons using one of <, <=, >, >= between a complex instance and a
+  Fractions instance now raise TypeError instead of returning True/False.  This
+  makes Fraction <=> complex comparisons consistent with int <=> complex, float
+  <=> complex, and complex <=> complex comparisons.
+
+- Issue #8139: ossaudiodev didn't initialize its types properly, therefore some
+  methods (such as oss_mixer_device.fileno()) were not available.  Initial patch
+  by Bertrand Janin.
 
 - Issue #8205: Remove the "Modules" directory from sys.path when Python is
   running from the build directory (POSIX only).
 
 - Issue #7512: shutil.copystat() could raise an OSError when the filesystem
-  didn't support chflags() (for example ZFS under FreeBSD).  The error is
-  now silenced.
+  didn't support chflags() (for example ZFS under FreeBSD).  The error is now
+  silenced.
 
-- Issue #7860: platform.uname now reports the correct 'machine' type
-  when Python is running in WOW64 mode on 64 bit Windows.
+- Issue #7860: platform.uname now reports the correct 'machine' type when Python
+  is running in WOW64 mode on 64 bit Windows.
 
 - Issue #3890, #8222: Fix recv() and recv_into() on non-blocking SSL sockets.
   Also, enable the SSL_MODE_AUTO_RETRY flag on SSL sockets, so that blocking
@@ -888,31 +1143,31 @@
 - Issue #4961: Inconsistent/wrong result of askyesno function in tkMessageBox
   with Tcl/Tk-8.5.
 
-- Issue #8140: extend compileall to compile single files. Add -i option.
+- 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 #7356: ctypes.util: Make parsing of ldconfig output independent of the
+  locale.
 
-- The internals of the subprocess module on POSIX systems have been replaced
-  by an extension module (_posixsubprocess) so that the fork()+exec() can be
-  done safely without the possibility of deadlock in multithreaded applications.
-
-- subprocess.Popen now has restore_signals and start_new_session features.
-  The default of restore_signals=True is a new behavior compared to earlier
-  Python versions.  This means that signals such as SIGPIPE are not ignored
-  by default in subprocesses launched by Python (Issue #1652).
+- The internals of the subprocess module on POSIX systems have been replaced by
+  an extension module (_posixsubprocess) so that the fork()+exec() can be done
+  safely without the possibility of deadlock in multithreaded applications.
+
+- subprocess.Popen now has restore_signals and start_new_session features.  The
+  default of restore_signals=True is a new behavior compared to earlier Python
+  versions.  This means that signals such as SIGPIPE are not ignored by default
+  in subprocesses launched by Python (Issue #1652).
 
 - Issue #6472: The xml.etree package is updated to ElementTree 1.3.  The
   cElementTree module is updated too.
 
 - 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
+  an non existent program name and Python is unable to retrieve the real program
+  name.
 
 - Issue #7880: Fix sysconfig when the python executable is a symbolic link.
 
-- Issue #6509: fix re.sub to work properly when the pattern, the string, and
-  the replacement were all bytes. Patch by Antoine Pitrou.
+- Issue #6509: fix re.sub to work properly when the pattern, the string, and the
+  replacement were all bytes.  Patch by Antoine Pitrou.
 
 - The sqlite3 module was updated to pysqlite 2.6.0. This fixes several obscure
   bugs and allows loading SQLite extensions from shared libraries.
@@ -942,16 +1197,16 @@
 
 - Issue #1537721: Add a writeheader() method to csv.DictWriter.
 
-- Issue #7959: ctypes callback functions are now registered correctly
-  with the cycle garbage collector.
+- Issue #7959: ctypes callback functions are now registered correctly with the
+  cycle garbage collector.
 
 - Issue #5801: removed spurious empty lines in wsgiref.
 
-- Issue #6666: fix bug in trace.py that applied the list of directories
-  to be ignored only to the first file.  Noted by Bogdan Opanchuk.
+- Issue #6666: fix bug in trace.py that applied the list of directories to be
+  ignored only to the first file.  Noted by Bogdan Opanchuk.
 
-- Issue #7597: curses.use_env() can now be called before initscr().
-  Noted by Kan-Ru Chen.
+- Issue #7597: curses.use_env() can now be called before initscr().  Noted by
+  Kan-Ru Chen.
 
 - Issue #7310: fix the __repr__ of os.environ to show the environment variables.
 
@@ -961,48 +1216,46 @@
 - Issue #7361: Importlib was not properly checking the number of bytes in
   bytecode file when it was less then 8 bytes.
 
-- Issue #7633: In the decimal module, Context class methods (with the
-  exception of canonical and is_canonical) now accept instances of int
-  and long wherever a Decimal instance is accepted, and implicitly
-  convert that argument to Decimal.  Previously only some arguments
-  were converted.
+- Issue #7633: In the decimal module, Context class methods (with the exception
+  of canonical and is_canonical) now accept instances of int and long wherever a
+  Decimal instance is accepted, and implicitly convert that argument to Decimal.
+  Previously only some arguments were converted.
 
 - Issue #7835: shelve should no longer produce mysterious warnings during
   interpreter shutdown.
 
-- Issue #2746: Don't escape ampersands and angle brackets ("&", "<", ">")
-  in XML processing instructions and comments.  These raw characters are
-  allowed by the XML specification, and are necessary when outputting e.g.
-  PHP code in a processing instruction.  Patch by Neil Muller.
-
-- Issue #6233: ElementTree failed converting unicode characters to XML
-  entities when they could't be represented in the requested output
-  encoding.  Patch by Jerry Chen.
+- Issue #2746: Don't escape ampersands and angle brackets ("&", "<", ">") in XML
+  processing instructions and comments.  These raw characters are allowed by the
+  XML specification, and are necessary when outputting e.g.  PHP code in a
+  processing instruction.  Patch by Neil Muller.
+
+- Issue #6233: ElementTree failed converting unicode characters to XML entities
+  when they could't be represented in the requested output encoding.  Patch by
+  Jerry Chen.
 
-- Issue #6003: add an argument to ``zipfile.Zipfile.writestr`` to
-  specify the compression type.
+- Issue #6003: add an argument to ``zipfile.Zipfile.writestr`` to specify the
+  compression type.
 
 - Issue #4772: Raise a ValueError when an unknown Bluetooth protocol is
   specified, rather than fall through to AF_PACKET (in the `socket` module).
-  Also, raise ValueError rather than TypeError when an unknown TIPC address
-  type is specified.  Patch by Brian Curtin.
+  Also, raise ValueError rather than TypeError when an unknown TIPC address type
+  is specified.  Patch by Brian Curtin.
 
-- Issue #6939: Fix file I/O objects in the `io` module to keep the original
-  file position when calling `truncate()`.  It would previously change the
-  file position to the given argument, which goes against the tradition of
+- Issue #6939: Fix file I/O objects in the `io` module to keep the original file
+  position when calling `truncate()`.  It would previously change the file
+  position to the given argument, which goes against the tradition of
   ftruncate() and other truncation APIs.  Patch by Pascal Chambon.
 
 - Issue #7610: Reworked implementation of the internal
-  :class:`zipfile.ZipExtFile` class used to represent files stored inside
-  an archive.  The new implementation is significantly faster and can
-  be wrapped in a :class:`io.BufferedReader` object for more speedups.
-  It also solves an issue where interleaved calls to `read()` and
-  `readline()` give wrong results.  Patch by Nir Aides.
+  :class:`zipfile.ZipExtFile` class used to represent files stored inside an
+  archive.  The new implementation is significantly faster and can be wrapped in
+  a :class:`io.BufferedReader` object for more speedups.  It also solves an
+  issue where interleaved calls to `read()` and `readline()` give wrong results.
+  Patch by Nir Aides.
 
 - Issue #6963: Added "maxtasksperchild" argument to multiprocessing.Pool,
-  allowing for a maximum number of tasks within the pool to be completed by
-  the worker before that worker is terminated, and a new one created to
-  replace it.
+  allowing for a maximum number of tasks within the pool to be completed by the
+  worker before that worker is terminated, and a new one created to replace it.
 
 - Issue #7792: Registering non-classes to ABCs raised an obscure error.
 
@@ -1016,21 +1269,21 @@
 - Issue #7561: Fix crashes when using bytearray objects with the posix
   module.
 
-- Issue #1670765: Prevent email.generator.Generator from re-wrapping
-  headers in multipart/signed MIME parts, which fixes one of the sources of
-  invalid modifications to such parts by Generator.
+- Issue #1670765: Prevent email.generator.Generator from re-wrapping headers in
+  multipart/signed MIME parts, which fixes one of the sources of invalid
+  modifications to such parts by Generator.
 
-- Issue #7703: Add support for the new buffer API to `binascii.a2bhqx`.
-  Patch by Florent Xicluna, along with some additional tests.
+- Issue #7703: Add support for the new buffer API to `binascii.a2bhqx`.  Patch
+  by Florent Xicluna, along with some additional tests.
 
-- Issue #7701: Fix crash in binascii.b2a_uu() in debug mode when given a
-  1-byte argument.  Patch by Victor Stinner.
+- Issue #7701: Fix crash in binascii.b2a_uu() in debug mode when given a 1-byte
+  argument.  Patch by Victor Stinner.
 
-- Issue #3299: Fix possible crash in the _sre module when given bad
-  argument values in debug mode.  Patch by Victor Stinner.
+- Issue #3299: Fix possible crash in the _sre module when given bad argument
+  values in debug mode.  Patch by Victor Stinner.
 
-- Issue #2846: Add support for gzip.GzipFile reading zero-padded files.
-  Patch by Brian Curtin.
+- Issue #2846: Add support for gzip.GzipFile reading zero-padded files.  Patch
+  by Brian Curtin.
 
 - Issue #7681: Use floor division in appropiate places in the wave module.
 
@@ -1038,63 +1291,61 @@
   Extension extra options may change the output without changing the .c
   file). Initial patch by Collin Winter.
 
-- Issue #7617: Make sure distutils.unixccompiler.UnixCCompiler recognizes
-  gcc when it has a fully qualified configuration prefix. Initial patch
-  by Arfrever.
+- Issue #7617: Make sure distutils.unixccompiler.UnixCCompiler recognizes gcc
+  when it has a fully qualified configuration prefix. Initial patch by Arfrever.
 
-- Issue #7105: Make WeakKeyDictionary and WeakValueDictionary robust against
-  the destruction of weakref'ed objects while iterating.
+- Issue #7105: Make WeakKeyDictionary and WeakValueDictionary robust against the
+  destruction of weakref'ed objects while iterating.
 
-- Issue #7455: Fix possible crash in cPickle on invalid input.  Patch by
-  Victor Stinner.
+- Issue #7455: Fix possible crash in cPickle on invalid input.  Patch by Victor
+  Stinner.
 
 - Issue #1628205: Socket file objects returned by socket.socket.makefile() now
-  properly handles EINTR within the read, readline, write & flush methods.
-  The socket.sendall() method now properly handles interrupted system calls.
+  properly handles EINTR within the read, readline, write & flush methods.  The
+  socket.sendall() method now properly handles interrupted system calls.
 
-- Issue #7471: Improve the performance of GzipFile's buffering mechanism,
-  and make it implement the `io.BufferedIOBase` ABC to allow for further
-  speedups by wrapping it in an `io.BufferedReader`.  Patch by Nir Aides.
+- Issue #7471: Improve the performance of GzipFile's buffering mechanism, and
+  make it implement the `io.BufferedIOBase` ABC to allow for further speedups by
+  wrapping it in an `io.BufferedReader`.  Patch by Nir Aides.
 
 - Issue #3972: http.client.HTTPConnection now accepts an optional source_address
   parameter to allow specifying where your connections come from.
 
 - socket.create_connection now accepts an optional source_address parameter.
 
-- Issue #5511: now zipfile.ZipFile can be used as a context manager.
-  Initial patch by Brian Curtin.
+- Issue #5511: now zipfile.ZipFile can be used as a context manager.  Initial
+  patch by Brian Curtin.
 
-- Issue #7556: Make sure Distutils' msvc9compile reads and writes the
-  MSVC XML Manifest file in text mode so string patterns can be used
-  in regular expressions.
-
-- Issue #7552: Removed line feed in the base64 Authorization header in
-  the Distutils upload command to avoid an error when PyPI reads it.
-  This occurs on long passwords. Initial patch by JP St. Pierre.
+- Issue #7556: Make sure Distutils' msvc9compile reads and writes the MSVC XML
+  Manifest file in text mode so string patterns can be used in regular
+  expressions.
+
+- Issue #7552: Removed line feed in the base64 Authorization header in the
+  Distutils upload command to avoid an error when PyPI reads it.  This occurs on
+  long passwords. Initial patch by JP St. Pierre.
 
 - Issue #7231: urllib2 cannot handle https with proxy requiring auth.  Patch by
   Tatsuhiro Tsujikawa.
 
-- Issue #4757: `zlib.compress` and other methods in the zlib module now
-  raise a TypeError when given an `str` object (rather than a `bytes`-like
-  object).  Patch by Victor Stinner and Florent Xicluna.
+- Issue #4757: `zlib.compress` and other methods in the zlib module now raise a
+  TypeError when given an `str` object (rather than a `bytes`-like object).
+  Patch by Victor Stinner and Florent Xicluna.
 
 - Issue #7349: Make methods of file objects in the io module accept None as an
   argument where file-like objects (ie StringIO and BytesIO) accept them to mean
   the same as passing no argument.
 
-- Issue #7357: tarfile no longer suppresses fatal extraction errors by
-  default.
+- Issue #7357: tarfile no longer suppresses fatal extraction errors by default.
 
-- Issue #5949: added check for correct lineends in input from IMAP server
-  in imaplib.
+- Issue #5949: added check for correct lineends in input from IMAP server in
+  imaplib.
 
 - Add count() and reverse() methods to collections.deque().
 
 - Fix variations of extending deques:  d.extend(d)  d.extendleft(d)  d+=d
 
-- Issue #6986: Fix crash in the JSON C accelerator when called with the
-  wrong parameter types.  Patch by Victor Stinner.
+- Issue #6986: Fix crash in the JSON C accelerator when called with the wrong
+  parameter types.  Patch by Victor Stinner.
 
 - Issue #7457: added a read_pkg_file method to
   distutils.dist.DistributionMetadata.
@@ -1102,26 +1353,26 @@
 - logging: Added optional `secure` parameter to SMTPHandler, to enable use of
   TLS with authentication credentials.
 
-- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is
-  generated in Distutils. Patch by Stephen Emslie.
+- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is generated
+  in Distutils.  Patch by Stephen Emslie.
 
 - Issue #4120: Drop reference to CRT from manifest when building extensions with
   msvc9compiler.
 
 - Issue #7333: The `posix` module gains an `initgroups()` function providing
-  access to the initgroups(3) C library call on Unix systems which implement
-  it.  Patch by Jean-Paul Calderone.
+  access to the initgroups(3) C library call on Unix systems which implement it.
+  Patch by Jean-Paul Calderone.
 
 - Issue #7408: Fixed distutils.tests.sdist so it doesn't check for group
   ownership when the group is not forced, because the group may be different
   from the user's group and inherit from its container when the test is run.
 
 - Issue #4486: When an exception has an explicit cause, do not print its
-  implicit context too.  This affects the `traceback` module as well as
-  built-in exception printing.
+  implicit context too.  This affects the `traceback` module as well as built-in
+  exception printing.
 
-- Issue #1515: Enable use of deepcopy() with instance methods.  Patch by
-  Robert Collins.
+- Issue #1515: Enable use of deepcopy() with instance methods.  Patch by Robert
+  Collins.
 
 - Issue #7403: logging: Fixed possible race condition in lock creation.
 
@@ -1129,66 +1380,64 @@
   `storbinary()` method of FTP and FTP_TLS objects gains an optional `rest`
   argument.  Patch by Pablo Mouzo.
 
-- Issue #5788: `datetime.timedelta` objects get a new `total_seconds()`
-  method returning the total number of seconds in the duration.  Patch by
-  Brian Quinlan.
+- Issue #5788: `datetime.timedelta` objects get a new `total_seconds()` method
+  returning the total number of seconds in the duration.  Patch by Brian
+  Quinlan.
 
 - Issue #7133: SSL objects now support the new buffer API.
 
-- Issue #1488943: difflib.Differ() doesn't always add hints for tab characters
+- Issue #1488943: difflib.Differ() doesn't always add hints for tab characters.
 
 - Issue #6123: tarfile now opens empty archives correctly and consistently
   raises ReadError on empty files.
 
-- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can
-  be 2.
+- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can be 2.
 
 - Issue #5037: Proxy the __bytes__ special method instead to __bytes__ instead
   of __str__.
 
-- Issue #7341: Close the internal file object in the TarFile constructor in
-  case of an error.
+- Issue #7341: Close the internal file object in the TarFile constructor in case
+  of an error.
 
 - Issue #7293: distutils.test_msvc9compiler is fixed to work on any fresh
   Windows box. Help provided by David Bolen.
 
-- Issue #2054: ftplib now provides an FTP_TLS class to do secure FTP using
-  TLS or SSL.  Patch by Giampaolo Rodola'.
+- Issue #2054: ftplib now provides an FTP_TLS class to do secure FTP using TLS
+  or SSL.  Patch by Giampaolo Rodola'.
 
-- Issue #7328: pydoc no longer corrupts sys.path when run with the '-m' switch
+- Issue #7328: pydoc no longer corrupts sys.path when run with the '-m' switch.
 
-- Issue #4969: The mimetypes module now reads the MIME database from
-  the registry under Windows.  Patch by Gabriel Genellina.
+- Issue #4969: The mimetypes module now reads the MIME database from the
+  registry under Windows.  Patch by Gabriel Genellina.
 
-- Issue #6816: runpy now provides a run_path function that allows Python code
-  to execute file paths that refer to source or compiled Python files as well
-  as zipfiles, directories and other valid sys.path entries that contain a
-  __main__.py file. This allows applications that run other Python scripts to
+- Issue #6816: runpy now provides a run_path function that allows Python code to
+  execute file paths that refer to source or compiled Python files as well as
+  zipfiles, directories and other valid sys.path entries that contain a
+  __main__.py file.  This allows applications that run other Python scripts to
   support the same flexibility as the CPython command line itself.
 
-- Issue #7318: multiprocessing now uses a timeout when it fails to establish
-  a connection with another process, rather than looping endlessly. The
-  default timeout is 20 seconds, which should be amply sufficient for
-  local connections.
+- Issue #7318: multiprocessing now uses a timeout when it fails to establish a
+  connection with another process, rather than looping endlessly.  The default
+  timeout is 20 seconds, which should be amply sufficient for local connections.
 
 - Issue #7197: Allow unittest.TextTestRunner objects to be pickled and
-  unpickled. This fixes crashes under Windows when trying to run
+  unpickled.  This fixes crashes under Windows when trying to run
   test_multiprocessing in verbose mode.
 
 - Issue #7893: ``unittest.TextTestResult`` is made public and a ``resultclass``
   argument added to the TextTestRunner constructor allowing a different result
   class to be used without having to subclass.
 
-- Issue 7588: ``unittest.TextTestResult.getDescription`` now includes the test
+- Issue #7588: ``unittest.TextTestResult.getDescription`` now includes the test
   name in failure reports even if the test has a docstring.
 
 - Issue #3001: Add a C implementation of recursive locks which is used by
-  default when instantiating a `threading.RLock` object. This makes
-  recursive locks as fast as regular non-recursive locks (previously,
-  they were slower by 10x to 15x).
+  default when instantiating a `threading.RLock` object. This makes recursive
+  locks as fast as regular non-recursive locks (previously, they were slower by
+  10x to 15x).
 
-- Issue #7282: Fix a memory leak when an RLock was used in a thread other
-  than those started through `threading.Thread` (for example, using
+- Issue #7282: Fix a memory leak when an RLock was used in a thread other than
+  those started through `threading.Thread` (for example, using
   `_thread.start_new_thread()`).
 
 - Issue #7187: Importlib would not silence the IOError raised when trying to
@@ -1200,20 +1449,19 @@
 - Issue #7211: Allow 64-bit values for the `ident` and `data` fields of kevent
   objects on 64-bit systems.  Patch by Michael Broghton.
 
-- Issue #6896: mailbox.Maildir now invalidates its internal cache each time
-  a modification is done through it.  This fixes inconsistencies and test
-  failures on systems with slightly bogus mtime behaviour.
-
-- Issue #7246 & Issue #7208: getpass now properly flushes input before
-  reading from stdin so that existing input does not confuse it and
-  lead to incorrect entry or an IOError.  It also properly flushes it
-  afterwards to avoid the terminal echoing the input afterwards on
-  OSes such as Solaris.
-
-- Issue #7233: Fix a number of two-argument Decimal methods to make
-  sure that they accept an int or long as the second argument.  Also
-  fix buggy handling of large arguments (those with coefficient longer
-  than the current precision) in shift and rotate.
+- Issue #6896: mailbox.Maildir now invalidates its internal cache each time a
+  modification is done through it.  This fixes inconsistencies and test failures
+  on systems with slightly bogus mtime behaviour.
+
+- Issue #7246 & Issue #7208: getpass now properly flushes input before reading
+  from stdin so that existing input does not confuse it and lead to incorrect
+  entry or an IOError.  It also properly flushes it afterwards to avoid the
+  terminal echoing the input afterwards on OSes such as Solaris.
+
+- Issue #7233: Fix a number of two-argument Decimal methods to make sure that
+  they accept an int or long as the second argument.  Also fix buggy handling of
+  large arguments (those with coefficient longer than the current precision) in
+  shift and rotate.
 
 - Issue #4750: Store the basename of the original filename in the gzip FNAME
   header as required by RFC 1952.
@@ -1235,31 +1483,31 @@
 - Issue #7080: locale.strxfrm() raises a MemoryError on 64-bit non-Windows
   platforms, and assorted locale fixes by Derk Drukker.
 
-- Issue #5833: Fix extra space character in readline completion with the
-  GNU readline library version 6.0.
+- Issue #5833: Fix extra space character in readline completion with the GNU
+  readline library version 6.0.
 
-- Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" environment
+- Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" environment.
 
 - Issue #7086: Added TCP support to SysLogHandler, and tidied up some
   anachronisms in the code which were a relic of 1.5.2 compatibility.
 
-- Issue #7082: When falling back to the MIME 'name' parameter, the
-  correct place to look for it is the Content-Type header.
+- Issue #7082: When falling back to the MIME 'name' parameter, the correct place
+  to look for it is the Content-Type header.
 
 - Make tokenize.detect_coding() normalize utf-8 and iso-8859-1 variants like the
   builtin tokenizer.
 
-- Issue #7048: Force Decimal.logb to round its result when that result
-  is too large to fit in the current precision.
+- Issue #7048: Force Decimal.logb to round its result when that result is too
+  large to fit in the current precision.
 
-- Issue #6236, #6348: Fix various failures in the I/O library under AIX
-  and other platforms, when using a non-gcc compiler. Patch by Derk Drukker.
+- Issue #6236, #6348: Fix various failures in the I/O library under AIX and
+  other platforms, when using a non-gcc compiler. Patch by Derk Drukker.
 
-- Issue #4606: Passing 'None' if ctypes argtype is set to POINTER(...)
-  does now always result in NULL.
+- Issue #4606: Passing 'None' if ctypes argtype is set to POINTER(...)  does now
+  always result in NULL.
 
-- Issue #5042: Structure sub-subclass does now initialize correctly
-  with base class positional arguments.
+- Issue #5042: Structure sub-subclass does now initialize correctly with base
+  class positional arguments.
 
 - Issue #6882: Import uuid creates zombies processes.
 
@@ -1269,22 +1517,21 @@
 
 - Issue #6888: pdb's alias command was broken when no arguments were given.
 
-- Issue #6857: Default format() alignment should be '>' for Decimal
-  instances.
+- Issue #6857: Default format() alignment should be '>' for Decimal instances.
 
-- Issue #6795: int(Decimal('nan')) now raises ValueError instead of
-  returning NaN or raising InvalidContext.  Also, fix infinite recursion
-  in long(Decimal('nan')).
+- Issue #6795: int(Decimal('nan')) now raises ValueError instead of returning
+  NaN or raising InvalidContext.  Also, fix infinite recursion in
+  long(Decimal('nan')).
 
-- Issue #6850: Fix bug in Decimal._parse_format_specifier for formats
-  with no type specifier.
+- Issue #6850: Fix bug in Decimal._parse_format_specifier for formats with no
+  type specifier.
 
 - Issue #6239: ctypes.c_char_p return value must return bytes.
 
-- Issue #6838: Use a list to accumulate the value instead of
-  repeatedly concatenating strings in http.client's
-  HTTPResponse._read_chunked providing a significant speed increase
-  when downloading large files servend with a Transfer-Encoding of 'chunked'.
+- Issue #6838: Use a list to accumulate the value instead of repeatedly
+  concatenating strings in http.client's HTTPResponse._read_chunked providing a
+  significant speed increase when downloading large files servend with a
+  Transfer-Encoding of 'chunked'.
 
 - Trying to import a submodule from a module that is not a package, ImportError
   should be raised, not AttributeError.
@@ -1293,8 +1540,7 @@
   fall back to computing what __package__ should be instead of giving up.
 
 - Raise a TypeError when the name of a module to be imported for
-  importlib.__import__ is not a string (was raising an
-  AttributeError before).
+  importlib.__import__ is not a string (was raising an AttributeError before).
 
 - Allow the fromlist passed into importlib.__import__ to be any iterable.
 
@@ -1316,50 +1562,50 @@
 
 - Issue #6665: Fix fnmatch to properly match filenames with newlines in them.
 
-- Issue #1135: Add the XView and YView mix-ins to avoid duplicating
-  the xview* and yview* methods.
+- Issue #1135: Add the XView and YView mix-ins to avoid duplicating the xview*
+  and yview* methods.
 
 - Issue #6629: Fix a data corruption issue in the new I/O library, which could
   occur when writing to a BufferedRandom object (e.g. a file opened in "rb+" or
   "wb+" mode) after having buffered a certain amount of data for reading. This
   bug was not present in the pure Python implementation.
 
-- Issue #6622: Fix "local variable 'secret' referenced before
-  assignment" bug in POP3.apop.
+- Issue #6622: Fix "local variable 'secret' referenced before assignment" bug in
+  POP3.apop.
 
 - Issue #2715: Remove remnants of Carbon.File from binhex module.
 
-- Issue #6595: The Decimal constructor now allows arbitrary Unicode
-  decimal digits in input, as recommended by the standard.  Previously
-  it was restricted to accepting [0-9].
+- Issue #6595: The Decimal constructor now allows arbitrary Unicode decimal
+  digits in input, as recommended by the standard.  Previously it was restricted
+  to accepting [0-9].
 
 - Issue #6106: telnetlib.Telnet.process_rawq doesn't handle default WILL/WONT
   DO/DONT correctly.
 
 - Issue #1424152: Fix for http.client, urllib.request to support SSL while
-  working through proxy. Original patch by Christopher Li, changes made by
-  Senthil Kumaran
+  working through proxy.  Original patch by Christopher Li, changes made by
+  Senthil Kumaran.
 
 - Add importlib.abc.ExecutionLoader to represent the PEP 302 protocol for
-  loaders that allow for modules to be executed. Both importlib.abc.PyLoader
-  and PyPycLoader inherit from this class and provide implementations in
-  relation to other methods required by the ABCs.
+  loaders that allow for modules to be executed. Both importlib.abc.PyLoader and
+  PyPycLoader inherit from this class and provide implementations in relation to
+  other methods required by the ABCs.
 
 - importlib.abc.PyLoader did not inherit from importlib.abc.ResourceLoader like
   the documentation said it did even though the code in PyLoader relied on the
   abstract method required by ResourceLoader.
 
-- Issue #6431: Make Fraction type return NotImplemented when it doesn't
-  know how to handle a comparison without loss of precision.  Also add
-  correct handling of infinities and nans for comparisons with float.
+- Issue #6431: Make Fraction type return NotImplemented when it doesn't know how
+  to handle a comparison without loss of precision.  Also add correct handling
+  of infinities and nans for comparisons with float.
 
 - Issue #6415: Fixed warnings.warn segfault on bad formatted string.
 
-- Issue #6358: The exit status of a command started with os.popen() was
-  reported differently than it did with python 2.x.
+- Issue #6358: The exit status of a command started with os.popen() was reported
+  differently than it did with python 2.x.
 
-- Issue #6323: The pdb debugger did not exit when running a script with a
-  syntax error.
+- Issue #6323: The pdb debugger did not exit when running a script with a syntax
+  error.
 
 - Issue #3392: The subprocess communicate() method no longer fails in select()
   when file descriptors are large; communicate() now uses poll() when possible.
@@ -1375,80 +1621,106 @@
 
 - Issue #6218: io.StringIO and io.BytesIO instances are now picklable.
 
-- The os.get_exec_path() function to return the list of directories that will
-  be searched for an executable when launching a subprocess was added.
+- The os.get_exec_path() function to return the list of directories that will be
+  searched for an executable when launching a subprocess was added.
 
 - Issue #7481: When a threading.Thread failed to start it would leave the
   instance stuck in initial state and present in threading.enumerate().
 
-- Issue #1068268: The subprocess module now handles EINTR in internal
-  os.waitpid and os.read system calls where appropriate.
+- Issue #1068268: The subprocess module now handles EINTR in internal os.waitpid
+  and os.read system calls where appropriate.
 
 - Issue #6729: Added ctypes.c_ssize_t to represent ssize_t.
 
 - Issue #6247: The argparse module has been added to the standard library.
 
-- Issue #8235: _socket: Add the constant ``SO_SETFIB``.  SO_SETFIB is
-  a socket option available on FreeBSD 7.1 and newer.
+- Issue #8235: _socket: Add the constant ``SO_SETFIB``.  SO_SETFIB is a socket
+  option available on FreeBSD 7.1 and newer.
 
 Extension Modules
 -----------------
 
+- Issue #9422: Fix memory leak when re-initializing a struct.Struct object.
+
+- 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 returns the same
+  information as the id command. os.getgroups() can now return more than 16
+  groups on MacOSX.
+
+- Issue #6095: Make directory argument to os.listdir optional.
+
+- Issue #9277: Fix bug in struct.pack for bools in standard mode (e.g.,
+  struct.pack('>?')): if conversion to bool raised an exception then that
+  exception wasn't properly propagated on machines where char is unsigned.
+
+- Issue #5180: Fixed a bug that prevented loading 2.x pickles in 3.x python when
+  they contain instances of old-style classes.
+
+- Issue #9165: Add new functions math.isfinite and cmath.isfinite, to accompany
+  existing isinf and isnan functions.
+
+- Issue #1578269: Implement os.symlink for Windows 6.0+.  Patch by Jason
+  R. Coombs.
+
+- In struct.pack, correctly propogate exceptions from computing the truth of an
+  object in the '?' format.
+
+- Issue #9000: datetime.timezone objects now have eval-friendly repr.
+
 - In the math module, correctly lookup __trunc__, __ceil__, and __floor__ as
   special methods.
 
-- Issue #9005: Prevent utctimetuple() from producing year 0 or year
-  10,000.  Prior to this change, timezone adjustment in utctimetuple()
-  could produce tm_year value of 0 or 10,000.  Now an OverflowError is
-  raised in these edge cases.
-
-- Issue #6641: The ``datetime.strptime`` method now supports the
-  ``%z`` directive.  When the ``%z`` directive is present in the
-  format string, an aware ``datetime`` object is returned with
-  ``tzinfo`` bound to a ``datetime.timezone`` instance constructed
-  from the parsed offset.  If both ``%z`` and ``%Z`` are present, the
-  data in ``%Z`` field is used for timezone name, but ``%Z`` data
-  without ``%z`` is discarded.
+- Issue #9005: Prevent utctimetuple() from producing year 0 or year 10,000.
+  Prior to this change, timezone adjustment in utctimetuple() could produce
+  tm_year value of 0 or 10,000.  Now an OverflowError is raised in these edge
+  cases.
+
+- Issue #6641: The ``datetime.strptime`` method now supports the ``%z``
+  directive.  When the ``%z`` directive is present in the format string, an
+  aware ``datetime`` object is returned with ``tzinfo`` bound to a
+  ``datetime.timezone`` instance constructed from the parsed offset.  If both
+  ``%z`` and ``%Z`` are present, the data in ``%Z`` field is used for timezone
+  name, but ``%Z`` data without ``%z`` is discarded.
 
 - Issue #5094: The ``datetime`` module now has a simple concrete class
-  implementing ``datetime.tzinfo`` interface.  Instances of the new
-  class, ``datetime.timezone``, return fixed name and UTC offset from
-  their ``tzname(dt)`` and ``utcoffset(dt)`` methods.  The ``dst(dt)``
-  method always returns ``None``.  A class attribute, ``utc`` contains
-  an instance representing the UTC timezone.  Original patch by Rafe
-  Kaplan.
+  implementing ``datetime.tzinfo`` interface.  Instances of the new class,
+  ``datetime.timezone``, return fixed name and UTC offset from their
+  ``tzname(dt)`` and ``utcoffset(dt)`` methods.  The ``dst(dt)`` method always
+  returns ``None``.  A class attribute, ``utc`` contains an instance
+  representing the UTC timezone.  Original patch by Rafe Kaplan.
 
-- Issue #8973: Add __all__ to struct module; this ensures that
-  help(struct) includes documentation for the struct.Struct class.
+- Issue #8973: Add __all__ to struct module; this ensures that help(struct)
+  includes documentation for the struct.Struct class.
 
 - Issue #3129: Trailing digits in struct format string are no longer ignored.
   For example, "1" or "ilib123" are now invalid formats and cause
   ``struct.error`` to be raised.  Patch by Caleb Deveraux.
 
-- Issue #7384: If the system readline library is linked against ncurses,
-  the curses module must be linked against ncurses as well. Otherwise it
-  is not safe to load both the readline and curses modules in an application.
-
-- Issue #2810: Fix cases where the Windows registry API returns
-  ERROR_MORE_DATA, requiring a re-try in order to get the complete result.
-
-- Issue #8692: Optimize math.factorial: replace the previous naive
-  algorithm with an improved 'binary-split' algorithm that uses fewer
-  multiplications and allows many of the multiplications to be
-  performed using plain C integer arithmetic instead of PyLong
-  arithmetic.  Also uses a lookup table for small arguments.
+- Issue #7384: If the system readline library is linked against ncurses, the
+  curses module must be linked against ncurses as well. Otherwise it is not safe
+  to load both the readline and curses modules in an application.
+
+- Issue #2810: Fix cases where the Windows registry API returns ERROR_MORE_DATA,
+  requiring a re-try in order to get the complete result.
+
+- Issue #8692: Optimize math.factorial: replace the previous naive algorithm
+  with an improved 'binary-split' algorithm that uses fewer multiplications and
+  allows many of the multiplications to be performed using plain C integer
+  arithmetic instead of PyLong arithmetic.  Also uses a lookup table for small
+  arguments.
 
 - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing
   overflow checks in the audioop module.
 
 - Issue #8644: The accuracy of td.total_seconds() has been improved (by
   calculating with integer arithmetic instead of float arithmetic internally):
-  the result is now always correctly rounded, and is equivalent to td /
-  timedelta(seconds=1).
+  the result is now always correctly rounded, and is equivalent to ``td /
+  timedelta(seconds=1)``.
 
-- Issue #2706: Allow division of a timedelta by another timedelta:
-  timedelta / timedelta, timedelta % timedelta, timedelta // timedelta
-  and divmod(timedelta, timedelta) are all supported.
+- Issue #2706: Allow division of a timedelta by another timedelta: timedelta /
+  timedelta, timedelta % timedelta, timedelta // timedelta and divmod(timedelta,
+  timedelta) are all supported.
 
 - Issue #8314: Fix unsigned long long bug in libffi on Sparc v8.
 
@@ -1461,7 +1733,7 @@
 
 - Issue #6949: Allow the _dbm extension to be built with db 4.8.x.
 
-- Issue #6544: fix a reference leak in the kqueue implementation's error
+- Issue #6544: Fix a reference leak in the kqueue implementation's error
   handling.
 
 - Stop providing crtassem.h symbols when compiling with Visual Studio 2010, as
@@ -1473,72 +1745,82 @@
 
 - Issue #3366: Add erf, erfc, expm1, gamma, lgamma functions to math module.
 
-- Issue #6877: It is now possible to link the readline extension to the
-  libedit readline emulation on OSX 10.5 or later.
+- Issue #6877: It is now possible to link the readline extension to the libedit
+  readline emulation on OSX 10.5 or later.
 
 - Issue #6848: Fix curses module build failure on OS X 10.6.
 
 - Fix a segfault that could be triggered by expat with specially formed input.
 
-- Issue #6561: '\d' in a regex now matches only characters with
-  Unicode category 'Nd' (Number, Decimal Digit).  Previously it also
-  matched characters with category 'No'.
-
-- Issue #4509: Array objects are no longer modified after an operation
-  failing due to the resize restriction in-place when the object has exported
-  buffers.
+- Issue #6561: '\d' in a regex now matches only characters with Unicode category
+  'Nd' (Number, Decimal Digit).  Previously it also matched characters with
+  category 'No'.
+
+- Issue #4509: Array objects are no longer modified after an operation failing
+  due to the resize restriction in-place when the object has exported buffers.
 
 - Issue #2389: Array objects are now pickled in a portable manner.
 
 - Expat: Fix DoS via XML document with malformed UTF-8 sequences
   (CVE_2009_3560).
 
-- Issue #7242: On Solaris 9 and earlier calling os.fork() from within a
-  thread could raise an incorrect RuntimeError about not holding the import
-  lock.  The import lock is now reinitialized after fork.
+- Issue #7242: On Solaris 9 and earlier calling os.fork() from within a thread
+  could raise an incorrect RuntimeError about not holding the import lock.  The
+  import lock is now reinitialized after fork.
 
 - Issue #7999: os.setreuid() and os.setregid() would refuse to accept a -1
   parameter on some platforms such as OS X.
 
 - Build the ossaudio extension on GNU/kFreeBSD.
 
-- Issue #7347: winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a
-  bug in the return value of QueryReflectionKey.
+- Issue #7347: winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a bug in
+  the return value of QueryReflectionKey.
+
+- Issue #7567: PyCurses_setupterm: Don't call `setupterm' twice.
 
 Build
 -----
 
+- Use OpenSSL 1.0.0a on Windows.
+
+- Issue #9280: Make sharedinstall depend on sharedmods.
+
+- Issue #9189: Make a user-specified CFLAGS, CPPFLAGS, or LDFLAGS setting
+  override the configure and makefile defaults, without deleting options the
+  user didn't intend to override.  Developers should no longer need to specify
+  OPT or EXTRA_CFLAGS, although those variables are still present for
+  backward-compatibility.
+
 - Issue #8854: Fix finding Visual Studio 2008 on Windows x64.
 
 - Issue #1759169, #8864: Drop _XOPEN_SOURCE on Solaris, define it for
   multiprocessing only.
 
-- Issue #8625: Turn off optimization in --with-pydebug builds with
-  gcc.  (Optimization was unintentionally turned on in gcc
-  --with-pydebug builds as a result of the issue #1628484 fix,
-  combined with autoconf's strange choice of default CFLAGS produced
-  by AC_PROG_CC for gcc.)
+- Issue #8625: Turn off optimization in --with-pydebug builds with gcc.
+  (Optimization was unintentionally turned on in gcc --with-pydebug builds as a
+  result of the issue #1628484 fix, combined with autoconf's strange choice of
+  default CFLAGS produced by AC_PROG_CC for gcc.)
 
-- Issue #3646: It is now easily possible to install a Python framework into
-  your home directory on MacOSX, see Mac/README for more information.
+- Issue #3646: It is now easily possible to install a Python framework into your
+  home directory on MacOSX, see Mac/README for more information.
 
 - Issue #3928: os.mknod() now available in Solaris, also.
 
 - Issue #3326: Build Python without -fno-strict-aliasing when the gcc does not
   give false warnings.
 
-- Issue #1628484: The Makefile doesn't ignore the CFLAGS environment
-  variable anymore.  It also forwards the LDFLAGS settings to the linker
-  when building a shared library.
+- Issue #1628484: The Makefile doesn't ignore the CFLAGS environment variable
+  anymore.  It also forwards the LDFLAGS settings to the linker when building a
+  shared library.
 
-- Issue #6716: Quote -x arguments of compileall in MSI installer.
-  Exclude 2to3 tests from compileall.
+- Issue #6716: Quote -x arguments of compileall in MSI installer.  Exclude 2to3
+  tests from compileall.
 
 - Issue #3920, #7903: Define _BSD_SOURCE on OpenBSD 4.4 through 4.9.
 
-- Issue #7632: When Py_USING_MEMORY_DEBUGGER is defined, disable the
-  private memory allocation scheme in dtoa.c and use PyMem_Malloc and
-  PyMem_Free instead.  Also disable caching of powers of 5.
+- Issue #7632: When Py_USING_MEMORY_DEBUGGER is defined, disable the private
+  memory allocation scheme in dtoa.c and use PyMem_Malloc and PyMem_Free
+  instead.  Also disable caching of powers of 5.
 
 - Issue #6491: Allow --with-dbmliborder to specify that no dbms will be built.
 
@@ -1557,21 +1839,21 @@
 - Issue #5792: Extend the short float repr support to x86 systems using
   icc or suncc.
 
-- Issue #6603: Change READ_TIMESTAMP macro in ceval.c so that it
-  compiles correctly under gcc on x86-64.  This fixes a reported
-  problem with the --with-tsc build on x86-64.
+- Issue #6603: Change READ_TIMESTAMP macro in ceval.c so that it compiles
+  correctly under gcc on x86-64.  This fixes a reported problem with the
+  --with-tsc build on x86-64.
 
-- Issue #6802: Fix build issues on MacOSX 10.6
+- Issue #6802: Fix build issues on MacOSX 10.6.
 
 - Issue #6244: Allow detect_tkinter to look for Tcl/Tk 8.6.
 
-- Issue 4601: 'make install' did not set the appropriate permissions on
+- Issue #4601: 'make install' did not set the appropriate permissions on
   directories.
 
-- Issue 5390: Add uninstall icon independent of whether file
-  extensions are installed.
+- Issue #5390: Add uninstall icon independent of whether file extensions are
+  installed.
 
-- Issue #7541: when using ``python-config`` with a framework install the
+- Issue #7541: When using ``python-config`` with a framework install the
   compiler might use the wrong library.
 
 - python-config now supports multiple options on the same command line.
@@ -1580,21 +1862,26 @@
 
 - Issue #8510: Update to autoconf2.65.
 
-
 Documentation
 ------------
 
-- A small wsgi server was added as Tools/scripts/serve.py, and is used to
+- Issue #9524: Document that two CTRL* signals are meant for use only
+  with os.kill.
+
+- Issue #9255: Document that the 'test' package is meant for internal Python use
+  only.
+
+- A small WSGI server was added as Tools/scripts/serve.py, and is used to
   implement a local documentation server via 'make serve' in the doc directory.
 
-- Updating `Using Python` documentation to include description of CPython's
-  -J and -X options.
+- Updating `Using Python` documentation to include description of CPython's -J
+  and -X options.
 
 - Document that importing a module that has None in sys.modules triggers an
   ImportError.
 
-- Issue #6556: Fixed the Distutils configuration files location explanation
-  for Windows.
+- Issue #6556: Fixed the Distutils configuration files location explanation for
+  Windows.
 
 - Update python manual page (options -B, -O0, -s, environment variables
   PYTHONDONTWRITEBYTECODE, PYTHONNOUSERSITE).
@@ -1605,14 +1892,19 @@
 Tests
 -----
 
-- Issue #7449: Skip test_socketserver if threading support is disabled
+- Issue #9251: test_threaded_import didn't fail when run through regrtest if the
+  import lock was disabled.
+
+- Issue #8605: Skip test_gdb if Python is compiled with optimizations.
+
+- Issue #7449: Skip test_socketserver if threading support is disabled.
 
-- Issue #8672: Add a zlib test ensuring that an incomplete stream can be
-  handled by a decompressor object without errors (it returns incomplete
-  uncompressed data).
+- Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled
+  by a decompressor object without errors (it returns incomplete uncompressed
+  data).
 
 - Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid
-  UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding)
+  UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding).
 
 - Issue #8576: Remove use of find_unused_port() in test_smtplib and
   test_multiprocessing.  Patch by Paul Moore.
@@ -1620,14 +1912,14 @@
 - Issue #7449: Fix many tests to support Python compiled without thread
   support. Patches written by Jerry Seutter.
 
-- Issue #8108: test_ftplib's non-blocking SSL server now has proper handling
-  of SSL shutdowns.
+- Issue #8108: test_ftplib's non-blocking SSL server now has proper handling of
+  SSL shutdowns.
 
-- Issues #8279, #8330, #8437, #8480, #8495: Fix test_gdb failures, patch
-  written by Dave Malcolm
+- Issues #8279, #8330, #8437, #8480, #8495: Fix test_gdb failures, patch written
+  by Dave Malcolm.
 
-- Issue #3864: Skip three test_signal tests on freebsd6 because they fail
-  if any thread was previously started, most likely due to a platform bug.
+- Issue #3864: Skip three test_signal tests on freebsd6 because they fail if any
+  thread was previously started, most likely due to a platform bug.
 
 - Issue #8193: Fix test_zlib failure with zlib 1.2.4.
 
@@ -1639,37 +1931,37 @@
 - Issue #8180 and #8207: Fix test_pep277 on OS X and add more tests for special
   Unicode normalization cases.
 
-- Issue #7783: test.support.open_urlresource invalidates the outdated files
-  from the local cache.
+- Issue #7783: test.support.open_urlresource invalidates the outdated files from
+  the local cache.
 
 - Issue #7849: Now the utility ``check_warnings`` verifies if the warnings are
   effectively raised.
 
-- The four path modules (genericpath, macpath, ntpath, posixpath) share a
-  common TestCase for some tests: test_genericpath.CommonTest.
+- The four path modules (genericpath, macpath, ntpath, posixpath) share a common
+  TestCase for some tests: test_genericpath.CommonTest.
 
-- Print platform information when running the whole test suite, or using
-  the --verbose flag.
+- Print platform information when running the whole test suite, or using the
+  --verbose flag.
 
 - Issue #767675: enable test_pep277 on POSIX platforms with Unicode-friendly
   filesystem encoding.
 
-- Issue #6292: for the moment at least, the test suite runs cleanly if python
-  is run with the -OO flag.  Tests requiring docstrings are skipped.
+- Issue #6292: for the moment at least, the test suite runs cleanly if python is
+  run with the -OO flag.  Tests requiring docstrings are skipped.
 
-- Issue #7712: test.support gained a new `temp_cwd` context manager which is
-  now also used by regrtest to run all the tests in a temporary directory.
-  The original CWD is saved in `support.SAVEDCWD`.
-  Thanks to Florent Xicluna who helped with the patch.
-
-- Issue #7924: Fix an intermittent 'XXX undetected error' failure in
-  test_capi (only seen so far on platforms where the curses module
-  wasn't built), due to an uncleared exception.
+- Issue #7712: test.support gained a new `temp_cwd` context manager which is now
+  also used by regrtest to run all the tests in a temporary directory.  The
+  original CWD is saved in `support.SAVEDCWD`.  Thanks to Florent Xicluna who
+  helped with the patch.
+
+- Issue #7924: Fix an intermittent 'XXX undetected error' failure in test_capi
+  (only seen so far on platforms where the curses module wasn't built), due to
+  an uncleared exception.
 
 - Issue #7728: test_timeout was changed to use support.bind_port instead of a
   hard coded port.
 
-- Issue #7376: instead of running a self-test (which was failing) when called
+- Issue #7376: Instead of running a self-test (which was failing) when called
   with no arguments, doctest.py now gives a usage message.
 
 - Issue #7396: fix regrtest -s, which was broken by the -j enhancement.
@@ -1677,20 +1969,20 @@
 - Issue #7498: test_multiprocessing now uses test.support.find_unused_port
   instead of a hardcoded port number in test_rapid_restart.
 
-- Issue #7431: use TESTFN in test_linecache instead of trying to create a
-  file in the Lib/test directory, which might be read-only for the
-  user running the tests.
-
-- Issue #7324: add a sanity check to regrtest argument parsing to
-  catch the case of an option with no handler.
-
-- Issue #7312: Add a -F flag to run the selected tests in a loop until
-  a test fails.  Can be combined with -j.
-
-- Issue #6551: test_zipimport could import and then destroy some modules of
-  the encodings package, which would make other tests fail further down
-  the road because the internally cached encoders and decoders would point
-  to empty global variables.
+- Issue #7431: Use TESTFN in test_linecache instead of trying to create a file
+  in the Lib/test directory, which might be read-only for the user running the
+  tests.
+
+- Issue #7324: Add a sanity check to regrtest argument parsing to catch the case
+  of an option with no handler.
+
+- Issue #7312: Add a -F flag to run the selected tests in a loop until a test
+  fails.  Can be combined with -j.
+
+- Issue #6551: test_zipimport could import and then destroy some modules of the
+  encodings package, which would make other tests fail further down the road
+  because the internally cached encoders and decoders would point to empty
+  global variables.
 
 - Issue #7295: Do not use a hardcoded file name in test_tarfile.
 
@@ -1706,38 +1998,37 @@
   calling methods on the object.
 
 - Issue #7222: Make thread "reaping" more reliable so that reference
-  leak-chasing test runs give sensible results. The previous method of
-  reaping threads could return successfully while some Thread objects were
-  still referenced. This also introduces a new private function:
+  leak-chasing test runs give sensible results. The previous method of reaping
+  threads could return successfully while some Thread objects were still
+  referenced. This also introduces a new private function:
   :func:`_thread._count()`.
 
-- Issue #7151: fixed regrtest -j so that output to stderr from a test no
-  longer runs the risk of causing the worker thread to fail.
+- Issue #7151: Fixed regrtest -j so that output to stderr from a test no longer
+  runs the risk of causing the worker thread to fail.
 
 - Issue #7055: test___all__ now greedily detects all modules which have an
   __all__ attribute, rather than using a hardcoded and incomplete list.
 
 - Issue #7058: Added save/restore for things like sys.argv and cwd to
-  runtest_inner in regrtest, with warnings if the called test modifies them,
-  and a new section in the summary report at the end.
+  runtest_inner in regrtest, with warnings if the called test modifies them, and
+  a new section in the summary report at the end.
 
 - Issue #7042: Fix test_signal (test_itimer_virtual) failure on OS X 10.6.
 
-- Fixed tests in importlib.test.source.test_abc_loader that were masking
-  the proper exceptions that should be raised for missing or improper code
-  object bytecode.
+- Fixed tests in importlib.test.source.test_abc_loader that were masking the
+  proper exceptions that should be raised for missing or improper code object
+  bytecode.
 
 - Removed importlib's custom test discovery code and switched to
-    unittest.TestLoader.discover().
+  unittest.TestLoader.discover().
 
 Tools/Demos
 -----------
 
-- Issue #5464: Implement plural forms in msgfmt.py.
+- Issue #5464, #8974: Implement plural forms in msgfmt.py.
 
 - iobench (a file I/O benchmark) and ccbench (a concurrency benchmark) were
-  added to the `Tools/` directory.  They were previously living in the
-  sandbox.
+  added to the `Tools/` directory.  They were previously living in the sandbox.
 
 
 What's New in Python 3.1?
@@ -1953,7 +2244,7 @@
   file is a binary.  Patch by Brodie Rao, tests by Daniel Diniz.  This fix
   corrects a pydoc regression.
 
-- Issue 5955: aifc's close method did not close the file it wrapped,
+- Issue #5955: aifc's close method did not close the file it wrapped,
   now it does.  This also means getfp method now returns the real fp.
 
 Installation
@@ -1986,7 +2277,7 @@
 Tests
 -----
 
-- Issue 5442: Tests for importlib were not properly skipping case-sensitivity
+- Issue #5442: Tests for importlib were not properly skipping case-sensitivity
   tests on darwin even when the OS was installed on a case-sensitive
   filesystem. Also fixed tests that should not be run when
   sys.dont_write_bytecode is true.
@@ -2102,7 +2393,7 @@
   conversions (including all float formatting operations) will be
   correctly rounded on these platforms.
 
-  See issue 1580 discussions for details of platforms for which
+  See issue #1580 discussions for details of platforms for which
   this change does not apply.
 
 - Issue #5759: float() didn't call __float__ on str subclasses.
@@ -2223,8 +2514,8 @@
   an error.  The _PY_STRUCT_FLOAT_COERCE constant has been removed.
   The version number has been bumped to 0.3.
 
-- Issue #5359: Readd the Berkley-DB detection code to allow _dbm be built
-  using Berkley-DB.
+- Issue #5359: Readd the Berkeley DB detection code to allow _dbm be built
+  using Berkeley DB.
 
 Tests
 -----

Modified: python/branches/py3k-dtoa/Misc/RPM/python-3.2.spec
==============================================================================
--- python/branches/py3k-dtoa/Misc/RPM/python-3.2.spec	(original)
+++ python/branches/py3k-dtoa/Misc/RPM/python-3.2.spec	Sun Aug  8 12:41:24 2010
@@ -39,7 +39,7 @@
 
 %define name python
 #--start constants--
-%define version 3.2a0
+%define version 3.2a1
 %define libvers 3.2
 #--end constants--
 %define release 1pydotorg
@@ -61,7 +61,7 @@
 Name: %{name}%{binsuffix}
 Version: %{version}
 Release: %{release}
-License: Modified CNRI Open Source License
+License: PSF
 Group: Development/Languages
 Source: Python-%{version}.tar.bz2
 %if %{include_docs}

Modified: python/branches/py3k-dtoa/Misc/developers.txt
==============================================================================
--- python/branches/py3k-dtoa/Misc/developers.txt	(original)
+++ python/branches/py3k-dtoa/Misc/developers.txt	Sun Aug  8 12:41:24 2010
@@ -20,6 +20,16 @@
 Permissions History
 -------------------
 
+- Terry Reedy was given commit access on Aug 04 2010 by MvL,
+  at suggestion of Nick Coghlan.
+
+- Brian Quinlan was given commit access on Jul 26 2010 by GFB,
+  for work related to PEP 3148.
+
+- Reid Kleckner was given commit access on Jul 11 2010 by GFB,
+  for work on the py3k-jit branch, at suggestion of the Unladen
+  Swallow team.
+
 - Alexander Belopolsky was given commit access on May 25 2010
   by MvL at suggestion of Mark Dickinson.
 

Modified: python/branches/py3k-dtoa/Misc/maintainers.rst
==============================================================================
--- python/branches/py3k-dtoa/Misc/maintainers.rst	(original)
+++ python/branches/py3k-dtoa/Misc/maintainers.rst	Sun Aug  8 12:41:24 2010
@@ -42,7 +42,7 @@
 __future__
 __main__            gvanrossum
 _dummy_thread       brett.cannon
-_thread
+_thread             pitrou
 abc
 aifc                r.david.murray
 argparse            bethard
@@ -89,7 +89,7 @@
 doctest             tim_one (inactive)
 dummy_threading     brett.cannon
 email               barry, r.david.murray
-encodings           lemburg, loewis
+encodings           lemburg
 errno
 exceptions
 fcntl
@@ -104,7 +104,7 @@
 gc                  pitrou
 getopt
 getpass
-gettext             loewis
+gettext
 glob
 grp
 gzip
@@ -125,7 +125,7 @@
 keyword
 lib2to3             benjamin.peterson
 linecache
-locale              loewis, lemburg
+locale              lemburg
 logging             vsajip
 macpath
 mailbox             andrew.kuchling
@@ -135,7 +135,7 @@
 mimetypes
 mmap
 modulefinder        theller, jvr
-msilib              loewis
+msilib
 msvcrt
 multiprocessing     jnoller
 netrc
@@ -144,10 +144,10 @@
 numbers
 operator
 optparse            aronacher
-os                  loewis
+os
 ossaudiodev
 parser
-pdb
+pdb                 georg.brandl
 pickle              alexandre.vassalotti, pitrou
 pickletools         alexandre.vassalotti
 pipes
@@ -206,33 +206,40 @@
 termios
 test
 textwrap
-threading
+threading           pitrou
 time                alexander.belopolsky
 timeit
 tkinter             gpolo
 token               georg.brandl
 tokenize
-trace
+trace               alexander.belopolsky
 traceback           georg.brandl
 tty
 turtle              gregorlingl
 types
-unicodedata         loewis, lemburg, ezio.melotti
+unicodedata         lemburg, ezio.melotti
 unittest            michael.foord
 urllib              orsenthil
 uu
 uuid
 warnings            brett.cannon
 wave
-weakref             fdrake
+weakref             fdrake, pitrou
 webbrowser          georg.brandl
-winreg
+winreg              brian.curtin
 winsound            effbot (inactive)
 wsgiref             pje
 xdrlib
-xml                 loewis
+xml.dom
+xml.dom.minidom
+xml.dom.pulldom
 xml.etree           effbot (inactive)
-xmlrpc              loewis
+xml.parsers.expat
+xml.sax
+xml.sax.handler
+xml.sax.saxutils
+xml.sax.xmlreader
+xmlrpc
 zipfile
 zipimport
 zlib
@@ -277,13 +284,13 @@
 i18n                lemburg
 import machinery    brett.cannon, ncoghlan
 io                  pitrou, benjamin.peterson
-locale              lemburg, loewis
+locale              lemburg
 mathematics         mark.dickinson, eric.smith, lemburg
 memory management   tim_one, lemburg
 networking          giampaolo.rodola
 packaging           tarek, lemburg
 py3 transition      benjamin.peterson
-release management  tarek, lemburg, benjamin.peterson, barry, loewis,
+release management  tarek, lemburg, benjamin.peterson, barry,
                     gvanrossum, anthonybaxter
 str.format          eric.smith
 time and dates      lemburg

Modified: python/branches/py3k-dtoa/Misc/python-wing.wpr
==============================================================================
--- python/branches/py3k-dtoa/Misc/python-wing.wpr	(original)
+++ python/branches/py3k-dtoa/Misc/python-wing.wpr	Sun Aug  8 12:41:24 2010
@@ -5,7 +5,7 @@
 ##################################################################
 [project attributes]
 proj.directory-list = [{'dirloc': loc('..'),
-                        'excludes': (),
+                        'excludes': [u'Lib/__pycache__'],
                         'filter': '*',
                         'include_hidden': False,
                         'recursive': True,

Modified: python/branches/py3k-dtoa/Modules/Setup.dist
==============================================================================
--- python/branches/py3k-dtoa/Modules/Setup.dist	(original)
+++ python/branches/py3k-dtoa/Modules/Setup.dist	Sun Aug  8 12:41:24 2010
@@ -170,7 +170,7 @@
 #atexit atexitmodule.c      # Register functions to be run at interpreter-shutdown
 #_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c	# elementtree accelerator
 #_pickle _pickle.c	# pickle accelerator
-#datetime datetimemodule.c	# date/time type
+#_datetime _datetimemodule.c	# datetime accelerator
 #_bisect _bisectmodule.c	# Bisection algorithms
 #_heapq _heapqmodule.c	# Heap queue algorithm
 

Modified: python/branches/py3k-dtoa/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_ctypes/_ctypes.c	(original)
+++ python/branches/py3k-dtoa/Modules/_ctypes/_ctypes.c	Sun Aug  8 12:41:24 2010
@@ -132,8 +132,6 @@
 /* a callable object used for unpickling */
 static PyObject *_unpickle;
 
-char *_ctypes_conversion_encoding = NULL;
-char *_ctypes_conversion_errors = NULL;
 
 
 /****************************************************************/
@@ -1090,13 +1088,7 @@
         return -1;
     }
 
-    if (PyUnicode_Check(value)) {
-        value = PyUnicode_AsEncodedString(value,
-                                          _ctypes_conversion_encoding,
-                                          _ctypes_conversion_errors);
-        if (!value)
-            return -1;
-    } else if (!PyBytes_Check(value)) {
+    if (!PyBytes_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                      "str/bytes expected instead of %s instance",
                      Py_TYPE(value)->tp_name);
@@ -1150,13 +1142,7 @@
                         "can't delete attribute");
         return -1;
     }
-    if (PyBytes_Check(value)) {
-        value = PyUnicode_FromEncodedObject(value,
-                                            _ctypes_conversion_encoding,
-                                            _ctypes_conversion_errors);
-        if (!value)
-            return -1;
-    } else if (!PyUnicode_Check(value)) {
+    if (!PyUnicode_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                         "unicode string expected instead of %s instance",
                         Py_TYPE(value)->tp_name);
@@ -1510,7 +1496,7 @@
         Py_INCREF(Py_None);
         return Py_None;
     }
-    if (PyBytes_Check(value) || PyUnicode_Check(value)) {
+    if (PyBytes_Check(value)) {
         PyCArgObject *parg;
         struct fielddesc *fd = _ctypes_get_fielddesc("z");
 

Modified: python/branches/py3k-dtoa/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_ctypes/callproc.c	(original)
+++ python/branches/py3k-dtoa/Modules/_ctypes/callproc.c	Sun Aug  8 12:41:24 2010
@@ -1641,37 +1641,6 @@
     return arg;
 }
 
-#ifdef CTYPES_UNICODE
-
-static char set_conversion_mode_doc[] =
-"set_conversion_mode(encoding, errors) -> (previous-encoding, previous-errors)\n\
-\n\
-Set the encoding and error handling ctypes uses when converting\n\
-between unicode and strings.  Returns the previous values.\n";
-
-static PyObject *
-set_conversion_mode(PyObject *self, PyObject *args)
-{
-    char *coding, *mode;
-    PyObject *result;
-
-    if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
-        return NULL;
-    result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
-    if (coding) {
-        PyMem_Free(_ctypes_conversion_encoding);
-        _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
-        strcpy(_ctypes_conversion_encoding, coding);
-    } else {
-        _ctypes_conversion_encoding = NULL;
-    }
-    PyMem_Free(_ctypes_conversion_errors);
-    _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
-    strcpy(_ctypes_conversion_errors, mode);
-    return result;
-}
-#endif
-
 static PyObject *
 resize(PyObject *self, PyObject *args)
 {
@@ -1852,9 +1821,6 @@
     {"_unpickle", unpickle, METH_VARARGS },
     {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
     {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
-#ifdef CTYPES_UNICODE
-    {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
-#endif
 #ifdef MS_WIN32
     {"get_last_error", get_last_error, METH_NOARGS},
     {"set_last_error", set_last_error, METH_VARARGS},

Modified: python/branches/py3k-dtoa/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_ctypes/cfield.c	(original)
+++ python/branches/py3k-dtoa/Modules/_ctypes/cfield.c	Sun Aug  8 12:41:24 2010
@@ -1168,20 +1168,6 @@
 static PyObject *
 c_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
-    if (PyUnicode_Check(value)) {
-        value = PyUnicode_AsEncodedString(value,
-                                          _ctypes_conversion_encoding,
-                                          _ctypes_conversion_errors);
-        if (value == NULL)
-            return NULL;
-        if (PyBytes_GET_SIZE(value) != 1) {
-            Py_DECREF(value);
-            goto error;
-        }
-        *(char *)ptr = PyBytes_AS_STRING(value)[0];
-        Py_DECREF(value);
-        _RET(value);
-    }
     if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) {
         *(char *)ptr = PyBytes_AS_STRING(value)[0];
         _RET(value);
@@ -1217,13 +1203,7 @@
 u_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
     Py_ssize_t len;
-    if (PyBytes_Check(value)) {
-        value = PyUnicode_FromEncodedObject(value,
-                                            _ctypes_conversion_encoding,
-                                            _ctypes_conversion_errors);
-        if (!value)
-            return NULL;
-    } else if (!PyUnicode_Check(value)) {
+    if (!PyUnicode_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                         "unicode string expected instead of %s instance",
                         value->ob_type->tp_name);
@@ -1292,13 +1272,7 @@
     /* It's easier to calculate in characters than in bytes */
     length /= sizeof(wchar_t);
 
-    if (PyBytes_Check(value)) {
-        value = PyUnicode_FromEncodedObject(value,
-                                            _ctypes_conversion_encoding,
-                                            _ctypes_conversion_errors);
-        if (!value)
-            return NULL;
-    } else if (!PyUnicode_Check(value)) {
+    if (!PyUnicode_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                         "unicode string expected instead of %s instance",
                         value->ob_type->tp_name);
@@ -1342,14 +1316,7 @@
     char *data;
     Py_ssize_t size;
 
-    if (PyUnicode_Check(value)) {
-        value = PyUnicode_AsEncodedString(value,
-                                                                          _ctypes_conversion_encoding,
-                                                                          _ctypes_conversion_errors);
-        if (value == NULL)
-            return NULL;
-        assert(PyBytes_Check(value));
-    } else if(PyBytes_Check(value)) {
+    if(PyBytes_Check(value)) {
         Py_INCREF(value);
     } else {
         PyErr_Format(PyExc_TypeError,
@@ -1393,14 +1360,6 @@
         *(char **)ptr = PyBytes_AsString(value);
         Py_INCREF(value);
         return value;
-    } else if (PyUnicode_Check(value)) {
-        PyObject *str = PyUnicode_AsEncodedString(value,
-                                                  _ctypes_conversion_encoding,
-                                                  _ctypes_conversion_errors);
-        if (str == NULL)
-            return NULL;
-        *(char **)ptr = PyBytes_AS_STRING(str);
-        return str;
     } else if (PyLong_Check(value)) {
 #if SIZEOF_VOID_P == SIZEOF_LONG_LONG
         *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value);
@@ -1454,13 +1413,7 @@
         Py_INCREF(Py_None);
         return Py_None;
     }
-    if (PyBytes_Check(value)) {
-        value = PyUnicode_FromEncodedObject(value,
-                                            _ctypes_conversion_encoding,
-                                            _ctypes_conversion_errors);
-        if (!value)
-            return NULL;
-    } else if (!PyUnicode_Check(value)) {
+    if (!PyUnicode_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                      "unicode string or integer address expected instead of %s instance",
                      value->ob_type->tp_name);
@@ -1540,12 +1493,6 @@
     /* convert value into a PyUnicodeObject or NULL */
     if (Py_None == value) {
         value = NULL;
-    } else if (PyBytes_Check(value)) {
-        value = PyUnicode_FromEncodedObject(value,
-                                            _ctypes_conversion_encoding,
-                                            _ctypes_conversion_errors);
-        if (!value)
-            return NULL;
     } else if (PyUnicode_Check(value)) {
         Py_INCREF(value); /* for the descref below */
     } else {

Modified: python/branches/py3k-dtoa/Modules/_ctypes/ctypes.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/_ctypes/ctypes.h	(original)
+++ python/branches/py3k-dtoa/Modules/_ctypes/ctypes.h	Sun Aug  8 12:41:24 2010
@@ -1,3 +1,7 @@
+#if defined (__SVR4) && defined (__sun)
+#   include <alloca.h>
+#endif
+
 #ifndef MS_WIN32
 #define max(a, b) ((a) > (b) ? (a) : (b))
 #define min(a, b) ((a) < (b) ? (a) : (b))

Modified: python/branches/py3k-dtoa/Modules/_cursesmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_cursesmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/_cursesmodule.c	Sun Aug  8 12:41:24 2010
@@ -2126,7 +2126,7 @@
         }
     }
 
-    if (setupterm(termstr,fd,&err) == ERR) {
+    if (!initialised_setupterm && setupterm(termstr,fd,&err) == ERR) {
         char* s = "setupterm: unknown error";
 
         if (err == 0) {

Modified: python/branches/py3k-dtoa/Modules/_io/_iomodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_io/_iomodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/_io/_iomodule.c	Sun Aug  8 12:41:24 2010
@@ -176,7 +176,7 @@
  * The main open() function
  */
 PyDoc_STRVAR(open_doc,
-"open(file, mode='r', buffering=None, encoding=None,\n"
+"open(file, mode='r', buffering=-1, encoding=None,\n"
 "     errors=None, newline=None, closefd=True) -> file object\n"
 "\n"
 "Open file and return a stream.  Raise IOError upon failure.\n"

Modified: python/branches/py3k-dtoa/Modules/_io/bufferedio.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_io/bufferedio.c	(original)
+++ python/branches/py3k-dtoa/Modules/_io/bufferedio.c	Sun Aug  8 12:41:24 2010
@@ -636,6 +636,8 @@
         return -1;
     }
 #ifdef WITH_THREAD
+    if (self->lock)
+        PyThread_free_lock(self->lock);
     self->lock = PyThread_allocate_lock();
     if (self->lock == NULL) {
         PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock");

Modified: python/branches/py3k-dtoa/Modules/_json.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_json.c	(original)
+++ python/branches/py3k-dtoa/Modules/_json.c	Sun Aug  8 12:41:24 2010
@@ -484,7 +484,7 @@
 }
 
 PyDoc_STRVAR(pydoc_scanstring,
-    "scanstring(basestring, end, strict=True) -> (bytes, end)\n"
+    "scanstring(string, end, strict=True) -> (string, end)\n"
     "\n"
     "Scan the string s for a JSON string. End is the index of the\n"
     "character in s after the quote that started the JSON string.\n"
@@ -512,7 +512,7 @@
     }
     else {
         PyErr_Format(PyExc_TypeError,
-                     "first argument must be a string or bytes, not %.80s",
+                     "first argument must be a string, not %.80s",
                      Py_TYPE(pystr)->tp_name);
         return NULL;
     }
@@ -520,7 +520,7 @@
 }
 
 PyDoc_STRVAR(pydoc_encode_basestring_ascii,
-    "encode_basestring_ascii(basestring) -> bytes\n"
+    "encode_basestring_ascii(string) -> string\n"
     "\n"
     "Return an ASCII-only JSON representation of a Python string"
 );
@@ -1454,7 +1454,7 @@
         }
         else {
             /* TODO: include repr of key */
-            PyErr_SetString(PyExc_ValueError, "keys must be a string");
+            PyErr_SetString(PyExc_TypeError, "keys must be a string");
             goto bail;
         }
 

Modified: python/branches/py3k-dtoa/Modules/_pickle.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_pickle.c	(original)
+++ python/branches/py3k-dtoa/Modules/_pickle.c	Sun Aug  8 12:41:24 2010
@@ -3466,29 +3466,19 @@
 static PyObject *
 instantiate(PyObject *cls, PyObject *args)
 {
-    PyObject *r = NULL;
-
-    /* XXX: The pickle.py module does not create instances this way when the
-       args tuple is empty. See Unpickler._instantiate(). */
-    if ((r = PyObject_CallObject(cls, args)))
-        return r;
-
-    /* XXX: Is this still nescessary? */
-    {
-        PyObject *tp, *v, *tb, *tmp_value;
-
-        PyErr_Fetch(&tp, &v, &tb);
-        tmp_value = v;
-        /* NULL occurs when there was a KeyboardInterrupt */
-        if (tmp_value == NULL)
-            tmp_value = Py_None;
-        if ((r = PyTuple_Pack(3, tmp_value, cls, args))) {
-            Py_XDECREF(v);
-            v = r;
-        }
-        PyErr_Restore(tp, v, tb);
+    PyObject *result = NULL;
+    /* Caller must assure args are a tuple.  Normally, args come from
+       Pdata_poptuple which packs objects from the top of the stack
+       into a newly created tuple. */
+    assert(PyTuple_Check(args));
+    if (Py_SIZE(args) > 0 || !PyType_Check(cls) ||
+        PyObject_HasAttrString(cls, "__getinitargs__")) {
+        result = PyObject_CallObject(cls, args);
+    }
+    else {
+        result = PyObject_CallMethod(cls, "__new__", "O", cls);
     }
-    return NULL;
+    return result;
 }
 
 static int
@@ -3547,7 +3537,7 @@
         if (len < 2)
             return bad_readline();
         class_name = PyUnicode_DecodeASCII(s, len - 1, "strict");
-        if (class_name == NULL) {
+        if (class_name != NULL) {
             cls = find_class(self, module_name, class_name);
             Py_DECREF(class_name);
         }
@@ -4276,7 +4266,7 @@
         return -1;
     PDATA_POP(self->stack, callable);
     if (callable) {
-        obj = instantiate(callable, argtup);
+        obj = PyObject_CallObject(callable, argtup);
         Py_DECREF(callable);
     }
     Py_DECREF(argtup);

Modified: python/branches/py3k-dtoa/Modules/_ssl.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_ssl.c	(original)
+++ python/branches/py3k-dtoa/Modules/_ssl.c	Sun Aug  8 12:41:24 2010
@@ -857,6 +857,7 @@
     }
 
     retval = _decode_certificate(x, verbose);
+    X509_free(x);
 
   fail0:
     Py_DECREF(filename);

Modified: python/branches/py3k-dtoa/Modules/_struct.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/_struct.c	(original)
+++ python/branches/py3k-dtoa/Modules/_struct.c	Sun Aug  8 12:41:24 2010
@@ -591,9 +591,13 @@
 static int
 np_bool(char *p, PyObject *v, const formatdef *f)
 {
-    BOOL_TYPE y;
+    int y;
+    BOOL_TYPE x;
     y = PyObject_IsTrue(v);
-    memcpy(p, (char *)&y, sizeof y);
+    if (y < 0)
+        return -1;
+    x = y;
+    memcpy(p, (char *)&x, sizeof x);
     return 0;
 }
 
@@ -863,9 +867,11 @@
 static int
 bp_bool(char *p, PyObject *v, const formatdef *f)
 {
-    char y;
+    int y;
     y = PyObject_IsTrue(v);
-    memcpy(p, (char *)&y, sizeof y);
+    if (y < 0)
+        return -1;
+    *p = (char)y;
     return 0;
 }
 
@@ -1241,6 +1247,9 @@
         PyErr_NoMemory();
         return -1;
     }
+    /* Free any s_codes value left over from a previous initialization. */
+    if (self->s_codes != NULL)
+        PyMem_FREE(self->s_codes);
     self->s_codes = codes;
 
     s = fmt;

Modified: python/branches/py3k-dtoa/Modules/arraymodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/arraymodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/arraymodule.c	Sun Aug  8 12:41:24 2010
@@ -800,7 +800,7 @@
         return -1;
 
     while ((v = PyIter_Next(it)) != NULL) {
-        if (ins1(self, (int) Py_SIZE(self), v) != 0) {
+        if (ins1(self, Py_SIZE(self), v) != 0) {
             Py_DECREF(v);
             Py_DECREF(it);
             return -1;
@@ -1075,7 +1075,7 @@
 static PyObject *
 array_append(arrayobject *self, PyObject *v)
 {
-    return ins(self, (int) Py_SIZE(self), v);
+    return ins(self, Py_SIZE(self), v);
 }
 
 PyDoc_STRVAR(append_doc,

Modified: python/branches/py3k-dtoa/Modules/binascii.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/binascii.c	(original)
+++ python/branches/py3k-dtoa/Modules/binascii.c	Sun Aug  8 12:41:24 2010
@@ -546,7 +546,7 @@
     Py_ssize_t len;
     int done = 0;
 
-    if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) )
+    if ( !PyArg_ParseTuple(args, "y*:a2b_hqx", &pascii) )
         return NULL;
     ascii_data = pascii.buf;
     len = pascii.len;
@@ -750,7 +750,7 @@
     PyObject *rv;
     Py_ssize_t in_len, out_len, out_len_left;
 
-    if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) )
+    if ( !PyArg_ParseTuple(args, "y*:rledecode_hqx", &pin) )
         return NULL;
     in_data = pin.buf;
     in_len = pin.len;
@@ -1121,7 +1121,7 @@
     char* retbuf;
     Py_ssize_t i, j;
 
-    if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg))
+    if (!PyArg_ParseTuple(args, "y*:a2b_hex", &parg))
         return NULL;
     argbuf = parg.buf;
     arglen = parg.len;
@@ -1199,7 +1199,7 @@
     static char *kwlist[] = {"data", "header", NULL};
     int header = 0;
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata,
+    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", kwlist, &pdata,
           &header))
         return NULL;
     data = pdata.buf;

Modified: python/branches/py3k-dtoa/Modules/bz2module.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/bz2module.c	(original)
+++ python/branches/py3k-dtoa/Modules/bz2module.c	Sun Aug  8 12:41:24 2010
@@ -138,6 +138,22 @@
 /* ===================================================================== */
 /* Utility functions. */
 
+/* Refuse regular I/O if there's data in the iteration-buffer.
+ * Mixing them would cause data to arrive out of order, as the read*
+ * methods don't use the iteration buffer. */
+static int
+check_iterbuffered(BZ2FileObject *f)
+{
+    if (f->f_buf != NULL &&
+        (f->f_bufend - f->f_bufptr) > 0 &&
+        f->f_buf[0] != '\0') {
+        PyErr_SetString(PyExc_ValueError,
+            "Mixing iteration and read methods would lose data");
+        return -1;
+    }
+    return 0;
+}
+
 static int
 Util_CatchBZ2Error(int bzerror)
 {
@@ -427,6 +443,10 @@
             goto cleanup;
     }
 
+    /* refuse to mix with f.next() */
+    if (check_iterbuffered(self))
+        goto cleanup;
+
     if (bytesrequested < 0)
         buffersize = Util_NewBufferSize((size_t)0);
     else
@@ -516,6 +536,10 @@
             goto cleanup;
     }
 
+    /* refuse to mix with f.next() */
+    if (check_iterbuffered(self))
+        goto cleanup;
+
     if (sizehint == 0)
         ret = PyBytes_FromStringAndSize("", 0);
     else
@@ -573,6 +597,10 @@
             goto cleanup;
     }
 
+    /* refuse to mix with f.next() */
+    if (check_iterbuffered(self))
+        goto cleanup;
+
     if ((list = PyList_New(0)) == NULL)
         goto cleanup;
 

Modified: python/branches/py3k-dtoa/Modules/cmathmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/cmathmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/cmathmodule.c	Sun Aug  8 12:41:24 2010
@@ -1024,6 +1024,19 @@
 Convert from polar coordinates to rectangular coordinates.");
 
 static PyObject *
+cmath_isfinite(PyObject *self, PyObject *args)
+{
+    Py_complex z;
+    if (!PyArg_ParseTuple(args, "D:isfinite", &z))
+        return NULL;
+    return PyBool_FromLong(Py_IS_FINITE(z.real) && Py_IS_FINITE(z.imag));
+}
+
+PyDoc_STRVAR(cmath_isfinite_doc,
+"isfinite(z) -> bool\n\
+Return True if both the real and imaginary parts of z are finite, else False.");
+
+static PyObject *
 cmath_isnan(PyObject *self, PyObject *args)
 {
     Py_complex z;
@@ -1065,6 +1078,7 @@
     {"cos",    cmath_cos,   METH_VARARGS, c_cos_doc},
     {"cosh",   cmath_cosh,  METH_VARARGS, c_cosh_doc},
     {"exp",    cmath_exp,   METH_VARARGS, c_exp_doc},
+    {"isfinite", cmath_isfinite, METH_VARARGS, cmath_isfinite_doc},
     {"isinf",  cmath_isinf, METH_VARARGS, cmath_isinf_doc},
     {"isnan",  cmath_isnan, METH_VARARGS, cmath_isnan_doc},
     {"log",    cmath_log,   METH_VARARGS, cmath_log_doc},

Deleted: python/branches/py3k-dtoa/Modules/datetimemodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/datetimemodule.c	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,5545 +0,0 @@
-/*  C implementation for the date/time type documented at
- *  http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
- */
-
-#include "Python.h"
-#include "modsupport.h"
-#include "structmember.h"
-
-#include <time.h>
-
-#include "timefuncs.h"
-
-/* Differentiate between building the core module and building extension
- * modules.
- */
-#ifndef Py_BUILD_CORE
-#define Py_BUILD_CORE
-#endif
-#include "datetime.h"
-#undef Py_BUILD_CORE
-
-/* We require that C int be at least 32 bits, and use int virtually
- * everywhere.  In just a few cases we use a temp long, where a Python
- * API returns a C long.  In such cases, we have to ensure that the
- * final result fits in a C int (this can be an issue on 64-bit boxes).
- */
-#if SIZEOF_INT < 4
-#       error "datetime.c requires that C int have at least 32 bits"
-#endif
-
-#define MINYEAR 1
-#define MAXYEAR 9999
-#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
-
-/* Nine decimal digits is easy to communicate, and leaves enough room
- * so that two delta days can be added w/o fear of overflowing a signed
- * 32-bit int, and with plenty of room left over to absorb any possible
- * carries from adding seconds.
- */
-#define MAX_DELTA_DAYS 999999999
-
-/* Rename the long macros in datetime.h to more reasonable short names. */
-#define GET_YEAR                PyDateTime_GET_YEAR
-#define GET_MONTH               PyDateTime_GET_MONTH
-#define GET_DAY                 PyDateTime_GET_DAY
-#define DATE_GET_HOUR           PyDateTime_DATE_GET_HOUR
-#define DATE_GET_MINUTE         PyDateTime_DATE_GET_MINUTE
-#define DATE_GET_SECOND         PyDateTime_DATE_GET_SECOND
-#define DATE_GET_MICROSECOND    PyDateTime_DATE_GET_MICROSECOND
-
-/* Date accessors for date and datetime. */
-#define SET_YEAR(o, v)          (((o)->data[0] = ((v) & 0xff00) >> 8), \
-                 ((o)->data[1] = ((v) & 0x00ff)))
-#define SET_MONTH(o, v)         (PyDateTime_GET_MONTH(o) = (v))
-#define SET_DAY(o, v)           (PyDateTime_GET_DAY(o) = (v))
-
-/* Date/Time accessors for datetime. */
-#define DATE_SET_HOUR(o, v)     (PyDateTime_DATE_GET_HOUR(o) = (v))
-#define DATE_SET_MINUTE(o, v)   (PyDateTime_DATE_GET_MINUTE(o) = (v))
-#define DATE_SET_SECOND(o, v)   (PyDateTime_DATE_GET_SECOND(o) = (v))
-#define DATE_SET_MICROSECOND(o, v)      \
-    (((o)->data[7] = ((v) & 0xff0000) >> 16), \
-     ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
-     ((o)->data[9] = ((v) & 0x0000ff)))
-
-/* Time accessors for time. */
-#define TIME_GET_HOUR           PyDateTime_TIME_GET_HOUR
-#define TIME_GET_MINUTE         PyDateTime_TIME_GET_MINUTE
-#define TIME_GET_SECOND         PyDateTime_TIME_GET_SECOND
-#define TIME_GET_MICROSECOND    PyDateTime_TIME_GET_MICROSECOND
-#define TIME_SET_HOUR(o, v)     (PyDateTime_TIME_GET_HOUR(o) = (v))
-#define TIME_SET_MINUTE(o, v)   (PyDateTime_TIME_GET_MINUTE(o) = (v))
-#define TIME_SET_SECOND(o, v)   (PyDateTime_TIME_GET_SECOND(o) = (v))
-#define TIME_SET_MICROSECOND(o, v)      \
-    (((o)->data[3] = ((v) & 0xff0000) >> 16), \
-     ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
-     ((o)->data[5] = ((v) & 0x0000ff)))
-
-/* Delta accessors for timedelta. */
-#define GET_TD_DAYS(o)          (((PyDateTime_Delta *)(o))->days)
-#define GET_TD_SECONDS(o)       (((PyDateTime_Delta *)(o))->seconds)
-#define GET_TD_MICROSECONDS(o)  (((PyDateTime_Delta *)(o))->microseconds)
-
-#define SET_TD_DAYS(o, v)       ((o)->days = (v))
-#define SET_TD_SECONDS(o, v)    ((o)->seconds = (v))
-#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
-
-/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
- * p->hastzinfo.
- */
-#define HASTZINFO(p)            (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
-
-/* M is a char or int claiming to be a valid month.  The macro is equivalent
- * to the two-sided Python test
- *      1 <= M <= 12
- */
-#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
-
-/* Forward declarations. */
-static PyTypeObject PyDateTime_DateType;
-static PyTypeObject PyDateTime_DateTimeType;
-static PyTypeObject PyDateTime_DeltaType;
-static PyTypeObject PyDateTime_TimeType;
-static PyTypeObject PyDateTime_TZInfoType;
-static PyTypeObject PyDateTime_TimeZoneType;
-
-/* ---------------------------------------------------------------------------
- * Math utilities.
- */
-
-/* k = i+j overflows iff k differs in sign from both inputs,
- * iff k^i has sign bit set and k^j has sign bit set,
- * iff (k^i)&(k^j) has sign bit set.
- */
-#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
-    ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
-
-/* Compute Python divmod(x, y), returning the quotient and storing the
- * remainder into *r.  The quotient is the floor of x/y, and that's
- * the real point of this.  C will probably truncate instead (C99
- * requires truncation; C89 left it implementation-defined).
- * Simplification:  we *require* that y > 0 here.  That's appropriate
- * for all the uses made of it.  This simplifies the code and makes
- * the overflow case impossible (divmod(LONG_MIN, -1) is the only
- * overflow case).
- */
-static int
-divmod(int x, int y, int *r)
-{
-    int quo;
-
-    assert(y > 0);
-    quo = x / y;
-    *r = x - quo * y;
-    if (*r < 0) {
-        --quo;
-        *r += y;
-    }
-    assert(0 <= *r && *r < y);
-    return quo;
-}
-
-/* Round a double to the nearest long.  |x| must be small enough to fit
- * in a C long; this is not checked.
- */
-static long
-round_to_long(double x)
-{
-    if (x >= 0.0)
-        x = floor(x + 0.5);
-    else
-        x = ceil(x - 0.5);
-    return (long)x;
-}
-
-/* Nearest integer to m / n for integers m and n. Half-integer results
- * are rounded to even.
- */
-static PyObject *
-divide_nearest(PyObject *m, PyObject *n)
-{
-    PyObject *result;
-    PyObject *temp;
-
-    temp = _PyLong_DivmodNear(m, n);
-    if (temp == NULL)
-        return NULL;
-    result = PyTuple_GET_ITEM(temp, 0);
-    Py_INCREF(result);
-    Py_DECREF(temp);
-
-    return result;
-}
-
-/* ---------------------------------------------------------------------------
- * General calendrical helper functions
- */
-
-/* For each month ordinal in 1..12, the number of days in that month,
- * and the number of days before that month in the same year.  These
- * are correct for non-leap years only.
- */
-static int _days_in_month[] = {
-    0, /* unused; this vector uses 1-based indexing */
-    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
-};
-
-static int _days_before_month[] = {
-    0, /* unused; this vector uses 1-based indexing */
-    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
-};
-
-/* year -> 1 if leap year, else 0. */
-static int
-is_leap(int year)
-{
-    /* Cast year to unsigned.  The result is the same either way, but
-     * C can generate faster code for unsigned mod than for signed
-     * mod (especially for % 4 -- a good compiler should just grab
-     * the last 2 bits when the LHS is unsigned).
-     */
-    const unsigned int ayear = (unsigned int)year;
-    return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
-}
-
-/* year, month -> number of days in that month in that year */
-static int
-days_in_month(int year, int month)
-{
-    assert(month >= 1);
-    assert(month <= 12);
-    if (month == 2 && is_leap(year))
-        return 29;
-    else
-        return _days_in_month[month];
-}
-
-/* year, month -> number of days in year preceeding first day of month */
-static int
-days_before_month(int year, int month)
-{
-    int days;
-
-    assert(month >= 1);
-    assert(month <= 12);
-    days = _days_before_month[month];
-    if (month > 2 && is_leap(year))
-        ++days;
-    return days;
-}
-
-/* year -> number of days before January 1st of year.  Remember that we
- * start with year 1, so days_before_year(1) == 0.
- */
-static int
-days_before_year(int year)
-{
-    int y = year - 1;
-    /* This is incorrect if year <= 0; we really want the floor
-     * here.  But so long as MINYEAR is 1, the smallest year this
-     * can see is 0 (this can happen in some normalization endcases),
-     * so we'll just special-case that.
-     */
-    assert (year >= 0);
-    if (y >= 0)
-        return y*365 + y/4 - y/100 + y/400;
-    else {
-        assert(y == -1);
-        return -366;
-    }
-}
-
-/* Number of days in 4, 100, and 400 year cycles.  That these have
- * the correct values is asserted in the module init function.
- */
-#define DI4Y    1461    /* days_before_year(5); days in 4 years */
-#define DI100Y  36524   /* days_before_year(101); days in 100 years */
-#define DI400Y  146097  /* days_before_year(401); days in 400 years  */
-
-/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
-static void
-ord_to_ymd(int ordinal, int *year, int *month, int *day)
-{
-    int n, n1, n4, n100, n400, leapyear, preceding;
-
-    /* ordinal is a 1-based index, starting at 1-Jan-1.  The pattern of
-     * leap years repeats exactly every 400 years.  The basic strategy is
-     * to find the closest 400-year boundary at or before ordinal, then
-     * work with the offset from that boundary to ordinal.  Life is much
-     * clearer if we subtract 1 from ordinal first -- then the values
-     * of ordinal at 400-year boundaries are exactly those divisible
-     * by DI400Y:
-     *
-     *    D  M   Y            n              n-1
-     *    -- --- ----        ----------     ----------------
-     *    31 Dec -400        -DI400Y       -DI400Y -1
-     *     1 Jan -399         -DI400Y +1   -DI400Y      400-year boundary
-     *    ...
-     *    30 Dec  000        -1             -2
-     *    31 Dec  000         0             -1
-     *     1 Jan  001         1              0          400-year boundary
-     *     2 Jan  001         2              1
-     *     3 Jan  001         3              2
-     *    ...
-     *    31 Dec  400         DI400Y        DI400Y -1
-     *     1 Jan  401         DI400Y +1     DI400Y      400-year boundary
-     */
-    assert(ordinal >= 1);
-    --ordinal;
-    n400 = ordinal / DI400Y;
-    n = ordinal % DI400Y;
-    *year = n400 * 400 + 1;
-
-    /* Now n is the (non-negative) offset, in days, from January 1 of
-     * year, to the desired date.  Now compute how many 100-year cycles
-     * precede n.
-     * Note that it's possible for n100 to equal 4!  In that case 4 full
-     * 100-year cycles precede the desired day, which implies the
-     * desired day is December 31 at the end of a 400-year cycle.
-     */
-    n100 = n / DI100Y;
-    n = n % DI100Y;
-
-    /* Now compute how many 4-year cycles precede it. */
-    n4 = n / DI4Y;
-    n = n % DI4Y;
-
-    /* And now how many single years.  Again n1 can be 4, and again
-     * meaning that the desired day is December 31 at the end of the
-     * 4-year cycle.
-     */
-    n1 = n / 365;
-    n = n % 365;
-
-    *year += n100 * 100 + n4 * 4 + n1;
-    if (n1 == 4 || n100 == 4) {
-        assert(n == 0);
-        *year -= 1;
-        *month = 12;
-        *day = 31;
-        return;
-    }
-
-    /* Now the year is correct, and n is the offset from January 1.  We
-     * find the month via an estimate that's either exact or one too
-     * large.
-     */
-    leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
-    assert(leapyear == is_leap(*year));
-    *month = (n + 50) >> 5;
-    preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
-    if (preceding > n) {
-        /* estimate is too large */
-        *month -= 1;
-        preceding -= days_in_month(*year, *month);
-    }
-    n -= preceding;
-    assert(0 <= n);
-    assert(n < days_in_month(*year, *month));
-
-    *day = n + 1;
-}
-
-/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
-static int
-ymd_to_ord(int year, int month, int day)
-{
-    return days_before_year(year) + days_before_month(year, month) + day;
-}
-
-/* Day of week, where Monday==0, ..., Sunday==6.  1/1/1 was a Monday. */
-static int
-weekday(int year, int month, int day)
-{
-    return (ymd_to_ord(year, month, day) + 6) % 7;
-}
-
-/* Ordinal of the Monday starting week 1 of the ISO year.  Week 1 is the
- * first calendar week containing a Thursday.
- */
-static int
-iso_week1_monday(int year)
-{
-    int first_day = ymd_to_ord(year, 1, 1);     /* ord of 1/1 */
-    /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
-    int first_weekday = (first_day + 6) % 7;
-    /* ordinal of closest Monday at or before 1/1 */
-    int week1_monday  = first_day - first_weekday;
-
-    if (first_weekday > 3)      /* if 1/1 was Fri, Sat, Sun */
-        week1_monday += 7;
-    return week1_monday;
-}
-
-/* ---------------------------------------------------------------------------
- * Range checkers.
- */
-
-/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS.  If so, return 0.
- * If not, raise OverflowError and return -1.
- */
-static int
-check_delta_day_range(int days)
-{
-    if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
-        return 0;
-    PyErr_Format(PyExc_OverflowError,
-                 "days=%d; must have magnitude <= %d",
-                 days, MAX_DELTA_DAYS);
-    return -1;
-}
-
-/* Check that date arguments are in range.  Return 0 if they are.  If they
- * aren't, raise ValueError and return -1.
- */
-static int
-check_date_args(int year, int month, int day)
-{
-
-    if (year < MINYEAR || year > MAXYEAR) {
-        PyErr_SetString(PyExc_ValueError,
-                        "year is out of range");
-        return -1;
-    }
-    if (month < 1 || month > 12) {
-        PyErr_SetString(PyExc_ValueError,
-                        "month must be in 1..12");
-        return -1;
-    }
-    if (day < 1 || day > days_in_month(year, month)) {
-        PyErr_SetString(PyExc_ValueError,
-                        "day is out of range for month");
-        return -1;
-    }
-    return 0;
-}
-
-/* Check that time arguments are in range.  Return 0 if they are.  If they
- * aren't, raise ValueError and return -1.
- */
-static int
-check_time_args(int h, int m, int s, int us)
-{
-    if (h < 0 || h > 23) {
-        PyErr_SetString(PyExc_ValueError,
-                        "hour must be in 0..23");
-        return -1;
-    }
-    if (m < 0 || m > 59) {
-        PyErr_SetString(PyExc_ValueError,
-                        "minute must be in 0..59");
-        return -1;
-    }
-    if (s < 0 || s > 59) {
-        PyErr_SetString(PyExc_ValueError,
-                        "second must be in 0..59");
-        return -1;
-    }
-    if (us < 0 || us > 999999) {
-        PyErr_SetString(PyExc_ValueError,
-                        "microsecond must be in 0..999999");
-        return -1;
-    }
-    return 0;
-}
-
-/* ---------------------------------------------------------------------------
- * Normalization utilities.
- */
-
-/* One step of a mixed-radix conversion.  A "hi" unit is equivalent to
- * factor "lo" units.  factor must be > 0.  If *lo is less than 0, or
- * at least factor, enough of *lo is converted into "hi" units so that
- * 0 <= *lo < factor.  The input values must be such that int overflow
- * is impossible.
- */
-static void
-normalize_pair(int *hi, int *lo, int factor)
-{
-    assert(factor > 0);
-    assert(lo != hi);
-    if (*lo < 0 || *lo >= factor) {
-        const int num_hi = divmod(*lo, factor, lo);
-        const int new_hi = *hi + num_hi;
-        assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
-        *hi = new_hi;
-    }
-    assert(0 <= *lo && *lo < factor);
-}
-
-/* Fiddle days (d), seconds (s), and microseconds (us) so that
- *      0 <= *s < 24*3600
- *      0 <= *us < 1000000
- * The input values must be such that the internals don't overflow.
- * The way this routine is used, we don't get close.
- */
-static void
-normalize_d_s_us(int *d, int *s, int *us)
-{
-    if (*us < 0 || *us >= 1000000) {
-        normalize_pair(s, us, 1000000);
-        /* |s| can't be bigger than about
-         * |original s| + |original us|/1000000 now.
-         */
-
-    }
-    if (*s < 0 || *s >= 24*3600) {
-        normalize_pair(d, s, 24*3600);
-        /* |d| can't be bigger than about
-         * |original d| +
-         * (|original s| + |original us|/1000000) / (24*3600) now.
-         */
-    }
-    assert(0 <= *s && *s < 24*3600);
-    assert(0 <= *us && *us < 1000000);
-}
-
-/* Fiddle years (y), months (m), and days (d) so that
- *      1 <= *m <= 12
- *      1 <= *d <= days_in_month(*y, *m)
- * The input values must be such that the internals don't overflow.
- * The way this routine is used, we don't get close.
- */
-static int
-normalize_y_m_d(int *y, int *m, int *d)
-{
-    int dim;            /* # of days in month */
-
-    /* This gets muddy:  the proper range for day can't be determined
-     * without knowing the correct month and year, but if day is, e.g.,
-     * plus or minus a million, the current month and year values make
-     * no sense (and may also be out of bounds themselves).
-     * Saying 12 months == 1 year should be non-controversial.
-     */
-    if (*m < 1 || *m > 12) {
-        --*m;
-        normalize_pair(y, m, 12);
-        ++*m;
-        /* |y| can't be bigger than about
-         * |original y| + |original m|/12 now.
-         */
-    }
-    assert(1 <= *m && *m <= 12);
-
-    /* Now only day can be out of bounds (year may also be out of bounds
-     * for a datetime object, but we don't care about that here).
-     * If day is out of bounds, what to do is arguable, but at least the
-     * method here is principled and explainable.
-     */
-    dim = days_in_month(*y, *m);
-    if (*d < 1 || *d > dim) {
-        /* Move day-1 days from the first of the month.  First try to
-         * get off cheap if we're only one day out of range
-         * (adjustments for timezone alone can't be worse than that).
-         */
-        if (*d == 0) {
-            --*m;
-            if (*m > 0)
-                *d = days_in_month(*y, *m);
-            else {
-                --*y;
-                *m = 12;
-                *d = 31;
-            }
-        }
-        else if (*d == dim + 1) {
-            /* move forward a day */
-            ++*m;
-            *d = 1;
-            if (*m > 12) {
-                *m = 1;
-                ++*y;
-            }
-        }
-        else {
-            int ordinal = ymd_to_ord(*y, *m, 1) +
-                                      *d - 1;
-            if (ordinal < 1 || ordinal > MAXORDINAL) {
-                goto error;
-            } else {
-                ord_to_ymd(ordinal, y, m, d);
-                return 0;
-            }
-        }
-    }
-    assert(*m > 0);
-    assert(*d > 0);
-    if (MINYEAR <= *y && *y <= MAXYEAR)
-        return 0;
- error:
-    PyErr_SetString(PyExc_OverflowError,
-            "date value out of range");
-    return -1;
-
-}
-
-/* Fiddle out-of-bounds months and days so that the result makes some kind
- * of sense.  The parameters are both inputs and outputs.  Returns < 0 on
- * failure, where failure means the adjusted year is out of bounds.
- */
-static int
-normalize_date(int *year, int *month, int *day)
-{
-    return normalize_y_m_d(year, month, day);
-}
-
-/* Force all the datetime fields into range.  The parameters are both
- * inputs and outputs.  Returns < 0 on error.
- */
-static int
-normalize_datetime(int *year, int *month, int *day,
-                   int *hour, int *minute, int *second,
-                   int *microsecond)
-{
-    normalize_pair(second, microsecond, 1000000);
-    normalize_pair(minute, second, 60);
-    normalize_pair(hour, minute, 60);
-    normalize_pair(day, hour, 24);
-    return normalize_date(year, month, day);
-}
-
-/* ---------------------------------------------------------------------------
- * Basic object allocation:  tp_alloc implementations.  These allocate
- * Python objects of the right size and type, and do the Python object-
- * initialization bit.  If there's not enough memory, they return NULL after
- * setting MemoryError.  All data members remain uninitialized trash.
- *
- * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
- * member is needed.  This is ugly, imprecise, and possibly insecure.
- * tp_basicsize for the time and datetime types is set to the size of the
- * struct that has room for the tzinfo member, so subclasses in Python will
- * allocate enough space for a tzinfo member whether or not one is actually
- * needed.  That's the "ugly and imprecise" parts.  The "possibly insecure"
- * part is that PyType_GenericAlloc() (which subclasses in Python end up
- * using) just happens today to effectively ignore the nitems argument
- * when tp_itemsize is 0, which it is for these type objects.  If that
- * changes, perhaps the callers of tp_alloc slots in this file should
- * be changed to force a 0 nitems argument unless the type being allocated
- * is a base type implemented in this file (so that tp_alloc is time_alloc
- * or datetime_alloc below, which know about the nitems abuse).
- */
-
-static PyObject *
-time_alloc(PyTypeObject *type, Py_ssize_t aware)
-{
-    PyObject *self;
-
-    self = (PyObject *)
-        PyObject_MALLOC(aware ?
-                        sizeof(PyDateTime_Time) :
-                sizeof(_PyDateTime_BaseTime));
-    if (self == NULL)
-        return (PyObject *)PyErr_NoMemory();
-    PyObject_INIT(self, type);
-    return self;
-}
-
-static PyObject *
-datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
-{
-    PyObject *self;
-
-    self = (PyObject *)
-        PyObject_MALLOC(aware ?
-                        sizeof(PyDateTime_DateTime) :
-                sizeof(_PyDateTime_BaseDateTime));
-    if (self == NULL)
-        return (PyObject *)PyErr_NoMemory();
-    PyObject_INIT(self, type);
-    return self;
-}
-
-/* ---------------------------------------------------------------------------
- * Helpers for setting object fields.  These work on pointers to the
- * appropriate base class.
- */
-
-/* For date and datetime. */
-static void
-set_date_fields(PyDateTime_Date *self, int y, int m, int d)
-{
-    self->hashcode = -1;
-    SET_YEAR(self, y);
-    SET_MONTH(self, m);
-    SET_DAY(self, d);
-}
-
-/* ---------------------------------------------------------------------------
- * Create various objects, mostly without range checking.
- */
-
-/* Create a date instance with no range checking. */
-static PyObject *
-new_date_ex(int year, int month, int day, PyTypeObject *type)
-{
-    PyDateTime_Date *self;
-
-    self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
-    if (self != NULL)
-        set_date_fields(self, year, month, day);
-    return (PyObject *) self;
-}
-
-#define new_date(year, month, day) \
-    new_date_ex(year, month, day, &PyDateTime_DateType)
-
-/* Create a datetime instance with no range checking. */
-static PyObject *
-new_datetime_ex(int year, int month, int day, int hour, int minute,
-             int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
-{
-    PyDateTime_DateTime *self;
-    char aware = tzinfo != Py_None;
-
-    self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
-    if (self != NULL) {
-        self->hastzinfo = aware;
-        set_date_fields((PyDateTime_Date *)self, year, month, day);
-        DATE_SET_HOUR(self, hour);
-        DATE_SET_MINUTE(self, minute);
-        DATE_SET_SECOND(self, second);
-        DATE_SET_MICROSECOND(self, usecond);
-        if (aware) {
-            Py_INCREF(tzinfo);
-            self->tzinfo = tzinfo;
-        }
-    }
-    return (PyObject *)self;
-}
-
-#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo)           \
-    new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo,            \
-                    &PyDateTime_DateTimeType)
-
-/* Create a time instance with no range checking. */
-static PyObject *
-new_time_ex(int hour, int minute, int second, int usecond,
-            PyObject *tzinfo, PyTypeObject *type)
-{
-    PyDateTime_Time *self;
-    char aware = tzinfo != Py_None;
-
-    self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
-    if (self != NULL) {
-        self->hastzinfo = aware;
-        self->hashcode = -1;
-        TIME_SET_HOUR(self, hour);
-        TIME_SET_MINUTE(self, minute);
-        TIME_SET_SECOND(self, second);
-        TIME_SET_MICROSECOND(self, usecond);
-        if (aware) {
-            Py_INCREF(tzinfo);
-            self->tzinfo = tzinfo;
-        }
-    }
-    return (PyObject *)self;
-}
-
-#define new_time(hh, mm, ss, us, tzinfo)                \
-    new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
-
-/* Create a timedelta instance.  Normalize the members iff normalize is
- * true.  Passing false is a speed optimization, if you know for sure
- * that seconds and microseconds are already in their proper ranges.  In any
- * case, raises OverflowError and returns NULL if the normalized days is out
- * of range).
- */
-static PyObject *
-new_delta_ex(int days, int seconds, int microseconds, int normalize,
-             PyTypeObject *type)
-{
-    PyDateTime_Delta *self;
-
-    if (normalize)
-        normalize_d_s_us(&days, &seconds, &microseconds);
-    assert(0 <= seconds && seconds < 24*3600);
-    assert(0 <= microseconds && microseconds < 1000000);
-
-    if (check_delta_day_range(days) < 0)
-        return NULL;
-
-    self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
-    if (self != NULL) {
-        self->hashcode = -1;
-        SET_TD_DAYS(self, days);
-        SET_TD_SECONDS(self, seconds);
-        SET_TD_MICROSECONDS(self, microseconds);
-    }
-    return (PyObject *) self;
-}
-
-#define new_delta(d, s, us, normalize)  \
-    new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
-
-
-typedef struct
-{
-    PyObject_HEAD
-    PyObject *offset;
-    PyObject *name;
-} PyDateTime_TimeZone;
-
-/* Create new timezone instance checking offset range.  This
-   function does not check the name argument.  Caller must assure
-   that offset is a timedelta instance and name is either NULL
-   or a unicode object. */
-static PyObject *
-new_timezone(PyObject *offset, PyObject *name)
-{
-    PyDateTime_TimeZone *self;
-    PyTypeObject *type = &PyDateTime_TimeZoneType;
-
-    assert(offset != NULL);
-    assert(PyDelta_Check(offset));
-    assert(name == NULL || PyUnicode_Check(name));
-
-    if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
-        PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                     " representing a whole number of minutes");
-        return NULL;
-    }
-    if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
-        GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
-        PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                     " strictly between -timedelta(hours=24) and"
-                     " timedelta(hours=24).");
-        return NULL;
-    }
-
-    self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
-    if (self == NULL) {
-        return NULL;
-    }
-    Py_INCREF(offset);
-    self->offset = offset;
-    Py_XINCREF(name);
-    self->name = name;
-    return (PyObject *)self;
-}
-
-/* ---------------------------------------------------------------------------
- * tzinfo helpers.
- */
-
-/* Ensure that p is None or of a tzinfo subclass.  Return 0 if OK; if not
- * raise TypeError and return -1.
- */
-static int
-check_tzinfo_subclass(PyObject *p)
-{
-    if (p == Py_None || PyTZInfo_Check(p))
-        return 0;
-    PyErr_Format(PyExc_TypeError,
-                 "tzinfo argument must be None or of a tzinfo subclass, "
-                 "not type '%s'",
-                 Py_TYPE(p)->tp_name);
-    return -1;
-}
-
-/* Return tzinfo.methname(tzinfoarg), without any checking of results.
- * If tzinfo is None, returns None.
- */
-static PyObject *
-call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
-{
-    PyObject *result;
-
-    assert(tzinfo && methname && tzinfoarg);
-    assert(check_tzinfo_subclass(tzinfo) >= 0);
-    if (tzinfo == Py_None) {
-        result = Py_None;
-        Py_INCREF(result);
-    }
-    else
-        result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
-    return result;
-}
-
-/* If self has a tzinfo member, return a BORROWED reference to it.  Else
- * return NULL, which is NOT AN ERROR.  There are no error returns here,
- * and the caller must not decref the result.
- */
-static PyObject *
-get_tzinfo_member(PyObject *self)
-{
-    PyObject *tzinfo = NULL;
-
-    if (PyDateTime_Check(self) && HASTZINFO(self))
-        tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
-    else if (PyTime_Check(self) && HASTZINFO(self))
-        tzinfo = ((PyDateTime_Time *)self)->tzinfo;
-
-    return tzinfo;
-}
-
-/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
- * result.  tzinfo must be an instance of the tzinfo class.  If the method
- * returns None, this returns 0 and sets *none to 1.  If the method doesn't
- * return None or timedelta, TypeError is raised and this returns -1.  If it
- * returnsa timedelta and the value is out of range or isn't a whole number
- * of minutes, ValueError is raised and this returns -1.
- * Else *none is set to 0 and the integer method result is returned.
- */
-static int
-call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
-                       int *none)
-{
-    PyObject *u;
-    int result = -1;
-
-    assert(tzinfo != NULL);
-    assert(PyTZInfo_Check(tzinfo));
-    assert(tzinfoarg != NULL);
-
-    *none = 0;
-    u = call_tzinfo_method(tzinfo, name, tzinfoarg);
-    if (u == NULL)
-        return -1;
-
-    else if (u == Py_None) {
-        result = 0;
-        *none = 1;
-    }
-    else if (PyDelta_Check(u)) {
-        const int days = GET_TD_DAYS(u);
-        if (days < -1 || days > 0)
-            result = 24*60;             /* trigger ValueError below */
-        else {
-            /* next line can't overflow because we know days
-             * is -1 or 0 now
-             */
-            int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
-            result = divmod(ss, 60, &ss);
-            if (ss || GET_TD_MICROSECONDS(u)) {
-                PyErr_Format(PyExc_ValueError,
-                             "tzinfo.%s() must return a "
-                             "whole number of minutes",
-                             name);
-                result = -1;
-            }
-        }
-    }
-    else {
-        PyErr_Format(PyExc_TypeError,
-                     "tzinfo.%s() must return None or "
-                     "timedelta, not '%s'",
-                     name, Py_TYPE(u)->tp_name);
-    }
-
-    Py_DECREF(u);
-    if (result < -1439 || result > 1439) {
-        PyErr_Format(PyExc_ValueError,
-                     "tzinfo.%s() returned %d; must be in "
-                     "-1439 .. 1439",
-                     name, result);
-        result = -1;
-    }
-    return result;
-}
-
-/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
- * result.  tzinfo must be an instance of the tzinfo class.  If utcoffset()
- * returns None, call_utcoffset returns 0 and sets *none to 1.  If uctoffset()
- * doesn't return None or timedelta, TypeError is raised and this returns -1.
- * If utcoffset() returns an invalid timedelta (out of range, or not a whole
- * # of minutes), ValueError is raised and this returns -1.  Else *none is
- * set to 0 and the offset is returned (as int # of minutes east of UTC).
- */
-static int
-call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
-{
-    return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
-}
-
-/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
- */
-static PyObject *
-offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
-    PyObject *result;
-
-    assert(tzinfo && name && tzinfoarg);
-    if (tzinfo == Py_None) {
-        result = Py_None;
-        Py_INCREF(result);
-    }
-    else {
-        int none;
-        int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
-                                            &none);
-        if (offset < 0 && PyErr_Occurred())
-            return NULL;
-        if (none) {
-            result = Py_None;
-            Py_INCREF(result);
-        }
-        else
-            result = new_delta(0, offset * 60, 0, 1);
-    }
-    return result;
-}
-
-/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
- * result.  tzinfo must be an instance of the tzinfo class.  If dst()
- * returns None, call_dst returns 0 and sets *none to 1.  If dst()
- & doesn't return None or timedelta, TypeError is raised and this
- * returns -1.  If dst() returns an invalid timedelta for a UTC offset,
- * ValueError is raised and this returns -1.  Else *none is set to 0 and
- * the offset is returned (as an int # of minutes east of UTC).
- */
-static int
-call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
-{
-    return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
-}
-
-/* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be
- * an instance of the tzinfo class or None.  If tzinfo isn't None, and
- * tzname() doesn't return None or a string, TypeError is raised and this
- * returns NULL.  If the result is a string, we ensure it is a Unicode
- * string.
- */
-static PyObject *
-call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    PyObject *result;
-
-    assert(tzinfo != NULL);
-    assert(check_tzinfo_subclass(tzinfo) >= 0);
-    assert(tzinfoarg != NULL);
-
-    if (tzinfo == Py_None) {
-        result = Py_None;
-        Py_INCREF(result);
-    }
-    else
-        result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
-
-    if (result != NULL && result != Py_None) {
-        if (!PyUnicode_Check(result)) {
-            PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
-                         "return None or a string, not '%s'",
-                         Py_TYPE(result)->tp_name);
-            Py_DECREF(result);
-            result = NULL;
-        }
-    }
-    return result;
-}
-
-typedef enum {
-              /* an exception has been set; the caller should pass it on */
-          OFFSET_ERROR,
-
-          /* type isn't date, datetime, or time subclass */
-          OFFSET_UNKNOWN,
-
-          /* date,
-           * datetime with !hastzinfo
-           * datetime with None tzinfo,
-           * datetime where utcoffset() returns None
-           * time with !hastzinfo
-           * time with None tzinfo,
-           * time where utcoffset() returns None
-           */
-          OFFSET_NAIVE,
-
-          /* time or datetime where utcoffset() doesn't return None */
-          OFFSET_AWARE
-} naivety;
-
-/* Classify an object as to whether it's naive or offset-aware.  See
- * the "naivety" typedef for details.  If the type is aware, *offset is set
- * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
- * If the type is offset-naive (or unknown, or error), *offset is set to 0.
- * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
- */
-static naivety
-classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
-{
-    int none;
-    PyObject *tzinfo;
-
-    assert(tzinfoarg != NULL);
-    *offset = 0;
-    tzinfo = get_tzinfo_member(op);     /* NULL means no tzinfo, not error */
-    if (tzinfo == Py_None)
-        return OFFSET_NAIVE;
-    if (tzinfo == NULL) {
-        /* note that a datetime passes the PyDate_Check test */
-        return (PyTime_Check(op) || PyDate_Check(op)) ?
-               OFFSET_NAIVE : OFFSET_UNKNOWN;
-    }
-    *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
-    if (*offset == -1 && PyErr_Occurred())
-        return OFFSET_ERROR;
-    return none ? OFFSET_NAIVE : OFFSET_AWARE;
-}
-
-/* Classify two objects as to whether they're naive or offset-aware.
- * This isn't quite the same as calling classify_utcoffset() twice:  for
- * binary operations (comparison and subtraction), we generally want to
- * ignore the tzinfo members if they're identical.  This is by design,
- * so that results match "naive" expectations when mixing objects from a
- * single timezone.  So in that case, this sets both offsets to 0 and
- * both naiveties to OFFSET_NAIVE.
- * The function returns 0 if everything's OK, and -1 on error.
- */
-static int
-classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
-                        PyObject *tzinfoarg1,
-                        PyObject *o2, int *offset2, naivety *n2,
-                        PyObject *tzinfoarg2)
-{
-    if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
-        *offset1 = *offset2 = 0;
-        *n1 = *n2 = OFFSET_NAIVE;
-    }
-    else {
-        *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
-        if (*n1 == OFFSET_ERROR)
-            return -1;
-        *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
-        if (*n2 == OFFSET_ERROR)
-            return -1;
-    }
-    return 0;
-}
-
-/* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,
- * stuff
- *     ", tzinfo=" + repr(tzinfo)
- * before the closing ")".
- */
-static PyObject *
-append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
-{
-    PyObject *temp;
-
-    assert(PyUnicode_Check(repr));
-    assert(tzinfo);
-    if (tzinfo == Py_None)
-        return repr;
-    /* Get rid of the trailing ')'. */
-    assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
-    temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
-                                      PyUnicode_GET_SIZE(repr) - 1);
-    Py_DECREF(repr);
-    if (temp == NULL)
-        return NULL;
-    repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
-    Py_DECREF(temp);
-    return repr;
-}
-
-/* ---------------------------------------------------------------------------
- * String format helpers.
- */
-
-static PyObject *
-format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
-{
-    static const char *DayNames[] = {
-        "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
-    };
-    static const char *MonthNames[] = {
-        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-    };
-
-    int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
-
-    return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
-                                DayNames[wday], MonthNames[GET_MONTH(date)-1],
-                                GET_DAY(date), hours, minutes, seconds,
-                                GET_YEAR(date));
-}
-
-/* Add an hours & minutes UTC offset string to buf.  buf has no more than
- * buflen bytes remaining.  The UTC offset is gotten by calling
- * tzinfo.uctoffset(tzinfoarg).  If that returns None, \0 is stored into
- * *buf, and that's all.  Else the returned value is checked for sanity (an
- * integer in range), and if that's OK it's converted to an hours & minutes
- * string of the form
- *   sign HH sep MM
- * Returns 0 if everything is OK.  If the return value from utcoffset() is
- * bogus, an appropriate exception is set and -1 is returned.
- */
-static int
-format_utcoffset(char *buf, size_t buflen, const char *sep,
-                PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    int offset;
-    int hours;
-    int minutes;
-    char sign;
-    int none;
-
-    assert(buflen >= 1);
-
-    offset = call_utcoffset(tzinfo, tzinfoarg, &none);
-    if (offset == -1 && PyErr_Occurred())
-        return -1;
-    if (none) {
-        *buf = '\0';
-        return 0;
-    }
-    sign = '+';
-    if (offset < 0) {
-        sign = '-';
-        offset = - offset;
-    }
-    hours = divmod(offset, 60, &minutes);
-    PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
-    return 0;
-}
-
-static PyObject *
-make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
-{
-    PyObject *temp;
-    PyObject *tzinfo = get_tzinfo_member(object);
-    PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
-    if (Zreplacement == NULL)
-        return NULL;
-    if (tzinfo == Py_None || tzinfo == NULL)
-        return Zreplacement;
-
-    assert(tzinfoarg != NULL);
-    temp = call_tzname(tzinfo, tzinfoarg);
-    if (temp == NULL)
-        goto Error;
-    if (temp == Py_None) {
-        Py_DECREF(temp);
-        return Zreplacement;
-    }
-
-    assert(PyUnicode_Check(temp));
-    /* Since the tzname is getting stuffed into the
-     * format, we have to double any % signs so that
-     * strftime doesn't treat them as format codes.
-     */
-    Py_DECREF(Zreplacement);
-    Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
-    Py_DECREF(temp);
-    if (Zreplacement == NULL)
-        return NULL;
-    if (!PyUnicode_Check(Zreplacement)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "tzname.replace() did not return a string");
-        goto Error;
-    }
-    return Zreplacement;
-
-  Error:
-    Py_DECREF(Zreplacement);
-    return NULL;
-}
-
-static PyObject *
-make_freplacement(PyObject *object)
-{
-    char freplacement[64];
-    if (PyTime_Check(object))
-        sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
-    else if (PyDateTime_Check(object))
-        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
-    else
-        sprintf(freplacement, "%06d", 0);
-
-    return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
-}
-
-/* I sure don't want to reproduce the strftime code from the time module,
- * so this imports the module and calls it.  All the hair is due to
- * giving special meanings to the %z, %Z and %f format codes via a
- * preprocessing step on the format string.
- * tzinfoarg is the argument to pass to the object's tzinfo method, if
- * needed.
- */
-static PyObject *
-wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
-              PyObject *tzinfoarg)
-{
-    PyObject *result = NULL;            /* guilty until proved innocent */
-
-    PyObject *zreplacement = NULL;      /* py string, replacement for %z */
-    PyObject *Zreplacement = NULL;      /* py string, replacement for %Z */
-    PyObject *freplacement = NULL;      /* py string, replacement for %f */
-
-    const char *pin;            /* pointer to next char in input format */
-    Py_ssize_t flen;            /* length of input format */
-    char ch;                    /* next char in input format */
-
-    PyObject *newfmt = NULL;            /* py string, the output format */
-    char *pnew;         /* pointer to available byte in output format */
-    size_t totalnew;            /* number bytes total in output format buffer,
-                               exclusive of trailing \0 */
-    size_t usednew;     /* number bytes used so far in output format buffer */
-
-    const char *ptoappend;      /* ptr to string to append to output buffer */
-    Py_ssize_t ntoappend;       /* # of bytes to append to output buffer */
-
-    assert(object && format && timetuple);
-    assert(PyUnicode_Check(format));
-    /* Convert the input format to a C string and size */
-    pin = _PyUnicode_AsStringAndSize(format, &flen);
-    if (!pin)
-        return NULL;
-
-    /* Give up if the year is before 1900.
-     * Python strftime() plays games with the year, and different
-     * games depending on whether envar PYTHON2K is set.  This makes
-     * years before 1900 a nightmare, even if the platform strftime
-     * supports them (and not all do).
-     * We could get a lot farther here by avoiding Python's strftime
-     * wrapper and calling the C strftime() directly, but that isn't
-     * an option in the Python implementation of this module.
-     */
-    {
-        long year;
-        PyObject *pyyear = PySequence_GetItem(timetuple, 0);
-        if (pyyear == NULL) return NULL;
-        assert(PyLong_Check(pyyear));
-        year = PyLong_AsLong(pyyear);
-        Py_DECREF(pyyear);
-        if (year < 1900) {
-            PyErr_Format(PyExc_ValueError, "year=%ld is before "
-                         "1900; the datetime strftime() "
-                         "methods require year >= 1900",
-                         year);
-            return NULL;
-        }
-    }
-
-    /* Scan the input format, looking for %z/%Z/%f escapes, building
-     * a new format.  Since computing the replacements for those codes
-     * is expensive, don't unless they're actually used.
-     */
-    if (flen > INT_MAX - 1) {
-        PyErr_NoMemory();
-        goto Done;
-    }
-
-    totalnew = flen + 1;        /* realistic if no %z/%Z */
-    newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
-    if (newfmt == NULL) goto Done;
-    pnew = PyBytes_AsString(newfmt);
-    usednew = 0;
-
-    while ((ch = *pin++) != '\0') {
-        if (ch != '%') {
-            ptoappend = pin - 1;
-            ntoappend = 1;
-        }
-        else if ((ch = *pin++) == '\0') {
-            /* There's a lone trailing %; doesn't make sense. */
-            PyErr_SetString(PyExc_ValueError, "strftime format "
-                            "ends with raw %");
-            goto Done;
-        }
-        /* A % has been seen and ch is the character after it. */
-        else if (ch == 'z') {
-            if (zreplacement == NULL) {
-                /* format utcoffset */
-                char buf[100];
-                PyObject *tzinfo = get_tzinfo_member(object);
-                zreplacement = PyBytes_FromStringAndSize("", 0);
-                if (zreplacement == NULL) goto Done;
-                if (tzinfo != Py_None && tzinfo != NULL) {
-                    assert(tzinfoarg != NULL);
-                    if (format_utcoffset(buf,
-                                         sizeof(buf),
-                                         "",
-                                         tzinfo,
-                                         tzinfoarg) < 0)
-                        goto Done;
-                    Py_DECREF(zreplacement);
-                    zreplacement =
-                      PyBytes_FromStringAndSize(buf,
-                                               strlen(buf));
-                    if (zreplacement == NULL)
-                        goto Done;
-                }
-            }
-            assert(zreplacement != NULL);
-            ptoappend = PyBytes_AS_STRING(zreplacement);
-            ntoappend = PyBytes_GET_SIZE(zreplacement);
-        }
-        else if (ch == 'Z') {
-            /* format tzname */
-            if (Zreplacement == NULL) {
-                Zreplacement = make_Zreplacement(object,
-                                                 tzinfoarg);
-                if (Zreplacement == NULL)
-                    goto Done;
-            }
-            assert(Zreplacement != NULL);
-            assert(PyUnicode_Check(Zreplacement));
-            ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
-                                                  &ntoappend);
-            ntoappend = Py_SIZE(Zreplacement);
-        }
-        else if (ch == 'f') {
-            /* format microseconds */
-            if (freplacement == NULL) {
-                freplacement = make_freplacement(object);
-                if (freplacement == NULL)
-                    goto Done;
-            }
-            assert(freplacement != NULL);
-            assert(PyBytes_Check(freplacement));
-            ptoappend = PyBytes_AS_STRING(freplacement);
-            ntoappend = PyBytes_GET_SIZE(freplacement);
-        }
-        else {
-            /* percent followed by neither z nor Z */
-            ptoappend = pin - 2;
-            ntoappend = 2;
-        }
-
-        /* Append the ntoappend chars starting at ptoappend to
-         * the new format.
-         */
-        if (ntoappend == 0)
-            continue;
-        assert(ptoappend != NULL);
-        assert(ntoappend > 0);
-        while (usednew + ntoappend > totalnew) {
-            size_t bigger = totalnew << 1;
-            if ((bigger >> 1) != totalnew) { /* overflow */
-                PyErr_NoMemory();
-                goto Done;
-            }
-            if (_PyBytes_Resize(&newfmt, bigger) < 0)
-                goto Done;
-            totalnew = bigger;
-            pnew = PyBytes_AsString(newfmt) + usednew;
-        }
-        memcpy(pnew, ptoappend, ntoappend);
-        pnew += ntoappend;
-        usednew += ntoappend;
-        assert(usednew <= totalnew);
-    }  /* end while() */
-
-    if (_PyBytes_Resize(&newfmt, usednew) < 0)
-        goto Done;
-    {
-        PyObject *format;
-        PyObject *time = PyImport_ImportModuleNoBlock("time");
-        if (time == NULL)
-            goto Done;
-        format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
-        if (format != NULL) {
-            result = PyObject_CallMethod(time, "strftime", "OO",
-                                         format, timetuple);
-            Py_DECREF(format);
-        }
-        Py_DECREF(time);
-    }
- Done:
-    Py_XDECREF(freplacement);
-    Py_XDECREF(zreplacement);
-    Py_XDECREF(Zreplacement);
-    Py_XDECREF(newfmt);
-    return result;
-}
-
-/* ---------------------------------------------------------------------------
- * Wrap functions from the time module.  These aren't directly available
- * from C.  Perhaps they should be.
- */
-
-/* Call time.time() and return its result (a Python float). */
-static PyObject *
-time_time(void)
-{
-    PyObject *result = NULL;
-    PyObject *time = PyImport_ImportModuleNoBlock("time");
-
-    if (time != NULL) {
-        result = PyObject_CallMethod(time, "time", "()");
-        Py_DECREF(time);
-    }
-    return result;
-}
-
-/* Build a time.struct_time.  The weekday and day number are automatically
- * computed from the y,m,d args.
- */
-static PyObject *
-build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
-{
-    PyObject *time;
-    PyObject *result = NULL;
-
-    time = PyImport_ImportModuleNoBlock("time");
-    if (time != NULL) {
-        result = PyObject_CallMethod(time, "struct_time",
-                                     "((iiiiiiiii))",
-                                     y, m, d,
-                                     hh, mm, ss,
-                                     weekday(y, m, d),
-                                     days_before_month(y, m) + d,
-                                     dstflag);
-        Py_DECREF(time);
-    }
-    return result;
-}
-
-/* ---------------------------------------------------------------------------
- * Miscellaneous helpers.
- */
-
-/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
- * The comparisons here all most naturally compute a cmp()-like result.
- * This little helper turns that into a bool result for rich comparisons.
- */
-static PyObject *
-diff_to_bool(int diff, int op)
-{
-    PyObject *result;
-    int istrue;
-
-    switch (op) {
-        case Py_EQ: istrue = diff == 0; break;
-        case Py_NE: istrue = diff != 0; break;
-        case Py_LE: istrue = diff <= 0; break;
-        case Py_GE: istrue = diff >= 0; break;
-        case Py_LT: istrue = diff < 0; break;
-        case Py_GT: istrue = diff > 0; break;
-        default:
-            assert(! "op unknown");
-            istrue = 0; /* To shut up compiler */
-    }
-    result = istrue ? Py_True : Py_False;
-    Py_INCREF(result);
-    return result;
-}
-
-/* Raises a "can't compare" TypeError and returns NULL. */
-static PyObject *
-cmperror(PyObject *a, PyObject *b)
-{
-    PyErr_Format(PyExc_TypeError,
-                 "can't compare %s to %s",
-                 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
-    return NULL;
-}
-
-/* ---------------------------------------------------------------------------
- * Cached Python objects; these are set by the module init function.
- */
-
-/* Conversion factors. */
-static PyObject *us_per_us = NULL;      /* 1 */
-static PyObject *us_per_ms = NULL;      /* 1000 */
-static PyObject *us_per_second = NULL;  /* 1000000 */
-static PyObject *us_per_minute = NULL;  /* 1e6 * 60 as Python int */
-static PyObject *us_per_hour = NULL;    /* 1e6 * 3600 as Python long */
-static PyObject *us_per_day = NULL;     /* 1e6 * 3600 * 24 as Python long */
-static PyObject *us_per_week = NULL;    /* 1e6*3600*24*7 as Python long */
-static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
-
-/* ---------------------------------------------------------------------------
- * Class implementations.
- */
-
-/*
- * PyDateTime_Delta implementation.
- */
-
-/* Convert a timedelta to a number of us,
- *      (24*3600*self.days + self.seconds)*1000000 + self.microseconds
- * as a Python int or long.
- * Doing mixed-radix arithmetic by hand instead is excruciating in C,
- * due to ubiquitous overflow possibilities.
- */
-static PyObject *
-delta_to_microseconds(PyDateTime_Delta *self)
-{
-    PyObject *x1 = NULL;
-    PyObject *x2 = NULL;
-    PyObject *x3 = NULL;
-    PyObject *result = NULL;
-
-    x1 = PyLong_FromLong(GET_TD_DAYS(self));
-    if (x1 == NULL)
-        goto Done;
-    x2 = PyNumber_Multiply(x1, seconds_per_day);        /* days in seconds */
-    if (x2 == NULL)
-        goto Done;
-    Py_DECREF(x1);
-    x1 = NULL;
-
-    /* x2 has days in seconds */
-    x1 = PyLong_FromLong(GET_TD_SECONDS(self));         /* seconds */
-    if (x1 == NULL)
-        goto Done;
-    x3 = PyNumber_Add(x1, x2);          /* days and seconds in seconds */
-    if (x3 == NULL)
-        goto Done;
-    Py_DECREF(x1);
-    Py_DECREF(x2);
-    x1 = x2 = NULL;
-
-    /* x3 has days+seconds in seconds */
-    x1 = PyNumber_Multiply(x3, us_per_second);          /* us */
-    if (x1 == NULL)
-        goto Done;
-    Py_DECREF(x3);
-    x3 = NULL;
-
-    /* x1 has days+seconds in us */
-    x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
-    if (x2 == NULL)
-        goto Done;
-    result = PyNumber_Add(x1, x2);
-
-Done:
-    Py_XDECREF(x1);
-    Py_XDECREF(x2);
-    Py_XDECREF(x3);
-    return result;
-}
-
-/* Convert a number of us (as a Python int or long) to a timedelta.
- */
-static PyObject *
-microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
-{
-    int us;
-    int s;
-    int d;
-    long temp;
-
-    PyObject *tuple = NULL;
-    PyObject *num = NULL;
-    PyObject *result = NULL;
-
-    tuple = PyNumber_Divmod(pyus, us_per_second);
-    if (tuple == NULL)
-        goto Done;
-
-    num = PyTuple_GetItem(tuple, 1);            /* us */
-    if (num == NULL)
-        goto Done;
-    temp = PyLong_AsLong(num);
-    num = NULL;
-    if (temp == -1 && PyErr_Occurred())
-        goto Done;
-    assert(0 <= temp && temp < 1000000);
-    us = (int)temp;
-    if (us < 0) {
-        /* The divisor was positive, so this must be an error. */
-        assert(PyErr_Occurred());
-        goto Done;
-    }
-
-    num = PyTuple_GetItem(tuple, 0);            /* leftover seconds */
-    if (num == NULL)
-        goto Done;
-    Py_INCREF(num);
-    Py_DECREF(tuple);
-
-    tuple = PyNumber_Divmod(num, seconds_per_day);
-    if (tuple == NULL)
-        goto Done;
-    Py_DECREF(num);
-
-    num = PyTuple_GetItem(tuple, 1);            /* seconds */
-    if (num == NULL)
-        goto Done;
-    temp = PyLong_AsLong(num);
-    num = NULL;
-    if (temp == -1 && PyErr_Occurred())
-        goto Done;
-    assert(0 <= temp && temp < 24*3600);
-    s = (int)temp;
-
-    if (s < 0) {
-        /* The divisor was positive, so this must be an error. */
-        assert(PyErr_Occurred());
-        goto Done;
-    }
-
-    num = PyTuple_GetItem(tuple, 0);            /* leftover days */
-    if (num == NULL)
-        goto Done;
-    Py_INCREF(num);
-    temp = PyLong_AsLong(num);
-    if (temp == -1 && PyErr_Occurred())
-        goto Done;
-    d = (int)temp;
-    if ((long)d != temp) {
-        PyErr_SetString(PyExc_OverflowError, "normalized days too "
-                        "large to fit in a C int");
-        goto Done;
-    }
-    result = new_delta_ex(d, s, us, 0, type);
-
-Done:
-    Py_XDECREF(tuple);
-    Py_XDECREF(num);
-    return result;
-}
-
-#define microseconds_to_delta(pymicros) \
-    microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
-
-static PyObject *
-multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
-{
-    PyObject *pyus_in;
-    PyObject *pyus_out;
-    PyObject *result;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-
-    pyus_out = PyNumber_Multiply(pyus_in, intobj);
-    Py_DECREF(pyus_in);
-    if (pyus_out == NULL)
-        return NULL;
-
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
-    return result;
-}
-
-static PyObject *
-multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
-{
-    PyObject *result = NULL;
-    PyObject *pyus_in = NULL, *temp, *pyus_out;
-    PyObject *ratio = NULL;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-    ratio = PyObject_CallMethod(floatobj, "as_integer_ratio", NULL);
-    if (ratio == NULL)
-        goto error;
-    temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
-    Py_DECREF(pyus_in);
-    pyus_in = NULL;
-    if (temp == NULL)
-        goto error;
-    pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
-    Py_DECREF(temp);
-    if (pyus_out == NULL)
-        goto error;
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
- error:
-    Py_XDECREF(pyus_in);
-    Py_XDECREF(ratio);
-
-    return result;
-}
-
-static PyObject *
-divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
-{
-    PyObject *pyus_in;
-    PyObject *pyus_out;
-    PyObject *result;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-
-    pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
-    Py_DECREF(pyus_in);
-    if (pyus_out == NULL)
-        return NULL;
-
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
-    return result;
-}
-
-static PyObject *
-divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *result;
-
-    pyus_left = delta_to_microseconds(left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds(right);
-    if (pyus_right == NULL)     {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    result = PyNumber_FloorDivide(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    return result;
-}
-
-static PyObject *
-truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *result;
-
-    pyus_left = delta_to_microseconds(left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds(right);
-    if (pyus_right == NULL)     {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    result = PyNumber_TrueDivide(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    return result;
-}
-
-static PyObject *
-truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
-{
-    PyObject *result = NULL;
-    PyObject *pyus_in = NULL, *temp, *pyus_out;
-    PyObject *ratio = NULL;
-
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-    ratio = PyObject_CallMethod(f, "as_integer_ratio", NULL);
-    if (ratio == NULL)
-        goto error;
-    temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
-    Py_DECREF(pyus_in);
-    pyus_in = NULL;
-    if (temp == NULL)
-        goto error;
-    pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
-    Py_DECREF(temp);
-    if (pyus_out == NULL)
-        goto error;
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
- error:
-    Py_XDECREF(pyus_in);
-    Py_XDECREF(ratio);
-
-    return result;
-}
-
-static PyObject *
-truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
-{
-    PyObject *result;
-    PyObject *pyus_in, *pyus_out;
-    pyus_in = delta_to_microseconds(delta);
-    if (pyus_in == NULL)
-        return NULL;
-    pyus_out = divide_nearest(pyus_in, i);
-    Py_DECREF(pyus_in);
-    if (pyus_out == NULL)
-        return NULL;
-    result = microseconds_to_delta(pyus_out);
-    Py_DECREF(pyus_out);
-
-    return result;
-}
-
-static PyObject *
-delta_add(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left) && PyDelta_Check(right)) {
-        /* delta + delta */
-        /* The C-level additions can't overflow because of the
-         * invariant bounds.
-         */
-        int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
-        int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
-        int microseconds = GET_TD_MICROSECONDS(left) +
-                           GET_TD_MICROSECONDS(right);
-        result = new_delta(days, seconds, microseconds, 1);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_negative(PyDateTime_Delta *self)
-{
-    return new_delta(-GET_TD_DAYS(self),
-                     -GET_TD_SECONDS(self),
-                     -GET_TD_MICROSECONDS(self),
-                     1);
-}
-
-static PyObject *
-delta_positive(PyDateTime_Delta *self)
-{
-    /* Could optimize this (by returning self) if this isn't a
-     * subclass -- but who uses unary + ?  Approximately nobody.
-     */
-    return new_delta(GET_TD_DAYS(self),
-                     GET_TD_SECONDS(self),
-                     GET_TD_MICROSECONDS(self),
-                     0);
-}
-
-static PyObject *
-delta_abs(PyDateTime_Delta *self)
-{
-    PyObject *result;
-
-    assert(GET_TD_MICROSECONDS(self) >= 0);
-    assert(GET_TD_SECONDS(self) >= 0);
-
-    if (GET_TD_DAYS(self) < 0)
-        result = delta_negative(self);
-    else
-        result = delta_positive(self);
-
-    return result;
-}
-
-static PyObject *
-delta_subtract(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left) && PyDelta_Check(right)) {
-        /* delta - delta */
-        PyObject *minus_right = PyNumber_Negative(right);
-        if (minus_right) {
-            result = delta_add(left, minus_right);
-            Py_DECREF(minus_right);
-        }
-        else
-            result = NULL;
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_richcompare(PyObject *self, PyObject *other, int op)
-{
-    if (PyDelta_Check(other)) {
-        int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
-        if (diff == 0) {
-            diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
-            if (diff == 0)
-                diff = GET_TD_MICROSECONDS(self) -
-                       GET_TD_MICROSECONDS(other);
-        }
-        return diff_to_bool(diff, op);
-    }
-    else {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-}
-
-static PyObject *delta_getstate(PyDateTime_Delta *self);
-
-static long
-delta_hash(PyDateTime_Delta *self)
-{
-    if (self->hashcode == -1) {
-        PyObject *temp = delta_getstate(self);
-        if (temp != NULL) {
-            self->hashcode = PyObject_Hash(temp);
-            Py_DECREF(temp);
-        }
-    }
-    return self->hashcode;
-}
-
-static PyObject *
-delta_multiply(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left)) {
-        /* delta * ??? */
-        if (PyLong_Check(right))
-            result = multiply_int_timedelta(right,
-                            (PyDateTime_Delta *) left);
-        else if (PyFloat_Check(right))
-            result = multiply_float_timedelta(right,
-                            (PyDateTime_Delta *) left);
-    }
-    else if (PyLong_Check(left))
-        result = multiply_int_timedelta(left,
-                        (PyDateTime_Delta *) right);
-    else if (PyFloat_Check(left))
-        result = multiply_float_timedelta(left,
-                        (PyDateTime_Delta *) right);
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_divide(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left)) {
-        /* delta * ??? */
-        if (PyLong_Check(right))
-            result = divide_timedelta_int(
-                            (PyDateTime_Delta *)left,
-                            right);
-        else if (PyDelta_Check(right))
-            result = divide_timedelta_timedelta(
-                            (PyDateTime_Delta *)left,
-                            (PyDateTime_Delta *)right);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_truedivide(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDelta_Check(left)) {
-        if (PyDelta_Check(right))
-            result = truedivide_timedelta_timedelta(
-                            (PyDateTime_Delta *)left,
-                            (PyDateTime_Delta *)right);
-        else if (PyFloat_Check(right))
-            result = truedivide_timedelta_float(
-                            (PyDateTime_Delta *)left, right);
-        else if (PyLong_Check(right))
-            result = truedivide_timedelta_int(
-                            (PyDateTime_Delta *)left, right);
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-static PyObject *
-delta_remainder(PyObject *left, PyObject *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *pyus_remainder;
-    PyObject *remainder;
-
-    if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-
-    pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
-    if (pyus_right == NULL) {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    if (pyus_remainder == NULL)
-        return NULL;
-
-    remainder = microseconds_to_delta(pyus_remainder);
-    Py_DECREF(pyus_remainder);
-    if (remainder == NULL)
-        return NULL;
-
-    return remainder;
-}
-
-static PyObject *
-delta_divmod(PyObject *left, PyObject *right)
-{
-    PyObject *pyus_left;
-    PyObject *pyus_right;
-    PyObject *divmod;
-    PyObject *delta;
-    PyObject *result;
-
-    if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-
-    pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
-    if (pyus_left == NULL)
-        return NULL;
-
-    pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
-    if (pyus_right == NULL) {
-        Py_DECREF(pyus_left);
-        return NULL;
-    }
-
-    divmod = PyNumber_Divmod(pyus_left, pyus_right);
-    Py_DECREF(pyus_left);
-    Py_DECREF(pyus_right);
-    if (divmod == NULL)
-        return NULL;
-
-    assert(PyTuple_Size(divmod) == 2);
-    delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
-    if (delta == NULL) {
-        Py_DECREF(divmod);
-        return NULL;
-    }
-    result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
-    Py_DECREF(delta);
-    Py_DECREF(divmod);
-    return result;
-}
-
-/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
- * timedelta constructor.  sofar is the # of microseconds accounted for
- * so far, and there are factor microseconds per current unit, the number
- * of which is given by num.  num * factor is added to sofar in a
- * numerically careful way, and that's the result.  Any fractional
- * microseconds left over (this can happen if num is a float type) are
- * added into *leftover.
- * Note that there are many ways this can give an error (NULL) return.
- */
-static PyObject *
-accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
-      double *leftover)
-{
-    PyObject *prod;
-    PyObject *sum;
-
-    assert(num != NULL);
-
-    if (PyLong_Check(num)) {
-        prod = PyNumber_Multiply(num, factor);
-        if (prod == NULL)
-            return NULL;
-        sum = PyNumber_Add(sofar, prod);
-        Py_DECREF(prod);
-        return sum;
-    }
-
-    if (PyFloat_Check(num)) {
-        double dnum;
-        double fracpart;
-        double intpart;
-        PyObject *x;
-        PyObject *y;
-
-        /* The Plan:  decompose num into an integer part and a
-         * fractional part, num = intpart + fracpart.
-         * Then num * factor ==
-         *      intpart * factor + fracpart * factor
-         * and the LHS can be computed exactly in long arithmetic.
-         * The RHS is again broken into an int part and frac part.
-         * and the frac part is added into *leftover.
-         */
-        dnum = PyFloat_AsDouble(num);
-        if (dnum == -1.0 && PyErr_Occurred())
-            return NULL;
-        fracpart = modf(dnum, &intpart);
-        x = PyLong_FromDouble(intpart);
-        if (x == NULL)
-            return NULL;
-
-        prod = PyNumber_Multiply(x, factor);
-        Py_DECREF(x);
-        if (prod == NULL)
-            return NULL;
-
-        sum = PyNumber_Add(sofar, prod);
-        Py_DECREF(prod);
-        if (sum == NULL)
-            return NULL;
-
-        if (fracpart == 0.0)
-            return sum;
-        /* So far we've lost no information.  Dealing with the
-         * fractional part requires float arithmetic, and may
-         * lose a little info.
-         */
-        assert(PyLong_Check(factor));
-        dnum = PyLong_AsDouble(factor);
-
-        dnum *= fracpart;
-        fracpart = modf(dnum, &intpart);
-        x = PyLong_FromDouble(intpart);
-        if (x == NULL) {
-            Py_DECREF(sum);
-            return NULL;
-        }
-
-        y = PyNumber_Add(sum, x);
-        Py_DECREF(sum);
-        Py_DECREF(x);
-        *leftover += fracpart;
-        return y;
-    }
-
-    PyErr_Format(PyExc_TypeError,
-                 "unsupported type for timedelta %s component: %s",
-                 tag, Py_TYPE(num)->tp_name);
-    return NULL;
-}
-
-static PyObject *
-delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-
-    /* Argument objects. */
-    PyObject *day = NULL;
-    PyObject *second = NULL;
-    PyObject *us = NULL;
-    PyObject *ms = NULL;
-    PyObject *minute = NULL;
-    PyObject *hour = NULL;
-    PyObject *week = NULL;
-
-    PyObject *x = NULL;         /* running sum of microseconds */
-    PyObject *y = NULL;         /* temp sum of microseconds */
-    double leftover_us = 0.0;
-
-    static char *keywords[] = {
-        "days", "seconds", "microseconds", "milliseconds",
-        "minutes", "hours", "weeks", NULL
-    };
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
-                                    keywords,
-                                    &day, &second, &us,
-                                    &ms, &minute, &hour, &week) == 0)
-        goto Done;
-
-    x = PyLong_FromLong(0);
-    if (x == NULL)
-        goto Done;
-
-#define CLEANUP         \
-    Py_DECREF(x);       \
-    x = y;              \
-    if (x == NULL)      \
-        goto Done
-
-    if (us) {
-        y = accum("microseconds", x, us, us_per_us, &leftover_us);
-        CLEANUP;
-    }
-    if (ms) {
-        y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
-        CLEANUP;
-    }
-    if (second) {
-        y = accum("seconds", x, second, us_per_second, &leftover_us);
-        CLEANUP;
-    }
-    if (minute) {
-        y = accum("minutes", x, minute, us_per_minute, &leftover_us);
-        CLEANUP;
-    }
-    if (hour) {
-        y = accum("hours", x, hour, us_per_hour, &leftover_us);
-        CLEANUP;
-    }
-    if (day) {
-        y = accum("days", x, day, us_per_day, &leftover_us);
-        CLEANUP;
-    }
-    if (week) {
-        y = accum("weeks", x, week, us_per_week, &leftover_us);
-        CLEANUP;
-    }
-    if (leftover_us) {
-        /* Round to nearest whole # of us, and add into x. */
-        PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
-        if (temp == NULL) {
-            Py_DECREF(x);
-            goto Done;
-        }
-        y = PyNumber_Add(x, temp);
-        Py_DECREF(temp);
-        CLEANUP;
-    }
-
-    self = microseconds_to_delta_ex(x, type);
-    Py_DECREF(x);
-Done:
-    return self;
-
-#undef CLEANUP
-}
-
-static int
-delta_bool(PyDateTime_Delta *self)
-{
-    return (GET_TD_DAYS(self) != 0
-        || GET_TD_SECONDS(self) != 0
-        || GET_TD_MICROSECONDS(self) != 0);
-}
-
-static PyObject *
-delta_repr(PyDateTime_Delta *self)
-{
-    if (GET_TD_MICROSECONDS(self) != 0)
-        return PyUnicode_FromFormat("%s(%d, %d, %d)",
-                                    Py_TYPE(self)->tp_name,
-                                    GET_TD_DAYS(self),
-                                    GET_TD_SECONDS(self),
-                                    GET_TD_MICROSECONDS(self));
-    if (GET_TD_SECONDS(self) != 0)
-        return PyUnicode_FromFormat("%s(%d, %d)",
-                                    Py_TYPE(self)->tp_name,
-                                    GET_TD_DAYS(self),
-                                    GET_TD_SECONDS(self));
-
-    return PyUnicode_FromFormat("%s(%d)",
-                                Py_TYPE(self)->tp_name,
-                                GET_TD_DAYS(self));
-}
-
-static PyObject *
-delta_str(PyDateTime_Delta *self)
-{
-    int us = GET_TD_MICROSECONDS(self);
-    int seconds = GET_TD_SECONDS(self);
-    int minutes = divmod(seconds, 60, &seconds);
-    int hours = divmod(minutes, 60, &minutes);
-    int days = GET_TD_DAYS(self);
-
-    if (days) {
-        if (us)
-            return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
-                                        days, (days == 1 || days == -1) ? "" : "s",
-                                        hours, minutes, seconds, us);
-        else
-            return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
-                                        days, (days == 1 || days == -1) ? "" : "s",
-                                        hours, minutes, seconds);
-    } else {
-        if (us)
-            return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
-                                        hours, minutes, seconds, us);
-        else
-            return PyUnicode_FromFormat("%d:%02d:%02d",
-                                        hours, minutes, seconds);
-    }
-
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* __getstate__ isn't exposed */
-static PyObject *
-delta_getstate(PyDateTime_Delta *self)
-{
-    return Py_BuildValue("iii", GET_TD_DAYS(self),
-                                GET_TD_SECONDS(self),
-                                GET_TD_MICROSECONDS(self));
-}
-
-static PyObject *
-delta_total_seconds(PyObject *self)
-{
-    PyObject *total_seconds;
-    PyObject *total_microseconds;
-    PyObject *one_million;
-
-    total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
-    if (total_microseconds == NULL)
-        return NULL;
-
-    one_million = PyLong_FromLong(1000000L);
-    if (one_million == NULL) {
-        Py_DECREF(total_microseconds);
-        return NULL;
-    }
-
-    total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
-
-    Py_DECREF(total_microseconds);
-    Py_DECREF(one_million);
-    return total_seconds;
-}
-
-static PyObject *
-delta_reduce(PyDateTime_Delta* self)
-{
-    return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
-}
-
-#define OFFSET(field)  offsetof(PyDateTime_Delta, field)
-
-static PyMemberDef delta_members[] = {
-
-    {"days",         T_INT, OFFSET(days),         READONLY,
-     PyDoc_STR("Number of days.")},
-
-    {"seconds",      T_INT, OFFSET(seconds),      READONLY,
-     PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
-
-    {"microseconds", T_INT, OFFSET(microseconds), READONLY,
-     PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
-    {NULL}
-};
-
-static PyMethodDef delta_methods[] = {
-    {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
-     PyDoc_STR("Total seconds in the duration.")},
-
-    {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL},
-};
-
-static char delta_doc[] =
-PyDoc_STR("Difference between two datetime values.");
-
-static PyNumberMethods delta_as_number = {
-    delta_add,                                  /* nb_add */
-    delta_subtract,                             /* nb_subtract */
-    delta_multiply,                             /* nb_multiply */
-    delta_remainder,                            /* nb_remainder */
-    delta_divmod,                               /* nb_divmod */
-    0,                                          /* nb_power */
-    (unaryfunc)delta_negative,                  /* nb_negative */
-    (unaryfunc)delta_positive,                  /* nb_positive */
-    (unaryfunc)delta_abs,                       /* nb_absolute */
-    (inquiry)delta_bool,                        /* nb_bool */
-    0,                                          /*nb_invert*/
-    0,                                          /*nb_lshift*/
-    0,                                          /*nb_rshift*/
-    0,                                          /*nb_and*/
-    0,                                          /*nb_xor*/
-    0,                                          /*nb_or*/
-    0,                                          /*nb_int*/
-    0,                                          /*nb_reserved*/
-    0,                                          /*nb_float*/
-    0,                                          /*nb_inplace_add*/
-    0,                                          /*nb_inplace_subtract*/
-    0,                                          /*nb_inplace_multiply*/
-    0,                                          /*nb_inplace_remainder*/
-    0,                                          /*nb_inplace_power*/
-    0,                                          /*nb_inplace_lshift*/
-    0,                                          /*nb_inplace_rshift*/
-    0,                                          /*nb_inplace_and*/
-    0,                                          /*nb_inplace_xor*/
-    0,                                          /*nb_inplace_or*/
-    delta_divide,                               /* nb_floor_divide */
-    delta_truedivide,                           /* nb_true_divide */
-    0,                                          /* nb_inplace_floor_divide */
-    0,                                          /* nb_inplace_true_divide */
-};
-
-static PyTypeObject PyDateTime_DeltaType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.timedelta",                               /* tp_name */
-    sizeof(PyDateTime_Delta),                           /* tp_basicsize */
-    0,                                                  /* tp_itemsize */
-    0,                                                  /* tp_dealloc */
-    0,                                                  /* tp_print */
-    0,                                                  /* tp_getattr */
-    0,                                                  /* tp_setattr */
-    0,                                                  /* tp_reserved */
-    (reprfunc)delta_repr,                               /* tp_repr */
-    &delta_as_number,                                   /* tp_as_number */
-    0,                                                  /* tp_as_sequence */
-    0,                                                  /* tp_as_mapping */
-    (hashfunc)delta_hash,                               /* tp_hash */
-    0,                                                  /* tp_call */
-    (reprfunc)delta_str,                                /* tp_str */
-    PyObject_GenericGetAttr,                            /* tp_getattro */
-    0,                                                  /* tp_setattro */
-    0,                                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,           /* tp_flags */
-    delta_doc,                                          /* tp_doc */
-    0,                                                  /* tp_traverse */
-    0,                                                  /* tp_clear */
-    delta_richcompare,                                  /* tp_richcompare */
-    0,                                                  /* tp_weaklistoffset */
-    0,                                                  /* tp_iter */
-    0,                                                  /* tp_iternext */
-    delta_methods,                                      /* tp_methods */
-    delta_members,                                      /* tp_members */
-    0,                                                  /* tp_getset */
-    0,                                                  /* tp_base */
-    0,                                                  /* tp_dict */
-    0,                                                  /* tp_descr_get */
-    0,                                                  /* tp_descr_set */
-    0,                                                  /* tp_dictoffset */
-    0,                                                  /* tp_init */
-    0,                                                  /* tp_alloc */
-    delta_new,                                          /* tp_new */
-    0,                                                  /* tp_free */
-};
-
-/*
- * PyDateTime_Date implementation.
- */
-
-/* Accessor properties. */
-
-static PyObject *
-date_year(PyDateTime_Date *self, void *unused)
-{
-    return PyLong_FromLong(GET_YEAR(self));
-}
-
-static PyObject *
-date_month(PyDateTime_Date *self, void *unused)
-{
-    return PyLong_FromLong(GET_MONTH(self));
-}
-
-static PyObject *
-date_day(PyDateTime_Date *self, void *unused)
-{
-    return PyLong_FromLong(GET_DAY(self));
-}
-
-static PyGetSetDef date_getset[] = {
-    {"year",        (getter)date_year},
-    {"month",       (getter)date_month},
-    {"day",         (getter)date_day},
-    {NULL}
-};
-
-/* Constructors. */
-
-static char *date_kws[] = {"year", "month", "day", NULL};
-
-static PyObject *
-date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-    PyObject *state;
-    int year;
-    int month;
-    int day;
-
-    /* Check for invocation from pickle with __getstate__ state */
-    if (PyTuple_GET_SIZE(args) == 1 &&
-        PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-        PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
-        MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
-    {
-        PyDateTime_Date *me;
-
-        me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
-        if (me != NULL) {
-            char *pdata = PyBytes_AS_STRING(state);
-            memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
-            me->hashcode = -1;
-        }
-        return (PyObject *)me;
-    }
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
-                                    &year, &month, &day)) {
-        if (check_date_args(year, month, day) < 0)
-            return NULL;
-        self = new_date_ex(year, month, day, type);
-    }
-    return self;
-}
-
-/* Return new date from localtime(t). */
-static PyObject *
-date_local_from_time_t(PyObject *cls, double ts)
-{
-    struct tm *tm;
-    time_t t;
-    PyObject *result = NULL;
-
-    t = _PyTime_DoubleToTimet(ts);
-    if (t == (time_t)-1 && PyErr_Occurred())
-        return NULL;
-    tm = localtime(&t);
-    if (tm)
-        result = PyObject_CallFunction(cls, "iii",
-                                       tm->tm_year + 1900,
-                                       tm->tm_mon + 1,
-                                       tm->tm_mday);
-    else
-        PyErr_SetString(PyExc_ValueError,
-                        "timestamp out of range for "
-                        "platform localtime() function");
-    return result;
-}
-
-/* Return new date from current time.
- * We say this is equivalent to fromtimestamp(time.time()), and the
- * only way to be sure of that is to *call* time.time().  That's not
- * generally the same as calling C's time.
- */
-static PyObject *
-date_today(PyObject *cls, PyObject *dummy)
-{
-    PyObject *time;
-    PyObject *result;
-
-    time = time_time();
-    if (time == NULL)
-        return NULL;
-
-    /* Note well:  today() is a class method, so this may not call
-     * date.fromtimestamp.  For example, it may call
-     * datetime.fromtimestamp.  That's why we need all the accuracy
-     * time.time() delivers; if someone were gonzo about optimization,
-     * date.today() could get away with plain C time().
-     */
-    result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
-    Py_DECREF(time);
-    return result;
-}
-
-/* Return new date from given timestamp (Python timestamp -- a double). */
-static PyObject *
-date_fromtimestamp(PyObject *cls, PyObject *args)
-{
-    double timestamp;
-    PyObject *result = NULL;
-
-    if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
-        result = date_local_from_time_t(cls, timestamp);
-    return result;
-}
-
-/* Return new date from proleptic Gregorian ordinal.  Raises ValueError if
- * the ordinal is out of range.
- */
-static PyObject *
-date_fromordinal(PyObject *cls, PyObject *args)
-{
-    PyObject *result = NULL;
-    int ordinal;
-
-    if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
-        int year;
-        int month;
-        int day;
-
-        if (ordinal < 1)
-            PyErr_SetString(PyExc_ValueError, "ordinal must be "
-                                              ">= 1");
-        else {
-            ord_to_ymd(ordinal, &year, &month, &day);
-            result = PyObject_CallFunction(cls, "iii",
-                                           year, month, day);
-        }
-    }
-    return result;
-}
-
-/*
- * Date arithmetic.
- */
-
-/* date + timedelta -> date.  If arg negate is true, subtract the timedelta
- * instead.
- */
-static PyObject *
-add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
-{
-    PyObject *result = NULL;
-    int year = GET_YEAR(date);
-    int month = GET_MONTH(date);
-    int deltadays = GET_TD_DAYS(delta);
-    /* C-level overflow is impossible because |deltadays| < 1e9. */
-    int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
-
-    if (normalize_date(&year, &month, &day) >= 0)
-        result = new_date(year, month, day);
-    return result;
-}
-
-static PyObject *
-date_add(PyObject *left, PyObject *right)
-{
-    if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-    if (PyDate_Check(left)) {
-        /* date + ??? */
-        if (PyDelta_Check(right))
-            /* date + delta */
-            return add_date_timedelta((PyDateTime_Date *) left,
-                                      (PyDateTime_Delta *) right,
-                                      0);
-    }
-    else {
-        /* ??? + date
-         * 'right' must be one of us, or we wouldn't have been called
-         */
-        if (PyDelta_Check(left))
-            /* delta + date */
-            return add_date_timedelta((PyDateTime_Date *) right,
-                                      (PyDateTime_Delta *) left,
-                                      0);
-    }
-    Py_INCREF(Py_NotImplemented);
-    return Py_NotImplemented;
-}
-
-static PyObject *
-date_subtract(PyObject *left, PyObject *right)
-{
-    if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-    if (PyDate_Check(left)) {
-        if (PyDate_Check(right)) {
-            /* date - date */
-            int left_ord = ymd_to_ord(GET_YEAR(left),
-                                      GET_MONTH(left),
-                                      GET_DAY(left));
-            int right_ord = ymd_to_ord(GET_YEAR(right),
-                                       GET_MONTH(right),
-                                       GET_DAY(right));
-            return new_delta(left_ord - right_ord, 0, 0, 0);
-        }
-        if (PyDelta_Check(right)) {
-            /* date - delta */
-            return add_date_timedelta((PyDateTime_Date *) left,
-                                      (PyDateTime_Delta *) right,
-                                      1);
-        }
-    }
-    Py_INCREF(Py_NotImplemented);
-    return Py_NotImplemented;
-}
-
-
-/* Various ways to turn a date into a string. */
-
-static PyObject *
-date_repr(PyDateTime_Date *self)
-{
-    return PyUnicode_FromFormat("%s(%d, %d, %d)",
-                                Py_TYPE(self)->tp_name,
-                                GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-}
-
-static PyObject *
-date_isoformat(PyDateTime_Date *self)
-{
-    return PyUnicode_FromFormat("%04d-%02d-%02d",
-                                GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-}
-
-/* str() calls the appropriate isoformat() method. */
-static PyObject *
-date_str(PyDateTime_Date *self)
-{
-    return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
-}
-
-
-static PyObject *
-date_ctime(PyDateTime_Date *self)
-{
-    return format_ctime(self, 0, 0, 0);
-}
-
-static PyObject *
-date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
-{
-    /* This method can be inherited, and needs to call the
-     * timetuple() method appropriate to self's class.
-     */
-    PyObject *result;
-    PyObject *tuple;
-    PyObject *format;
-    static char *keywords[] = {"format", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
-                                      &format))
-        return NULL;
-
-    tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
-    if (tuple == NULL)
-        return NULL;
-    result = wrap_strftime((PyObject *)self, format, tuple,
-                           (PyObject *)self);
-    Py_DECREF(tuple);
-    return result;
-}
-
-static PyObject *
-date_format(PyDateTime_Date *self, PyObject *args)
-{
-    PyObject *format;
-
-    if (!PyArg_ParseTuple(args, "U:__format__", &format))
-        return NULL;
-
-    /* if the format is zero length, return str(self) */
-    if (PyUnicode_GetSize(format) == 0)
-        return PyObject_Str((PyObject *)self);
-
-    return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
-}
-
-/* ISO methods. */
-
-static PyObject *
-date_isoweekday(PyDateTime_Date *self)
-{
-    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-
-    return PyLong_FromLong(dow + 1);
-}
-
-static PyObject *
-date_isocalendar(PyDateTime_Date *self)
-{
-    int  year         = GET_YEAR(self);
-    int  week1_monday = iso_week1_monday(year);
-    int today         = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
-    int  week;
-    int  day;
-
-    week = divmod(today - week1_monday, 7, &day);
-    if (week < 0) {
-        --year;
-        week1_monday = iso_week1_monday(year);
-        week = divmod(today - week1_monday, 7, &day);
-    }
-    else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
-        ++year;
-        week = 0;
-    }
-    return Py_BuildValue("iii", year, week + 1, day + 1);
-}
-
-/* Miscellaneous methods. */
-
-static PyObject *
-date_richcompare(PyObject *self, PyObject *other, int op)
-{
-    if (PyDate_Check(other)) {
-        int diff = memcmp(((PyDateTime_Date *)self)->data,
-                          ((PyDateTime_Date *)other)->data,
-                          _PyDateTime_DATE_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-    else {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-}
-
-static PyObject *
-date_timetuple(PyDateTime_Date *self)
-{
-    return build_struct_time(GET_YEAR(self),
-                             GET_MONTH(self),
-                             GET_DAY(self),
-                             0, 0, 0, -1);
-}
-
-static PyObject *
-date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
-{
-    PyObject *clone;
-    PyObject *tuple;
-    int year = GET_YEAR(self);
-    int month = GET_MONTH(self);
-    int day = GET_DAY(self);
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
-                                      &year, &month, &day))
-        return NULL;
-    tuple = Py_BuildValue("iii", year, month, day);
-    if (tuple == NULL)
-        return NULL;
-    clone = date_new(Py_TYPE(self), tuple, NULL);
-    Py_DECREF(tuple);
-    return clone;
-}
-
-/*
-    Borrowed from stringobject.c, originally it was string_hash()
-*/
-static long
-generic_hash(unsigned char *data, int len)
-{
-    register unsigned char *p;
-    register long x;
-
-    p = (unsigned char *) data;
-    x = *p << 7;
-    while (--len >= 0)
-        x = (1000003*x) ^ *p++;
-    x ^= len;
-    if (x == -1)
-        x = -2;
-
-    return x;
-}
-
-
-static PyObject *date_getstate(PyDateTime_Date *self);
-
-static long
-date_hash(PyDateTime_Date *self)
-{
-    if (self->hashcode == -1)
-        self->hashcode = generic_hash(
-            (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
-
-    return self->hashcode;
-}
-
-static PyObject *
-date_toordinal(PyDateTime_Date *self)
-{
-    return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
-                                     GET_DAY(self)));
-}
-
-static PyObject *
-date_weekday(PyDateTime_Date *self)
-{
-    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
-
-    return PyLong_FromLong(dow);
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* __getstate__ isn't exposed */
-static PyObject *
-date_getstate(PyDateTime_Date *self)
-{
-    PyObject* field;
-    field = PyBytes_FromStringAndSize((char*)self->data,
-                                       _PyDateTime_DATE_DATASIZE);
-    return Py_BuildValue("(N)", field);
-}
-
-static PyObject *
-date_reduce(PyDateTime_Date *self, PyObject *arg)
-{
-    return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
-}
-
-static PyMethodDef date_methods[] = {
-
-    /* Class methods: */
-
-    {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
-                                                       METH_CLASS,
-     PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
-               "time.time()).")},
-
-    {"fromordinal", (PyCFunction)date_fromordinal,      METH_VARARGS |
-                                                    METH_CLASS,
-     PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
-               "ordinal.")},
-
-    {"today",         (PyCFunction)date_today,   METH_NOARGS | METH_CLASS,
-     PyDoc_STR("Current date or datetime:  same as "
-               "self.__class__.fromtimestamp(time.time()).")},
-
-    /* Instance methods: */
-
-    {"ctime",       (PyCFunction)date_ctime,        METH_NOARGS,
-     PyDoc_STR("Return ctime() style string.")},
-
-    {"strftime",        (PyCFunction)date_strftime,     METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("format -> strftime() style string.")},
-
-    {"__format__",      (PyCFunction)date_format,       METH_VARARGS,
-     PyDoc_STR("Formats self with strftime.")},
-
-    {"timetuple",   (PyCFunction)date_timetuple,    METH_NOARGS,
-     PyDoc_STR("Return time tuple, compatible with time.localtime().")},
-
-    {"isocalendar", (PyCFunction)date_isocalendar,  METH_NOARGS,
-     PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
-               "weekday.")},
-
-    {"isoformat",   (PyCFunction)date_isoformat,        METH_NOARGS,
-     PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
-
-    {"isoweekday",  (PyCFunction)date_isoweekday,   METH_NOARGS,
-     PyDoc_STR("Return the day of the week represented by the date.\n"
-               "Monday == 1 ... Sunday == 7")},
-
-    {"toordinal",   (PyCFunction)date_toordinal,    METH_NOARGS,
-     PyDoc_STR("Return proleptic Gregorian ordinal.  January 1 of year "
-               "1 is day 1.")},
-
-    {"weekday",     (PyCFunction)date_weekday,      METH_NOARGS,
-     PyDoc_STR("Return the day of the week represented by the date.\n"
-               "Monday == 0 ... Sunday == 6")},
-
-    {"replace",     (PyCFunction)date_replace,      METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("Return date with new specified fields.")},
-
-    {"__reduce__", (PyCFunction)date_reduce,        METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL}
-};
-
-static char date_doc[] =
-PyDoc_STR("date(year, month, day) --> date object");
-
-static PyNumberMethods date_as_number = {
-    date_add,                                           /* nb_add */
-    date_subtract,                                      /* nb_subtract */
-    0,                                                  /* nb_multiply */
-    0,                                                  /* nb_remainder */
-    0,                                                  /* nb_divmod */
-    0,                                                  /* nb_power */
-    0,                                                  /* nb_negative */
-    0,                                                  /* nb_positive */
-    0,                                                  /* nb_absolute */
-    0,                                                  /* nb_bool */
-};
-
-static PyTypeObject PyDateTime_DateType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.date",                                    /* tp_name */
-    sizeof(PyDateTime_Date),                            /* tp_basicsize */
-    0,                                                  /* tp_itemsize */
-    0,                                                  /* tp_dealloc */
-    0,                                                  /* tp_print */
-    0,                                                  /* tp_getattr */
-    0,                                                  /* tp_setattr */
-    0,                                                  /* tp_reserved */
-    (reprfunc)date_repr,                                /* tp_repr */
-    &date_as_number,                                    /* tp_as_number */
-    0,                                                  /* tp_as_sequence */
-    0,                                                  /* tp_as_mapping */
-    (hashfunc)date_hash,                                /* tp_hash */
-    0,                                                  /* tp_call */
-    (reprfunc)date_str,                                 /* tp_str */
-    PyObject_GenericGetAttr,                            /* tp_getattro */
-    0,                                                  /* tp_setattro */
-    0,                                                  /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,           /* tp_flags */
-    date_doc,                                           /* tp_doc */
-    0,                                                  /* tp_traverse */
-    0,                                                  /* tp_clear */
-    date_richcompare,                                   /* tp_richcompare */
-    0,                                                  /* tp_weaklistoffset */
-    0,                                                  /* tp_iter */
-    0,                                                  /* tp_iternext */
-    date_methods,                                       /* tp_methods */
-    0,                                                  /* tp_members */
-    date_getset,                                        /* tp_getset */
-    0,                                                  /* tp_base */
-    0,                                                  /* tp_dict */
-    0,                                                  /* tp_descr_get */
-    0,                                                  /* tp_descr_set */
-    0,                                                  /* tp_dictoffset */
-    0,                                                  /* tp_init */
-    0,                                                  /* tp_alloc */
-    date_new,                                           /* tp_new */
-    0,                                                  /* tp_free */
-};
-
-/*
- * PyDateTime_TZInfo implementation.
- */
-
-/* This is a pure abstract base class, so doesn't do anything beyond
- * raising NotImplemented exceptions.  Real tzinfo classes need
- * to derive from this.  This is mostly for clarity, and for efficiency in
- * datetime and time constructors (their tzinfo arguments need to
- * be subclasses of this tzinfo class, which is easy and quick to check).
- *
- * Note:  For reasons having to do with pickling of subclasses, we have
- * to allow tzinfo objects to be instantiated.  This wasn't an issue
- * in the Python implementation (__init__() could raise NotImplementedError
- * there without ill effect), but doing so in the C implementation hit a
- * brick wall.
- */
-
-static PyObject *
-tzinfo_nogo(const char* methodname)
-{
-    PyErr_Format(PyExc_NotImplementedError,
-                 "a tzinfo subclass must implement %s()",
-                 methodname);
-    return NULL;
-}
-
-/* Methods.  A subclass must implement these. */
-
-static PyObject *
-tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    return tzinfo_nogo("tzname");
-}
-
-static PyObject *
-tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    return tzinfo_nogo("utcoffset");
-}
-
-static PyObject *
-tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    return tzinfo_nogo("dst");
-}
-
-static PyObject *
-tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
-{
-    int y, m, d, hh, mm, ss, us;
-
-    PyObject *result;
-    int off, dst;
-    int none;
-    int delta;
-
-    if (! PyDateTime_Check(dt)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "fromutc: argument must be a datetime");
-        return NULL;
-    }
-    if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
-                        "is not self");
-        return NULL;
-    }
-
-    off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
-    if (off == -1 && PyErr_Occurred())
-        return NULL;
-    if (none) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
-                        "utcoffset() result required");
-        return NULL;
-    }
-
-    dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
-    if (dst == -1 && PyErr_Occurred())
-        return NULL;
-    if (none) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
-                        "dst() result required");
-        return NULL;
-    }
-
-    y = GET_YEAR(dt);
-    m = GET_MONTH(dt);
-    d = GET_DAY(dt);
-    hh = DATE_GET_HOUR(dt);
-    mm = DATE_GET_MINUTE(dt);
-    ss = DATE_GET_SECOND(dt);
-    us = DATE_GET_MICROSECOND(dt);
-
-    delta = off - dst;
-    mm += delta;
-    if ((mm < 0 || mm >= 60) &&
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
-        return NULL;
-    result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
-    if (result == NULL)
-        return result;
-
-    dst = call_dst(dt->tzinfo, result, &none);
-    if (dst == -1 && PyErr_Occurred())
-        goto Fail;
-    if (none)
-        goto Inconsistent;
-    if (dst == 0)
-        return result;
-
-    mm += dst;
-    if ((mm < 0 || mm >= 60) &&
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
-        goto Fail;
-    Py_DECREF(result);
-    result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
-    return result;
-
-Inconsistent:
-    PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
-                    "inconsistent results; cannot convert");
-
-    /* fall thru to failure */
-Fail:
-    Py_DECREF(result);
-    return NULL;
-}
-
-/*
- * Pickle support.  This is solely so that tzinfo subclasses can use
- * pickling -- tzinfo itself is supposed to be uninstantiable.
- */
-
-static PyObject *
-tzinfo_reduce(PyObject *self)
-{
-    PyObject *args, *state, *tmp;
-    PyObject *getinitargs, *getstate;
-
-    tmp = PyTuple_New(0);
-    if (tmp == NULL)
-        return NULL;
-
-    getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
-    if (getinitargs != NULL) {
-        args = PyObject_CallObject(getinitargs, tmp);
-        Py_DECREF(getinitargs);
-        if (args == NULL) {
-            Py_DECREF(tmp);
-            return NULL;
-        }
-    }
-    else {
-        PyErr_Clear();
-        args = tmp;
-        Py_INCREF(args);
-    }
-
-    getstate = PyObject_GetAttrString(self, "__getstate__");
-    if (getstate != NULL) {
-        state = PyObject_CallObject(getstate, tmp);
-        Py_DECREF(getstate);
-        if (state == NULL) {
-            Py_DECREF(args);
-            Py_DECREF(tmp);
-            return NULL;
-        }
-    }
-    else {
-        PyObject **dictptr;
-        PyErr_Clear();
-        state = Py_None;
-        dictptr = _PyObject_GetDictPtr(self);
-        if (dictptr && *dictptr && PyDict_Size(*dictptr))
-            state = *dictptr;
-        Py_INCREF(state);
-    }
-
-    Py_DECREF(tmp);
-
-    if (state == Py_None) {
-        Py_DECREF(state);
-        return Py_BuildValue("(ON)", Py_TYPE(self), args);
-    }
-    else
-        return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
-}
-
-static PyMethodDef tzinfo_methods[] = {
-
-    {"tzname",          (PyCFunction)tzinfo_tzname,             METH_O,
-     PyDoc_STR("datetime -> string name of time zone.")},
-
-    {"utcoffset",       (PyCFunction)tzinfo_utcoffset,          METH_O,
-     PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
-           "values indicating West of UTC")},
-
-    {"dst",             (PyCFunction)tzinfo_dst,                METH_O,
-     PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
-
-    {"fromutc",         (PyCFunction)tzinfo_fromutc,            METH_O,
-     PyDoc_STR("datetime in UTC -> datetime in local time.")},
-
-    {"__reduce__",  (PyCFunction)tzinfo_reduce,             METH_NOARGS,
-     PyDoc_STR("-> (cls, state)")},
-
-    {NULL, NULL}
-};
-
-static char tzinfo_doc[] =
-PyDoc_STR("Abstract base class for time zone info objects.");
-
-static PyTypeObject PyDateTime_TZInfoType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.tzinfo",                          /* tp_name */
-    sizeof(PyDateTime_TZInfo),                  /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    0,                                          /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
-    0,                                          /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    0,                                          /* tp_hash */
-    0,                                          /* tp_call */
-    0,                                          /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
-    tzinfo_doc,                                 /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    0,                                          /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    0,                                          /* tp_iter */
-    0,                                          /* tp_iternext */
-    tzinfo_methods,                             /* tp_methods */
-    0,                                          /* tp_members */
-    0,                                          /* tp_getset */
-    0,                                          /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    0,                                          /* tp_alloc */
-    PyType_GenericNew,                          /* tp_new */
-    0,                                          /* tp_free */
-};
-
-static char *timezone_kws[] = {"offset", "name", NULL};
-
-static PyObject *
-timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *offset;
-    PyObject *name = NULL;
-    if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
-                                    &PyDateTime_DeltaType, &offset,
-                                    &PyUnicode_Type, &name))
-        return new_timezone(offset, name);
-
-    return NULL;
-}
-
-static void
-timezone_dealloc(PyDateTime_TimeZone *self)
-{
-    Py_CLEAR(self->offset);
-    Py_CLEAR(self->name);
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-static PyObject *
-timezone_richcompare(PyDateTime_TimeZone *self,
-                     PyDateTime_TimeZone *other, int op)
-{
-    if (op != Py_EQ && op != Py_NE) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-    return delta_richcompare(self->offset, other->offset, op);
-}
-
-static long
-timezone_hash(PyDateTime_TimeZone *self)
-{
-    return delta_hash((PyDateTime_Delta *)self->offset);
-}
-
-/* Check argument type passed to tzname, utcoffset, or dst methods.
-   Returns 0 for good argument.  Returns -1 and sets exception info
-   otherwise.
- */
-static int
-_timezone_check_argument(PyObject *dt, const char *meth)
-{
-    if (dt == Py_None || PyDateTime_Check(dt))
-        return 0;
-    PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
-                 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
-    return -1;
-}
-
-static PyObject *
-timezone_str(PyDateTime_TimeZone *self)
-{
-    char buf[10];
-    int hours, minutes, seconds;
-    PyObject *offset;
-    char sign;
-
-    if (self->name != NULL) {
-        Py_INCREF(self->name);
-        return self->name;
-    }
-    /* Offset is normalized, so it is negative if days < 0 */
-    if (GET_TD_DAYS(self->offset) < 0) {
-        sign = '-';
-        offset = delta_negative((PyDateTime_Delta *)self->offset);
-        if (offset == NULL)
-            return NULL;
-    }
-    else {
-        sign = '+';
-        offset = self->offset;
-        Py_INCREF(offset);
-    }
-    /* Offset is not negative here. */
-    seconds = GET_TD_SECONDS(offset);
-    Py_DECREF(offset);
-    minutes = divmod(seconds, 60, &seconds);
-    hours = divmod(minutes, 60, &minutes);
-    assert(seconds == 0);
-    /* XXX ignore sub-minute data, curently not allowed. */
-    PyOS_snprintf(buf, sizeof(buf), "UTC%c%02d:%02d", sign, hours, minutes);
-
-    return PyUnicode_FromString(buf);
-}
-
-static PyObject *
-timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
-{
-    if (_timezone_check_argument(dt, "tzname") == -1)
-        return NULL;
-
-    return timezone_str(self);
-}
-
-static PyObject *
-timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
-{
-    if (_timezone_check_argument(dt, "utcoffset") == -1)
-        return NULL;
-
-    Py_INCREF(self->offset);
-    return self->offset;
-}
-
-static PyObject *
-timezone_dst(PyObject *self, PyObject *dt)
-{
-    if (_timezone_check_argument(dt, "dst") == -1)
-        return NULL;
-
-    Py_RETURN_NONE;
-}
-
-static PyObject *
-add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
-                       int factor);
-
-static PyObject *
-timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
-{
-    if (! PyDateTime_Check(dt)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "fromutc: argument must be a datetime");
-        return NULL;
-    }
-    if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
-                        "is not self");
-        return NULL;
-    }
-
-    return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
-}
-
-static PyObject *
-timezone_getinitargs(PyDateTime_TimeZone *self)
-{
-    if (self->name == NULL)
-        return Py_BuildValue("(O)", self->offset);
-    return Py_BuildValue("(OO)", self->offset, self->name);
-}
-
-static PyMethodDef timezone_methods[] = {
-    {"tzname", (PyCFunction)timezone_tzname, METH_O,
-     PyDoc_STR("If name is specified when timezone is created, returns the name."
-               "  Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
-
-    {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
-     PyDoc_STR("Return fixed offset.")},
-
-    {"dst", (PyCFunction)timezone_dst, METH_O,
-     PyDoc_STR("Return None.")},
-
-    {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
-     PyDoc_STR("datetime in UTC -> datetime in local time.")},
-
-    {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
-     PyDoc_STR("pickle support")},
-
-    {NULL, NULL}
-};
-
-static char timezone_doc[] =
-PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
-
-static PyTypeObject PyDateTime_TimeZoneType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.timezone",              /* tp_name */
-    sizeof(PyDateTime_TimeZone),      /* tp_basicsize */
-    0,                                /* tp_itemsize */
-    (destructor)timezone_dealloc,     /* tp_dealloc */
-    0,                                /* tp_print */
-    0,                                /* tp_getattr */
-    0,                                /* tp_setattr */
-    0,                                /* tp_reserved */
-    0,                                /* tp_repr */
-    0,                                /* tp_as_number */
-    0,                                /* tp_as_sequence */
-    0,                                /* tp_as_mapping */
-    (hashfunc)timezone_hash,          /* tp_hash */
-    0,                                /* tp_call */
-    (reprfunc)timezone_str,           /* tp_str */
-    0,                                /* tp_getattro */
-    0,                                /* tp_setattro */
-    0,                                /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,               /* tp_flags */
-    timezone_doc,                     /* tp_doc */
-    0,                                /* tp_traverse */
-    0,                                /* tp_clear */
-    (richcmpfunc)timezone_richcompare,/* tp_richcompare */
-    0,                                /* tp_weaklistoffset */
-    0,                                /* tp_iter */
-    0,                                /* tp_iternext */
-    timezone_methods,                 /* tp_methods */
-    0,                                /* tp_members */
-    0,                                /* tp_getset */
-    &PyDateTime_TZInfoType,           /* tp_base */
-    0,                                /* tp_dict */
-    0,                                /* tp_descr_get */
-    0,                                /* tp_descr_set */
-    0,                                /* tp_dictoffset */
-    0,                                /* tp_init */
-    0,                                /* tp_alloc */
-    timezone_new,                     /* tp_new */
-};
-
-/*
- * PyDateTime_Time implementation.
- */
-
-/* Accessor properties.
- */
-
-static PyObject *
-time_hour(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_HOUR(self));
-}
-
-static PyObject *
-time_minute(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_MINUTE(self));
-}
-
-/* The name time_second conflicted with some platform header file. */
-static PyObject *
-py_time_second(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_SECOND(self));
-}
-
-static PyObject *
-time_microsecond(PyDateTime_Time *self, void *unused)
-{
-    return PyLong_FromLong(TIME_GET_MICROSECOND(self));
-}
-
-static PyObject *
-time_tzinfo(PyDateTime_Time *self, void *unused)
-{
-    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
-    Py_INCREF(result);
-    return result;
-}
-
-static PyGetSetDef time_getset[] = {
-    {"hour",        (getter)time_hour},
-    {"minute",      (getter)time_minute},
-    {"second",      (getter)py_time_second},
-    {"microsecond", (getter)time_microsecond},
-    {"tzinfo",          (getter)time_tzinfo},
-    {NULL}
-};
-
-/*
- * Constructors.
- */
-
-static char *time_kws[] = {"hour", "minute", "second", "microsecond",
-                           "tzinfo", NULL};
-
-static PyObject *
-time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-    PyObject *state;
-    int hour = 0;
-    int minute = 0;
-    int second = 0;
-    int usecond = 0;
-    PyObject *tzinfo = Py_None;
-
-    /* Check for invocation from pickle with __getstate__ state */
-    if (PyTuple_GET_SIZE(args) >= 1 &&
-        PyTuple_GET_SIZE(args) <= 2 &&
-        PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-        PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
-        ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
-    {
-        PyDateTime_Time *me;
-        char aware;
-
-        if (PyTuple_GET_SIZE(args) == 2) {
-            tzinfo = PyTuple_GET_ITEM(args, 1);
-            if (check_tzinfo_subclass(tzinfo) < 0) {
-                PyErr_SetString(PyExc_TypeError, "bad "
-                    "tzinfo state arg");
-                return NULL;
-            }
-        }
-        aware = (char)(tzinfo != Py_None);
-        me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
-        if (me != NULL) {
-            char *pdata = PyBytes_AS_STRING(state);
-
-            memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
-            me->hashcode = -1;
-            me->hastzinfo = aware;
-            if (aware) {
-                Py_INCREF(tzinfo);
-                me->tzinfo = tzinfo;
-            }
-        }
-        return (PyObject *)me;
-    }
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
-                                    &hour, &minute, &second, &usecond,
-                                    &tzinfo)) {
-        if (check_time_args(hour, minute, second, usecond) < 0)
-            return NULL;
-        if (check_tzinfo_subclass(tzinfo) < 0)
-            return NULL;
-        self = new_time_ex(hour, minute, second, usecond, tzinfo,
-                           type);
-    }
-    return self;
-}
-
-/*
- * Destructor.
- */
-
-static void
-time_dealloc(PyDateTime_Time *self)
-{
-    if (HASTZINFO(self)) {
-        Py_XDECREF(self->tzinfo);
-    }
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-/*
- * Indirect access to tzinfo methods.
- */
-
-/* These are all METH_NOARGS, so don't need to check the arglist. */
-static PyObject *
-time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "utcoffset", Py_None);
-}
-
-static PyObject *
-time_dst(PyDateTime_Time *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "dst", Py_None);
-}
-
-static PyObject *
-time_tzname(PyDateTime_Time *self, PyObject *unused) {
-    return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
-                       Py_None);
-}
-
-/*
- * Various ways to turn a time into a string.
- */
-
-static PyObject *
-time_repr(PyDateTime_Time *self)
-{
-    const char *type_name = Py_TYPE(self)->tp_name;
-    int h = TIME_GET_HOUR(self);
-    int m = TIME_GET_MINUTE(self);
-    int s = TIME_GET_SECOND(self);
-    int us = TIME_GET_MICROSECOND(self);
-    PyObject *result = NULL;
-
-    if (us)
-        result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
-                                      type_name, h, m, s, us);
-    else if (s)
-        result = PyUnicode_FromFormat("%s(%d, %d, %d)",
-                                      type_name, h, m, s);
-    else
-        result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
-    if (result != NULL && HASTZINFO(self))
-        result = append_keyword_tzinfo(result, self->tzinfo);
-    return result;
-}
-
-static PyObject *
-time_str(PyDateTime_Time *self)
-{
-    return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
-}
-
-static PyObject *
-time_isoformat(PyDateTime_Time *self, PyObject *unused)
-{
-    char buf[100];
-    PyObject *result;
-    int us = TIME_GET_MICROSECOND(self);;
-
-    if (us)
-        result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
-                                      TIME_GET_HOUR(self),
-                                      TIME_GET_MINUTE(self),
-                                      TIME_GET_SECOND(self),
-                                      us);
-    else
-        result = PyUnicode_FromFormat("%02d:%02d:%02d",
-                                      TIME_GET_HOUR(self),
-                                      TIME_GET_MINUTE(self),
-                                      TIME_GET_SECOND(self));
-
-    if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
-        return result;
-
-    /* We need to append the UTC offset. */
-    if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
-                         Py_None) < 0) {
-        Py_DECREF(result);
-        return NULL;
-    }
-    PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
-    return result;
-}
-
-static PyObject *
-time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
-{
-    PyObject *result;
-    PyObject *tuple;
-    PyObject *format;
-    static char *keywords[] = {"format", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
-                                      &format))
-        return NULL;
-
-    /* Python's strftime does insane things with the year part of the
-     * timetuple.  The year is forced to (the otherwise nonsensical)
-     * 1900 to worm around that.
-     */
-    tuple = Py_BuildValue("iiiiiiiii",
-                          1900, 1, 1, /* year, month, day */
-                  TIME_GET_HOUR(self),
-                  TIME_GET_MINUTE(self),
-                  TIME_GET_SECOND(self),
-                  0, 1, -1); /* weekday, daynum, dst */
-    if (tuple == NULL)
-        return NULL;
-    assert(PyTuple_Size(tuple) == 9);
-    result = wrap_strftime((PyObject *)self, format, tuple,
-                           Py_None);
-    Py_DECREF(tuple);
-    return result;
-}
-
-/*
- * Miscellaneous methods.
- */
-
-static PyObject *
-time_richcompare(PyObject *self, PyObject *other, int op)
-{
-    int diff;
-    naivety n1, n2;
-    int offset1, offset2;
-
-    if (! PyTime_Check(other)) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-    if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
-                                other, &offset2, &n2, Py_None) < 0)
-        return NULL;
-    assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
-    /* If they're both naive, or both aware and have the same offsets,
-     * we get off cheap.  Note that if they're both naive, offset1 ==
-     * offset2 == 0 at this point.
-     */
-    if (n1 == n2 && offset1 == offset2) {
-        diff = memcmp(((PyDateTime_Time *)self)->data,
-                      ((PyDateTime_Time *)other)->data,
-                      _PyDateTime_TIME_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-
-    if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
-        assert(offset1 != offset2);             /* else last "if" handled it */
-        /* Convert everything except microseconds to seconds.  These
-         * can't overflow (no more than the # of seconds in 2 days).
-         */
-        offset1 = TIME_GET_HOUR(self) * 3600 +
-                  (TIME_GET_MINUTE(self) - offset1) * 60 +
-                  TIME_GET_SECOND(self);
-        offset2 = TIME_GET_HOUR(other) * 3600 +
-                  (TIME_GET_MINUTE(other) - offset2) * 60 +
-                  TIME_GET_SECOND(other);
-        diff = offset1 - offset2;
-        if (diff == 0)
-            diff = TIME_GET_MICROSECOND(self) -
-                   TIME_GET_MICROSECOND(other);
-        return diff_to_bool(diff, op);
-    }
-
-    assert(n1 != n2);
-    PyErr_SetString(PyExc_TypeError,
-                    "can't compare offset-naive and "
-                    "offset-aware times");
-    return NULL;
-}
-
-static long
-time_hash(PyDateTime_Time *self)
-{
-    if (self->hashcode == -1) {
-        naivety n;
-        int offset;
-        PyObject *temp;
-
-        n = classify_utcoffset((PyObject *)self, Py_None, &offset);
-        assert(n != OFFSET_UNKNOWN);
-        if (n == OFFSET_ERROR)
-            return -1;
-
-        /* Reduce this to a hash of another object. */
-        if (offset == 0) {
-            self->hashcode = generic_hash(
-                (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
-            return self->hashcode;
-        }
-        else {
-            int hour;
-            int minute;
-
-            assert(n == OFFSET_AWARE);
-            assert(HASTZINFO(self));
-            hour = divmod(TIME_GET_HOUR(self) * 60 +
-                            TIME_GET_MINUTE(self) - offset,
-                          60,
-                          &minute);
-            if (0 <= hour && hour < 24)
-                temp = new_time(hour, minute,
-                                TIME_GET_SECOND(self),
-                                TIME_GET_MICROSECOND(self),
-                                Py_None);
-            else
-                temp = Py_BuildValue("iiii",
-                           hour, minute,
-                           TIME_GET_SECOND(self),
-                           TIME_GET_MICROSECOND(self));
-        }
-        if (temp != NULL) {
-            self->hashcode = PyObject_Hash(temp);
-            Py_DECREF(temp);
-        }
-    }
-    return self->hashcode;
-}
-
-static PyObject *
-time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
-{
-    PyObject *clone;
-    PyObject *tuple;
-    int hh = TIME_GET_HOUR(self);
-    int mm = TIME_GET_MINUTE(self);
-    int ss = TIME_GET_SECOND(self);
-    int us = TIME_GET_MICROSECOND(self);
-    PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
-                                      time_kws,
-                                      &hh, &mm, &ss, &us, &tzinfo))
-        return NULL;
-    tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
-    if (tuple == NULL)
-        return NULL;
-    clone = time_new(Py_TYPE(self), tuple, NULL);
-    Py_DECREF(tuple);
-    return clone;
-}
-
-static int
-time_bool(PyDateTime_Time *self)
-{
-    int offset;
-    int none;
-
-    if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
-        /* Since utcoffset is in whole minutes, nothing can
-         * alter the conclusion that this is nonzero.
-         */
-        return 1;
-    }
-    offset = 0;
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        offset = call_utcoffset(self->tzinfo, Py_None, &none);
-        if (offset == -1 && PyErr_Occurred())
-            return -1;
-    }
-    return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* Let basestate be the non-tzinfo data string.
- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
- * So it's a tuple in any (non-error) case.
- * __getstate__ isn't exposed.
- */
-static PyObject *
-time_getstate(PyDateTime_Time *self)
-{
-    PyObject *basestate;
-    PyObject *result = NULL;
-
-    basestate =  PyBytes_FromStringAndSize((char *)self->data,
-                                            _PyDateTime_TIME_DATASIZE);
-    if (basestate != NULL) {
-        if (! HASTZINFO(self) || self->tzinfo == Py_None)
-            result = PyTuple_Pack(1, basestate);
-        else
-            result = PyTuple_Pack(2, basestate, self->tzinfo);
-        Py_DECREF(basestate);
-    }
-    return result;
-}
-
-static PyObject *
-time_reduce(PyDateTime_Time *self, PyObject *arg)
-{
-    return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
-}
-
-static PyMethodDef time_methods[] = {
-
-    {"isoformat",   (PyCFunction)time_isoformat,        METH_NOARGS,
-     PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
-               "[+HH:MM].")},
-
-    {"strftime",        (PyCFunction)time_strftime,     METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("format -> strftime() style string.")},
-
-    {"__format__",      (PyCFunction)date_format,       METH_VARARGS,
-     PyDoc_STR("Formats self with strftime.")},
-
-    {"utcoffset",       (PyCFunction)time_utcoffset,    METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
-
-    {"tzname",          (PyCFunction)time_tzname,       METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.tzname(self).")},
-
-    {"dst",             (PyCFunction)time_dst,          METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.dst(self).")},
-
-    {"replace",     (PyCFunction)time_replace,          METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("Return time with new specified fields.")},
-
-    {"__reduce__", (PyCFunction)time_reduce,        METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL}
-};
-
-static char time_doc[] =
-PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
-\n\
-All arguments are optional. tzinfo may be None, or an instance of\n\
-a tzinfo subclass. The remaining arguments may be ints or longs.\n");
-
-static PyNumberMethods time_as_number = {
-    0,                                          /* nb_add */
-    0,                                          /* nb_subtract */
-    0,                                          /* nb_multiply */
-    0,                                          /* nb_remainder */
-    0,                                          /* nb_divmod */
-    0,                                          /* nb_power */
-    0,                                          /* nb_negative */
-    0,                                          /* nb_positive */
-    0,                                          /* nb_absolute */
-    (inquiry)time_bool,                         /* nb_bool */
-};
-
-static PyTypeObject PyDateTime_TimeType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.time",                            /* tp_name */
-    sizeof(PyDateTime_Time),                    /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    (destructor)time_dealloc,                   /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)time_repr,                        /* tp_repr */
-    &time_as_number,                            /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    (hashfunc)time_hash,                        /* tp_hash */
-    0,                                          /* tp_call */
-    (reprfunc)time_str,                         /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
-    time_doc,                                   /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    time_richcompare,                           /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    0,                                          /* tp_iter */
-    0,                                          /* tp_iternext */
-    time_methods,                               /* tp_methods */
-    0,                                          /* tp_members */
-    time_getset,                                /* tp_getset */
-    0,                                          /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    time_alloc,                                 /* tp_alloc */
-    time_new,                                   /* tp_new */
-    0,                                          /* tp_free */
-};
-
-/*
- * PyDateTime_DateTime implementation.
- */
-
-/* Accessor properties.  Properties for day, month, and year are inherited
- * from date.
- */
-
-static PyObject *
-datetime_hour(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_HOUR(self));
-}
-
-static PyObject *
-datetime_minute(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_MINUTE(self));
-}
-
-static PyObject *
-datetime_second(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_SECOND(self));
-}
-
-static PyObject *
-datetime_microsecond(PyDateTime_DateTime *self, void *unused)
-{
-    return PyLong_FromLong(DATE_GET_MICROSECOND(self));
-}
-
-static PyObject *
-datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
-{
-    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
-    Py_INCREF(result);
-    return result;
-}
-
-static PyGetSetDef datetime_getset[] = {
-    {"hour",        (getter)datetime_hour},
-    {"minute",      (getter)datetime_minute},
-    {"second",      (getter)datetime_second},
-    {"microsecond", (getter)datetime_microsecond},
-    {"tzinfo",          (getter)datetime_tzinfo},
-    {NULL}
-};
-
-/*
- * Constructors.
- */
-
-static char *datetime_kws[] = {
-    "year", "month", "day", "hour", "minute", "second",
-    "microsecond", "tzinfo", NULL
-};
-
-static PyObject *
-datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
-{
-    PyObject *self = NULL;
-    PyObject *state;
-    int year;
-    int month;
-    int day;
-    int hour = 0;
-    int minute = 0;
-    int second = 0;
-    int usecond = 0;
-    PyObject *tzinfo = Py_None;
-
-    /* Check for invocation from pickle with __getstate__ state */
-    if (PyTuple_GET_SIZE(args) >= 1 &&
-        PyTuple_GET_SIZE(args) <= 2 &&
-        PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-        PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
-        MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
-    {
-        PyDateTime_DateTime *me;
-        char aware;
-
-        if (PyTuple_GET_SIZE(args) == 2) {
-            tzinfo = PyTuple_GET_ITEM(args, 1);
-            if (check_tzinfo_subclass(tzinfo) < 0) {
-                PyErr_SetString(PyExc_TypeError, "bad "
-                    "tzinfo state arg");
-                return NULL;
-            }
-        }
-        aware = (char)(tzinfo != Py_None);
-        me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
-        if (me != NULL) {
-            char *pdata = PyBytes_AS_STRING(state);
-
-            memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
-            me->hashcode = -1;
-            me->hastzinfo = aware;
-            if (aware) {
-                Py_INCREF(tzinfo);
-                me->tzinfo = tzinfo;
-            }
-        }
-        return (PyObject *)me;
-    }
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
-                                    &year, &month, &day, &hour, &minute,
-                                    &second, &usecond, &tzinfo)) {
-        if (check_date_args(year, month, day) < 0)
-            return NULL;
-        if (check_time_args(hour, minute, second, usecond) < 0)
-            return NULL;
-        if (check_tzinfo_subclass(tzinfo) < 0)
-            return NULL;
-        self = new_datetime_ex(year, month, day,
-                                hour, minute, second, usecond,
-                                tzinfo, type);
-    }
-    return self;
-}
-
-/* TM_FUNC is the shared type of localtime() and gmtime(). */
-typedef struct tm *(*TM_FUNC)(const time_t *timer);
-
-/* Internal helper.
- * Build datetime from a time_t and a distinct count of microseconds.
- * Pass localtime or gmtime for f, to control the interpretation of timet.
- */
-static PyObject *
-datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
-                           PyObject *tzinfo)
-{
-    struct tm *tm;
-    PyObject *result = NULL;
-
-    tm = f(&timet);
-    if (tm) {
-        /* The platform localtime/gmtime may insert leap seconds,
-         * indicated by tm->tm_sec > 59.  We don't care about them,
-         * except to the extent that passing them on to the datetime
-         * constructor would raise ValueError for a reason that
-         * made no sense to the user.
-         */
-        if (tm->tm_sec > 59)
-            tm->tm_sec = 59;
-        result = PyObject_CallFunction(cls, "iiiiiiiO",
-                                       tm->tm_year + 1900,
-                                       tm->tm_mon + 1,
-                                       tm->tm_mday,
-                                       tm->tm_hour,
-                                       tm->tm_min,
-                                       tm->tm_sec,
-                                       us,
-                                       tzinfo);
-    }
-    else
-        PyErr_SetString(PyExc_ValueError,
-                        "timestamp out of range for "
-                        "platform localtime()/gmtime() function");
-    return result;
-}
-
-/* Internal helper.
- * Build datetime from a Python timestamp.  Pass localtime or gmtime for f,
- * to control the interpretation of the timestamp.  Since a double doesn't
- * have enough bits to cover a datetime's full range of precision, it's
- * better to call datetime_from_timet_and_us provided you have a way
- * to get that much precision (e.g., C time() isn't good enough).
- */
-static PyObject *
-datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
-                        PyObject *tzinfo)
-{
-    time_t timet;
-    double fraction;
-    int us;
-
-    timet = _PyTime_DoubleToTimet(timestamp);
-    if (timet == (time_t)-1 && PyErr_Occurred())
-        return NULL;
-    fraction = timestamp - (double)timet;
-    us = (int)round_to_long(fraction * 1e6);
-    if (us < 0) {
-        /* Truncation towards zero is not what we wanted
-           for negative numbers (Python's mod semantics) */
-        timet -= 1;
-        us += 1000000;
-    }
-    /* If timestamp is less than one microsecond smaller than a
-     * full second, round up. Otherwise, ValueErrors are raised
-     * for some floats. */
-    if (us == 1000000) {
-        timet += 1;
-        us = 0;
-    }
-    return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
-}
-
-/* Internal helper.
- * Build most accurate possible datetime for current time.  Pass localtime or
- * gmtime for f as appropriate.
- */
-static PyObject *
-datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
-{
-#ifdef HAVE_GETTIMEOFDAY
-    struct timeval t;
-
-#ifdef GETTIMEOFDAY_NO_TZ
-    gettimeofday(&t);
-#else
-    gettimeofday(&t, (struct timezone *)NULL);
-#endif
-    return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
-                                      tzinfo);
-
-#else   /* ! HAVE_GETTIMEOFDAY */
-    /* No flavor of gettimeofday exists on this platform.  Python's
-     * time.time() does a lot of other platform tricks to get the
-     * best time it can on the platform, and we're not going to do
-     * better than that (if we could, the better code would belong
-     * in time.time()!)  We're limited by the precision of a double,
-     * though.
-     */
-    PyObject *time;
-    double dtime;
-
-    time = time_time();
-    if (time == NULL)
-        return NULL;
-    dtime = PyFloat_AsDouble(time);
-    Py_DECREF(time);
-    if (dtime == -1.0 && PyErr_Occurred())
-        return NULL;
-    return datetime_from_timestamp(cls, f, dtime, tzinfo);
-#endif  /* ! HAVE_GETTIMEOFDAY */
-}
-
-/* Return best possible local time -- this isn't constrained by the
- * precision of a timestamp.
- */
-static PyObject *
-datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
-{
-    PyObject *self;
-    PyObject *tzinfo = Py_None;
-    static char *keywords[] = {"tz", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
-                                      &tzinfo))
-        return NULL;
-    if (check_tzinfo_subclass(tzinfo) < 0)
-        return NULL;
-
-    self = datetime_best_possible(cls,
-                                  tzinfo == Py_None ? localtime : gmtime,
-                                  tzinfo);
-    if (self != NULL && tzinfo != Py_None) {
-        /* Convert UTC to tzinfo's zone. */
-        PyObject *temp = self;
-        self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
-        Py_DECREF(temp);
-    }
-    return self;
-}
-
-/* Return best possible UTC time -- this isn't constrained by the
- * precision of a timestamp.
- */
-static PyObject *
-datetime_utcnow(PyObject *cls, PyObject *dummy)
-{
-    return datetime_best_possible(cls, gmtime, Py_None);
-}
-
-/* Return new local datetime from timestamp (Python timestamp -- a double). */
-static PyObject *
-datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
-{
-    PyObject *self;
-    double timestamp;
-    PyObject *tzinfo = Py_None;
-    static char *keywords[] = {"timestamp", "tz", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
-                                      keywords, &timestamp, &tzinfo))
-        return NULL;
-    if (check_tzinfo_subclass(tzinfo) < 0)
-        return NULL;
-
-    self = datetime_from_timestamp(cls,
-                                   tzinfo == Py_None ? localtime : gmtime,
-                                   timestamp,
-                                   tzinfo);
-    if (self != NULL && tzinfo != Py_None) {
-        /* Convert UTC to tzinfo's zone. */
-        PyObject *temp = self;
-        self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
-        Py_DECREF(temp);
-    }
-    return self;
-}
-
-/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
-static PyObject *
-datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
-{
-    double timestamp;
-    PyObject *result = NULL;
-
-    if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
-        result = datetime_from_timestamp(cls, gmtime, timestamp,
-                                         Py_None);
-    return result;
-}
-
-/* Return new datetime from _strptime.strptime_datetime(). */
-static PyObject *
-datetime_strptime(PyObject *cls, PyObject *args)
-{
-    static PyObject *module = NULL;
-    const Py_UNICODE *string, *format;
-
-    if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
-        return NULL;
-
-    if (module == NULL) {
-        module = PyImport_ImportModuleNoBlock("_strptime");
-        if (module == NULL)
-            return NULL;
-    }
-    return PyObject_CallMethod(module, "_strptime_datetime", "Ouu",
-                               cls, string, format);
-}
-
-/* Return new datetime from date/datetime and time arguments. */
-static PyObject *
-datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
-{
-    static char *keywords[] = {"date", "time", NULL};
-    PyObject *date;
-    PyObject *time;
-    PyObject *result = NULL;
-
-    if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
-                                    &PyDateTime_DateType, &date,
-                                    &PyDateTime_TimeType, &time)) {
-        PyObject *tzinfo = Py_None;
-
-        if (HASTZINFO(time))
-            tzinfo = ((PyDateTime_Time *)time)->tzinfo;
-        result = PyObject_CallFunction(cls, "iiiiiiiO",
-                                        GET_YEAR(date),
-                                        GET_MONTH(date),
-                                        GET_DAY(date),
-                                        TIME_GET_HOUR(time),
-                                        TIME_GET_MINUTE(time),
-                                        TIME_GET_SECOND(time),
-                                        TIME_GET_MICROSECOND(time),
-                                        tzinfo);
-    }
-    return result;
-}
-
-/*
- * Destructor.
- */
-
-static void
-datetime_dealloc(PyDateTime_DateTime *self)
-{
-    if (HASTZINFO(self)) {
-        Py_XDECREF(self->tzinfo);
-    }
-    Py_TYPE(self)->tp_free((PyObject *)self);
-}
-
-/*
- * Indirect access to tzinfo methods.
- */
-
-/* These are all METH_NOARGS, so don't need to check the arglist. */
-static PyObject *
-datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "utcoffset", (PyObject *)self);
-}
-
-static PyObject *
-datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "dst", (PyObject *)self);
-}
-
-static PyObject *
-datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
-    return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
-                       (PyObject *)self);
-}
-
-/*
- * datetime arithmetic.
- */
-
-/* factor must be 1 (to add) or -1 (to subtract).  The result inherits
- * the tzinfo state of date.
- */
-static PyObject *
-add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
-                       int factor)
-{
-    /* Note that the C-level additions can't overflow, because of
-     * invariant bounds on the member values.
-     */
-    int year = GET_YEAR(date);
-    int month = GET_MONTH(date);
-    int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
-    int hour = DATE_GET_HOUR(date);
-    int minute = DATE_GET_MINUTE(date);
-    int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
-    int microsecond = DATE_GET_MICROSECOND(date) +
-                      GET_TD_MICROSECONDS(delta) * factor;
-
-    assert(factor == 1 || factor == -1);
-    if (normalize_datetime(&year, &month, &day,
-                           &hour, &minute, &second, &microsecond) < 0)
-        return NULL;
-    else
-        return new_datetime(year, month, day,
-                            hour, minute, second, microsecond,
-                            HASTZINFO(date) ? date->tzinfo : Py_None);
-}
-
-static PyObject *
-datetime_add(PyObject *left, PyObject *right)
-{
-    if (PyDateTime_Check(left)) {
-        /* datetime + ??? */
-        if (PyDelta_Check(right))
-            /* datetime + delta */
-            return add_datetime_timedelta(
-                            (PyDateTime_DateTime *)left,
-                            (PyDateTime_Delta *)right,
-                            1);
-    }
-    else if (PyDelta_Check(left)) {
-        /* delta + datetime */
-        return add_datetime_timedelta((PyDateTime_DateTime *) right,
-                                      (PyDateTime_Delta *) left,
-                                      1);
-    }
-    Py_INCREF(Py_NotImplemented);
-    return Py_NotImplemented;
-}
-
-static PyObject *
-datetime_subtract(PyObject *left, PyObject *right)
-{
-    PyObject *result = Py_NotImplemented;
-
-    if (PyDateTime_Check(left)) {
-        /* datetime - ??? */
-        if (PyDateTime_Check(right)) {
-            /* datetime - datetime */
-            naivety n1, n2;
-            int offset1, offset2;
-            int delta_d, delta_s, delta_us;
-
-            if (classify_two_utcoffsets(left, &offset1, &n1, left,
-                                        right, &offset2, &n2,
-                                        right) < 0)
-                return NULL;
-            assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
-            if (n1 != n2) {
-                PyErr_SetString(PyExc_TypeError,
-                    "can't subtract offset-naive and "
-                    "offset-aware datetimes");
-                return NULL;
-            }
-            delta_d = ymd_to_ord(GET_YEAR(left),
-                                 GET_MONTH(left),
-                                 GET_DAY(left)) -
-                      ymd_to_ord(GET_YEAR(right),
-                                 GET_MONTH(right),
-                                 GET_DAY(right));
-            /* These can't overflow, since the values are
-             * normalized.  At most this gives the number of
-             * seconds in one day.
-             */
-            delta_s = (DATE_GET_HOUR(left) -
-                       DATE_GET_HOUR(right)) * 3600 +
-                      (DATE_GET_MINUTE(left) -
-                       DATE_GET_MINUTE(right)) * 60 +
-                      (DATE_GET_SECOND(left) -
-                       DATE_GET_SECOND(right));
-            delta_us = DATE_GET_MICROSECOND(left) -
-                       DATE_GET_MICROSECOND(right);
-            /* (left - offset1) - (right - offset2) =
-             * (left - right) + (offset2 - offset1)
-             */
-            delta_s += (offset2 - offset1) * 60;
-            result = new_delta(delta_d, delta_s, delta_us, 1);
-        }
-        else if (PyDelta_Check(right)) {
-            /* datetime - delta */
-            result = add_datetime_timedelta(
-                            (PyDateTime_DateTime *)left,
-                            (PyDateTime_Delta *)right,
-                            -1);
-        }
-    }
-
-    if (result == Py_NotImplemented)
-        Py_INCREF(result);
-    return result;
-}
-
-/* Various ways to turn a datetime into a string. */
-
-static PyObject *
-datetime_repr(PyDateTime_DateTime *self)
-{
-    const char *type_name = Py_TYPE(self)->tp_name;
-    PyObject *baserepr;
-
-    if (DATE_GET_MICROSECOND(self)) {
-        baserepr = PyUnicode_FromFormat(
-                      "%s(%d, %d, %d, %d, %d, %d, %d)",
-                      type_name,
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                      DATE_GET_SECOND(self),
-                      DATE_GET_MICROSECOND(self));
-    }
-    else if (DATE_GET_SECOND(self)) {
-        baserepr = PyUnicode_FromFormat(
-                      "%s(%d, %d, %d, %d, %d, %d)",
-                      type_name,
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                      DATE_GET_SECOND(self));
-    }
-    else {
-        baserepr = PyUnicode_FromFormat(
-                      "%s(%d, %d, %d, %d, %d)",
-                      type_name,
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
-    }
-    if (baserepr == NULL || ! HASTZINFO(self))
-        return baserepr;
-    return append_keyword_tzinfo(baserepr, self->tzinfo);
-}
-
-static PyObject *
-datetime_str(PyDateTime_DateTime *self)
-{
-    return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
-}
-
-static PyObject *
-datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
-{
-    int sep = 'T';
-    static char *keywords[] = {"sep", NULL};
-    char buffer[100];
-    PyObject *result;
-    int us = DATE_GET_MICROSECOND(self);
-
-    if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
-        return NULL;
-    if (us)
-        result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
-                                      GET_YEAR(self), GET_MONTH(self),
-                                      GET_DAY(self), (int)sep,
-                                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                                      DATE_GET_SECOND(self), us);
-    else
-        result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
-                                      GET_YEAR(self), GET_MONTH(self),
-                                      GET_DAY(self), (int)sep,
-                                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
-                                      DATE_GET_SECOND(self));
-
-    if (!result || !HASTZINFO(self))
-        return result;
-
-    /* We need to append the UTC offset. */
-    if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
-                         (PyObject *)self) < 0) {
-        Py_DECREF(result);
-        return NULL;
-    }
-    PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
-    return result;
-}
-
-static PyObject *
-datetime_ctime(PyDateTime_DateTime *self)
-{
-    return format_ctime((PyDateTime_Date *)self,
-                        DATE_GET_HOUR(self),
-                        DATE_GET_MINUTE(self),
-                        DATE_GET_SECOND(self));
-}
-
-/* Miscellaneous methods. */
-
-static PyObject *
-datetime_richcompare(PyObject *self, PyObject *other, int op)
-{
-    int diff;
-    naivety n1, n2;
-    int offset1, offset2;
-
-    if (! PyDateTime_Check(other)) {
-        if (PyDate_Check(other)) {
-            /* Prevent invocation of date_richcompare.  We want to
-               return NotImplemented here to give the other object
-               a chance.  But since DateTime is a subclass of
-               Date, if the other object is a Date, it would
-               compute an ordering based on the date part alone,
-               and we don't want that.  So force unequal or
-               uncomparable here in that case. */
-            if (op == Py_EQ)
-                Py_RETURN_FALSE;
-            if (op == Py_NE)
-                Py_RETURN_TRUE;
-            return cmperror(self, other);
-        }
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-
-    if (classify_two_utcoffsets(self, &offset1, &n1, self,
-                                other, &offset2, &n2, other) < 0)
-        return NULL;
-    assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
-    /* If they're both naive, or both aware and have the same offsets,
-     * we get off cheap.  Note that if they're both naive, offset1 ==
-     * offset2 == 0 at this point.
-     */
-    if (n1 == n2 && offset1 == offset2) {
-        diff = memcmp(((PyDateTime_DateTime *)self)->data,
-                      ((PyDateTime_DateTime *)other)->data,
-                      _PyDateTime_DATETIME_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-
-    if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
-        PyDateTime_Delta *delta;
-
-        assert(offset1 != offset2);             /* else last "if" handled it */
-        delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
-                                                       other);
-        if (delta == NULL)
-            return NULL;
-        diff = GET_TD_DAYS(delta);
-        if (diff == 0)
-            diff = GET_TD_SECONDS(delta) |
-                   GET_TD_MICROSECONDS(delta);
-        Py_DECREF(delta);
-        return diff_to_bool(diff, op);
-    }
-
-    assert(n1 != n2);
-    PyErr_SetString(PyExc_TypeError,
-                    "can't compare offset-naive and "
-                    "offset-aware datetimes");
-    return NULL;
-}
-
-static long
-datetime_hash(PyDateTime_DateTime *self)
-{
-    if (self->hashcode == -1) {
-        naivety n;
-        int offset;
-        PyObject *temp;
-
-        n = classify_utcoffset((PyObject *)self, (PyObject *)self,
-                               &offset);
-        assert(n != OFFSET_UNKNOWN);
-        if (n == OFFSET_ERROR)
-            return -1;
-
-        /* Reduce this to a hash of another object. */
-        if (n == OFFSET_NAIVE) {
-            self->hashcode = generic_hash(
-                (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
-            return self->hashcode;
-        }
-        else {
-            int days;
-            int seconds;
-
-            assert(n == OFFSET_AWARE);
-            assert(HASTZINFO(self));
-            days = ymd_to_ord(GET_YEAR(self),
-                              GET_MONTH(self),
-                              GET_DAY(self));
-            seconds = DATE_GET_HOUR(self) * 3600 +
-                      (DATE_GET_MINUTE(self) - offset) * 60 +
-                      DATE_GET_SECOND(self);
-            temp = new_delta(days,
-                             seconds,
-                             DATE_GET_MICROSECOND(self),
-                             1);
-        }
-        if (temp != NULL) {
-            self->hashcode = PyObject_Hash(temp);
-            Py_DECREF(temp);
-        }
-    }
-    return self->hashcode;
-}
-
-static PyObject *
-datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
-{
-    PyObject *clone;
-    PyObject *tuple;
-    int y = GET_YEAR(self);
-    int m = GET_MONTH(self);
-    int d = GET_DAY(self);
-    int hh = DATE_GET_HOUR(self);
-    int mm = DATE_GET_MINUTE(self);
-    int ss = DATE_GET_SECOND(self);
-    int us = DATE_GET_MICROSECOND(self);
-    PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
-                                      datetime_kws,
-                                      &y, &m, &d, &hh, &mm, &ss, &us,
-                                      &tzinfo))
-        return NULL;
-    tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
-    if (tuple == NULL)
-        return NULL;
-    clone = datetime_new(Py_TYPE(self), tuple, NULL);
-    Py_DECREF(tuple);
-    return clone;
-}
-
-static PyObject *
-datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
-{
-    int y, m, d, hh, mm, ss, us;
-    PyObject *result;
-    int offset, none;
-
-    PyObject *tzinfo;
-    static char *keywords[] = {"tz", NULL};
-
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
-                                      &PyDateTime_TZInfoType, &tzinfo))
-        return NULL;
-
-    if (!HASTZINFO(self) || self->tzinfo == Py_None)
-        goto NeedAware;
-
-    /* Conversion to self's own time zone is a NOP. */
-    if (self->tzinfo == tzinfo) {
-        Py_INCREF(self);
-        return (PyObject *)self;
-    }
-
-    /* Convert self to UTC. */
-    offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
-    if (offset == -1 && PyErr_Occurred())
-        return NULL;
-    if (none)
-        goto NeedAware;
-
-    y = GET_YEAR(self);
-    m = GET_MONTH(self);
-    d = GET_DAY(self);
-    hh = DATE_GET_HOUR(self);
-    mm = DATE_GET_MINUTE(self);
-    ss = DATE_GET_SECOND(self);
-    us = DATE_GET_MICROSECOND(self);
-
-    mm -= offset;
-    if ((mm < 0 || mm >= 60) &&
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
-        return NULL;
-
-    /* Attach new tzinfo and let fromutc() do the rest. */
-    result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
-    if (result != NULL) {
-        PyObject *temp = result;
-
-        result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
-        Py_DECREF(temp);
-    }
-    return result;
-
-NeedAware:
-    PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
-                                      "a naive datetime");
-    return NULL;
-}
-
-static PyObject *
-datetime_timetuple(PyDateTime_DateTime *self)
-{
-    int dstflag = -1;
-
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        int none;
-
-        dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
-        if (dstflag == -1 && PyErr_Occurred())
-            return NULL;
-
-        if (none)
-            dstflag = -1;
-        else if (dstflag != 0)
-            dstflag = 1;
-
-    }
-    return build_struct_time(GET_YEAR(self),
-                             GET_MONTH(self),
-                             GET_DAY(self),
-                             DATE_GET_HOUR(self),
-                             DATE_GET_MINUTE(self),
-                             DATE_GET_SECOND(self),
-                             dstflag);
-}
-
-static PyObject *
-datetime_getdate(PyDateTime_DateTime *self)
-{
-    return new_date(GET_YEAR(self),
-                    GET_MONTH(self),
-                    GET_DAY(self));
-}
-
-static PyObject *
-datetime_gettime(PyDateTime_DateTime *self)
-{
-    return new_time(DATE_GET_HOUR(self),
-                    DATE_GET_MINUTE(self),
-                    DATE_GET_SECOND(self),
-                    DATE_GET_MICROSECOND(self),
-                    Py_None);
-}
-
-static PyObject *
-datetime_gettimetz(PyDateTime_DateTime *self)
-{
-    return new_time(DATE_GET_HOUR(self),
-                    DATE_GET_MINUTE(self),
-                    DATE_GET_SECOND(self),
-                    DATE_GET_MICROSECOND(self),
-                    HASTZINFO(self) ? self->tzinfo : Py_None);
-}
-
-static PyObject *
-datetime_utctimetuple(PyDateTime_DateTime *self)
-{
-    int y = GET_YEAR(self);
-    int m = GET_MONTH(self);
-    int d = GET_DAY(self);
-    int hh = DATE_GET_HOUR(self);
-    int mm = DATE_GET_MINUTE(self);
-    int ss = DATE_GET_SECOND(self);
-    int us = 0;         /* microseconds are ignored in a timetuple */
-    int offset = 0;
-
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        int none;
-
-        offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
-        if (offset == -1 && PyErr_Occurred())
-            return NULL;
-    }
-    /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
-     * 0 in a UTC timetuple regardless of what dst() says.
-     */
-    if (offset) {
-        /* Subtract offset minutes & normalize. */
-        int stat;
-
-        mm -= offset;
-        stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
-        /* OverflowError may be raised in the edge cases. */
-        if (stat < 0)
-            return NULL;
-    }
-    return build_struct_time(y, m, d, hh, mm, ss, 0);
-}
-
-/* Pickle support, a simple use of __reduce__. */
-
-/* Let basestate be the non-tzinfo data string.
- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
- * So it's a tuple in any (non-error) case.
- * __getstate__ isn't exposed.
- */
-static PyObject *
-datetime_getstate(PyDateTime_DateTime *self)
-{
-    PyObject *basestate;
-    PyObject *result = NULL;
-
-    basestate = PyBytes_FromStringAndSize((char *)self->data,
-                                           _PyDateTime_DATETIME_DATASIZE);
-    if (basestate != NULL) {
-        if (! HASTZINFO(self) || self->tzinfo == Py_None)
-            result = PyTuple_Pack(1, basestate);
-        else
-            result = PyTuple_Pack(2, basestate, self->tzinfo);
-        Py_DECREF(basestate);
-    }
-    return result;
-}
-
-static PyObject *
-datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
-{
-    return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
-}
-
-static PyMethodDef datetime_methods[] = {
-
-    /* Class methods: */
-
-    {"now",         (PyCFunction)datetime_now,
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,
-     PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
-
-    {"utcnow",         (PyCFunction)datetime_utcnow,
-     METH_NOARGS | METH_CLASS,
-     PyDoc_STR("Return a new datetime representing UTC day and time.")},
-
-    {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,
-     PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
-
-    {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
-     METH_VARARGS | METH_CLASS,
-     PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
-               "(like time.time()).")},
-
-    {"strptime", (PyCFunction)datetime_strptime,
-     METH_VARARGS | METH_CLASS,
-     PyDoc_STR("string, format -> new datetime parsed from a string "
-               "(like time.strptime()).")},
-
-    {"combine", (PyCFunction)datetime_combine,
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,
-     PyDoc_STR("date, time -> datetime with same date and time fields")},
-
-    /* Instance methods: */
-
-    {"date",   (PyCFunction)datetime_getdate, METH_NOARGS,
-     PyDoc_STR("Return date object with same year, month and day.")},
-
-    {"time",   (PyCFunction)datetime_gettime, METH_NOARGS,
-     PyDoc_STR("Return time object with same time but with tzinfo=None.")},
-
-    {"timetz",   (PyCFunction)datetime_gettimetz, METH_NOARGS,
-     PyDoc_STR("Return time object with same time and tzinfo.")},
-
-    {"ctime",       (PyCFunction)datetime_ctime,        METH_NOARGS,
-     PyDoc_STR("Return ctime() style string.")},
-
-    {"timetuple",   (PyCFunction)datetime_timetuple, METH_NOARGS,
-     PyDoc_STR("Return time tuple, compatible with time.localtime().")},
-
-    {"utctimetuple",   (PyCFunction)datetime_utctimetuple, METH_NOARGS,
-     PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
-
-    {"isoformat",   (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("[sep] -> string in ISO 8601 format, "
-               "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
-               "sep is used to separate the year from the time, and "
-               "defaults to 'T'.")},
-
-    {"utcoffset",       (PyCFunction)datetime_utcoffset, METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
-
-    {"tzname",          (PyCFunction)datetime_tzname,   METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.tzname(self).")},
-
-    {"dst",             (PyCFunction)datetime_dst, METH_NOARGS,
-     PyDoc_STR("Return self.tzinfo.dst(self).")},
-
-    {"replace",     (PyCFunction)datetime_replace,      METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("Return datetime with new specified fields.")},
-
-    {"astimezone",  (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
-     PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
-
-    {"__reduce__", (PyCFunction)datetime_reduce,     METH_NOARGS,
-     PyDoc_STR("__reduce__() -> (cls, state)")},
-
-    {NULL,      NULL}
-};
-
-static char datetime_doc[] =
-PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
-\n\
-The year, month and day arguments are required. tzinfo may be None, or an\n\
-instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
-
-static PyNumberMethods datetime_as_number = {
-    datetime_add,                               /* nb_add */
-    datetime_subtract,                          /* nb_subtract */
-    0,                                          /* nb_multiply */
-    0,                                          /* nb_remainder */
-    0,                                          /* nb_divmod */
-    0,                                          /* nb_power */
-    0,                                          /* nb_negative */
-    0,                                          /* nb_positive */
-    0,                                          /* nb_absolute */
-    0,                                          /* nb_bool */
-};
-
-static PyTypeObject PyDateTime_DateTimeType = {
-    PyVarObject_HEAD_INIT(NULL, 0)
-    "datetime.datetime",                        /* tp_name */
-    sizeof(PyDateTime_DateTime),                /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    (destructor)datetime_dealloc,               /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    (reprfunc)datetime_repr,                    /* tp_repr */
-    &datetime_as_number,                        /* tp_as_number */
-    0,                                          /* tp_as_sequence */
-    0,                                          /* tp_as_mapping */
-    (hashfunc)datetime_hash,                    /* tp_hash */
-    0,                                          /* tp_call */
-    (reprfunc)datetime_str,                     /* tp_str */
-    PyObject_GenericGetAttr,                    /* tp_getattro */
-    0,                                          /* tp_setattro */
-    0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
-    datetime_doc,                               /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    datetime_richcompare,                       /* tp_richcompare */
-    0,                                          /* tp_weaklistoffset */
-    0,                                          /* tp_iter */
-    0,                                          /* tp_iternext */
-    datetime_methods,                           /* tp_methods */
-    0,                                          /* tp_members */
-    datetime_getset,                            /* tp_getset */
-    &PyDateTime_DateType,                       /* tp_base */
-    0,                                          /* tp_dict */
-    0,                                          /* tp_descr_get */
-    0,                                          /* tp_descr_set */
-    0,                                          /* tp_dictoffset */
-    0,                                          /* tp_init */
-    datetime_alloc,                             /* tp_alloc */
-    datetime_new,                               /* tp_new */
-    0,                                          /* tp_free */
-};
-
-/* ---------------------------------------------------------------------------
- * Module methods and initialization.
- */
-
-static PyMethodDef module_methods[] = {
-    {NULL, NULL}
-};
-
-/* C API.  Clients get at this via PyDateTime_IMPORT, defined in
- * datetime.h.
- */
-static PyDateTime_CAPI CAPI = {
-    &PyDateTime_DateType,
-    &PyDateTime_DateTimeType,
-    &PyDateTime_TimeType,
-    &PyDateTime_DeltaType,
-    &PyDateTime_TZInfoType,
-    new_date_ex,
-    new_datetime_ex,
-    new_time_ex,
-    new_delta_ex,
-    datetime_fromtimestamp,
-    date_fromtimestamp
-};
-
-
-
-static struct PyModuleDef datetimemodule = {
-    PyModuleDef_HEAD_INIT,
-    "datetime",
-    "Fast implementation of the datetime type.",
-    -1,
-    module_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit_datetime(void)
-{
-    PyObject *m;        /* a module object */
-    PyObject *d;        /* its dict */
-    PyObject *x;
-    PyObject *delta;
-
-    m = PyModule_Create(&datetimemodule);
-    if (m == NULL)
-        return NULL;
-
-    if (PyType_Ready(&PyDateTime_DateType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_DeltaType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_TimeType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
-        return NULL;
-    if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
-        return NULL;
-
-    /* timedelta values */
-    d = PyDateTime_DeltaType.tp_dict;
-
-    x = new_delta(0, 0, 1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* date values */
-    d = PyDateTime_DateType.tp_dict;
-
-    x = new_date(1, 1, 1);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_date(MAXYEAR, 12, 31);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(1, 0, 0, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* time values */
-    d = PyDateTime_TimeType.tp_dict;
-
-    x = new_time(0, 0, 0, 0, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_time(23, 59, 59, 999999, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(0, 0, 1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* datetime values */
-    d = PyDateTime_DateTimeType.tp_dict;
-
-    x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    x = new_delta(0, 0, 1, 0);
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* timezone values */
-    d = PyDateTime_TimeZoneType.tp_dict;
-
-    delta = new_delta(0, 0, 0, 0);
-    if (delta == NULL)
-        return NULL;
-    x = new_timezone(delta, NULL);
-    Py_DECREF(delta);
-    if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    delta = new_delta(-1, 60, 0, 1); /* -23:59 */
-    if (delta == NULL)
-        return NULL;
-    x = new_timezone(delta, NULL);
-    Py_DECREF(delta);
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
-    if (delta == NULL)
-        return NULL;
-    x = new_timezone(delta, NULL);
-    Py_DECREF(delta);
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
-        return NULL;
-    Py_DECREF(x);
-
-    /* module initialization */
-    PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
-    PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
-
-    Py_INCREF(&PyDateTime_DateType);
-    PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
-
-    Py_INCREF(&PyDateTime_DateTimeType);
-    PyModule_AddObject(m, "datetime",
-                       (PyObject *)&PyDateTime_DateTimeType);
-
-    Py_INCREF(&PyDateTime_TimeType);
-    PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
-
-    Py_INCREF(&PyDateTime_DeltaType);
-    PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
-
-    Py_INCREF(&PyDateTime_TZInfoType);
-    PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
-
-    Py_INCREF(&PyDateTime_TimeZoneType);
-    PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
-
-    x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
-    if (x == NULL)
-        return NULL;
-    PyModule_AddObject(m, "datetime_CAPI", x);
-
-    /* A 4-year cycle has an extra leap day over what we'd get from
-     * pasting together 4 single years.
-     */
-    assert(DI4Y == 4 * 365 + 1);
-    assert(DI4Y == days_before_year(4+1));
-
-    /* Similarly, a 400-year cycle has an extra leap day over what we'd
-     * get from pasting together 4 100-year cycles.
-     */
-    assert(DI400Y == 4 * DI100Y + 1);
-    assert(DI400Y == days_before_year(400+1));
-
-    /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
-     * pasting together 25 4-year cycles.
-     */
-    assert(DI100Y == 25 * DI4Y - 1);
-    assert(DI100Y == days_before_year(100+1));
-
-    us_per_us = PyLong_FromLong(1);
-    us_per_ms = PyLong_FromLong(1000);
-    us_per_second = PyLong_FromLong(1000000);
-    us_per_minute = PyLong_FromLong(60000000);
-    seconds_per_day = PyLong_FromLong(24 * 3600);
-    if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
-        us_per_minute == NULL || seconds_per_day == NULL)
-        return NULL;
-
-    /* The rest are too big for 32-bit ints, but even
-     * us_per_week fits in 40 bits, so doubles should be exact.
-     */
-    us_per_hour = PyLong_FromDouble(3600000000.0);
-    us_per_day = PyLong_FromDouble(86400000000.0);
-    us_per_week = PyLong_FromDouble(604800000000.0);
-    if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
-        return NULL;
-    return m;
-}
-
-/* ---------------------------------------------------------------------------
-Some time zone algebra.  For a datetime x, let
-    x.n = x stripped of its timezone -- its naive time.
-    x.o = x.utcoffset(), and assuming that doesn't raise an exception or
-      return None
-    x.d = x.dst(), and assuming that doesn't raise an exception or
-      return None
-    x.s = x's standard offset, x.o - x.d
-
-Now some derived rules, where k is a duration (timedelta).
-
-1. x.o = x.s + x.d
-   This follows from the definition of x.s.
-
-2. If x and y have the same tzinfo member, x.s = y.s.
-   This is actually a requirement, an assumption we need to make about
-   sane tzinfo classes.
-
-3. The naive UTC time corresponding to x is x.n - x.o.
-   This is again a requirement for a sane tzinfo class.
-
-4. (x+k).s = x.s
-   This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
-
-5. (x+k).n = x.n + k
-   Again follows from how arithmetic is defined.
-
-Now we can explain tz.fromutc(x).  Let's assume it's an interesting case
-(meaning that the various tzinfo methods exist, and don't blow up or return
-None when called).
-
-The function wants to return a datetime y with timezone tz, equivalent to x.
-x is already in UTC.
-
-By #3, we want
-
-    y.n - y.o = x.n                             [1]
-
-The algorithm starts by attaching tz to x.n, and calling that y.  So
-x.n = y.n at the start.  Then it wants to add a duration k to y, so that [1]
-becomes true; in effect, we want to solve [2] for k:
-
-   (y+k).n - (y+k).o = x.n                      [2]
-
-By #1, this is the same as
-
-   (y+k).n - ((y+k).s + (y+k).d) = x.n          [3]
-
-By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
-Substituting that into [3],
-
-   x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
-   k - (y+k).s - (y+k).d = 0; rearranging,
-   k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
-   k = y.s - (y+k).d
-
-On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
-approximate k by ignoring the (y+k).d term at first.  Note that k can't be
-very large, since all offset-returning methods return a duration of magnitude
-less than 24 hours.  For that reason, if y is firmly in std time, (y+k).d must
-be 0, so ignoring it has no consequence then.
-
-In any case, the new value is
-
-    z = y + y.s                                 [4]
-
-It's helpful to step back at look at [4] from a higher level:  it's simply
-mapping from UTC to tz's standard time.
-
-At this point, if
-
-    z.n - z.o = x.n                             [5]
-
-we have an equivalent time, and are almost done.  The insecurity here is
-at the start of daylight time.  Picture US Eastern for concreteness.  The wall
-time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
-sense then.  The docs ask that an Eastern tzinfo class consider such a time to
-be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
-on the day DST starts.  We want to return the 1:MM EST spelling because that's
-the only spelling that makes sense on the local wall clock.
-
-In fact, if [5] holds at this point, we do have the standard-time spelling,
-but that takes a bit of proof.  We first prove a stronger result.  What's the
-difference between the LHS and RHS of [5]?  Let
-
-    diff = x.n - (z.n - z.o)                    [6]
-
-Now
-    z.n =                       by [4]
-    (y + y.s).n =               by #5
-    y.n + y.s =                 since y.n = x.n
-    x.n + y.s =                 since z and y are have the same tzinfo member,
-                                    y.s = z.s by #2
-    x.n + z.s
-
-Plugging that back into [6] gives
-
-    diff =
-    x.n - ((x.n + z.s) - z.o) =     expanding
-    x.n - x.n - z.s + z.o =         cancelling
-    - z.s + z.o =                   by #2
-    z.d
-
-So diff = z.d.
-
-If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
-spelling we wanted in the endcase described above.  We're done.  Contrarily,
-if z.d = 0, then we have a UTC equivalent, and are also done.
-
-If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
-add to z (in effect, z is in tz's standard time, and we need to shift the
-local clock into tz's daylight time).
-
-Let
-
-    z' = z + z.d = z + diff                     [7]
-
-and we can again ask whether
-
-    z'.n - z'.o = x.n                           [8]
-
-If so, we're done.  If not, the tzinfo class is insane, according to the
-assumptions we've made.  This also requires a bit of proof.  As before, let's
-compute the difference between the LHS and RHS of [8] (and skipping some of
-the justifications for the kinds of substitutions we've done several times
-already):
-
-    diff' = x.n - (z'.n - z'.o) =           replacing z'.n via [7]
-        x.n  - (z.n + diff - z'.o) =    replacing diff via [6]
-        x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
-        x.n - z.n - x.n + z.n - z.o + z'.o =    cancel x.n
-        - z.n + z.n - z.o + z'.o =              cancel z.n
-        - z.o + z'.o =                      #1 twice
-        -z.s - z.d + z'.s + z'.d =          z and z' have same tzinfo
-        z'.d - z.d
-
-So z' is UTC-equivalent to x iff z'.d = z.d at this point.  If they are equal,
-we've found the UTC-equivalent so are done.  In fact, we stop with [7] and
-return z', not bothering to compute z'.d.
-
-How could z.d and z'd differ?  z' = z + z.d [7], so merely moving z' by
-a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
-would have to change the result dst() returns:  we start in DST, and moving
-a little further into it takes us out of DST.
-
-There isn't a sane case where this can happen.  The closest it gets is at
-the end of DST, where there's an hour in UTC with no spelling in a hybrid
-tzinfo class.  In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT.  During
-that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
-UTC) because the docs insist on that, but 0:MM is taken as being in daylight
-time (4:MM UTC).  There is no local time mapping to 5:MM UTC.  The local
-clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
-standard time.  Since that's what the local clock *does*, we want to map both
-UTC hours 5:MM and 6:MM to 1:MM Eastern.  The result is ambiguous
-in local time, but so it goes -- it's the way the local clock works.
-
-When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
-so z=0:MM.  z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
-z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
-(correctly) concludes that z' is not UTC-equivalent to x.
-
-Because we know z.d said z was in daylight time (else [5] would have held and
-we would have stopped then), and we know z.d != z'.d (else [8] would have held
-and we would have stopped then), and there are only 2 possible values dst() can
-return in Eastern, it follows that z'.d must be 0 (which it is in the example,
-but the reasoning doesn't depend on the example -- it depends on there being
-two possible dst() outcomes, one zero and the other non-zero).  Therefore
-z' must be in standard time, and is the spelling we want in this case.
-
-Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
-concerned (because it takes z' as being in standard time rather than the
-daylight time we intend here), but returning it gives the real-life "local
-clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
-tz.
-
-When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
-the 1:MM standard time spelling we want.
-
-So how can this break?  One of the assumptions must be violated.  Two
-possibilities:
-
-1) [2] effectively says that y.s is invariant across all y belong to a given
-   time zone.  This isn't true if, for political reasons or continental drift,
-   a region decides to change its base offset from UTC.
-
-2) There may be versions of "double daylight" time where the tail end of
-   the analysis gives up a step too early.  I haven't thought about that
-   enough to say.
-
-In any case, it's clear that the default fromutc() is strong enough to handle
-"almost all" time zones:  so long as the standard offset is invariant, it
-doesn't matter if daylight time transition points change from year to year, or
-if daylight time is skipped in some years; it doesn't matter how large or
-small dst() may get within its bounds; and it doesn't even matter if some
-perverse time zone returns a negative dst()).  So a breaking case must be
-pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
---------------------------------------------------------------------------- */

Modified: python/branches/py3k-dtoa/Modules/getpath.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/getpath.c	(original)
+++ python/branches/py3k-dtoa/Modules/getpath.c	Sun Aug  8 12:41:24 2010
@@ -552,7 +552,7 @@
         if (!ismodule(argv0_path)) {
                 /* We are in the build directory so use the name of the
                    executable - we know that the absolute path is passed */
-                wcsncpy(argv0_path, prog, MAXPATHLEN);
+                wcsncpy(argv0_path, progpath, MAXPATHLEN);
         }
         else {
                 /* Use the location of the library as the progpath */

Modified: python/branches/py3k-dtoa/Modules/main.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/main.c	(original)
+++ python/branches/py3k-dtoa/Modules/main.c	Sun Aug  8 12:41:24 2010
@@ -253,6 +253,62 @@
     }
 }
 
+static int
+run_command(wchar_t *command, PyCompilerFlags *cf)
+{
+    PyObject *unicode, *bytes;
+    int ret;
+
+    unicode = PyUnicode_FromWideChar(command, -1);
+    if (unicode == NULL)
+        goto error;
+    bytes = PyUnicode_AsUTF8String(unicode);
+    Py_DECREF(unicode);
+    if (bytes == NULL)
+        goto error;
+    ret = PyRun_SimpleStringFlags(PyBytes_AsString(bytes), cf);
+    Py_DECREF(bytes);
+    return ret != 0;
+
+error:
+    PyErr_Print();
+    return 1;
+}
+
+static int
+run_file(FILE *fp, const wchar_t *filename, PyCompilerFlags *p_cf)
+{
+    PyObject *unicode, *bytes = NULL;
+    char *filename_str;
+    int run;
+
+    /* call pending calls like signal handlers (SIGINT) */
+    if (Py_MakePendingCalls() == -1) {
+        PyErr_Print();
+        return 1;
+    }
+
+    if (filename) {
+        unicode = PyUnicode_FromWideChar(filename, wcslen(filename));
+        if (unicode != NULL) {
+            bytes = PyUnicode_AsUTF8String(unicode);
+            Py_DECREF(unicode);
+        }
+        if (bytes != NULL)
+            filename_str = PyBytes_AsString(bytes);
+        else {
+            PyErr_Clear();
+            filename_str = "<decoding error>";
+        }
+    }
+    else
+        filename_str = "<stdin>";
+
+    run = PyRun_AnyFileExFlags(fp, filename_str, filename != NULL, p_cf);
+    Py_XDECREF(bytes);
+    return run != 0;
+}
+
 
 /* Main program */
 
@@ -564,22 +620,8 @@
     }
 
     if (command) {
-        char *commandStr;
-        PyObject *commandObj = PyUnicode_FromWideChar(
-            command, wcslen(command));
+        sts = run_command(command, &cf);
         free(command);
-        if (commandObj != NULL)
-            commandStr = _PyUnicode_AsString(commandObj);
-        else
-            commandStr = NULL;
-        if (commandStr != NULL) {
-            sts = PyRun_SimpleStringFlags(commandStr, &cf) != 0;
-            Py_DECREF(commandObj);
-        }
-        else {
-            PyErr_Print();
-            sts = 1;
-        }
     } else if (module) {
         sts = RunModule(module, 1);
     }
@@ -636,30 +678,8 @@
             }
         }
 
-        if (sts==-1) {
-            PyObject *filenameObj = NULL;
-            char *p_cfilename = "<stdin>";
-            if (filename) {
-                filenameObj = PyUnicode_FromWideChar(
-                    filename, wcslen(filename));
-                if (filenameObj != NULL)
-                    p_cfilename = _PyUnicode_AsString(filenameObj);
-                else
-                    p_cfilename = "<decoding error>";
-            }
-            /* call pending calls like signal handlers (SIGINT) */
-            if (Py_MakePendingCalls() == -1) {
-                PyErr_Print();
-                sts = 1;
-            } else {
-                sts = PyRun_AnyFileExFlags(
-                    fp,
-                    p_cfilename,
-                    filename != NULL, &cf) != 0;
-            }
-            Py_XDECREF(filenameObj);
-        }
-
+        if (sts == -1)
+            sts = run_file(fp, filename, &cf);
     }
 
     /* Check this environment variable at the end, to give programs the

Modified: python/branches/py3k-dtoa/Modules/makesetup
==============================================================================
--- python/branches/py3k-dtoa/Modules/makesetup	(original)
+++ python/branches/py3k-dtoa/Modules/makesetup	Sun Aug  8 12:41:24 2010
@@ -219,7 +219,7 @@
 			case $doconfig in
 			no)	cc="$cc \$(CCSHARED) \$(CFLAGS) \$(CPPFLAGS)";;
 			*)
-				cc="$cc \$(PY_CFLAGS)";;
+				cc="$cc \$(PY_CORE_CFLAGS)";;
 			esac
 			rule="$obj: $src; $cc $cpps -c $src -o $obj"
 			echo "$rule" >>$rulesf

Modified: python/branches/py3k-dtoa/Modules/mathmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/mathmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/mathmodule.c	Sun Aug  8 12:41:24 2010
@@ -69,6 +69,7 @@
 
 static const double pi = 3.141592653589793238462643383279502884197;
 static const double sqrtpi = 1.772453850905516027298167483341145182798;
+static const double logpi = 1.144729885849400174143427351353058711647;
 
 static double
 sinpi(double x)
@@ -356,20 +357,15 @@
     if (absx < 1e-20)
         return -log(absx);
 
-    /* Lanczos' formula */
-    if (x > 0.0) {
-        /* we could save a fraction of a ulp in accuracy by having a
-           second set of numerator coefficients for lanczos_sum that
-           absorbed the exp(-lanczos_g) term, and throwing out the
-           lanczos_g subtraction below; it's probably not worth it. */
-        r = log(lanczos_sum(x)) - lanczos_g +
-            (x-0.5)*(log(x+lanczos_g-0.5)-1);
-    }
-    else {
-        r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
-            (log(lanczos_sum(absx)) - lanczos_g +
-             (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
-    }
+    /* Lanczos' formula.  We could save a fraction of a ulp in accuracy by
+       having a second set of numerator coefficients for lanczos_sum that
+       absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
+       subtraction below; it's probably not worth it. */
+    r = log(lanczos_sum(absx)) - lanczos_g;
+    r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
+    if (x < 0.0)
+        /* Use reflection formula to get value for negative x. */
+        r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
     if (Py_IS_INFINITY(r))
         errno = ERANGE;
     return r;
@@ -900,7 +896,7 @@
       "gamma(x)\n\nGamma function at x.")
 FUNC1A(lgamma, m_lgamma,
       "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
-FUNC1(log1p, m_log1p, 1,
+FUNC1(log1p, m_log1p, 0,
       "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
       "The result is computed in a way which is accurate for x near zero.")
 FUNC1(sin, sin, 0,
@@ -1174,7 +1170,7 @@
  * http://www.luschny.de/math/factorial/binarysplitfact.html
  *
  * Faster algorithms exist, but they're more complicated and depend on
- * a fast prime factoriazation algorithm.
+ * a fast prime factorization algorithm.
  *
  * Notes on the algorithm
  * ----------------------
@@ -1822,6 +1818,19 @@
 Convert angle x from degrees to radians.");
 
 static PyObject *
+math_isfinite(PyObject *self, PyObject *arg)
+{
+    double x = PyFloat_AsDouble(arg);
+    if (x == -1.0 && PyErr_Occurred())
+        return NULL;
+    return PyBool_FromLong((long)Py_IS_FINITE(x));
+}
+
+PyDoc_STRVAR(math_isfinite_doc,
+"isfinite(x) -> bool\n\n\
+Return True if x is neither an infinity nor a NaN, and False otherwise.");
+
+static PyObject *
 math_isnan(PyObject *self, PyObject *arg)
 {
     double x = PyFloat_AsDouble(arg);
@@ -1832,7 +1841,7 @@
 
 PyDoc_STRVAR(math_isnan_doc,
 "isnan(x) -> bool\n\n\
-Check if float x is not a number (NaN).");
+Return True if x is a NaN (not a number), and False otherwise.");
 
 static PyObject *
 math_isinf(PyObject *self, PyObject *arg)
@@ -1845,7 +1854,7 @@
 
 PyDoc_STRVAR(math_isinf_doc,
 "isinf(x) -> bool\n\n\
-Check if float x is infinite (positive or negative).");
+Return True if x is a positive or negative infinity, and False otherwise.");
 
 static PyMethodDef math_methods[] = {
     {"acos",            math_acos,      METH_O,         math_acos_doc},
@@ -1872,6 +1881,7 @@
     {"fsum",            math_fsum,      METH_O,         math_fsum_doc},
     {"gamma",           math_gamma,     METH_O,         math_gamma_doc},
     {"hypot",           math_hypot,     METH_VARARGS,   math_hypot_doc},
+    {"isfinite",        math_isfinite,  METH_O,         math_isfinite_doc},
     {"isinf",           math_isinf,     METH_O,         math_isinf_doc},
     {"isnan",           math_isnan,     METH_O,         math_isnan_doc},
     {"ldexp",           math_ldexp,     METH_VARARGS,   math_ldexp_doc},

Modified: python/branches/py3k-dtoa/Modules/mmapmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/mmapmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/mmapmodule.c	Sun Aug  8 12:41:24 2010
@@ -651,6 +651,31 @@
     }
 }
 
+static PyObject *
+mmap_closed_get(mmap_object *self)
+{
+#ifdef MS_WINDOWS
+    return PyBool_FromLong(self->map_handle == NULL ? 1 : 0);
+#elif defined(UNIX)
+    return PyBool_FromLong(self->data == NULL ? 1 : 0);
+#endif
+}
+
+static PyObject *
+mmap__enter__method(mmap_object *self, PyObject *args)
+{
+    CHECK_VALID(NULL);
+
+    Py_INCREF(self);
+    return (PyObject *)self;
+}
+
+static PyObject *
+mmap__exit__method(PyObject *self, PyObject *args)
+{
+    return PyObject_CallMethod(self, "close", NULL);
+}
+
 static struct PyMethodDef mmap_object_methods[] = {
     {"close",           (PyCFunction) mmap_close_method,        METH_NOARGS},
     {"find",            (PyCFunction) mmap_find_method,         METH_VARARGS},
@@ -666,9 +691,17 @@
     {"tell",            (PyCFunction) mmap_tell_method,         METH_NOARGS},
     {"write",           (PyCFunction) mmap_write_method,        METH_VARARGS},
     {"write_byte",      (PyCFunction) mmap_write_byte_method,   METH_VARARGS},
+    {"__enter__",       (PyCFunction) mmap__enter__method,      METH_NOARGS},
+    {"__exit__",        (PyCFunction) mmap__exit__method,       METH_VARARGS},
     {NULL,         NULL}       /* sentinel */
 };
 
+static PyGetSetDef mmap_object_getset[] = {
+    {"closed", (getter) mmap_closed_get, NULL, NULL},
+    {NULL}
+};
+
+
 /* Functions for treating an mmap'ed file as a buffer */
 
 static int
@@ -975,7 +1008,7 @@
     0,                                          /* tp_iternext */
     mmap_object_methods,                        /* tp_methods */
     0,                                          /* tp_members */
-    0,                                          /* tp_getset */
+    mmap_object_getset,                         /* tp_getset */
     0,                                          /* tp_base */
     0,                                          /* tp_dict */
     0,                                          /* tp_descr_get */
@@ -1203,6 +1236,11 @@
                      1);
      */
     if (fileno != -1 && fileno != 0) {
+        /* Ensure that fileno is within the CRT's valid range */
+        if (_PyVerify_fd(fileno) == 0) {
+            PyErr_SetFromErrno(mmap_module_error);
+            return NULL;
+        }
         fh = (HANDLE)_get_osfhandle(fileno);
         if (fh==(HANDLE)-1) {
             PyErr_SetFromErrno(mmap_module_error);

Modified: python/branches/py3k-dtoa/Modules/posixmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/posixmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/posixmodule.c	Sun Aug  8 12:41:24 2010
@@ -262,6 +262,15 @@
 #ifdef HAVE_PROCESS_H
 #include <process.h>
 #endif
+#ifndef VOLUME_NAME_DOS
+#define VOLUME_NAME_DOS	0x0
+#endif
+#ifndef VOLUME_NAME_NT
+#define VOLUME_NAME_NT	0x2
+#endif
+#ifndef IO_REPARSE_TAG_SYMLINK
+#define IO_REPARSE_TAG_SYMLINK	(0xA000000CL)
+#endif
 #include "osdefs.h"
 #include <malloc.h>
 #include <windows.h>
@@ -571,7 +580,7 @@
 
 #ifdef MS_WINDOWS
 static PyObject *
-win32_error(char* function, char* filename)
+win32_error(char* function, const char* filename)
 {
     /* XXX We should pass the function name along in the future.
        (winreg.c also wants to pass the function name.)
@@ -978,12 +987,28 @@
     return TRUE;
 }
 
-static int
-win32_stat(const char* path, struct win32_stat *result)
+/* About the following functions: win32_lstat, win32_lstat_w, win32_stat,
+   win32_stat_w
+
+   In Posix, stat automatically traverses symlinks and returns the stat
+   structure for the target.  In Windows, the equivalent GetFileAttributes by
+   default does not traverse symlinks and instead returns attributes for
+   the symlink.
+
+   Therefore, win32_lstat will get the attributes traditionally, and
+   win32_stat will first explicitly resolve the symlink target and then will
+   call win32_lstat on that result.
+
+   The _w represent Unicode equivalents of the aformentioned ANSI functions. */
+
+static int 
+win32_lstat(const char* path, struct win32_stat *result)
 {
     WIN32_FILE_ATTRIBUTE_DATA info;
     int code;
     char *dot;
+    WIN32_FIND_DATAA find_data;
+    HANDLE find_data_handle;
     if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
         if (GetLastError() != ERROR_SHARING_VIOLATION) {
             /* Protocol violation: we explicitly clear errno, instead of
@@ -1000,27 +1025,44 @@
             }
         }
     }
+
     code = attribute_data_to_stat(&info, result);
     if (code != 0)
         return code;
+
+    /* Get WIN32_FIND_DATA structure for the path to determine if
+       it is a symlink */
+    if(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+        find_data_handle = FindFirstFileA(path, &find_data);
+        if(find_data_handle != INVALID_HANDLE_VALUE) {
+            if(find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) {
+                /* first clear the S_IFMT bits */
+                result->st_mode ^= (result->st_mode & 0170000);
+                /* now set the bits that make this a symlink */
+                result->st_mode |= 0120000;
+            }
+            FindClose(find_data_handle);
+        }
+    }
+
     /* Set S_IFEXEC if it is an .exe, .bat, ... */
     dot = strrchr(path, '.');
     if (dot) {
-        if (stricmp(dot, ".bat") == 0 ||
-        stricmp(dot, ".cmd") == 0 ||
-        stricmp(dot, ".exe") == 0 ||
-        stricmp(dot, ".com") == 0)
+        if (stricmp(dot, ".bat") == 0 || stricmp(dot, ".cmd") == 0 ||
+            stricmp(dot, ".exe") == 0 || stricmp(dot, ".com") == 0)
             result->st_mode |= 0111;
     }
     return code;
 }
 
 static int
-win32_wstat(const wchar_t* path, struct win32_stat *result)
+win32_lstat_w(const wchar_t* path, struct win32_stat *result)
 {
     int code;
     const wchar_t *dot;
     WIN32_FILE_ATTRIBUTE_DATA info;
+    WIN32_FIND_DATAW find_data;
+    HANDLE find_data_handle;
     if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
         if (GetLastError() != ERROR_SHARING_VIOLATION) {
             /* Protocol violation: we explicitly clear errno, instead of
@@ -1028,8 +1070,8 @@
             errno = 0;
             return -1;
         } else {
-            /* Could not get attributes on open file. Fall back to
-               reading the directory. */
+            /* Could not get attributes on open file. Fall back to reading
+            the directory. */
             if (!attributes_from_dir_w(path, &info)) {
                 /* Very strange. This should not fail now */
                 errno = 0;
@@ -1040,18 +1082,199 @@
     code = attribute_data_to_stat(&info, result);
     if (code < 0)
         return code;
+
+    /* Get WIN32_FIND_DATA structure for the path to determine if
+       it is a symlink */
+    if(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+        find_data_handle = FindFirstFileW(path, &find_data);
+        if(find_data_handle != INVALID_HANDLE_VALUE) {
+            if(find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) {
+                /* first clear the S_IFMT bits */
+                result->st_mode ^= (result->st_mode & 0170000);
+                /* now set the bits that make this a symlink */
+                result->st_mode |= 0120000;
+            }
+            FindClose(find_data_handle);
+        }
+    }
+
     /* Set IFEXEC if it is an .exe, .bat, ... */
     dot = wcsrchr(path, '.');
     if (dot) {
-        if (_wcsicmp(dot, L".bat") == 0 ||
-            _wcsicmp(dot, L".cmd") == 0 ||
-            _wcsicmp(dot, L".exe") == 0 ||
-            _wcsicmp(dot, L".com") == 0)
+        if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
+            _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
             result->st_mode |= 0111;
     }
     return code;
 }
 
+/* Grab GetFinalPathNameByHandle dynamically from kernel32 */
+static int has_GetFinalPathNameByHandle = 0;
+static DWORD (CALLBACK *Py_GetFinalPathNameByHandleA)(HANDLE, LPSTR, DWORD,
+                                                      DWORD);
+static DWORD (CALLBACK *Py_GetFinalPathNameByHandleW)(HANDLE, LPWSTR, DWORD,
+                                                      DWORD);
+static int
+check_GetFinalPathNameByHandle()
+{
+    HINSTANCE hKernel32;
+    /* only recheck */
+    if (!has_GetFinalPathNameByHandle)
+    {
+        hKernel32 = GetModuleHandle("KERNEL32");
+        *(FARPROC*)&Py_GetFinalPathNameByHandleA = GetProcAddress(hKernel32,
+                                                "GetFinalPathNameByHandleA");
+        *(FARPROC*)&Py_GetFinalPathNameByHandleW = GetProcAddress(hKernel32,
+                                                "GetFinalPathNameByHandleW");
+        has_GetFinalPathNameByHandle = Py_GetFinalPathNameByHandleA &&
+                                       Py_GetFinalPathNameByHandleW;
+    }
+    return has_GetFinalPathNameByHandle;
+}
+
+static int
+win32_stat(const char* path, struct win32_stat *result)
+{
+    /* Traverse the symlink to the target using
+    GetFinalPathNameByHandle()
+    */
+    int code;
+    HANDLE hFile;
+    int buf_size;
+    char *target_path;
+    int result_length;
+    WIN32_FILE_ATTRIBUTE_DATA info;
+    
+    if(!check_GetFinalPathNameByHandle()) {
+        /* if the OS doesn't have GetFinalPathNameByHandle, it doesn't
+           have symlinks, so just fall back to the traditional behavior
+           found in lstat. */
+        return win32_lstat(path, result);
+    }
+
+    hFile = CreateFileA(
+        path,
+        0, /* desired access */
+        0, /* share mode */
+        NULL, /* security attributes */
+        OPEN_EXISTING,
+        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
+        FILE_FLAG_BACKUP_SEMANTICS,
+        NULL);
+    
+    if(hFile == INVALID_HANDLE_VALUE) {
+        /* Either the target doesn't exist, or we don't have access to
+           get a handle to it. If the former, we need to return an error.
+           If the latter, we can use attributes_from_dir. */
+        if (GetLastError() != ERROR_SHARING_VIOLATION) {
+            /* Protocol violation: we explicitly clear errno, instead of
+               setting it to a POSIX error. Callers should use GetLastError. */
+            errno = 0;
+            return -1;
+        } else {
+            /* Could not get attributes on open file. Fall back to
+               reading the directory. */
+            if (!attributes_from_dir(path, &info)) {
+                /* Very strange. This should not fail now */
+                errno = 0;
+                return -1;
+            }
+        }
+        code = attribute_data_to_stat(&info, result);
+    }
+    
+    buf_size = Py_GetFinalPathNameByHandleA(hFile, 0, 0, VOLUME_NAME_DOS);
+    if(!buf_size) return -1;
+    target_path = (char *)malloc((buf_size+1)*sizeof(char));
+    result_length = Py_GetFinalPathNameByHandleA(hFile, target_path,
+                                                 buf_size, VOLUME_NAME_DOS);
+    
+    if(!result_length)
+        return -1;
+
+    if(!CloseHandle(hFile))
+        return -1;
+
+    target_path[result_length] = 0;
+    code = win32_lstat(target_path, result);
+    free(target_path);
+    
+    return code;
+}
+
+static int 
+win32_stat_w(const wchar_t* path, struct win32_stat *result)
+{
+    /* Traverse the symlink to the target using GetFinalPathNameByHandle() */
+    int code;
+    HANDLE hFile;
+    int buf_size;
+    wchar_t *target_path;
+    int result_length;
+    WIN32_FILE_ATTRIBUTE_DATA info;
+    
+    if(!check_GetFinalPathNameByHandle()) {
+        /* If the OS doesn't have GetFinalPathNameByHandle, it doesn't have
+           symlinks, so just fall back to the traditional behavior found
+           in lstat. */
+        return win32_lstat_w(path, result);
+    }
+
+    hFile = CreateFileW(
+        path,
+        0, /* desired access */
+        0, /* share mode */
+        NULL, /* security attributes */
+        OPEN_EXISTING,
+        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
+        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
+        NULL);
+    
+    if(hFile == INVALID_HANDLE_VALUE) {
+        /* Either the target doesn't exist, or we don't have access to
+           get a handle to it. If the former, we need to return an error.
+           If the latter, we can use attributes_from_dir. */
+        if (GetLastError() != ERROR_SHARING_VIOLATION) {
+            /* Protocol violation: we explicitly clear errno, instead of
+               setting it to a POSIX error. Callers should use GetLastError. */
+            errno = 0;
+            return -1;
+        } else {
+            /* Could not get attributes on open file. Fall back to
+               reading the directory. */
+            if (!attributes_from_dir_w(path, &info)) {
+                /* Very strange. This should not fail now */
+                errno = 0;
+                return -1;
+            }
+        }
+        code = attribute_data_to_stat(&info, result);
+    }
+    else {
+        /* We have a good handle to the target, use it to determine the target
+           path name (then we'll call lstat on it). */
+        buf_size = Py_GetFinalPathNameByHandleW(hFile, 0, 0, VOLUME_NAME_DOS);
+        if(!buf_size)
+            return -1;
+
+        target_path = (wchar_t *)malloc((buf_size+1)*sizeof(wchar_t));
+        result_length = Py_GetFinalPathNameByHandleW(hFile, target_path,
+                                                buf_size, VOLUME_NAME_DOS);
+        
+        if(!result_length)
+            return -1;
+
+        if(!CloseHandle(hFile))
+            return -1;
+
+        target_path[result_length] = 0;
+        code = win32_lstat_w(target_path, result);
+        free(target_path);
+    }
+    
+    return code;
+}
+
 static int
 win32_fstat(int file_number, struct win32_stat *result)
 {
@@ -1097,9 +1320,12 @@
     /* similar to stat() */
     result->st_mode = attributes_to_mode(info.dwFileAttributes);
     result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
-    FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
-    FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
-    FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
+    FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime,
+                             &result->st_ctime_nsec);
+    FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime,
+                             &result->st_mtime_nsec);
+    FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime,
+                             &result->st_atime_nsec);
     /* specific to fstat() */
     result->st_nlink = info.nNumberOfLinks;
     result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
@@ -2074,10 +2300,10 @@
 
 
 PyDoc_STRVAR(posix_listdir__doc__,
-"listdir(path) -> list_of_strings\n\n\
+"listdir([path]) -> list_of_strings\n\n\
 Return a list containing the names of the entries in the directory.\n\
 \n\
-    path: path of directory to list\n\
+    path: path of directory to list (default: '.')\n\
 \n\
 The list is in arbitrary order.  It does not include the special\n\
 entries '.' and '..' even if they are present in the directory.");
@@ -2098,18 +2324,25 @@
     char *bufptr = namebuf;
     Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */
 
-    PyObject *po;
-    if (PyArg_ParseTuple(args, "U:listdir", &po)) {
+    PyObject *po = NULL;
+    if (PyArg_ParseTuple(args, "|U:listdir", &po)) {
         WIN32_FIND_DATAW wFileData;
-        Py_UNICODE *wnamebuf;
+        Py_UNICODE *wnamebuf, *po_wchars;
+        
+        if (po == NULL) { // Default arg: "."
+            po_wchars = L".";
+            len = 1;
+        } else {
+            po_wchars = PyUnicode_AS_UNICODE(po);
+            len = PyUnicode_GET_SIZE(po);
+        }
         /* Overallocate for \\*.*\0 */
-        len = PyUnicode_GET_SIZE(po);
         wnamebuf = malloc((len + 5) * sizeof(wchar_t));
         if (!wnamebuf) {
             PyErr_NoMemory();
             return NULL;
         }
-        wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po));
+        wcscpy(wnamebuf, po_wchars);
         if (len > 0) {
             Py_UNICODE wch = wnamebuf[len-1];
             if (wch != L'/' && wch != L'\\' && wch != L':')
@@ -2331,12 +2564,17 @@
     int arg_is_unicode = 1;
 
     errno = 0;
-    if (!PyArg_ParseTuple(args, "U:listdir", &v)) {
+    /* v is never read, so it does not need to be initialized yet. */
+    if (!PyArg_ParseTuple(args, "|U:listdir", &v)) {
         arg_is_unicode = 0;
         PyErr_Clear();
     }
-    if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname))
+    oname = NULL;
+    if (!PyArg_ParseTuple(args, "|O&:listdir", PyUnicode_FSConverter, &oname))
         return NULL;
+    if (oname == NULL) { // Default arg: "."
+      oname = PyBytes_FromString(".");
+    }
     name = PyBytes_AsString(oname);
     if ((dirp = opendir(name)) == NULL) {
         return posix_error_with_allocated_filename(oname);
@@ -2443,6 +2681,70 @@
     }
     return PyBytes_FromString(outbuf);
 } /* end of posix__getfullpathname */
+
+/* A helper function for samepath on windows */
+static PyObject *
+posix__getfinalpathname(PyObject *self, PyObject *args)
+{
+    HANDLE hFile;
+    int buf_size;
+    wchar_t *target_path;
+    int result_length;
+    PyObject *result;
+    wchar_t *path;
+    
+    if (!PyArg_ParseTuple(args, "u|:_getfullpathname", &path)) {
+        return NULL;
+    }
+
+    if(!check_GetFinalPathNameByHandle()) {
+        /* If the OS doesn't have GetFinalPathNameByHandle, return a
+           NotImplementedError. */
+        return PyErr_Format(PyExc_NotImplementedError,
+            "GetFinalPathNameByHandle not available on this platform");
+    }
+
+    hFile = CreateFileW(
+        path,
+        0, /* desired access */
+        0, /* share mode */
+        NULL, /* security attributes */
+        OPEN_EXISTING,
+        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
+        FILE_FLAG_BACKUP_SEMANTICS,
+        NULL);
+    
+    if(hFile == INVALID_HANDLE_VALUE) {
+        return win32_error_unicode("GetFinalPathNamyByHandle", path);
+        return PyErr_Format(PyExc_RuntimeError,
+                            "Could not get a handle to file.");
+    }
+
+    /* We have a good handle to the target, use it to determine the
+       target path name. */
+    buf_size = Py_GetFinalPathNameByHandleW(hFile, 0, 0, VOLUME_NAME_NT);
+
+    if(!buf_size)
+        return win32_error_unicode("GetFinalPathNameByHandle", path);
+
+    target_path = (wchar_t *)malloc((buf_size+1)*sizeof(wchar_t));
+    if(!target_path)
+        return PyErr_NoMemory();
+
+    result_length = Py_GetFinalPathNameByHandleW(hFile, target_path,
+                                                 buf_size, VOLUME_NAME_DOS);
+    if(!result_length)
+        return win32_error_unicode("GetFinalPathNamyByHandle", path);
+
+    if(!CloseHandle(hFile))
+        return win32_error_unicode("GetFinalPathNameByHandle", path);
+
+    target_path[result_length] = 0;
+    result = PyUnicode_FromUnicode(target_path, result_length);
+    free(target_path);
+    return result;
+
+} /* end of posix__getfinalpathname */
 #endif /* MS_WINDOWS */
 
 PyDoc_STRVAR(posix_mkdir__doc__,
@@ -2623,7 +2925,7 @@
 posix_stat(PyObject *self, PyObject *args)
 {
 #ifdef MS_WINDOWS
-    return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat);
+    return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_stat_w);
 #else
     return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL);
 #endif
@@ -2681,6 +2983,41 @@
     return PyLong_FromLong((long)i);
 }
 
+#ifdef MS_WINDOWS
+
+/* override the default DeleteFileW behavior so that directory
+symlinks can be removed with this function, the same as with
+Unix symlinks */
+BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
+{
+    WIN32_FILE_ATTRIBUTE_DATA info;
+    WIN32_FIND_DATAW find_data;
+    HANDLE find_data_handle;
+    int is_directory = 0;
+    int is_link = 0;
+
+    if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
+        is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
+        
+        /* Get WIN32_FIND_DATA structure for the path to determine if
+           it is a symlink */
+        if(is_directory &&
+           info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+            find_data_handle = FindFirstFileW(lpFileName, &find_data);
+
+            if(find_data_handle != INVALID_HANDLE_VALUE) {
+                is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK;
+                FindClose(find_data_handle);
+            }
+        }
+    }
+
+    if (is_directory && is_link)
+        return RemoveDirectoryW(lpFileName);
+
+    return DeleteFileW(lpFileName);
+}
+#endif /* MS_WINDOWS */
 
 PyDoc_STRVAR(posix_unlink__doc__,
 "unlink(path)\n\n\
@@ -2694,7 +3031,8 @@
 posix_unlink(PyObject *self, PyObject *args)
 {
 #ifdef MS_WINDOWS
-    return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW);
+    return win32_1str(args, "remove", "y:remove", DeleteFileA,
+                      "U:remove", Py_DeleteFileW);
 #else
     return posix_1str(args, "O&:remove", unlink);
 #endif
@@ -3837,17 +4175,49 @@
 #define MAX_GROUPS 64
 #endif
     gid_t grouplist[MAX_GROUPS];
+
+    /* On MacOSX getgroups(2) can return more than MAX_GROUPS results 
+     * This is a helper variable to store the intermediate result when
+     * that happens.
+     *
+     * To keep the code readable the OSX behaviour is unconditional,
+     * according to the POSIX spec this should be safe on all unix-y
+     * systems.
+     */
+    gid_t* alt_grouplist = grouplist;
     int n;
 
     n = getgroups(MAX_GROUPS, grouplist);
-    if (n < 0)
-        posix_error();
-    else {
-        result = PyList_New(n);
-        if (result != NULL) {
+    if (n < 0) {
+        if (errno == EINVAL) {
+            n = getgroups(0, NULL);
+            if (n == -1) {
+                return posix_error();
+            }
+            if (n == 0) {
+                /* Avoid malloc(0) */
+                alt_grouplist = grouplist;
+            } else {
+                alt_grouplist = PyMem_Malloc(n * sizeof(gid_t));
+                if (alt_grouplist == NULL) {
+                    errno = EINVAL;
+                    return posix_error();
+                }
+                n = getgroups(n, alt_grouplist);
+                if (n == -1) {
+                    PyMem_Free(alt_grouplist);
+                    return posix_error();
+                }
+            }
+        } else {
+            return posix_error();
+        }
+    }
+    result = PyList_New(n);
+    if (result != NULL) {
         int i;
         for (i = 0; i < n; ++i) {
-            PyObject *o = PyLong_FromLong((long)grouplist[i]);
+            PyObject *o = PyLong_FromLong((long)alt_grouplist[i]);
             if (o == NULL) {
             Py_DECREF(result);
             result = NULL;
@@ -3855,7 +4225,10 @@
             }
             PyList_SET_ITEM(result, i, o);
         }
-        }
+    }
+
+    if (alt_grouplist != grouplist) {
+        PyMem_Free(alt_grouplist);
     }
 
     return result;
@@ -4544,7 +4917,8 @@
     return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL);
 #else /* !HAVE_LSTAT */
 #ifdef MS_WINDOWS
-    return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat);
+    return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat",
+                         win32_lstat_w);
 #else
     return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL);
 #endif
@@ -4609,6 +4983,198 @@
 }
 #endif /* HAVE_SYMLINK */
 
+#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
+
+PyDoc_STRVAR(win_readlink__doc__,
+"readlink(path) -> path\n\n\
+Return a string representing the path to which the symbolic link points.");
+
+/* The following structure was copied from
+   http://msdn.microsoft.com/en-us/library/ms791514.aspx as the required
+   include doesn't seem to be present in the Windows SDK (at least as included
+   with Visual Studio Express). */
+typedef struct _REPARSE_DATA_BUFFER {
+    ULONG ReparseTag;
+    USHORT ReparseDataLength;
+    USHORT Reserved;
+    union {
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT SubstituteNameLength;
+            USHORT PrintNameOffset;
+            USHORT PrintNameLength;
+            ULONG Flags;
+            WCHAR PathBuffer[1];
+        } SymbolicLinkReparseBuffer;
+
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT  SubstituteNameLength;
+            USHORT  PrintNameOffset;
+            USHORT  PrintNameLength;
+            WCHAR  PathBuffer[1];
+        } MountPointReparseBuffer;
+
+        struct {
+            UCHAR  DataBuffer[1];
+        } GenericReparseBuffer;
+    };
+} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
+
+#define REPARSE_DATA_BUFFER_HEADER_SIZE  FIELD_OFFSET(REPARSE_DATA_BUFFER,\
+                                                      GenericReparseBuffer)
+
+#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE  ( 16 * 1024 )
+
+/* Windows readlink implementation */
+static PyObject *
+win_readlink(PyObject *self, PyObject *args)
+{
+    wchar_t *path;
+    DWORD n_bytes_returned;
+    DWORD io_result;
+    PyObject *result;
+    HANDLE reparse_point_handle;
+
+    char target_buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+    REPARSE_DATA_BUFFER *rdb = (REPARSE_DATA_BUFFER *)target_buffer;
+    wchar_t *print_name;
+
+    if (!PyArg_ParseTuple(args,
+                  "u:readlink",
+                  &path))
+        return NULL;
+
+    /* First get a handle to the reparse point */
+    Py_BEGIN_ALLOW_THREADS
+    reparse_point_handle = CreateFileW(
+        path,
+        0,
+        0,
+        0,
+        OPEN_EXISTING,
+        FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
+        0);
+    Py_END_ALLOW_THREADS
+    
+    if (reparse_point_handle==INVALID_HANDLE_VALUE)
+    {
+        return win32_error_unicode("readlink", path);
+    }
+    
+    Py_BEGIN_ALLOW_THREADS
+    /* New call DeviceIoControl to read the reparse point */
+    io_result = DeviceIoControl(
+        reparse_point_handle,
+        FSCTL_GET_REPARSE_POINT,
+        0, 0, /* in buffer */
+        target_buffer, sizeof(target_buffer),
+        &n_bytes_returned,
+        0 /* we're not using OVERLAPPED_IO */
+        );
+    CloseHandle(reparse_point_handle);
+    Py_END_ALLOW_THREADS
+
+    if (io_result==0)
+    {
+        return win32_error_unicode("readlink", path);
+    }
+
+    if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
+    {
+        PyErr_SetString(PyExc_ValueError,
+                "not a symbolic link");
+        return NULL;
+    }
+    print_name = rdb->SymbolicLinkReparseBuffer.PathBuffer +
+                 rdb->SymbolicLinkReparseBuffer.PrintNameOffset;
+
+    result = PyUnicode_FromWideChar(print_name,
+                    rdb->SymbolicLinkReparseBuffer.PrintNameLength/2);
+    return result;
+}
+
+#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
+
+#if !defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+
+/* Grab CreateSymbolicLinkW dynamically from kernel32 */
+static int has_CreateSymbolicLinkW = 0;
+static DWORD (CALLBACK *Py_CreateSymbolicLinkW)(LPWSTR, LPWSTR, DWORD);
+static int
+check_CreateSymbolicLinkW()
+{
+    HINSTANCE hKernel32;
+    /* only recheck */
+    if (has_CreateSymbolicLinkW)
+        return has_CreateSymbolicLinkW;
+    hKernel32 = GetModuleHandle("KERNEL32");
+    *(FARPROC*)&Py_CreateSymbolicLinkW = GetProcAddress(hKernel32,
+                                                        "CreateSymbolicLinkW");
+    if (Py_CreateSymbolicLinkW)
+        has_CreateSymbolicLinkW = 1;
+    return has_CreateSymbolicLinkW;
+}
+
+PyDoc_STRVAR(win_symlink__doc__,
+"symlink(src, dst, target_is_directory=False)\n\n\
+Create a symbolic link pointing to src named dst.\n\
+target_is_directory is required if the target is to be interpreted as\n\
+a directory.\n\
+This function requires Windows 6.0 or greater, and raises a\n\
+NotImplementedError otherwise.");
+
+static PyObject *
+win_symlink(PyObject *self, PyObject *args, PyObject *kwargs)
+{
+    static char *kwlist[] = {"src", "dest", "target_is_directory", NULL};
+    PyObject *src, *dest;
+    int target_is_directory = 0;
+    DWORD res;
+    WIN32_FILE_ATTRIBUTE_DATA src_info;
+    
+    if (!check_CreateSymbolicLinkW())
+    {
+        /* raise NotImplementedError */
+        return PyErr_Format(PyExc_NotImplementedError,
+            "CreateSymbolicLinkW not found");
+    }
+    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|i:symlink",
+        kwlist, &src, &dest, &target_is_directory))
+        return NULL;
+    if (!convert_to_unicode(&src)) { return NULL; }
+    if (!convert_to_unicode(&dest)) {
+        Py_DECREF(src);
+        return NULL;
+    }
+    
+    /* if src is a directory, ensure target_is_directory==1 */
+    if(
+        GetFileAttributesExW(
+            PyUnicode_AsUnicode(src), GetFileExInfoStandard, &src_info
+        ))
+    {
+        target_is_directory = target_is_directory ||
+            (src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
+    }
+
+    Py_BEGIN_ALLOW_THREADS
+    res = Py_CreateSymbolicLinkW(
+        PyUnicode_AsUnicode(dest),
+        PyUnicode_AsUnicode(src),
+        target_is_directory);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(src);
+    Py_DECREF(dest);
+    if (!res)
+    {
+        return win32_error_unicode("symlink", PyUnicode_AsUnicode(src));
+    }
+    
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+#endif /* !defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
 
 #ifdef HAVE_TIMES
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
@@ -7076,13 +7642,20 @@
 #ifdef HAVE_READLINK
     {"readlink",        posix_readlink, METH_VARARGS, posix_readlink__doc__},
 #endif /* HAVE_READLINK */
-    {"rename",          posix_rename, METH_VARARGS, posix_rename__doc__},
-    {"rmdir",           posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
-    {"stat",            posix_stat, METH_VARARGS, posix_stat__doc__},
+#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
+    {"readlink",	win_readlink, METH_VARARGS, win_readlink__doc__},
+#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
+    {"rename",	posix_rename, METH_VARARGS, posix_rename__doc__},
+    {"rmdir",	posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
+    {"stat",	posix_stat, METH_VARARGS, posix_stat__doc__},
     {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
 #ifdef HAVE_SYMLINK
     {"symlink",         posix_symlink, METH_VARARGS, posix_symlink__doc__},
 #endif /* HAVE_SYMLINK */
+#if !defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+    {"symlink", (PyCFunction)win_symlink, METH_VARARGS | METH_KEYWORDS,
+                win_symlink__doc__},
+#endif /* !defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
 #ifdef HAVE_SYSTEM
     {"system",          posix_system, METH_VARARGS, posix_system__doc__},
 #endif
@@ -7307,6 +7880,7 @@
     {"abort",           posix_abort, METH_NOARGS, posix_abort__doc__},
 #ifdef MS_WINDOWS
     {"_getfullpathname",        posix__getfullpathname, METH_VARARGS, NULL},
+    {"_getfinalpathname",       posix__getfinalpathname, METH_VARARGS, NULL},
 #endif
 #ifdef HAVE_GETLOADAVG
     {"getloadavg",      posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},

Modified: python/branches/py3k-dtoa/Modules/readline.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/readline.c	(original)
+++ python/branches/py3k-dtoa/Modules/readline.c	Sun Aug  8 12:41:24 2010
@@ -378,6 +378,38 @@
 "set_completer_delims(string) -> None\n\
 set the readline word delimiters for tab-completion");
 
+/* _py_free_history_entry: Utility function to free a history entry. */
+
+#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0500
+
+/* Readline version >= 5.0 introduced a timestamp field into the history entry
+   structure; this needs to be freed to avoid a memory leak.  This version of
+   readline also introduced the handy 'free_history_entry' function, which
+   takes care of the timestamp. */
+
+static void
+_py_free_history_entry(HIST_ENTRY *entry)
+{
+    histdata_t data = free_history_entry(entry);
+    free(data);
+}
+
+#else
+
+/* No free_history_entry function;  free everything manually. */
+
+static void
+_py_free_history_entry(HIST_ENTRY *entry)
+{
+    if (entry->line)
+        free((void *)entry->line);
+    if (entry->data)
+        free(entry->data);
+    free(entry);
+}
+
+#endif
+
 static PyObject *
 py_remove_history(PyObject *self, PyObject *args)
 {
@@ -399,12 +431,7 @@
         return NULL;
     }
     /* free memory allocated for the history entry */
-    if (entry->line)
-        free(entry->line);
-    if (entry->data)
-        free(entry->data);
-    free(entry);
-
+    _py_free_history_entry(entry);
     Py_RETURN_NONE;
 }
 
@@ -436,12 +463,7 @@
         return NULL;
     }
     /* free memory allocated for the old history entry */
-    if (old_entry->line)
-        free(old_entry->line);
-    if (old_entry->data)
-        free(old_entry->data);
-    free(old_entry);
-
+    _py_free_history_entry(old_entry);
     Py_RETURN_NONE;
 }
 
@@ -512,6 +534,25 @@
 \n\
 Returns current completer function.");
 
+/* Private function to get current length of history.  XXX It may be
+ * possible to replace this with a direct use of history_length instead,
+ * but it's not clear whether BSD's libedit keeps history_length up to date.
+ * See issue #8065.*/
+
+static int
+_py_get_history_length(void)
+{
+    HISTORY_STATE *hist_st = history_get_history_state();
+    int length = hist_st->length;
+    /* the history docs don't say so, but the address of hist_st changes each
+       time history_get_history_state is called which makes me think it's
+       freshly malloc'd memory...  on the other hand, the address of the last
+       line stays the same as long as history isn't extended, so it appears to
+       be malloc'd but managed by the history package... */
+    free(hist_st);
+    return length;
+}
+
 /* Exported function to get any element of history */
 
 static PyObject *
@@ -530,9 +571,7 @@
          * code doesn't have to worry about the
          * difference.
          */
-        HISTORY_STATE *hist_st;
-        hist_st = history_get_history_state();
-
+        int length = _py_get_history_length();
         idx --;
 
         /*
@@ -540,7 +579,7 @@
          * the index is out of range, therefore
          * test for that and fail gracefully.
          */
-        if (idx < 0 || idx >= hist_st->length) {
+        if (idx < 0 || idx >= length) {
             Py_RETURN_NONE;
         }
     }
@@ -562,10 +601,7 @@
 static PyObject *
 get_current_history_length(PyObject *self, PyObject *noarg)
 {
-    HISTORY_STATE *hist_st;
-
-    hist_st = history_get_history_state();
-    return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0);
+    return PyLong_FromLong((long)_py_get_history_length());
 }
 
 PyDoc_STRVAR(doc_get_current_history_length,
@@ -1045,29 +1081,22 @@
     n = strlen(p);
     if (n > 0) {
         char *line;
-        HISTORY_STATE *state = history_get_history_state();
-        if (state->length > 0)
+        int length = _py_get_history_length();
+        if (length > 0)
 #ifdef __APPLE__
             if (using_libedit_emulation) {
                 /*
                  * Libedit's emulation uses 0-based indexes,
                  * the real readline uses 1-based indexes.
                  */
-                line = history_get(state->length - 1)->line;
+                line = history_get(length - 1)->line;
             } else
 #endif /* __APPLE__ */
-            line = history_get(state->length)->line;
+            line = history_get(length)->line;
         else
             line = "";
         if (strcmp(p, line))
             add_history(p);
-        /* the history docs don't say so, but the address of state
-           changes each time history_get_history_state is called
-           which makes me think it's freshly malloc'd memory...
-           on the other hand, the address of the last line stays the
-           same as long as history isn't extended, so it appears to
-           be malloc'd but managed by the history package... */
-        free(state);
     }
     /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
        release the original. */

Modified: python/branches/py3k-dtoa/Modules/selectmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/selectmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/selectmodule.c	Sun Aug  8 12:41:24 2010
@@ -915,10 +915,9 @@
 }
 
 PyDoc_STRVAR(pyepoll_register_doc,
-"register(fd[, eventmask]) -> bool\n\
+"register(fd[, eventmask]) -> None\n\
 \n\
-Registers a new fd or modifies an already registered fd. register() returns\n\
-True if a new fd was registered or False if the event mask for fd was modified.\n\
+Registers a new fd or modifies an already registered fd.\n\
 fd is the target file descriptor of the operation.\n\
 events is a bit set composed of the various EPOLL constants; the default\n\
 is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\

Modified: python/branches/py3k-dtoa/Modules/sha1module.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/sha1module.c	(original)
+++ python/branches/py3k-dtoa/Modules/sha1module.c	Sun Aug  8 12:41:24 2010
@@ -127,50 +127,50 @@
 
     /* compress */
     /* round one */
-    #define FF0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
-    #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
-    #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
-    #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
+    #define FF_0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
+    #define FF_1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
+    #define FF_2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
+    #define FF_3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
 
     for (i = 0; i < 20; ) {
-       FF0(a,b,c,d,e,i++);
-       FF0(e,a,b,c,d,i++);
-       FF0(d,e,a,b,c,i++);
-       FF0(c,d,e,a,b,i++);
-       FF0(b,c,d,e,a,i++);
+       FF_0(a,b,c,d,e,i++);
+       FF_0(e,a,b,c,d,i++);
+       FF_0(d,e,a,b,c,i++);
+       FF_0(c,d,e,a,b,i++);
+       FF_0(b,c,d,e,a,i++);
     }
 
     /* round two */
     for (; i < 40; )  {
-       FF1(a,b,c,d,e,i++);
-       FF1(e,a,b,c,d,i++);
-       FF1(d,e,a,b,c,i++);
-       FF1(c,d,e,a,b,i++);
-       FF1(b,c,d,e,a,i++);
+       FF_1(a,b,c,d,e,i++);
+       FF_1(e,a,b,c,d,i++);
+       FF_1(d,e,a,b,c,i++);
+       FF_1(c,d,e,a,b,i++);
+       FF_1(b,c,d,e,a,i++);
     }
 
     /* round three */
     for (; i < 60; )  {
-       FF2(a,b,c,d,e,i++);
-       FF2(e,a,b,c,d,i++);
-       FF2(d,e,a,b,c,i++);
-       FF2(c,d,e,a,b,i++);
-       FF2(b,c,d,e,a,i++);
+       FF_2(a,b,c,d,e,i++);
+       FF_2(e,a,b,c,d,i++);
+       FF_2(d,e,a,b,c,i++);
+       FF_2(c,d,e,a,b,i++);
+       FF_2(b,c,d,e,a,i++);
     }
 
     /* round four */
     for (; i < 80; )  {
-       FF3(a,b,c,d,e,i++);
-       FF3(e,a,b,c,d,i++);
-       FF3(d,e,a,b,c,i++);
-       FF3(c,d,e,a,b,i++);
-       FF3(b,c,d,e,a,i++);
+       FF_3(a,b,c,d,e,i++);
+       FF_3(e,a,b,c,d,i++);
+       FF_3(d,e,a,b,c,i++);
+       FF_3(c,d,e,a,b,i++);
+       FF_3(b,c,d,e,a,i++);
     }
 
-    #undef FF0
-    #undef FF1
-    #undef FF2
-    #undef FF3
+    #undef FF_0
+    #undef FF_1
+    #undef FF_2
+    #undef FF_3
 
     /* store */
     sha1->state[0] = sha1->state[0] + a;

Modified: python/branches/py3k-dtoa/Modules/signalmodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/signalmodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/signalmodule.c	Sun Aug  8 12:41:24 2010
@@ -255,8 +255,23 @@
     int sig_num;
     PyObject *old_handler;
     void (*func)(int);
+#ifdef MS_WINDOWS
+    int cur_sig, num_valid_sigs = 6;
+    static int valid_sigs[] = {SIGABRT, SIGFPE, SIGILL, SIGINT,
+                               SIGSEGV, SIGTERM};
+    BOOL valid_sig = FALSE;
+#endif
     if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj))
         return NULL;
+#ifdef MS_WINDOWS
+    /* Validate that sig_num is one of the allowable signals */
+    for (cur_sig = 0; cur_sig < num_valid_sigs; cur_sig++)
+        valid_sig |= (sig_num == valid_sigs[cur_sig]);
+    if (!valid_sig) {
+        PyErr_SetString(PyExc_ValueError, "signal number out of range");
+        return NULL;
+    }
+#endif
 #ifdef WITH_THREAD
     if (PyThread_get_thread_ident() != main_thread) {
         PyErr_SetString(PyExc_ValueError,

Modified: python/branches/py3k-dtoa/Modules/timemodule.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/timemodule.c	(original)
+++ python/branches/py3k-dtoa/Modules/timemodule.c	Sun Aug  8 12:41:24 2010
@@ -3,22 +3,10 @@
 
 #include "Python.h"
 #include "structseq.h"
-#include "timefuncs.h"
+#include "_time.h"
 
 #define TZNAME_ENCODING "utf-8"
 
-#ifdef __APPLE__
-#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
-  /*
-   * floattime falls back to ftime when getttimeofday fails because the latter
-   * might fail on some platforms. This fallback is unwanted on MacOSX because
-   * that makes it impossible to use a binary build on OSX 10.4 on earlier
-   * releases of the OS. Therefore claim we don't support ftime.
-   */
-# undef HAVE_FTIME
-#endif
-#endif
-
 #include <ctype.h>
 
 #ifdef HAVE_SYS_TYPES_H
@@ -29,13 +17,6 @@
 #include <io.h>
 #endif
 
-#ifdef HAVE_FTIME
-#include <sys/timeb.h>
-#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
-extern int ftime(struct timeb *);
-#endif /* MS_WINDOWS */
-#endif /* HAVE_FTIME */
-
 #if defined(__WATCOMC__) && !defined(__QNX__)
 #include <i86.h>
 #else
@@ -946,44 +927,12 @@
     return m;
 }
 
-
-/* Implement floattime() for various platforms */
-
 static double
 floattime(void)
 {
-    /* There are three ways to get the time:
-      (1) gettimeofday() -- resolution in microseconds
-      (2) ftime() -- resolution in milliseconds
-      (3) time() -- resolution in seconds
-      In all cases the return value is a float in seconds.
-      Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
-      fail, so we fall back on ftime() or time().
-      Note: clock resolution does not imply clock accuracy! */
-#ifdef HAVE_GETTIMEOFDAY
-    {
-        struct timeval t;
-#ifdef GETTIMEOFDAY_NO_TZ
-        if (gettimeofday(&t) == 0)
-            return (double)t.tv_sec + t.tv_usec*0.000001;
-#else /* !GETTIMEOFDAY_NO_TZ */
-        if (gettimeofday(&t, (struct timezone *)NULL) == 0)
-            return (double)t.tv_sec + t.tv_usec*0.000001;
-#endif /* !GETTIMEOFDAY_NO_TZ */
-    }
-
-#endif /* !HAVE_GETTIMEOFDAY */
-    {
-#if defined(HAVE_FTIME)
-        struct timeb t;
-        ftime(&t);
-        return (double)t.time + (double)t.millitm * (double)0.001;
-#else /* !HAVE_FTIME */
-        time_t secs;
-        time(&secs);
-        return (double)secs;
-#endif /* !HAVE_FTIME */
-    }
+    _PyTime_timeval t;
+    _PyTime_gettimeofday(&t);
+    return (double)t.tv_sec + t.tv_usec*0.000001;
 }
 
 

Modified: python/branches/py3k-dtoa/Modules/zipimport.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zipimport.c	(original)
+++ python/branches/py3k-dtoa/Modules/zipimport.c	Sun Aug  8 12:41:24 2010
@@ -523,19 +523,19 @@
 "is_package(fullname) -> bool.\n\
 \n\
 Return True if the module specified by fullname is a package.\n\
-Raise ZipImportError is the module couldn't be found.");
+Raise ZipImportError if the module couldn't be found.");
 
 PyDoc_STRVAR(doc_get_code,
 "get_code(fullname) -> code object.\n\
 \n\
 Return the code object for the specified module. Raise ZipImportError\n\
-is the module couldn't be found.");
+if the module couldn't be found.");
 
 PyDoc_STRVAR(doc_get_source,
 "get_source(fullname) -> source string.\n\
 \n\
 Return the source code for the specified module. Raise ZipImportError\n\
-is the module couldn't be found, return None if the archive does\n\
+if the module couldn't be found, return None if the archive does\n\
 contain the module, but has no source for it.");
 
 

Modified: python/branches/py3k-dtoa/Modules/zlib/ChangeLog
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/ChangeLog	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/ChangeLog	Sun Aug  8 12:41:24 2010
@@ -1,6 +1,359 @@
 
                 ChangeLog file for zlib
 
+Changes in 1.2.5 (19 Apr 2010)
+- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev]
+- Default to libdir as sharedlibdir in configure [Nieder]
+- Update copyright dates on modified source files
+- Update trees.c to be able to generate modified trees.h
+- Exit configure for MinGW, suggesting win32/Makefile.gcc
+
+Changes in 1.2.4.5 (18 Apr 2010)
+- Set sharedlibdir in configure [Torok]
+- Set LDFLAGS in Makefile.in [Bar-Lev]
+- Avoid mkdir objs race condition in Makefile.in [Bowler]
+- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays
+- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C
+- Don't use hidden attribute when it is a warning generator (e.g. Solaris)
+
+Changes in 1.2.4.4 (18 Apr 2010)
+- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok]
+- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty
+- Try to use bash or ksh regardless of functionality of /bin/sh
+- Fix configure incompatibility with NetBSD sh
+- Remove attempt to run under bash or ksh since have better NetBSD fix
+- Fix win32/Makefile.gcc for MinGW [Bar-Lev]
+- Add diagnostic messages when using CROSS_PREFIX in configure
+- Added --sharedlibdir option to configure [Weigelt]
+- Use hidden visibility attribute when available [Frysinger]
+
+Changes in 1.2.4.3 (10 Apr 2010)
+- Only use CROSS_PREFIX in configure for ar and ranlib if they exist
+- Use CROSS_PREFIX for nm [Bar-Lev]
+- Assume _LARGEFILE64_SOURCE defined is equivalent to true
+- Avoid use of undefined symbols in #if with && and ||
+- Make *64 prototypes in gzguts.h consistent with functions
+- Add -shared load option for MinGW in configure [Bowler]
+- Move z_off64_t to public interface, use instead of off64_t
+- Remove ! from shell test in configure (not portable to Solaris)
+- Change +0 macro tests to -0 for possibly increased portability
+
+Changes in 1.2.4.2 (9 Apr 2010)
+- Add consistent carriage returns to readme.txt's in masmx86 and masmx64
+- Really provide prototypes for *64 functions when building without LFS
+- Only define unlink() in minigzip.c if unistd.h not included
+- Update README to point to contrib/vstudio project files
+- Move projects/vc6 to old/ and remove projects/
+- Include stdlib.h in minigzip.c for setmode() definition under WinCE
+- Clean up assembler builds in win32/Makefile.msc [Rowe]
+- Include sys/types.h for Microsoft for off_t definition
+- Fix memory leak on error in gz_open()
+- Symbolize nm as $NM in configure [Weigelt]
+- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt]
+- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined
+- Fix bug in gzeof() to take into account unused input data
+- Avoid initialization of structures with variables in puff.c
+- Updated win32/README-WIN32.txt [Rowe]
+
+Changes in 1.2.4.1 (28 Mar 2010)
+- Remove the use of [a-z] constructs for sed in configure [gentoo 310225]
+- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech]
+- Restore "for debugging" comment on sprintf() in gzlib.c
+- Remove fdopen for MVS from gzguts.h
+- Put new README-WIN32.txt in win32 [Rowe]
+- Add check for shell to configure and invoke another shell if needed
+- Fix big fat stinking bug in gzseek() on uncompressed files
+- Remove vestigial F_OPEN64 define in zutil.h
+- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE
+- Avoid errors on non-LFS systems when applications define LFS macros
+- Set EXE to ".exe" in configure for MINGW [Kahle]
+- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill]
+- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev]
+- Add DLL install in win32/makefile.gcc [Bar-Lev]
+- Allow Linux* or linux* from uname in configure [Bar-Lev]
+- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev]
+- Add cross-compilation prefixes to configure [Bar-Lev]
+- Match type exactly in gz_load() invocation in gzread.c
+- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func
+- Provide prototypes for *64 functions when building zlib without LFS
+- Don't use -lc when linking shared library on MinGW
+- Remove errno.h check in configure and vestigial errno code in zutil.h
+
+Changes in 1.2.4 (14 Mar 2010)
+- Fix VER3 extraction in configure for no fourth subversion
+- Update zlib.3, add docs to Makefile.in to make .pdf out of it
+- Add zlib.3.pdf to distribution
+- Don't set error code in gzerror() if passed pointer is NULL
+- Apply destination directory fixes to CMakeLists.txt [Lowman]
+- Move #cmakedefine's to a new zconf.in.cmakein
+- Restore zconf.h for builds that don't use configure or cmake
+- Add distclean to dummy Makefile for convenience
+- Update and improve INDEX, README, and FAQ
+- Update CMakeLists.txt for the return of zconf.h [Lowman]
+- Update contrib/vstudio/vc9 and vc10 [Vollant]
+- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc
+- Apply license and readme changes to contrib/asm686 [Raiter]
+- Check file name lengths and add -c option in minigzip.c [Li]
+- Update contrib/amd64 and contrib/masmx86/ [Vollant]
+- Avoid use of "eof" parameter in trees.c to not shadow library variable
+- Update make_vms.com for removal of zlibdefs.h [Zinser]
+- Update assembler code and vstudio projects in contrib [Vollant]
+- Remove outdated assembler code contrib/masm686 and contrib/asm586
+- Remove old vc7 and vc8 from contrib/vstudio
+- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe]
+- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open()
+- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant]
+- Remove *64 functions from win32/zlib.def (they're not 64-bit yet)
+- Fix bug in void-returning vsprintf() case in gzwrite.c
+- Fix name change from inflate.h in contrib/inflate86/inffas86.c
+- Check if temporary file exists before removing in make_vms.com [Zinser]
+- Fix make install and uninstall for --static option
+- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta]
+- Update readme.txt in contrib/masmx64 and masmx86 to assemble
+
+Changes in 1.2.3.9 (21 Feb 2010)
+- Expunge gzio.c
+- Move as400 build information to old
+- Fix updates in contrib/minizip and contrib/vstudio
+- Add const to vsnprintf test in configure to avoid warnings [Weigelt]
+- Delete zconf.h (made by configure) [Weigelt]
+- Change zconf.in.h to zconf.h.in per convention [Weigelt]
+- Check for NULL buf in gzgets()
+- Return empty string for gzgets() with len == 1 (like fgets())
+- Fix description of gzgets() in zlib.h for end-of-file, NULL return
+- Update minizip to 1.1 [Vollant]
+- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c
+- Note in zlib.h that gzerror() should be used to distinguish from EOF
+- Remove use of snprintf() from gzlib.c
+- Fix bug in gzseek()
+- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant]
+- Fix zconf.h generation in CMakeLists.txt [Lowman]
+- Improve comments in zconf.h where modified by configure
+
+Changes in 1.2.3.8 (13 Feb 2010)
+- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
+- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
+- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
+- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
+- Fix missing error return in gzflush(), add zlib.h note
+- Add *64 functions to zlib.map [Levin]
+- Fix signed/unsigned comparison in gz_comp()
+- Use SFLAGS when testing shared linking in configure
+- Add --64 option to ./configure to use -m64 with gcc
+- Fix ./configure --help to correctly name options
+- Have make fail if a test fails [Levin]
+- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
+- Remove assembler object files from contrib
+
+Changes in 1.2.3.7 (24 Jan 2010)
+- Always gzopen() with O_LARGEFILE if available
+- Fix gzdirect() to work immediately after gzopen() or gzdopen()
+- Make gzdirect() more precise when the state changes while reading
+- Improve zlib.h documentation in many places
+- Catch memory allocation failure in gz_open()
+- Complete close operation if seek forward in gzclose_w() fails
+- Return Z_ERRNO from gzclose_r() if close() fails
+- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
+- Return zero for gzwrite() errors to match zlib.h description
+- Return -1 on gzputs() error to match zlib.h description
+- Add zconf.in.h to allow recovery from configure modification [Weigelt]
+- Fix static library permissions in Makefile.in [Weigelt]
+- Avoid warnings in configure tests that hide functionality [Weigelt]
+- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
+- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
+- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
+- Keep object files in subdirectories to reduce the clutter somewhat
+- Remove default Makefile and zlibdefs.h, add dummy Makefile
+- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
+- Remove zlibdefs.h completely -- modify zconf.h instead
+
+Changes in 1.2.3.6 (17 Jan 2010)
+- Avoid void * arithmetic in gzread.c and gzwrite.c
+- Make compilers happier with const char * for gz_error message
+- Avoid unused parameter warning in inflate.c
+- Avoid signed-unsigned comparison warning in inflate.c
+- Indent #pragma's for traditional C
+- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
+- Correct email address in configure for system options
+- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
+- Update zlib.map [Brown]
+- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok]
+- Apply various fixes to CMakeLists.txt [Lowman]
+- Add checks on len in gzread() and gzwrite()
+- Add error message for no more room for gzungetc()
+- Remove zlib version check in gzwrite()
+- Defer compression of gzprintf() result until need to
+- Use snprintf() in gzdopen() if available
+- Remove USE_MMAP configuration determination (only used by minigzip)
+- Remove examples/pigz.c (available separately)
+- Update examples/gun.c to 1.6
+
+Changes in 1.2.3.5 (8 Jan 2010)
+- Add space after #if in zutil.h for some compilers
+- Fix relatively harmless bug in deflate_fast() [Exarevsky]
+- Fix same problem in deflate_slow()
+- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
+- Add deflate_rle() for faster Z_RLE strategy run-length encoding
+- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
+- Change name of "write" variable in inffast.c to avoid library collisions
+- Fix premature EOF from gzread() in gzio.c [Brown]
+- Use zlib header window size if windowBits is 0 in inflateInit2()
+- Remove compressBound() call in deflate.c to avoid linking compress.o
+- Replace use of errno in gz* with functions, support WinCE [Alves]
+- Provide alternative to perror() in minigzip.c for WinCE [Alves]
+- Don't use _vsnprintf on later versions of MSVC [Lowman]
+- Add CMake build script and input file [Lowman]
+- Update contrib/minizip to 1.1 [Svensson, Vollant]
+- Moved nintendods directory from contrib to .
+- Replace gzio.c with a new set of routines with the same functionality
+- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
+- Update contrib/minizip to 1.1b
+- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
+
+Changes in 1.2.3.4 (21 Dec 2009)
+- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
+- Update comments in configure and Makefile.in for default --shared
+- Fix test -z's in configure [Marquess]
+- Build examplesh and minigzipsh when not testing
+- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
+- Import LDFLAGS from the environment in configure
+- Fix configure to populate SFLAGS with discovered CFLAGS options
+- Adapt make_vms.com to the new Makefile.in [Zinser]
+- Add zlib2ansi script for C++ compilation [Marquess]
+- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
+- Add AMD64 assembler code for longest match to contrib [Teterin]
+- Include options from $SFLAGS when doing $LDSHARED
+- Simplify 64-bit file support by introducing z_off64_t type
+- Make shared object files in objs directory to work around old Sun cc
+- Use only three-part version number for Darwin shared compiles
+- Add rc option to ar in Makefile.in for when ./configure not run
+- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
+- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
+- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
+- Rename Makefile.in targets allstatic to static and allshared to shared
+- Fix static and shared Makefile.in targets to be independent
+- Correct error return bug in gz_open() by setting state [Brown]
+- Put spaces before ;;'s in configure for better sh compatibility
+- Add pigz.c (parallel implementation of gzip) to examples/
+- Correct constant in crc32.c to UL [Leventhal]
+- Reject negative lengths in crc32_combine()
+- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
+- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
+- Correct typo in doc/algorithm.txt [Janik]
+- Fix bug in adler32_combine() [Zhu]
+- Catch missing-end-of-block-code error in all inflates and in puff
+    Assures that random input to inflate eventually results in an error
+- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
+- Update ENOUGH and its usage to reflect discovered bounds
+- Fix gzerror() error report on empty input file [Brown]
+- Add ush casts in trees.c to avoid pedantic runtime errors
+- Fix typo in zlib.h uncompress() description [Reiss]
+- Correct inflate() comments with regard to automatic header detection
+- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
+- Put new version of gzlog (2.0) in examples with interruption recovery
+- Add puff compile option to permit invalid distance-too-far streams
+- Add puff TEST command options, ability to read piped input
+- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
+  _LARGEFILE64_SOURCE not defined
+- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
+- Fix deflateSetDictionary() to use all 32K for output consistency
+- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
+- Clear bytes after deflate lookahead to avoid use of uninitialized data
+- Change a limit in inftrees.c to be more transparent to Coverity Prevent
+- Update win32/zlib.def with exported symbols from zlib.h
+- Correct spelling error in zlib.h [Willem]
+- Allow Z_BLOCK for deflate() to force a new block
+- Allow negative bits in inflatePrime() to delete existing bit buffer
+- Add Z_TREES flush option to inflate() to return at end of trees
+- Add inflateMark() to return current state information for random access
+- Add Makefile for NintendoDS to contrib [Costa]
+- Add -w in configure compile tests to avoid spurious warnings [Beucler]
+- Fix typos in zlib.h comments for deflateSetDictionary()
+- Fix EOF detection in transparent gzread() [Maier]
+
+Changes in 1.2.3.3 (2 October 2006)
+- Make --shared the default for configure, add a --static option
+- Add compile option to permit invalid distance-too-far streams
+- Add inflateUndermine() function which is required to enable above
+- Remove use of "this" variable name for C++ compatibility [Marquess]
+- Add testing of shared library in make test, if shared library built
+- Use ftello() and fseeko() if available instead of ftell() and fseek()
+- Provide two versions of all functions that use the z_off_t type for
+  binary compatibility -- a normal version and a 64-bit offset version,
+  per the Large File Support Extension when _LARGEFILE64_SOURCE is
+  defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
+  is defined to be 64
+- Add a --uname= option to configure to perhaps help with cross-compiling
+
+Changes in 1.2.3.2 (3 September 2006)
+- Turn off silly Borland warnings [Hay]
+- Use off64_t and define _LARGEFILE64_SOURCE when present
+- Fix missing dependency on inffixed.h in Makefile.in
+- Rig configure --shared to build both shared and static [Teredesai, Truta]
+- Remove zconf.in.h and instead create a new zlibdefs.h file
+- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
+- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
+
+Changes in 1.2.3.1 (16 August 2006)
+- Add watcom directory with OpenWatcom make files [Daniel]
+- Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
+- Update make_vms.com [Zinser]
+- Use -fPIC for shared build in configure [Teredesai, Nicholson]
+- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen]
+- Use fdopen() (not _fdopen()) for Interix in zutil.h [BŠck]
+- Add some FAQ entries about the contrib directory
+- Update the MVS question in the FAQ
+- Avoid extraneous reads after EOF in gzio.c [Brown]
+- Correct spelling of "successfully" in gzio.c [Randers-Pehrson]
+- Add comments to zlib.h about gzerror() usage [Brown]
+- Set extra flags in gzip header in gzopen() like deflate() does
+- Make configure options more compatible with double-dash conventions
+  [Weigelt]
+- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen]
+- Fix uninstall target in Makefile.in [Truta]
+- Add pkgconfig support [Weigelt]
+- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt]
+- Replace set_data_type() with a more accurate detect_data_type() in
+  trees.c, according to the txtvsbin.txt document [Truta]
+- Swap the order of #include <stdio.h> and #include "zlib.h" in
+  gzio.c, example.c and minigzip.c [Truta]
+- Shut up annoying VS2005 warnings about standard C deprecation [Rowe,
+  Truta] (where?)
+- Fix target "clean" from win32/Makefile.bor [Truta]
+- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe]
+- Update zlib www home address in win32/DLL_FAQ.txt [Truta]
+- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove]
+- Enable browse info in the "Debug" and "ASM Debug" configurations in
+  the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta]
+- Add pkgconfig support [Weigelt]
+- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h,
+  for use in win32/zlib1.rc [Polushin, Rowe, Truta]
+- Add a document that explains the new text detection scheme to
+  doc/txtvsbin.txt [Truta]
+- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta]
+- Move algorithm.txt into doc/ [Truta]
+- Synchronize FAQ with website
+- Fix compressBound(), was low for some pathological cases [Fearnley]
+- Take into account wrapper variations in deflateBound()
+- Set examples/zpipe.c input and output to binary mode for Windows
+- Update examples/zlib_how.html with new zpipe.c (also web site)
+- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
+  that gcc became pickier in 4.0)
+- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain
+  un-versioned, the patch adds versioning only for symbols introduced in
+  zlib-1.2.0 or later.  It also declares as local those symbols which are
+  not designed to be exported." [Levin]
+- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure
+- Do not initialize global static by default in trees.c, add a response
+  NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess]
+- Don't use strerror() in gzio.c under WinCE [Yakimov]
+- Don't use errno.h in zutil.h under WinCE [Yakimov]
+- Move arguments for AR to its usage to allow replacing ar [Marot]
+- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson]
+- Improve inflateInit() and inflateInit2() documentation
+- Fix structure size comment in inflate.h
+- Change configure help option from --h* to --help [Santos]
+
 Changes in 1.2.3 (18 July 2005)
 - Apply security vulnerability fixes to contrib/infback9 as well
 - Clean up some text files (carriage returns, trailing space)
@@ -13,7 +366,7 @@
   compile
 - Fix some spelling errors in comments [Betts]
 - Correct inflateInit2() error return documentation in zlib.h
-- Added zran.c example of compressed data random access to examples
+- Add zran.c example of compressed data random access to examples
   directory, shows use of inflatePrime()
 - Fix cast for assignments to strm->state in inflate.c and infback.c
 - Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]

Modified: python/branches/py3k-dtoa/Modules/zlib/FAQ
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/FAQ	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/FAQ	Sun Aug  8 12:41:24 2010
@@ -3,8 +3,8 @@
 
 
 If your question is not there, please check the zlib home page
-http://www.zlib.org which may have more recent information.
-The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
+http://zlib.net/ which may have more recent information.
+The lastest zlib FAQ is at http://zlib.net/zlib_faq.html
 
 
  1. Is zlib Y2K-compliant?
@@ -13,54 +13,51 @@
 
  2. Where can I get a Windows DLL version?
 
-    The zlib sources can be compiled without change to produce a DLL.
-    See the file win32/DLL_FAQ.txt in the zlib distribution.
-    Pointers to the precompiled DLL are found in the zlib web site at
-    http://www.zlib.org.
+    The zlib sources can be compiled without change to produce a DLL.  See the
+    file win32/DLL_FAQ.txt in the zlib distribution.  Pointers to the
+    precompiled DLL are found in the zlib web site at http://zlib.net/ .
 
  3. Where can I get a Visual Basic interface to zlib?
 
     See
-        * http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm
-        * contrib/visual-basic.txt in the zlib distribution
+        * http://marknelson.us/1997/01/01/zlib-engine/
         * win32/DLL_FAQ.txt in the zlib distribution
 
  4. compress() returns Z_BUF_ERROR.
 
-    Make sure that before the call of compress, the length of the compressed
-    buffer is equal to the total size of the compressed buffer and not
-    zero. For Visual Basic, check that this parameter is passed by reference
+    Make sure that before the call of compress(), the length of the compressed
+    buffer is equal to the available size of the compressed buffer and not
+    zero.  For Visual Basic, check that this parameter is passed by reference
     ("as any"), not by value ("as long").
 
  5. deflate() or inflate() returns Z_BUF_ERROR.
 
-    Before making the call, make sure that avail_in and avail_out are not
-    zero. When setting the parameter flush equal to Z_FINISH, also make sure
-    that avail_out is big enough to allow processing all pending input.
-    Note that a Z_BUF_ERROR is not fatal--another call to deflate() or
-    inflate() can be made with more input or output space. A Z_BUF_ERROR
-    may in fact be unavoidable depending on how the functions are used, since
-    it is not possible to tell whether or not there is more output pending
-    when strm.avail_out returns with zero.
+    Before making the call, make sure that avail_in and avail_out are not zero.
+    When setting the parameter flush equal to Z_FINISH, also make sure that
+    avail_out is big enough to allow processing all pending input.  Note that a
+    Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be
+    made with more input or output space.  A Z_BUF_ERROR may in fact be
+    unavoidable depending on how the functions are used, since it is not
+    possible to tell whether or not there is more output pending when
+    strm.avail_out returns with zero.  See http://zlib.net/zlib_how.html for a
+    heavily annotated example.
 
  6. Where's the zlib documentation (man pages, etc.)?
 
-    It's in zlib.h for the moment, and Francis S. Lin has converted it to a
-    web page zlib.html. Volunteers to transform this to Unix-style man pages,
-    please contact us (zlib at gzip.org). Examples of zlib usage are in the files
-    example.c and minigzip.c.
+    It's in zlib.h .  Examples of zlib usage are in the files example.c and
+    minigzip.c, with more in examples/ .
 
  7. Why don't you use GNU autoconf or libtool or ...?
 
-    Because we would like to keep zlib as a very small and simple
-    package. zlib is rather portable and doesn't need much configuration.
+    Because we would like to keep zlib as a very small and simple package.
+    zlib is rather portable and doesn't need much configuration.
 
  8. I found a bug in zlib.
 
-    Most of the time, such problems are due to an incorrect usage of
-    zlib. Please try to reproduce the problem with a small program and send
-    the corresponding source to us at zlib at gzip.org . Do not send
-    multi-megabyte data files without prior agreement.
+    Most of the time, such problems are due to an incorrect usage of zlib.
+    Please try to reproduce the problem with a small program and send the
+    corresponding source to us at zlib at gzip.org .  Do not send multi-megabyte
+    data files without prior agreement.
 
  9. Why do I get "undefined reference to gzputc"?
 
@@ -82,7 +79,7 @@
 
 12. Can zlib handle .Z files?
 
-    No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt
+    No, sorry.  You have to spawn an uncompress or gunzip subprocess, or adapt
     the code of uncompress on your own.
 
 13. How can I make a Unix shared library?
@@ -99,8 +96,10 @@
 
     However, many flavors of Unix come with a shared zlib already installed.
     Before going to the trouble of compiling a shared version of zlib and
-    trying to install it, you may want to check if it's already there! If you
-    can #include <zlib.h>, it's there. The -lz option will probably link to it.
+    trying to install it, you may want to check if it's already there!  If you
+    can #include <zlib.h>, it's there.  The -lz option will probably link to
+    it.  You can check the version at the top of zlib.h or with the
+    ZLIB_VERSION symbol defined in zlib.h .
 
 15. I have a question about OttoPDF.
 
@@ -109,8 +108,8 @@
 
 16. Can zlib decode Flate data in an Adobe PDF file?
 
-    Yes. See http://www.fastio.com/ (ClibPDF), or http://www.pdflib.com/ .
-    To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ .
+    Yes. See http://www.pdflib.com/ . To modify PDF forms, see
+    http://sourceforge.net/projects/acroformtool/ .
 
 17. Why am I getting this "register_frame_info not found" error on Solaris?
 
@@ -121,67 +120,67 @@
         symbol __register_frame_info: referenced symbol not found
 
     The symbol __register_frame_info is not part of zlib, it is generated by
-    the C compiler (cc or gcc). You must recompile applications using zlib
-    which have this problem. This problem is specific to Solaris. See
+    the C compiler (cc or gcc).  You must recompile applications using zlib
+    which have this problem.  This problem is specific to Solaris.  See
     http://www.sunfreeware.com for Solaris versions of zlib and applications
     using zlib.
 
 18. Why does gzip give an error on a file I make with compress/deflate?
 
     The compress and deflate functions produce data in the zlib format, which
-    is different and incompatible with the gzip format. The gz* functions in
-    zlib on the other hand use the gzip format. Both the zlib and gzip
-    formats use the same compressed data format internally, but have different
-    headers and trailers around the compressed data.
+    is different and incompatible with the gzip format.  The gz* functions in
+    zlib on the other hand use the gzip format.  Both the zlib and gzip formats
+    use the same compressed data format internally, but have different headers
+    and trailers around the compressed data.
 
 19. Ok, so why are there two different formats?
 
-    The gzip format was designed to retain the directory information about
-    a single file, such as the name and last modification date. The zlib
-    format on the other hand was designed for in-memory and communication
-    channel applications, and has a much more compact header and trailer and
-    uses a faster integrity check than gzip.
+    The gzip format was designed to retain the directory information about a
+    single file, such as the name and last modification date.  The zlib format
+    on the other hand was designed for in-memory and communication channel
+    applications, and has a much more compact header and trailer and uses a
+    faster integrity check than gzip.
 
 20. Well that's nice, but how do I make a gzip file in memory?
 
     You can request that deflate write the gzip format instead of the zlib
-    format using deflateInit2(). You can also request that inflate decode
-    the gzip format using inflateInit2(). Read zlib.h for more details.
+    format using deflateInit2().  You can also request that inflate decode the
+    gzip format using inflateInit2().  Read zlib.h for more details.
 
 21. Is zlib thread-safe?
 
-    Yes. However any library routines that zlib uses and any application-
-    provided memory allocation routines must also be thread-safe. zlib's gz*
+    Yes.  However any library routines that zlib uses and any application-
+    provided memory allocation routines must also be thread-safe.  zlib's gz*
     functions use stdio library routines, and most of zlib's functions use the
-    library memory allocation routines by default. zlib's Init functions allow
-    for the application to provide custom memory allocation routines.
+    library memory allocation routines by default.  zlib's *Init* functions
+    allow for the application to provide custom memory allocation routines.
 
     Of course, you should only operate on any given zlib or gzip stream from a
     single thread at a time.
 
 22. Can I use zlib in my commercial application?
 
-    Yes. Please read the license in zlib.h.
+    Yes.  Please read the license in zlib.h.
 
 23. Is zlib under the GNU license?
 
-    No. Please read the license in zlib.h.
+    No.  Please read the license in zlib.h.
 
 24. The license says that altered source versions must be "plainly marked". So
     what exactly do I need to do to meet that requirement?
 
-    You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
+    You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h.  In
     particular, the final version number needs to be changed to "f", and an
-    identification string should be appended to ZLIB_VERSION. Version numbers
+    identification string should be appended to ZLIB_VERSION.  Version numbers
     x.x.x.f are reserved for modifications to zlib by others than the zlib
-    maintainers. For example, if the version of the base zlib you are altering
+    maintainers.  For example, if the version of the base zlib you are altering
     is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
-    ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also
+    ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3".  You can also
     update the version strings in deflate.c and inftrees.c.
 
     For altered source distributions, you should also note the origin and
     nature of the changes in zlib.h, as well as in ChangeLog and README, along
-    with the dates of the alterations. The origin should include at least your
+    with the dates of the alterations.  The origin should include at least your
     name (or your company's name), and an email address to contact for help or
     issues with the library.
 
@@ -197,105 +196,112 @@
 
 26. Will zlib work on a 64-bit machine?
 
-    It should. It has been tested on 64-bit machines, and has no dependence
-    on any data types being limited to 32-bits in length. If you have any
+    Yes.  It has been tested on 64-bit machines, and has no dependence on any
+    data types being limited to 32-bits in length.  If you have any
     difficulties, please provide a complete problem report to zlib at gzip.org
 
 27. Will zlib decompress data from the PKWare Data Compression Library?
 
-    No. The PKWare DCL uses a completely different compressed data format
-    than does PKZIP and zlib. However, you can look in zlib's contrib/blast
+    No.  The PKWare DCL uses a completely different compressed data format than
+    does PKZIP and zlib.  However, you can look in zlib's contrib/blast
     directory for a possible solution to your problem.
 
 28. Can I access data randomly in a compressed stream?
 
-    No, not without some preparation. If when compressing you periodically
-    use Z_FULL_FLUSH, carefully write all the pending data at those points,
-    and keep an index of those locations, then you can start decompression
-    at those points. You have to be careful to not use Z_FULL_FLUSH too
-    often, since it can significantly degrade compression.
+    No, not without some preparation.  If when compressing you periodically use
+    Z_FULL_FLUSH, carefully write all the pending data at those points, and
+    keep an index of those locations, then you can start decompression at those
+    points.  You have to be careful to not use Z_FULL_FLUSH too often, since it
+    can significantly degrade compression.  Alternatively, you can scan a
+    deflate stream once to generate an index, and then use that index for
+    random access.  See examples/zran.c .
 
 29. Does zlib work on MVS, OS/390, CICS, etc.?
 
-    We don't know for sure. We have heard occasional reports of success on
-    these systems. If you do use it on one of these, please provide us with
-    a report, instructions, and patches that we can reference when we get
-    these questions. Thanks.
+    It has in the past, but we have not heard of any recent evidence.  There
+    were working ports of zlib 1.1.4 to MVS, but those links no longer work.
+    If you know of recent, successful applications of zlib on these operating
+    systems, please let us know.  Thanks.
 
-30. Is there some simpler, easier to read version of inflate I can look at
-    to understand the deflate format?
+30. Is there some simpler, easier to read version of inflate I can look at to
+    understand the deflate format?
 
-    First off, you should read RFC 1951. Second, yes. Look in zlib's
+    First off, you should read RFC 1951.  Second, yes.  Look in zlib's
     contrib/puff directory.
 
 31. Does zlib infringe on any patents?
 
-    As far as we know, no. In fact, that was originally the whole point behind
-    zlib. Look here for some more information:
+    As far as we know, no.  In fact, that was originally the whole point behind
+    zlib.  Look here for some more information:
 
     http://www.gzip.org/#faq11
 
 32. Can zlib work with greater than 4 GB of data?
 
-    Yes. inflate() and deflate() will process any amount of data correctly.
+    Yes.  inflate() and deflate() will process any amount of data correctly.
     Each call of inflate() or deflate() is limited to input and output chunks
     of the maximum value that can be stored in the compiler's "unsigned int"
-    type, but there is no limit to the number of chunks. Note however that the
-    strm.total_in and strm_total_out counters may be limited to 4 GB. These
+    type, but there is no limit to the number of chunks.  Note however that the
+    strm.total_in and strm_total_out counters may be limited to 4 GB.  These
     counters are provided as a convenience and are not used internally by
-    inflate() or deflate(). The application can easily set up its own counters
+    inflate() or deflate().  The application can easily set up its own counters
     updated after each call of inflate() or deflate() to count beyond 4 GB.
     compress() and uncompress() may be limited to 4 GB, since they operate in a
-    single call. gzseek() and gztell() may be limited to 4 GB depending on how
-    zlib is compiled. See the zlibCompileFlags() function in zlib.h.
+    single call.  gzseek() and gztell() may be limited to 4 GB depending on how
+    zlib is compiled.  See the zlibCompileFlags() function in zlib.h.
 
-    The word "may" appears several times above since there is a 4 GB limit
-    only if the compiler's "long" type is 32 bits. If the compiler's "long"
-    type is 64 bits, then the limit is 16 exabytes.
+    The word "may" appears several times above since there is a 4 GB limit only
+    if the compiler's "long" type is 32 bits.  If the compiler's "long" type is
+    64 bits, then the limit is 16 exabytes.
 
 33. Does zlib have any security vulnerabilities?
 
-    The only one that we are aware of is potentially in gzprintf(). If zlib
-    is compiled to use sprintf() or vsprintf(), then there is no protection
-    against a buffer overflow of a 4K string space, other than the caller of
-    gzprintf() assuring that the output will not exceed 4K. On the other
-    hand, if zlib is compiled to use snprintf() or vsnprintf(), which should
-    normally be the case, then there is no vulnerability. The ./configure
-    script will display warnings if an insecure variation of sprintf() will
-    be used by gzprintf(). Also the zlibCompileFlags() function will return
-    information on what variant of sprintf() is used by gzprintf().
+    The only one that we are aware of is potentially in gzprintf().  If zlib is
+    compiled to use sprintf() or vsprintf(), then there is no protection
+    against a buffer overflow of an 8K string space (or other value as set by
+    gzbuffer()), other than the caller of gzprintf() assuring that the output
+    will not exceed 8K.  On the other hand, if zlib is compiled to use
+    snprintf() or vsnprintf(), which should normally be the case, then there is
+    no vulnerability.  The ./configure script will display warnings if an
+    insecure variation of sprintf() will be used by gzprintf().  Also the
+    zlibCompileFlags() function will return information on what variant of
+    sprintf() is used by gzprintf().
 
     If you don't have snprintf() or vsnprintf() and would like one, you can
     find a portable implementation here:
 
         http://www.ijs.si/software/snprintf/
 
-    Note that you should be using the most recent version of zlib. Versions
-    1.1.3 and before were subject to a double-free vulnerability.
+    Note that you should be using the most recent version of zlib.  Versions
+    1.1.3 and before were subject to a double-free vulnerability, and versions
+    1.2.1 and 1.2.2 were subject to an access exception when decompressing
+    invalid compressed data.
 
 34. Is there a Java version of zlib?
 
     Probably what you want is to use zlib in Java. zlib is already included
     as part of the Java SDK in the java.util.zip package. If you really want
     a version of zlib written in the Java language, look on the zlib home
-    page for links: http://www.zlib.org/
+    page for links: http://zlib.net/ .
 
 35. I get this or that compiler or source-code scanner warning when I crank it
     up to maximally-pedantic. Can't you guys write proper code?
 
     Many years ago, we gave up attempting to avoid warnings on every compiler
-    in the universe. It just got to be a waste of time, and some compilers
-    were downright silly. So now, we simply make sure that the code always
-    works.
+    in the universe.  It just got to be a waste of time, and some compilers
+    were downright silly as well as contradicted each other.  So now, we simply
+    make sure that the code always works.
 
 36. Valgrind (or some similar memory access checker) says that deflate is
     performing a conditional jump that depends on an uninitialized value.
     Isn't that a bug?
 
-    No.  That is intentional for performance reasons, and the output of
-    deflate is not affected.  This only started showing up recently since
-    zlib 1.2.x uses malloc() by default for allocations, whereas earlier
-    versions used calloc(), which zeros out the allocated memory.
+    No.  That is intentional for performance reasons, and the output of deflate
+    is not affected.  This only started showing up recently since zlib 1.2.x
+    uses malloc() by default for allocations, whereas earlier versions used
+    calloc(), which zeros out the allocated memory.  Even though the code was
+    correct, versions 1.2.4 and later was changed to not stimulate these
+    checkers.
 
 37. Will zlib read the (insert any ancient or arcane format here) compressed
     data format?
@@ -305,20 +311,21 @@
 
 38. How can I encrypt/decrypt zip files with zlib?
 
-    zlib doesn't support encryption. The original PKZIP encryption is very weak
-    and can be broken with freely available programs. To get strong encryption,
-    use GnuPG, http://www.gnupg.org/ , which already includes zlib compression.
-    For PKZIP compatible "encryption", look at http://www.info-zip.org/
+    zlib doesn't support encryption.  The original PKZIP encryption is very
+    weak and can be broken with freely available programs.  To get strong
+    encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib
+    compression.  For PKZIP compatible "encryption", look at
+    http://www.info-zip.org/
 
 39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
 
-    "gzip" is the gzip format, and "deflate" is the zlib format. They should
-    probably have called the second one "zlib" instead to avoid confusion
-    with the raw deflate compressed data format. While the HTTP 1.1 RFC 2616
+    "gzip" is the gzip format, and "deflate" is the zlib format.  They should
+    probably have called the second one "zlib" instead to avoid confusion with
+    the raw deflate compressed data format.  While the HTTP 1.1 RFC 2616
     correctly points to the zlib specification in RFC 1950 for the "deflate"
     transfer encoding, there have been reports of servers and browsers that
     incorrectly produce or expect raw deflate data per the deflate
-    specficiation in RFC 1951, most notably Microsoft. So even though the
+    specficiation in RFC 1951, most notably Microsoft.  So even though the
     "deflate" transfer encoding using the zlib format would be the more
     efficient approach (and in fact exactly what the zlib format was designed
     for), using the "gzip" transfer encoding is probably more reliable due to
@@ -328,12 +335,32 @@
 
 40. Does zlib support the new "Deflate64" format introduced by PKWare?
 
-    No. PKWare has apparently decided to keep that format proprietary, since
-    they have not documented it as they have previous compression formats.
-    In any case, the compression improvements are so modest compared to other
-    more modern approaches, that it's not worth the effort to implement.
+    No.  PKWare has apparently decided to keep that format proprietary, since
+    they have not documented it as they have previous compression formats.  In
+    any case, the compression improvements are so modest compared to other more
+    modern approaches, that it's not worth the effort to implement.
 
-41. Can you please sign these lengthy legal documents and fax them back to us
+41. I'm having a problem with the zip functions in zlib, can you help?
+
+    There are no zip functions in zlib.  You are probably using minizip by
+    Giles Vollant, which is found in the contrib directory of zlib.  It is not
+    part of zlib.  In fact none of the stuff in contrib is part of zlib.  The
+    files in there are not supported by the zlib authors.  You need to contact
+    the authors of the respective contribution for help.
+
+42. The match.asm code in contrib is under the GNU General Public License.
+    Since it's part of zlib, doesn't that mean that all of zlib falls under the
+    GNU GPL?
+
+    No.  The files in contrib are not part of zlib.  They were contributed by
+    other authors and are provided as a convenience to the user within the zlib
+    distribution.  Each item in contrib has its own license.
+
+43. Is zlib subject to export controls?  What is its ECCN?
+
+    zlib is not subject to export controls, and so is classified as EAR99.
+
+44. Can you please sign these lengthy legal documents and fax them back to us
     so that we can use your software in our product?
 
     No. Go away. Shoo.

Modified: python/branches/py3k-dtoa/Modules/zlib/INDEX
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/INDEX	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/INDEX	Sun Aug  8 12:41:24 2010
@@ -1,23 +1,32 @@
+CMakeLists.txt  cmake build file
 ChangeLog       history of changes
 FAQ             Frequently Asked Questions about zlib
 INDEX           this file
-Makefile        makefile for Unix (generated by configure)
-Makefile.in     makefile for Unix (template for configure)
+Makefile        dummy Makefile that tells you to ./configure
+Makefile.in     template for Unix Makefile
 README          guess what
-algorithm.txt   description of the (de)compression algorithm
 configure       configure script for Unix
-zconf.in.h      template for zconf.h (used by configure)
+make_vms.com    makefile for VMS
+treebuild.xml   XML description of source file dependencies
+zconf.h.cmakein zconf.h template for cmake
+zconf.h.in      zconf.h template for configure
+zlib.3          Man page for zlib
+zlib.3.pdf      Man page in PDF format
+zlib.map        Linux symbol information
+zlib.pc.in      Template for pkg-config descriptor
+zlib2ansi       perl script to convert source files for C++ compilation
 
 amiga/          makefiles for Amiga SAS C
-as400/          makefiles for IBM AS/400
+doc/            documentation for formats and algorithms
 msdos/          makefiles for MSDOS
+nintendods/     makefile for Nintendo DS
 old/            makefiles for various architectures and zlib documentation
                 files that have not yet been updated for zlib 1.2.x
-projects/       projects for various Integrated Development Environments
 qnx/            makefiles for QNX
+watcom/         makefiles for OpenWatcom
 win32/          makefiles for Windows
 
-                zlib public header files (must be kept):
+                zlib public header files (required for library use):
 zconf.h
 zlib.h
 
@@ -28,7 +37,11 @@
 crc32.h
 deflate.c
 deflate.h
-gzio.c
+gzclose.c
+gzguts.h
+gzlib.c
+gzread.c
+gzwrite.c
 infback.c
 inffast.c
 inffast.h
@@ -46,6 +59,7 @@
                 source files for sample programs:
 example.c
 minigzip.c
+See examples/README.examples for more
 
                 unsupported contribution by third parties
 See contrib/README.contrib

Modified: python/branches/py3k-dtoa/Modules/zlib/Makefile
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/Makefile	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/Makefile	Sun Aug  8 12:41:24 2010
@@ -1,154 +1,5 @@
-# Makefile for zlib
-# Copyright (C) 1995-2005 Jean-loup Gailly.
-# For conditions of distribution and use, see copyright notice in zlib.h
+all:
+	- at echo "Please use ./configure first.  Thank you."
 
-# To compile and test, type:
-#    ./configure; make test
-# The call of configure is optional if you don't have special requirements
-# If you wish to build zlib as a shared library, use: ./configure -s
-
-# To use the asm code, type:
-#    cp contrib/asm?86/match.S ./match.S
-#    make LOC=-DASMV OBJA=match.o
-
-# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
-#    make install
-# To install in $HOME instead of /usr/local, use:
-#    make install prefix=$HOME
-
-CC=cc
-
-CFLAGS=-O
-#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
-#CFLAGS=-g -DDEBUG
-#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
-#           -Wstrict-prototypes -Wmissing-prototypes
-
-LDFLAGS=libz.a
-LDSHARED=$(CC)
-CPP=$(CC) -E
-
-LIBS=libz.a
-SHAREDLIB=libz.so
-SHAREDLIBV=libz.so.1.2.3
-SHAREDLIBM=libz.so.1
-
-AR=ar rc
-RANLIB=ranlib
-TAR=tar
-SHELL=/bin/sh
-EXE=
-
-prefix = /usr/local
-exec_prefix = ${prefix}
-libdir = ${exec_prefix}/lib
-includedir = ${prefix}/include
-mandir = ${prefix}/share/man
-man3dir = ${mandir}/man3
-
-OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
-       zutil.o inflate.o infback.o inftrees.o inffast.o
-
-OBJA =
-# to use the asm code: make OBJA=match.o
-
-TEST_OBJS = example.o minigzip.o
-
-all: example$(EXE) minigzip$(EXE)
-
-check: test
-test: all
-	@LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
-	echo hello world | ./minigzip | ./minigzip -d || \
-	  echo '		*** minigzip test FAILED ***' ; \
-	if ./example; then \
-	  echo '		*** zlib test OK ***'; \
-	else \
-	  echo '		*** zlib test FAILED ***'; \
-	fi
-
-libz.a: $(OBJS) $(OBJA)
-	$(AR) $@ $(OBJS) $(OBJA)
-	-@ ($(RANLIB) $@ || true) >/dev/null 2>&1
-
-match.o: match.S
-	$(CPP) match.S > _match.s
-	$(CC) -c _match.s
-	mv _match.o match.o
-	rm -f _match.s
-
-$(SHAREDLIBV): $(OBJS)
-	$(LDSHARED) -o $@ $(OBJS)
-	rm -f $(SHAREDLIB) $(SHAREDLIBM)
-	ln -s $@ $(SHAREDLIB)
-	ln -s $@ $(SHAREDLIBM)
-
-example$(EXE): example.o $(LIBS)
-	$(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
-
-minigzip$(EXE): minigzip.o $(LIBS)
-	$(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
-
-install: $(LIBS)
-	- at if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
-	- at if [ ! -d $(includedir)  ]; then mkdir -p $(includedir); fi
-	- at if [ ! -d $(libdir)      ]; then mkdir -p $(libdir); fi
-	- at if [ ! -d $(man3dir)     ]; then mkdir -p $(man3dir); fi
-	cp zlib.h zconf.h $(includedir)
-	chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
-	cp $(LIBS) $(libdir)
-	cd $(libdir); chmod 755 $(LIBS)
-	-@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
-	cd $(libdir); if test -f $(SHAREDLIBV); then \
-	  rm -f $(SHAREDLIB) $(SHAREDLIBM); \
-	  ln -s $(SHAREDLIBV) $(SHAREDLIB); \
-	  ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
-	  (ldconfig || true)  >/dev/null 2>&1; \
-	fi
-	cp zlib.3 $(man3dir)
-	chmod 644 $(man3dir)/zlib.3
-# The ranlib in install is needed on NeXTSTEP which checks file times
-# ldconfig is for Linux
-
-uninstall:
-	cd $(includedir); \
-	cd $(libdir); rm -f libz.a; \
-	if test -f $(SHAREDLIBV); then \
-	  rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
-	fi
-	cd $(man3dir); rm -f zlib.3
-
-mostlyclean: clean
-clean:
-	rm -f *.o *~ example$(EXE) minigzip$(EXE) \
-	   libz.* foo.gz so_locations \
-	   _match.s maketree contrib/infback9/*.o
-
-maintainer-clean: distclean
-distclean: clean
-	cp -p Makefile.in Makefile
-	cp -p zconf.in.h zconf.h
-	rm -f .DS_Store
-
-tags:
-	etags *.[ch]
-
-depend:
-	makedepend -- $(CFLAGS) -- *.[ch]
-
-# DO NOT DELETE THIS LINE -- make depend depends on it.
-
-adler32.o: zlib.h zconf.h
-compress.o: zlib.h zconf.h
-crc32.o: crc32.h zlib.h zconf.h
-deflate.o: deflate.h zutil.h zlib.h zconf.h
-example.o: zlib.h zconf.h
-gzio.o: zutil.h zlib.h zconf.h
-inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
-inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
-infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
-inftrees.o: zutil.h zlib.h zconf.h inftrees.h
-minigzip.o: zlib.h zconf.h
-trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
-uncompr.o: zlib.h zconf.h
-zutil.o: zutil.h zlib.h zconf.h
+distclean:
+	make -f Makefile.in distclean

Modified: python/branches/py3k-dtoa/Modules/zlib/Makefile.in
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/Makefile.in	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/Makefile.in	Sun Aug  8 12:41:24 2010
@@ -1,11 +1,11 @@
 # Makefile for zlib
-# Copyright (C) 1995-2005 Jean-loup Gailly.
+# Copyright (C) 1995-2010 Jean-loup Gailly.
 # For conditions of distribution and use, see copyright notice in zlib.h
 
 # To compile and test, type:
 #    ./configure; make test
-# The call of configure is optional if you don't have special requirements
-# If you wish to build zlib as a shared library, use: ./configure -s
+# Normally configure builds both a static and a shared library.
+# If you want to build just a static library, use: ./configure --static
 
 # To use the asm code, type:
 #    cp contrib/asm?86/match.S ./match.S
@@ -24,17 +24,22 @@
 #CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
 #           -Wstrict-prototypes -Wmissing-prototypes
 
-LDFLAGS=libz.a
+SFLAGS=-O
+LDFLAGS=
+TEST_LDFLAGS=-L. libz.a
 LDSHARED=$(CC)
 CPP=$(CC) -E
 
-LIBS=libz.a
+STATICLIB=libz.a
 SHAREDLIB=libz.so
-SHAREDLIBV=libz.so.1.2.3
+SHAREDLIBV=libz.so.1.2.5
 SHAREDLIBM=libz.so.1
+LIBS=$(STATICLIB) $(SHAREDLIBV)
 
 AR=ar rc
 RANLIB=ranlib
+LDCONFIG=ldconfig
+LDSHAREDLIBC=-lc
 TAR=tar
 SHELL=/bin/sh
 EXE=
@@ -42,33 +47,68 @@
 prefix = /usr/local
 exec_prefix = ${prefix}
 libdir = ${exec_prefix}/lib
+sharedlibdir = ${libdir}
 includedir = ${prefix}/include
 mandir = ${prefix}/share/man
 man3dir = ${mandir}/man3
+pkgconfigdir = ${libdir}/pkgconfig
 
-OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
-       zutil.o inflate.o infback.o inftrees.o inffast.o
+OBJC = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \
+	gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o
 
+PIC_OBJC = adler32.lo compress.lo crc32.lo deflate.lo gzclose.lo gzlib.lo gzread.lo \
+	gzwrite.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo uncompr.lo zutil.lo
+
+# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo
 OBJA =
-# to use the asm code: make OBJA=match.o
+PIC_OBJA =
+
+OBJS = $(OBJC) $(OBJA)
+
+PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA)
+
+all: static shared
 
-TEST_OBJS = example.o minigzip.o
+static: example$(EXE) minigzip$(EXE)
 
-all: example$(EXE) minigzip$(EXE)
+shared: examplesh$(EXE) minigzipsh$(EXE)
+
+all64: example64$(EXE) minigzip64$(EXE)
 
 check: test
-test: all
-	@LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
-	echo hello world | ./minigzip | ./minigzip -d || \
-	  echo '		*** minigzip test FAILED ***' ; \
-	if ./example; then \
+
+test: all teststatic testshared
+
+teststatic: static
+	@if echo hello world | ./minigzip | ./minigzip -d && ./example; then \
 	  echo '		*** zlib test OK ***'; \
 	else \
-	  echo '		*** zlib test FAILED ***'; \
+	  echo '		*** zlib test FAILED ***'; false; \
+	fi
+	- at rm -f foo.gz
+
+testshared: shared
+	@LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
+	LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \
+	DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \
+	SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \
+	if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh; then \
+	  echo '		*** zlib shared test OK ***'; \
+	else \
+	  echo '		*** zlib shared test FAILED ***'; false; \
+	fi
+	- at rm -f foo.gz
+
+test64: all64
+	@if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64; then \
+	  echo '		*** zlib 64-bit test OK ***'; \
+	else \
+	  echo '		*** zlib 64-bit test FAILED ***'; false; \
 	fi
+	- at rm -f foo.gz
 
-libz.a: $(OBJS) $(OBJA)
-	$(AR) $@ $(OBJS) $(OBJA)
+libz.a: $(OBJS)
+	$(AR) $@ $(OBJS)
 	-@ ($(RANLIB) $@ || true) >/dev/null 2>&1
 
 match.o: match.S
@@ -77,58 +117,116 @@
 	mv _match.o match.o
 	rm -f _match.s
 
-$(SHAREDLIBV): $(OBJS)
-	$(LDSHARED) -o $@ $(OBJS)
+match.lo: match.S
+	$(CPP) match.S > _match.s
+	$(CC) -c -fPIC _match.s
+	mv _match.o match.lo
+	rm -f _match.s
+
+example64.o: example.c zlib.h zconf.h
+	$(CC) $(CFLAGS) -D_FILE_OFFSET_BITS=64 -c -o $@ example.c
+
+minigzip64.o: minigzip.c zlib.h zconf.h
+	$(CC) $(CFLAGS) -D_FILE_OFFSET_BITS=64 -c -o $@ minigzip.c
+
+.SUFFIXES: .lo
+
+.c.lo:
+	- at mkdir objs 2>/dev/null || test -d objs
+	$(CC) $(SFLAGS) -DPIC -c -o objs/$*.o $<
+	- at mv objs/$*.o $@
+
+$(SHAREDLIBV): $(PIC_OBJS)
+	$(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS)
 	rm -f $(SHAREDLIB) $(SHAREDLIBM)
 	ln -s $@ $(SHAREDLIB)
 	ln -s $@ $(SHAREDLIBM)
+	- at rmdir objs
 
-example$(EXE): example.o $(LIBS)
-	$(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
+example$(EXE): example.o $(STATICLIB)
+	$(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS)
 
-minigzip$(EXE): minigzip.o $(LIBS)
-	$(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
+minigzip$(EXE): minigzip.o $(STATICLIB)
+	$(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS)
 
-install: $(LIBS)
-	- at if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
-	- at if [ ! -d $(includedir)  ]; then mkdir -p $(includedir); fi
-	- at if [ ! -d $(libdir)      ]; then mkdir -p $(libdir); fi
-	- at if [ ! -d $(man3dir)     ]; then mkdir -p $(man3dir); fi
-	cp zlib.h zconf.h $(includedir)
-	chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
-	cp $(LIBS) $(libdir)
-	cd $(libdir); chmod 755 $(LIBS)
-	-@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
-	cd $(libdir); if test -f $(SHAREDLIBV); then \
+examplesh$(EXE): example.o $(SHAREDLIBV)
+	$(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV)
+
+minigzipsh$(EXE): minigzip.o $(SHAREDLIBV)
+	$(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV)
+
+example64$(EXE): example64.o $(STATICLIB)
+	$(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS)
+
+minigzip64$(EXE): minigzip64.o $(STATICLIB)
+	$(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS)
+
+install-libs: $(LIBS)
+	- at if [ ! -d $(DESTDIR)$(exec_prefix)  ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
+	- at if [ ! -d $(DESTDIR)$(libdir)       ]; then mkdir -p $(DESTDIR)$(libdir); fi
+	- at if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi
+	- at if [ ! -d $(DESTDIR)$(man3dir)      ]; then mkdir -p $(DESTDIR)$(man3dir); fi
+	- at if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
+	cp $(STATICLIB) $(DESTDIR)$(libdir)
+	cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)
+	cd $(DESTDIR)$(libdir); chmod u=rw,go=r $(STATICLIB)
+	-@(cd $(DESTDIR)$(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
+	- at cd $(DESTDIR)$(sharedlibdir); if test "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \
+	  chmod 755 $(SHAREDLIBV); \
 	  rm -f $(SHAREDLIB) $(SHAREDLIBM); \
 	  ln -s $(SHAREDLIBV) $(SHAREDLIB); \
 	  ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
-	  (ldconfig || true)  >/dev/null 2>&1; \
+	  ($(LDCONFIG) || true)  >/dev/null 2>&1; \
 	fi
-	cp zlib.3 $(man3dir)
-	chmod 644 $(man3dir)/zlib.3
+	cp zlib.3 $(DESTDIR)$(man3dir)
+	chmod 644 $(DESTDIR)$(man3dir)/zlib.3
+	cp zlib.pc $(DESTDIR)$(pkgconfigdir)
+	chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc
 # The ranlib in install is needed on NeXTSTEP which checks file times
 # ldconfig is for Linux
 
+install: install-libs
+	- at if [ ! -d $(DESTDIR)$(includedir)   ]; then mkdir -p $(DESTDIR)$(includedir); fi
+	cp zlib.h zconf.h $(DESTDIR)$(includedir)
+	chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
+
 uninstall:
-	cd $(includedir); \
-	cd $(libdir); rm -f libz.a; \
-	if test -f $(SHAREDLIBV); then \
+	cd $(DESTDIR)$(includedir); rm -f zlib.h zconf.h
+	cd $(DESTDIR)$(libdir); rm -f libz.a; \
+	if test "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \
 	  rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
 	fi
-	cd $(man3dir); rm -f zlib.3
+	cd $(DESTDIR)$(man3dir); rm -f zlib.3
+	cd $(DESTDIR)$(pkgconfigdir); rm -f zlib.pc
+
+docs: zlib.3.pdf
+
+zlib.3.pdf: zlib.3
+	groff -mandoc -f H -T ps zlib.3 | ps2pdf - zlib.3.pdf
+
+zconf.h.in: zconf.h.cmakein
+	sed "/^#cmakedefine/D" < zconf.h.cmakein > zconf.h.in
+	touch -r zconf.h.cmakein zconf.h.in
+
+zconf: zconf.h.in
+	cp -p zconf.h.in zconf.h
 
 mostlyclean: clean
 clean:
-	rm -f *.o *~ example$(EXE) minigzip$(EXE) \
+	rm -f *.o *.lo *~ \
+	   example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \
+	   example64$(EXE) minigzip64$(EXE) \
 	   libz.* foo.gz so_locations \
 	   _match.s maketree contrib/infback9/*.o
+	rm -rf objs
 
 maintainer-clean: distclean
-distclean: clean
-	cp -p Makefile.in Makefile
-	cp -p zconf.in.h zconf.h
-	rm -f .DS_Store
+distclean: clean zconf docs
+	rm -f Makefile zlib.pc
+	- at rm -f .DS_Store
+	- at printf 'all:\n\t- at echo "Please use ./configure first.  Thank you."\n' > Makefile
+	- at printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile
+	- at touch -r Makefile.in Makefile
 
 tags:
 	etags *.[ch]
@@ -138,17 +236,22 @@
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
-adler32.o: zlib.h zconf.h
-compress.o: zlib.h zconf.h
-crc32.o: crc32.h zlib.h zconf.h
+adler32.o zutil.o: zutil.h zlib.h zconf.h
+gzclose.o gzlib.o gzread.o gzwrite.o: zlib.h zconf.h gzguts.h
+compress.o example.o minigzip.o uncompr.o: zlib.h zconf.h
+crc32.o: zutil.h zlib.h zconf.h crc32.h
 deflate.o: deflate.h zutil.h zlib.h zconf.h
-example.o: zlib.h zconf.h
-gzio.o: zutil.h zlib.h zconf.h
+infback.o inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
 inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
-inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
-infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
 inftrees.o: zutil.h zlib.h zconf.h inftrees.h
-minigzip.o: zlib.h zconf.h
 trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
-uncompr.o: zlib.h zconf.h
-zutil.o: zutil.h zlib.h zconf.h
+
+adler32.lo zutil.lo: zutil.h zlib.h zconf.h
+gzclose.lo gzlib.lo gzread.lo gzwrite.lo: zlib.h zconf.h gzguts.h
+compress.lo example.lo minigzip.lo uncompr.lo: zlib.h zconf.h
+crc32.lo: zutil.h zlib.h zconf.h crc32.h
+deflate.lo: deflate.h zutil.h zlib.h zconf.h
+infback.lo inflate.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
+inffast.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.lo: zutil.h zlib.h zconf.h inftrees.h
+trees.lo: deflate.h zutil.h zlib.h zconf.h trees.h

Modified: python/branches/py3k-dtoa/Modules/zlib/README
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/README	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/README	Sun Aug  8 12:41:24 2010
@@ -1,56 +1,52 @@
 ZLIB DATA COMPRESSION LIBRARY
 
-zlib 1.2.3 is a general purpose data compression library.  All the code is
+zlib 1.2.5 is a general purpose data compression library.  All the code is
 thread safe.  The data format used by the zlib library is described by RFCs
 (Request for Comments) 1950 to 1952 in the files
 http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
-and rfc1952.txt (gzip format). These documents are also available in other
-formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
+and rfc1952.txt (gzip format).
 
 All functions of the compression library are documented in the file zlib.h
-(volunteer to write man pages welcome, contact zlib at gzip.org). A usage example
+(volunteer to write man pages welcome, contact zlib at gzip.org).  A usage example
 of the library is given in the file example.c which also tests that the library
-is working correctly. Another example is given in the file minigzip.c. The
+is working correctly.  Another example is given in the file minigzip.c.  The
 compression library itself is composed of all source files except example.c and
 minigzip.c.
 
 To compile all files and run the test program, follow the instructions given at
-the top of Makefile. In short "make test; make install" should work for most
-machines. For Unix: "./configure; make test; make install". For MSDOS, use one
-of the special makefiles such as Makefile.msc. For VMS, use make_vms.com.
+the top of Makefile.in.  In short "./configure; make test", and if that goes
+well, "make install" should work for most flavors of Unix.  For Windows, use one
+of the special makefiles in win32/ or contrib/vstudio/ .  For VMS, use
+make_vms.com.
 
 Questions about zlib should be sent to <zlib at gzip.org>, or to Gilles Vollant
-<info at winimage.com> for the Windows DLL version. The zlib home page is
-http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem,
-please check this site to verify that you have the latest version of zlib;
-otherwise get the latest version and check whether the problem still exists or
-not.
-
-PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking
-for help.
-
-Mark Nelson <markn at ieee.org> wrote an article about zlib for the Jan. 1997
-issue of  Dr. Dobb's Journal; a copy of the article is available in
-http://dogma.net/markn/articles/zlibtool/zlibtool.htm
-
-The changes made in version 1.2.3 are documented in the file ChangeLog.
-
-Unsupported third party contributions are provided in directory "contrib".
-
-A Java implementation of zlib is available in the Java Development Kit
-http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html
-See the zlib home page http://www.zlib.org for details.
-
-A Perl interface to zlib written by Paul Marquess <pmqs at cpan.org> is in the
-CPAN (Comprehensive Perl Archive Network) sites
-http://www.cpan.org/modules/by-module/Compress/
+<info at winimage.com> for the Windows DLL version.  The zlib home page is
+http://zlib.net/ .  Before reporting a problem, please check this site to
+verify that you have the latest version of zlib; otherwise get the latest
+version and check whether the problem still exists or not.
+
+PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
+
+Mark Nelson <markn at ieee.org> wrote an article about zlib for the Jan.  1997
+issue of Dr.  Dobb's Journal; a copy of the article is available at
+http://marknelson.us/1997/01/01/zlib-engine/ .
+
+The changes made in version 1.2.5 are documented in the file ChangeLog.
+
+Unsupported third party contributions are provided in directory contrib/ .
+
+zlib is available in Java using the java.util.zip package, documented at
+http://java.sun.com/developer/technicalArticles/Programming/compression/ .
+
+A Perl interface to zlib written by Paul Marquess <pmqs at cpan.org> is available
+at CPAN (Comprehensive Perl Archive Network) sites, including
+http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
 
 A Python interface to zlib written by A.M. Kuchling <amk at amk.ca> is
 available in Python 1.5 and later versions, see
-http://www.python.org/doc/lib/module-zlib.html
+http://www.python.org/doc/lib/module-zlib.html .
 
-A zlib binding for TCL written by Andreas Kupries <a.kupries at westend.com> is
-availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html
+zlib is built into tcl: http://wiki.tcl.tk/4610 .
 
 An experimental package to read and write files in .zip format, written on top
 of zlib by Gilles Vollant <info at winimage.com>, is available in the
@@ -74,25 +70,21 @@
 - zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
   other compilers. Use "make test" to check your compiler.
 
-- gzdopen is not supported on BEOS and by some Mac compilers.
+- gzdopen is not supported on RISCOS or BEOS.
 
 - For PalmOs, see http://palmzlib.sourceforge.net/
 
-- When building a shared, i.e. dynamic library on Mac OS X, the library must be
-  installed before testing (do "make install" before "make test"), since the
-  library location is specified in the library.
-
 
 Acknowledgments:
 
-  The deflate format used by zlib was defined by Phil Katz. The deflate
-  and zlib specifications were written by L. Peter Deutsch. Thanks to all the
-  people who reported problems and suggested various improvements in zlib;
-  they are too numerous to cite here.
+  The deflate format used by zlib was defined by Phil Katz.  The deflate and
+  zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
+  people who reported problems and suggested various improvements in zlib; they
+  are too numerous to cite here.
 
 Copyright notice:
 
- (C) 1995-2004 Jean-loup Gailly and Mark Adler
+ (C) 1995-2010 Jean-loup Gailly and Mark Adler
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -113,13 +105,11 @@
   Jean-loup Gailly        Mark Adler
   jloup at gzip.org          madler at alumni.caltech.edu
 
-If you use the zlib library in a product, we would appreciate *not*
-receiving lengthy legal documents to sign. The sources are provided
-for free but without warranty of any kind.  The library has been
-entirely written by Jean-loup Gailly and Mark Adler; it does not
-include third-party code.
-
-If you redistribute modified sources, we would appreciate that you include
-in the file ChangeLog history information documenting your changes. Please
-read the FAQ for more information on the distribution of modified source
-versions.
+If you use the zlib library in a product, we would appreciate *not* receiving
+lengthy legal documents to sign.  The sources are provided for free but without
+warranty of any kind.  The library has been entirely written by Jean-loup
+Gailly and Mark Adler; it does not include third-party code.
+
+If you redistribute modified sources, we would appreciate that you include in
+the file ChangeLog history information documenting your changes.  Please read
+the FAQ for more information on the distribution of modified source versions.

Modified: python/branches/py3k-dtoa/Modules/zlib/adler32.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/adler32.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/adler32.c	Sun Aug  8 12:41:24 2010
@@ -1,12 +1,15 @@
 /* adler32.c -- compute the Adler-32 checksum of a data stream
- * Copyright (C) 1995-2004 Mark Adler
+ * Copyright (C) 1995-2007 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
 /* @(#) $Id$ */
 
-#define ZLIB_INTERNAL
-#include "zlib.h"
+#include "zutil.h"
+
+#define local static
+
+local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2);
 
 #define BASE 65521UL    /* largest prime smaller than 65536 */
 #define NMAX 5552
@@ -125,10 +128,10 @@
 }
 
 /* ========================================================================= */
-uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+local uLong adler32_combine_(adler1, adler2, len2)
     uLong adler1;
     uLong adler2;
-    z_off_t len2;
+    z_off64_t len2;
 {
     unsigned long sum1;
     unsigned long sum2;
@@ -141,9 +144,26 @@
     MOD(sum2);
     sum1 += (adler2 & 0xffff) + BASE - 1;
     sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
-    if (sum1 > BASE) sum1 -= BASE;
-    if (sum1 > BASE) sum1 -= BASE;
-    if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
-    if (sum2 > BASE) sum2 -= BASE;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
+    if (sum2 >= BASE) sum2 -= BASE;
     return sum1 | (sum2 << 16);
 }
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
+
+uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}

Modified: python/branches/py3k-dtoa/Modules/zlib/compress.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/compress.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/compress.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* compress.c -- compress a memory buffer
- * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -75,5 +75,6 @@
 uLong ZEXPORT compressBound (sourceLen)
     uLong sourceLen;
 {
-    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13;
 }

Modified: python/branches/py3k-dtoa/Modules/zlib/configure
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/configure	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/configure	Sun Aug  8 12:41:24 2010
@@ -1,37 +1,61 @@
 #!/bin/sh
-# configure script for zlib. This script is needed only if
-# you wish to build a shared library and your system supports them,
-# of if you need special compiler, flags or install directory.
-# Otherwise, you can just use directly "make test; make install"
+# configure script for zlib.
 #
-# To create a shared library, use "configure --shared"; by default a static
-# library is created. If the primitive shared library support provided here
-# does not work, use ftp://prep.ai.mit.edu/pub/gnu/libtool-*.tar.gz
+# Normally configure builds both a static and a shared library.
+# If you want to build just a static library, use: ./configure --static
 #
 # To impose specific compiler or flags or install directory, use for example:
 #    prefix=$HOME CC=cc CFLAGS="-O4" ./configure
 # or for csh/tcsh users:
 #    (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
-# LDSHARED is the command to be used to create a shared library
 
 # Incorrect settings of CC or CFLAGS may prevent creating a shared library.
 # If you have problems, try without defining CC and CFLAGS before reporting
 # an error.
 
-LIBS=libz.a
-LDFLAGS="-L. ${LIBS}"
+if [ -n "${CHOST}" ]; then
+    uname="$(echo "${CHOST}" | sed -e 's/^[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)-.*$/\1/')"
+    CROSS_PREFIX="${CHOST}-"
+fi
+
+STATICLIB=libz.a
+LDFLAGS="${LDFLAGS} -L. ${STATICLIB}"
 VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`
+VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\).*/\1/p' < zlib.h`
 VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
 VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h`
-AR=${AR-"ar rc"}
-RANLIB=${RANLIB-"ranlib"}
+if "${CROSS_PREFIX}ar" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+    AR=${AR-"${CROSS_PREFIX}ar"}
+    test -n "${CROSS_PREFIX}" && echo Using ${AR}
+else
+    AR=${AR-"ar"}
+    test -n "${CROSS_PREFIX}" && echo Using ${AR}
+fi
+AR_RC="${AR} rc"
+if "${CROSS_PREFIX}ranlib" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+    RANLIB=${RANLIB-"${CROSS_PREFIX}ranlib"}
+    test -n "${CROSS_PREFIX}" && echo Using ${RANLIB}
+else
+    RANLIB=${RANLIB-"ranlib"}
+fi
+if "${CROSS_PREFIX}nm" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+    NM=${NM-"${CROSS_PREFIX}nm"}
+    test -n "${CROSS_PREFIX}" && echo Using ${NM}
+else
+    NM=${NM-"nm"}
+fi
+LDCONFIG=${LDCONFIG-"ldconfig"}
+LDSHAREDLIBC="${LDSHAREDLIBC--lc}"
 prefix=${prefix-/usr/local}
 exec_prefix=${exec_prefix-'${prefix}'}
 libdir=${libdir-'${exec_prefix}/lib'}
+sharedlibdir=${sharedlibdir-'${libdir}'}
 includedir=${includedir-'${prefix}/include'}
 mandir=${mandir-'${prefix}/share/man'}
 shared_ext='.so'
-shared=0
+shared=1
+zprefix=0
+build64=0
 gcc=0
 old_cc="$CC"
 old_cflags="$CFLAGS"
@@ -39,21 +63,29 @@
 while test $# -ge 1
 do
 case "$1" in
-    -h* | --h*)
+    -h* | --help)
       echo 'usage:'
-      echo '  configure [--shared] [--prefix=PREFIX]  [--exec_prefix=EXPREFIX]'
-      echo '     [--libdir=LIBDIR] [--includedir=INCLUDEDIR]'
-        exit 0;;
-    -p*=* | --p*=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
-    -e*=* | --e*=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
-    -l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
-    -i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift;;
-    -p* | --p*) prefix="$2"; shift; shift;;
-    -e* | --e*) exec_prefix="$2"; shift; shift;;
-    -l* | --l*) libdir="$2"; shift; shift;;
-    -i* | --i*) includedir="$2"; shift; shift;;
-    -s* | --s*) shared=1; shift;;
-    *) echo "unknown option: $1"; echo "$0 --help for help"; exit 1;;
+      echo '  configure [--zprefix] [--prefix=PREFIX]  [--eprefix=EXPREFIX]'
+      echo '    [--static] [--64] [--libdir=LIBDIR] [--sharedlibdir=LIBDIR]'
+      echo '    [--includedir=INCLUDEDIR]'
+        exit 0 ;;
+    -p*=* | --prefix=*) prefix=`echo $1 | sed 's/.*=//'`; shift ;;
+    -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/.*=//'`; shift ;;
+    -l*=* | --libdir=*) libdir=`echo $1 | sed 's/.*=//'`; shift ;;
+    --sharedlibdir=*) sharedlibdir=`echo $1 | sed 's/.*=//'`; shift ;;
+    -i*=* | --includedir=*) includedir=`echo $1 | sed 's/.*=//'`;shift ;;
+    -u*=* | --uname=*) uname=`echo $1 | sed 's/.*=//'`;shift ;;
+    -p* | --prefix) prefix="$2"; shift; shift ;;
+    -e* | --eprefix) exec_prefix="$2"; shift; shift ;;
+    -l* | --libdir) libdir="$2"; shift; shift ;;
+    -i* | --includedir) includedir="$2"; shift; shift ;;
+    -s* | --shared | --enable-shared) shared=1; shift ;;
+    -t | --static) shared=0; shift ;;
+    -z* | --zprefix) zprefix=1; shift ;;
+    -6* | --64) build64=1; shift ;;
+    --sysconfdir=*) echo "ignored option: --sysconfdir"; shift ;;
+    --localstatedir=*) echo "ignored option: --localstatedir"; shift ;;
+    *) echo "unknown option: $1"; echo "$0 --help for help"; exit 1 ;;
     esac
 done
 
@@ -63,46 +95,68 @@
 int hello() {return getchar();}
 EOF
 
-test -z "$CC" && echo Checking for gcc...
-cc=${CC-gcc}
+test -z "$CC" && echo Checking for ${CROSS_PREFIX}gcc...
+cc=${CC-${CROSS_PREFIX}gcc}
 cflags=${CFLAGS-"-O3"}
 # to force the asm version use: CFLAGS="-O3 -DASMV" ./configure
 case "$cc" in
-  *gcc*) gcc=1;;
+  *gcc*) gcc=1 ;;
 esac
 
 if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then
   CC="$cc"
-  SFLAGS=${CFLAGS-"-fPIC -O3"}
-  CFLAGS="$cflags"
-  case `(uname -s || echo unknown) 2>/dev/null` in
-  Linux | linux | GNU | GNU/*) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1"};;
-  CYGWIN* | Cygwin* | cygwin* | OS/2* )
-             EXE='.exe';;
+  SFLAGS="${CFLAGS--O3} -fPIC"
+  CFLAGS="${CFLAGS--O3}"
+  if test $build64 -eq 1; then
+    CFLAGS="${CFLAGS} -m64"
+    SFLAGS="${SFLAGS} -m64"
+  fi
+  if test "${ZLIBGCCWARN}" = "YES"; then
+    CFLAGS="${CFLAGS} -Wall -Wextra -pedantic"
+  fi
+  if test -z "$uname"; then
+    uname=`(uname -s || echo unknown) 2>/dev/null`
+  fi
+  case "$uname" in
+  Linux* | linux* | GNU | GNU/* | *BSD | DragonFly) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map"} ;;
+  CYGWIN* | Cygwin* | cygwin* | OS/2*)
+        EXE='.exe' ;;
+  MINGW*|mingw*)
+# temporary bypass
+        rm -f $test.[co] $test $test$shared_ext
+        echo "Please use win32/Makefile.gcc instead."
+        exit 1
+        LDSHARED=${LDSHARED-"$cc -shared"}
+        LDSHAREDLIBC=""
+        EXE='.exe' ;;
   QNX*)  # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
          # (alain.bonnefoy at icbt.com)
-                 LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"};;
+                 LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;;
   HP-UX*)
          LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
          case `(uname -m || echo unknown) 2>/dev/null` in
          ia64)
                  shared_ext='.so'
-                 SHAREDLIB='libz.so';;
+                 SHAREDLIB='libz.so' ;;
          *)
                  shared_ext='.sl'
-                 SHAREDLIB='libz.sl';;
-         esac;;
+                 SHAREDLIB='libz.sl' ;;
+         esac ;;
   Darwin*)   shared_ext='.dylib'
              SHAREDLIB=libz$shared_ext
              SHAREDLIBV=libz.$VER$shared_ext
              SHAREDLIBM=libz.$VER1$shared_ext
-             LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER"};;
-  *)             LDSHARED=${LDSHARED-"$cc -shared"};;
+             LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"} ;;
+  *)             LDSHARED=${LDSHARED-"$cc -shared"} ;;
   esac
 else
   # find system name and corresponding cc options
   CC=${CC-cc}
-  case `(uname -sr || echo unknown) 2>/dev/null` in
+  gcc=0
+  if test -z "$uname"; then
+    uname=`(uname -sr || echo unknown) 2>/dev/null`
+  fi
+  case "$uname" in
   HP-UX*)    SFLAGS=${CFLAGS-"-O +z"}
              CFLAGS=${CFLAGS-"-O"}
 #            LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
@@ -110,57 +164,64 @@
          case `(uname -m || echo unknown) 2>/dev/null` in
          ia64)
              shared_ext='.so'
-             SHAREDLIB='libz.so';;
+             SHAREDLIB='libz.so' ;;
          *)
              shared_ext='.sl'
-             SHAREDLIB='libz.sl';;
-         esac;;
+             SHAREDLIB='libz.sl' ;;
+         esac ;;
   IRIX*)     SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
              CFLAGS=${CFLAGS-"-ansi -O2"}
-             LDSHARED=${LDSHARED-"cc -shared"};;
+             LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
   OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
              CFLAGS=${CFLAGS-"-O -std1"}
-             LDSHARED=${LDSHARED-"cc -shared  -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"};;
+             LDFLAGS="${LDFLAGS} -Wl,-rpath,."
+             LDSHARED=${LDSHARED-"cc -shared  -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;;
   OSF1*)     SFLAGS=${CFLAGS-"-O -std1"}
              CFLAGS=${CFLAGS-"-O -std1"}
-             LDSHARED=${LDSHARED-"cc -shared"};;
+             LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
   QNX*)      SFLAGS=${CFLAGS-"-4 -O"}
              CFLAGS=${CFLAGS-"-4 -O"}
              LDSHARED=${LDSHARED-"cc"}
              RANLIB=${RANLIB-"true"}
-             AR="cc -A";;
+             AR_RC="cc -A" ;;
   SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
              CFLAGS=${CFLAGS-"-O3"}
-             LDSHARED=${LDSHARED-"cc -dy -KPIC -G"};;
-  SunOS\ 5*) SFLAGS=${CFLAGS-"-fast -xcg89 -KPIC -R."}
-             CFLAGS=${CFLAGS-"-fast -xcg89"}
-             LDSHARED=${LDSHARED-"cc -G"};;
+             LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;;
+  SunOS\ 5*) LDSHARED=${LDSHARED-"cc -G"}
+         case `(uname -m || echo unknown) 2>/dev/null` in
+         i86*)
+             SFLAGS=${CFLAGS-"-xpentium -fast -KPIC -R."}
+             CFLAGS=${CFLAGS-"-xpentium -fast"} ;;
+         *)
+             SFLAGS=${CFLAGS-"-fast -xcg92 -KPIC -R."}
+             CFLAGS=${CFLAGS-"-fast -xcg92"} ;;
+         esac ;;
   SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
              CFLAGS=${CFLAGS-"-O2"}
-             LDSHARED=${LDSHARED-"ld"};;
-  SunStudio\ 9*) SFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
-             CFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xtarget=ultra3 -xarch=v9b"}
-             LDSHARED=${LDSHARED-"cc -xarch=v9b"};;
+             LDSHARED=${LDSHARED-"ld"} ;;
+  SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
+             CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"}
+             LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;;
   UNIX_System_V\ 4.2.0)
              SFLAGS=${CFLAGS-"-KPIC -O"}
              CFLAGS=${CFLAGS-"-O"}
-             LDSHARED=${LDSHARED-"cc -G"};;
+             LDSHARED=${LDSHARED-"cc -G"} ;;
   UNIX_SV\ 4.2MP)
              SFLAGS=${CFLAGS-"-Kconform_pic -O"}
              CFLAGS=${CFLAGS-"-O"}
-             LDSHARED=${LDSHARED-"cc -G"};;
+             LDSHARED=${LDSHARED-"cc -G"} ;;
   OpenUNIX\ 5)
              SFLAGS=${CFLAGS-"-KPIC -O"}
              CFLAGS=${CFLAGS-"-O"}
-             LDSHARED=${LDSHARED-"cc -G"};;
+             LDSHARED=${LDSHARED-"cc -G"} ;;
   AIX*)  # Courtesy of dbakker at arrayasolutions.com
              SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
              CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
-             LDSHARED=${LDSHARED-"xlc -G"};;
-  # send working options for other systems to support at gzip.org
+             LDSHARED=${LDSHARED-"xlc -G"} ;;
+  # send working options for other systems to zlib at gzip.org
   *)         SFLAGS=${CFLAGS-"-O"}
              CFLAGS=${CFLAGS-"-O"}
-             LDSHARED=${LDSHARED-"cc -shared"};;
+             LDSHARED=${LDSHARED-"cc -shared"} ;;
   esac
 fi
 
@@ -171,38 +232,83 @@
 if test $shared -eq 1; then
   echo Checking for shared library support...
   # we must test in two steps (cc then ld), required at least on SunOS 4.x
-  if test "`($CC -c $SFLAGS $test.c) 2>&1`" = "" &&
-     test "`($LDSHARED -o $test$shared_ext $test.o) 2>&1`" = ""; then
-    CFLAGS="$SFLAGS"
-    LIBS="$SHAREDLIBV"
+  if test "`($CC -w -c $SFLAGS $test.c) 2>&1`" = "" &&
+     test "`($LDSHARED $SFLAGS -o $test$shared_ext $test.o) 2>&1`" = ""; then
     echo Building shared library $SHAREDLIBV with $CC.
   elif test -z "$old_cc" -a -z "$old_cflags"; then
     echo No shared library support.
     shared=0;
   else
+    echo Tested $CC -w -c $SFLAGS $test.c
+    $CC -w -c $SFLAGS $test.c
+    echo Tested $LDSHARED $SFLAGS -o $test$shared_ext $test.o
+    $LDSHARED $SFLAGS -o $test$shared_ext $test.o
     echo 'No shared library support; try without defining CC and CFLAGS'
     shared=0;
   fi
 fi
 if test $shared -eq 0; then
   LDSHARED="$CC"
-  echo Building static library $LIBS version $VER with $CC.
+  ALL="static"
+  TEST="all teststatic"
+  SHAREDLIB=""
+  SHAREDLIBV=""
+  SHAREDLIBM=""
+  echo Building static library $STATICLIB version $VER with $CC.
 else
-  LDFLAGS="-L. ${SHAREDLIBV}"
+  ALL="static shared"
+  TEST="all teststatic testshared"
 fi
 
 cat > $test.c <<EOF
+#include <sys/types.h>
+off64_t dummy = 0;
+EOF
+if test "`($CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c) 2>&1`" = ""; then
+  CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1"
+  SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1"
+  ALL="${ALL} all64"
+  TEST="${TEST} test64"
+  echo "Checking for off64_t... Yes."
+  echo "Checking for fseeko... Yes."
+else
+  echo "Checking for off64_t... No."
+  cat > $test.c <<EOF
+#include <stdio.h>
+int main(void) {
+  fseeko(NULL, 0, 0);
+  return 0;
+}
+EOF
+  if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
+    echo "Checking for fseeko... Yes."
+  else
+    CFLAGS="${CFLAGS} -DNO_FSEEKO"
+    SFLAGS="${SFLAGS} -DNO_FSEEKO"
+    echo "Checking for fseeko... No."
+  fi
+fi
+
+cp -p zconf.h.in zconf.h
+
+cat > $test.c <<EOF
 #include <unistd.h>
 int main() { return 0; }
 EOF
 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
-  sed < zconf.in.h "/HAVE_UNISTD_H/s%0%1%" > zconf.h
+  sed < zconf.h "/^#ifdef HAVE_UNISTD_H.* may be/s/def HAVE_UNISTD_H\(.*\) may be/ 1\1 was/" > zconf.temp.h
+  mv zconf.temp.h zconf.h
   echo "Checking for unistd.h... Yes."
 else
-  cp -p zconf.in.h zconf.h
   echo "Checking for unistd.h... No."
 fi
 
+if test $zprefix -eq 1; then
+  sed < zconf.h "/#ifdef Z_PREFIX.* may be/s/def Z_PREFIX\(.*\) may be/ 1\1 was/" > zconf.temp.h
+  mv zconf.temp.h zconf.h
+  echo "Using z_ prefix on all symbols."
+fi
+
 cat > $test.c <<EOF
 #include <stdio.h>
 #include <stdarg.h>
@@ -219,13 +325,13 @@
 EOF
 
 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
-  echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()"
+  echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()."
 
   cat > $test.c <<EOF
 #include <stdio.h>
 #include <stdarg.h>
 
-int mytest(char *fmt, ...)
+int mytest(const char *fmt, ...)
 {
   char buf[20];
   va_list ap;
@@ -249,7 +355,7 @@
 #include <stdio.h>
 #include <stdarg.h>
 
-int mytest(char *fmt, ...)
+int mytest(const char *fmt, ...)
 {
   int n;
   char buf[20];
@@ -271,6 +377,7 @@
       echo "Checking for return value of vsnprintf()... Yes."
     else
       CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
+      SFLAGS="$SFLAGS -DHAS_vsnprintf_void"
       echo "Checking for return value of vsnprintf()... No."
       echo "  WARNING: apparently vsnprintf() does not return a value. zlib"
       echo "  can build but will be open to possible string-format security"
@@ -278,6 +385,7 @@
     fi
   else
     CFLAGS="$CFLAGS -DNO_vsnprintf"
+    SFLAGS="$SFLAGS -DNO_vsnprintf"
     echo "Checking for vsnprintf() in stdio.h... No."
     echo "  WARNING: vsnprintf() not found, falling back to vsprintf(). zlib"
     echo "  can build but will be open to possible buffer-overflow security"
@@ -287,7 +395,7 @@
 #include <stdio.h>
 #include <stdarg.h>
 
-int mytest(char *fmt, ...)
+int mytest(const char *fmt, ...)
 {
   int n;
   char buf[20];
@@ -309,6 +417,7 @@
       echo "Checking for return value of vsprintf()... Yes."
     else
       CFLAGS="$CFLAGS -DHAS_vsprintf_void"
+      SFLAGS="$SFLAGS -DHAS_vsprintf_void"
       echo "Checking for return value of vsprintf()... No."
       echo "  WARNING: apparently vsprintf() does not return a value. zlib"
       echo "  can build but will be open to possible string-format security"
@@ -316,7 +425,7 @@
     fi
   fi
 else
-  echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()"
+  echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()."
 
   cat >$test.c <<EOF
 #include <stdio.h>
@@ -358,6 +467,7 @@
       echo "Checking for return value of snprintf()... Yes."
     else
       CFLAGS="$CFLAGS -DHAS_snprintf_void"
+      SFLAGS="$SFLAGS -DHAS_snprintf_void"
       echo "Checking for return value of snprintf()... No."
       echo "  WARNING: apparently snprintf() does not return a value. zlib"
       echo "  can build but will be open to possible string-format security"
@@ -365,6 +475,7 @@
     fi
   else
     CFLAGS="$CFLAGS -DNO_snprintf"
+    SFLAGS="$SFLAGS -DNO_snprintf"
     echo "Checking for snprintf() in stdio.h... No."
     echo "  WARNING: snprintf() not found, falling back to sprintf(). zlib"
     echo "  can build but will be open to possible buffer-overflow security"
@@ -390,6 +501,7 @@
       echo "Checking for return value of sprintf()... Yes."
     else
       CFLAGS="$CFLAGS -DHAS_sprintf_void"
+      SFLAGS="$SFLAGS -DHAS_sprintf_void"
       echo "Checking for return value of sprintf()... No."
       echo "  WARNING: apparently sprintf() does not return a value. zlib"
       echo "  can build but will be open to possible string-format security"
@@ -398,41 +510,37 @@
   fi
 fi
 
-cat >$test.c <<EOF
-#include <errno.h>
-int main() { return 0; }
-EOF
-if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
-  echo "Checking for errno.h... Yes."
-else
-  echo "Checking for errno.h... No."
-  CFLAGS="$CFLAGS -DNO_ERRNO_H"
-fi
-
-cat > $test.c <<EOF
-#include <sys/types.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-caddr_t hello() {
-  return mmap((caddr_t)0, (off_t)0, PROT_READ, MAP_SHARED, 0, (off_t)0);
+if test "$gcc" -eq 1; then
+  cat > $test.c <<EOF
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+int ZLIB_INTERNAL foo;
+int main()
+{
+  return 0;
 }
 EOF
-if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
-  CFLAGS="$CFLAGS -DUSE_MMAP"
-  echo Checking for mmap support... Yes.
-else
-  echo Checking for mmap support... No.
+  if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
+    echo "Checking for attribute(visibility) support... Yes."
+  else
+    CFLAGS="$CFLAGS -DNO_VIZ"
+    SFLAGS="$SFLAGS -DNO_VIZ"
+    echo "Checking for attribute(visibility) support... No."
+  fi
 fi
 
 CPP=${CPP-"$CC -E"}
 case $CFLAGS in
   *ASMV*)
-    if test "`nm $test.o | grep _hello`" = ""; then
+    if test "`$NM $test.o | grep _hello`" = ""; then
       CPP="$CPP -DNO_UNDERLINE"
       echo Checking for underline in external names... No.
     else
       echo Checking for underline in external names... Yes.
-    fi;;
+    fi ;;
 esac
 
 rm -f $test.[co] $test $test$shared_ext
@@ -441,19 +549,48 @@
 sed < Makefile.in "
 /^CC *=/s#=.*#=$CC#
 /^CFLAGS *=/s#=.*#=$CFLAGS#
+/^SFLAGS *=/s#=.*#=$SFLAGS#
+/^LDFLAGS *=/s#=.*#=$LDFLAGS#
+/^LDSHARED *=/s#=.*#=$LDSHARED#
+/^CPP *=/s#=.*#=$CPP#
+/^STATICLIB *=/s#=.*#=$STATICLIB#
+/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
+/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
+/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
+/^AR *=/s#=.*#=$AR_RC#
+/^RANLIB *=/s#=.*#=$RANLIB#
+/^LDCONFIG *=/s#=.*#=$LDCONFIG#
+/^LDSHAREDLIBC *=/s#=.*#=$LDSHAREDLIBC#
+/^EXE *=/s#=.*#=$EXE#
+/^prefix *=/s#=.*#=$prefix#
+/^exec_prefix *=/s#=.*#=$exec_prefix#
+/^libdir *=/s#=.*#=$libdir#
+/^sharedlibdir *=/s#=.*#=$sharedlibdir#
+/^includedir *=/s#=.*#=$includedir#
+/^mandir *=/s#=.*#=$mandir#
+/^all: */s#:.*#: $ALL#
+/^test: */s#:.*#: $TEST#
+" > Makefile
+
+sed < zlib.pc.in "
+/^CC *=/s#=.*#=$CC#
+/^CFLAGS *=/s#=.*#=$CFLAGS#
 /^CPP *=/s#=.*#=$CPP#
 /^LDSHARED *=/s#=.*#=$LDSHARED#
-/^LIBS *=/s#=.*#=$LIBS#
+/^STATICLIB *=/s#=.*#=$STATICLIB#
 /^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
 /^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
 /^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
-/^AR *=/s#=.*#=$AR#
+/^AR *=/s#=.*#=$AR_RC#
 /^RANLIB *=/s#=.*#=$RANLIB#
 /^EXE *=/s#=.*#=$EXE#
 /^prefix *=/s#=.*#=$prefix#
 /^exec_prefix *=/s#=.*#=$exec_prefix#
 /^libdir *=/s#=.*#=$libdir#
+/^sharedlibdir *=/s#=.*#=$sharedlibdir#
 /^includedir *=/s#=.*#=$includedir#
 /^mandir *=/s#=.*#=$mandir#
 /^LDFLAGS *=/s#=.*#=$LDFLAGS#
-" > Makefile
+" | sed -e "
+s/\@VERSION\@/$VER/g;
+" > zlib.pc

Modified: python/branches/py3k-dtoa/Modules/zlib/crc32.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/crc32.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/crc32.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* crc32.c -- compute the CRC-32 of a data stream
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2006, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  *
  * Thanks to Rodney Brown <rbrown64 at csc.com.au> for his contribution of faster
@@ -53,7 +53,7 @@
 
 /* Definitions for doing the crc four data bytes at a time. */
 #ifdef BYFOUR
-#  define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
+#  define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \
                 (((w)&0xff00)<<8)+(((w)&0xff)<<24))
    local unsigned long crc32_little OF((unsigned long,
                         const unsigned char FAR *, unsigned));
@@ -68,6 +68,8 @@
 local unsigned long gf2_matrix_times OF((unsigned long *mat,
                                          unsigned long vec));
 local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
+local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2);
+
 
 #ifdef DYNAMIC_CRC_TABLE
 
@@ -219,7 +221,7 @@
 unsigned long ZEXPORT crc32(crc, buf, len)
     unsigned long crc;
     const unsigned char FAR *buf;
-    unsigned len;
+    uInt len;
 {
     if (buf == Z_NULL) return 0UL;
 
@@ -367,22 +369,22 @@
 }
 
 /* ========================================================================= */
-uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+local uLong crc32_combine_(crc1, crc2, len2)
     uLong crc1;
     uLong crc2;
-    z_off_t len2;
+    z_off64_t len2;
 {
     int n;
     unsigned long row;
     unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
     unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
 
-    /* degenerate case */
-    if (len2 == 0)
+    /* degenerate case (also disallow negative lengths) */
+    if (len2 <= 0)
         return crc1;
 
     /* put operator for one zero bit in odd */
-    odd[0] = 0xedb88320L;           /* CRC-32 polynomial */
+    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
     row = 1;
     for (n = 1; n < GF2_DIM; n++) {
         odd[n] = row;
@@ -421,3 +423,20 @@
     crc1 ^= crc2;
     return crc1;
 }
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
+
+uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}

Modified: python/branches/py3k-dtoa/Modules/zlib/deflate.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/deflate.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/deflate.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* deflate.c -- compress data using the deflation algorithm
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -52,7 +52,7 @@
 #include "deflate.h"
 
 const char deflate_copyright[] =
-   " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
+   " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler ";
 /*
   If you use the zlib library in a product, an acknowledgment is welcome
   in the documentation of your product. If for some reason you cannot
@@ -79,19 +79,18 @@
 #ifndef FASTEST
 local block_state deflate_slow   OF((deflate_state *s, int flush));
 #endif
+local block_state deflate_rle    OF((deflate_state *s, int flush));
+local block_state deflate_huff   OF((deflate_state *s, int flush));
 local void lm_init        OF((deflate_state *s));
 local void putShortMSB    OF((deflate_state *s, uInt b));
 local void flush_pending  OF((z_streamp strm));
 local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
-#ifndef FASTEST
 #ifdef ASMV
       void match_init OF((void)); /* asm code initialization */
       uInt longest_match  OF((deflate_state *s, IPos cur_match));
 #else
 local uInt longest_match  OF((deflate_state *s, IPos cur_match));
 #endif
-#endif
-local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
 
 #ifdef DEBUG
 local  void check_match OF((deflate_state *s, IPos start, IPos match,
@@ -110,11 +109,6 @@
 #endif
 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
 
-#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
-/* Minimum amount of lookahead, except at the end of the input file.
- * See deflate.c for comments about the MIN_MATCH+1.
- */
-
 /* Values for max_lazy_match, good_match and max_chain_length, depending on
  * the desired pack level (0..9). The values given below have been tuned to
  * exclude worst case performance for pathological files. Better values may be
@@ -288,6 +282,8 @@
     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
 
+    s->high_water = 0;      /* nothing written to s->window yet */
+
     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
 
     overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
@@ -332,8 +328,8 @@
         strm->adler = adler32(strm->adler, dictionary, dictLength);
 
     if (length < MIN_MATCH) return Z_OK;
-    if (length > MAX_DIST(s)) {
-        length = MAX_DIST(s);
+    if (length > s->w_size) {
+        length = s->w_size;
         dictionary += dictLength - length; /* use the tail of the dictionary */
     }
     zmemcpy(s->window, dictionary, length);
@@ -435,9 +431,10 @@
     }
     func = configuration_table[s->level].func;
 
-    if (func != configuration_table[level].func && strm->total_in != 0) {
+    if ((strategy != s->strategy || func != configuration_table[level].func) &&
+        strm->total_in != 0) {
         /* Flush the last buffer: */
-        err = deflate(strm, Z_PARTIAL_FLUSH);
+        err = deflate(strm, Z_BLOCK);
     }
     if (s->level != level) {
         s->level = level;
@@ -481,33 +478,66 @@
  * resulting from using fixed blocks instead of stored blocks, which deflate
  * can emit on compressed data for some combinations of the parameters.
  *
- * This function could be more sophisticated to provide closer upper bounds
- * for every combination of windowBits and memLevel, as well as wrap.
- * But even the conservative upper bound of about 14% expansion does not
- * seem onerous for output buffer allocation.
+ * This function could be more sophisticated to provide closer upper bounds for
+ * every combination of windowBits and memLevel.  But even the conservative
+ * upper bound of about 14% expansion does not seem onerous for output buffer
+ * allocation.
  */
 uLong ZEXPORT deflateBound(strm, sourceLen)
     z_streamp strm;
     uLong sourceLen;
 {
     deflate_state *s;
-    uLong destLen;
+    uLong complen, wraplen;
+    Bytef *str;
 
-    /* conservative upper bound */
-    destLen = sourceLen +
-              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
+    /* conservative upper bound for compressed data */
+    complen = sourceLen +
+              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
 
-    /* if can't get parameters, return conservative bound */
+    /* if can't get parameters, return conservative bound plus zlib wrapper */
     if (strm == Z_NULL || strm->state == Z_NULL)
-        return destLen;
+        return complen + 6;
 
-    /* if not default parameters, return conservative bound */
+    /* compute wrapper length */
     s = strm->state;
+    switch (s->wrap) {
+    case 0:                                 /* raw deflate */
+        wraplen = 0;
+        break;
+    case 1:                                 /* zlib wrapper */
+        wraplen = 6 + (s->strstart ? 4 : 0);
+        break;
+    case 2:                                 /* gzip wrapper */
+        wraplen = 18;
+        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
+            if (s->gzhead->extra != Z_NULL)
+                wraplen += 2 + s->gzhead->extra_len;
+            str = s->gzhead->name;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            str = s->gzhead->comment;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            if (s->gzhead->hcrc)
+                wraplen += 2;
+        }
+        break;
+    default:                                /* for compiler happiness */
+        wraplen = 6;
+    }
+
+    /* if not default parameters, return conservative bound */
     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
-        return destLen;
+        return complen + wraplen;
 
     /* default settings: return tight bound for that case */
-    return compressBound(sourceLen);
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13 - 6 + wraplen;
 }
 
 /* =========================================================================
@@ -557,7 +587,7 @@
     deflate_state *s;
 
     if (strm == Z_NULL || strm->state == Z_NULL ||
-        flush > Z_FINISH || flush < 0) {
+        flush > Z_BLOCK || flush < 0) {
         return Z_STREAM_ERROR;
     }
     s = strm->state;
@@ -581,7 +611,7 @@
             put_byte(s, 31);
             put_byte(s, 139);
             put_byte(s, 8);
-            if (s->gzhead == NULL) {
+            if (s->gzhead == Z_NULL) {
                 put_byte(s, 0);
                 put_byte(s, 0);
                 put_byte(s, 0);
@@ -608,7 +638,7 @@
                             (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
                              4 : 0));
                 put_byte(s, s->gzhead->os & 0xff);
-                if (s->gzhead->extra != NULL) {
+                if (s->gzhead->extra != Z_NULL) {
                     put_byte(s, s->gzhead->extra_len & 0xff);
                     put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
                 }
@@ -650,7 +680,7 @@
     }
 #ifdef GZIP
     if (s->status == EXTRA_STATE) {
-        if (s->gzhead->extra != NULL) {
+        if (s->gzhead->extra != Z_NULL) {
             uInt beg = s->pending;  /* start of bytes to update crc */
 
             while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
@@ -678,7 +708,7 @@
             s->status = NAME_STATE;
     }
     if (s->status == NAME_STATE) {
-        if (s->gzhead->name != NULL) {
+        if (s->gzhead->name != Z_NULL) {
             uInt beg = s->pending;  /* start of bytes to update crc */
             int val;
 
@@ -709,7 +739,7 @@
             s->status = COMMENT_STATE;
     }
     if (s->status == COMMENT_STATE) {
-        if (s->gzhead->comment != NULL) {
+        if (s->gzhead->comment != Z_NULL) {
             uInt beg = s->pending;  /* start of bytes to update crc */
             int val;
 
@@ -787,7 +817,9 @@
         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
         block_state bstate;
 
-        bstate = (*(configuration_table[s->level].func))(s, flush);
+        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
+                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :
+                        (*(configuration_table[s->level].func))(s, flush));
 
         if (bstate == finish_started || bstate == finish_done) {
             s->status = FINISH_STATE;
@@ -808,13 +840,17 @@
         if (bstate == block_done) {
             if (flush == Z_PARTIAL_FLUSH) {
                 _tr_align(s);
-            } else { /* FULL_FLUSH or SYNC_FLUSH */
+            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
                 _tr_stored_block(s, (char*)0, 0L, 0);
                 /* For a full flush, this empty block will be recognized
                  * as a special marker by inflate_sync().
                  */
                 if (flush == Z_FULL_FLUSH) {
                     CLEAR_HASH(s);             /* forget history */
+                    if (s->lookahead == 0) {
+                        s->strstart = 0;
+                        s->block_start = 0L;
+                    }
                 }
             }
             flush_pending(strm);
@@ -1167,12 +1203,13 @@
     return s->lookahead;
 }
 #endif /* ASMV */
-#endif /* FASTEST */
+
+#else /* FASTEST */
 
 /* ---------------------------------------------------------------------------
- * Optimized version for level == 1 or strategy == Z_RLE only
+ * Optimized version for FASTEST only
  */
-local uInt longest_match_fast(s, cur_match)
+local uInt longest_match(s, cur_match)
     deflate_state *s;
     IPos cur_match;                             /* current match */
 {
@@ -1225,6 +1262,8 @@
     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
 }
 
+#endif /* FASTEST */
+
 #ifdef DEBUG
 /* ===========================================================================
  * Check that the match at match_start is indeed a match.
@@ -1303,7 +1342,6 @@
                later. (Using level 0 permanently is not an optimal usage of
                zlib, so we don't care about this pathological case.)
              */
-            /* %%% avoid this when Z_RLE */
             n = s->hash_size;
             p = &s->head[n];
             do {
@@ -1355,27 +1393,61 @@
          */
 
     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
+
+    /* If the WIN_INIT bytes after the end of the current data have never been
+     * written, then zero those bytes in order to avoid memory check reports of
+     * the use of uninitialized (or uninitialised as Julian writes) bytes by
+     * the longest match routines.  Update the high water mark for the next
+     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
+     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
+     */
+    if (s->high_water < s->window_size) {
+        ulg curr = s->strstart + (ulg)(s->lookahead);
+        ulg init;
+
+        if (s->high_water < curr) {
+            /* Previous high water mark below current data -- zero WIN_INIT
+             * bytes or up to end of window, whichever is less.
+             */
+            init = s->window_size - curr;
+            if (init > WIN_INIT)
+                init = WIN_INIT;
+            zmemzero(s->window + curr, (unsigned)init);
+            s->high_water = curr + init;
+        }
+        else if (s->high_water < (ulg)curr + WIN_INIT) {
+            /* High water mark at or above current data, but below current data
+             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
+             * to end of window, whichever is less.
+             */
+            init = (ulg)curr + WIN_INIT - s->high_water;
+            if (init > s->window_size - s->high_water)
+                init = s->window_size - s->high_water;
+            zmemzero(s->window + s->high_water, (unsigned)init);
+            s->high_water += init;
+        }
+    }
 }
 
 /* ===========================================================================
  * Flush the current block, with given end-of-file flag.
  * IN assertion: strstart is set to the end of the current match.
  */
-#define FLUSH_BLOCK_ONLY(s, eof) { \
+#define FLUSH_BLOCK_ONLY(s, last) { \
    _tr_flush_block(s, (s->block_start >= 0L ? \
                    (charf *)&s->window[(unsigned)s->block_start] : \
                    (charf *)Z_NULL), \
                 (ulg)((long)s->strstart - s->block_start), \
-                (eof)); \
+                (last)); \
    s->block_start = s->strstart; \
    flush_pending(s->strm); \
    Tracev((stderr,"[FLUSH]")); \
 }
 
 /* Same but force premature exit if necessary. */
-#define FLUSH_BLOCK(s, eof) { \
-   FLUSH_BLOCK_ONLY(s, eof); \
-   if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
+#define FLUSH_BLOCK(s, last) { \
+   FLUSH_BLOCK_ONLY(s, last); \
+   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
 }
 
 /* ===========================================================================
@@ -1449,7 +1521,7 @@
     deflate_state *s;
     int flush;
 {
-    IPos hash_head = NIL; /* head of the hash chain */
+    IPos hash_head;       /* head of the hash chain */
     int bflush;           /* set if current block must be flushed */
 
     for (;;) {
@@ -1469,6 +1541,7 @@
         /* Insert the string window[strstart .. strstart+2] in the
          * dictionary, and set hash_head to the head of the hash chain:
          */
+        hash_head = NIL;
         if (s->lookahead >= MIN_MATCH) {
             INSERT_STRING(s, s->strstart, hash_head);
         }
@@ -1481,19 +1554,8 @@
              * of window index 0 (in particular we have to avoid a match
              * of the string with itself at the start of the input file).
              */
-#ifdef FASTEST
-            if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
-                (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
-                s->match_length = longest_match_fast (s, hash_head);
-            }
-#else
-            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
-                s->match_length = longest_match (s, hash_head);
-            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
-                s->match_length = longest_match_fast (s, hash_head);
-            }
-#endif
-            /* longest_match() or longest_match_fast() sets match_start */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
         }
         if (s->match_length >= MIN_MATCH) {
             check_match(s, s->strstart, s->match_start, s->match_length);
@@ -1555,7 +1617,7 @@
     deflate_state *s;
     int flush;
 {
-    IPos hash_head = NIL;    /* head of hash chain */
+    IPos hash_head;          /* head of hash chain */
     int bflush;              /* set if current block must be flushed */
 
     /* Process the input block. */
@@ -1576,6 +1638,7 @@
         /* Insert the string window[strstart .. strstart+2] in the
          * dictionary, and set hash_head to the head of the hash chain:
          */
+        hash_head = NIL;
         if (s->lookahead >= MIN_MATCH) {
             INSERT_STRING(s, s->strstart, hash_head);
         }
@@ -1591,12 +1654,8 @@
              * of window index 0 (in particular we have to avoid a match
              * of the string with itself at the start of the input file).
              */
-            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
-                s->match_length = longest_match (s, hash_head);
-            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
-                s->match_length = longest_match_fast (s, hash_head);
-            }
-            /* longest_match() or longest_match_fast() sets match_start */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
 
             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
 #if TOO_FAR <= 32767
@@ -1674,7 +1733,6 @@
 }
 #endif /* FASTEST */
 
-#if 0
 /* ===========================================================================
  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
@@ -1684,11 +1742,9 @@
     deflate_state *s;
     int flush;
 {
-    int bflush;         /* set if current block must be flushed */
-    uInt run;           /* length of run */
-    uInt max;           /* maximum length of run */
-    uInt prev;          /* byte at distance one to match */
-    Bytef *scan;        /* scan for end of run */
+    int bflush;             /* set if current block must be flushed */
+    uInt prev;              /* byte at distance one to match */
+    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
 
     for (;;) {
         /* Make sure that we always have enough lookahead, except
@@ -1704,23 +1760,33 @@
         }
 
         /* See how many times the previous byte repeats */
-        run = 0;
-        if (s->strstart > 0) {      /* if there is a previous byte, that is */
-            max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
+        s->match_length = 0;
+        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
             scan = s->window + s->strstart - 1;
-            prev = *scan++;
-            do {
-                if (*scan++ != prev)
-                    break;
-            } while (++run < max);
+            prev = *scan;
+            if (prev == *++scan && prev == *++scan && prev == *++scan) {
+                strend = s->window + s->strstart + MAX_MATCH;
+                do {
+                } while (prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         scan < strend);
+                s->match_length = MAX_MATCH - (int)(strend - scan);
+                if (s->match_length > s->lookahead)
+                    s->match_length = s->lookahead;
+            }
         }
 
         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
-        if (run >= MIN_MATCH) {
-            check_match(s, s->strstart, s->strstart - 1, run);
-            _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
-            s->lookahead -= run;
-            s->strstart += run;
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->strstart - 1, s->match_length);
+
+            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+            s->strstart += s->match_length;
+            s->match_length = 0;
         } else {
             /* No match, output a literal byte */
             Tracevv((stderr,"%c", s->window[s->strstart]));
@@ -1733,4 +1799,36 @@
     FLUSH_BLOCK(s, flush == Z_FINISH);
     return flush == Z_FINISH ? finish_done : block_done;
 }
-#endif
+
+/* ===========================================================================
+ * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
+ * (It will be regenerated if this run of deflate switches away from Huffman.)
+ */
+local block_state deflate_huff(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;             /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we have a literal to write. */
+        if (s->lookahead == 0) {
+            fill_window(s);
+            if (s->lookahead == 0) {
+                if (flush == Z_NO_FLUSH)
+                    return need_more;
+                break;      /* flush the current block */
+            }
+        }
+
+        /* Output a literal byte */
+        s->match_length = 0;
+        Tracevv((stderr,"%c", s->window[s->strstart]));
+        _tr_tally_lit (s, s->window[s->strstart], bflush);
+        s->lookahead--;
+        s->strstart++;
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    FLUSH_BLOCK(s, flush == Z_FINISH);
+    return flush == Z_FINISH ? finish_done : block_done;
+}

Modified: python/branches/py3k-dtoa/Modules/zlib/deflate.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/deflate.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/deflate.h	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* deflate.h -- internal compression state
- * Copyright (C) 1995-2004 Jean-loup Gailly
+ * Copyright (C) 1995-2010 Jean-loup Gailly
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -260,6 +260,13 @@
      * are always zero.
      */
 
+    ulg high_water;
+    /* High water mark offset in window for initialized bytes -- bytes above
+     * this are set to zero in order to avoid memory check warnings when
+     * longest match routines access bytes past the input.  This is then
+     * updated to the new high water mark.
+     */
+
 } FAR deflate_state;
 
 /* Output a byte on the stream.
@@ -278,14 +285,18 @@
  * distances are limited to MAX_DIST instead of WSIZE.
  */
 
+#define WIN_INIT MAX_MATCH
+/* Number of bytes after end of data in window to initialize in order to avoid
+   memory checker errors from longest match routines */
+
         /* in trees.c */
-void _tr_init         OF((deflate_state *s));
-int  _tr_tally        OF((deflate_state *s, unsigned dist, unsigned lc));
-void _tr_flush_block  OF((deflate_state *s, charf *buf, ulg stored_len,
-                          int eof));
-void _tr_align        OF((deflate_state *s));
-void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
-                          int eof));
+void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
+int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
+void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
+void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
+void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
 
 #define d_code(dist) \
    ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
@@ -298,11 +309,11 @@
 /* Inline versions of _tr_tally for speed: */
 
 #if defined(GEN_TREES_H) || !defined(STDC)
-  extern uch _length_code[];
-  extern uch _dist_code[];
+  extern uch ZLIB_INTERNAL _length_code[];
+  extern uch ZLIB_INTERNAL _dist_code[];
 #else
-  extern const uch _length_code[];
-  extern const uch _dist_code[];
+  extern const uch ZLIB_INTERNAL _length_code[];
+  extern const uch ZLIB_INTERNAL _dist_code[];
 #endif
 
 # define _tr_tally_lit(s, c, flush) \

Modified: python/branches/py3k-dtoa/Modules/zlib/example.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/example.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/example.c	Sun Aug  8 12:41:24 2010
@@ -1,19 +1,19 @@
 /* example.c -- usage example of the zlib compression library
- * Copyright (C) 1995-2004 Jean-loup Gailly.
+ * Copyright (C) 1995-2006 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
 /* @(#) $Id$ */
 
-#include <stdio.h>
 #include "zlib.h"
+#include <stdio.h>
 
 #ifdef STDC
 #  include <string.h>
 #  include <stdlib.h>
 #endif
 
-#if defined(VMS)
+#if defined(VMS) || defined(RISCOS)
 #  define TESTFILE "foo-gz"
 #else
 #  define TESTFILE "foo.gz"

Modified: python/branches/py3k-dtoa/Modules/zlib/infback.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/infback.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/infback.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* infback.c -- inflate using a call-back interface
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2009 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -55,7 +55,7 @@
     state->wbits = windowBits;
     state->wsize = 1U << windowBits;
     state->window = window;
-    state->write = 0;
+    state->wnext = 0;
     state->whave = 0;
     return Z_OK;
 }
@@ -253,7 +253,7 @@
     unsigned bits;              /* bits in bit buffer */
     unsigned copy;              /* number of stored or match bytes to copy */
     unsigned char FAR *from;    /* where to copy match bytes from */
-    code this;                  /* current decoding table entry */
+    code here;                  /* current decoding table entry */
     code last;                  /* parent table entry */
     unsigned len;               /* length to copy for repeats, bits to drop */
     int ret;                    /* return code */
@@ -389,19 +389,19 @@
             state->have = 0;
             while (state->have < state->nlen + state->ndist) {
                 for (;;) {
-                    this = state->lencode[BITS(state->lenbits)];
-                    if ((unsigned)(this.bits) <= bits) break;
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
                     PULLBYTE();
                 }
-                if (this.val < 16) {
-                    NEEDBITS(this.bits);
-                    DROPBITS(this.bits);
-                    state->lens[state->have++] = this.val;
+                if (here.val < 16) {
+                    NEEDBITS(here.bits);
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
                 }
                 else {
-                    if (this.val == 16) {
-                        NEEDBITS(this.bits + 2);
-                        DROPBITS(this.bits);
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
                         if (state->have == 0) {
                             strm->msg = (char *)"invalid bit length repeat";
                             state->mode = BAD;
@@ -411,16 +411,16 @@
                         copy = 3 + BITS(2);
                         DROPBITS(2);
                     }
-                    else if (this.val == 17) {
-                        NEEDBITS(this.bits + 3);
-                        DROPBITS(this.bits);
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 3 + BITS(3);
                         DROPBITS(3);
                     }
                     else {
-                        NEEDBITS(this.bits + 7);
-                        DROPBITS(this.bits);
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 11 + BITS(7);
                         DROPBITS(7);
@@ -438,7 +438,16 @@
             /* handle error breaks in while */
             if (state->mode == BAD) break;
 
-            /* build code tables */
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
             state->next = state->codes;
             state->lencode = (code const FAR *)(state->next);
             state->lenbits = 9;
@@ -474,28 +483,28 @@
 
             /* get a literal, length, or end-of-block code */
             for (;;) {
-                this = state->lencode[BITS(state->lenbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if (this.op && (this.op & 0xf0) == 0) {
-                last = this;
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->lencode[last.val +
+                    here = state->lencode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
             }
-            DROPBITS(this.bits);
-            state->length = (unsigned)this.val;
+            DROPBITS(here.bits);
+            state->length = (unsigned)here.val;
 
             /* process literal */
-            if (this.op == 0) {
-                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+            if (here.op == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                         "inflate:         literal '%c'\n" :
-                        "inflate:         literal 0x%02x\n", this.val));
+                        "inflate:         literal 0x%02x\n", here.val));
                 ROOM();
                 *put++ = (unsigned char)(state->length);
                 left--;
@@ -504,21 +513,21 @@
             }
 
             /* process end of block */
-            if (this.op & 32) {
+            if (here.op & 32) {
                 Tracevv((stderr, "inflate:         end of block\n"));
                 state->mode = TYPE;
                 break;
             }
 
             /* invalid code */
-            if (this.op & 64) {
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid literal/length code";
                 state->mode = BAD;
                 break;
             }
 
             /* length code -- get extra bits, if any */
-            state->extra = (unsigned)(this.op) & 15;
+            state->extra = (unsigned)(here.op) & 15;
             if (state->extra != 0) {
                 NEEDBITS(state->extra);
                 state->length += BITS(state->extra);
@@ -528,30 +537,30 @@
 
             /* get distance code */
             for (;;) {
-                this = state->distcode[BITS(state->distbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if ((this.op & 0xf0) == 0) {
-                last = this;
+            if ((here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->distcode[last.val +
+                    here = state->distcode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
             }
-            DROPBITS(this.bits);
-            if (this.op & 64) {
+            DROPBITS(here.bits);
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
-            state->offset = (unsigned)this.val;
+            state->offset = (unsigned)here.val;
 
             /* get distance extra bits, if any */
-            state->extra = (unsigned)(this.op) & 15;
+            state->extra = (unsigned)(here.op) & 15;
             if (state->extra != 0) {
                 NEEDBITS(state->extra);
                 state->offset += BITS(state->extra);

Modified: python/branches/py3k-dtoa/Modules/zlib/inffast.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/inffast.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/inffast.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* inffast.c -- fast decoding
- * Copyright (C) 1995-2004 Mark Adler
+ * Copyright (C) 1995-2008, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -64,7 +64,7 @@
       requires strm->avail_out >= 258 for each loop to avoid checking for
       output space.
  */
-void inflate_fast(strm, start)
+void ZLIB_INTERNAL inflate_fast(strm, start)
 z_streamp strm;
 unsigned start;         /* inflate()'s starting value for strm->avail_out */
 {
@@ -79,7 +79,7 @@
 #endif
     unsigned wsize;             /* window size or zero if not using window */
     unsigned whave;             /* valid bytes in the window */
-    unsigned write;             /* window write index */
+    unsigned wnext;             /* window write index */
     unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
     unsigned long hold;         /* local strm->hold */
     unsigned bits;              /* local strm->bits */
@@ -87,7 +87,7 @@
     code const FAR *dcode;      /* local strm->distcode */
     unsigned lmask;             /* mask for first level of length codes */
     unsigned dmask;             /* mask for first level of distance codes */
-    code this;                  /* retrieved table entry */
+    code here;                  /* retrieved table entry */
     unsigned op;                /* code bits, operation, extra bits, or */
                                 /*  window position, window bytes to copy */
     unsigned len;               /* match length, unused bytes */
@@ -106,7 +106,7 @@
 #endif
     wsize = state->wsize;
     whave = state->whave;
-    write = state->write;
+    wnext = state->wnext;
     window = state->window;
     hold = state->hold;
     bits = state->bits;
@@ -124,20 +124,20 @@
             hold += (unsigned long)(PUP(in)) << bits;
             bits += 8;
         }
-        this = lcode[hold & lmask];
+        here = lcode[hold & lmask];
       dolen:
-        op = (unsigned)(this.bits);
+        op = (unsigned)(here.bits);
         hold >>= op;
         bits -= op;
-        op = (unsigned)(this.op);
+        op = (unsigned)(here.op);
         if (op == 0) {                          /* literal */
-            Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                     "inflate:         literal '%c'\n" :
-                    "inflate:         literal 0x%02x\n", this.val));
-            PUP(out) = (unsigned char)(this.val);
+                    "inflate:         literal 0x%02x\n", here.val));
+            PUP(out) = (unsigned char)(here.val);
         }
         else if (op & 16) {                     /* length base */
-            len = (unsigned)(this.val);
+            len = (unsigned)(here.val);
             op &= 15;                           /* number of extra bits */
             if (op) {
                 if (bits < op) {
@@ -155,14 +155,14 @@
                 hold += (unsigned long)(PUP(in)) << bits;
                 bits += 8;
             }
-            this = dcode[hold & dmask];
+            here = dcode[hold & dmask];
           dodist:
-            op = (unsigned)(this.bits);
+            op = (unsigned)(here.bits);
             hold >>= op;
             bits -= op;
-            op = (unsigned)(this.op);
+            op = (unsigned)(here.op);
             if (op & 16) {                      /* distance base */
-                dist = (unsigned)(this.val);
+                dist = (unsigned)(here.val);
                 op &= 15;                       /* number of extra bits */
                 if (bits < op) {
                     hold += (unsigned long)(PUP(in)) << bits;
@@ -187,12 +187,34 @@
                 if (dist > op) {                /* see if copy from window */
                     op = dist - op;             /* distance back in window */
                     if (op > whave) {
-                        strm->msg = (char *)"invalid distance too far back";
-                        state->mode = BAD;
-                        break;
+                        if (state->sane) {
+                            strm->msg =
+                                (char *)"invalid distance too far back";
+                            state->mode = BAD;
+                            break;
+                        }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                        if (len <= op - whave) {
+                            do {
+                                PUP(out) = 0;
+                            } while (--len);
+                            continue;
+                        }
+                        len -= op - whave;
+                        do {
+                            PUP(out) = 0;
+                        } while (--op > whave);
+                        if (op == 0) {
+                            from = out - dist;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--len);
+                            continue;
+                        }
+#endif
                     }
                     from = window - OFF;
-                    if (write == 0) {           /* very common case */
+                    if (wnext == 0) {           /* very common case */
                         from += wsize - op;
                         if (op < len) {         /* some from window */
                             len -= op;
@@ -202,17 +224,17 @@
                             from = out - dist;  /* rest from output */
                         }
                     }
-                    else if (write < op) {      /* wrap around window */
-                        from += wsize + write - op;
-                        op -= write;
+                    else if (wnext < op) {      /* wrap around window */
+                        from += wsize + wnext - op;
+                        op -= wnext;
                         if (op < len) {         /* some from end of window */
                             len -= op;
                             do {
                                 PUP(out) = PUP(from);
                             } while (--op);
                             from = window - OFF;
-                            if (write < len) {  /* some from start of window */
-                                op = write;
+                            if (wnext < len) {  /* some from start of window */
+                                op = wnext;
                                 len -= op;
                                 do {
                                     PUP(out) = PUP(from);
@@ -222,7 +244,7 @@
                         }
                     }
                     else {                      /* contiguous in window */
-                        from += write - op;
+                        from += wnext - op;
                         if (op < len) {         /* some from window */
                             len -= op;
                             do {
@@ -259,7 +281,7 @@
                 }
             }
             else if ((op & 64) == 0) {          /* 2nd level distance code */
-                this = dcode[this.val + (hold & ((1U << op) - 1))];
+                here = dcode[here.val + (hold & ((1U << op) - 1))];
                 goto dodist;
             }
             else {
@@ -269,7 +291,7 @@
             }
         }
         else if ((op & 64) == 0) {              /* 2nd level length code */
-            this = lcode[this.val + (hold & ((1U << op) - 1))];
+            here = lcode[here.val + (hold & ((1U << op) - 1))];
             goto dolen;
         }
         else if (op & 32) {                     /* end-of-block */
@@ -305,7 +327,7 @@
    inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
    - Using bit fields for code structure
    - Different op definition to avoid & for extra bits (do & for table bits)
-   - Three separate decoding do-loops for direct, window, and write == 0
+   - Three separate decoding do-loops for direct, window, and wnext == 0
    - Special case for distance > 1 copies to do overlapped load and store copy
    - Explicit branch predictions (based on measured branch probabilities)
    - Deferring match copy and interspersed it with decoding subsequent codes

Modified: python/branches/py3k-dtoa/Modules/zlib/inffast.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/inffast.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/inffast.h	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* inffast.h -- header to use inffast.c
- * Copyright (C) 1995-2003 Mark Adler
+ * Copyright (C) 1995-2003, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -8,4 +8,4 @@
    subject to change. Applications should only use zlib.h.
  */
 
-void inflate_fast OF((z_streamp strm, unsigned start));
+void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));

Modified: python/branches/py3k-dtoa/Modules/zlib/inflate.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/inflate.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/inflate.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* inflate.c -- zlib decompression
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -45,7 +45,7 @@
  * - Rearrange window copies in inflate_fast() for speed and simplification
  * - Unroll last copy for window match in inflate_fast()
  * - Use local copies of window variables in inflate_fast() for speed
- * - Pull out common write == 0 case for speed in inflate_fast()
+ * - Pull out common wnext == 0 case for speed in inflate_fast()
  * - Make op and len in inflate_fast() unsigned for consistency
  * - Add FAR to lcode and dcode declarations in inflate_fast()
  * - Simplified bad distance check in inflate_fast()
@@ -117,28 +117,52 @@
     state->head = Z_NULL;
     state->wsize = 0;
     state->whave = 0;
-    state->write = 0;
+    state->wnext = 0;
     state->hold = 0;
     state->bits = 0;
     state->lencode = state->distcode = state->next = state->codes;
+    state->sane = 1;
+    state->back = -1;
     Tracev((stderr, "inflate: reset\n"));
     return Z_OK;
 }
 
-int ZEXPORT inflatePrime(strm, bits, value)
+int ZEXPORT inflateReset2(strm, windowBits)
 z_streamp strm;
-int bits;
-int value;
+int windowBits;
 {
+    int wrap;
     struct inflate_state FAR *state;
 
+    /* get the state */
     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
     state = (struct inflate_state FAR *)strm->state;
-    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
-    value &= (1L << bits) - 1;
-    state->hold += value << state->bits;
-    state->bits += bits;
-    return Z_OK;
+
+    /* extract wrap request from windowBits parameter */
+    if (windowBits < 0) {
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+    else {
+        wrap = (windowBits >> 4) + 1;
+#ifdef GUNZIP
+        if (windowBits < 48)
+            windowBits &= 15;
+#endif
+    }
+
+    /* set number of window bits, free window if different */
+    if (windowBits && (windowBits < 8 || windowBits > 15))
+        return Z_STREAM_ERROR;
+    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
+        ZFREE(strm, state->window);
+        state->window = Z_NULL;
+    }
+
+    /* update state and reset the rest of it */
+    state->wrap = wrap;
+    state->wbits = (unsigned)windowBits;
+    return inflateReset(strm);
 }
 
 int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
@@ -147,6 +171,7 @@
 const char *version;
 int stream_size;
 {
+    int ret;
     struct inflate_state FAR *state;
 
     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
@@ -164,24 +189,13 @@
     if (state == Z_NULL) return Z_MEM_ERROR;
     Tracev((stderr, "inflate: allocated\n"));
     strm->state = (struct internal_state FAR *)state;
-    if (windowBits < 0) {
-        state->wrap = 0;
-        windowBits = -windowBits;
-    }
-    else {
-        state->wrap = (windowBits >> 4) + 1;
-#ifdef GUNZIP
-        if (windowBits < 48) windowBits &= 15;
-#endif
-    }
-    if (windowBits < 8 || windowBits > 15) {
+    state->window = Z_NULL;
+    ret = inflateReset2(strm, windowBits);
+    if (ret != Z_OK) {
         ZFREE(strm, state);
         strm->state = Z_NULL;
-        return Z_STREAM_ERROR;
     }
-    state->wbits = (unsigned)windowBits;
-    state->window = Z_NULL;
-    return inflateReset(strm);
+    return ret;
 }
 
 int ZEXPORT inflateInit_(strm, version, stream_size)
@@ -192,6 +206,27 @@
     return inflateInit2_(strm, DEF_WBITS, version, stream_size);
 }
 
+int ZEXPORT inflatePrime(strm, bits, value)
+z_streamp strm;
+int bits;
+int value;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (bits < 0) {
+        state->hold = 0;
+        state->bits = 0;
+        return Z_OK;
+    }
+    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
+    value &= (1L << bits) - 1;
+    state->hold += value << state->bits;
+    state->bits += bits;
+    return Z_OK;
+}
+
 /*
    Return state with length and distance decoding tables and index sizes set to
    fixed code decoding.  Normally this returns fixed tables from inffixed.h.
@@ -340,7 +375,7 @@
     /* if window not in use yet, initialize */
     if (state->wsize == 0) {
         state->wsize = 1U << state->wbits;
-        state->write = 0;
+        state->wnext = 0;
         state->whave = 0;
     }
 
@@ -348,22 +383,22 @@
     copy = out - strm->avail_out;
     if (copy >= state->wsize) {
         zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
-        state->write = 0;
+        state->wnext = 0;
         state->whave = state->wsize;
     }
     else {
-        dist = state->wsize - state->write;
+        dist = state->wsize - state->wnext;
         if (dist > copy) dist = copy;
-        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
+        zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);
         copy -= dist;
         if (copy) {
             zmemcpy(state->window, strm->next_out - copy, copy);
-            state->write = copy;
+            state->wnext = copy;
             state->whave = state->wsize;
         }
         else {
-            state->write += dist;
-            if (state->write == state->wsize) state->write = 0;
+            state->wnext += dist;
+            if (state->wnext == state->wsize) state->wnext = 0;
             if (state->whave < state->wsize) state->whave += dist;
         }
     }
@@ -564,7 +599,7 @@
     unsigned in, out;           /* save starting available input and output */
     unsigned copy;              /* number of stored or match bytes to copy */
     unsigned char FAR *from;    /* where to copy match bytes from */
-    code this;                  /* current decoding table entry */
+    code here;                  /* current decoding table entry */
     code last;                  /* parent table entry */
     unsigned len;               /* length to copy for repeats, bits to drop */
     int ret;                    /* return code */
@@ -619,7 +654,9 @@
             }
             DROPBITS(4);
             len = BITS(4) + 8;
-            if (len > state->wbits) {
+            if (state->wbits == 0)
+                state->wbits = len;
+            else if (len > state->wbits) {
                 strm->msg = (char *)"invalid window size";
                 state->mode = BAD;
                 break;
@@ -771,7 +808,7 @@
             strm->adler = state->check = adler32(0L, Z_NULL, 0);
             state->mode = TYPE;
         case TYPE:
-            if (flush == Z_BLOCK) goto inf_leave;
+            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
         case TYPEDO:
             if (state->last) {
                 BYTEBITS();
@@ -791,7 +828,11 @@
                 fixedtables(state);
                 Tracev((stderr, "inflate:     fixed codes block%s\n",
                         state->last ? " (last)" : ""));
-                state->mode = LEN;              /* decode codes */
+                state->mode = LEN_;             /* decode codes */
+                if (flush == Z_TREES) {
+                    DROPBITS(2);
+                    goto inf_leave;
+                }
                 break;
             case 2:                             /* dynamic block */
                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
@@ -816,6 +857,9 @@
             Tracev((stderr, "inflate:       stored length %u\n",
                     state->length));
             INITBITS();
+            state->mode = COPY_;
+            if (flush == Z_TREES) goto inf_leave;
+        case COPY_:
             state->mode = COPY;
         case COPY:
             copy = state->length;
@@ -876,19 +920,19 @@
         case CODELENS:
             while (state->have < state->nlen + state->ndist) {
                 for (;;) {
-                    this = state->lencode[BITS(state->lenbits)];
-                    if ((unsigned)(this.bits) <= bits) break;
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
                     PULLBYTE();
                 }
-                if (this.val < 16) {
-                    NEEDBITS(this.bits);
-                    DROPBITS(this.bits);
-                    state->lens[state->have++] = this.val;
+                if (here.val < 16) {
+                    NEEDBITS(here.bits);
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
                 }
                 else {
-                    if (this.val == 16) {
-                        NEEDBITS(this.bits + 2);
-                        DROPBITS(this.bits);
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
                         if (state->have == 0) {
                             strm->msg = (char *)"invalid bit length repeat";
                             state->mode = BAD;
@@ -898,16 +942,16 @@
                         copy = 3 + BITS(2);
                         DROPBITS(2);
                     }
-                    else if (this.val == 17) {
-                        NEEDBITS(this.bits + 3);
-                        DROPBITS(this.bits);
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 3 + BITS(3);
                         DROPBITS(3);
                     }
                     else {
-                        NEEDBITS(this.bits + 7);
-                        DROPBITS(this.bits);
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 11 + BITS(7);
                         DROPBITS(7);
@@ -925,7 +969,16 @@
             /* handle error breaks in while */
             if (state->mode == BAD) break;
 
-            /* build code tables */
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
             state->next = state->codes;
             state->lencode = (code const FAR *)(state->next);
             state->lenbits = 9;
@@ -946,88 +999,102 @@
                 break;
             }
             Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN_;
+            if (flush == Z_TREES) goto inf_leave;
+        case LEN_:
             state->mode = LEN;
         case LEN:
             if (have >= 6 && left >= 258) {
                 RESTORE();
                 inflate_fast(strm, out);
                 LOAD();
+                if (state->mode == TYPE)
+                    state->back = -1;
                 break;
             }
+            state->back = 0;
             for (;;) {
-                this = state->lencode[BITS(state->lenbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if (this.op && (this.op & 0xf0) == 0) {
-                last = this;
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->lencode[last.val +
+                    here = state->lencode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
+                state->back += last.bits;
             }
-            DROPBITS(this.bits);
-            state->length = (unsigned)this.val;
-            if ((int)(this.op) == 0) {
-                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            state->length = (unsigned)here.val;
+            if ((int)(here.op) == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                         "inflate:         literal '%c'\n" :
-                        "inflate:         literal 0x%02x\n", this.val));
+                        "inflate:         literal 0x%02x\n", here.val));
                 state->mode = LIT;
                 break;
             }
-            if (this.op & 32) {
+            if (here.op & 32) {
                 Tracevv((stderr, "inflate:         end of block\n"));
+                state->back = -1;
                 state->mode = TYPE;
                 break;
             }
-            if (this.op & 64) {
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid literal/length code";
                 state->mode = BAD;
                 break;
             }
-            state->extra = (unsigned)(this.op) & 15;
+            state->extra = (unsigned)(here.op) & 15;
             state->mode = LENEXT;
         case LENEXT:
             if (state->extra) {
                 NEEDBITS(state->extra);
                 state->length += BITS(state->extra);
                 DROPBITS(state->extra);
+                state->back += state->extra;
             }
             Tracevv((stderr, "inflate:         length %u\n", state->length));
+            state->was = state->length;
             state->mode = DIST;
         case DIST:
             for (;;) {
-                this = state->distcode[BITS(state->distbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if ((this.op & 0xf0) == 0) {
-                last = this;
+            if ((here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->distcode[last.val +
+                    here = state->distcode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
+                state->back += last.bits;
             }
-            DROPBITS(this.bits);
-            if (this.op & 64) {
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
-            state->offset = (unsigned)this.val;
-            state->extra = (unsigned)(this.op) & 15;
+            state->offset = (unsigned)here.val;
+            state->extra = (unsigned)(here.op) & 15;
             state->mode = DISTEXT;
         case DISTEXT:
             if (state->extra) {
                 NEEDBITS(state->extra);
                 state->offset += BITS(state->extra);
                 DROPBITS(state->extra);
+                state->back += state->extra;
             }
 #ifdef INFLATE_STRICT
             if (state->offset > state->dmax) {
@@ -1036,11 +1103,6 @@
                 break;
             }
 #endif
-            if (state->offset > state->whave + out - left) {
-                strm->msg = (char *)"invalid distance too far back";
-                state->mode = BAD;
-                break;
-            }
             Tracevv((stderr, "inflate:         distance %u\n", state->offset));
             state->mode = MATCH;
         case MATCH:
@@ -1048,12 +1110,32 @@
             copy = out - left;
             if (state->offset > copy) {         /* copy from window */
                 copy = state->offset - copy;
-                if (copy > state->write) {
-                    copy -= state->write;
+                if (copy > state->whave) {
+                    if (state->sane) {
+                        strm->msg = (char *)"invalid distance too far back";
+                        state->mode = BAD;
+                        break;
+                    }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                    Trace((stderr, "inflate.c too far\n"));
+                    copy -= state->whave;
+                    if (copy > state->length) copy = state->length;
+                    if (copy > left) copy = left;
+                    left -= copy;
+                    state->length -= copy;
+                    do {
+                        *put++ = 0;
+                    } while (--copy);
+                    if (state->length == 0) state->mode = LEN;
+                    break;
+#endif
+                }
+                if (copy > state->wnext) {
+                    copy -= state->wnext;
                     from = state->window + (state->wsize - copy);
                 }
                 else
-                    from = state->window + (state->write - copy);
+                    from = state->window + (state->wnext - copy);
                 if (copy > state->length) copy = state->length;
             }
             else {                              /* copy from output */
@@ -1146,7 +1228,8 @@
         strm->adler = state->check =
             UPDATE(state->check, strm->next_out - out, out);
     strm->data_type = state->bits + (state->last ? 64 : 0) +
-                      (state->mode == TYPE ? 128 : 0);
+                      (state->mode == TYPE ? 128 : 0) +
+                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
     if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
         ret = Z_BUF_ERROR;
     return ret;
@@ -1366,3 +1449,32 @@
     dest->state = (struct internal_state FAR *)copy;
     return Z_OK;
 }
+
+int ZEXPORT inflateUndermine(strm, subvert)
+z_streamp strm;
+int subvert;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    state->sane = !subvert;
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+    return Z_OK;
+#else
+    state->sane = 1;
+    return Z_DATA_ERROR;
+#endif
+}
+
+long ZEXPORT inflateMark(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
+    state = (struct inflate_state FAR *)strm->state;
+    return ((long)(state->back) << 16) +
+        (state->mode == COPY ? state->length :
+            (state->mode == MATCH ? state->was - state->length : 0));
+}

Modified: python/branches/py3k-dtoa/Modules/zlib/inflate.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/inflate.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/inflate.h	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* inflate.h -- internal inflate state definition
- * Copyright (C) 1995-2004 Mark Adler
+ * Copyright (C) 1995-2009 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -32,11 +32,13 @@
         TYPE,       /* i: waiting for type bits, including last-flag bit */
         TYPEDO,     /* i: same, but skip check to exit inflate on new block */
         STORED,     /* i: waiting for stored size (length and complement) */
+        COPY_,      /* i/o: same as COPY below, but only first time in */
         COPY,       /* i/o: waiting for input or output to copy stored block */
         TABLE,      /* i: waiting for dynamic block table lengths */
         LENLENS,    /* i: waiting for code length code lengths */
         CODELENS,   /* i: waiting for length/lit and distance code lengths */
-            LEN,        /* i: waiting for length/lit code */
+            LEN_,       /* i: same as LEN below, but only first time in */
+            LEN,        /* i: waiting for length/lit/eob code */
             LENEXT,     /* i: waiting for length extra bits */
             DIST,       /* i: waiting for distance code */
             DISTEXT,    /* i: waiting for distance extra bits */
@@ -53,19 +55,21 @@
 /*
     State transitions between above modes -
 
-    (most modes can go to the BAD or MEM mode -- not shown for clarity)
+    (most modes can go to BAD or MEM on error -- not shown for clarity)
 
     Process header:
-        HEAD -> (gzip) or (zlib)
-        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
-        NAME -> COMMENT -> HCRC -> TYPE
+        HEAD -> (gzip) or (zlib) or (raw)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
+                  HCRC -> TYPE
         (zlib) -> DICTID or TYPE
         DICTID -> DICT -> TYPE
+        (raw) -> TYPEDO
     Read deflate blocks:
-            TYPE -> STORED or TABLE or LEN or CHECK
-            STORED -> COPY -> TYPE
-            TABLE -> LENLENS -> CODELENS -> LEN
-    Read deflate codes:
+            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
+            STORED -> COPY_ -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN_
+            LEN_ -> LEN
+    Read deflate codes in fixed or dynamic block:
                 LEN -> LENEXT or LIT or TYPE
                 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
                 LIT -> LEN
@@ -73,7 +77,7 @@
         CHECK -> LENGTH -> DONE
  */
 
-/* state maintained between inflate() calls.  Approximately 7K bytes. */
+/* state maintained between inflate() calls.  Approximately 10K bytes. */
 struct inflate_state {
     inflate_mode mode;          /* current inflate mode */
     int last;                   /* true if processing last block */
@@ -88,7 +92,7 @@
     unsigned wbits;             /* log base 2 of requested window size */
     unsigned wsize;             /* window size or zero if not using window */
     unsigned whave;             /* valid bytes in the window */
-    unsigned write;             /* window write index */
+    unsigned wnext;             /* window write index */
     unsigned char FAR *window;  /* allocated sliding window, if needed */
         /* bit accumulator */
     unsigned long hold;         /* input bit accumulator */
@@ -112,4 +116,7 @@
     unsigned short lens[320];   /* temporary storage for code lengths */
     unsigned short work[288];   /* work area for code table building */
     code codes[ENOUGH];         /* space for code tables */
+    int sane;                   /* if false, allow invalid distance too far */
+    int back;                   /* bits back of last unprocessed length/lit */
+    unsigned was;               /* initial length of match */
 };

Modified: python/branches/py3k-dtoa/Modules/zlib/inftrees.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/inftrees.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/inftrees.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* inftrees.c -- generate Huffman trees for efficient decoding
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -9,7 +9,7 @@
 #define MAXBITS 15
 
 const char inflate_copyright[] =
-   " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
+   " inflate 1.2.5 Copyright 1995-2010 Mark Adler ";
 /*
   If you use the zlib library in a product, an acknowledgment is welcome
   in the documentation of your product. If for some reason you cannot
@@ -29,7 +29,7 @@
    table index bits.  It will differ if the request is greater than the
    longest code or if it is less than the shortest code.
  */
-int inflate_table(type, lens, codes, table, bits, work)
+int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
 codetype type;
 unsigned short FAR *lens;
 unsigned codes;
@@ -50,7 +50,7 @@
     unsigned fill;              /* index for replicating entries */
     unsigned low;               /* low bits for current root entry */
     unsigned mask;              /* mask for low root bits */
-    code this;                  /* table entry for duplication */
+    code here;                  /* table entry for duplication */
     code FAR *next;             /* next available space in table */
     const unsigned short FAR *base;     /* base value table to use */
     const unsigned short FAR *extra;    /* extra bits table to use */
@@ -62,7 +62,7 @@
         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
     static const unsigned short lext[31] = { /* Length codes 257..285 extra */
         16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
-        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195};
     static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
@@ -115,15 +115,15 @@
         if (count[max] != 0) break;
     if (root > max) root = max;
     if (max == 0) {                     /* no symbols to code at all */
-        this.op = (unsigned char)64;    /* invalid code marker */
-        this.bits = (unsigned char)1;
-        this.val = (unsigned short)0;
-        *(*table)++ = this;             /* make a table to force an error */
-        *(*table)++ = this;
+        here.op = (unsigned char)64;    /* invalid code marker */
+        here.bits = (unsigned char)1;
+        here.val = (unsigned short)0;
+        *(*table)++ = here;             /* make a table to force an error */
+        *(*table)++ = here;
         *bits = 1;
         return 0;     /* no symbols, but wait for decoding to report error */
     }
-    for (min = 1; min <= MAXBITS; min++)
+    for (min = 1; min < max; min++)
         if (count[min] != 0) break;
     if (root < min) root = min;
 
@@ -166,11 +166,10 @@
        entered in the tables.
 
        used keeps track of how many table entries have been allocated from the
-       provided *table space.  It is checked when a LENS table is being made
-       against the space in *table, ENOUGH, minus the maximum space needed by
-       the worst case distance code, MAXD.  This should never happen, but the
-       sufficiency of ENOUGH has not been proven exhaustively, hence the check.
-       This assumes that when type == LENS, bits == 9.
+       provided *table space.  It is checked for LENS and DIST tables against
+       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+       the initial root table size constants.  See the comments in inftrees.h
+       for more information.
 
        sym increments through all symbols, and the loop terminates when
        all codes of length max, i.e. all codes, have been processed.  This
@@ -209,24 +208,25 @@
     mask = used - 1;            /* mask for comparing low */
 
     /* check available table space */
-    if (type == LENS && used >= ENOUGH - MAXD)
+    if ((type == LENS && used >= ENOUGH_LENS) ||
+        (type == DISTS && used >= ENOUGH_DISTS))
         return 1;
 
     /* process all codes and make table entries */
     for (;;) {
         /* create table entry */
-        this.bits = (unsigned char)(len - drop);
+        here.bits = (unsigned char)(len - drop);
         if ((int)(work[sym]) < end) {
-            this.op = (unsigned char)0;
-            this.val = work[sym];
+            here.op = (unsigned char)0;
+            here.val = work[sym];
         }
         else if ((int)(work[sym]) > end) {
-            this.op = (unsigned char)(extra[work[sym]]);
-            this.val = base[work[sym]];
+            here.op = (unsigned char)(extra[work[sym]]);
+            here.val = base[work[sym]];
         }
         else {
-            this.op = (unsigned char)(32 + 64);         /* end of block */
-            this.val = 0;
+            here.op = (unsigned char)(32 + 64);         /* end of block */
+            here.val = 0;
         }
 
         /* replicate for those indices with low len bits equal to huff */
@@ -235,7 +235,7 @@
         min = fill;                 /* save offset to next table */
         do {
             fill -= incr;
-            next[(huff >> drop) + fill] = this;
+            next[(huff >> drop) + fill] = here;
         } while (fill != 0);
 
         /* backwards increment the len-bit code huff */
@@ -277,7 +277,8 @@
 
             /* check for enough space */
             used += 1U << curr;
-            if (type == LENS && used >= ENOUGH - MAXD)
+            if ((type == LENS && used >= ENOUGH_LENS) ||
+                (type == DISTS && used >= ENOUGH_DISTS))
                 return 1;
 
             /* point entry in root table to sub-table */
@@ -295,20 +296,20 @@
        through high index bits.  When the current sub-table is filled, the loop
        drops back to the root table to fill in any remaining entries there.
      */
-    this.op = (unsigned char)64;                /* invalid code marker */
-    this.bits = (unsigned char)(len - drop);
-    this.val = (unsigned short)0;
+    here.op = (unsigned char)64;                /* invalid code marker */
+    here.bits = (unsigned char)(len - drop);
+    here.val = (unsigned short)0;
     while (huff != 0) {
         /* when done with sub-table, drop back to root table */
         if (drop != 0 && (huff & mask) != low) {
             drop = 0;
             len = root;
             next = *table;
-            this.bits = (unsigned char)len;
+            here.bits = (unsigned char)len;
         }
 
         /* put invalid code marker in table */
-        next[huff >> drop] = this;
+        next[huff >> drop] = here;
 
         /* backwards increment the len-bit code huff */
         incr = 1U << (len - 1);

Modified: python/branches/py3k-dtoa/Modules/zlib/inftrees.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/inftrees.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/inftrees.h	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* inftrees.h -- header to use inftrees.c
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2005, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -35,21 +35,28 @@
     01000000 - invalid code
  */
 
-/* Maximum size of dynamic tree.  The maximum found in a long but non-
-   exhaustive search was 1444 code structures (852 for length/literals
-   and 592 for distances, the latter actually the result of an
-   exhaustive search).  The true maximum is not known, but the value
-   below is more than safe. */
-#define ENOUGH 2048
-#define MAXD 592
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1444, which is the sum of 852 for literal/length codes and 592 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in inflate.c and infback.c.  If the root table size is
+   changed, then these maximum sizes would be need to be recalculated and
+   updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 592
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
 
-/* Type of code to build for inftable() */
+/* Type of code to build for inflate_table() */
 typedef enum {
     CODES,
     LENS,
     DISTS
 } codetype;
 
-extern int inflate_table OF((codetype type, unsigned short FAR *lens,
+int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
                              unsigned codes, code FAR * FAR *table,
                              unsigned FAR *bits, unsigned short FAR *work));

Modified: python/branches/py3k-dtoa/Modules/zlib/make_vms.com
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/make_vms.com	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/make_vms.com	Sun Aug  8 12:41:24 2010
@@ -1,33 +1,57 @@
 $! make libz under VMS written by
 $! Martin P.J. Zinser
-$! <zinser at zinser.no-ip.info or zinser at sysdev.deutsche-boerse.com>
 $!
-$ on error then goto err_exit
+$! In case of problems with the install you might contact me at
+$! zinser at zinser.no-ip.info(preferred) or
+$! zinser at sysdev.deutsche-boerse.com (work)
+$!
+$! Make procedure history for Zlib
 $!
+$!------------------------------------------------------------------------------
+$! Version history
+$! 0.01 20060120 First version to receive a number
+$! 0.02 20061008 Adapt to new Makefile.in
+$! 0.03 20091224 Add support for large file check
+$! 0.04 20100110 Add new gzclose, gzlib, gzread, gzwrite
+$! 0.05 20100221 Exchange zlibdefs.h by zconf.h.in
 $!
-$! Just some general constants...
+$ on error then goto err_exit
+$ set proc/parse=ext
 $!
 $ true  = 1
 $ false = 0
 $ tmpnam = "temp_" + f$getjpi("","pid")
-$ SAY = "WRITE SYS$OUTPUT"
+$ tt = tmpnam + ".txt"
+$ tc = tmpnam + ".c"
+$ th = tmpnam + ".h"
+$ define/nolog tconfig 'th'
+$ its_decc = false
+$ its_vaxc = false
+$ its_gnuc = false
+$ s_case   = False
 $!
 $! Setup variables holding "config" information
 $!
-$ Make     = ""
+$ Make    = ""
 $ name     = "Zlib"
 $ version  = "?.?.?"
 $ v_string = "ZLIB_VERSION"
 $ v_file   = "zlib.h"
-$ ccopt    = ""
-$ lopts    = ""
+$ ccopt   = ""
+$ lopts   = ""
+$ dnsrl   = ""
+$ aconf_in_file = "zconf.h.in#zconf.h_in"
+$ conf_check_string = ""
 $ linkonly = false
 $ optfile  = name + ".opt"
-$ its_decc = false
-$ its_vaxc = false
-$ its_gnuc = false
-$ axp      = f$getsyi("HW_MODEL").ge.1024
-$ s_case   = false
+$ libdefs  = ""
+$ axp      = f$getsyi("HW_MODEL").ge.1024 .and. f$getsyi("HW_MODEL").lt.4096
+$!
+$ whoami = f$parse(f$enviornment("Procedure"),,,,"NO_CONCEAL")
+$ mydef  = F$parse(whoami,,,"DEVICE")
+$ mydir  = f$parse(whoami,,,"DIRECTORY") - "]["
+$ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type")
+$!
 $! Check for MMK/MMS
 $!
 $ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS"
@@ -36,11 +60,16 @@
 $!
 $ gosub find_version
 $!
+$  open/write topt tmp.opt
+$  open/write optf 'optfile'
+$!
 $ gosub check_opts
 $!
 $! Look for the compiler used
 $!
 $ gosub check_compiler
+$ close topt
+$!
 $ if its_decc
 $ then
 $   ccopt = "/prefix=all" + ccopt
@@ -60,6 +89,52 @@
 $    if f$trnlnm("SYS").eqs."" then define sys sys$library:
 $ endif
 $!
+$! Build a fake configure input header
+$!
+$ open/write conf_hin config.hin
+$ write conf_hin "#undef _LARGEFILE64_SOURCE"
+$ close conf_hin
+$!
+$!
+$ i = 0
+$FIND_ACONF:
+$ fname = f$element(i,"#",aconf_in_file)
+$ if fname .eqs. "#" then goto AMISS_ERR
+$ if f$search(fname) .eqs. ""
+$ then
+$   i = i + 1
+$   goto find_aconf
+$ endif
+$ open/read/err=aconf_err aconf_in 'fname'
+$ open/write aconf zconf.h
+$ACONF_LOOP:
+$ read/end_of_file=aconf_exit aconf_in line
+$ work = f$edit(line, "compress,trim")
+$ if f$extract(0,6,work) .nes. "#undef"
+$ then
+$   if f$extract(0,12,work) .nes. "#cmakedefine"
+$   then
+$       write aconf line
+$   endif
+$ else
+$   cdef = f$element(1," ",work)
+$   gosub check_config
+$ endif
+$ goto aconf_loop
+$ACONF_EXIT:
+$ write aconf "#define VMS 1"
+$ write aconf "#include <unistd.h>"
+$ write aconf "#include <unixio.h>"
+$ write aconf "#ifdef _LARGEFILE"
+$ write aconf "#define off64_t __off64_t"
+$ write aconf "#define fopen64 fopen"
+$ write aconf "#define fseeko64 fseeko"
+$ write aconf "#define lseek64 lseek"
+$ write aconf "#define ftello64 ftell"
+$ write aconf "#endif"
+$ close aconf_in
+$ close aconf
+$ if f$search("''th'") .nes. "" then delete 'th';*
 $! Build the thing plain or with mms
 $!
 $ write sys$output "Compiling Zlib sources ..."
@@ -74,8 +149,14 @@
                 crc32.c zlib.h zconf.h
 $   CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" -
                 deflate.c deflate.h zutil.h zlib.h zconf.h
-$   CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" -
-                gzio.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzclose.OBJ "CC ''CCOPT' gzclose" -
+                gzclose.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzlib.OBJ "CC ''CCOPT' gzlib" -
+                gzlib.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzread.OBJ "CC ''CCOPT' gzread" -
+                gzread.c zutil.h zlib.h zconf.h
+$   CALL MAKE gzwrite.OBJ "CC ''CCOPT' gzwrite" -
+                gzwrite.c zutil.h zlib.h zconf.h
 $   CALL MAKE infback.OBJ "CC ''CCOPT' infback" -
                 infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
 $   CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" -
@@ -107,7 +188,7 @@
 $   endif
 $  else
 $   gosub crea_mms
-$   SAY "Make ''name' ''version' with ''Make' "
+$   write sys$output "Make ''name' ''version' with ''Make' "
 $   'make'
 $  endif
 $!
@@ -133,6 +214,15 @@
 $ goto err_exit
 $ERR_EXIT:
 $ set message/facil/ident/sever/text
+$ close/nolog optf
+$ close/nolog topt
+$ close/nolog conf_hin
+$ close/nolog aconf_in
+$ close/nolog aconf
+$ close/nolog out
+$ close/nolog min
+$ close/nolog mod
+$ close/nolog h_in
 $ write sys$output "Exiting..."
 $ exit 2
 $!
@@ -180,61 +270,72 @@
 $!
 $! Check command line options and set symbols accordingly
 $!
+$!------------------------------------------------------------------------------
+$! Version history
+$! 0.01 20041206 First version to receive a number
+$! 0.02 20060126 Add new "HELP" target
 $ CHECK_OPTS:
 $ i = 1
 $ OPT_LOOP:
 $ if i .lt. 9
 $ then
 $   cparm = f$edit(p'i',"upcase")
-$   if cparm .eqs. "DEBUG"
-$   then
-$     ccopt = ccopt + "/noopt/deb"
-$     lopts = lopts + "/deb"
-$   endif
-$   if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
-$   then
-$     start = f$locate("=",cparm) + 1
-$     len   = f$length(cparm) - start
-$     ccopt = ccopt + f$extract(start,len,cparm)
-$     if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
-         then s_case = true
-$   endif
-$   if cparm .eqs. "LINK" then linkonly = true
-$   if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
-$   then
-$     start = f$locate("=",cparm) + 1
-$     len   = f$length(cparm) - start
-$     lopts = lopts + f$extract(start,len,cparm)
-$   endif
-$   if f$locate("CC=",cparm) .lt. f$length(cparm)
+$!
+$! Check if parameter actually contains something
+$!
+$   if f$edit(cparm,"trim") .nes. ""
 $   then
-$     start  = f$locate("=",cparm) + 1
-$     len    = f$length(cparm) - start
-$     cc_com = f$extract(start,len,cparm)
-      if (cc_com .nes. "DECC") .and. -
-         (cc_com .nes. "VAXC") .and. -
-	 (cc_com .nes. "GNUC")
+$     if cparm .eqs. "DEBUG"
 $     then
-$       write sys$output "Unsupported compiler choice ''cc_com' ignored"
-$       write sys$output "Use DECC, VAXC, or GNUC instead"
-$     else
-$     	if cc_com .eqs. "DECC" then its_decc = true
-$     	if cc_com .eqs. "VAXC" then its_vaxc = true
-$     	if cc_com .eqs. "GNUC" then its_gnuc = true
+$       ccopt = ccopt + "/noopt/deb"
+$       lopts = lopts + "/deb"
 $     endif
-$   endif
-$   if f$locate("MAKE=",cparm) .lt. f$length(cparm)
-$   then
-$     start  = f$locate("=",cparm) + 1
-$     len    = f$length(cparm) - start
-$     mmks = f$extract(start,len,cparm)
-$     if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
+$     if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
 $     then
-$       make = mmks
-$     else
-$       write sys$output "Unsupported make choice ''mmks' ignored"
-$       write sys$output "Use MMK or MMS instead"
+$       start = f$locate("=",cparm) + 1
+$       len   = f$length(cparm) - start
+$       ccopt = ccopt + f$extract(start,len,cparm)
+$       if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
+          then s_case = true
 $     endif
+$     if cparm .eqs. "LINK" then linkonly = true
+$     if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
+$     then
+$       start = f$locate("=",cparm) + 1
+$       len   = f$length(cparm) - start
+$       lopts = lopts + f$extract(start,len,cparm)
+$     endif
+$     if f$locate("CC=",cparm) .lt. f$length(cparm)
+$     then
+$       start  = f$locate("=",cparm) + 1
+$       len    = f$length(cparm) - start
+$       cc_com = f$extract(start,len,cparm)
+        if (cc_com .nes. "DECC") .and. -
+           (cc_com .nes. "VAXC") .and. -
+           (cc_com .nes. "GNUC")
+$       then
+$         write sys$output "Unsupported compiler choice ''cc_com' ignored"
+$         write sys$output "Use DECC, VAXC, or GNUC instead"
+$       else
+$         if cc_com .eqs. "DECC" then its_decc = true
+$         if cc_com .eqs. "VAXC" then its_vaxc = true
+$         if cc_com .eqs. "GNUC" then its_gnuc = true
+$       endif
+$     endif
+$     if f$locate("MAKE=",cparm) .lt. f$length(cparm)
+$     then
+$       start  = f$locate("=",cparm) + 1
+$       len    = f$length(cparm) - start
+$       mmks = f$extract(start,len,cparm)
+$       if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
+$       then
+$         make = mmks
+$       else
+$         write sys$output "Unsupported make choice ''mmks' ignored"
+$         write sys$output "Use MMK or MMS instead"
+$       endif
+$     endif
+$     if cparm .eqs. "HELP" then gosub bhelp
 $   endif
 $   i = i + 1
 $   goto opt_loop
@@ -244,6 +345,11 @@
 $!
 $! Look for the compiler used
 $!
+$! Version history
+$! 0.01 20040223 First version to receive a number
+$! 0.02 20040229 Save/set value of decc$no_rooted_search_lists
+$! 0.03 20060202 Extend handling of GNU C
+$! 0.04 20090402 Compaq -> hp
 $CHECK_COMPILER:
 $ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
 $ then
@@ -257,9 +363,26 @@
 $ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
 $ then goto CC_ERR
 $ else
-$   if its_decc then write sys$output "CC compiler check ... Compaq C"
-$   if its_vaxc then write sys$output "CC compiler check ... VAX C"
-$   if its_gnuc then write sys$output "CC compiler check ... GNU C"
+$   if its_decc
+$   then
+$     write sys$output "CC compiler check ... hp C"
+$     if f$trnlnm("decc$no_rooted_search_lists") .nes. ""
+$     then
+$       dnrsl = f$trnlnm("decc$no_rooted_search_lists")
+$     endif
+$     define/nolog decc$no_rooted_search_lists 1
+$   else
+$     if its_vaxc then write sys$output "CC compiler check ... VAX C"
+$     if its_gnuc
+$     then
+$         write sys$output "CC compiler check ... GNU C"
+$         if f$trnlnm(topt) then write topt "gnu_cc:[000000]gcclib.olb/lib"
+$         if f$trnlnm(optf) then write optf "gnu_cc:[000000]gcclib.olb/lib"
+$         cc = "gcc"
+$     endif
+$     if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share"
+$     if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share"
+$   endif
 $ endif
 $ return
 $!------------------------------------------------------------------------------
@@ -276,7 +399,8 @@
 # written by Martin P.J. Zinser
 # <zinser at zinser.no-ip.info or zinser at sysdev.deutsche-boerse.com>
 
-OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj, infback.obj\
+OBJS = adler32.obj, compress.obj, crc32.obj, gzclose.obj, gzlib.obj\
+       gzread.obj, gzwrite.obj, uncompr.obj, infback.obj\
        deflate.obj, trees.obj, zutil.obj, inflate.obj, \
        inftrees.obj, inffast.obj
 
@@ -308,7 +432,10 @@
 crc32.obj    : crc32.c zutil.h zlib.h zconf.h
 deflate.obj  : deflate.c deflate.h zutil.h zlib.h zconf.h
 example.obj  : example.c zlib.h zconf.h
-gzio.obj     : gzio.c zutil.h zlib.h zconf.h
+gzclose.obj  : gzclose.c zutil.h zlib.h zconf.h
+gzlib.obj    : gzlib.c zutil.h zlib.h zconf.h
+gzread.obj   : gzread.c zutil.h zlib.h zconf.h
+gzwrite.obj  : gzwrite.c zutil.h zlib.h zconf.h
 inffast.obj  : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h
 inflate.obj  : inflate.c zutil.h zlib.h zconf.h
 inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h
@@ -328,7 +455,7 @@
 $CREA_OLIST:
 $ open/read min makefile.in
 $ open/write mod modules.opt
-$ src_check = "OBJS ="
+$ src_check = "OBJC ="
 $MRLOOP:
 $ read/end=mrdone min rec
 $ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop
@@ -382,13 +509,182 @@
 $ return
 $!------------------------------------------------------------------------------
 $!
+$CHECK_CONFIG:
+$!
+$ in_ldef = f$locate(cdef,libdefs)
+$ if (in_ldef .lt. f$length(libdefs))
+$ then
+$   write aconf "#define ''cdef' 1"
+$   libdefs = f$extract(0,in_ldef,libdefs) + -
+              f$extract(in_ldef + f$length(cdef) + 1, -
+                        f$length(libdefs) - in_ldef - f$length(cdef) - 1, -
+                        libdefs)
+$ else
+$   if (f$type('cdef') .eqs. "INTEGER")
+$   then
+$     write aconf "#define ''cdef' ", 'cdef'
+$   else
+$     if (f$type('cdef') .eqs. "STRING")
+$     then
+$       write aconf "#define ''cdef' ", """", '''cdef'', """"
+$     else
+$       gosub check_cc_def
+$     endif
+$   endif
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Check if this is a define relating to the properties of the C/C++
+$! compiler
+$!
+$ CHECK_CC_DEF:
+$ if (cdef .eqs. "_LARGEFILE64_SOURCE")
+$ then
+$   copy sys$input: 'tc'
+$   deck
+#include "tconfig"
+#define _LARGEFILE
+#include <stdio.h>
+
+int main(){
+FILE *fp;
+  fp = fopen("temp.txt","r");
+  fseeko(fp,1,SEEK_SET);
+  fclose(fp);
+}
+
+$   eod
+$   test_inv = false
+$   comm_h = false
+$   gosub cc_prop_check
+$   return
+$ endif
+$ write aconf "/* ", line, " */"
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Check for properties of C/C++ compiler
+$!
+$! Version history
+$! 0.01 20031020 First version to receive a number
+$! 0.02 20031022 Added logic for defines with value
+$! 0.03 20040309 Make sure local config file gets not deleted
+$! 0.04 20041230 Also write include for configure run
+$! 0.05 20050103 Add processing of "comment defines"
+$CC_PROP_CHECK:
+$ cc_prop = true
+$ is_need = false
+$ is_need = (f$extract(0,4,cdef) .eqs. "NEED") .or. (test_inv .eq. true)
+$ if f$search(th) .eqs. "" then create 'th'
+$ set message/nofac/noident/nosever/notext
+$ on error then continue
+$ cc 'tmpnam'
+$ if .not. ($status)  then cc_prop = false
+$ on error then continue
+$! The headers might lie about the capabilities of the RTL
+$ link 'tmpnam',tmp.opt/opt
+$ if .not. ($status)  then cc_prop = false
+$ set message/fac/ident/sever/text
+$ on error then goto err_exit
+$ delete/nolog 'tmpnam'.*;*/exclude='th'
+$ if (cc_prop .and. .not. is_need) .or. -
+     (.not. cc_prop .and. is_need)
+$ then
+$   write sys$output "Checking for ''cdef'... yes"
+$   if f$type('cdef_val'_yes) .nes. ""
+$   then
+$     if f$type('cdef_val'_yes) .eqs. "INTEGER" -
+         then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_yes)
+$     if f$type('cdef_val'_yes) .eqs. "STRING" -
+         then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_yes)
+$   else
+$     call write_config f$fao("#define !AS 1",cdef)
+$   endif
+$   if (cdef .eqs. "HAVE_FSEEKO") .or. (cdef .eqs. "_LARGE_FILES") .or. -
+       (cdef .eqs. "_LARGEFILE64_SOURCE") then -
+      call write_config f$string("#define _LARGEFILE 1")
+$ else
+$   write sys$output "Checking for ''cdef'... no"
+$   if (comm_h)
+$   then
+      call write_config f$fao("/* !AS */",line)
+$   else
+$     if f$type('cdef_val'_no) .nes. ""
+$     then
+$       if f$type('cdef_val'_no) .eqs. "INTEGER" -
+           then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_no)
+$       if f$type('cdef_val'_no) .eqs. "STRING" -
+           then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_no)
+$     else
+$       call write_config f$fao("#undef !AS",cdef)
+$     endif
+$   endif
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
+$! Check for properties of C/C++ compiler with multiple result values
+$!
+$! Version history
+$! 0.01 20040127 First version
+$! 0.02 20050103 Reconcile changes from cc_prop up to version 0.05
+$CC_MPROP_CHECK:
+$ cc_prop = true
+$ i    = 1
+$ idel = 1
+$ MT_LOOP:
+$ if f$type(result_'i') .eqs. "STRING"
+$ then
+$   set message/nofac/noident/nosever/notext
+$   on error then continue
+$   cc 'tmpnam'_'i'
+$   if .not. ($status)  then cc_prop = false
+$   on error then continue
+$! The headers might lie about the capabilities of the RTL
+$   link 'tmpnam'_'i',tmp.opt/opt
+$   if .not. ($status)  then cc_prop = false
+$   set message/fac/ident/sever/text
+$   on error then goto err_exit
+$   delete/nolog 'tmpnam'_'i'.*;*
+$   if (cc_prop)
+$   then
+$     write sys$output "Checking for ''cdef'... ", mdef_'i'
+$     if f$type(mdef_'i') .eqs. "INTEGER" -
+         then call write_config f$fao("#define !AS !UL",cdef,mdef_'i')
+$     if f$type('cdef_val'_yes) .eqs. "STRING" -
+         then call write_config f$fao("#define !AS !AS",cdef,mdef_'i')
+$     goto msym_clean
+$   else
+$     i = i + 1
+$     goto mt_loop
+$   endif
+$ endif
+$ write sys$output "Checking for ''cdef'... no"
+$ call write_config f$fao("#undef !AS",cdef)
+$ MSYM_CLEAN:
+$ if (idel .le. msym_max)
+$ then
+$   delete/sym mdef_'idel'
+$   idel = idel + 1
+$   goto msym_clean
+$ endif
+$ return
+$!------------------------------------------------------------------------------
+$!
 $! Analyze Object files for OpenVMS AXP to extract Procedure and Data
 $! information to build a symbol vector for a shareable image
 $! All the "brains" of this logic was suggested by Hartmut Becker
 $! (Hartmut.Becker at compaq.com). All the bugs were introduced by me
-$! (zinser at decus.de), so if you do have problem reports please do not
+$! (zinser at zinser.no-ip.info), so if you do have problem reports please do not
 $! bother Hartmut/HP, but get in touch with me
 $!
+$! Version history
+$! 0.01 20040406 Skip over shareable images in option file
+$! 0.02 20041109 Fix option file for shareable images with case_sensitive=YES
+$! 0.03 20050107 Skip over Identification labels in option file
+$! 0.04 20060117 Add uppercase alias to code compiled with /name=as_is
+$!
 $ ANAL_OBJ_AXP: Subroutine
 $ V = 'F$Verify(0)
 $ SAY := "WRITE_ SYS$OUTPUT"
@@ -409,6 +705,17 @@
 $ open/append atmp a.tmp
 $ loop:
 $ read/end=end_loop in line
+$ if f$locate("/SHARE",f$edit(line,"upcase")) .lt. f$length(line)
+$ then
+$   write sys$output "ANAL_SKP_SHR-i-skipshare, ''line'"
+$   goto loop
+$ endif
+$ if f$locate("IDENTIFICATION=",f$edit(line,"upcase")) .lt. f$length(line)
+$ then
+$   write sys$output "ANAL_OBJ_AXP-i-ident: Identification ", -
+                     f$element(1,"=",line)
+$   goto loop
+$ endif
 $ f= f$search(line)
 $ if f .eqs. ""
 $ then
@@ -450,8 +757,31 @@
 sub/symbol: "/symbol_vector=(/whole
 sub/"/=DATA)/whole
 exit
-$ sort/nodupl d.tmp,f.tmp 'p2'
-$ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;*
+$ sort/nodupl d.tmp,f.tmp g.tmp
+$ open/read raw_vector g.tmp
+$ open/write case_vector 'p2'
+$ RAWLOOP:
+$ read/end=end_rawloop raw_vector raw_element
+$ write case_vector raw_element
+$ if f$locate("=PROCEDURE)",raw_element) .lt. f$length(raw_element)
+$ then
+$     name = f$element(1,"=",raw_element) - "("
+$     if f$edit(name,"UPCASE") .nes. name then -
+          write case_vector f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)", -
+	                          f$edit(name,"UPCASE"), name)
+$ endif
+$ if f$locate("=DATA)",raw_element) .lt. f$length(raw_element)
+$ then
+$     name = f$element(1,"=",raw_element) - "("
+$     if f$edit(name,"UPCASE") .nes. name then -
+          write case_vector f$fao(" symbol_vector=(!AS/!AS=DATA)", -
+	                          f$edit(name,"UPCASE"), name)
+$ endif
+$ goto rawloop
+$ END_RAWLOOP:
+$ close raw_vector
+$ close case_vector
+$ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;*,g.tmp;*
 $ if f$search("x.tmp") .nes. "" -
 	then $ delete x.tmp;*
 $!
@@ -459,3 +789,16 @@
 $ if V then set verify
 $ endsubroutine
 $!------------------------------------------------------------------------------
+$!
+$! Write configuration to both permanent and temporary config file
+$!
+$! Version history
+$! 0.01 20031029 First version to receive a number
+$!
+$WRITE_CONFIG: SUBROUTINE
+$  write aconf 'p1'
+$  open/append confh 'th'
+$  write confh 'p1'
+$  close confh
+$ENDSUBROUTINE
+$!------------------------------------------------------------------------------

Modified: python/branches/py3k-dtoa/Modules/zlib/minigzip.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/minigzip.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/minigzip.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* minigzip.c -- simulate gzip using the zlib compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2006, 2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -15,8 +15,8 @@
 
 /* @(#) $Id$ */
 
-#include <stdio.h>
 #include "zlib.h"
+#include <stdio.h>
 
 #ifdef STDC
 #  include <string.h>
@@ -32,6 +32,9 @@
 #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
 #  include <fcntl.h>
 #  include <io.h>
+#  ifdef UNDER_CE
+#    include <stdlib.h>
+#  endif
 #  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
 #else
 #  define SET_BINARY_MODE(file)
@@ -41,13 +44,84 @@
 #  define unlink delete
 #  define GZ_SUFFIX "-gz"
 #endif
+#ifdef RISCOS
+#  define unlink remove
+#  define GZ_SUFFIX "-gz"
+#  define fileno(file) file->__file
+#endif
 #if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
 #  include <unix.h> /* for fileno */
 #endif
 
+#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE)
 #ifndef WIN32 /* unlink already in stdio.h for WIN32 */
   extern int unlink OF((const char *));
 #endif
+#endif
+
+#if defined(UNDER_CE)
+#  include <windows.h>
+#  define perror(s) pwinerror(s)
+
+/* Map the Windows error number in ERROR to a locale-dependent error
+   message string and return a pointer to it.  Typically, the values
+   for ERROR come from GetLastError.
+
+   The string pointed to shall not be modified by the application,
+   but may be overwritten by a subsequent call to strwinerror
+
+   The strwinerror function does not change the current setting
+   of GetLastError.  */
+
+static char *strwinerror (error)
+     DWORD error;
+{
+    static char buf[1024];
+
+    wchar_t *msgbuf;
+    DWORD lasterr = GetLastError();
+    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
+        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+        NULL,
+        error,
+        0, /* Default language */
+        (LPVOID)&msgbuf,
+        0,
+        NULL);
+    if (chars != 0) {
+        /* If there is an \r\n appended, zap it.  */
+        if (chars >= 2
+            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
+            chars -= 2;
+            msgbuf[chars] = 0;
+        }
+
+        if (chars > sizeof (buf) - 1) {
+            chars = sizeof (buf) - 1;
+            msgbuf[chars] = 0;
+        }
+
+        wcstombs(buf, msgbuf, chars + 1);
+        LocalFree(msgbuf);
+    }
+    else {
+        sprintf(buf, "unknown win32 error (%ld)", error);
+    }
+
+    SetLastError(lasterr);
+    return buf;
+}
+
+static void pwinerror (s)
+    const char *s;
+{
+    if (s && *s)
+        fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ()));
+    else
+        fprintf(stderr, "%s\n", strwinerror(GetLastError ()));
+}
+
+#endif /* UNDER_CE */
 
 #ifndef GZ_SUFFIX
 #  define GZ_SUFFIX ".gz"
@@ -193,6 +267,11 @@
     FILE  *in;
     gzFile out;
 
+    if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) {
+        fprintf(stderr, "%s: filename too long\n", prog);
+        exit(1);
+    }
+
     strcpy(outfile, file);
     strcat(outfile, GZ_SUFFIX);
 
@@ -222,7 +301,12 @@
     char *infile, *outfile;
     FILE  *out;
     gzFile in;
-    uInt len = (uInt)strlen(file);
+    size_t len = strlen(file);
+
+    if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) {
+        fprintf(stderr, "%s: filename too long\n", prog);
+        exit(1);
+    }
 
     strcpy(buf, file);
 
@@ -253,7 +337,8 @@
 
 
 /* ===========================================================================
- * Usage:  minigzip [-d] [-f] [-h] [-r] [-1 to -9] [files...]
+ * Usage:  minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...]
+ *   -c : write to standard output
  *   -d : decompress
  *   -f : compress with Z_FILTERED
  *   -h : compress with Z_HUFFMAN_ONLY
@@ -265,17 +350,30 @@
     int argc;
     char *argv[];
 {
+    int copyout = 0;
     int uncompr = 0;
     gzFile file;
-    char outmode[20];
+    char *bname, outmode[20];
 
     strcpy(outmode, "wb6 ");
 
     prog = argv[0];
+    bname = strrchr(argv[0], '/');
+    if (bname)
+      bname++;
+    else
+      bname = argv[0];
     argc--, argv++;
 
+    if (!strcmp(bname, "gunzip"))
+      uncompr = 1;
+    else if (!strcmp(bname, "zcat"))
+      copyout = uncompr = 1;
+
     while (argc > 0) {
-      if (strcmp(*argv, "-d") == 0)
+      if (strcmp(*argv, "-c") == 0)
+        copyout = 1;
+      else if (strcmp(*argv, "-d") == 0)
         uncompr = 1;
       else if (strcmp(*argv, "-f") == 0)
         outmode[3] = 'f';
@@ -305,11 +403,36 @@
             gz_compress(stdin, file);
         }
     } else {
+        if (copyout) {
+            SET_BINARY_MODE(stdout);
+        }
         do {
             if (uncompr) {
-                file_uncompress(*argv);
+                if (copyout) {
+                    file = gzopen(*argv, "rb");
+                    if (file == NULL)
+                        fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv);
+                    else
+                        gz_uncompress(file, stdout);
+                } else {
+                    file_uncompress(*argv);
+                }
             } else {
-                file_compress(*argv, outmode);
+                if (copyout) {
+                    FILE * in = fopen(*argv, "rb");
+
+                    if (in == NULL) {
+                        perror(*argv);
+                    } else {
+                        file = gzdopen(fileno(stdout), outmode);
+                        if (file == NULL) error("can't gzdopen stdout");
+
+                        gz_compress(in, file);
+                    }
+
+                } else {
+                    file_compress(*argv, outmode);
+                }
             }
         } while (argv++, --argc);
     }

Modified: python/branches/py3k-dtoa/Modules/zlib/trees.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/trees.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/trees.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,6 @@
 /* trees.c -- output deflated data using Huffman coding
- * Copyright (C) 1995-2005 Jean-loup Gailly
+ * Copyright (C) 1995-2010 Jean-loup Gailly
+ * detect_data_type() function provided freely by Cosmin Truta, 2006
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -152,7 +153,7 @@
                               int blcodes));
 local void compress_block OF((deflate_state *s, ct_data *ltree,
                               ct_data *dtree));
-local void set_data_type  OF((deflate_state *s));
+local int  detect_data_type OF((deflate_state *s));
 local unsigned bi_reverse OF((unsigned value, int length));
 local void bi_windup      OF((deflate_state *s));
 local void bi_flush       OF((deflate_state *s));
@@ -203,12 +204,12 @@
      * unused bits in value.
      */
     if (s->bi_valid > (int)Buf_size - length) {
-        s->bi_buf |= (value << s->bi_valid);
+        s->bi_buf |= (ush)value << s->bi_valid;
         put_short(s, s->bi_buf);
         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
         s->bi_valid += length - Buf_size;
     } else {
-        s->bi_buf |= value << s->bi_valid;
+        s->bi_buf |= (ush)value << s->bi_valid;
         s->bi_valid += length;
     }
 }
@@ -218,12 +219,12 @@
 { int len = length;\
   if (s->bi_valid > (int)Buf_size - len) {\
     int val = value;\
-    s->bi_buf |= (val << s->bi_valid);\
+    s->bi_buf |= (ush)val << s->bi_valid;\
     put_short(s, s->bi_buf);\
     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
     s->bi_valid += len - Buf_size;\
   } else {\
-    s->bi_buf |= (value) << s->bi_valid;\
+    s->bi_buf |= (ush)(value) << s->bi_valid;\
     s->bi_valid += len;\
   }\
 }
@@ -250,11 +251,13 @@
     if (static_init_done) return;
 
     /* For some embedded targets, global variables are not initialized: */
+#ifdef NO_INIT_GLOBAL_POINTERS
     static_l_desc.static_tree = static_ltree;
     static_l_desc.extra_bits = extra_lbits;
     static_d_desc.static_tree = static_dtree;
     static_d_desc.extra_bits = extra_dbits;
     static_bl_desc.extra_bits = extra_blbits;
+#endif
 
     /* Initialize the mapping length (0..255) -> length code (0..28) */
     length = 0;
@@ -348,13 +351,14 @@
                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
     }
 
-    fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
+    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
     for (i = 0; i < DIST_CODE_LEN; i++) {
         fprintf(header, "%2u%s", _dist_code[i],
                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
     }
 
-    fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
+    fprintf(header,
+        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
         fprintf(header, "%2u%s", _length_code[i],
                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
@@ -379,7 +383,7 @@
 /* ===========================================================================
  * Initialize the tree data structures for a new zlib stream.
  */
-void _tr_init(s)
+void ZLIB_INTERNAL _tr_init(s)
     deflate_state *s;
 {
     tr_static_init();
@@ -864,13 +868,13 @@
 /* ===========================================================================
  * Send a stored block
  */
-void _tr_stored_block(s, buf, stored_len, eof)
+void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
     deflate_state *s;
     charf *buf;       /* input block */
     ulg stored_len;   /* length of input block */
-    int eof;          /* true if this is the last block for a file */
+    int last;         /* one if this is the last block for a file */
 {
-    send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
+    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
 #ifdef DEBUG
     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
     s->compressed_len += (stored_len + 4) << 3;
@@ -889,7 +893,7 @@
  * To simplify the code, we assume the worst case of last real code encoded
  * on one bit only.
  */
-void _tr_align(s)
+void ZLIB_INTERNAL _tr_align(s)
     deflate_state *s;
 {
     send_bits(s, STATIC_TREES<<1, 3);
@@ -918,11 +922,11 @@
  * Determine the best encoding for the current block: dynamic trees, static
  * trees or store, and output the encoded block to the zip file.
  */
-void _tr_flush_block(s, buf, stored_len, eof)
+void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
     deflate_state *s;
     charf *buf;       /* input block, or NULL if too old */
     ulg stored_len;   /* length of input block */
-    int eof;          /* true if this is the last block for a file */
+    int last;         /* one if this is the last block for a file */
 {
     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
     int max_blindex = 0;  /* index of last bit length code of non zero freq */
@@ -931,8 +935,8 @@
     if (s->level > 0) {
 
         /* Check if the file is binary or text */
-        if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
-            set_data_type(s);
+        if (s->strm->data_type == Z_UNKNOWN)
+            s->strm->data_type = detect_data_type(s);
 
         /* Construct the literal and distance trees */
         build_tree(s, (tree_desc *)(&(s->l_desc)));
@@ -978,20 +982,20 @@
          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
          * transform a block into a stored block.
          */
-        _tr_stored_block(s, buf, stored_len, eof);
+        _tr_stored_block(s, buf, stored_len, last);
 
 #ifdef FORCE_STATIC
     } else if (static_lenb >= 0) { /* force static trees */
 #else
     } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
 #endif
-        send_bits(s, (STATIC_TREES<<1)+eof, 3);
+        send_bits(s, (STATIC_TREES<<1)+last, 3);
         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
 #ifdef DEBUG
         s->compressed_len += 3 + s->static_len;
 #endif
     } else {
-        send_bits(s, (DYN_TREES<<1)+eof, 3);
+        send_bits(s, (DYN_TREES<<1)+last, 3);
         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
                        max_blindex+1);
         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
@@ -1005,21 +1009,21 @@
      */
     init_block(s);
 
-    if (eof) {
+    if (last) {
         bi_windup(s);
 #ifdef DEBUG
         s->compressed_len += 7;  /* align on byte boundary */
 #endif
     }
     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
-           s->compressed_len-7*eof));
+           s->compressed_len-7*last));
 }
 
 /* ===========================================================================
  * Save the match info and tally the frequency counts. Return true if
  * the current block must be flushed.
  */
-int _tr_tally (s, dist, lc)
+int ZLIB_INTERNAL _tr_tally (s, dist, lc)
     deflate_state *s;
     unsigned dist;  /* distance of matched string */
     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
@@ -1118,24 +1122,45 @@
 }
 
 /* ===========================================================================
- * Set the data type to BINARY or TEXT, using a crude approximation:
- * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
- * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
+ * Check if the data type is TEXT or BINARY, using the following algorithm:
+ * - TEXT if the two conditions below are satisfied:
+ *    a) There are no non-portable control characters belonging to the
+ *       "black list" (0..6, 14..25, 28..31).
+ *    b) There is at least one printable character belonging to the
+ *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
+ * - BINARY otherwise.
+ * - The following partially-portable control characters form a
+ *   "gray list" that is ignored in this detection algorithm:
+ *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  * IN assertion: the fields Freq of dyn_ltree are set.
  */
-local void set_data_type(s)
+local int detect_data_type(s)
     deflate_state *s;
 {
+    /* black_mask is the bit mask of black-listed bytes
+     * set bits 0..6, 14..25, and 28..31
+     * 0xf3ffc07f = binary 11110011111111111100000001111111
+     */
+    unsigned long black_mask = 0xf3ffc07fUL;
     int n;
 
-    for (n = 0; n < 9; n++)
+    /* Check for non-textual ("black-listed") bytes. */
+    for (n = 0; n <= 31; n++, black_mask >>= 1)
+        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
+            return Z_BINARY;
+
+    /* Check for textual ("white-listed") bytes. */
+    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
+            || s->dyn_ltree[13].Freq != 0)
+        return Z_TEXT;
+    for (n = 32; n < LITERALS; n++)
         if (s->dyn_ltree[n].Freq != 0)
-            break;
-    if (n == 9)
-        for (n = 14; n < 32; n++)
-            if (s->dyn_ltree[n].Freq != 0)
-                break;
-    s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
+            return Z_TEXT;
+
+    /* There are no "black-listed" or "white-listed" bytes:
+     * this stream either is empty or has tolerated ("gray-listed") bytes only.
+     */
+    return Z_BINARY;
 }
 
 /* ===========================================================================

Modified: python/branches/py3k-dtoa/Modules/zlib/trees.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/trees.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/trees.h	Sun Aug  8 12:41:24 2010
@@ -70,7 +70,7 @@
 {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
 };
 
-const uch _dist_code[DIST_CODE_LEN] = {
+const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
  0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
  8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
@@ -99,7 +99,7 @@
 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
 };
 
-const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
+const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
  0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,

Modified: python/branches/py3k-dtoa/Modules/zlib/uncompr.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/uncompr.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/uncompr.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* uncompr.c -- decompress a memory buffer
- * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -16,8 +16,6 @@
    been saved previously by the compressor and transmitted to the decompressor
    by some mechanism outside the scope of this compression library.)
    Upon exit, destLen is the actual size of the compressed buffer.
-     This function can be used to decompress a whole file at once if the
-   input file is mmap'ed.
 
      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_BUF_ERROR if there was not enough room in the output

Modified: python/branches/py3k-dtoa/Modules/zlib/zconf.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/zconf.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/zconf.h	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* zconf.h -- configuration of the zlib compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -11,52 +11,124 @@
 /*
  * If you *really* need a unique prefix for all types and library functions,
  * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
  */
-#ifdef Z_PREFIX
-#  define deflateInit_          z_deflateInit_
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+
+/* all linked symbols */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  define compress              z_compress
+#  define compress2             z_compress2
+#  define compressBound         z_compressBound
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
 #  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
 #  define deflateEnd            z_deflateEnd
-#  define inflateInit_          z_inflateInit_
-#  define inflate               z_inflate
-#  define inflateEnd            z_inflateEnd
 #  define deflateInit2_         z_deflateInit2_
-#  define deflateSetDictionary  z_deflateSetDictionary
-#  define deflateCopy           z_deflateCopy
-#  define deflateReset          z_deflateReset
+#  define deflateInit_          z_deflateInit_
 #  define deflateParams         z_deflateParams
-#  define deflateBound          z_deflateBound
 #  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  define gz_error              z_gz_error
+#  define gz_intmax             z_gz_intmax
+#  define gz_strwinerror        z_gz_strwinerror
+#  define gzbuffer              z_gzbuffer
+#  define gzclearerr            z_gzclearerr
+#  define gzclose               z_gzclose
+#  define gzclose_r             z_gzclose_r
+#  define gzclose_w             z_gzclose_w
+#  define gzdirect              z_gzdirect
+#  define gzdopen               z_gzdopen
+#  define gzeof                 z_gzeof
+#  define gzerror               z_gzerror
+#  define gzflush               z_gzflush
+#  define gzgetc                z_gzgetc
+#  define gzgets                z_gzgets
+#  define gzoffset              z_gzoffset
+#  define gzoffset64            z_gzoffset64
+#  define gzopen                z_gzopen
+#  define gzopen64              z_gzopen64
+#  define gzprintf              z_gzprintf
+#  define gzputc                z_gzputc
+#  define gzputs                z_gzputs
+#  define gzread                z_gzread
+#  define gzrewind              z_gzrewind
+#  define gzseek                z_gzseek
+#  define gzseek64              z_gzseek64
+#  define gzsetparams           z_gzsetparams
+#  define gztell                z_gztell
+#  define gztell64              z_gztell64
+#  define gzungetc              z_gzungetc
+#  define gzwrite               z_gzwrite
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetHeader      z_inflateGetHeader
 #  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
 #  define inflateSetDictionary  z_inflateSetDictionary
 #  define inflateSync           z_inflateSync
 #  define inflateSyncPoint      z_inflateSyncPoint
-#  define inflateCopy           z_inflateCopy
-#  define inflateReset          z_inflateReset
-#  define inflateBack           z_inflateBack
-#  define inflateBackEnd        z_inflateBackEnd
-#  define compress              z_compress
-#  define compress2             z_compress2
-#  define compressBound         z_compressBound
+#  define inflateUndermine      z_inflateUndermine
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
 #  define uncompress            z_uncompress
-#  define adler32               z_adler32
-#  define crc32                 z_crc32
-#  define get_crc_table         z_get_crc_table
 #  define zError                z_zError
+#  define zcalloc               z_zcalloc
+#  define zcfree                z_zcfree
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
 
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
 #  define alloc_func            z_alloc_func
+#  define charf                 z_charf
 #  define free_func             z_free_func
+#  define gzFile                z_gzFile
+#  define gz_header             z_gz_header
+#  define gz_headerp            z_gz_headerp
 #  define in_func               z_in_func
+#  define intf                  z_intf
 #  define out_func              z_out_func
-#  define Byte                  z_Byte
 #  define uInt                  z_uInt
-#  define uLong                 z_uLong
-#  define Bytef                 z_Bytef
-#  define charf                 z_charf
-#  define intf                  z_intf
 #  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
 #  define uLongf                z_uLongf
-#  define voidpf                z_voidpf
 #  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  define gz_header_s           z_gz_header_s
+#  define internal_state        z_internal_state
+
 #endif
 
 #if defined(__MSDOS__) && !defined(MSDOS)
@@ -284,49 +356,73 @@
    typedef Byte       *voidp;
 #endif
 
-#if 0           /* HAVE_UNISTD_H -- this line is updated by ./configure */
-#  include <sys/types.h> /* for off_t */
-#  include <unistd.h>    /* for SEEK_* and off_t */
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef STDC
+#  include <sys/types.h>    /* for off_t */
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
+#  include <unistd.h>       /* for SEEK_* and off_t */
 #  ifdef VMS
-#    include <unixio.h>   /* for off_t */
+#    include <unixio.h>     /* for off_t */
+#  endif
+#  ifndef z_off_t
+#    define z_off_t off_t
 #  endif
-#  define z_off_t off_t
 #endif
+
 #ifndef SEEK_SET
 #  define SEEK_SET        0       /* Seek from beginning of file.  */
 #  define SEEK_CUR        1       /* Seek from current position.  */
 #  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
 #endif
+
 #ifndef z_off_t
 #  define z_off_t long
 #endif
 
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define z_off64_t off64_t
+#else
+#  define z_off64_t z_off_t
+#endif
+
 #if defined(__OS400__)
 #  define NO_vsnprintf
 #endif
 
 #if defined(__MVS__)
 #  define NO_vsnprintf
-#  ifdef FAR
-#    undef FAR
-#  endif
 #endif
 
 /* MVS linker does not support external names larger than 8 bytes */
 #if defined(__MVS__)
-#   pragma map(deflateInit_,"DEIN")
-#   pragma map(deflateInit2_,"DEIN2")
-#   pragma map(deflateEnd,"DEEND")
-#   pragma map(deflateBound,"DEBND")
-#   pragma map(inflateInit_,"ININ")
-#   pragma map(inflateInit2_,"ININ2")
-#   pragma map(inflateEnd,"INEND")
-#   pragma map(inflateSync,"INSY")
-#   pragma map(inflateSetDictionary,"INSEDI")
-#   pragma map(compressBound,"CMBND")
-#   pragma map(inflate_table,"INTABL")
-#   pragma map(inflate_fast,"INFA")
-#   pragma map(inflate_copyright,"INCOPY")
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
 #endif
 
 #endif /* ZCONF_H */

Modified: python/branches/py3k-dtoa/Modules/zlib/zlib.3
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/zlib.3	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/zlib.3	Sun Aug  8 12:41:24 2010
@@ -1,4 +1,4 @@
-.TH ZLIB 3 "18 July 2005"
+.TH ZLIB 3 "19 Apr 2010"
 .SH NAME
 zlib \- compression/decompression library
 .SH SYNOPSIS
@@ -9,15 +9,15 @@
 The
 .I zlib
 library is a general purpose data compression library.
-The code is thread safe.
+The code is thread safe, assuming that the standard library functions
+used are thread safe, such as memory allocation routines.
 It provides in-memory compression and decompression functions,
 including integrity checks of the uncompressed data.
 This version of the library supports only one compression method (deflation)
-but other algorithms will be added later
-and will have the same stream interface.
+but other algorithms may be added later
+with the same stream interface.
 .LP
 Compression can be done in a single step if the buffers are large enough
-(for example if an input file is mmap'ed),
 or can be done by repeated calls of the compression function.
 In the latter case,
 the application must provide more input and/or consume the output
@@ -30,7 +30,7 @@
 .LP
 The library does not install any signal handler.
 The decoder checks the consistency of the compressed data,
-so the library should never crash even in case of corrupted input.
+so the library should never crash even in the case of corrupted input.
 .LP
 All functions of the compression library are documented in the file
 .IR zlib.h .
@@ -38,18 +38,19 @@
 in the files
 .I example.c
 and
-.IR minigzip.c .
+.IR minigzip.c,
+as well as other examples in the
+.IR examples/
+directory.
 .LP
 Changes to this version are documented in the file
 .I ChangeLog
-that accompanies the source,
-and are concerned primarily with bug fixes and portability enhancements.
+that accompanies the source.
 .LP
-A Java implementation of
 .I zlib
-is available in the Java Development Kit 1.1:
+is available in Java using the java.util.zip package:
 .IP
-http://www.javasoft.com/products/JDK/1.1/docs/api/Package-java.util.zip.html
+http://java.sun.com/developer/technicalArticles/Programming/compression/
 .LP
 A Perl interface to
 .IR zlib ,
@@ -57,7 +58,7 @@
 is available at CPAN (Comprehensive Perl Archive Network) sites,
 including:
 .IP
-http://www.cpan.org/modules/by-module/Compress/
+http://search.cpan.org/~pmqs/IO-Compress-Zlib/
 .LP
 A Python interface to
 .IR zlib ,
@@ -66,14 +67,11 @@
 .IP
 http://www.python.org/doc/lib/module-zlib.html
 .LP
-A
 .I zlib
-binding for
-.IR tcl (1),
-written by Andreas Kupries (a.kupries at westend.com),
-is availlable at:
+is built into
+.IR tcl:
 .IP
-http://www.westend.com/~kupries/doc/trf/man/man.html
+http://wiki.tcl.tk/4610
 .LP
 An experimental package to read and write files in .zip format,
 written on top of
@@ -81,40 +79,34 @@
 by Gilles Vollant (info at winimage.com),
 is available at:
 .IP
-http://www.winimage.com/zLibDll/unzip.html
+http://www.winimage.com/zLibDll/minizip.html
 and also in the
 .I contrib/minizip
 directory of the main
 .I zlib
-web site.
+source distribution.
 .SH "SEE ALSO"
 The
 .I zlib
-web site can be found at either of these locations:
+web site can be found at:
 .IP
-http://www.zlib.org
-.br
-http://www.gzip.org/zlib/
+http://zlib.net/
 .LP
 The data format used by the zlib library is described by RFC
 (Request for Comments) 1950 to 1952 in the files:
 .IP
-http://www.ietf.org/rfc/rfc1950.txt (concerning zlib format)
+http://www.ietf.org/rfc/rfc1950.txt (for the zlib header and trailer format)
 .br
-http://www.ietf.org/rfc/rfc1951.txt (concerning deflate format)
+http://www.ietf.org/rfc/rfc1951.txt (for the deflate compressed data format)
 .br
-http://www.ietf.org/rfc/rfc1952.txt (concerning gzip format)
-.LP
-These documents are also available in other formats from:
-.IP
-ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
+http://www.ietf.org/rfc/rfc1952.txt (for the gzip header and trailer format)
 .LP
-Mark Nelson (markn at ieee.org) wrote an article about
+Mark Nelson wrote an article about
 .I zlib
 for the Jan. 1997 issue of  Dr. Dobb's Journal;
 a copy of the article is available at:
 .IP
-http://dogma.net/markn/articles/zlibtool/zlibtool.htm
+http://marknelson.us/1997/01/01/zlib-engine/
 .SH "REPORTING PROBLEMS"
 Before reporting a problem,
 please check the
@@ -127,14 +119,14 @@
 .I zlib
 FAQ at:
 .IP
-http://www.gzip.org/zlib/zlib_faq.html
+http://zlib.net/zlib_faq.html
 .LP
 before asking for help.
 Send questions and/or comments to zlib at gzip.org,
 or (for the Windows DLL version) to Gilles Vollant (info at winimage.com).
 .SH AUTHORS
-Version 1.2.3
-Copyright (C) 1995-2005 Jean-loup Gailly (jloup at gzip.org)
+Version 1.2.5
+Copyright (C) 1995-2010 Jean-loup Gailly (jloup at gzip.org)
 and Mark Adler (madler at alumni.caltech.edu).
 .LP
 This software is provided "as-is,"

Modified: python/branches/py3k-dtoa/Modules/zlib/zlib.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/zlib.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/zlib.h	Sun Aug  8 12:41:24 2010
@@ -1,7 +1,7 @@
 /* zlib.h -- interface of the 'zlib' general purpose compression library
-  version 1.2.3, July 18th, 2005
+  version 1.2.5, April 19th, 2010
 
-  Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
+  Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,41 +37,44 @@
 extern "C" {
 #endif
 
-#define ZLIB_VERSION "1.2.3"
-#define ZLIB_VERNUM 0x1230
-
-/*
-     The 'zlib' compression library provides in-memory compression and
-  decompression functions, including integrity checks of the uncompressed
-  data.  This version of the library supports only one compression method
-  (deflation) but other algorithms will be added later and will have the same
-  stream interface.
-
-     Compression can be done in a single step if the buffers are large
-  enough (for example if an input file is mmap'ed), or can be done by
-  repeated calls of the compression function.  In the latter case, the
-  application must provide more input and/or consume the output
+#define ZLIB_VERSION "1.2.5"
+#define ZLIB_VERNUM 0x1250
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 5
+#define ZLIB_VER_SUBREVISION 0
+
+/*
+    The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed data.
+  This version of the library supports only one compression method (deflation)
+  but other algorithms will be added later and will have the same stream
+  interface.
+
+    Compression can be done in a single step if the buffers are large enough,
+  or can be done by repeated calls of the compression function.  In the latter
+  case, the application must provide more input and/or consume the output
   (providing more output space) before each call.
 
-     The compressed data format used by default by the in-memory functions is
+    The compressed data format used by default by the in-memory functions is
   the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
   around a deflate stream, which is itself documented in RFC 1951.
 
-     The library also supports reading and writing files in gzip (.gz) format
+    The library also supports reading and writing files in gzip (.gz) format
   with an interface similar to that of stdio using the functions that start
   with "gz".  The gzip format is different from the zlib format.  gzip is a
   gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
 
-     This library can optionally read and write gzip streams in memory as well.
+    This library can optionally read and write gzip streams in memory as well.
 
-     The zlib format was designed to be compact and fast for use in memory
+    The zlib format was designed to be compact and fast for use in memory
   and on communications channels.  The gzip format was designed for single-
   file compression on file systems, has a larger header than zlib to maintain
   directory information, and uses a different, slower check method than zlib.
 
-     The library does not install any signal handler. The decoder checks
-  the consistency of the compressed data, so the library should never
-  crash even in case of corrupted input.
+    The library does not install any signal handler.  The decoder checks
+  the consistency of the compressed data, so the library should never crash
+  even in case of corrupted input.
 */
 
 typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
@@ -126,45 +129,45 @@
 typedef gz_header FAR *gz_headerp;
 
 /*
-   The application must update next_in and avail_in when avail_in has
-   dropped to zero. It must update next_out and avail_out when avail_out
-   has dropped to zero. The application must initialize zalloc, zfree and
-   opaque before calling the init function. All other fields are set by the
-   compression library and must not be updated by the application.
-
-   The opaque value provided by the application will be passed as the first
-   parameter for calls of zalloc and zfree. This can be useful for custom
-   memory management. The compression library attaches no meaning to the
+     The application must update next_in and avail_in when avail_in has dropped
+   to zero.  It must update next_out and avail_out when avail_out has dropped
+   to zero.  The application must initialize zalloc, zfree and opaque before
+   calling the init function.  All other fields are set by the compression
+   library and must not be updated by the application.
+
+     The opaque value provided by the application will be passed as the first
+   parameter for calls of zalloc and zfree.  This can be useful for custom
+   memory management.  The compression library attaches no meaning to the
    opaque value.
 
-   zalloc must return Z_NULL if there is not enough memory for the object.
+     zalloc must return Z_NULL if there is not enough memory for the object.
    If zlib is used in a multi-threaded application, zalloc and zfree must be
    thread safe.
 
-   On 16-bit systems, the functions zalloc and zfree must be able to allocate
-   exactly 65536 bytes, but will not be required to allocate more than this
-   if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
-   pointers returned by zalloc for objects of exactly 65536 bytes *must*
-   have their offset normalized to zero. The default allocation function
-   provided by this library ensures this (see zutil.c). To reduce memory
-   requirements and avoid any allocation of 64K objects, at the expense of
-   compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
-
-   The fields total_in and total_out can be used for statistics or
-   progress reports. After compression, total_in holds the total size of
-   the uncompressed data and may be saved for use in the decompressor
-   (particularly if the decompressor wants to decompress everything in
-   a single step).
+     On 16-bit systems, the functions zalloc and zfree must be able to allocate
+   exactly 65536 bytes, but will not be required to allocate more than this if
+   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
+   returned by zalloc for objects of exactly 65536 bytes *must* have their
+   offset normalized to zero.  The default allocation function provided by this
+   library ensures this (see zutil.c).  To reduce memory requirements and avoid
+   any allocation of 64K objects, at the expense of compression ratio, compile
+   the library with -DMAX_WBITS=14 (see zconf.h).
+
+     The fields total_in and total_out can be used for statistics or progress
+   reports.  After compression, total_in holds the total size of the
+   uncompressed data and may be saved for use in the decompressor (particularly
+   if the decompressor wants to decompress everything in a single step).
 */
 
                         /* constants */
 
 #define Z_NO_FLUSH      0
-#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
+#define Z_PARTIAL_FLUSH 1
 #define Z_SYNC_FLUSH    2
 #define Z_FULL_FLUSH    3
 #define Z_FINISH        4
 #define Z_BLOCK         5
+#define Z_TREES         6
 /* Allowed flush values; see deflate() and inflate() below for details */
 
 #define Z_OK            0
@@ -176,8 +179,8 @@
 #define Z_MEM_ERROR    (-4)
 #define Z_BUF_ERROR    (-5)
 #define Z_VERSION_ERROR (-6)
-/* Return codes for the compression/decompression functions. Negative
- * values are errors, positive values are used for special but normal events.
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
  */
 
 #define Z_NO_COMPRESSION         0
@@ -207,119 +210,140 @@
 #define zlib_version zlibVersion()
 /* for compatibility with versions < 1.0.2 */
 
+
                         /* basic functions */
 
 ZEXTERN const char * ZEXPORT zlibVersion OF((void));
 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
-   If the first character differs, the library code actually used is
-   not compatible with the zlib.h header file used by the application.
-   This check is automatically made by deflateInit and inflateInit.
+   If the first character differs, the library code actually used is not
+   compatible with the zlib.h header file used by the application.  This check
+   is automatically made by deflateInit and inflateInit.
  */
 
 /*
 ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
 
-     Initializes the internal stream state for compression. The fields
-   zalloc, zfree and opaque must be initialized before by the caller.
-   If zalloc and zfree are set to Z_NULL, deflateInit updates them to
-   use default allocation functions.
+     Initializes the internal stream state for compression.  The fields
+   zalloc, zfree and opaque must be initialized before by the caller.  If
+   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
+   allocation functions.
 
      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
-   1 gives best speed, 9 gives best compression, 0 gives no compression at
-   all (the input data is simply copied a block at a time).
-   Z_DEFAULT_COMPRESSION requests a default compromise between speed and
-   compression (currently equivalent to level 6).
+   1 gives best speed, 9 gives best compression, 0 gives no compression at all
+   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
+   requests a default compromise between speed and compression (currently
+   equivalent to level 6).
 
-     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_STREAM_ERROR if level is not a valid compression level,
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if level is not a valid compression level, or
    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
-   with the version assumed by the caller (ZLIB_VERSION).
-   msg is set to null if there is no error message.  deflateInit does not
-   perform any compression: this will be done by deflate().
+   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
+   if there is no error message.  deflateInit does not perform any compression:
+   this will be done by deflate().
 */
 
 
 ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
 /*
     deflate compresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full. It may introduce some
-  output latency (reading input without producing any output) except when
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
   forced to flush.
 
-    The detailed semantics are as follows. deflate performs one or both of the
+    The detailed semantics are as follows.  deflate performs one or both of the
   following actions:
 
   - Compress more input starting at next_in and update next_in and avail_in
-    accordingly. If not all input can be processed (because there is not
+    accordingly.  If not all input can be processed (because there is not
     enough room in the output buffer), next_in and avail_in are updated and
     processing will resume at this point for the next call of deflate().
 
   - Provide more output starting at next_out and update next_out and avail_out
-    accordingly. This action is forced if the parameter flush is non zero.
+    accordingly.  This action is forced if the parameter flush is non zero.
     Forcing flush frequently degrades the compression ratio, so this parameter
-    should be set only when necessary (in interactive applications).
-    Some output may be provided even if flush is not set.
+    should be set only when necessary (in interactive applications).  Some
+    output may be provided even if flush is not set.
 
-  Before the call of deflate(), the application should ensure that at least
-  one of the actions is possible, by providing more input and/or consuming
-  more output, and updating avail_in or avail_out accordingly; avail_out
-  should never be zero before the call. The application can consume the
-  compressed output when it wants, for example when the output buffer is full
-  (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
-  and with zero avail_out, it must be called again after making room in the
-  output buffer because there might be more output pending.
+    Before the call of deflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating avail_in or avail_out accordingly; avail_out should
+  never be zero before the call.  The application can consume the compressed
+  output when it wants, for example when the output buffer is full (avail_out
+  == 0), or after each call of deflate().  If deflate returns Z_OK and with
+  zero avail_out, it must be called again after making room in the output
+  buffer because there might be more output pending.
 
     Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
-  decide how much data to accumualte before producing output, in order to
+  decide how much data to accumulate before producing output, in order to
   maximize compression.
 
     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
   flushed to the output buffer and the output is aligned on a byte boundary, so
-  that the decompressor can get all input data available so far. (In particular
-  avail_in is zero after the call if enough output space has been provided
-  before the call.)  Flushing may degrade compression for some compression
-  algorithms and so it should be used only when necessary.
+  that the decompressor can get all input data available so far.  (In
+  particular avail_in is zero after the call if enough output space has been
+  provided before the call.) Flushing may degrade compression for some
+  compression algorithms and so it should be used only when necessary.  This
+  completes the current deflate block and follows it with an empty stored block
+  that is three bits plus filler bits to the next byte, followed by four bytes
+  (00 00 ff ff).
+
+    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+  output buffer, but the output is not aligned to a byte boundary.  All of the
+  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+  This completes the current deflate block and follows it with an empty fixed
+  codes block that is 10 bits long.  This assures that enough bytes are output
+  in order for the decompressor to finish the block before the empty fixed code
+  block.
+
+    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+  seven bits of the current block are held to be written as the next byte after
+  the next deflate block is completed.  In this case, the decompressor may not
+  be provided enough bits at this point in order to complete decompression of
+  the data provided so far to the compressor.  It may need to wait for the next
+  block to be emitted.  This is for advanced applications that need to control
+  the emission of deflate blocks.
 
     If flush is set to Z_FULL_FLUSH, all output is flushed as with
   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
   restart from this point if previous compressed data has been damaged or if
-  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
   compression.
 
     If deflate returns with avail_out == 0, this function must be called again
   with the same value of the flush parameter and more output space (updated
   avail_out), until the flush is complete (deflate returns with non-zero
-  avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
   avail_out is greater than six to avoid repeated flush markers due to
   avail_out == 0 on return.
 
     If the parameter flush is set to Z_FINISH, pending input is processed,
-  pending output is flushed and deflate returns with Z_STREAM_END if there
-  was enough output space; if deflate returns with Z_OK, this function must be
+  pending output is flushed and deflate returns with Z_STREAM_END if there was
+  enough output space; if deflate returns with Z_OK, this function must be
   called again with Z_FINISH and more output space (updated avail_out) but no
-  more input data, until it returns with Z_STREAM_END or an error. After
-  deflate has returned Z_STREAM_END, the only possible operations on the
-  stream are deflateReset or deflateEnd.
+  more input data, until it returns with Z_STREAM_END or an error.  After
+  deflate has returned Z_STREAM_END, the only possible operations on the stream
+  are deflateReset or deflateEnd.
 
     Z_FINISH can be used immediately after deflateInit if all the compression
-  is to be done in a single step. In this case, avail_out must be at least
-  the value returned by deflateBound (see below). If deflate does not return
+  is to be done in a single step.  In this case, avail_out must be at least the
+  value returned by deflateBound (see below).  If deflate does not return
   Z_STREAM_END, then it must be called again as described above.
 
     deflate() sets strm->adler to the adler32 checksum of all input read
   so far (that is, total_in bytes).
 
     deflate() may update strm->data_type if it can make a good guess about
-  the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
-  binary. This field is only for information purposes and does not affect
-  the compression algorithm in any manner.
+  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered
+  binary.  This field is only for information purposes and does not affect the
+  compression algorithm in any manner.
 
     deflate() returns Z_OK if some progress has been made (more input
   processed or more output produced), Z_STREAM_END if all input has been
   consumed and all output has been produced (only when flush is set to
   Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
-  if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
-  (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
+  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible
+  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not
   fatal, and deflate() can be called again with more input and more output
   space to continue compressing.
 */
@@ -328,13 +352,13 @@
 ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
 /*
      All dynamically allocated data structures for this stream are freed.
-   This function discards any unprocessed input and does not flush any
-   pending output.
+   This function discards any unprocessed input and does not flush any pending
+   output.
 
      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
-   prematurely (some input or output was discarded). In the error case,
-   msg may be set but then points to a static string (which must not be
+   prematurely (some input or output was discarded).  In the error case, msg
+   may be set but then points to a static string (which must not be
    deallocated).
 */
 
@@ -342,10 +366,10 @@
 /*
 ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
 
-     Initializes the internal stream state for decompression. The fields
+     Initializes the internal stream state for decompression.  The fields
    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
-   the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
-   value depends on the compression method), inflateInit determines the
+   the caller.  If next_in is not Z_NULL and avail_in is large enough (the
+   exact value depends on the compression method), inflateInit determines the
    compression method from the zlib header and allocates all data structures
    accordingly; otherwise the allocation will be deferred to the first call of
    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
@@ -353,95 +377,108 @@
 
      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
-   version assumed by the caller.  msg is set to null if there is no error
-   message. inflateInit does not perform any decompression apart from reading
-   the zlib header if present: this will be done by inflate().  (So next_in and
-   avail_in may be modified, but next_out and avail_out are unchanged.)
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit() does not process any header information -- that is deferred
+   until inflate() is called.
 */
 
 
 ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
 /*
     inflate decompresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full. It may introduce
+  buffer becomes empty or the output buffer becomes full.  It may introduce
   some output latency (reading input without producing any output) except when
   forced to flush.
 
-  The detailed semantics are as follows. inflate performs one or both of the
+  The detailed semantics are as follows.  inflate performs one or both of the
   following actions:
 
   - Decompress more input starting at next_in and update next_in and avail_in
-    accordingly. If not all input can be processed (because there is not
-    enough room in the output buffer), next_in is updated and processing
-    will resume at this point for the next call of inflate().
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), next_in is updated and processing will
+    resume at this point for the next call of inflate().
 
   - Provide more output starting at next_out and update next_out and avail_out
-    accordingly.  inflate() provides as much output as possible, until there
-    is no more input data or no more space in the output buffer (see below
-    about the flush parameter).
-
-  Before the call of inflate(), the application should ensure that at least
-  one of the actions is possible, by providing more input and/or consuming
-  more output, and updating the next_* and avail_* values accordingly.
-  The application can consume the uncompressed output when it wants, for
-  example when the output buffer is full (avail_out == 0), or after each
-  call of inflate(). If inflate returns Z_OK and with zero avail_out, it
-  must be called again after making room in the output buffer because there
-  might be more output pending.
-
-    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
-  Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
-  output as possible to the output buffer. Z_BLOCK requests that inflate() stop
-  if and when it gets to the next deflate block boundary. When decoding the
-  zlib or gzip format, this will cause inflate() to return immediately after
-  the header and before the first block. When doing a raw inflate, inflate()
-  will go ahead and process the first block, and will return when it gets to
-  the end of that block, or when it runs out of data.
+    accordingly.  inflate() provides as much output as possible, until there is
+    no more input data or no more space in the output buffer (see below about
+    the flush parameter).
+
+    Before the call of inflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating the next_* and avail_* values accordingly.  The
+  application can consume the uncompressed output when it wants, for example
+  when the output buffer is full (avail_out == 0), or after each call of
+  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
+  called again after making room in the output buffer because there might be
+  more output pending.
+
+    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
+  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer.  Z_BLOCK requests that inflate()
+  stop if and when it gets to the next deflate block boundary.  When decoding
+  the zlib or gzip format, this will cause inflate() to return immediately
+  after the header and before the first block.  When doing a raw inflate,
+  inflate() will go ahead and process the first block, and will return when it
+  gets to the end of that block, or when it runs out of data.
 
     The Z_BLOCK option assists in appending to or combining deflate streams.
   Also to assist in this, on return inflate() will set strm->data_type to the
-  number of unused bits in the last byte taken from strm->next_in, plus 64
-  if inflate() is currently decoding the last block in the deflate stream,
-  plus 128 if inflate() returned immediately after decoding an end-of-block
-  code or decoding the complete header up to just before the first byte of the
-  deflate stream. The end-of-block will not be indicated until all of the
-  uncompressed data from that block has been written to strm->next_out.  The
-  number of unused bits may in general be greater than seven, except when
-  bit 7 of data_type is set, in which case the number of unused bits will be
-  less than eight.
+  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  inflate() is currently decoding the last block in the deflate stream, plus
+  128 if inflate() returned immediately after decoding an end-of-block code or
+  decoding the complete header up to just before the first byte of the deflate
+  stream.  The end-of-block will not be indicated until all of the uncompressed
+  data from that block has been written to strm->next_out.  The number of
+  unused bits may in general be greater than seven, except when bit 7 of
+  data_type is set, in which case the number of unused bits will be less than
+  eight.  data_type is set as noted here every time inflate() returns for all
+  flush options, and so can be used to determine the amount of currently
+  consumed input in bits.
+
+    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+  end of each deflate block header is reached, before any actual data in that
+  block is decoded.  This allows the caller to determine the length of the
+  deflate block header for later use in random access within a deflate block.
+  256 is added to the value of strm->data_type when inflate() returns
+  immediately after reaching the end of the deflate block header.
 
     inflate() should normally be called until it returns Z_STREAM_END or an
-  error. However if all decompression is to be performed in a single step
-  (a single call of inflate), the parameter flush should be set to
-  Z_FINISH. In this case all pending input is processed and all pending
-  output is flushed; avail_out must be large enough to hold all the
-  uncompressed data. (The size of the uncompressed data may have been saved
-  by the compressor for this purpose.) The next operation on this stream must
-  be inflateEnd to deallocate the decompression state. The use of Z_FINISH
-  is never required, but can be used to inform inflate that a faster approach
-  may be used for the single inflate() call.
+  error.  However if all decompression is to be performed in a single step (a
+  single call of inflate), the parameter flush should be set to Z_FINISH.  In
+  this case all pending input is processed and all pending output is flushed;
+  avail_out must be large enough to hold all the uncompressed data.  (The size
+  of the uncompressed data may have been saved by the compressor for this
+  purpose.) The next operation on this stream must be inflateEnd to deallocate
+  the decompression state.  The use of Z_FINISH is never required, but can be
+  used to inform inflate that a faster approach may be used for the single
+  inflate() call.
 
      In this implementation, inflate() always flushes as much output as
   possible to the output buffer, and always uses the faster approach on the
-  first call. So the only effect of the flush parameter in this implementation
+  first call.  So the only effect of the flush parameter in this implementation
   is on the return value of inflate(), as noted below, or when it returns early
-  because Z_BLOCK is used.
+  because Z_BLOCK or Z_TREES is used.
 
      If a preset dictionary is needed after this call (see inflateSetDictionary
   below), inflate sets strm->adler to the adler32 checksum of the dictionary
   chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
   strm->adler to the adler32 checksum of all output produced so far (that is,
   total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
-  below. At the end of the stream, inflate() checks that its computed adler32
+  below.  At the end of the stream, inflate() checks that its computed adler32
   checksum is equal to that saved by the compressor and returns Z_STREAM_END
   only if the checksum is correct.
 
-    inflate() will decompress and check either zlib-wrapped or gzip-wrapped
-  deflate data.  The header type is detected automatically.  Any information
-  contained in the gzip header is not retained, so applications that need that
-  information should instead use raw inflate, see inflateInit2() below, or
-  inflateBack() and perform their own processing of the gzip header and
-  trailer.
+    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically, if requested when
+  initializing with inflateInit2().  Any information contained in the gzip
+  header is not retained, so applications that need that information should
+  instead use raw inflate, see inflateInit2() below, or inflateBack() and
+  perform their own processing of the gzip header and trailer.
 
     inflate() returns Z_OK if some progress has been made (more input processed
   or more output produced), Z_STREAM_END if the end of the compressed data has
@@ -449,27 +486,28 @@
   preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
   corrupted (input stream not conforming to the zlib format or incorrect check
   value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
-  if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
+  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,
   Z_BUF_ERROR if no progress is possible or if there was not enough room in the
-  output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
+  output buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
   inflate() can be called again with more input and more output space to
-  continue decompressing. If Z_DATA_ERROR is returned, the application may then
-  call inflateSync() to look for a good compression block if a partial recovery
-  of the data is desired.
+  continue decompressing.  If Z_DATA_ERROR is returned, the application may
+  then call inflateSync() to look for a good compression block if a partial
+  recovery of the data is desired.
 */
 
 
 ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
 /*
      All dynamically allocated data structures for this stream are freed.
-   This function discards any unprocessed input and does not flush any
-   pending output.
+   This function discards any unprocessed input and does not flush any pending
+   output.
 
      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
-   was inconsistent. In the error case, msg may be set but then points to a
+   was inconsistent.  In the error case, msg may be set but then points to a
    static string (which must not be deallocated).
 */
 
+
                         /* Advanced functions */
 
 /*
@@ -484,55 +522,57 @@
                                      int  memLevel,
                                      int  strategy));
 
-     This is another version of deflateInit with more compression options. The
-   fields next_in, zalloc, zfree and opaque must be initialized before by
-   the caller.
+     This is another version of deflateInit with more compression options.  The
+   fields next_in, zalloc, zfree and opaque must be initialized before by the
+   caller.
 
-     The method parameter is the compression method. It must be Z_DEFLATED in
+     The method parameter is the compression method.  It must be Z_DEFLATED in
    this version of the library.
 
      The windowBits parameter is the base two logarithm of the window size
-   (the size of the history buffer). It should be in the range 8..15 for this
-   version of the library. Larger values of this parameter result in better
-   compression at the expense of memory usage. The default value is 15 if
+   (the size of the history buffer).  It should be in the range 8..15 for this
+   version of the library.  Larger values of this parameter result in better
+   compression at the expense of memory usage.  The default value is 15 if
    deflateInit is used instead.
 
-     windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
-   determines the window size. deflate() will then generate raw deflate data
+     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
+   determines the window size.  deflate() will then generate raw deflate data
    with no zlib header or trailer, and will not compute an adler32 check value.
 
-     windowBits can also be greater than 15 for optional gzip encoding. Add
+     windowBits can also be greater than 15 for optional gzip encoding.  Add
    16 to windowBits to write a simple gzip header and trailer around the
-   compressed data instead of a zlib wrapper. The gzip header will have no
-   file name, no extra data, no comment, no modification time (set to zero),
-   no header crc, and the operating system will be set to 255 (unknown).  If a
+   compressed data instead of a zlib wrapper.  The gzip header will have no
+   file name, no extra data, no comment, no modification time (set to zero), no
+   header crc, and the operating system will be set to 255 (unknown).  If a
    gzip stream is being written, strm->adler is a crc32 instead of an adler32.
 
      The memLevel parameter specifies how much memory should be allocated
-   for the internal compression state. memLevel=1 uses minimum memory but
-   is slow and reduces compression ratio; memLevel=9 uses maximum memory
-   for optimal speed. The default value is 8. See zconf.h for total memory
-   usage as a function of windowBits and memLevel.
+   for the internal compression state.  memLevel=1 uses minimum memory but is
+   slow and reduces compression ratio; memLevel=9 uses maximum memory for
+   optimal speed.  The default value is 8.  See zconf.h for total memory usage
+   as a function of windowBits and memLevel.
 
-     The strategy parameter is used to tune the compression algorithm. Use the
+     The strategy parameter is used to tune the compression algorithm.  Use the
    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
    filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
    string match), or Z_RLE to limit match distances to one (run-length
-   encoding). Filtered data consists mostly of small values with a somewhat
-   random distribution. In this case, the compression algorithm is tuned to
-   compress them better. The effect of Z_FILTERED is to force more Huffman
+   encoding).  Filtered data consists mostly of small values with a somewhat
+   random distribution.  In this case, the compression algorithm is tuned to
+   compress them better.  The effect of Z_FILTERED is to force more Huffman
    coding and less string matching; it is somewhat intermediate between
-   Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
-   Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
-   parameter only affects the compression ratio but not the correctness of the
-   compressed output even if it is not set appropriately.  Z_FIXED prevents the
-   use of dynamic Huffman codes, allowing for a simpler decoder for special
-   applications.
-
-      deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
-   method). msg is set to null if there is no error message.  deflateInit2 does
-   not perform any compression: this will be done by deflate().
+   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
+   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
+   strategy parameter only affects the compression ratio but not the
+   correctness of the compressed output even if it is not set appropriately.
+   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+   decoder for special applications.
+
+     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
+   set to null if there is no error message.  deflateInit2 does not perform any
+   compression: this will be done by deflate().
 */
 
 ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
@@ -540,37 +580,37 @@
                                              uInt  dictLength));
 /*
      Initializes the compression dictionary from the given byte sequence
-   without producing any compressed output. This function must be called
-   immediately after deflateInit, deflateInit2 or deflateReset, before any
-   call of deflate. The compressor and decompressor must use exactly the same
+   without producing any compressed output.  This function must be called
+   immediately after deflateInit, deflateInit2 or deflateReset, before any call
+   of deflate.  The compressor and decompressor must use exactly the same
    dictionary (see inflateSetDictionary).
 
      The dictionary should consist of strings (byte sequences) that are likely
    to be encountered later in the data to be compressed, with the most commonly
-   used strings preferably put towards the end of the dictionary. Using a
+   used strings preferably put towards the end of the dictionary.  Using a
    dictionary is most useful when the data to be compressed is short and can be
    predicted with good accuracy; the data can then be compressed better than
    with the default empty dictionary.
 
      Depending on the size of the compression data structures selected by
    deflateInit or deflateInit2, a part of the dictionary may in effect be
-   discarded, for example if the dictionary is larger than the window size in
-   deflate or deflate2. Thus the strings most likely to be useful should be
-   put at the end of the dictionary, not at the front. In addition, the
-   current implementation of deflate will use at most the window size minus
-   262 bytes of the provided dictionary.
+   discarded, for example if the dictionary is larger than the window size
+   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
+   useful should be put at the end of the dictionary, not at the front.  In
+   addition, the current implementation of deflate will use at most the window
+   size minus 262 bytes of the provided dictionary.
 
      Upon return of this function, strm->adler is set to the adler32 value
    of the dictionary; the decompressor may later use this value to determine
-   which dictionary has been used by the compressor. (The adler32 value
+   which dictionary has been used by the compressor.  (The adler32 value
    applies to the whole dictionary even if only a subset of the dictionary is
    actually used by the compressor.) If a raw deflate was requested, then the
    adler32 value is not computed and strm->adler is not set.
 
      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
-   parameter is invalid (such as NULL dictionary) or the stream state is
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
    inconsistent (for example if deflate has already been called for this stream
-   or if the compression method is bsort). deflateSetDictionary does not
+   or if the compression method is bsort).  deflateSetDictionary does not
    perform any compression: this will be done by deflate().
 */
 
@@ -581,26 +621,26 @@
 
      This function can be useful when several compression strategies will be
    tried, for example when there are several ways of pre-processing the input
-   data with a filter. The streams that will be discarded should then be freed
+   data with a filter.  The streams that will be discarded should then be freed
    by calling deflateEnd.  Note that deflateCopy duplicates the internal
-   compression state which can be quite large, so this strategy is slow and
-   can consume lots of memory.
+   compression state which can be quite large, so this strategy is slow and can
+   consume lots of memory.
 
      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-   (such as zalloc being NULL). msg is left unchanged in both source and
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
    destination.
 */
 
 ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
 /*
      This function is equivalent to deflateEnd followed by deflateInit,
-   but does not free and reallocate all the internal compression state.
-   The stream will keep the same compression level and any other attributes
-   that may have been set by deflateInit2.
+   but does not free and reallocate all the internal compression state.  The
+   stream will keep the same compression level and any other attributes that
+   may have been set by deflateInit2.
 
-      deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being NULL).
+     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
 */
 
 ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
@@ -610,18 +650,18 @@
      Dynamically update the compression level and compression strategy.  The
    interpretation of level and strategy is as in deflateInit2.  This can be
    used to switch between compression and straight copy of the input data, or
-   to switch to a different kind of input data requiring a different
-   strategy. If the compression level is changed, the input available so far
-   is compressed with the old level (and may be flushed); the new level will
-   take effect only at the next call of deflate().
+   to switch to a different kind of input data requiring a different strategy.
+   If the compression level is changed, the input available so far is
+   compressed with the old level (and may be flushed); the new level will take
+   effect only at the next call of deflate().
 
      Before the call of deflateParams, the stream state must be set as for
-   a call of deflate(), since the currently available input may have to
-   be compressed and flushed. In particular, strm->avail_out must be non-zero.
+   a call of deflate(), since the currently available input may have to be
+   compressed and flushed.  In particular, strm->avail_out must be non-zero.
 
      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
-   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
-   if strm->avail_out was zero.
+   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if
+   strm->avail_out was zero.
 */
 
 ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
@@ -645,9 +685,10 @@
                                        uLong sourceLen));
 /*
      deflateBound() returns an upper bound on the compressed size after
-   deflation of sourceLen bytes.  It must be called after deflateInit()
-   or deflateInit2().  This would be used to allocate an output buffer
-   for deflation in a single pass, and so would be called before deflate().
+   deflation of sourceLen bytes.  It must be called after deflateInit() or
+   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
+   to allocate an output buffer for deflation in a single pass, and so would be
+   called before deflate().
 */
 
 ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
@@ -655,21 +696,21 @@
                                      int value));
 /*
      deflatePrime() inserts bits in the deflate output stream.  The intent
-  is that this function is used to start off the deflate output with the
-  bits leftover from a previous deflate stream when appending to it.  As such,
-  this function can only be used for raw deflate, and must be used before the
-  first deflate() call after a deflateInit2() or deflateReset().  bits must be
-  less than or equal to 16, and that many of the least significant bits of
-  value will be inserted in the output.
+   is that this function is used to start off the deflate output with the bits
+   leftover from a previous deflate stream when appending to it.  As such, this
+   function can only be used for raw deflate, and must be used before the first
+   deflate() call after a deflateInit2() or deflateReset().  bits must be less
+   than or equal to 16, and that many of the least significant bits of value
+   will be inserted in the output.
 
-      deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+     deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
 ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
                                          gz_headerp head));
 /*
-      deflateSetHeader() provides gzip header information for when a gzip
+     deflateSetHeader() provides gzip header information for when a gzip
    stream is requested by deflateInit2().  deflateSetHeader() may be called
    after deflateInit2() or deflateReset() and before the first call of
    deflate().  The text, time, os, extra field, name, and comment information
@@ -682,11 +723,11 @@
    1.3.x) do not support header crc's, and will report that it is a "multi-part
    gzip file" and give up.
 
-      If deflateSetHeader is not used, the default gzip header has text false,
+     If deflateSetHeader is not used, the default gzip header has text false,
    the time set to zero, and os set to 255, with no extra, name, or comment
    fields.  The gzip header is returned to the default state by deflateReset().
 
-      deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
@@ -694,43 +735,50 @@
 ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
                                      int  windowBits));
 
-     This is another version of inflateInit with an extra parameter. The
+     This is another version of inflateInit with an extra parameter.  The
    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
    before by the caller.
 
      The windowBits parameter is the base two logarithm of the maximum window
    size (the size of the history buffer).  It should be in the range 8..15 for
-   this version of the library. The default value is 15 if inflateInit is used
-   instead. windowBits must be greater than or equal to the windowBits value
+   this version of the library.  The default value is 15 if inflateInit is used
+   instead.  windowBits must be greater than or equal to the windowBits value
    provided to deflateInit2() while compressing, or it must be equal to 15 if
-   deflateInit2() was not used. If a compressed stream with a larger window
+   deflateInit2() was not used.  If a compressed stream with a larger window
    size is given as input, inflate() will return with the error code
    Z_DATA_ERROR instead of trying to allocate a larger window.
 
-     windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
-   determines the window size. inflate() will then process raw deflate data,
+     windowBits can also be zero to request that inflate use the window size in
+   the zlib header of the compressed stream.
+
+     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
+   determines the window size.  inflate() will then process raw deflate data,
    not looking for a zlib or gzip header, not generating a check value, and not
-   looking for any check values for comparison at the end of the stream. This
+   looking for any check values for comparison at the end of the stream.  This
    is for use with other formats that use the deflate compressed data format
-   such as zip.  Those formats provide their own check values. If a custom
+   such as zip.  Those formats provide their own check values.  If a custom
    format is developed using the raw deflate format for compressed data, it is
    recommended that a check value such as an adler32 or a crc32 be applied to
    the uncompressed data as is done in the zlib, gzip, and zip formats.  For
-   most applications, the zlib format should be used as is. Note that comments
+   most applications, the zlib format should be used as is.  Note that comments
    above on the use in deflateInit2() applies to the magnitude of windowBits.
 
-     windowBits can also be greater than 15 for optional gzip decoding. Add
+     windowBits can also be greater than 15 for optional gzip decoding.  Add
    32 to windowBits to enable zlib and gzip decoding with automatic header
    detection, or add 16 to decode only the gzip format (the zlib format will
-   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is
-   a crc32 instead of an adler32.
+   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
+   crc32 instead of an adler32.
 
      inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
-   is set to null if there is no error message.  inflateInit2 does not perform
-   any decompression apart from reading the zlib header if present: this will
-   be done by inflate(). (So next_in and avail_in may be modified, but next_out
-   and avail_out are unchanged.)
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit2 does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit2() does not process any header information -- that is
+   deferred until inflate() is called.
 */
 
 ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
@@ -738,8 +786,8 @@
                                              uInt  dictLength));
 /*
      Initializes the decompression dictionary from the given uncompressed byte
-   sequence. This function must be called immediately after a call of inflate,
-   if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
+   sequence.  This function must be called immediately after a call of inflate,
+   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
    can be determined from the adler32 value returned by that call of inflate.
    The compressor and decompressor must use exactly the same dictionary (see
    deflateSetDictionary).  For raw inflate, this function can be called
@@ -748,26 +796,26 @@
    dictionary that was used for compression is provided.
 
      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
-   parameter is invalid (such as NULL dictionary) or the stream state is
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
-   expected one (incorrect adler32 value). inflateSetDictionary does not
+   expected one (incorrect adler32 value).  inflateSetDictionary does not
    perform any decompression: this will be done by subsequent calls of
    inflate().
 */
 
 ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
 /*
-    Skips invalid compressed data until a full flush point (see above the
-  description of deflate with Z_FULL_FLUSH) can be found, or until all
-  available input is skipped. No output is provided.
-
-    inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
-  if no more input was provided, Z_DATA_ERROR if no flush point has been found,
-  or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
-  case, the application may save the current current value of total_in which
-  indicates where valid compressed data was found. In the error case, the
-  application may repeatedly call inflateSync, providing more input each time,
-  until success or end of the input data.
+     Skips invalid compressed data until a full flush point (see above the
+   description of deflate with Z_FULL_FLUSH) can be found, or until all
+   available input is skipped.  No output is provided.
+
+     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+   if no more input was provided, Z_DATA_ERROR if no flush point has been
+   found, or Z_STREAM_ERROR if the stream structure was inconsistent.  In the
+   success case, the application may save the current current value of total_in
+   which indicates where valid compressed data was found.  In the error case,
+   the application may repeatedly call inflateSync, providing more input each
+   time, until success or end of the input data.
 */
 
 ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
@@ -782,18 +830,30 @@
 
      inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-   (such as zalloc being NULL). msg is left unchanged in both source and
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
    destination.
 */
 
 ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
 /*
      This function is equivalent to inflateEnd followed by inflateInit,
-   but does not free and reallocate all the internal decompression state.
-   The stream will keep attributes that may have been set by inflateInit2.
+   but does not free and reallocate all the internal decompression state.  The
+   stream will keep attributes that may have been set by inflateInit2.
 
-      inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being NULL).
+     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+                                      int windowBits));
+/*
+     This function is the same as inflateReset, but it also permits changing
+   the wrap and window size requests.  The windowBits parameter is interpreted
+   the same as it is for inflateInit2.
+
+     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+   the windowBits parameter is invalid.
 */
 
 ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
@@ -801,54 +861,87 @@
                                      int value));
 /*
      This function inserts bits in the inflate input stream.  The intent is
-  that this function is used to start inflating at a bit position in the
-  middle of a byte.  The provided bits will be used before any bytes are used
-  from next_in.  This function should only be used with raw inflate, and
-  should be used before the first inflate() call after inflateInit2() or
-  inflateReset().  bits must be less than or equal to 16, and that many of the
-  least significant bits of value will be inserted in the input.
+   that this function is used to start inflating at a bit position in the
+   middle of a byte.  The provided bits will be used before any bytes are used
+   from next_in.  This function should only be used with raw inflate, and
+   should be used before the first inflate() call after inflateInit2() or
+   inflateReset().  bits must be less than or equal to 16, and that many of the
+   least significant bits of value will be inserted in the input.
+
+     If bits is negative, then the input stream bit buffer is emptied.  Then
+   inflatePrime() can be called again to put bits in the buffer.  This is used
+   to clear out bits leftover after feeding inflate a block description prior
+   to feeding inflate codes.
 
-      inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
+/*
+     This function returns two values, one in the lower 16 bits of the return
+   value, and the other in the remaining upper bits, obtained by shifting the
+   return value down 16 bits.  If the upper value is -1 and the lower value is
+   zero, then inflate() is currently decoding information outside of a block.
+   If the upper value is -1 and the lower value is non-zero, then inflate is in
+   the middle of a stored block, with the lower value equaling the number of
+   bytes from the input remaining to copy.  If the upper value is not -1, then
+   it is the number of bits back from the current bit position in the input of
+   the code (literal or length/distance pair) currently being processed.  In
+   that case the lower value is the number of bytes already emitted for that
+   code.
+
+     A code is being processed if inflate is waiting for more input to complete
+   decoding of the code, or if it has completed decoding but is waiting for
+   more output space to write the literal or match data.
+
+     inflateMark() is used to mark locations in the input data for random
+   access, which may be at bit positions, and to note those cases where the
+   output of a code may span boundaries of random access blocks.  The current
+   location in the input stream can be determined from avail_in and data_type
+   as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+     inflateMark returns the value noted above or -1 << 16 if the provided
+   source stream state was inconsistent.
+*/
+
 ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
                                          gz_headerp head));
 /*
-      inflateGetHeader() requests that gzip header information be stored in the
+     inflateGetHeader() requests that gzip header information be stored in the
    provided gz_header structure.  inflateGetHeader() may be called after
    inflateInit2() or inflateReset(), and before the first call of inflate().
    As inflate() processes the gzip stream, head->done is zero until the header
    is completed, at which time head->done is set to one.  If a zlib stream is
    being decoded, then head->done is set to -1 to indicate that there will be
-   no gzip header information forthcoming.  Note that Z_BLOCK can be used to
-   force inflate() to return immediately after header processing is complete
-   and before any actual data is decompressed.
+   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
+   used to force inflate() to return immediately after header processing is
+   complete and before any actual data is decompressed.
 
-      The text, time, xflags, and os fields are filled in with the gzip header
+     The text, time, xflags, and os fields are filled in with the gzip header
    contents.  hcrc is set to true if there is a header CRC.  (The header CRC
-   was valid if done is set to one.)  If extra is not Z_NULL, then extra_max
+   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
    contains the maximum number of bytes to write to extra.  Once done is true,
    extra_len contains the actual extra field length, and extra contains the
    extra field, or that field truncated if extra_max is less than extra_len.
    If name is not Z_NULL, then up to name_max characters are written there,
    terminated with a zero unless the length is greater than name_max.  If
    comment is not Z_NULL, then up to comm_max characters are written there,
-   terminated with a zero unless the length is greater than comm_max.  When
-   any of extra, name, or comment are not Z_NULL and the respective field is
-   not present in the header, then that field is set to Z_NULL to signal its
+   terminated with a zero unless the length is greater than comm_max.  When any
+   of extra, name, or comment are not Z_NULL and the respective field is not
+   present in the header, then that field is set to Z_NULL to signal its
    absence.  This allows the use of deflateSetHeader() with the returned
    structure to duplicate the header.  However if those fields are set to
    allocated memory, then the application will need to save those pointers
    elsewhere so that they can be eventually freed.
 
-      If inflateGetHeader is not used, then the header information is simply
+     If inflateGetHeader is not used, then the header information is simply
    discarded.  The header is always checked for validity, including the header
    CRC if present.  inflateReset() will reset the process to discard the header
    information.  The application would need to call inflateGetHeader() again to
    retrieve the header from the next gzip stream.
 
-      inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
@@ -869,9 +962,9 @@
      See inflateBack() for the usage of these routines.
 
      inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
-   the paramaters are invalid, Z_MEM_ERROR if the internal state could not
-   be allocated, or Z_VERSION_ERROR if the version of the library does not
-   match the version of the header file.
+   the paramaters are invalid, Z_MEM_ERROR if the internal state could not be
+   allocated, or Z_VERSION_ERROR if the version of the library does not match
+   the version of the header file.
 */
 
 typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
@@ -891,15 +984,15 @@
      inflateBackInit() must be called first to allocate the internal state
    and to initialize the state with the user-provided window buffer.
    inflateBack() may then be used multiple times to inflate a complete, raw
-   deflate stream with each call.  inflateBackEnd() is then called to free
-   the allocated state.
+   deflate stream with each call.  inflateBackEnd() is then called to free the
+   allocated state.
 
      A raw deflate stream is one with no zlib or gzip header or trailer.
    This routine would normally be used in a utility that reads zip or gzip
    files and writes out uncompressed files.  The utility would decode the
-   header and process the trailer on its own, hence this routine expects
-   only the raw deflate stream to decompress.  This is different from the
-   normal behavior of inflate(), which expects either a zlib or gzip header and
+   header and process the trailer on its own, hence this routine expects only
+   the raw deflate stream to decompress.  This is different from the normal
+   behavior of inflate(), which expects either a zlib or gzip header and
    trailer around the deflate stream.
 
      inflateBack() uses two subroutines supplied by the caller that are then
@@ -925,7 +1018,7 @@
    calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
    immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
    must also be initialized, and then if strm->avail_in is not zero, input will
-   initially be taken from strm->next_in[0 .. strm->avail_in - 1].
+   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
 
      The in_desc and out_desc parameters of inflateBack() is passed as the
    first parameter of in() and out() respectively when they are called.  These
@@ -935,15 +1028,15 @@
      On return, inflateBack() will set strm->next_in and strm->avail_in to
    pass back any unused input that was provided by the last in() call.  The
    return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
-   if in() or out() returned an error, Z_DATA_ERROR if there was a format
-   error in the deflate stream (in which case strm->msg is set to indicate the
-   nature of the error), or Z_STREAM_ERROR if the stream was not properly
-   initialized.  In the case of Z_BUF_ERROR, an input or output error can be
-   distinguished using strm->next_in which will be Z_NULL only if in() returned
-   an error.  If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
-   out() returning non-zero.  (in() will always be called before out(), so
-   strm->next_in is assured to be defined if out() returns non-zero.)  Note
-   that inflateBack() cannot return Z_OK.
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+   in the deflate stream (in which case strm->msg is set to indicate the nature
+   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+   In the case of Z_BUF_ERROR, an input or output error can be distinguished
+   using strm->next_in which will be Z_NULL only if in() returned an error.  If
+   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+   non-zero.  (in() will always be called before out(), so strm->next_in is
+   assured to be defined if out() returns non-zero.) Note that inflateBack()
+   cannot return Z_OK.
 */
 
 ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
@@ -999,23 +1092,22 @@
                         /* utility functions */
 
 /*
-     The following utility functions are implemented on top of the
-   basic stream-oriented functions. To simplify the interface, some
-   default options are assumed (compression level and memory usage,
-   standard memory allocation functions). The source code of these
-   utility functions can easily be modified if you need special options.
+     The following utility functions are implemented on top of the basic
+   stream-oriented functions.  To simplify the interface, some default options
+   are assumed (compression level and memory usage, standard memory allocation
+   functions).  The source code of these utility functions can be modified if
+   you need special options.
 */
 
 ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
                                  const Bytef *source, uLong sourceLen));
 /*
      Compresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer. Upon entry, destLen is the total
-   size of the destination buffer, which must be at least the value returned
-   by compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
    compressed buffer.
-     This function can be used to compress a whole file at once if the
-   input file is mmap'ed.
+
      compress returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_BUF_ERROR if there was not enough room in the output
    buffer.
@@ -1025,11 +1117,11 @@
                                   const Bytef *source, uLong sourceLen,
                                   int level));
 /*
-     Compresses the source buffer into the destination buffer. The level
+     Compresses the source buffer into the destination buffer.  The level
    parameter has the same meaning as in deflateInit.  sourceLen is the byte
-   length of the source buffer. Upon entry, destLen is the total size of the
+   length of the source buffer.  Upon entry, destLen is the total size of the
    destination buffer, which must be at least the value returned by
-   compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
    compressed buffer.
 
      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
@@ -1040,22 +1132,20 @@
 ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
 /*
      compressBound() returns an upper bound on the compressed size after
-   compress() or compress2() on sourceLen bytes.  It would be used before
-   a compress() or compress2() call to allocate the destination buffer.
+   compress() or compress2() on sourceLen bytes.  It would be used before a
+   compress() or compress2() call to allocate the destination buffer.
 */
 
 ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
                                    const Bytef *source, uLong sourceLen));
 /*
      Decompresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer. Upon entry, destLen is the total
-   size of the destination buffer, which must be large enough to hold the
-   entire uncompressed data. (The size of the uncompressed data must have
-   been saved previously by the compressor and transmitted to the decompressor
-   by some mechanism outside the scope of this compression library.)
-   Upon exit, destLen is the actual size of the compressed buffer.
-     This function can be used to decompress a whole file at once if the
-   input file is mmap'ed.
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data.  (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit, destLen
+   is the actual size of the uncompressed buffer.
 
      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
    enough memory, Z_BUF_ERROR if there was not enough room in the output
@@ -1063,136 +1153,199 @@
 */
 
 
-typedef voidp gzFile;
+                        /* gzip file access functions */
+
+/*
+     This library supports reading and writing files in gzip (.gz) format with
+   an interface similar to that of stdio, using the functions that start with
+   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
+   wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef voidp gzFile;       /* opaque gzip file descriptor */
 
-ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
 /*
-     Opens a gzip (.gz) file for reading or writing. The mode parameter
-   is as in fopen ("rb" or "wb") but can also include a compression level
-   ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
-   Huffman only compression as in "wb1h", or 'R' for run-length encoding
-   as in "wb1R". (See the description of deflateInit2 for more information
-   about the strategy parameter.)
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
+   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+   for fixed code compression as in "wb9F".  (See the description of
+   deflateInit2 for more information about the strategy parameter.) Also "a"
+   can be used instead of "w" to request that the gzip stream that will be
+   written be appended to the file.  "+" will result in an error, since reading
+   and writing to the same gzip file is not supported.
 
      gzopen can be used to read a file which is not in gzip format; in this
    case gzread will directly read from the file without decompression.
 
-     gzopen returns NULL if the file could not be opened or if there was
-   insufficient memory to allocate the (de)compression state; errno
-   can be checked to distinguish the two cases (if errno is zero, the
-   zlib error is Z_MEM_ERROR).  */
-
-ZEXTERN gzFile ZEXPORT gzdopen  OF((int fd, const char *mode));
-/*
-     gzdopen() associates a gzFile with the file descriptor fd.  File
-   descriptors are obtained from calls like open, dup, creat, pipe or
-   fileno (in the file has been previously opened with fopen).
-   The mode parameter is as in gzopen.
-     The next call of gzclose on the returned gzFile will also close the
-   file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
-   descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
-     gzdopen returns NULL if there was insufficient memory to allocate
-   the (de)compression state.
+     gzopen returns NULL if the file could not be opened, if there was
+   insufficient memory to allocate the gzFile state, or if an invalid mode was
+   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+   errno can be checked to determine if the reason gzopen failed was that the
+   file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
+   are obtained from calls like open, dup, creat, pipe or fileno (if the file
+   has been previously opened with fopen).  The mode parameter is as in gzopen.
+
+     The next call of gzclose on the returned gzFile will also close the file
+   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+   mode);.  The duplicated descriptor should be saved to avoid a leak, since
+   gzdopen does not close fd if it fails.
+
+     gzdopen returns NULL if there was insufficient memory to allocate the
+   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
+   used until the next gz* read, write, seek, or close operation, so gzdopen
+   will not detect if fd is invalid (unless fd is -1).
+*/
+
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
+/*
+     Set the internal buffer size used by this library's functions.  The
+   default buffer size is 8192 bytes.  This function must be called after
+   gzopen() or gzdopen(), and before any other calls that read or write the
+   file.  The buffer memory allocation is always deferred to the first read or
+   write.  Two buffers are allocated, either both of the specified size when
+   writing, or one of the specified size and the other twice that size when
+   reading.  A larger buffer size of, for example, 64K or 128K bytes will
+   noticeably increase the speed of decompression (reading).
+
+     The new buffer size also affects the maximum length for gzprintf().
+
+     gzbuffer() returns 0 on success, or -1 on failure, such as being called
+   too late.
 */
 
 ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
 /*
-     Dynamically update the compression level or strategy. See the description
+     Dynamically update the compression level or strategy.  See the description
    of deflateInit2 for the meaning of these parameters.
+
      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
    opened for writing.
 */
 
-ZEXTERN int ZEXPORT    gzread  OF((gzFile file, voidp buf, unsigned len));
+ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
 /*
-     Reads the given number of uncompressed bytes from the compressed file.
-   If the input file was not in gzip format, gzread copies the given number
-   of bytes into the buffer.
-     gzread returns the number of uncompressed bytes actually read (0 for
-   end of file, -1 for error). */
+     Reads the given number of uncompressed bytes from the compressed file.  If
+   the input file was not in gzip format, gzread copies the given number of
+   bytes into the buffer.
+
+     After reaching the end of a gzip stream in the input, gzread will continue
+   to read, looking for another gzip stream, or failing that, reading the rest
+   of the input file directly without decompression.  The entire input file
+   will be read if gzread is called until it returns less than the requested
+   len.
 
-ZEXTERN int ZEXPORT    gzwrite OF((gzFile file,
-                                   voidpc buf, unsigned len));
+     gzread returns the number of uncompressed bytes actually read, less than
+   len for end of file, or -1 for error.
+*/
+
+ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
+                                voidpc buf, unsigned len));
 /*
      Writes the given number of uncompressed bytes into the compressed file.
-   gzwrite returns the number of uncompressed bytes actually written
-   (0 in case of error).
+   gzwrite returns the number of uncompressed bytes written or 0 in case of
+   error.
 */
 
-ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
+ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
 /*
-     Converts, formats, and writes the args to the compressed file under
-   control of the format string, as in fprintf. gzprintf returns the number of
-   uncompressed bytes actually written (0 in case of error).  The number of
-   uncompressed bytes written is limited to 4095. The caller should assure that
-   this limit is not exceeded. If it is exceeded, then gzprintf() will return
-   return an error (0) with nothing written. In this case, there may also be a
-   buffer overflow with unpredictable consequences, which is possible only if
-   zlib was compiled with the insecure functions sprintf() or vsprintf()
-   because the secure snprintf() or vsnprintf() functions were not available.
+     Converts, formats, and writes the arguments to the compressed file under
+   control of the format string, as in fprintf.  gzprintf returns the number of
+   uncompressed bytes actually written, or 0 in case of error.  The number of
+   uncompressed bytes written is limited to 8191, or one less than the buffer
+   size given to gzbuffer().  The caller should assure that this limit is not
+   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with
+   nothing written.  In this case, there may also be a buffer overflow with
+   unpredictable consequences, which is possible only if zlib was compiled with
+   the insecure functions sprintf() or vsprintf() because the secure snprintf()
+   or vsnprintf() functions were not available.  This can be determined using
+   zlibCompileFlags().
 */
 
 ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
 /*
-      Writes the given null-terminated string to the compressed file, excluding
+     Writes the given null-terminated string to the compressed file, excluding
    the terminating null character.
-      gzputs returns the number of characters written, or -1 in case of error.
+
+     gzputs returns the number of characters written, or -1 in case of error.
 */
 
 ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
 /*
-      Reads bytes from the compressed file until len-1 characters are read, or
-   a newline character is read and transferred to buf, or an end-of-file
-   condition is encountered.  The string is then terminated with a null
-   character.
-      gzgets returns buf, or Z_NULL in case of error.
+     Reads bytes from the compressed file until len-1 characters are read, or a
+   newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  If any characters are read or if len == 1, the
+   string is terminated with a null character.  If no characters are read due
+   to an end-of-file or len < 1, then the buffer is left untouched.
+
+     gzgets returns buf which is a null-terminated string, or it returns NULL
+   for end-of-file or in case of error.  If there was an error, the contents at
+   buf are indeterminate.
 */
 
-ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
+ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
 /*
-      Writes c, converted to an unsigned char, into the compressed file.
-   gzputc returns the value that was written, or -1 in case of error.
+     Writes c, converted to an unsigned char, into the compressed file.  gzputc
+   returns the value that was written, or -1 in case of error.
 */
 
-ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
+ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
 /*
-      Reads one byte from the compressed file. gzgetc returns this byte
-   or -1 in case of end of file or error.
+     Reads one byte from the compressed file.  gzgetc returns this byte or -1
+   in case of end of file or error.
 */
 
-ZEXTERN int ZEXPORT    gzungetc OF((int c, gzFile file));
+ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
 /*
-      Push one character back onto the stream to be read again later.
-   Only one character of push-back is allowed.  gzungetc() returns the
-   character pushed, or -1 on failure.  gzungetc() will fail if a
-   character has been pushed but not read yet, or if c is -1. The pushed
-   character will be discarded if the stream is repositioned with gzseek()
-   or gzrewind().
+     Push one character back onto the stream to be read as the first character
+   on the next read.  At least one character of push-back is allowed.
+   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
+   fail if c is -1, and may fail if a character has been pushed but not read
+   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
+   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
+   The pushed character will be discarded if the stream is repositioned with
+   gzseek() or gzrewind().
 */
 
-ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
+ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
 /*
-     Flushes all pending output into the compressed file. The parameter
-   flush is as in the deflate() function. The return value is the zlib
-   error number (see function gzerror below). gzflush returns Z_OK if
-   the flush parameter is Z_FINISH and all output could be flushed.
-     gzflush should be called only when strictly necessary because it can
-   degrade compression.
+     Flushes all pending output into the compressed file.  The parameter flush
+   is as in the deflate() function.  The return value is the zlib error number
+   (see function gzerror below).  gzflush is only permitted when writing.
+
+     If the flush parameter is Z_FINISH, the remaining data is written and the
+   gzip stream is completed in the output.  If gzwrite() is called again, a new
+   gzip stream will be started in the output.  gzread() is able to read such
+   concatented gzip streams.
+
+     gzflush should be called only when strictly necessary because it will
+   degrade compression if called too often.
 */
 
-ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
-                                      z_off_t offset, int whence));
 /*
-      Sets the starting position for the next gzread or gzwrite on the
-   given compressed file. The offset represents a number of bytes in the
-   uncompressed data stream. The whence parameter is defined as in lseek(2);
+ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
+                                   z_off_t offset, int whence));
+
+     Sets the starting position for the next gzread or gzwrite on the given
+   compressed file.  The offset represents a number of bytes in the
+   uncompressed data stream.  The whence parameter is defined as in lseek(2);
    the value SEEK_END is not supported.
+
      If the file is opened for reading, this function is emulated but can be
-   extremely slow. If the file is opened for writing, only forward seeks are
+   extremely slow.  If the file is opened for writing, only forward seeks are
    supported; gzseek then compresses a sequence of zeroes up to the new
    starting position.
 
-      gzseek returns the resulting offset location as measured in bytes from
+     gzseek returns the resulting offset location as measured in bytes from
    the beginning of the uncompressed stream, or -1 in case of error, in
    particular if the file is opened for writing and the new starting position
    would be before the current position.
@@ -1202,68 +1355,127 @@
 /*
      Rewinds the given file. This function is supported only for reading.
 
-   gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
 */
 
+/*
 ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+
+     Returns the starting position for the next gzread or gzwrite on the given
+   compressed file.  This position represents a number of bytes in the
+   uncompressed data stream, and is zero when starting, even if appending or
+   reading a gzip stream from the middle of a file using gzdopen().
+
+     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
 /*
-     Returns the starting position for the next gzread or gzwrite on the
-   given compressed file. This position represents a number of bytes in the
-   uncompressed data stream.
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
 
-   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+     Returns the current offset in the file being read or written.  This offset
+   includes the count of bytes that precede the gzip stream, for example when
+   appending or when using gzdopen() for reading.  When reading, the offset
+   does not include as yet unused buffered input.  This information can be used
+   for a progress indicator.  On error, gzoffset() returns -1.
 */
 
 ZEXTERN int ZEXPORT gzeof OF((gzFile file));
 /*
-     Returns 1 when EOF has previously been detected reading the given
-   input stream, otherwise zero.
+     Returns true (1) if the end-of-file indicator has been set while reading,
+   false (0) otherwise.  Note that the end-of-file indicator is set only if the
+   read tried to go past the end of the input, but came up short.  Therefore,
+   just like feof(), gzeof() may return false even if there is no more data to
+   read, in the event that the last read request was for the exact number of
+   bytes remaining in the input file.  This will happen if the input file size
+   is an exact multiple of the buffer size.
+
+     If gzeof() returns true, then the read functions will return no more data,
+   unless the end-of-file indicator is reset by gzclearerr() and the input file
+   has grown since the previous end of file was detected.
 */
 
 ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
 /*
-     Returns 1 if file is being read directly without decompression, otherwise
-   zero.
+     Returns true (1) if file is being copied directly while reading, or false
+   (0) if file is a gzip stream being decompressed.  This state can change from
+   false to true while reading the input file if the end of a gzip stream is
+   reached, but is followed by data that is not another gzip stream.
+
+     If the input file is empty, gzdirect() will return true, since the input
+   does not contain a gzip stream.
+
+     If gzdirect() is used immediately after gzopen() or gzdopen() it will
+   cause buffers to be allocated to allow reading the file to determine if it
+   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
+   gzdirect().
 */
 
 ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
 /*
-     Flushes all pending output if necessary, closes the compressed file
-   and deallocates all the (de)compression state. The return value is the zlib
-   error number (see function gzerror below).
+     Flushes all pending output if necessary, closes the compressed file and
+   deallocates the (de)compression state.  Note that once file is closed, you
+   cannot call gzerror with file, since its structures have been deallocated.
+   gzclose must not be called more than once on the same file, just as free
+   must not be called more than once on the same allocation.
+
+     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+   file operation error, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+     Same as gzclose(), but gzclose_r() is only for use when reading, and
+   gzclose_w() is only for use when writing or appending.  The advantage to
+   using these instead of gzclose() is that they avoid linking in zlib
+   compression or decompression code that is not used when only reading or only
+   writing respectively.  If gzclose() is used, then both compression and
+   decompression code will be included the application when linking to a static
+   zlib library.
 */
 
 ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
 /*
-     Returns the error message for the last error which occurred on the
-   given compressed file. errnum is set to zlib error number. If an
-   error occurred in the file system and not in the compression library,
-   errnum is set to Z_ERRNO and the application may consult errno
-   to get the exact error code.
+     Returns the error message for the last error which occurred on the given
+   compressed file.  errnum is set to zlib error number.  If an error occurred
+   in the file system and not in the compression library, errnum is set to
+   Z_ERRNO and the application may consult errno to get the exact error code.
+
+     The application must not modify the returned string.  Future calls to
+   this function may invalidate the previously returned string.  If file is
+   closed, then the string previously returned by gzerror will no longer be
+   available.
+
+     gzerror() should be used to distinguish errors from end-of-file for those
+   functions above that do not distinguish those cases in their return values.
 */
 
 ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
 /*
-     Clears the error and end-of-file flags for file. This is analogous to the
-   clearerr() function in stdio. This is useful for continuing to read a gzip
+     Clears the error and end-of-file flags for file.  This is analogous to the
+   clearerr() function in stdio.  This is useful for continuing to read a gzip
    file that is being written concurrently.
 */
 
+
                         /* checksum functions */
 
 /*
      These functions are not related to compression but are exported
-   anyway because they might be useful in applications using the
-   compression library.
+   anyway because they might be useful in applications using the compression
+   library.
 */
 
 ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
 /*
      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
-   return the updated checksum. If buf is NULL, this function returns
-   the required initial value for the checksum.
-   An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
-   much faster. Usage example:
+   return the updated checksum.  If buf is Z_NULL, this function returns the
+   required initial value for the checksum.
+
+     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+   much faster.
+
+   Usage example:
 
      uLong adler = adler32(0L, Z_NULL, 0);
 
@@ -1273,9 +1485,10 @@
      if (adler != original_adler) error();
 */
 
+/*
 ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
                                           z_off_t len2));
-/*
+
      Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
    and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
    each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
@@ -1285,9 +1498,11 @@
 ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
 /*
      Update a running CRC-32 with the bytes buf[0..len-1] and return the
-   updated CRC-32. If buf is NULL, this function returns the required initial
-   value for the for the crc. Pre- and post-conditioning (one's complement) is
-   performed within this function so it shouldn't be done by the application.
+   updated CRC-32.  If buf is Z_NULL, this function returns the required
+   initial value for the for the crc.  Pre- and post-conditioning (one's
+   complement) is performed within this function so it shouldn't be done by the
+   application.
+
    Usage example:
 
      uLong crc = crc32(0L, Z_NULL, 0);
@@ -1298,9 +1513,9 @@
      if (crc != original_crc) error();
 */
 
+/*
 ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
 
-/*
      Combine two CRC-32 check values into one.  For two sequences of bytes,
    seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
    calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
@@ -1339,16 +1554,57 @@
         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
 #define inflateBackInit(strm, windowBits, window) \
         inflateBackInit_((strm), (windowBits), (window), \
-        ZLIB_VERSION, sizeof(z_stream))
+                                            ZLIB_VERSION, sizeof(z_stream))
+
+/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
+ * both are true, the application gets the *64 functions, and the regular
+ * functions are changed to 64 bits) -- in case these are set on systems
+ * without large file support, _LFS64_LARGEFILE must also be true
+ */
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
+   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
+#endif
 
+#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0
+#  define gzopen gzopen64
+#  define gzseek gzseek64
+#  define gztell gztell64
+#  define gzoffset gzoffset64
+#  define adler32_combine adler32_combine64
+#  define crc32_combine crc32_combine64
+#  ifdef _LARGEFILE64_SOURCE
+     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
+     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
+     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
+     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#  endif
+#else
+   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
 
+/* hack for buggy compilers */
 #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
-    struct internal_state {int dummy;}; /* hack for buggy compilers */
+    struct internal_state {int dummy;};
 #endif
 
+/* undocumented functions */
 ZEXTERN const char   * ZEXPORT zError           OF((int));
-ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
 ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
 
 #ifdef __cplusplus
 }

Modified: python/branches/py3k-dtoa/Modules/zlib/zutil.c
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/zutil.c	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/zutil.c	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* zutil.c -- target dependent utility functions for the compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2005, 2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -34,25 +34,25 @@
     uLong flags;
 
     flags = 0;
-    switch (sizeof(uInt)) {
+    switch ((int)(sizeof(uInt))) {
     case 2:     break;
     case 4:     flags += 1;     break;
     case 8:     flags += 2;     break;
     default:    flags += 3;
     }
-    switch (sizeof(uLong)) {
+    switch ((int)(sizeof(uLong))) {
     case 2:     break;
     case 4:     flags += 1 << 2;        break;
     case 8:     flags += 2 << 2;        break;
     default:    flags += 3 << 2;
     }
-    switch (sizeof(voidpf)) {
+    switch ((int)(sizeof(voidpf))) {
     case 2:     break;
     case 4:     flags += 1 << 4;        break;
     case 8:     flags += 2 << 4;        break;
     default:    flags += 3 << 4;
     }
-    switch (sizeof(z_off_t)) {
+    switch ((int)(sizeof(z_off_t))) {
     case 2:     break;
     case 4:     flags += 1 << 6;        break;
     case 8:     flags += 2 << 6;        break;
@@ -117,9 +117,9 @@
 #  ifndef verbose
 #    define verbose 0
 #  endif
-int z_verbose = verbose;
+int ZLIB_INTERNAL z_verbose = verbose;
 
-void z_error (m)
+void ZLIB_INTERNAL z_error (m)
     char *m;
 {
     fprintf(stderr, "%s\n", m);
@@ -146,7 +146,7 @@
 
 #ifndef HAVE_MEMCPY
 
-void zmemcpy(dest, source, len)
+void ZLIB_INTERNAL zmemcpy(dest, source, len)
     Bytef* dest;
     const Bytef* source;
     uInt  len;
@@ -157,7 +157,7 @@
     } while (--len != 0);
 }
 
-int zmemcmp(s1, s2, len)
+int ZLIB_INTERNAL zmemcmp(s1, s2, len)
     const Bytef* s1;
     const Bytef* s2;
     uInt  len;
@@ -170,7 +170,7 @@
     return 0;
 }
 
-void zmemzero(dest, len)
+void ZLIB_INTERNAL zmemzero(dest, len)
     Bytef* dest;
     uInt  len;
 {
@@ -213,7 +213,7 @@
  * a protected system like OS/2. Use Microsoft C instead.
  */
 
-voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
 {
     voidpf buf = opaque; /* just to make some compilers happy */
     ulg bsize = (ulg)items*size;
@@ -237,7 +237,7 @@
     return buf;
 }
 
-void  zcfree (voidpf opaque, voidpf ptr)
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
 {
     int n;
     if (*(ush*)&ptr != 0) { /* object < 64K */
@@ -272,13 +272,13 @@
 #  define _hfree   hfree
 #endif
 
-voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
 {
     if (opaque) opaque = 0; /* to make compiler happy */
     return _halloc((long)items, size);
 }
 
-void  zcfree (voidpf opaque, voidpf ptr)
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
 {
     if (opaque) opaque = 0; /* to make compiler happy */
     _hfree(ptr);
@@ -297,7 +297,7 @@
 extern void   free   OF((voidpf ptr));
 #endif
 
-voidpf zcalloc (opaque, items, size)
+voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
     voidpf opaque;
     unsigned items;
     unsigned size;
@@ -307,7 +307,7 @@
                               (voidpf)calloc(items, size);
 }
 
-void  zcfree (opaque, ptr)
+void ZLIB_INTERNAL zcfree (opaque, ptr)
     voidpf opaque;
     voidpf ptr;
 {

Modified: python/branches/py3k-dtoa/Modules/zlib/zutil.h
==============================================================================
--- python/branches/py3k-dtoa/Modules/zlib/zutil.h	(original)
+++ python/branches/py3k-dtoa/Modules/zlib/zutil.h	Sun Aug  8 12:41:24 2010
@@ -1,5 +1,5 @@
 /* zutil.h -- internal interface and configuration of the compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -13,31 +13,21 @@
 #ifndef ZUTIL_H
 #define ZUTIL_H
 
-#define ZLIB_INTERNAL
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
 #include "zlib.h"
 
 #ifdef STDC
-#  ifndef _WIN32_WCE
+#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
 #    include <stddef.h>
 #  endif
 #  include <string.h>
 #  include <stdlib.h>
 #endif
-#ifdef NO_ERRNO_H
-#   ifdef _WIN32_WCE
-      /* The Microsoft C Run-Time Library for Windows CE doesn't have
-       * errno.  We define it as a global variable to simplify porting.
-       * Its value is always 0 and should not be used.  We rename it to
-       * avoid conflict with other libraries that use the same workaround.
-       */
-#     define errno z_errno
-#   endif
-    extern int errno;
-#else
-#  ifndef _WIN32_WCE
-#    include <errno.h>
-#  endif
-#endif
 
 #ifndef local
 #  define local static
@@ -89,7 +79,7 @@
 #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
 #  define OS_CODE  0x00
 #  if defined(__TURBOC__) || defined(__BORLANDC__)
-#    if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
+#    if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
        /* Allow compilation with ANSI keywords only enabled */
        void _Cdecl farfree( void *block );
        void *_Cdecl farmalloc( unsigned long nbytes );
@@ -118,7 +108,7 @@
 #ifdef OS2
 #  define OS_CODE  0x06
 #  ifdef M_I86
-     #include <malloc.h>
+#    include <malloc.h>
 #  endif
 #endif
 
@@ -147,11 +137,11 @@
 #  define OS_CODE  0x0f
 #endif
 
-#if defined(_BEOS_)
+#if defined(_BEOS_) || defined(RISCOS)
 #  define fdopen(fd,mode) NULL /* No fdopen() */
 #endif
 
-#if (defined(_MSC_VER) && (_MSC_VER > 600))
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
 #  if defined(_WIN32_WCE)
 #    define fdopen(fd,mode) NULL /* No fdopen() */
 #    ifndef _PTRDIFF_T_DEFINED
@@ -163,6 +153,18 @@
 #  endif
 #endif
 
+#if defined(__BORLANDC__)
+  #pragma warn -8004
+  #pragma warn -8008
+  #pragma warn -8066
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
+    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#endif
+
         /* common defaults */
 
 #ifndef OS_CODE
@@ -197,7 +199,9 @@
 #  ifdef WIN32
      /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
 #    if !defined(vsnprintf) && !defined(NO_vsnprintf)
-#      define vsnprintf _vsnprintf
+#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
+#         define vsnprintf _vsnprintf
+#      endif
 #    endif
 #  endif
 #  ifdef __SASC
@@ -232,16 +236,16 @@
 #    define zmemzero(dest, len) memset(dest, 0, len)
 #  endif
 #else
-   extern void zmemcpy  OF((Bytef* dest, const Bytef* source, uInt len));
-   extern int  zmemcmp  OF((const Bytef* s1, const Bytef* s2, uInt len));
-   extern void zmemzero OF((Bytef* dest, uInt len));
+   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
+   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
+   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
 #endif
 
 /* Diagnostic functions */
 #ifdef DEBUG
 #  include <stdio.h>
-   extern int z_verbose;
-   extern void z_error    OF((char *m));
+   extern int ZLIB_INTERNAL z_verbose;
+   extern void ZLIB_INTERNAL z_error OF((char *m));
 #  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
 #  define Trace(x) {if (z_verbose>=0) fprintf x ;}
 #  define Tracev(x) {if (z_verbose>0) fprintf x ;}
@@ -258,8 +262,9 @@
 #endif
 
 
-voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
-void   zcfree  OF((voidpf opaque, voidpf ptr));
+voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
+                        unsigned size));
+void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
 
 #define ZALLOC(strm, items, size) \
            (*((strm)->zalloc))((strm)->opaque, (items), (size))

Modified: python/branches/py3k-dtoa/Objects/bytearrayobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/bytearrayobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/bytearrayobject.c	Sun Aug  8 12:41:24 2010
@@ -33,6 +33,7 @@
         PyObject *index = PyNumber_Index(arg);
         if (index == NULL) {
             PyErr_Format(PyExc_TypeError, "an integer is required");
+            *value = -1;
             return 0;
         }
         face_value = PyLong_AsLong(index);
@@ -42,6 +43,7 @@
     if (face_value < 0 || face_value >= 256) {
         /* this includes the OverflowError in case the long is too large */
         PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
+        *value = -1;
         return 0;
     }
 
@@ -647,6 +649,11 @@
 
             if (!_canresize(self))
                 return -1;
+
+            if (slicelen == 0)
+                /* Nothing to do here. */
+                return 0;
+
             if (step < 0) {
                 stop = start + 1;
                 start = stop + step * (slicelen - 1) - 1;
@@ -663,7 +670,7 @@
                         self->ob_bytes + cur + 1, lim);
             }
             /* Move the tail of the bytes, in one chunk */
-            cur = start + slicelen*step;
+            cur = start + (size_t)slicelen*step;
             if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
                 memmove(self->ob_bytes + cur - slicelen,
                         self->ob_bytes + cur,
@@ -677,7 +684,8 @@
         }
         else {
             /* Assign slice */
-            Py_ssize_t cur, i;
+            Py_ssize_t i;
+            size_t cur;
 
             if (needed != slicelen) {
                 PyErr_Format(PyExc_ValueError,

Modified: python/branches/py3k-dtoa/Objects/complexobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/complexobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/complexobject.c	Sun Aug  8 12:41:24 2010
@@ -394,12 +394,6 @@
     return complex_format(v, 0, 'r');
 }
 
-static PyObject *
-complex_str(PyComplexObject *v)
-{
-    return complex_format(v, PyFloat_STR_PRECISION, 'g');
-}
-
 static long
 complex_hash(PyComplexObject *v)
 {
@@ -1104,7 +1098,7 @@
     0,                                          /* tp_as_mapping */
     (hashfunc)complex_hash,                     /* tp_hash */
     0,                                          /* tp_call */
-    (reprfunc)complex_str,                      /* tp_str */
+    (reprfunc)complex_repr,                     /* tp_str */
     PyObject_GenericGetAttr,                    /* tp_getattro */
     0,                                          /* tp_setattro */
     0,                                          /* tp_as_buffer */

Modified: python/branches/py3k-dtoa/Objects/floatobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/floatobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/floatobject.c	Sun Aug  8 12:41:24 2010
@@ -309,32 +309,20 @@
 }
 
 static PyObject *
-float_str_or_repr(PyFloatObject *v, int precision, char format_code)
+float_repr(PyFloatObject *v)
 {
     PyObject *result;
     char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
-                                      format_code, precision,
+                                      'r', 0,
                                       Py_DTSF_ADD_DOT_0,
                                       NULL);
     if (!buf)
-    return PyErr_NoMemory();
+        return PyErr_NoMemory();
     result = PyUnicode_FromString(buf);
     PyMem_Free(buf);
     return result;
 }
 
-static PyObject *
-float_repr(PyFloatObject *v)
-{
-    return float_str_or_repr(v, 0, 'r');
-}
-
-static PyObject *
-float_str(PyFloatObject *v)
-{
-    return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
-}
-
 /* Comparison is pretty much a nightmare.  When comparing float to float,
  * we do it as straightforwardly (and long-windedly) as conceivable, so
  * that, e.g., Python x == y delivers the same result as the platform
@@ -1173,7 +1161,7 @@
     CONVERT_TO_DOUBLE(v, x);
 
     if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
-        return float_str((PyFloatObject *)v);
+        return float_repr((PyFloatObject *)v);
 
     if (x == 0.0) {
         if (copysign(1.0, x) == -1.0)
@@ -1955,7 +1943,7 @@
     0,                                          /* tp_as_mapping */
     (hashfunc)float_hash,                       /* tp_hash */
     0,                                          /* tp_call */
-    (reprfunc)float_str,                        /* tp_str */
+    (reprfunc)float_repr,                       /* tp_str */
     PyObject_GenericGetAttr,                    /* tp_getattro */
     0,                                          /* tp_setattro */
     0,                                          /* tp_as_buffer */

Modified: python/branches/py3k-dtoa/Objects/iterobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/iterobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/iterobject.c	Sun Aug  8 12:41:24 2010
@@ -177,9 +177,7 @@
         Py_DECREF(args);
         if (result != NULL) {
             int ok;
-            ok = PyObject_RichCompareBool(result,
-                                          it->it_sentinel,
-                                          Py_EQ);
+            ok = PyObject_RichCompareBool(it->it_sentinel, result, Py_EQ);               
             if (ok == 0)
                 return result; /* Common case, fast path */
             Py_DECREF(result);

Modified: python/branches/py3k-dtoa/Objects/memoryobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/memoryobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/memoryobject.c	Sun Aug  8 12:41:24 2010
@@ -624,7 +624,7 @@
 static int
 memory_ass_sub(PyMemoryViewObject *self, PyObject *key, PyObject *value)
 {
-    Py_ssize_t start, len, bytelen, i;
+    Py_ssize_t start, len, bytelen;
     Py_buffer srcview;
     Py_buffer *view = &(self->view);
     char *srcbuf, *destbuf;
@@ -694,16 +694,8 @@
     if (destbuf + bytelen < srcbuf || srcbuf + bytelen < destbuf)
         /* No overlapping */
         memcpy(destbuf, srcbuf, bytelen);
-    else if (destbuf < srcbuf) {
-        /* Copy in ascending order */
-        for (i = 0; i < bytelen; i++)
-            destbuf[i] = srcbuf[i];
-    }
-    else {
-        /* Copy in descencing order */
-        for (i = bytelen - 1; i >= 0; i--)
-            destbuf[i] = srcbuf[i];
-    }
+    else
+        memmove(destbuf, srcbuf, bytelen);
 
     PyBuffer_Release(&srcview);
     return 0;

Modified: python/branches/py3k-dtoa/Objects/object.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/object.c	(original)
+++ python/branches/py3k-dtoa/Objects/object.c	Sun Aug  8 12:41:24 2010
@@ -258,15 +258,10 @@
     return PyObject_INIT_VAR(op, tp, nitems);
 }
 
-/* Implementation of PyObject_Print with recursion checking */
-static int
-internal_print(PyObject *op, FILE *fp, int flags, int nesting)
+int
+PyObject_Print(PyObject *op, FILE *fp, int flags)
 {
     int ret = 0;
-    if (nesting > 10) {
-        PyErr_SetString(PyExc_RuntimeError, "print recursion");
-        return -1;
-    }
     if (PyErr_CheckSignals())
         return -1;
 #ifdef USE_STACKCHECK
@@ -333,12 +328,6 @@
     return ret;
 }
 
-int
-PyObject_Print(PyObject *op, FILE *fp, int flags)
-{
-    return internal_print(op, fp, flags, 0);
-}
-
 /* For debugging convenience.  Set a breakpoint here and call it from your DLL */
 void
 _Py_BreakPoint(void)

Modified: python/branches/py3k-dtoa/Objects/setobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/setobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/setobject.c	Sun Aug  8 12:41:24 2010
@@ -1846,12 +1846,10 @@
         if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
             return -1;
         PyErr_Clear();
-        tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
+        tmpkey = make_new_set(&PyFrozenSet_Type, key);
         if (tmpkey == NULL)
             return -1;
-        set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
         rv = set_contains(so, tmpkey);
-        set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
         Py_DECREF(tmpkey);
     }
     return rv;
@@ -1881,12 +1879,10 @@
         if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
             return NULL;
         PyErr_Clear();
-        tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
+        tmpkey = make_new_set(&PyFrozenSet_Type, key);
         if (tmpkey == NULL)
             return NULL;
-        set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
         rv = set_discard_key(so, tmpkey);
-        set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
         Py_DECREF(tmpkey);
         if (rv == -1)
             return NULL;
@@ -1915,12 +1911,10 @@
         if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
             return NULL;
         PyErr_Clear();
-        tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
+        tmpkey = make_new_set(&PyFrozenSet_Type, key);
         if (tmpkey == NULL)
             return NULL;
-        set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
         result = set_discard(so, tmpkey);
-        set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
         Py_DECREF(tmpkey);
         return result;
     }

Modified: python/branches/py3k-dtoa/Objects/sliceobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/sliceobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/sliceobject.c	Sun Aug  8 12:41:24 2010
@@ -131,7 +131,8 @@
 
 int
 PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length,
-                     Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)
+                     Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step,
+                     Py_ssize_t *slicelength)
 {
     /* this is harder to get right than you might think */
 
@@ -147,6 +148,13 @@
                             "slice step cannot be zero");
             return -1;
         }
+        /* Here *step might be -PY_SSIZE_T_MAX-1; in this case we replace it
+         * with -PY_SSIZE_T_MAX.  This doesn't affect the semantics, and it
+         * guards against later undefined behaviour resulting from code that
+         * does "step = -step" as part of a slice reversal.
+         */
+        if (*step < -PY_SSIZE_T_MAX)
+            *step = -PY_SSIZE_T_MAX;
     }
 
     defstart = *step < 0 ? length-1 : 0;

Modified: python/branches/py3k-dtoa/Objects/stringlib/formatter.h
==============================================================================
--- python/branches/py3k-dtoa/Objects/stringlib/formatter.h	(original)
+++ python/branches/py3k-dtoa/Objects/stringlib/formatter.h	Sun Aug  8 12:41:24 2010
@@ -776,14 +776,6 @@
             goto done;
         }
 
-        /* Error to specify a comma. */
-        if (format->thousands_separators) {
-            PyErr_SetString(PyExc_ValueError,
-                            "Thousands separators not allowed with integer"
-                            " format specifier 'c'");
-            goto done;
-        }
-
         /* taken from unicodeobject.c formatchar() */
         /* Integer input truncated to a character */
 /* XXX: won't work for int */
@@ -958,11 +950,12 @@
     }
 
     if (type == '\0') {
-        /* Omitted type specifier. This is like 'g' but with at least one
-           digit after the decimal point, and different default precision.*/
-        type = 'g';
-        default_precision = PyFloat_STR_PRECISION;
+        /* Omitted type specifier.  Behaves in the same way as repr(x)
+           and str(x) if no precision is given, else like 'g', but with
+           at least one digit after the decimal point. */
         flags |= Py_DTSF_ADD_DOT_0;
+        type = 'r';
+        default_precision = 0;
     }
 
     if (type == 'n')
@@ -982,6 +975,8 @@
 
     if (precision < 0)
         precision = default_precision;
+    else if (type == 'r')
+        type = 'g';
 
     /* Cast "type", because if we're in unicode we need to pass a
        8-bit char. This is safe, because we've restricted what "type"
@@ -1142,11 +1137,12 @@
 
     if (type == '\0') {
         /* Omitted type specifier. Should be like str(self). */
-        type = 'g';
-        default_precision = PyFloat_STR_PRECISION;
-        add_parens = 1;
-        if (re == 0.0)
+        type = 'r';
+        default_precision = 0;
+        if (re == 0.0 && copysign(1.0, re) == 1.0)
             skip_re = 1;
+        else
+            add_parens = 1;
     }
 
     if (type == 'n')
@@ -1156,6 +1152,8 @@
 
     if (precision < 0)
         precision = default_precision;
+    else if (type == 'r')
+        type = 'g';
 
     /* Cast "type", because if we're in unicode we need to pass a
        8-bit char. This is safe, because we've restricted what "type"
@@ -1231,8 +1229,11 @@
                                     n_re_digits, n_re_remainder,
                                     re_has_decimal, &locale, &tmp_format);
 
-    /* Same formatting, but always include a sign. */
-    tmp_format.sign = '+';
+    /* Same formatting, but always include a sign, unless the real part is
+     * going to be omitted, in which case we use whatever sign convention was
+     * requested by the original format. */
+    if (!skip_re)
+        tmp_format.sign = '+';
     n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, p_im,
                                     n_im_digits, n_im_remainder,
                                     im_has_decimal, &locale, &tmp_format);

Modified: python/branches/py3k-dtoa/Objects/structseq.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/structseq.c	(original)
+++ python/branches/py3k-dtoa/Objects/structseq.c	Sun Aug  8 12:41:24 2010
@@ -30,113 +30,30 @@
 PyStructSequence_New(PyTypeObject *type)
 {
     PyStructSequence *obj;
+    Py_ssize_t size = REAL_SIZE_TP(type), i;
 
-    obj = PyObject_New(PyStructSequence, type);
+    obj = PyObject_GC_NewVar(PyStructSequence, type, size);
     if (obj == NULL)
         return NULL;
+    /* Hack the size of the variable object, so invisible fields don't appear
+     to Python code. */
     Py_SIZE(obj) = VISIBLE_SIZE_TP(type);
+    for (i = 0; i < size; i++)
+        obj->ob_item[i] = NULL;
 
-    return (PyObject*) obj;
+    return (PyObject*)obj;
 }
 
 static void
 structseq_dealloc(PyStructSequence *obj)
 {
     Py_ssize_t i, size;
-
+    
     size = REAL_SIZE(obj);
     for (i = 0; i < size; ++i) {
         Py_XDECREF(obj->ob_item[i]);
     }
-    PyObject_Del(obj);
-}
-
-static Py_ssize_t
-structseq_length(PyStructSequence *obj)
-{
-    return VISIBLE_SIZE(obj);
-}
-
-static PyObject*
-structseq_item(PyStructSequence *obj, Py_ssize_t i)
-{
-    if (i < 0 || i >= VISIBLE_SIZE(obj)) {
-        PyErr_SetString(PyExc_IndexError, "tuple index out of range");
-        return NULL;
-    }
-    Py_INCREF(obj->ob_item[i]);
-    return obj->ob_item[i];
-}
-
-static PyObject*
-structseq_slice(PyStructSequence *obj, Py_ssize_t low, Py_ssize_t high)
-{
-    PyTupleObject *np;
-    Py_ssize_t i;
-
-    if (low < 0)
-        low = 0;
-    if (high > VISIBLE_SIZE(obj))
-        high = VISIBLE_SIZE(obj);
-    if (high < low)
-        high = low;
-    np = (PyTupleObject *)PyTuple_New(high-low);
-    if (np == NULL)
-        return NULL;
-    for(i = low; i < high; ++i) {
-        PyObject *v = obj->ob_item[i];
-        Py_INCREF(v);
-        PyTuple_SET_ITEM(np, i-low, v);
-    }
-    return (PyObject *) np;
-}
-
-static PyObject *
-structseq_subscript(PyStructSequence *self, PyObject *item)
-{
-    if (PyIndex_Check(item)) {
-        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-        if (i == -1 && PyErr_Occurred())
-            return NULL;
-
-        if (i < 0)
-            i += VISIBLE_SIZE(self);
-
-        if (i < 0 || i >= VISIBLE_SIZE(self)) {
-            PyErr_SetString(PyExc_IndexError,
-                "tuple index out of range");
-            return NULL;
-        }
-        Py_INCREF(self->ob_item[i]);
-        return self->ob_item[i];
-    }
-    else if (PySlice_Check(item)) {
-        Py_ssize_t start, stop, step, slicelen, cur, i;
-        PyObject *result;
-
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
-                                 VISIBLE_SIZE(self), &start, &stop,
-                                 &step, &slicelen) < 0) {
-            return NULL;
-        }
-        if (slicelen <= 0)
-            return PyTuple_New(0);
-        result = PyTuple_New(slicelen);
-        if (result == NULL)
-            return NULL;
-        for (cur = start, i = 0; i < slicelen;
-             cur += step, i++) {
-            PyObject *v = self->ob_item[cur];
-            Py_INCREF(v);
-            PyTuple_SET_ITEM(result, i, v);
-        }
-        return result;
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "structseq index must be integer");
-        return NULL;
-    }
+    PyObject_GC_Del(obj);
 }
 
 static PyObject *
@@ -223,11 +140,6 @@
     return (PyObject*) res;
 }
 
-static PyObject *
-make_tuple(PyStructSequence *obj)
-{
-    return structseq_slice(obj, 0, VISIBLE_SIZE(obj));
-}
 
 static PyObject *
 structseq_repr(PyStructSequence *obj)
@@ -236,7 +148,6 @@
 #define REPR_BUFFER_SIZE 512
 #define TYPE_MAXSIZE 100
 
-    PyObject *tup;
     PyTypeObject *typ = Py_TYPE(obj);
     int i, removelast = 0;
     Py_ssize_t len;
@@ -246,10 +157,6 @@
     /* pointer to end of writeable buffer; safes space for "...)\0" */
     endofbuf= &buf[REPR_BUFFER_SIZE-5];
 
-    if ((tup = make_tuple(obj)) == NULL) {
-        return NULL;
-    }
-
     /* "typename(", limited to  TYPE_MAXSIZE */
     len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE :
                             strlen(typ->tp_name);
@@ -262,19 +169,17 @@
         char *cname, *crepr;
 
         cname = typ->tp_members[i].name;
-
-        val = PyTuple_GetItem(tup, i);
-        if (cname == NULL || val == NULL) {
+        if (cname == NULL) {
+            PyErr_Format(PyExc_SystemError, "In structseq_repr(), member %d name is NULL"
+                         " for type %.500s", i, typ->tp_name);
             return NULL;
         }
+        val = PyStructSequence_GET_ITEM(obj, i);
         repr = PyObject_Repr(val);
-        if (repr == NULL) {
-            Py_DECREF(tup);
+        if (repr == NULL)
             return NULL;
-        }
         crepr = _PyUnicode_AsString(repr);
         if (crepr == NULL) {
-            Py_DECREF(tup);
             Py_DECREF(repr);
             return NULL;
         }
@@ -300,7 +205,6 @@
             break;
         }
     }
-    Py_DECREF(tup);
     if (removelast) {
         /* overwrite last ", " */
         pbuf-=2;
@@ -312,62 +216,6 @@
 }
 
 static PyObject *
-structseq_concat(PyStructSequence *obj, PyObject *b)
-{
-    PyObject *tup, *result;
-    tup = make_tuple(obj);
-    result = PySequence_Concat(tup, b);
-    Py_DECREF(tup);
-    return result;
-}
-
-static PyObject *
-structseq_repeat(PyStructSequence *obj, Py_ssize_t n)
-{
-    PyObject *tup, *result;
-    tup = make_tuple(obj);
-    result = PySequence_Repeat(tup, n);
-    Py_DECREF(tup);
-    return result;
-}
-
-static int
-structseq_contains(PyStructSequence *obj, PyObject *o)
-{
-    PyObject *tup;
-    int result;
-    tup = make_tuple(obj);
-    if (!tup)
-        return -1;
-    result = PySequence_Contains(tup, o);
-    Py_DECREF(tup);
-    return result;
-}
-
-static long
-structseq_hash(PyObject *obj)
-{
-    PyObject *tup;
-    long result;
-    tup = make_tuple((PyStructSequence*) obj);
-    if (!tup)
-        return -1;
-    result = PyObject_Hash(tup);
-    Py_DECREF(tup);
-    return result;
-}
-
-static PyObject *
-structseq_richcompare(PyObject *obj, PyObject *o2, int op)
-{
-    PyObject *tup, *result;
-    tup = make_tuple((PyStructSequence*) obj);
-    result = PyObject_RichCompare(tup, o2, op);
-    Py_DECREF(tup);
-    return result;
-}
-
-static PyObject *
 structseq_reduce(PyStructSequence* self)
 {
     PyObject* tup;
@@ -409,33 +257,16 @@
     return result;
 }
 
-static PySequenceMethods structseq_as_sequence = {
-    (lenfunc)structseq_length,
-    (binaryfunc)structseq_concat,           /* sq_concat */
-    (ssizeargfunc)structseq_repeat,         /* sq_repeat */
-    (ssizeargfunc)structseq_item,               /* sq_item */
-    0,                                          /* sq_slice */
-    0,                                          /* sq_ass_item */
-    0,                                          /* sq_ass_slice */
-    (objobjproc)structseq_contains,             /* sq_contains */
-};
-
-static PyMappingMethods structseq_as_mapping = {
-    (lenfunc)structseq_length,
-    (binaryfunc)structseq_subscript,
-};
-
 static PyMethodDef structseq_methods[] = {
-    {"__reduce__", (PyCFunction)structseq_reduce,
-     METH_NOARGS, NULL},
+    {"__reduce__", (PyCFunction)structseq_reduce, METH_NOARGS, NULL},
     {NULL, NULL}
 };
 
 static PyTypeObject _struct_sequence_template = {
     PyVarObject_HEAD_INIT(&PyType_Type, 0)
     NULL,                                       /* tp_name */
-    0,                                          /* tp_basicsize */
-    0,                                          /* tp_itemsize */
+    sizeof(PyStructSequence) - sizeof(PyObject *), /* tp_basicsize */
+    sizeof(PyObject *),                         /* tp_itemsize */
     (destructor)structseq_dealloc,              /* tp_dealloc */
     0,                                          /* tp_print */
     0,                                          /* tp_getattr */
@@ -443,19 +274,19 @@
     0,                                          /* tp_reserved */
     (reprfunc)structseq_repr,                   /* tp_repr */
     0,                                          /* tp_as_number */
-    &structseq_as_sequence,                     /* tp_as_sequence */
-    &structseq_as_mapping,                      /* tp_as_mapping */
-    structseq_hash,                             /* tp_hash */
+    0,                                          /* tp_as_sequence */
+    0,                                          /* tp_as_mapping */
+    0,                                          /* tp_hash */
     0,                                          /* tp_call */
     0,                                          /* tp_str */
     0,                                          /* tp_getattro */
     0,                                          /* tp_setattro */
     0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,                     /* tp_flags */
+    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
     NULL,                                       /* tp_doc */
     0,                                          /* tp_traverse */
     0,                                          /* tp_clear */
-    structseq_richcompare,                      /* tp_richcompare */
+    0,                                          /* tp_richcompare */
     0,                                          /* tp_weaklistoffset */
     0,                                          /* tp_iter */
     0,                                          /* tp_iternext */
@@ -494,11 +325,9 @@
     n_members = i;
 
     memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject));
+    type->tp_base = &PyTuple_Type;
     type->tp_name = desc->name;
     type->tp_doc = desc->doc;
-    type->tp_basicsize = sizeof(PyStructSequence)+
-        sizeof(PyObject*)*(n_members-1);
-    type->tp_itemsize = 0;
 
     members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1);
     if (members == NULL)

Modified: python/branches/py3k-dtoa/Objects/unicodeobject.c
==============================================================================
--- python/branches/py3k-dtoa/Objects/unicodeobject.c	(original)
+++ python/branches/py3k-dtoa/Objects/unicodeobject.c	Sun Aug  8 12:41:24 2010
@@ -307,8 +307,7 @@
   reset:
     /* Reset the object caches */
     if (unicode->defenc) {
-        Py_DECREF(unicode->defenc);
-        unicode->defenc = NULL;
+        Py_CLEAR(unicode->defenc);
     }
     unicode->hash = -1;
 
@@ -427,8 +426,7 @@
             unicode->length = 0;
         }
         if (unicode->defenc) {
-            Py_DECREF(unicode->defenc);
-            unicode->defenc = NULL;
+            Py_CLEAR(unicode->defenc);
         }
         /* Add to free list */
         *(PyUnicodeObject **)unicode = free_list;
@@ -9242,7 +9240,7 @@
                 else if (c >= '0' && c <= '9') {
                     prec = c - '0';
                     while (--fmtcnt >= 0) {
-                        c = Py_CHARMASK(*fmt++);
+                        c = *fmt++;
                         if (c < '0' || c > '9')
                             break;
                         if ((prec*10) / 10 != prec) {

Modified: python/branches/py3k-dtoa/PC/VS8.0/pythoncore.vcproj
==============================================================================
--- python/branches/py3k-dtoa/PC/VS8.0/pythoncore.vcproj	(original)
+++ python/branches/py3k-dtoa/PC/VS8.0/pythoncore.vcproj	Sun Aug  8 12:41:24 2010
@@ -879,6 +879,10 @@
 				>
 			</File>
 			<File
+                                RelativePath="..\..\Include\pytime.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\Include\pymem.h"
 				>
 			</File>
@@ -943,6 +947,10 @@
 				>
 			</File>
 			<File
+                                RelativePath="..\..\Include\_time.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\Include\timefuncs.h"
 				>
 			</File>
@@ -1091,7 +1099,7 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Modules\datetimemodule.c"
+				RelativePath="..\..\Modules\_datetimemodule.c"
 				>
 			</File>
 			<File
@@ -1167,6 +1175,10 @@
 				>
 			</File>
 			<File
+                                RelativePath="..\..\Modules\_time.c"
+				>
+			</File>
+			<File
 				RelativePath="..\..\Modules\timemodule.c"
 				>
 			</File>
@@ -1759,6 +1771,10 @@
 				>
 			</File>
 			<File
+                                RelativePath="..\..\Python\pytime.c"
+				>
+			</File>
+			<File
 				RelativePath="..\..\Python\pystate.c"
 				>
 			</File>

Modified: python/branches/py3k-dtoa/PC/_subprocess.c
==============================================================================
--- python/branches/py3k-dtoa/PC/_subprocess.c	(original)
+++ python/branches/py3k-dtoa/PC/_subprocess.c	Sun Aug  8 12:41:24 2010
@@ -429,6 +429,7 @@
     PyObject* env_mapping;
     Py_UNICODE* current_directory;
     PyObject* startup_info;
+    DWORD error;
 
     if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess",
                            &application_name,
@@ -478,8 +479,22 @@
 
     Py_XDECREF(environment);
 
-    if (! result)
-        return PyErr_SetFromWindowsErr(GetLastError());
+    if (! result) {
+        error = GetLastError();
+        if(si.hStdInput != INVALID_HANDLE_VALUE) {
+            CloseHandle(si.hStdInput);
+            si.hStdInput = INVALID_HANDLE_VALUE;
+        }
+        if(si.hStdOutput != INVALID_HANDLE_VALUE) {
+            CloseHandle(si.hStdOutput);
+            si.hStdOutput = INVALID_HANDLE_VALUE;
+        }
+        if(si.hStdError != INVALID_HANDLE_VALUE) {
+            CloseHandle(si.hStdError);
+            si.hStdError = INVALID_HANDLE_VALUE;
+        }
+        return PyErr_SetFromWindowsErr(error);
+    }
 
     return Py_BuildValue("NNii",
                          sp_handle_new(pi.hProcess),

Modified: python/branches/py3k-dtoa/PC/config.c
==============================================================================
--- python/branches/py3k-dtoa/PC/config.c	(original)
+++ python/branches/py3k-dtoa/PC/config.c	Sun Aug  8 12:41:24 2010
@@ -43,7 +43,7 @@
 extern PyObject* PyInit_parser(void);
 extern PyObject* PyInit_winreg(void);
 extern PyObject* PyInit__struct(void);
-extern PyObject* PyInit_datetime(void);
+extern PyObject* PyInit__datetime(void);
 extern PyObject* PyInit__functools(void);
 extern PyObject* PyInit__json(void);
 extern PyObject* PyInit_zlib(void);
@@ -116,7 +116,7 @@
     {"parser", PyInit_parser},
     {"winreg", PyInit_winreg},
     {"_struct", PyInit__struct},
-    {"datetime", PyInit_datetime},
+    {"_datetime", PyInit__datetime},
     {"_functools", PyInit__functools},
     {"_json", PyInit__json},
 

Modified: python/branches/py3k-dtoa/PC/python_nt.rc
==============================================================================
--- python/branches/py3k-dtoa/PC/python_nt.rc	(original)
+++ python/branches/py3k-dtoa/PC/python_nt.rc	Sun Aug  8 12:41:24 2010
@@ -61,7 +61,7 @@
             VALUE "FileDescription", "Python Core\0"
             VALUE "FileVersion", PYTHON_VERSION
             VALUE "InternalName", "Python DLL\0"
-            VALUE "LegalCopyright", "Copyright © 2001-2008 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
+            VALUE "LegalCopyright", "Copyright © 2001-2010 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

Modified: python/branches/py3k-dtoa/PCbuild/build_ssl.py
==============================================================================
--- python/branches/py3k-dtoa/PCbuild/build_ssl.py	(original)
+++ python/branches/py3k-dtoa/PCbuild/build_ssl.py	Sun Aug  8 12:41:24 2010
@@ -23,6 +23,7 @@
 # python.exe build_ssl.py Release x64
 # python.exe build_ssl.py Release Win32
 
+from __future__ import with_statement
 import os, sys, re, shutil
 
 # Find all "foo.exe" files on the PATH.
@@ -121,13 +122,10 @@
     """
     if not os.path.isfile(makefile):
         return
-    # 2.4 compatibility
     fin = open(makefile)
-    if 1: # with open(makefile) as fin:
+    with open(makefile) as fin:
         lines = fin.readlines()
-        fin.close()
-    fout = open(makefile, 'w')
-    if 1: # with open(makefile, 'w') as fout:
+    with open(makefile, 'w') as fout:
         for line in lines:
             if line.startswith("PERL="):
                 continue
@@ -143,11 +141,10 @@
                         line = line + noalgo
                 line = line + '\n'
             fout.write(line)
-    fout.close()
 
 def run_configure(configure, do_script):
-    print("perl Configure "+configure)
-    os.system("perl Configure "+configure)
+    print("perl Configure "+configure+" no-idea no-mdc2")
+    os.system("perl Configure "+configure+" no-idea no-mdc2")
     print(do_script)
     os.system(do_script)
 
@@ -166,12 +163,14 @@
         do_script = "ms\\do_nasm"
         makefile="ms\\nt.mak"
         m32 = makefile
+        dirsuffix = "32"
     elif sys.argv[2] == "x64":
         arch="amd64"
         configure = "VC-WIN64A"
         do_script = "ms\\do_win64a"
         makefile = "ms\\nt64.mak"
         m32 = makefile.replace('64', '')
+        dirsuffix = "64"
         #os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON"
     else:
         raise ValueError(str(sys.argv))
@@ -228,6 +227,13 @@
             shutil.copy(r"crypto\buildinf.h", r"crypto\buildinf_%s.h" % arch)
             shutil.copy(r"crypto\opensslconf.h", r"crypto\opensslconf_%s.h" % arch)
 
+        # If the assembler files don't exist in tmpXX, copy them there
+        if not os.path.exists("tmp"+dirsuffix):
+            os.mkdir("tmp"+dirsuffix)
+        for f in os.listdir("asm"+dirsuffix):
+            if not f.endswith(".asm"): continue
+            shutil.copy(r"asm%s\%s" % (dirsuffix, f), "tmp"+dirsuffix)
+
         # Now run make.
         if arch == "amd64":
             rc = os.system("ml64 -c -Foms\\uptable.obj ms\\uptable.asm")

Modified: python/branches/py3k-dtoa/PCbuild/pyproject.vsprops
==============================================================================
--- python/branches/py3k-dtoa/PCbuild/pyproject.vsprops	(original)
+++ python/branches/py3k-dtoa/PCbuild/pyproject.vsprops	Sun Aug  8 12:41:24 2010
@@ -58,7 +58,7 @@
 	/>
 	<UserMacro
 		Name="opensslDir"
-		Value="$(externalsDir)\openssl-0.9.8l"
+		Value="$(externalsDir)\openssl-1.0.0a"
 	/>
 	<UserMacro
 		Name="tcltkDir"

Modified: python/branches/py3k-dtoa/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/py3k-dtoa/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/py3k-dtoa/PCbuild/pythoncore.vcproj	Sun Aug  8 12:41:24 2010
@@ -876,6 +876,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\Include\pytime.h"
+				>
+			</File>
+			<File
 				RelativePath="..\Include\pymem.h"
 				>
 			</File>
@@ -1068,7 +1072,7 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\datetimemodule.c"
+				RelativePath="..\Modules\_datetimemodule.c"
 				>
 			</File>
 			<File
@@ -1768,6 +1772,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\Python\pytime.c"
+				>
+			</File>
+			<File
 				RelativePath="..\Python\pystate.c"
 				>
 			</File>

Modified: python/branches/py3k-dtoa/PCbuild/readme.txt
==============================================================================
--- python/branches/py3k-dtoa/PCbuild/readme.txt	(original)
+++ python/branches/py3k-dtoa/PCbuild/readme.txt	Sun Aug  8 12:41:24 2010
@@ -139,7 +139,7 @@
 
     Get the source code through
 
-    svn export http://svn.python.org/projects/external/openssl-0.9.8l
+    svn export http://svn.python.org/projects/external/openssl-1.0.0a
 
     ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for
     obtaining external sources then you don't need to manually get the source
@@ -152,6 +152,8 @@
     You must install the NASM assembler from
         http://nasm.sf.net
     for x86 builds.  Put nasmw.exe anywhere in your PATH.
+    Note: recent releases of nasm only have nasm.exe. Just rename it to 
+    nasmw.exe.
 
     You can also install ActivePerl from
         http://www.activestate.com/Products/ActivePerl/

Modified: python/branches/py3k-dtoa/Python/ceval.c
==============================================================================
--- python/branches/py3k-dtoa/Python/ceval.c	(original)
+++ python/branches/py3k-dtoa/Python/ceval.c	Sun Aug  8 12:41:24 2010
@@ -3464,7 +3464,8 @@
             return 1;
         }
         Py_DECREF(w);
-        PyErr_SetString(PyExc_ValueError, "too many values to unpack");
+        PyErr_Format(PyExc_ValueError, "too many values to unpack "
+                     "(expected %d)", argcnt);
         goto Error;
     }
 

Modified: python/branches/py3k-dtoa/Python/getargs.c
==============================================================================
--- python/branches/py3k-dtoa/Python/getargs.c	(original)
+++ python/branches/py3k-dtoa/Python/getargs.c	Sun Aug  8 12:41:24 2010
@@ -1246,13 +1246,15 @@
             PyErr_Clear();
             return converterr("read-write buffer", arg, msgbuf, bufsize);
         }
+        if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) {
+            PyBuffer_Release((Py_buffer*)p);
+            return converterr("contiguous buffer", arg, msgbuf, bufsize);
+        }
         if (addcleanup(p, freelist, cleanup_buffer)) {
             return converterr(
                 "(cleanup problem)",
                 arg, msgbuf, bufsize);
         }
-        if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C'))
-            return converterr("contiguous buffer", arg, msgbuf, bufsize);
         break;
     }
 
@@ -1274,41 +1276,26 @@
 
     *errmsg = NULL;
     *p = NULL;
-    if (pb == NULL ||
-        pb->bf_getbuffer == NULL ||
-        pb->bf_releasebuffer != NULL) {
-        *errmsg = "bytes or read-only buffer";
+    if (pb != NULL && pb->bf_releasebuffer != NULL) {
+        *errmsg = "read-only pinned buffer";
         return -1;
     }
 
-    if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) {
-        *errmsg = "bytes or single-segment read-only buffer";
+    if (getbuffer(arg, &view, errmsg) < 0)
         return -1;
-    }
     count = view.len;
     *p = view.buf;
     PyBuffer_Release(&view);
     return count;
 }
 
-/* XXX for 3.x, getbuffer and convertbuffer can probably
-   be merged again. */
 static int
 getbuffer(PyObject *arg, Py_buffer *view, char **errmsg)
 {
-    PyBufferProcs *pb = Py_TYPE(arg)->tp_as_buffer;
-    if (pb == NULL) {
+    if (PyObject_GetBuffer(arg, view, PyBUF_SIMPLE) != 0) {
         *errmsg = "bytes or buffer";
         return -1;
     }
-    if (pb->bf_getbuffer == NULL) {
-        *errmsg = "convertible to a buffer";
-        return -1;
-    }
-    if (PyObject_GetBuffer(arg, view, 0) < 0) {
-        *errmsg = "convertible to a buffer";
-        return -1;
-    }
     if (!PyBuffer_IsContiguous(view, 'C')) {
         PyBuffer_Release(view);
         *errmsg = "contiguous buffer";

Modified: python/branches/py3k-dtoa/Python/getcopyright.c
==============================================================================
--- python/branches/py3k-dtoa/Python/getcopyright.c	(original)
+++ python/branches/py3k-dtoa/Python/getcopyright.c	Sun Aug  8 12:41:24 2010
@@ -2,7 +2,7 @@
 
 #include "Python.h"
 
-static char cprt[] = 
+static char cprt[] =
 "\
 Copyright (c) 2001-2010 Python Software Foundation.\n\
 All Rights Reserved.\n\

Modified: python/branches/py3k-dtoa/Python/getversion.c
==============================================================================
--- python/branches/py3k-dtoa/Python/getversion.c	(original)
+++ python/branches/py3k-dtoa/Python/getversion.c	Sun Aug  8 12:41:24 2010
@@ -9,7 +9,7 @@
 Py_GetVersion(void)
 {
 	static char version[250];
-	PyOS_snprintf(version, sizeof(version), "%.80s (%.80s) %.80s", 
+	PyOS_snprintf(version, sizeof(version), "%.80s (%.80s) %.80s",
 		      PY_VERSION, Py_GetBuildInfo(), Py_GetCompiler());
 	return version;
 }

Modified: python/branches/py3k-dtoa/Python/graminit.c
==============================================================================
--- python/branches/py3k-dtoa/Python/graminit.c	(original)
+++ python/branches/py3k-dtoa/Python/graminit.c	Sun Aug  8 12:41:24 2010
@@ -180,8 +180,8 @@
     {24, 9},
 };
 static arc arcs_8_5[4] = {
-    {28, 1},
-    {31, 2},
+    {28, 10},
+    {31, 11},
     {32, 3},
     {0, 5},
 };
@@ -190,7 +190,7 @@
     {0, 6},
 };
 static arc arcs_8_7[2] = {
-    {28, 10},
+    {28, 12},
     {32, 3},
 };
 static arc arcs_8_8[1] = {
@@ -201,14 +201,40 @@
     {0, 9},
 };
 static arc arcs_8_10[3] = {
-    {30, 7},
-    {29, 11},
+    {30, 5},
+    {29, 4},
     {0, 10},
 };
-static arc arcs_8_11[1] = {
+static arc arcs_8_11[3] = {
+    {28, 13},
+    {30, 14},
+    {0, 11},
+};
+static arc arcs_8_12[3] = {
+    {30, 7},
+    {29, 15},
+    {0, 12},
+};
+static arc arcs_8_13[2] = {
+    {30, 14},
+    {0, 13},
+};
+static arc arcs_8_14[2] = {
+    {28, 16},
+    {32, 3},
+};
+static arc arcs_8_15[1] = {
     {24, 6},
 };
-static state states_8[12] = {
+static arc arcs_8_16[3] = {
+    {30, 14},
+    {29, 17},
+    {0, 16},
+};
+static arc arcs_8_17[1] = {
+    {24, 13},
+};
+static state states_8[18] = {
     {3, arcs_8_0},
     {3, arcs_8_1},
     {3, arcs_8_2},
@@ -220,7 +246,13 @@
     {1, arcs_8_8},
     {2, arcs_8_9},
     {3, arcs_8_10},
-    {1, arcs_8_11},
+    {3, arcs_8_11},
+    {3, arcs_8_12},
+    {2, arcs_8_13},
+    {2, arcs_8_14},
+    {1, arcs_8_15},
+    {3, arcs_8_16},
+    {1, arcs_8_17},
 };
 static arc arcs_9_0[1] = {
     {21, 1},
@@ -263,8 +295,8 @@
     {24, 9},
 };
 static arc arcs_10_5[4] = {
-    {34, 1},
-    {31, 2},
+    {34, 10},
+    {31, 11},
     {32, 3},
     {0, 5},
 };
@@ -273,7 +305,7 @@
     {0, 6},
 };
 static arc arcs_10_7[2] = {
-    {34, 10},
+    {34, 12},
     {32, 3},
 };
 static arc arcs_10_8[1] = {
@@ -284,14 +316,40 @@
     {0, 9},
 };
 static arc arcs_10_10[3] = {
-    {30, 7},
-    {29, 11},
+    {30, 5},
+    {29, 4},
     {0, 10},
 };
-static arc arcs_10_11[1] = {
+static arc arcs_10_11[3] = {
+    {34, 13},
+    {30, 14},
+    {0, 11},
+};
+static arc arcs_10_12[3] = {
+    {30, 7},
+    {29, 15},
+    {0, 12},
+};
+static arc arcs_10_13[2] = {
+    {30, 14},
+    {0, 13},
+};
+static arc arcs_10_14[2] = {
+    {34, 16},
+    {32, 3},
+};
+static arc arcs_10_15[1] = {
     {24, 6},
 };
-static state states_10[12] = {
+static arc arcs_10_16[3] = {
+    {30, 14},
+    {29, 17},
+    {0, 16},
+};
+static arc arcs_10_17[1] = {
+    {24, 13},
+};
+static state states_10[18] = {
     {3, arcs_10_0},
     {3, arcs_10_1},
     {3, arcs_10_2},
@@ -303,7 +361,13 @@
     {1, arcs_10_8},
     {2, arcs_10_9},
     {3, arcs_10_10},
-    {1, arcs_10_11},
+    {3, arcs_10_11},
+    {3, arcs_10_12},
+    {2, arcs_10_13},
+    {2, arcs_10_14},
+    {1, arcs_10_15},
+    {3, arcs_10_16},
+    {1, arcs_10_17},
 };
 static arc arcs_11_0[1] = {
     {21, 1},
@@ -1755,11 +1819,11 @@
      "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
     {263, "parameters", 0, 4, states_7,
      "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-    {264, "typedargslist", 0, 12, states_8,
+    {264, "typedargslist", 0, 18, states_8,
      "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
     {265, "tfpdef", 0, 4, states_9,
      "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-    {266, "varargslist", 0, 12, states_10,
+    {266, "varargslist", 0, 18, states_10,
      "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
     {267, "vfpdef", 0, 2, states_11,
      "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},

Modified: python/branches/py3k-dtoa/Python/pythonrun.c
==============================================================================
--- python/branches/py3k-dtoa/Python/pythonrun.c	(original)
+++ python/branches/py3k-dtoa/Python/pythonrun.c	Sun Aug  8 12:41:24 2010
@@ -268,6 +268,8 @@
     /* Initialize _warnings. */
     _PyWarnings_Init();
 
+    _PyTime_Init();
+
     initfsencoding();
 
     if (install_sigs)

Modified: python/branches/py3k-dtoa/README
==============================================================================
--- python/branches/py3k-dtoa/README	(original)
+++ python/branches/py3k-dtoa/README	Sun Aug  8 12:41:24 2010
@@ -1,15 +1,14 @@
-This is Python version 3.2
-==========================
+This is Python version 3.2 alpha 1
+==================================
 
 Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
 Python Software Foundation.
 All rights reserved.
 
-Python 3.x is a new version of the language, which is incompatible with the
-2.x line of releases.  The language is mostly the same, but many details,
-especially how built-in objects like dictionaries and strings work, have
-changed considerably, and a lot of deprecated features have finally been
-removed.
+Python 3.x is a new version of the language, which is incompatible with the 2.x
+line of releases.  The language is mostly the same, but many details, especially
+how built-in objects like dictionaries and strings work, have changed
+considerably, and a lot of deprecated features have finally been removed.
 
 
 Build Instructions
@@ -24,20 +23,19 @@
 
 This will install Python as python3.
 
-You can pass many options to the configure script; run "./configure
---help" to find out more.  On OSX and Cygwin, the executable is called
-python.exe; elsewhere it's just python.
-
-On Mac OS X, if you have configured Python with --enable-framework,
-you should use "make frameworkinstall" to do the installation.  Note
-that this installs the Python executable in a place that is not
-normally on your PATH, you may want to set up a symlink in
-/usr/local/bin.
+You can pass many options to the configure script; run "./configure --help" to
+find out more.  On OSX and Cygwin, the executable is called python.exe;
+elsewhere it's just python.
+
+On Mac OS X, if you have configured Python with --enable-framework, you should
+use "make frameworkinstall" to do the installation.  Note that this installs the
+Python executable in a place that is not normally on your PATH, you may want to
+set up a symlink in /usr/local/bin.
 
 On Windows, see PCbuild/readme.txt.
 
-If you wish, you can create a subdirectory and invoke configure from
-there.  For example:
+If you wish, you can create a subdirectory and invoke configure from there.  For
+example:
 
     mkdir debug
     cd debug
@@ -45,21 +43,21 @@
     make
     make test
 
-(This will fail if you *also* built at the top-level directory.  You
-should do a "make clean" at the toplevel first.)
+(This will fail if you *also* built at the top-level directory.  You should do a
+"make clean" at the toplevel first.)
 
 
 What's New
 ----------
 
 We try to have a comprehensive overview of the changes in the "What's New in
-Python 3.1" document, found at
+Python 3.2" document, found at
 
-    http://docs.python.org/dev/3.1/whatsnew/3.1.html
+    http://docs.python.org/3.2/whatsnew/3.2.html
 
-For a more detailed change log, read Misc/NEWS (though this file, too,
-is incomplete, and also doesn't list anything merged in from the 2.7
-release under development).
+For a more detailed change log, read Misc/NEWS (though this file, too, is
+incomplete, and also doesn't list anything merged in from the 2.7 release under
+development).
 
 If you want to install multiple versions of Python see the section below
 entitled "Installing multiple versions".
@@ -68,89 +66,84 @@
 Documentation
 -------------
 
-Documentation for Python 3.1 is online, updated twice a day:
+Documentation for Python 3.2 is online, updated daily:
 
-    http://docs.python.org/dev/3.1/
+    http://docs.python.org/3.2/
 
-All documentation is also available online at the Python web site
-(http://docs.python.org/, see below).  It is available online for
-occasional reference, or can be downloaded in many formats for faster
-access.  The documentation is downloadable in HTML, PostScript, PDF,
-LaTeX (through 2.5), and reStructuredText (2.6+) formats; the LaTeX and
-reStructuredText versions are primarily for documentation authors,
-translators, and people with special formatting requirements.
+It can also be downloaded in many formats for faster access.  The documentation
+is downloadable in HTML, PDF, and reStructuredText formats; the latter version
+is primarily for documentation authors, translators, and people with special
+formatting requirements.
 
 
 Converting From Python 2.x to 3.x
 ---------------------------------
 
-Python starting with 2.6 will contain features to help locating code that
-needs to be changed, such as optional warnings when deprecated features are
-used, and backported versions of certain key Python 3.x features.
+Python starting with 2.6 contains features to help locating code that needs to
+be changed, such as optional warnings when deprecated features are used, and
+backported versions of certain key Python 3.x features.
 
 A source-to-source translation tool, "2to3", can take care of the mundane task
 of converting large amounts of source code.  It is not a complete solution but
 is complemented by the deprecation warnings in 2.6.  See
-http://docs.python.org/dev/py3k/library/2to3.html for more information.
+http://docs.python.org/3.2/library/2to3.html for more information.
 
 
 Testing
 -------
 
-To test the interpreter, type "make test" in the top-level directory.
-This runs the test set twice (once with no compiled files, once with
-the compiled files left by the previous test run).  The test set
-produces some output.  You can generally ignore the messages about
-skipped tests due to optional features which can't be imported.
-If a message is printed about a failed test or a traceback or core
-dump is produced, something is wrong.  On some Linux systems (those
-that are not yet using glibc 6), test_strftime fails due to a
-non-standard implementation of strftime() in the C library. Please
-ignore this, or upgrade to glibc version 6.
+To test the interpreter, type "make test" in the top-level directory.  This runs
+the test set twice (once with no compiled files, once with the compiled files
+left by the previous test run).  The test set produces some output.  You can
+generally ignore the messages about skipped tests due to optional features which
+can't be imported.  If a message is printed about a failed test or a traceback
+or core dump is produced, something is wrong.  On some Linux systems (those that
+are not yet using glibc 6), test_strftime fails due to a non-standard
+implementation of strftime() in the C library. Please ignore this, or upgrade to
+glibc version 6.
 
 By default, tests are prevented from overusing resources like disk space and
 memory.  To enable these tests, run "make testall".
 
-IMPORTANT: If the tests fail and you decide to mail a bug report,
-*don't* include the output of "make test".  It is useless.  Run the
-failing test manually, as follows:
+IMPORTANT: If the tests fail and you decide to mail a bug report, *don't*
+include the output of "make test".  It is useless.  Run the failing test
+manually, as follows:
 
         ./python Lib/test/regrtest.py -v test_whatever
 
-(substituting the top of the source tree for '.' if you built in a
-different directory).  This runs the test in verbose mode.
+(substituting the top of the source tree for '.' if you built in a different
+directory).  This runs the test in verbose mode.
 
 
 Installing multiple versions
 ----------------------------
 
 On Unix and Mac systems if you intend to install multiple versions of Python
-using the same installation prefix (--prefix argument to the configure
-script) you must take care that your primary python executable is not
-overwritten by the installation of a different version.  All files and
-directories installed using "make altinstall" contain the major and minor
-version and can thus live side-by-side.  "make install" also creates
-${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y.  If you intend
-to install multiple versions using the same prefix you must decide which
-version (if any) is your "primary" version.  Install that version using
-"make install".  Install all other versions using "make altinstall".
-
-For example, if you want to install Python 2.5, 2.6 and 3.0 with 2.6 being
-the primary version, you would execute "make install" in your 2.6 build
-directory and "make altinstall" in the others.
+using the same installation prefix (--prefix argument to the configure script)
+you must take care that your primary python executable is not overwritten by the
+installation of a different version.  All files and directories installed using
+"make altinstall" contain the major and minor version and can thus live
+side-by-side.  "make install" also creates ${prefix}/bin/python3 which refers to
+${prefix}/bin/pythonX.Y.  If you intend to install multiple versions using the
+same prefix you must decide which version (if any) is your "primary" version.
+Install that version using "make install".  Install all other versions using
+"make altinstall".
+
+For example, if you want to install Python 2.5, 2.6 and 3.2 with 2.6 being the
+primary version, you would execute "make install" in your 2.6 build directory
+and "make altinstall" in the others.
 
 
 Issue Tracker and Mailing List
 ------------------------------
 
-We're soliciting bug reports about all aspects of the language.  Fixes
-are also welcome, preferable in unified diff format.  Please use the
-issue tracker:
+We're soliciting bug reports about all aspects of the language.  Fixes are also
+welcome, preferable in unified diff format.  Please use the issue tracker:
 
     http://bugs.python.org/
 
-If you're not sure whether you're dealing with a bug or a feature, use
-the mailing list:
+If you're not sure whether you're dealing with a bug or a feature, use the
+mailing list:
 
     python-dev at python.org
 

Modified: python/branches/py3k-dtoa/Tools/README
==============================================================================
--- python/branches/py3k-dtoa/Tools/README	(original)
+++ python/branches/py3k-dtoa/Tools/README	Sun Aug  8 12:41:24 2010
@@ -1,31 +1,40 @@
 This directory contains a number of Python programs that are useful
 while building or extending Python.
 
-faqwiz		FAQ Wizard: a CGI script for a user-editable FAQ.
+buildbot        Batchfiles for running on Windows buildslaves.
 
-freeze		Create a stand-alone executable from a Python program.
+ccbench         A Python concurrency benchmark.
+
+framer          Generate boilerplate code for C extension types.
+
+freeze          Create a stand-alone executable from a Python program.
 
 gdb             Python code to be run inside gdb, to make it easier to
                 debug Python itself (by David Malcolm).
 
-i18n		Tools for internationalization. pygettext.py 
-		parses Python source code and generates .pot files,
-		and msgfmt.py generates a binary message catalog 
-		from a catalog in text format.
-
-pynche		A Tkinter-based color editor.
-
-scripts		A number of useful single-file programs, e.g. tabnanny.py
-		(by Tim Peters), which checks for inconsistent mixing
-		of tabs and spaces.
-
-unicode		Tools used to generate unicode database files for
-		Python 2.0 (by Fredrik Lundh).
-
-versioncheck	A tool to automate checking whether you have the latest
-		version of a package (by Jack Jansen).
-
-world		Script to take a list of Internet addresses and print
-		out where in the world those addresses originate from,
-		based on the top-level domain country code found in
-		the address. 
+i18n            Tools for internationalization. pygettext.py
+                parses Python source code and generates .pot files,
+                and msgfmt.py generates a binary message catalog
+                from a catalog in text format.
+
+iobench         Benchmark for the new Python I/O system.
+
+msi             Support for packaging Python as an MSI package on Windows.
+
+pybench         Comprehensive Python benchmarking suite.
+
+pynche          A Tkinter-based color editor.
+
+scripts         A number of useful single-file programs, e.g. tabnanny.py
+                (by Tim Peters), which checks for inconsistent mixing
+                of tabs and spaces.
+
+ssl             Currently, a tool to fetch server certificates.
+
+unicode         Tools used to generate unicode database files for
+                Python 2.0 (by Fredrik Lundh).
+
+world           Script to take a list of Internet addresses and print
+                out where in the world those addresses originate from,
+                based on the top-level domain country code found in
+                the address.

Modified: python/branches/py3k-dtoa/Tools/buildbot/external-common.bat
==============================================================================
--- python/branches/py3k-dtoa/Tools/buildbot/external-common.bat	(original)
+++ python/branches/py3k-dtoa/Tools/buildbot/external-common.bat	Sun Aug  8 12:41:24 2010
@@ -14,7 +14,8 @@
 @rem if exist tk8.4.16 rd /s/q tk8.4.16
 @rem if exist tk-8.4.18.1 rd /s/q tk-8.4.18.1
 @rem if exist db-4.4.20 rd /s/q db-4.4.20
- at rem if exist openssl-0.9.8l rd /s/q openssl-0.9.8l
+if exist openssl-0.9.8l rd /s/q openssl-0.9.8l
+if exist openssl-1.0.0a rd /s/q openssl-1.0.0a
 @rem if exist sqlite-3.6.21 rd /s/q sqlite-3.6.21    
 
 @rem bzip
@@ -27,7 +28,7 @@
 if not exist db-4.4.20 svn export http://svn.python.org/projects/external/db-4.4.20-vs9 db-4.4.20
 
 @rem OpenSSL
-if not exist openssl-0.9.8l svn export http://svn.python.org/projects/external/openssl-0.9.8l
+if not exist openssl-1.0.0a svn export http://svn.python.org/projects/external/openssl-1.0.0a
 
 @rem tcl/tk
 if not exist tcl-8.5.2.1 (

Modified: python/branches/py3k-dtoa/Tools/framer/framer/bases.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/framer/framer/bases.py	(original)
+++ python/branches/py3k-dtoa/Tools/framer/framer/bases.py	Sun Aug  8 12:41:24 2010
@@ -199,7 +199,7 @@
         p(template.type_struct_start)
         for s in Slots[:-5]: # XXX
             val = self.__slots.get(s, s.default)
-            ntabs = 4 - (4 + len(val)) / 8
+            ntabs = 4 - (4 + len(val)) // 8
             line = "        %s,%s/* %s */" % (val, "\t" * ntabs, s.name)
             print(line, file=f)
         p(template.type_struct_end)

Modified: python/branches/py3k-dtoa/Tools/framer/framer/template.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/framer/framer/template.py	(original)
+++ python/branches/py3k-dtoa/Tools/framer/framer/template.py	Sun Aug  8 12:41:24 2010
@@ -76,7 +76,7 @@
 
 module_init_start = """\
 PyMODINIT_FUNC
-init%(ModuleName)s(void)
+PyInit_%(ModuleName)s(void)
 {
         PyObject *mod;
 

Modified: python/branches/py3k-dtoa/Tools/freeze/freeze.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/freeze/freeze.py	(original)
+++ python/branches/py3k-dtoa/Tools/freeze/freeze.py	Sun Aug  8 12:41:24 2010
@@ -201,7 +201,7 @@
 
     # modules that are imported by the Python runtime
     implicits = []
-    for module in ('site', 'warnings',):
+    for module in ('site', 'warnings', 'encodings.utf_8', 'encodings.latin_1'):
         if module not in exclude:
             implicits.append(module)
 

Modified: python/branches/py3k-dtoa/Tools/freeze/makeconfig.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/freeze/makeconfig.py	(original)
+++ python/branches/py3k-dtoa/Tools/freeze/makeconfig.py	Sun Aug  8 12:41:24 2010
@@ -3,14 +3,13 @@
 
 # Write the config.c file
 
-never = ['marshal', '__main__', 'builtins', 'sys', 'exceptions', '_warnings']
+never = ['marshal', 'imp', '_ast', '__main__', 'builtins',
+         'sys', 'gc', '_warnings']
 
 def makeconfig(infp, outfp, modules, with_ifdef=0):
     m1 = re.compile('-- ADDMODULE MARKER 1 --')
     m2 = re.compile('-- ADDMODULE MARKER 2 --')
-    while 1:
-        line = infp.readline()
-        if not line: break
+    for line in infp:
         outfp.write(line)
         if m1 and m1.search(line):
             m1 = None
@@ -18,8 +17,8 @@
                 if mod in never:
                     continue
                 if with_ifdef:
-                    outfp.write("#ifndef init%s\n"%mod)
-                outfp.write('extern void init%s(void);\n' % mod)
+                    outfp.write("#ifndef PyInit_%s\n"%mod)
+                outfp.write('extern PyObject* PyInit_%s(void);\n' % mod)
                 if with_ifdef:
                     outfp.write("#endif\n")
         elif m2 and m2.search(line):
@@ -27,7 +26,7 @@
             for mod in modules:
                 if mod in never:
                     continue
-                outfp.write('\t{"%s", init%s},\n' %
+                outfp.write('\t{"%s", PyInit_%s},\n' %
                             (mod, mod))
     if m1:
         sys.stderr.write('MARKER 1 never found\n')

Modified: python/branches/py3k-dtoa/Tools/gdb/libpython.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/gdb/libpython.py	(original)
+++ python/branches/py3k-dtoa/Tools/gdb/libpython.py	Sun Aug  8 12:41:24 2010
@@ -43,6 +43,7 @@
 from __future__ import with_statement
 import gdb
 import locale
+import sys
 
 # Look up the gdb.Type for some standard types:
 _type_char_ptr = gdb.lookup_type('char').pointer() # char*
@@ -55,7 +56,6 @@
 
 Py_TPFLAGS_HEAPTYPE = (1L << 9)
 
-Py_TPFLAGS_INT_SUBCLASS      = (1L << 23)
 Py_TPFLAGS_LONG_SUBCLASS     = (1L << 24)
 Py_TPFLAGS_LIST_SUBCLASS     = (1L << 25)
 Py_TPFLAGS_TUPLE_SUBCLASS    = (1L << 26)
@@ -312,8 +312,6 @@
         if tp_flags & Py_TPFLAGS_HEAPTYPE:
             return HeapTypeObjectPtr
 
-        if tp_flags & Py_TPFLAGS_INT_SUBCLASS:
-            return PyIntObjectPtr
         if tp_flags & Py_TPFLAGS_LONG_SUBCLASS:
             return PyLongObjectPtr
         if tp_flags & Py_TPFLAGS_LIST_SUBCLASS:

Modified: python/branches/py3k-dtoa/Tools/i18n/msgfmt.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/i18n/msgfmt.py	(original)
+++ python/branches/py3k-dtoa/Tools/i18n/msgfmt.py	Sun Aug  8 12:41:24 2010
@@ -165,7 +165,7 @@
             section = STR
             if l.startswith('msgstr['):
                 if not is_plural:
-                    print(sys.stderr, 'plural without msgid_plural on %s:%d' % (infile, lno),
+                    print('plural without msgid_plural on %s:%d' % (infile, lno),
                           file=sys.stderr)
                     sys.exit(1)
                 l = l.split(']', 1)[1]
@@ -173,7 +173,7 @@
                     msgstr += b'\0' # Separator of the various plural forms
             else:
                 if is_plural:
-                    print(sys.stderr, 'indexed msgstr required for plural on  %s:%d' % (infile, lno),
+                    print('indexed msgstr required for plural on  %s:%d' % (infile, lno),
                           file=sys.stderr)
                     sys.exit(1)
                 l = l[6:]

Modified: python/branches/py3k-dtoa/Tools/msi/msi.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/msi/msi.py	(original)
+++ python/branches/py3k-dtoa/Tools/msi/msi.py	Sun Aug  8 12:41:24 2010
@@ -879,7 +879,6 @@
     shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out)
     shutil.copyfileobj(open("crtlicense.txt"), out)
     for name, pat, file in (("bzip2","bzip2-*", "LICENSE"),
-                      ("Berkeley DB", "db-*", "LICENSE"),
                       ("openssl", "openssl-*", "LICENSE"),
                       ("Tcl", "tcl8*", "license.terms"),
                       ("Tk", "tk8*", "license.terms"),
@@ -903,6 +902,13 @@
             kw['componentflags'] = 2 #msidbComponentAttributesOptional
         Directory.__init__(self, *args, **kw)
 
+    def check_unpackaged(self):
+        self.unpackaged_files.discard('__pycache__')
+        self.unpackaged_files.discard('.svn')
+        if self.unpackaged_files:
+            print "Warning: Unpackaged files in %s" % self.absolute
+            print self.unpackaged_files
+
 # See "File Table", "Component Table", "Directory Table",
 # "FeatureComponents Table"
 def add_files(db):
@@ -966,13 +972,13 @@
         extensions.remove("_ctypes.pyd")
 
     # Add all .py files in Lib, except tkinter, test
-    dirs={}
+    dirs = []
     pydirs = [(root,"Lib")]
     while pydirs:
         # Commit every now and then, or else installer will complain
         db.Commit()
         parent, dir = pydirs.pop()
-        if dir == ".svn" or dir.startswith("plat-"):
+        if dir == ".svn" or dir == '__pycache__' or dir.startswith("plat-"):
             continue
         elif dir in ["tkinter", "idlelib", "Icons"]:
             if not have_tcl:
@@ -990,7 +996,7 @@
             default_feature.set_current()
         lib = PyDirectory(db, cab, parent, dir, dir, "%s|%s" % (parent.make_short(dir), dir))
         # Add additional files
-        dirs[dir]=lib
+        dirs.append(lib)
         lib.glob("*.txt")
         if dir=='site-packages':
             lib.add_file("README.txt", src="README")
@@ -1000,16 +1006,13 @@
         if files:
             # Add an entry to the RemoveFile table to remove bytecode files.
             lib.remove_pyc()
-        if dir.endswith('.egg-info'):
-            lib.add_file('entry_points.txt')
-            lib.add_file('PKG-INFO')
-            lib.add_file('top_level.txt')
-            lib.add_file('zip-safe')
-            continue
+        # package READMEs if present
+        lib.glob("README")
+        if dir=='Lib':
+            lib.add_file('wsgiref.egg-info')
         if dir=='test' and parent.physical=='Lib':
             lib.add_file("185test.db")
             lib.add_file("audiotest.au")
-            lib.add_file("cfgparser.1")
             lib.add_file("sgml_input.html")
             lib.add_file("testtar.tar")
             lib.add_file("test_difflib_expect.html")
@@ -1019,7 +1022,12 @@
             lib.glob("*.uue")
             lib.glob("*.pem")
             lib.glob("*.pck")
+            lib.glob("cfgparser.*")
             lib.add_file("zipdir.zip")
+        if dir=='capath':
+            lib.glob("*.0")
+        if dir=='tests' and parent.physical=='distutils':
+            lib.add_file("Setup.sample")
         if dir=='decimaltestdata':
             lib.glob("*.decTest")
         if dir=='xmltestdata':
@@ -1027,19 +1035,26 @@
             lib.add_file("test.xml.out")
         if dir=='output':
             lib.glob("test_*")
+        if dir=='sndhdrdata':
+            lib.glob("sndhdr.*")
         if dir=='idlelib':
             lib.glob("*.def")
             lib.add_file("idle.bat")
+            lib.add_file("ChangeLog")
         if dir=="Icons":
             lib.glob("*.gif")
             lib.add_file("idle.icns")
         if dir=="command" and parent.physical=="distutils":
             lib.glob("wininst*.exe")
+            lib.add_file("command_template")
         if dir=="setuptools":
             lib.add_file("cli.exe")
             lib.add_file("gui.exe")
         if dir=="lib2to3":
             lib.removefile("pickle", "*.pickle")
+        if dir=="macholib":
+            lib.add_file("README.ctypes")
+            lib.glob("fetch_macholib*")
         if dir=="data" and parent.physical=="test" and parent.basedir.physical=="email":
             # This should contain all non-.svn files listed in subversion
             for f in os.listdir(lib.absolute):
@@ -1051,6 +1066,8 @@
         for f in os.listdir(lib.absolute):
             if os.path.isdir(os.path.join(lib.absolute, f)):
                 pydirs.append((lib, f))
+    for d in dirs:
+        d.check_unpackaged()
     # Add DLLs
     default_feature.set_current()
     lib = DLLs
@@ -1122,7 +1139,7 @@
     # Add tools
     tools.set_current()
     tooldir = PyDirectory(db, cab, root, "Tools", "Tools", "TOOLS|Tools")
-    for f in ['i18n', 'pynche', 'Scripts', 'versioncheck', 'webchecker']:
+    for f in ['i18n', 'pynche', 'Scripts', 'versioncheck']:
         lib = PyDirectory(db, cab, tooldir, f, f, "%s|%s" % (tooldir.make_short(f), f))
         lib.glob("*.py")
         lib.glob("*.pyw", exclude=['pydocgui.pyw'])

Modified: python/branches/py3k-dtoa/Tools/msi/msilib.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/msi/msilib.py	(original)
+++ python/branches/py3k-dtoa/Tools/msi/msilib.py	Sun Aug  8 12:41:24 2010
@@ -451,6 +451,12 @@
         else:
             self.absolute = physical
             blogical = None
+        # initially assume that all files in this directory are unpackaged
+        # as files from self.absolute get added, this set is reduced
+        self.unpackaged_files = set()
+        for f in os.listdir(self.absolute):
+            if os.path.isfile(os.path.join(self.absolute, f)):
+                self.unpackaged_files.add(f)
         add_data(db, "Directory", [(logical, blogical, default)])
 
     def start_component(self, component = None, feature = None, flags = None, keyfile = None, uuid=None):
@@ -527,6 +533,11 @@
             src = file
             file = os.path.basename(file)
         absolute = os.path.join(self.absolute, src)
+        if absolute.startswith(self.absolute):
+            # mark file as packaged
+            relative = absolute[len(self.absolute)+1:]
+            if relative in self.unpackaged_files:
+                self.unpackaged_files.remove(relative)
         assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names
         if self.keyfiles.has_key(file):
             logical = self.keyfiles[file]
@@ -572,10 +583,17 @@
         return files
 
     def remove_pyc(self):
-        "Remove .pyc/.pyo files on uninstall"
+        "Remove .pyc/.pyo files from __pycache__ on uninstall"
+        directory = self.logical + "_pycache"
+        add_data(self.db, "Directory", [(directory, self.logical, "__PYCA~1|__pycache__")])
+        flags = 256 if Win64 else 0
+        add_data(self.db, "Component",
+                [(directory, gen_uuid(), directory, flags, None, None)])
+        add_data(self.db, "FeatureComponents", [(current_feature.id, directory)])
+        add_data(self.db, "CreateFolder", [(directory, directory)])
         add_data(self.db, "RemoveFile",
-                 [(self.component+"c", self.component, "*.pyc", self.logical, 2),
-                  (self.component+"o", self.component, "*.pyo", self.logical, 2)])
+                 [(self.component, self.component, "*.*", directory, 2),
+                 ])
 
     def removefile(self, key, pattern):
         "Add a RemoveFile entry"

Modified: python/branches/py3k-dtoa/Tools/msi/uuids.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/msi/uuids.py	(original)
+++ python/branches/py3k-dtoa/Tools/msi/uuids.py	Sun Aug  8 12:41:24 2010
@@ -77,4 +77,12 @@
     '3.1.1150':'{7ff90460-89b7-435b-b583-b37b2815ccc7}', # 3.1.1
     '3.1.2121':'{ec45624a-378c-43be-91f3-3f7a59b0d90c}', # 3.1.2c1
     '3.1.2150':'{d40af016-506c-43fb-a738-bd54fa8c1e85}', # 3.1.2
+    '3.2.101' :'{b411f168-7a36-4fff-902c-a554d1c78a4f}', # 3.2a1
+    '3.2.102' :'{79ff73b7-8359-410f-b9c5-152d2026f8c8}', # 3.2a2
+    '3.2.103' :'{e7635c65-c221-4b9b-b70a-5611b8369d77}', # 3.2a3
+    '3.2.111' :'{20bfc16f-c7cd-4fc0-8f96-9914614a3c50}', # 3.2b1
+    '3.2.112' :'{0e350c98-8d73-4993-b686-cfe87160046e}', # 3.2b2
+    '3.2.121' :'{2094968d-7583-47f6-a7fd-22304532e09f}', # 3.2rc1
+    '3.2.122' :'{4f3edfa6-cf70-469a-825f-e1206aa7f412}', # 3.2rc2
+    '3.2.150' :'{b2042d5e-986d-44ec-aee3-afe4108ccc93}', # 3.2.0
 }

Modified: python/branches/py3k-dtoa/Tools/pynche/ChipViewer.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/ChipViewer.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/ChipViewer.py	Sun Aug  8 12:41:24 2010
@@ -13,7 +13,7 @@
 selected and nearest ChipWidgets.
 """
 
-from Tkinter import *
+from tkinter import *
 import ColorDB
 
 

Modified: python/branches/py3k-dtoa/Tools/pynche/DetailsViewer.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/DetailsViewer.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/DetailsViewer.py	Sun Aug  8 12:41:24 2010
@@ -52,7 +52,7 @@
 Shift + Right == +25
 """
 
-from Tkinter import *
+from tkinter import *
 
 STOP = 'Stop'
 WRAP = 'Wrap Around'

Modified: python/branches/py3k-dtoa/Tools/pynche/ListViewer.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/ListViewer.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/ListViewer.py	Sun Aug  8 12:41:24 2010
@@ -15,7 +15,7 @@
 given name, without selecting the color.
 """
 
-from Tkinter import *
+from tkinter import *
 import ColorDB
 
 ADDTOVIEW = 'Color %List Window...'

Modified: python/branches/py3k-dtoa/Tools/pynche/PyncheWidget.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/PyncheWidget.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/PyncheWidget.py	Sun Aug  8 12:41:24 2010
@@ -6,9 +6,8 @@
 
 import sys
 import os
-from Tkinter import *
-import tkMessageBox
-import tkFileDialog
+from tkinter import *
+from tkinter import messagebox, filedialog
 import ColorDB
 
 # Milliseconds between interrupt checks
@@ -150,7 +149,7 @@
 
     def __popup_about(self, event=None):
         from Main import __version__
-        tkMessageBox.showinfo('About Pynche ' + __version__,
+        messagebox.showinfo('About Pynche ' + __version__,
                               '''\
 Pynche %s
 The PYthonically Natural
@@ -168,7 +167,7 @@
     def __load(self, event=None):
         while 1:
             idir, ifile = os.path.split(self.__sb.colordb().filename())
-            file = tkFileDialog.askopenfilename(
+            file = filedialog.askopenfilename(
                 filetypes=[('Text files', '*.txt'),
                            ('All files', '*'),
                            ],
@@ -180,12 +179,12 @@
             try:
                 colordb = ColorDB.get_colordb(file)
             except IOError:
-                tkMessageBox.showerror('Read error', '''\
+                messagebox.showerror('Read error', '''\
 Could not open file for reading:
 %s''' % file)
                 continue
             if colordb is None:
-                tkMessageBox.showerror('Unrecognized color file type', '''\
+                messagebox.showerror('Unrecognized color file type', '''\
 Unrecognized color file type in file:
 %s''' % file)
                 continue
@@ -249,6 +248,8 @@
 
 
 
+import functools
+ at functools.total_ordering
 class PopupViewer:
     def __init__(self, module, name, switchboard, root):
         self.__m = module
@@ -279,8 +280,11 @@
             self.__sb.add_view(self.__window)
         self.__window.deiconify()
 
-    def __cmp__(self, other):
-        return cmp(self.__menutext, other.__menutext)
+    def __eq__(self, other):
+        return self.__menutext == other.__menutext
+
+    def __lt__(self, other):
+        return self.__menutext < other.__menutext
 
 
 def make_view_popups(switchboard, root, extrapath):

Modified: python/branches/py3k-dtoa/Tools/pynche/StripViewer.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/StripViewer.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/StripViewer.py	Sun Aug  8 12:41:24 2010
@@ -24,7 +24,7 @@
 this can be slow.
 """
 
-from Tkinter import *
+from tkinter import *
 import ColorDB
 
 # Load this script into the Tcl interpreter and call it in
@@ -62,32 +62,32 @@
 # red variations, green+blue = cyan constant
 def constant_red_generator(numchips, red, green, blue):
     seq = constant(numchips)
-    return list(map(None, [red] * numchips, seq, seq))
+    return list(zip([red] * numchips, seq, seq))
 
 # green variations, red+blue = magenta constant
 def constant_green_generator(numchips, red, green, blue):
     seq = constant(numchips)
-    return list(map(None, seq, [green] * numchips, seq))
+    return list(zip(seq, [green] * numchips, seq))
 
 # blue variations, red+green = yellow constant
 def constant_blue_generator(numchips, red, green, blue):
     seq = constant(numchips)
-    return list(map(None, seq, seq, [blue] * numchips))
+    return list(zip(seq, seq, [blue] * numchips))
 
 # red variations, green+blue = cyan constant
 def constant_cyan_generator(numchips, red, green, blue):
     seq = constant(numchips)
-    return list(map(None, seq, [green] * numchips, [blue] * numchips))
+    return list(zip(seq, [green] * numchips, [blue] * numchips))
 
 # green variations, red+blue = magenta constant
 def constant_magenta_generator(numchips, red, green, blue):
     seq = constant(numchips)
-    return list(map(None, [red] * numchips, seq, [blue] * numchips))
+    return list(zip([red] * numchips, seq, [blue] * numchips))
 
 # blue variations, red+green = yellow constant
 def constant_yellow_generator(numchips, red, green, blue):
     seq = constant(numchips)
-    return list(map(None, [red] * numchips, [green] * numchips, seq))
+    return list(zip([red] * numchips, [green] * numchips, seq))
 
 
 
@@ -119,7 +119,7 @@
         return arrow, text
 
     def _x(self):
-        coords = self._canvas.coords(self._TAG)
+        coords = list(self._canvas.coords(self._TAG))
         assert coords
         return coords[0]
 
@@ -151,7 +151,7 @@
         return arrow, text
 
     def _x(self):
-        coords = self._canvas.coords(self._TAG)
+        coords = list(self._canvas.coords(self._TAG))
         assert coords
         return coords[0] + self._ARROWWIDTH
 

Modified: python/branches/py3k-dtoa/Tools/pynche/Switchboard.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/Switchboard.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/Switchboard.py	Sun Aug  8 12:41:24 2010
@@ -42,7 +42,6 @@
 """
 
 import sys
-from types import DictType
 import marshal
 
 
@@ -62,10 +61,11 @@
         if initfile:
             try:
                 try:
-                    fp = open(initfile)
+                    fp = open(initfile, 'rb')
                     self.__optiondb = marshal.load(fp)
-                    if not isinstance(self.__optiondb, DictType):
-                        print('Problem reading options from file:', initfile, file=sys.stderr)
+                    if not isinstance(self.__optiondb, dict):
+                        print('Problem reading options from file:', initfile,
+                              file=sys.stderr)
                         self.__optiondb = {}
                 except (IOError, EOFError, ValueError):
                     pass
@@ -116,7 +116,7 @@
         fp = None
         try:
             try:
-                fp = open(self.__initfile, 'w')
+                fp = open(self.__initfile, 'wb')
             except IOError:
                 print('Cannot write options to file:', \
                       self.__initfile, file=sys.stderr)

Modified: python/branches/py3k-dtoa/Tools/pynche/TextViewer.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/TextViewer.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/TextViewer.py	Sun Aug  8 12:41:24 2010
@@ -15,7 +15,7 @@
 in the text window (which only has a background).
 """
 
-from Tkinter import *
+from tkinter import *
 import ColorDB
 
 ADDTOVIEW = 'Text Window...'

Modified: python/branches/py3k-dtoa/Tools/pynche/TypeinViewer.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/pynche/TypeinViewer.py	(original)
+++ python/branches/py3k-dtoa/Tools/pynche/TypeinViewer.py	Sun Aug  8 12:41:24 2010
@@ -12,7 +12,7 @@
 you must hit Return or Tab to select the color.
 """
 
-from Tkinter import *
+from tkinter import *
 
 
 

Modified: python/branches/py3k-dtoa/Tools/scripts/README
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/README	(original)
+++ python/branches/py3k-dtoa/Tools/scripts/README	Sun Aug  8 12:41:24 2010
@@ -1,68 +1,65 @@
-This directory contains a collection of executable Python scripts that
-are useful while building, extending or managing Python.  Some (e.g.,
-dutree or lll) are also generally useful UNIX tools.
+This directory contains a collection of executable Python scripts that are
+useful while building, extending or managing Python.  Some (e.g., dutree or lll)
+are also generally useful UNIX tools.
 
 See also the Demo/scripts directory!
 
-analyze_dxp.py		Analyzes the result of sys.getdxp()
-byext.py		Print lines/words/chars stats of files by extension
-byteyears.py		Print product of a file's size and age
-checkappend.py		Search for multi-argument .append() calls
-checkpyc.py		Check presence and validity of ".pyc" files
-classfix.py		Convert old class syntax to new
-cleanfuture.py		Fix reduntant Python __future__ statements
-combinerefs.py		A helper for analyzing PYTHONDUMPREFS output.
-copytime.py		Copy one file's atime and mtime to another
-crlf.py			Change CRLF line endings to LF (Windows to Unix)
-cvsfiles.py		Print a list of files that are under CVS
-db2pickle.py		Dump a database file to a pickle
-diff.py			Print file diffs in context, unified, or ndiff formats
-dutree.py		Format du(1) output as a tree sorted by size
-eptags.py		Create Emacs TAGS file for Python modules
+2to3                    Main script for running the 2to3 conversion tool
+analyze_dxp.py          Analyzes the result of sys.getdxp()
+byext.py                Print lines/words/chars stats of files by extension
+byteyears.py            Print product of a file's size and age
+checkpyc.py             Check presence and validity of ".pyc" files
+cleanfuture.py          Fix redundant Python __future__ statements
+combinerefs.py          A helper for analyzing PYTHONDUMPREFS output
+copytime.py             Copy one file's atime and mtime to another
+crlf.py                 Change CRLF line endings to LF (Windows to Unix)
+db2pickle.py            Dump a database file to a pickle
+diff.py                 Print file diffs in context, unified, or ndiff formats
+dutree.py               Format du(1) output as a tree sorted by size
+eptags.py               Create Emacs TAGS file for Python modules
 find_recursionlimit.py  Find the maximum recursion limit on this machine 
-finddiv.py		A grep-like tool that looks for division operators
-findlinksto.py		Recursively find symbolic links to a given path prefix
-findnocoding.py		Find source files which need an encoding declaration
-fixcid.py		Massive identifier substitution on C source files
-fixdiv.py		Tool to fix division operators.
-fixheader.py		Add some cpp magic to a C include file
-fixnotice.py		Fix the copyright notice in source files
-fixps.py		Fix Python scripts' first line (if #!)
-ftpmirror.py		FTP mirror script
-google.py		Open a webbrowser with Google
-gprof2html.py		Transform gprof(1) output into useful HTML
-h2py.py			Translate #define's into Python assignments
-idle			Main program to start IDLE
-ifdef.py		Remove #if(n)def groups from C sources
-lfcr.py			Change LF line endings to CRLF (Unix to Windows)
-linktree.py		Make a copy of a tree with links to original files
-lll.py			Find and list symbolic links in current directory
-logmerge.py		Consolidate CVS/RCS logs read from stdin
-mailerdaemon.py		parse error messages from mailer daemons (Sjoerd&Jack)
-md5sum.py		Print MD5 checksums of argument files.
-methfix.py		Fix old method syntax def f(self, (a1, ..., aN)):
-mkreal.py		Turn a symbolic link into a real file or directory
-ndiff.py		Intelligent diff between text files (Tim Peters)
-nm2def.py		Create a template for PC/python_nt.def (Marc Lemburg)
-objgraph.py		Print object graph from nm output on a library
-parseentities.py	Utility for parsing HTML entity definitions
-pathfix.py		Change #!/usr/local/bin/python into something else
-pdeps.py		Print dependencies between Python modules
-pickle2db.py		Load a pickle generated by db2pickle.py to a database
-pindent.py		Indent Python code, giving block-closing comments
-ptags.py		Create vi tags file for Python modules
-pydoc			Python documentation browser.
-pysource.py		Find Python source files
-redemo.py		Basic regular expression demonstration facility
-reindent.py		Change .py files to use 4-space indents.
-rgrep.py		Reverse grep through a file (useful for big logfiles)
-serve.py		Small wsgiref-based web server, used in make serve in Doc
-setup.py		Install all scripts listed here
-suff.py			Sort a list of files by suffix
-svneol.py		Sets svn:eol-style on all files in directory
-texcheck.py             Validate Python LaTeX formatting (Raymond Hettinger)
-texi2html.py		Convert GNU texinfo files into HTML
-treesync.py		Synchronize source trees (very ideosyncratic)
-untabify.py		Replace tabs with spaces in argument files
-which.py		Find a program in $PATH
-xxci.py			Wrapper for rcsdiff and ci
+finddiv.py              A grep-like tool that looks for division operators
+findlinksto.py          Recursively find symbolic links to a given path prefix
+findnocoding.py         Find source files which need an encoding declaration
+fixcid.py               Massive identifier substitution on C source files
+fixdiv.py               Tool to fix division operators.
+fixheader.py            Add some cpp magic to a C include file
+fixnotice.py            Fix the copyright notice in source files
+fixps.py                Fix Python scripts' first line (if #!)
+ftpmirror.py            FTP mirror script
+google.py               Open a webbrowser with Google
+gprof2html.py           Transform gprof(1) output into useful HTML
+h2py.py                 Translate #define's into Python assignments
+idle3                   Main program to start IDLE
+ifdef.py                Remove #if(n)def groups from C sources
+lfcr.py                 Change LF line endings to CRLF (Unix to Windows)
+linktree.py             Make a copy of a tree with links to original files
+lll.py                  Find and list symbolic links in current directory
+mailerdaemon.py         Parse error messages from mailer daemons (Sjoerd&Jack)
+make_ctype.py           Generate ctype.h replacement in stringobject.c
+md5sum.py               Print MD5 checksums of argument files
+mkreal.py               Turn a symbolic link into a real file or directory
+ndiff.py                Intelligent diff between text files (Tim Peters)
+nm2def.py               Create a template for PC/python_nt.def (Marc Lemburg)
+objgraph.py             Print object graph from nm output on a library
+parseentities.py        Utility for parsing HTML entity definitions
+patchcheck.py           Perform common checks and cleanup before committing
+pathfix.py              Change #!/usr/local/bin/python into something else
+pdeps.py                Print dependencies between Python modules
+pickle2db.py            Load a pickle generated by db2pickle.py to a database
+pindent.py              Indent Python code, giving block-closing comments
+ptags.py                Create vi tags file for Python modules
+pydoc3                  Python documentation browser
+pysource.py             Find Python source files
+redemo.py               Basic regular expression demonstration facility
+reindent.py             Change .py files to use 4-space indents
+reindent-rst.py         Fix-up reStructuredText file whitespace
+rgrep.py                Reverse grep through a file (useful for big logfiles)
+serve.py                Small wsgiref-based web server, used in make serve in Doc
+suff.py                 Sort a list of files by suffix
+svneol.py               Set svn:eol-style on all files in directory
+texi2html.py            Convert GNU texinfo files into HTML
+treesync.py             Synchronize source trees (very idiosyncratic)
+untabify.py             Replace tabs with spaces in argument files
+win_add2path.py         Add Python to the search path on Windows
+which.py                Find a program in $PATH

Modified: python/branches/py3k-dtoa/Tools/scripts/byext.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/byext.py	(original)
+++ python/branches/py3k-dtoa/Tools/scripts/byext.py	Sun Aug  8 12:41:24 2010
@@ -1,4 +1,4 @@
-#! /usr/bin/env python3.0
+#! /usr/bin/env python3
 
 """Show file statistics by extension."""
 

Deleted: python/branches/py3k-dtoa/Tools/scripts/checkappend.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/checkappend.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,169 +0,0 @@
-#! /usr/bin/env python3
-
-# Released to the public domain, by Tim Peters, 28 February 2000.
-
-"""checkappend.py -- search for multi-argument .append() calls.
-
-Usage:  specify one or more file or directory paths:
-    checkappend [-v] file_or_dir [file_or_dir] ...
-
-Each file_or_dir is checked for multi-argument .append() calls.  When
-a directory, all .py files in the directory, and recursively in its
-subdirectories, are checked.
-
-Use -v for status msgs.  Use -vv for more status msgs.
-
-In the absence of -v, the only output is pairs of the form
-
-    filename(linenumber):
-    line containing the suspicious append
-
-Note that this finds multi-argument append calls regardless of whether
-they're attached to list objects.  If a module defines a class with an
-append method that takes more than one argument, calls to that method
-will be listed.
-
-Note that this will not find multi-argument list.append calls made via a
-bound method object.  For example, this is not caught:
-
-    somelist = []
-    push = somelist.append
-    push(1, 2, 3)
-"""
-
-__version__ = 1, 0, 0
-
-import os
-import sys
-import getopt
-import tokenize
-
-verbose = 0
-
-def errprint(*args):
-    msg = ' '.join(args)
-    sys.stderr.write(msg)
-    sys.stderr.write("\n")
-
-def main():
-    args = sys.argv[1:]
-    global verbose
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], "v")
-    except getopt.error as msg:
-        errprint(str(msg) + "\n\n" + __doc__)
-        return
-    for opt, optarg in opts:
-        if opt == '-v':
-            verbose = verbose + 1
-    if not args:
-        errprint(__doc__)
-        return
-    for arg in args:
-        check(arg)
-
-def check(file):
-    if os.path.isdir(file) and not os.path.islink(file):
-        if verbose:
-            print("%r: listing directory" % (file,))
-        names = os.listdir(file)
-        for name in names:
-            fullname = os.path.join(file, name)
-            if ((os.path.isdir(fullname) and
-                 not os.path.islink(fullname))
-                or os.path.normcase(name[-3:]) == ".py"):
-                check(fullname)
-        return
-
-    try:
-        f = open(file)
-    except IOError as msg:
-        errprint("%r: I/O Error: %s" % (file, msg))
-        return
-
-    if verbose > 1:
-        print("checking %r ..." % (file,))
-
-    ok = AppendChecker(file, f).run()
-    if verbose and ok:
-        print("%r: Clean bill of health." % (file,))
-
-[FIND_DOT,
- FIND_APPEND,
- FIND_LPAREN,
- FIND_COMMA,
- FIND_STMT]   = range(5)
-
-class AppendChecker:
-    def __init__(self, fname, file):
-        self.fname = fname
-        self.file = file
-        self.state = FIND_DOT
-        self.nerrors = 0
-
-    def run(self):
-        try:
-            tokens = tokenize.generate_tokens(self.file.readline)
-            for _token in tokens:
-                self.tokeneater(*_token)
-        except tokenize.TokenError as msg:
-            errprint("%r: Token Error: %s" % (self.fname, msg))
-            self.nerrors = self.nerrors + 1
-        return self.nerrors == 0
-
-    def tokeneater(self, type, token, start, end, line,
-                NEWLINE=tokenize.NEWLINE,
-                JUNK=(tokenize.COMMENT, tokenize.NL),
-                OP=tokenize.OP,
-                NAME=tokenize.NAME):
-
-        state = self.state
-
-        if type in JUNK:
-            pass
-
-        elif state is FIND_DOT:
-            if type is OP and token == ".":
-                state = FIND_APPEND
-
-        elif state is FIND_APPEND:
-            if type is NAME and token == "append":
-                self.line = line
-                self.lineno = start[0]
-                state = FIND_LPAREN
-            else:
-                state = FIND_DOT
-
-        elif state is FIND_LPAREN:
-            if type is OP and token == "(":
-                self.level = 1
-                state = FIND_COMMA
-            else:
-                state = FIND_DOT
-
-        elif state is FIND_COMMA:
-            if type is OP:
-                if token in ("(", "{", "["):
-                    self.level = self.level + 1
-                elif token in (")", "}", "]"):
-                    self.level = self.level - 1
-                    if self.level == 0:
-                        state = FIND_DOT
-                elif token == "," and self.level == 1:
-                    self.nerrors = self.nerrors + 1
-                    print("%s(%d):\n%s" % (self.fname, self.lineno,
-                                           self.line))
-                    # don't gripe about this stmt again
-                    state = FIND_STMT
-
-        elif state is FIND_STMT:
-            if type is NEWLINE:
-                state = FIND_DOT
-
-        else:
-            raise SystemError("unknown internal state '%r'" % (state,))
-
-        self.state = state
-
-if __name__ == '__main__':
-    main()

Deleted: python/branches/py3k-dtoa/Tools/scripts/classfix.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/classfix.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,190 +0,0 @@
-#! /usr/bin/env python3
-
-# This script is obsolete -- it is kept for historical purposes only.
-#
-# Fix Python source files to use the new class definition syntax, i.e.,
-# the syntax used in Python versions before 0.9.8:
-#       class C() = base(), base(), ...: ...
-# is changed to the current syntax:
-#       class C(base, base, ...): ...
-#
-# The script uses heuristics to find class definitions that usually
-# work but occasionally can fail; carefully check the output!
-#
-# Command line arguments are files or directories to be processed.
-# Directories are searched recursively for files whose name looks
-# like a python module.
-# Symbolic links are always ignored (except as explicit directory
-# arguments).  Of course, the original file is kept as a back-up
-# (with a "~" attached to its name).
-#
-# Changes made are reported to stdout in a diff-like format.
-#
-# Undoubtedly you can do this using find and sed or perl, but this is
-# a nice example of Python code that recurses down a directory tree
-# and uses regular expressions.  Also note several subtleties like
-# preserving the file's mode and avoiding to even write a temp file
-# when no changes are needed for a file.
-#
-# NB: by changing only the function fixline() you can turn this
-# into a program for a different change to Python programs...
-
-import sys
-import re
-import os
-from stat import *
-
-err = sys.stderr.write
-dbg = err
-rep = sys.stdout.write
-
-def main():
-    bad = 0
-    if not sys.argv[1:]: # No arguments
-        err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
-        sys.exit(2)
-    for arg in sys.argv[1:]:
-        if os.path.isdir(arg):
-            if recursedown(arg): bad = 1
-        elif os.path.islink(arg):
-            err(arg + ': will not process symbolic links\n')
-            bad = 1
-        else:
-            if fix(arg): bad = 1
-    sys.exit(bad)
-
-ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
-def ispython(name):
-    return ispythonprog.match(name) >= 0
-
-def recursedown(dirname):
-    dbg('recursedown(%r)\n' % (dirname,))
-    bad = 0
-    try:
-        names = os.listdir(dirname)
-    except os.error as msg:
-        err('%s: cannot list directory: %r\n' % (dirname, msg))
-        return 1
-    names.sort()
-    subdirs = []
-    for name in names:
-        if name in (os.curdir, os.pardir): continue
-        fullname = os.path.join(dirname, name)
-        if os.path.islink(fullname): pass
-        elif os.path.isdir(fullname):
-            subdirs.append(fullname)
-        elif ispython(name):
-            if fix(fullname): bad = 1
-    for fullname in subdirs:
-        if recursedown(fullname): bad = 1
-    return bad
-
-def fix(filename):
-##  dbg('fix(%r)\n' % (filename,))
-    try:
-        f = open(filename, 'r')
-    except IOError as msg:
-        err('%s: cannot open: %r\n' % (filename, msg))
-        return 1
-    head, tail = os.path.split(filename)
-    tempname = os.path.join(head, '@' + tail)
-    g = None
-    # If we find a match, we rewind the file and start over but
-    # now copy everything to a temp file.
-    lineno = 0
-    while 1:
-        line = f.readline()
-        if not line: break
-        lineno = lineno + 1
-        while line[-2:] == '\\\n':
-            nextline = f.readline()
-            if not nextline: break
-            line = line + nextline
-            lineno = lineno + 1
-        newline = fixline(line)
-        if newline != line:
-            if g is None:
-                try:
-                    g = open(tempname, 'w')
-                except IOError as msg:
-                    f.close()
-                    err('%s: cannot create: %r\n' % (tempname, msg))
-                    return 1
-                f.seek(0)
-                lineno = 0
-                rep(filename + ':\n')
-                continue # restart from the beginning
-            rep(repr(lineno) + '\n')
-            rep('< ' + line)
-            rep('> ' + newline)
-        if g is not None:
-            g.write(newline)
-
-    # End of file
-    f.close()
-    if not g: return 0 # No changes
-
-    # Finishing touch -- move files
-
-    # First copy the file's mode to the temp file
-    try:
-        statbuf = os.stat(filename)
-        os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
-    except os.error as msg:
-        err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
-    # Then make a backup of the original file as filename~
-    try:
-        os.rename(filename, filename + '~')
-    except os.error as msg:
-        err('%s: warning: backup failed (%r)\n' % (filename, msg))
-    # Now move the temp file to the original file
-    try:
-        os.rename(tempname, filename)
-    except os.error as msg:
-        err('%s: rename failed (%r)\n' % (filename, msg))
-        return 1
-    # Return succes
-    return 0
-
-# This expression doesn't catch *all* class definition headers,
-# but it's pretty darn close.
-classexpr = '^([ \t]*class +[a-zA-Z0-9_]+) *( *) *((=.*)?):'
-classprog = re.compile(classexpr)
-
-# Expressions for finding base class expressions.
-baseexpr = '^ *(.*) *( *) *$'
-baseprog = re.compile(baseexpr)
-
-def fixline(line):
-    if classprog.match(line) < 0: # No 'class' keyword -- no change
-        return line
-
-    (a0, b0), (a1, b1), (a2, b2) = classprog.regs[:3]
-    # a0, b0 = Whole match (up to ':')
-    # a1, b1 = First subexpression (up to classname)
-    # a2, b2 = Second subexpression (=.*)
-    head = line[:b1]
-    tail = line[b0:] # Unmatched rest of line
-
-    if a2 == b2: # No base classes -- easy case
-        return head + ':' + tail
-
-    # Get rid of leading '='
-    basepart = line[a2+1:b2]
-
-    # Extract list of base expressions
-    bases = basepart.split(',')
-
-    # Strip trailing '()' from each base expression
-    for i in range(len(bases)):
-        if baseprog.match(bases[i]) >= 0:
-            x1, y1 = baseprog.regs[1]
-            bases[i] = bases[i][x1:y1]
-
-    # Join the bases back again and build the new line
-    basepart = ', '.join(bases)
-
-    return head + '(' + basepart + '):' + tail
-
-if __name__ == '__main__':
-    main()

Deleted: python/branches/py3k-dtoa/Tools/scripts/cvsfiles.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/cvsfiles.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,72 +0,0 @@
-#! /usr/bin/env python3
-
-"""Print a list of files that are mentioned in CVS directories.
-
-Usage: cvsfiles.py [-n file] [directory] ...
-
-If the '-n file' option is given, only files under CVS that are newer
-than the given file are printed; by default, all files under CVS are
-printed.  As a special case, if a file does not exist, it is always
-printed.
-"""
-
-import os
-import sys
-import stat
-import getopt
-
-cutofftime = 0
-
-def main():
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], "n:")
-    except getopt.error as msg:
-        print(msg)
-        print(__doc__, end=' ')
-        return 1
-    global cutofftime
-    newerfile = None
-    for o, a in opts:
-        if o == '-n':
-            cutofftime = getmtime(a)
-    if args:
-        for arg in args:
-            process(arg)
-    else:
-        process(".")
-
-def process(dir):
-    cvsdir = 0
-    subdirs = []
-    names = os.listdir(dir)
-    for name in names:
-        fullname = os.path.join(dir, name)
-        if name == "CVS":
-            cvsdir = fullname
-        else:
-            if os.path.isdir(fullname):
-                if not os.path.islink(fullname):
-                    subdirs.append(fullname)
-    if cvsdir:
-        entries = os.path.join(cvsdir, "Entries")
-        for e in open(entries).readlines():
-            words = e.split('/')
-            if words[0] == '' and words[1:]:
-                name = words[1]
-                fullname = os.path.join(dir, name)
-                if cutofftime and getmtime(fullname) <= cutofftime:
-                    pass
-                else:
-                    print(fullname)
-    for sub in subdirs:
-        process(sub)
-
-def getmtime(filename):
-    try:
-        st = os.stat(filename)
-    except os.error:
-        return 0
-    return st[stat.ST_MTIME]
-
-if __name__ == '__main__':
-    main()

Deleted: python/branches/py3k-dtoa/Tools/scripts/logmerge.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/logmerge.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,185 +0,0 @@
-#! /usr/bin/env python3
-
-"""Consolidate a bunch of CVS or RCS logs read from stdin.
-
-Input should be the output of a CVS or RCS logging command, e.g.
-
-    cvs log -rrelease14:
-
-which dumps all log messages from release1.4 upwards (assuming that
-release 1.4 was tagged with tag 'release14').  Note the trailing
-colon!
-
-This collects all the revision records and outputs them sorted by date
-rather than by file, collapsing duplicate revision record, i.e.,
-records with the same message for different files.
-
-The -t option causes it to truncate (discard) the last revision log
-entry; this is useful when using something like the above cvs log
-command, which shows the revisions including the given tag, while you
-probably want everything *since* that tag.
-
-The -r option reverses the output (oldest first; the default is oldest
-last).
-
-The -b tag option restricts the output to *only* checkin messages
-belonging to the given branch tag.  The form -b HEAD restricts the
-output to checkin messages belonging to the CVS head (trunk).  (It
-produces some output if tag is a non-branch tag, but this output is
-not very useful.)
-
--h prints this message and exits.
-
-XXX This code was created by reverse engineering CVS 1.9 and RCS 5.7
-from their output.
-"""
-
-import sys, errno, getopt, re
-
-sep1 = '='*77 + '\n'                    # file separator
-sep2 = '-'*28 + '\n'                    # revision separator
-
-def main():
-    """Main program"""
-    truncate_last = 0
-    reverse = 0
-    branch = None
-    opts, args = getopt.getopt(sys.argv[1:], "trb:h")
-    for o, a in opts:
-        if o == '-t':
-            truncate_last = 1
-        elif o == '-r':
-            reverse = 1
-        elif o == '-b':
-            branch = a
-        elif o == '-h':
-            print(__doc__)
-            sys.exit(0)
-    database = []
-    while 1:
-        chunk = read_chunk(sys.stdin)
-        if not chunk:
-            break
-        records = digest_chunk(chunk, branch)
-        if truncate_last:
-            del records[-1]
-        database[len(database):] = records
-    database.sort()
-    if not reverse:
-        database.reverse()
-    format_output(database)
-
-def read_chunk(fp):
-    """Read a chunk -- data for one file, ending with sep1.
-
-    Split the chunk in parts separated by sep2.
-
-    """
-    chunk = []
-    lines = []
-    while 1:
-        line = fp.readline()
-        if not line:
-            break
-        if line == sep1:
-            if lines:
-                chunk.append(lines)
-            break
-        if line == sep2:
-            if lines:
-                chunk.append(lines)
-                lines = []
-        else:
-            lines.append(line)
-    return chunk
-
-def digest_chunk(chunk, branch=None):
-    """Digest a chunk -- extract working file name and revisions"""
-    lines = chunk[0]
-    key = 'Working file:'
-    keylen = len(key)
-    for line in lines:
-        if line[:keylen] == key:
-            working_file = line[keylen:].strip()
-            break
-    else:
-        working_file = None
-    if branch is None:
-        pass
-    elif branch == "HEAD":
-        branch = re.compile(r"^\d+\.\d+$")
-    else:
-        revisions = {}
-        key = 'symbolic names:\n'
-        found = 0
-        for line in lines:
-            if line == key:
-                found = 1
-            elif found:
-                if line[0] in '\t ':
-                    tag, rev = line.split()
-                    if tag[-1] == ':':
-                        tag = tag[:-1]
-                    revisions[tag] = rev
-                else:
-                    found = 0
-        rev = revisions.get(branch)
-        branch = re.compile(r"^<>$") # <> to force a mismatch by default
-        if rev:
-            if rev.find('.0.') >= 0:
-                rev = rev.replace('.0.', '.')
-                branch = re.compile(r"^" + re.escape(rev) + r"\.\d+$")
-    records = []
-    for lines in chunk[1:]:
-        revline = lines[0]
-        dateline = lines[1]
-        text = lines[2:]
-        words = dateline.split()
-        author = None
-        if len(words) >= 3 and words[0] == 'date:':
-            dateword = words[1]
-            timeword = words[2]
-            if timeword[-1:] == ';':
-                timeword = timeword[:-1]
-            date = dateword + ' ' + timeword
-            if len(words) >= 5 and words[3] == 'author:':
-                author = words[4]
-                if author[-1:] == ';':
-                    author = author[:-1]
-        else:
-            date = None
-            text.insert(0, revline)
-        words = revline.split()
-        if len(words) >= 2 and words[0] == 'revision':
-            rev = words[1]
-        else:
-            # No 'revision' line -- weird...
-            rev = None
-            text.insert(0, revline)
-        if branch:
-            if rev is None or not branch.match(rev):
-                continue
-        records.append((date, working_file, rev, author, text))
-    return records
-
-def format_output(database):
-    prevtext = None
-    prev = []
-    database.append((None, None, None, None, None)) # Sentinel
-    for (date, working_file, rev, author, text) in database:
-        if text != prevtext:
-            if prev:
-                print(sep2, end=' ')
-                for (p_date, p_working_file, p_rev, p_author) in prev:
-                    print(p_date, p_author, p_working_file, p_rev)
-                sys.stdout.writelines(prevtext)
-            prev = []
-        prev.append((date, working_file, rev, author))
-        prevtext = text
-
-if __name__ == '__main__':
-    try:
-        main()
-    except IOError as e:
-        if e.errno != errno.EPIPE:
-            raise

Deleted: python/branches/py3k-dtoa/Tools/scripts/methfix.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/methfix.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,171 +0,0 @@
-#! /usr/bin/env python3
-
-# Fix Python source files to avoid using
-#       def method(self, (arg1, ..., argn)):
-# instead of the more rational
-#       def method(self, arg1, ..., argn):
-#
-# Command line arguments are files or directories to be processed.
-# Directories are searched recursively for files whose name looks
-# like a python module.
-# Symbolic links are always ignored (except as explicit directory
-# arguments).  Of course, the original file is kept as a back-up
-# (with a "~" attached to its name).
-# It complains about binaries (files containing null bytes)
-# and about files that are ostensibly not Python files: if the first
-# line starts with '#!' and does not contain the string 'python'.
-#
-# Changes made are reported to stdout in a diff-like format.
-#
-# Undoubtedly you can do this using find and sed or perl, but this is
-# a nice example of Python code that recurses down a directory tree
-# and uses regular expressions.  Also note several subtleties like
-# preserving the file's mode and avoiding to even write a temp file
-# when no changes are needed for a file.
-#
-# NB: by changing only the function fixline() you can turn this
-# into a program for a different change to Python programs...
-
-import sys
-import re
-import os
-from stat import *
-
-err = sys.stderr.write
-dbg = err
-rep = sys.stdout.write
-
-def main():
-    bad = 0
-    if not sys.argv[1:]: # No arguments
-        err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
-        sys.exit(2)
-    for arg in sys.argv[1:]:
-        if os.path.isdir(arg):
-            if recursedown(arg): bad = 1
-        elif os.path.islink(arg):
-            err(arg + ': will not process symbolic links\n')
-            bad = 1
-        else:
-            if fix(arg): bad = 1
-    sys.exit(bad)
-
-ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
-def ispython(name):
-    return ispythonprog.match(name) >= 0
-
-def recursedown(dirname):
-    dbg('recursedown(%r)\n' % (dirname,))
-    bad = 0
-    try:
-        names = os.listdir(dirname)
-    except os.error as msg:
-        err('%s: cannot list directory: %r\n' % (dirname, msg))
-        return 1
-    names.sort()
-    subdirs = []
-    for name in names:
-        if name in (os.curdir, os.pardir): continue
-        fullname = os.path.join(dirname, name)
-        if os.path.islink(fullname): pass
-        elif os.path.isdir(fullname):
-            subdirs.append(fullname)
-        elif ispython(name):
-            if fix(fullname): bad = 1
-    for fullname in subdirs:
-        if recursedown(fullname): bad = 1
-    return bad
-
-def fix(filename):
-##  dbg('fix(%r)\n' % (filename,))
-    try:
-        f = open(filename, 'r')
-    except IOError as msg:
-        err('%s: cannot open: %r\n' % (filename, msg))
-        return 1
-    head, tail = os.path.split(filename)
-    tempname = os.path.join(head, '@' + tail)
-    g = None
-    # If we find a match, we rewind the file and start over but
-    # now copy everything to a temp file.
-    lineno = 0
-    while 1:
-        line = f.readline()
-        if not line: break
-        lineno = lineno + 1
-        if g is None and '\0' in line:
-            # Check for binary files
-            err(filename + ': contains null bytes; not fixed\n')
-            f.close()
-            return 1
-        if lineno == 1 and g is None and line[:2] == '#!':
-            # Check for non-Python scripts
-            words = line[2:].split()
-            if words and re.search('[pP]ython', words[0]) < 0:
-                msg = filename + ': ' + words[0]
-                msg = msg + ' script; not fixed\n'
-                err(msg)
-                f.close()
-                return 1
-        while line[-2:] == '\\\n':
-            nextline = f.readline()
-            if not nextline: break
-            line = line + nextline
-            lineno = lineno + 1
-        newline = fixline(line)
-        if newline != line:
-            if g is None:
-                try:
-                    g = open(tempname, 'w')
-                except IOError as msg:
-                    f.close()
-                    err('%s: cannot create: %r\n' % (tempname, msg))
-                    return 1
-                f.seek(0)
-                lineno = 0
-                rep(filename + ':\n')
-                continue # restart from the beginning
-            rep(repr(lineno) + '\n')
-            rep('< ' + line)
-            rep('> ' + newline)
-        if g is not None:
-            g.write(newline)
-
-    # End of file
-    f.close()
-    if not g: return 0 # No changes
-
-    # Finishing touch -- move files
-
-    # First copy the file's mode to the temp file
-    try:
-        statbuf = os.stat(filename)
-        os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
-    except os.error as msg:
-        err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
-    # Then make a backup of the original file as filename~
-    try:
-        os.rename(filename, filename + '~')
-    except os.error as msg:
-        err('%s: warning: backup failed (%r)\n' % (filename, msg))
-    # Now move the temp file to the original file
-    try:
-        os.rename(tempname, filename)
-    except os.error as msg:
-        err('%s: rename failed (%r)\n' % (filename, msg))
-        return 1
-    # Return succes
-    return 0
-
-
-fixpat = '^[ \t]+def +[a-zA-Z0-9_]+ *( *self *, *(( *(.*) *)) *) *:'
-fixprog = re.compile(fixpat)
-
-def fixline(line):
-    if fixprog.match(line) >= 0:
-        (a, b), (c, d) = fixprog.regs[1:3]
-        line = line[:a] + line[c:d] + line[b:]
-    return line
-
-if __name__ == '__main__':
-    main()

Modified: python/branches/py3k-dtoa/Tools/scripts/serve.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/serve.py	(original)
+++ python/branches/py3k-dtoa/Tools/scripts/serve.py	Sun Aug  8 12:41:24 2010
@@ -19,7 +19,7 @@
 
     if os.path.exists(fn):
         respond('200 OK', [('Content-Type', type)])
-        return util.FileWrapper(open(fn))
+        return util.FileWrapper(open(fn, "rb"))
     else:
         respond('404 Not Found', [('Content-Type', 'text/plain')])
         return ['not found']

Deleted: python/branches/py3k-dtoa/Tools/scripts/setup.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/setup.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,20 +0,0 @@
-from distutils.core import setup
-
-if __name__ == '__main__':
-    setup(
-      scripts=[
-        'byteyears.py',
-        'checkpyc.py',
-        'copytime.py',
-        'crlf.py',
-        'dutree.py',
-        'ftpmirror.py',
-        'h2py.py',
-        'lfcr.py',
-        '../i18n/pygettext.py',
-        'logmerge.py',
-        '../../Lib/tabnanny.py',
-        '../../Lib/timeit.py',
-        'untabify.py',
-        ],
-      )

Modified: python/branches/py3k-dtoa/Tools/scripts/win_add2path.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/win_add2path.py	(original)
+++ python/branches/py3k-dtoa/Tools/scripts/win_add2path.py	Sun Aug  8 12:41:24 2010
@@ -15,7 +15,7 @@
 HKCU = winreg.HKEY_CURRENT_USER
 ENV = "Environment"
 PATH = "PATH"
-DEFAULT = u"%PATH%"
+DEFAULT = "%PATH%"
 
 def modify():
     pythonpath = os.path.dirname(os.path.normpath(sys.executable))

Deleted: python/branches/py3k-dtoa/Tools/scripts/xxci.py
==============================================================================
--- python/branches/py3k-dtoa/Tools/scripts/xxci.py	Sun Aug  8 12:41:24 2010
+++ (empty file)
@@ -1,121 +0,0 @@
-#! /usr/bin/env python3
-
-# xxci
-#
-# check in files for which rcsdiff returns nonzero exit status
-
-import sys
-import os
-from stat import *
-import fnmatch
-
-EXECMAGIC = '\001\140\000\010'
-
-MAXSIZE = 200*1024 # Files this big must be binaries and are skipped.
-
-def getargs():
-    args = sys.argv[1:]
-    if args:
-        return args
-    print('No arguments, checking almost *, in "ls -t" order')
-    list = []
-    for file in os.listdir(os.curdir):
-        if not skipfile(file):
-            list.append((getmtime(file), file))
-    list.sort()
-    if not list:
-        print('Nothing to do -- exit 1')
-        sys.exit(1)
-    list.sort()
-    list.reverse()
-    for mtime, file in list: args.append(file)
-    return args
-
-def getmtime(file):
-    try:
-        st = os.stat(file)
-        return st[ST_MTIME]
-    except os.error:
-        return -1
-
-badnames = ['tags', 'TAGS', 'xyzzy', 'nohup.out', 'core']
-badprefixes = ['.', ',', '@', '#', 'o.']
-badsuffixes = \
-        ['~', '.a', '.o', '.old', '.bak', '.orig', '.new', '.prev', '.not', \
-         '.pyc', '.fdc', '.rgb', '.elc', ',v']
-ignore = []
-
-def setup():
-    ignore[:] = badnames
-    for p in badprefixes:
-        ignore.append(p + '*')
-    for p in badsuffixes:
-        ignore.append('*' + p)
-    try:
-        f = open('.xxcign', 'r')
-    except IOError:
-        return
-    ignore[:] = ignore + f.read().split()
-
-def skipfile(file):
-    for p in ignore:
-        if fnmatch.fnmatch(file, p): return 1
-    try:
-        st = os.lstat(file)
-    except os.error:
-        return 1 # Doesn't exist -- skip it
-    # Skip non-plain files.
-    if not S_ISREG(st[ST_MODE]): return 1
-    # Skip huge files -- probably binaries.
-    if st[ST_SIZE] >= MAXSIZE: return 1
-    # Skip executables
-    try:
-        data = open(file, 'r').read(len(EXECMAGIC))
-        if data == EXECMAGIC: return 1
-    except:
-        pass
-    return 0
-
-def badprefix(file):
-    for bad in badprefixes:
-        if file[:len(bad)] == bad: return 1
-    return 0
-
-def badsuffix(file):
-    for bad in badsuffixes:
-        if file[-len(bad):] == bad: return 1
-    return 0
-
-def go(args):
-    for file in args:
-        print(file + ':')
-        if differing(file):
-            showdiffs(file)
-            if askyesno('Check in ' + file + ' ? '):
-                sts = os.system('rcs -l ' + file) # ignored
-                sts = os.system('ci -l ' + file)
-
-def differing(file):
-    cmd = 'co -p ' + file + ' 2>/dev/null | cmp -s - ' + file
-    sts = os.system(cmd)
-    return sts != 0
-
-def showdiffs(file):
-    cmd = 'rcsdiff ' + file + ' 2>&1 | ${PAGER-more}'
-    sts = os.system(cmd)
-
-def raw_input(prompt):
-    sys.stdout.write(prompt)
-    sys.stdout.flush()
-    return sys.stdin.readline()
-
-def askyesno(prompt):
-    s = input(prompt)
-    return s in ['y', 'yes']
-
-if __name__ == '__main__':
-    try:
-        setup()
-        go(getargs())
-    except KeyboardInterrupt:
-        print('[Intr]')

Modified: python/branches/py3k-dtoa/configure
==============================================================================
--- python/branches/py3k-dtoa/configure	(original)
+++ python/branches/py3k-dtoa/configure	Sun Aug  8 12:41:24 2010
@@ -3158,9 +3158,12 @@
 (it is also a good idea to do 'make clean' before compiling)" "$LINENO" 5
 fi
 
-# If the user set CFLAGS, use this instead of the automatically
-# determined setting
-preset_cflags="$CFLAGS"
+# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2
+# when the compiler supports them, but we don't always want -O2, and
+# we set -g later.
+if test -z "$CFLAGS"; then
+        CFLAGS=
+fi
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -3952,10 +3955,6 @@
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-if test ! -z "$preset_cflags"
-then
-	CFLAGS=$preset_cflags
-fi
 
 
 

Modified: python/branches/py3k-dtoa/configure.in
==============================================================================
--- python/branches/py3k-dtoa/configure.in	(original)
+++ python/branches/py3k-dtoa/configure.in	Sun Aug  8 12:41:24 2010
@@ -461,14 +461,13 @@
 (it is also a good idea to do 'make clean' before compiling)])
 fi
 
-# If the user set CFLAGS, use this instead of the automatically
-# determined setting
-preset_cflags="$CFLAGS"
-AC_PROG_CC
-if test ! -z "$preset_cflags"
-then
-	CFLAGS=$preset_cflags
+# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2
+# when the compiler supports them, but we don't always want -O2, and
+# we set -g later.
+if test -z "$CFLAGS"; then
+        CFLAGS=
 fi
+AC_PROG_CC
 
 AC_SUBST(CXX)
 AC_SUBST(MAINCC)
@@ -2459,7 +2458,7 @@
 fi
 AC_MSG_RESULT($with_doc_strings)
 
-# Check for Python-specific malloc support
+# Check if eval loop should use timestamp counter profiling
 AC_MSG_CHECKING(for --with-tsc)
 AC_ARG_WITH(tsc,
 	    AS_HELP_STRING([--with(out)-tsc],[enable/disable timestamp counter profile]),[

Modified: python/branches/py3k-dtoa/setup.py
==============================================================================
--- python/branches/py3k-dtoa/setup.py	(original)
+++ python/branches/py3k-dtoa/setup.py	Sun Aug  8 12:41:24 2010
@@ -222,7 +222,7 @@
         if compiler is not None:
             (ccshared,cflags) = sysconfig.get_config_vars('CCSHARED','CFLAGS')
             args['compiler_so'] = compiler + ' ' + ccshared + ' ' + cflags
-        self.compiler_obj.set_executables(**args)
+        self.compiler.set_executables(**args)
 
         build_ext.build_extensions(self)
 
@@ -343,8 +343,8 @@
 
     def detect_modules(self):
         # Ensure that /usr/local is always used
-        add_dir_to_list(self.compiler_obj.library_dirs, '/usr/local/lib')
-        add_dir_to_list(self.compiler_obj.include_dirs, '/usr/local/include')
+        add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
+        add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
 
         # Add paths specified in the environment variables LDFLAGS and
         # CPPFLAGS for header and library files.
@@ -353,9 +353,9 @@
         # the environment variable is not set even though the value were passed
         # into configure and stored in the Makefile (issue found on OS X 10.3).
         for env_var, arg_name, dir_list in (
-                ('LDFLAGS', '-R', self.compiler_obj.runtime_library_dirs),
-                ('LDFLAGS', '-L', self.compiler_obj.library_dirs),
-                ('CPPFLAGS', '-I', self.compiler_obj.include_dirs)):
+                ('LDFLAGS', '-R', self.compiler.runtime_library_dirs),
+                ('LDFLAGS', '-L', self.compiler.library_dirs),
+                ('CPPFLAGS', '-I', self.compiler.include_dirs)):
             env_val = sysconfig.get_config_var(env_var)
             if env_val:
                 # To prevent optparse from raising an exception about any
@@ -381,19 +381,19 @@
                         add_dir_to_list(dir_list, directory)
 
         if os.path.normpath(sys.prefix) != '/usr':
-            add_dir_to_list(self.compiler_obj.library_dirs,
+            add_dir_to_list(self.compiler.library_dirs,
                             sysconfig.get_config_var("LIBDIR"))
-            add_dir_to_list(self.compiler_obj.include_dirs,
+            add_dir_to_list(self.compiler.include_dirs,
                             sysconfig.get_config_var("INCLUDEDIR"))
 
         # lib_dirs and inc_dirs are used to search for files;
         # if a file is found in one of those directories, it can
         # be assumed that no additional -I,-L directives are needed.
-        lib_dirs = self.compiler_obj.library_dirs + [
+        lib_dirs = self.compiler.library_dirs + [
             '/lib64', '/usr/lib64',
             '/lib', '/usr/lib',
             ]
-        inc_dirs = self.compiler_obj.include_dirs + ['/usr/include']
+        inc_dirs = self.compiler.include_dirs + ['/usr/include']
         exts = []
         missing = []
 
@@ -452,7 +452,7 @@
         # time operations and variables
         exts.append( Extension('time', ['timemodule.c', '_time.c'],
                                libraries=math_libs) )
-        exts.append( Extension('datetime', ['datetimemodule.c', '_time.c'],
+        exts.append( Extension('_datetime', ['_datetimemodule.c', '_time.c'],
                                libraries=math_libs) )
         # fast iterator tools implemented in C
         exts.append( Extension("itertools", ["itertoolsmodule.c"]) )
@@ -525,7 +525,7 @@
         exts.append( Extension('audioop', ['audioop.c']) )
 
         # readline
-        do_readline = self.compiler_obj.find_library_file(lib_dirs, 'readline')
+        do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
         readline_termcap_library = ""
         curses_library = ""
         # Determine if readline is already linked against curses or tinfo.
@@ -534,28 +534,29 @@
             tmpfile = os.path.join(self.build_temp, 'readline_termcap_lib')
             if not os.path.exists(self.build_temp):
                 os.makedirs(self.build_temp)
-            os.system("ldd %s > %s" % (do_readline, tmpfile))
-            fp = open(tmpfile)
-            for ln in fp:
-                if 'curses' in ln:
-                    readline_termcap_library = re.sub(
-                        r'.*lib(n?cursesw?)\.so.*', r'\1', ln
-                    ).rstrip()
-                    break
-                if 'tinfo' in ln: # termcap interface split out from ncurses
-                    readline_termcap_library = 'tinfo'
-                    break
-            fp.close()
+            ret = os.system("ldd %s > %s" % (do_readline, tmpfile))
+            if ret >> 8 == 0:
+                fp = open(tmpfile)
+                for ln in fp:
+                    if 'curses' in ln:
+                        readline_termcap_library = re.sub(
+                            r'.*lib(n?cursesw?)\.so.*', r'\1', ln
+                        ).rstrip()
+                        break
+                    if 'tinfo' in ln: # termcap interface split out from ncurses
+                        readline_termcap_library = 'tinfo'
+                        break
+                fp.close()
             os.unlink(tmpfile)
         # Issue 7384: If readline is already linked against curses,
         # use the same library for the readline and curses modules.
         if 'curses' in readline_termcap_library:
             curses_library = readline_termcap_library
-        elif self.compiler_obj.find_library_file(lib_dirs, 'ncursesw'):
+        elif self.compiler.find_library_file(lib_dirs, 'ncursesw'):
             curses_library = 'ncursesw'
-        elif self.compiler_obj.find_library_file(lib_dirs, 'ncurses'):
+        elif self.compiler.find_library_file(lib_dirs, 'ncurses'):
             curses_library = 'ncurses'
-        elif self.compiler_obj.find_library_file(lib_dirs, 'curses'):
+        elif self.compiler.find_library_file(lib_dirs, 'curses'):
             curses_library = 'curses'
 
         if platform == 'darwin':
@@ -585,7 +586,7 @@
                 pass # Issue 7384: Already linked against curses or tinfo.
             elif curses_library:
                 readline_libs.append(curses_library)
-            elif self.compiler_obj.find_library_file(lib_dirs +
+            elif self.compiler.find_library_file(lib_dirs +
                                                      ['/usr/lib/termcap'],
                                                      'termcap'):
                 readline_libs.append('termcap')
@@ -598,7 +599,7 @@
 
         # crypt module.
 
-        if self.compiler_obj.find_library_file(lib_dirs, 'crypt'):
+        if self.compiler.find_library_file(lib_dirs, 'crypt'):
             libs = ['crypt']
         else:
             libs = []
@@ -626,7 +627,7 @@
                                ['/usr/kerberos/include'])
             if krb5_h:
                 ssl_incs += krb5_h
-        ssl_libs = find_library_file(self.compiler_obj, 'ssl',lib_dirs,
+        ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
                                      ['/usr/local/ssl/lib',
                                       '/usr/contrib/ssl/lib/'
                                      ] )
@@ -951,7 +952,7 @@
                 os.path.join(sqlite_incdir, '..', '..', 'lib64'),
                 os.path.join(sqlite_incdir, '..', '..', 'lib'),
             ]
-            sqlite_libfile = self.compiler_obj.find_library_file(
+            sqlite_libfile = self.compiler.find_library_file(
                                 sqlite_dirs_to_check + lib_dirs, 'sqlite3')
             if sqlite_libfile:
                 sqlite_libdir = [os.path.abspath(os.path.dirname(sqlite_libfile))]
@@ -1013,7 +1014,7 @@
                 if cand == "ndbm":
                     if find_file("ndbm.h", inc_dirs, []) is not None:
                         # Some systems have -lndbm, others don't
-                        if self.compiler_obj.find_library_file(lib_dirs,
+                        if self.compiler.find_library_file(lib_dirs,
                                                                'ndbm'):
                             ndbm_libs = ['ndbm']
                         else:
@@ -1027,9 +1028,9 @@
                         break
 
                 elif cand == "gdbm":
-                    if self.compiler_obj.find_library_file(lib_dirs, 'gdbm'):
+                    if self.compiler.find_library_file(lib_dirs, 'gdbm'):
                         gdbm_libs = ['gdbm']
-                        if self.compiler_obj.find_library_file(lib_dirs,
+                        if self.compiler.find_library_file(lib_dirs,
                                                                'gdbm_compat'):
                             gdbm_libs.append('gdbm_compat')
                         if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
@@ -1070,7 +1071,7 @@
 
         # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
         if ('gdbm' in dbm_order and
-            self.compiler_obj.find_library_file(lib_dirs, 'gdbm')):
+            self.compiler.find_library_file(lib_dirs, 'gdbm')):
             exts.append( Extension('_gdbm', ['_gdbmmodule.c'],
                                    libraries = ['gdbm'] ) )
         else:
@@ -1086,7 +1087,7 @@
             # Sun yellow pages. Some systems have the functions in libc.
             if (platform not in ['cygwin', 'qnx6'] and
                 find_file('rpcsvc/yp_prot.h', inc_dirs, []) is not None):
-                if (self.compiler_obj.find_library_file(lib_dirs, 'nsl')):
+                if (self.compiler.find_library_file(lib_dirs, 'nsl')):
                     libs = ['nsl']
                 else:
                     libs = []
@@ -1111,9 +1112,9 @@
         elif curses_library == 'curses' and platform != 'darwin':
                 # OSX has an old Berkeley curses, not good enough for
                 # the _curses module.
-            if (self.compiler_obj.find_library_file(lib_dirs, 'terminfo')):
+            if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
                 curses_libs = ['curses', 'terminfo']
-            elif (self.compiler_obj.find_library_file(lib_dirs, 'termcap')):
+            elif (self.compiler.find_library_file(lib_dirs, 'termcap')):
                 curses_libs = ['curses', 'termcap']
             else:
                 curses_libs = ['curses']
@@ -1125,7 +1126,7 @@
 
         # If the curses module is enabled, check for the panel module
         if (module_enabled(exts, '_curses') and
-            self.compiler_obj.find_library_file(lib_dirs, panel_library)):
+            self.compiler.find_library_file(lib_dirs, panel_library)):
             exts.append( Extension('_curses_panel', ['_curses_panel.c'],
                                    libraries = [panel_library] + curses_libs) )
         else:
@@ -1158,7 +1159,7 @@
                     version = line.split()[2]
                     break
             if version >= version_req:
-                if (self.compiler_obj.find_library_file(lib_dirs, 'z')):
+                if (self.compiler.find_library_file(lib_dirs, 'z')):
                     if sys.platform == "darwin":
                         zlib_extra_link_args = ('-Wl,-search_paths_first',)
                     else:
@@ -1190,7 +1191,7 @@
                                extra_link_args = extra_link_args) )
 
         # Gustavo Niemeyer's bz2 module.
-        if (self.compiler_obj.find_library_file(lib_dirs, 'bz2')):
+        if (self.compiler.find_library_file(lib_dirs, 'bz2')):
             if sys.platform == "darwin":
                 bz2_extra_link_args = ('-Wl,-search_paths_first',)
             else:
@@ -1451,9 +1452,9 @@
         tcllib = tklib = tcl_includes = tk_includes = None
         for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
                         '8.2', '82', '8.1', '81', '8.0', '80']:
-            tklib = self.compiler_obj.find_library_file(lib_dirs,
+            tklib = self.compiler.find_library_file(lib_dirs,
                                                         'tk' + version)
-            tcllib = self.compiler_obj.find_library_file(lib_dirs,
+            tcllib = self.compiler.find_library_file(lib_dirs,
                                                          'tcl' + version)
             if tklib and tcllib:
                 # Exit the loop when we've found the Tcl/Tk libraries
@@ -1512,11 +1513,11 @@
                 return
 
         # Check for BLT extension
-        if self.compiler_obj.find_library_file(lib_dirs + added_lib_dirs,
+        if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
                                                'BLT8.0'):
             defs.append( ('WITH_BLT', 1) )
             libs.append('BLT8.0')
-        elif self.compiler_obj.find_library_file(lib_dirs + added_lib_dirs,
+        elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
                                                 'BLT'):
             defs.append( ('WITH_BLT', 1) )
             libs.append('BLT')
@@ -1571,7 +1572,7 @@
                              ]]
 
         # Add .S (preprocessed assembly) to C compiler source extensions.
-        self.compiler_obj.src_extensions.append('.S')
+        self.compiler.src_extensions.append('.S')
 
         include_dirs = [os.path.join(ffi_srcdir, 'include'),
                         os.path.join(ffi_srcdir, 'powerpc')]
@@ -1616,7 +1617,7 @@
                 exec(f.read(), globals(), fficonfig)
 
             # Add .S (preprocessed assembly) to C compiler source extensions.
-            self.compiler_obj.src_extensions.append('.S')
+            self.compiler.src_extensions.append('.S')
 
             include_dirs = [os.path.join(ffi_builddir, 'include'),
                             ffi_builddir,
@@ -1698,7 +1699,7 @@
         ffi_lib = None
         if ffi_inc is not None:
             for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'):
-                if (self.compiler_obj.find_library_file(lib_dirs, lib_name)):
+                if (self.compiler.find_library_file(lib_dirs, lib_name)):
                     ffi_lib = lib_name
                     break
 


More information about the Python-checkins mailing list