[Python-checkins] r84330 - in python/branches/pep-0384: .bzrignore .hgignore 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/tkinter/guido/ss1.py Demo/zlib/minigzip.py Demo/zlib/zlibdemo.py Doc/Makefile Doc/README.txt Doc/c-api/abstract.rst Doc/c-api/arg.rst Doc/c-api/bytes.rst Doc/c-api/dict.rst Doc/c-api/exceptions.rst Doc/c-api/file.rst Doc/c-api/import.rst Doc/c-api/init.rst Doc/c-api/long.rst Doc/c-api/module.rst Doc/c-api/sys.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/extending.rst Doc/distutils/sourcedist.rst Doc/distutils/uploading.rst Doc/documenting/building.rst Doc/documenting/markup.rst Doc/extending/extending.rst Doc/faq/library.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/base64.rst Doc/library/bdb.rst Doc/library/binascii.rst Doc/library/bisect.rst Doc/library/cgi.rst Doc/library/cmd.rst Doc/library/codecs.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/decimal.rst Doc/library/dis.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/gc.rst Doc/library/gzip.rst Doc/library/hashlib.rst Doc/library/heapq.rst Doc/library/html.parser.rst Doc/library/http.client.rst Doc/library/importlib.rst Doc/library/io.rst Doc/library/itertools.rst Doc/library/json.rst Doc/library/linecache.rst Doc/library/locale.rst Doc/library/logging.rst Doc/library/mmap.rst Doc/library/msvcrt.rst Doc/library/operator.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/poplib.rst Doc/library/pyexpat.rst Doc/library/re.rst Doc/library/runpy.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/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.etree.elementtree.rst Doc/library/xml.sax.reader.rst Doc/library/zipfile.rst Doc/library/zipimport.rst Doc/license.rst Doc/make.bat Doc/reference/compound_stmts.rst Doc/reference/lexical_analysis.rst Doc/tools/sphinx-build.py 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 Include/Python.h Include/floatobject.h Include/moduleobject.h Include/patchlevel.h Include/pyport.h Include/pythonrun.h Include/pytime.h Include/setobject.h Include/structseq.h Include/sysmodule.h Include/unicodeobject.h Include/warnings.h LICENSE Lib/_abcoll.py Lib/abc.py Lib/argparse.py Lib/asyncore.py Lib/base64.py Lib/bdb.py Lib/cProfile.py Lib/cgi.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/dis.py Lib/distutils/__init__.py Lib/distutils/command/bdist_msi.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/sdist.py Lib/distutils/sysconfig.py Lib/distutils/tests/test_log.py Lib/distutils/tests/test_sdist.py Lib/distutils/tests/test_sysconfig.py Lib/doctest.py Lib/email/_parseaddr.py Lib/email/base64mime.py Lib/email/header.py Lib/email/message.py Lib/email/test/test_email.py Lib/encodings/aliases.py Lib/fileinput.py Lib/fnmatch.py Lib/ftplib.py Lib/functools.py Lib/getopt.py Lib/gzip.py Lib/hmac.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/_bootstrap.py Lib/importlib/abc.py Lib/importlib/test/source/test_file_loader.py Lib/inspect.py Lib/json/__init__.py Lib/json/decoder.py Lib/json/encoder.py Lib/lib2to3 Lib/lib2to3/fixer_util.py Lib/lib2to3/fixes/fix_itertools_imports.py Lib/lib2to3/fixes/fix_operator.py Lib/lib2to3/fixes/fix_urllib.py Lib/lib2to3/pytree.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_pytree.py Lib/lib2to3/tests/test_util.py Lib/logging/__init__.py Lib/logging/config.py Lib/logging/handlers.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.py Lib/pickle.py Lib/pickletools.py Lib/platform.py Lib/poplib.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/ssl.py Lib/string.py Lib/subprocess.py Lib/sysconfig.py Lib/test/cfgparser.2 Lib/test/cfgparser.3 Lib/test/data/README Lib/test/datetimetester.py Lib/test/formatfloat_testcases.txt Lib/test/mock_socket.py Lib/test/regrtest.py Lib/test/script_helper.py Lib/test/sortperf.py Lib/test/support.py Lib/test/test_SimpleHTTPServer.py Lib/test/test_abc.py Lib/test/test_argparse.py Lib/test/test_asyncore.py Lib/test/test_binascii.py Lib/test/test_binop.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_bz2.py Lib/test/test_calendar.py Lib/test/test_cfgparser.py Lib/test/test_cmd.py Lib/test/test_cmd_line.py Lib/test/test_cmd_line_script.py Lib/test/test_collections.py Lib/test/test_complex.py Lib/test/test_curses.py Lib/test/test_datetime.py Lib/test/test_dis.py Lib/test/test_doctest.py Lib/test/test_fileinput.py Lib/test/test_float.py Lib/test/test_fnmatch.py Lib/test/test_ftplib.py Lib/test/test_functools.py Lib/test/test_gc.py Lib/test/test_genericpath.py Lib/test/test_getopt.py Lib/test/test_gzip.py Lib/test/test_http_cookies.py Lib/test/test_httplib.py Lib/test/test_httpservers.py Lib/test/test_imp.py Lib/test/test_import.py Lib/test/test_io.py Lib/test/test_ioctl.py Lib/test/test_line_tracing.py Lib/test/test_logging.py Lib/test/test_minidom.py Lib/test/test_mmap.py Lib/test/test_multiprocessing.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_pep277.py Lib/test/test_platform.py Lib/test/test_poplib.py Lib/test/test_posix.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_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_socket.py Lib/test/test_ssl.py Lib/test/test_strtod.py Lib/test/test_struct.py Lib/test/test_subprocess.py Lib/test/test_sunau.py Lib/test/test_sundry.py Lib/test/test_syntax.py Lib/test/test_sys.py Lib/test/test_sys_setprofile.py Lib/test/test_sys_settrace.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_types.py Lib/test/test_unicode.py Lib/test/test_unicode_file.py Lib/test/test_unicodedata.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urllib2_localnet.py Lib/test/test_urllib2net.py Lib/test/test_urlparse.py Lib/test/test_winsound.py Lib/test/test_xml_etree.py Lib/test/test_zipfile.py Lib/test/test_zipimport.py Lib/threading.py Lib/timeit.py Lib/tkinter/__main__.py Lib/trace.py Lib/urllib/parse.py Lib/urllib/request.py Lib/urllib/robotparser.py Lib/xml/dom/minidom.py Lib/xml/etree/ElementInclude.py Lib/xml/etree/ElementTree.py Lib/xmlrpc/client.py Lib/zipfile.py Makefile.pre.in Misc/ACKS Misc/NEWS Misc/README Misc/RPM/python-3.2.spec Misc/developers.txt Misc/maintainers.rst Misc/python-wing.wpr Modules/Setup.dist Modules/_collectionsmodule.c Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/libffi/fficonfig.py.in Modules/_ctypes/libffi_msvc/ffi.c Modules/_ctypes/libffi_msvc/ffi.h Modules/_ctypes/malloc_closure.c Modules/_cursesmodule.c Modules/_datetimemodule.c Modules/_elementtree.c Modules/_functoolsmodule.c Modules/_hashopenssl.c Modules/_io/bufferedio.c Modules/_json.c Modules/_localemodule.c Modules/_randommodule.c Modules/_ssl.c Modules/_struct.c Modules/_threadmodule.c Modules/_time.c Modules/_time.h Modules/arraymodule.c Modules/binascii.c Modules/bz2module.c Modules/datetimemodule.c Modules/errnomodule.c Modules/gcmodule.c Modules/getpath.c Modules/main.c Modules/mmapmodule.c Modules/nismodule.c Modules/posixmodule.c Modules/pwdmodule.c Modules/pyexpat.c Modules/readline.c Modules/selectmodule.c Modules/sha1module.c Modules/signalmodule.c Modules/socketmodule.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/abstract.c Objects/bytearrayobject.c Objects/bytes_methods.c Objects/bytesobject.c Objects/capsule.c Objects/complexobject.c Objects/fileobject.c Objects/floatobject.c Objects/iterobject.c Objects/listobject.c Objects/memoryobject.c Objects/moduleobject.c Objects/object.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/fastsearch.h Objects/stringlib/formatter.h Objects/typeobject.c Objects/unicodectype.c Objects/unicodeobject.c Objects/unicodetype_db.h PC/VS8.0/pythoncore.vcproj PC/_subprocess.c PC/config.c PC/msvcrtmodule.c PC/pyconfig.h PC/python_nt.rc PC/winreg.c PCbuild/build_ssl.py PCbuild/pyproject.vsprops PCbuild/pythoncore.vcproj PCbuild/readme.txt Parser Python/_warnings.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/ceval_gil.h Python/getargs.c Python/getcopyright.c Python/getversion.c Python/import.c Python/modsupport.c Python/peephole.c Python/pythonrun.c Python/pytime.c Python/sysmodule.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/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/2to3 Tools/scripts/README Tools/scripts/byext.py Tools/scripts/checkappend.py Tools/scripts/checkpyc.py Tools/scripts/classfix.py Tools/scripts/cvsfiles.py Tools/scripts/logmerge.py Tools/scripts/methfix.py Tools/scripts/patchcheck.py Tools/scripts/reindent-rst.py Tools/scripts/reindent.py Tools/scripts/rgrep.py Tools/scripts/serve.py Tools/scripts/setup.py Tools/scripts/suff.py Tools/scripts/svneol.py Tools/scripts/untabify.py Tools/scripts/win_add2path.py Tools/scripts/xxci.py Tools/unicode/makeunicodedata.py Tools/versioncheck configure configure.in pyconfig.h.in setup.py

martin.v.loewis python-checkins at python.org
Fri Aug 27 21:11:18 CEST 2010


Author: martin.v.loewis
Date: Fri Aug 27 21:11:11 2010
New Revision: 84330

Log:
Merged revisions 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,83816,83818,83822,83828-83830,83833-83835,83837-83839,83841,83845-83846,83851,83854,83859-83864,83869-83872,83874-83878,83880,83882,83885-83892,83894-83895,83900-83901,83908,83918,83921,83927,83932-83933,83936-83937,83939,83943-83944,83947-83949,83951,83959-83960,83966,83971-83983,83986-83991,83993,83998-84001,84005-84009,84011-84013,84015-84026,84028,84030,84032,84035-84036,84038-84039,84043,84045,84047,84050,84054,84056-84060,84062-84063,84065,84067-84070,84072,84074,84076,84078,84080-84086,84088-84089,84092,84094-84099,84105-84106,84109,84111-84113,84120-84126,84129-84134,84137-84147,84149-84150,84153-84157,84159,84162-84168,84170-84173,84176-84177,84179-84189,84191,84193-84195,84199-84206,84208-84210,84212,84214,84218,84221-84229,84231,84234,84236-84239,84242-84244,84247-84249,84252,84256-84265,84267-84268,84270-84271,84277-84279,84281-84284,84287-84289,84294-84295,84299,84301,84303-84304,84306-84310,84313-84317,84319-84320,84323,84326-84327,84329 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/branches/py3k

................
  r83065 | georg.brandl | 2010-07-23 10:46:35 +0200 (Fr, 23 Jul 2010) | 1 line
  
  Use augassign.
................
  r83066 | ronald.oussoren | 2010-07-23 11:43:17 +0200 (Fr, 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 11:50:05 +0200 (Fr, 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 13:31:31 +0200 (Fr, 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 13:48:36 +0200 (Fr, 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 13:54:59 +0200 (Fr, 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 14:16:41 +0200 (Fr, 23 Jul 2010) | 3 lines
  
  Issue #6095: Make directory argument to os.listdir optional.
  Patch by Virgil Dupras.
................
  r83080 | brett.cannon | 2010-07-23 14:26:35 +0200 (Fr, 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 15:53:51 +0200 (Fr, 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 15:54:14 +0200 (Fr, 23 Jul 2010) | 4 lines
  
  Test calendar.monthrange.
  
  Closes issue 9342. Thanks John Chandler for the patch.
................
  r83090 | brett.cannon | 2010-07-23 16:03:16 +0200 (Fr, 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 16:45:19 +0200 (Fr, 23 Jul 2010) | 1 line
  
  Stop shadowing a test class.
................
  r83092 | brett.cannon | 2010-07-23 17:43:14 +0200 (Fr, 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 17:50:02 +0200 (Fr, 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 17:50:52 +0200 (Fr, 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 18:05:35 +0200 (Fr, 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 18:20:40 +0200 (Fr, 23 Jul 2010) | 2 lines
  
  New tests for smtpd module. Has full coverage for SMTPChannel and SMTPServer.
................
  r83100 | brett.cannon | 2010-07-23 18:22:25 +0200 (Fr, 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 18:23:13 +0200 (Fr, 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 18:30:10 +0200 (Fr, 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 18:48:22 +0200 (Fr, 23 Jul 2010) | 1 line
  
  #9359: fix typo. Thanks to Piotr Kasprzyk for the patch.
................
  r83106 | georg.brandl | 2010-07-23 18:55:26 +0200 (Fr, 23 Jul 2010) | 1 line
  
  Fix some markup glitches.
................
  r83107 | georg.brandl | 2010-07-23 18:55:42 +0200 (Fr, 23 Jul 2010) | 1 line
  
  Update to 1.0.
................
  r83108 | brett.cannon | 2010-07-23 18:56:21 +0200 (Fr, 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 18:58:21 +0200 (Fr, 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 18:58:57 +0200 (Fr, 23 Jul 2010) | 2 lines
  
  Add Brian Brazil.
................
  r83112 | alexander.belopolsky | 2010-07-23 21:25:47 +0200 (Fr, 23 Jul 2010) | 2 lines
  
  Issue #7989: Added pure python implementation of the datetime module.
................
  r83115 | alexander.belopolsky | 2010-07-23 22:03:53 +0200 (Fr, 23 Jul 2010) | 1 line
  
  Use _datetime docstring if _datetime is available.
................
  r83116 | victor.stinner | 2010-07-24 02:49:20 +0200 (Sa, 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 04:24:55 +0200 (Sa, 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 11:51:40 +0200 (Sa, 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 12:09:11 +0200 (Sa, 24 Jul 2010) | 2 lines
  
  Put listdir default argument into declaration.
................
  r83133 | ronald.oussoren | 2010-07-24 16:15:19 +0200 (Sa, 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 16:58:54 +0200 (So, 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 17:02:55 +0200 (So, 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 17:05:42 +0200 (So, 25 Jul 2010) | 1 line
  
  Corrected comments on where settrace and setprofile are tested.
................
  r83149 | andrew.kuchling | 2010-07-26 00:57:12 +0200 (Mo, 26 Jul 2010) | 1 line
  
  #1495229: update the type names used by the XML DOM mapping
................
  r83150 | michael.foord | 2010-07-26 01:09:25 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Issue #4686 - add .args to exceptions in the configparsermodule
................
  r83151 | andrew.kuchling | 2010-07-26 01:23:30 +0200 (Mo, 26 Jul 2010) | 1 line
  
  #7637: clarify description of encoding parameter
................
  r83152 | andrew.kuchling | 2010-07-26 01:38:47 +0200 (Mo, 26 Jul 2010) | 1 line
  
  #777884: make .normalize() do nothing for childless nodes, instead of raising an exception
................
  r83154 | brian.curtin | 2010-07-26 02:27:10 +0200 (Mo, 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 04:36:32 +0200 (Mo, 26 Jul 2010) | 2 lines
  
  Add note about #7113 and add Łukasz Langa to ACKS
................
  r83157 | alexander.belopolsky | 2010-07-26 04:36:41 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Make python version of fromtimestamp behave more like C.
................
  r83160 | georg.brandl | 2010-07-26 10:51:42 +0200 (Mo, 26 Jul 2010) | 1 line
  
  #9381: fix markup.
................
  r83161 | georg.brandl | 2010-07-26 11:33:12 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Add Brian Quinlan.
................
  r83162 | andrew.kuchling | 2010-07-26 14:54:02 +0200 (Mo, 26 Jul 2010) | 1 line
  
  #7637: fix a grammar error; simplify a sentence
................
  r83163 | andrew.kuchling | 2010-07-26 15:08:58 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Reword paragraph
................
  r83166 | georg.brandl | 2010-07-26 17:11:49 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Fix grammar.
................
  r83168 | georg.brandl | 2010-07-26 19:00:20 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Fix indentation in example.
................
  r83169 | georg.brandl | 2010-07-26 19:09:32 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Add Reid.
................
  r83170 | alexander.belopolsky | 2010-07-26 20:27:49 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Added versionadded entry for the annotate argument.
................
  r83171 | georg.brandl | 2010-07-26 23:12:13 +0200 (Mo, 26 Jul 2010) | 1 line
  
  Clarify.
................
  r83173 | gregory.p.smith | 2010-07-27 07:31:29 +0200 (Di, 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 16:16:32 +0200 (Di, 27 Jul 2010) | 1 line
  
  Issue #9384: python -m tkinter will now display a simple demo applet.
................
  r83181 | georg.brandl | 2010-07-27 20:19:21 +0200 (Di, 27 Jul 2010) | 1 line
  
  Update Sphinx to 1.0.1.
................
  r83182 | florent.xicluna | 2010-07-27 23:20:15 +0200 (Di, 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-28 00:03:33 +0200 (Mi, 28 Jul 2010) | 1 line
  
  Use proper skips and assert* methods in test_asyncore.
................
  r83184 | antoine.pitrou | 2010-07-28 00:08:27 +0200 (Mi, 28 Jul 2010) | 3 lines
  
  Issue #9294: remove dead code in Objects/object.c.  Patch by Grant Limberg.
................
  r83186 | ezio.melotti | 2010-07-28 00:24:13 +0200 (Mi, 28 Jul 2010) | 1 line
  
  With skipUnless there is no need to add test classes conditionally.
................
  r83188 | alexander.belopolsky | 2010-07-28 01:02:38 +0200 (Mi, 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 01:36:41 +0200 (Mi, 28 Jul 2010) | 2 lines
  
  Fix ctypes tests to avoid implicit bytes-unicode conversion
................
  r83195 | victor.stinner | 2010-07-28 02:15:03 +0200 (Mi, 28 Jul 2010) | 2 lines
  
  Issue #8966: ctypes: Remove implicit bytes-unicode conversion
................
  r83196 | ezio.melotti | 2010-07-28 02:23:21 +0200 (Mi, 28 Jul 2010) | 1 line
  
  Fix failure introduced in r83182.
................
  r83197 | victor.stinner | 2010-07-28 02:40:58 +0200 (Mi, 28 Jul 2010) | 2 lines
  
  Issue #8991: convertbuffer() rejects discontigious buffers
................
  r83201 | georg.brandl | 2010-07-28 10:19:35 +0200 (Mi, 28 Jul 2010) | 1 line
  
  #9354: Provide getsockopt() in asyncore file_wrapper().  Patch by Lukas Langa.
................
  r83202 | georg.brandl | 2010-07-28 15:13:46 +0200 (Mi, 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 18:27:56 +0200 (Mi, 28 Jul 2010) | 3 lines
  
  Fix Issue6325 - robotparse to honor urls with query strings.
................
  r83212 | florent.xicluna | 2010-07-28 18:39:41 +0200 (Mi, 28 Jul 2010) | 2 lines
  
  Syntax cleanup.
................
  r83213 | georg.brandl | 2010-07-28 19:37:27 +0200 (Mi, 28 Jul 2010) | 1 line
  
  Add missing file.
................
  r83214 | victor.stinner | 2010-07-28 23:23:23 +0200 (Mi, 28 Jul 2010) | 2 lines
  
  #9283: Fix repr(os.environ), display unicode keys and values on POSIX systems
................
  r83215 | victor.stinner | 2010-07-28 23:25:42 +0200 (Mi, 28 Jul 2010) | 2 lines
  
  Issue #9283: Oops, add missing { and } to repr(os.environ)
................
  r83216 | victor.stinner | 2010-07-29 02:29:00 +0200 (Do, 29 Jul 2010) | 2 lines
  
  Update test_os.py according to my last changes on _Environ.__repr__()
................
  r83217 | georg.brandl | 2010-07-29 13:15:36 +0200 (Do, 29 Jul 2010) | 1 line
  
  Remove Python 1.5 compatibility note.
................
  r83218 | georg.brandl | 2010-07-29 13:49:05 +0200 (Do, 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 13:56:20 +0200 (Do, 29 Jul 2010) | 1 line
  
  Fix for r83202: improve the handling of empty lines.
................
  r83220 | georg.brandl | 2010-07-29 14:17:40 +0200 (Do, 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 15:19:42 +0200 (Do, 29 Jul 2010) | 1 line
  
  Fix #9412: make list of messages an instance attribute instead of class attribute.
................
  r83223 | georg.brandl | 2010-07-29 15:38:37 +0200 (Do, 29 Jul 2010) | 1 line
  
  #3874: document HTMLParser.unknown_decl().
................
  r83224 | mark.dickinson | 2010-07-29 15:56:56 +0200 (Do, 29 Jul 2010) | 1 line
  
  Fix typo.
................
  r83226 | georg.brandl | 2010-07-29 16:17:12 +0200 (Do, 29 Jul 2010) | 1 line
  
  #1090076: explain the behavior of *vars* in get() better.
................
  r83227 | georg.brandl | 2010-07-29 16:23:06 +0200 (Do, 29 Jul 2010) | 1 line
  
  Use Py_CLEAR().
................
  r83229 | georg.brandl | 2010-07-29 16:32:22 +0200 (Do, 29 Jul 2010) | 1 line
  
  #9407: document configparser.Error.
................
  r83230 | georg.brandl | 2010-07-29 16:36:11 +0200 (Do, 29 Jul 2010) | 1 line
  
  Use correct directive and name.
................
  r83231 | georg.brandl | 2010-07-29 16:46:07 +0200 (Do, 29 Jul 2010) | 1 line
  
  #9397: remove mention of dbm.bsd which does not exist anymore.
................
  r83232 | georg.brandl | 2010-07-29 16:49:08 +0200 (Do, 29 Jul 2010) | 1 line
  
  #9388: remove ERA_YEAR which is never defined in the source code.
................
  r83234 | georg.brandl | 2010-07-29 18:01:11 +0200 (Do, 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 18:26:56 +0200 (Do, 29 Jul 2010) | 2 lines
  
  #9397: remove mention of dbm.bsd which does not exist anymore.
................
  r83236 | georg.brandl | 2010-07-29 19:16:10 +0200 (Do, 29 Jul 2010) | 1 line
  
  #6630: allow customizing flags for compiling string.Template.idpattern.
................
  r83237 | victor.stinner | 2010-07-29 19:19:38 +0200 (Do, 29 Jul 2010) | 2 lines
  
  #8603: Add environb to os.__all__
................
  r83238 | georg.brandl | 2010-07-29 19:55:01 +0200 (Do, 29 Jul 2010) | 1 line
  
  #4108: the first default entry (User-agent: *) wins.
................
  r83239 | mark.dickinson | 2010-07-29 23:41:59 +0200 (Do, 29 Jul 2010) | 2 lines
  
  Issue #9422:  Fix memory leak when re-initializing a struct.Struct object.
................
  r83259 | georg.brandl | 2010-07-30 09:03:39 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Clarification.
................
  r83260 | georg.brandl | 2010-07-30 09:14:01 +0200 (Fr, 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 09:21:26 +0200 (Fr, 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 10:29:39 +0200 (Fr, 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 10:43:32 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Allow giving an explicit line number to "until".
................
  r83264 | georg.brandl | 2010-07-30 10:45:26 +0200 (Fr, 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 10:54:49 +0200 (Fr, 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 11:14:20 +0200 (Fr, 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 11:23:23 +0200 (Fr, 30 Jul 2010) | 2 lines
  
  Issue #8048: Prevent doctests from failing when sys.displayhook has
  been reassigned.
................
  r83269 | georg.brandl | 2010-07-30 11:43:00 +0200 (Fr, 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 11:54:44 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Remove redundant import.
................
  r83271 | georg.brandl | 2010-07-30 11:59:28 +0200 (Fr, 30 Jul 2010) | 1 line
  
  #5727: Restore the ability to use readline when calling into pdb in doctests.
................
  r83272 | georg.brandl | 2010-07-30 12:29:19 +0200 (Fr, 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 13:31:03 +0200 (Fr, 30 Jul 2010) | 1 line
  
  #3143: enable "collapsible sidebar" feature of new Sphinx version.
................
  r83275 | georg.brandl | 2010-07-30 14:01:20 +0200 (Fr, 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 15:13:02 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Add note about surprising behaviour from round function.
................
  r83281 | georg.brandl | 2010-07-30 15:36:43 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Add myself for pdb.
................
  r83283 | georg.brandl | 2010-07-30 16:16:43 +0200 (Fr, 30 Jul 2010) | 1 line
  
  #7964 followup: add test case to ensure issue remains fixed.
................
  r83284 | georg.brandl | 2010-07-30 17:01:23 +0200 (Fr, 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 17:33:52 +0200 (Fr, 30 Jul 2010) | 1 line
  
  pdb now has its own tests.
................
  r83286 | georg.brandl | 2010-07-30 18:00:46 +0200 (Fr, 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 19:04:28 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Add "longlist" and "source" commands, ideas borrowed from pdb++ by Antonio Cuni.
................
  r83288 | martin.v.loewis | 2010-07-30 19:29:39 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Drop 2.4 support. Add disabled algorithms to Configure options.
................
  r83289 | martin.v.loewis | 2010-07-30 19:30:51 +0200 (Fr, 30 Jul 2010) | 2 lines
  
  Use OpenSSL 1.0.0a on Windows.
................
  r83291 | georg.brandl | 2010-07-30 20:08:12 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Fix source finding if the given frame is a module-level frame.
................
  r83292 | georg.brandl | 2010-07-30 20:15:16 +0200 (Fr, 30 Jul 2010) | 1 line
  
  Test that "source" with nonexisting things works as expected.
................
  r83293 | georg.brandl | 2010-07-30 20:46:38 +0200 (Fr, 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 21:34:36 +0200 (Fr, 30 Jul 2010) | 2 lines
  
  Fix issue9301 - handle unquote({}) kind of case.
................
  r83296 | martin.v.loewis | 2010-07-30 22:03:17 +0200 (Fr, 30 Jul 2010) | 2 lines
  
  Import files from zlib 1.2.5.
................
  r83307 | matthias.klose | 2010-07-30 23:40:57 +0200 (Fr, 30 Jul 2010) | 2 lines
  
  - Issue #7567: PyCurses_setupterm: Don't call `setupterm' twice.
................
  r83308 | georg.brandl | 2010-07-31 00:20:16 +0200 (Sa, 31 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 09:12:50 +0200 (Sa, 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 10:14:16 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Fix pdb test failures on the buildbots.
................
  r83316 | georg.brandl | 2010-07-31 10:20:02 +0200 (Sa, 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 10:27:46 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Update pydoc topics and adapt Topics builder to Sphinx 1.0.
................
  r83318 | georg.brandl | 2010-07-31 10:56:11 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Bump versions and review NEWS file.
................
  r83319 | florent.xicluna | 2010-07-31 10:56:55 +0200 (Sa, 31 Jul 2010) | 2 lines
  
  Fix an oversight in r83294.  unquote() should reject bytes.  Issue #9301.
................
  r83320 | georg.brandl | 2010-07-31 11:01:16 +0200 (Sa, 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 11:03:30 +0200 (Sa, 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 11:10:51 +0200 (Sa, 31 Jul 2010) | 1 line
  
  reverted distutils doc to its 3.1 state
................
  r83323 | georg.brandl | 2010-07-31 11:15:10 +0200 (Sa, 31 Jul 2010) | 1 line
  
  After distutils doc reversal, change back **bold todo** items to XXX comments.
................
  r83324 | martin.v.loewis | 2010-07-31 11:21:51 +0200 (Sa, 31 Jul 2010) | 2 lines
  
  Update OpenSSL version.
................
  r83325 | georg.brandl | 2010-07-31 11:37:03 +0200 (Sa, 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 12:08:09 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Avoid triggering DeprecationWarnings in test_smtpd and smtpd.
................
  r83327 | raymond.hettinger | 2010-07-31 12:11:39 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Add functools.lfu_cache() and functools.lru_cache().
................
  r83328 | raymond.hettinger | 2010-07-31 12:14:41 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Document how to change OrderedDict update order from first to last.
................
  r83329 | georg.brandl | 2010-07-31 12:16:21 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Revert r83327.  This will have to wait until after the alpha1 release.
................
  r83335 | martin.v.loewis | 2010-07-31 12:49:53 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Copy asm files into place.
................
  r83336 | martin.v.loewis | 2010-07-31 12:50:16 +0200 (Sa, 31 Jul 2010) | 2 lines
  
  Delete openssl checkouts.
................
  r83337 | victor.stinner | 2010-07-31 12:52:56 +0200 (Sa, 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 12:56:53 +0200 (Sa, 31 Jul 2010) | 2 lines
  
  Truly uncomment rm lines.
................
  r83339 | georg.brandl | 2010-07-31 13:00:47 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Rewrap.
................
  r83341 | georg.brandl | 2010-07-31 13:40:07 +0200 (Sa, 31 Jul 2010) | 1 line
  
  #9430: document timedelta str() and repr().
................
  r83342 | georg.brandl | 2010-07-31 13:52:46 +0200 (Sa, 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 14:06:51 +0200 (Sa, 31 Jul 2010) | 1 line
  
  From Martin: New UUIDs for the 3.2 release series.
................
  r83348 | georg.brandl | 2010-07-31 20:05:35 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Post-release updates.
................
  r83349 | antoine.pitrou | 2010-07-31 20:08:33 +0200 (Sa, 31 Jul 2010) | 3 lines
  
  Add ssl changes to the 3.2 "what's new".
................
  r83350 | georg.brandl | 2010-07-31 20:09:23 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Re-commit r83327 now that the release is done.
................
  r83351 | georg.brandl | 2010-07-31 20:09:46 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Move news item to the correct position.
................
  r83352 | georg.brandl | 2010-07-31 20:11:07 +0200 (Sa, 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 20:59:20 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Drop webchecker and BerkeleyDB license.
................
  r83355 | georg.brandl | 2010-07-31 21:17:11 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Fix bad merge: test_support -> support.
................
  r83356 | georg.brandl | 2010-07-31 21:29:15 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Remove trailing whitespace.
................
  r83357 | georg.brandl | 2010-07-31 21:59:55 +0200 (Sa, 31 Jul 2010) | 1 line
  
  #5778: document that sys.version can contain a newline.
................
  r83358 | georg.brandl | 2010-07-31 22:05:31 +0200 (Sa, 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 22:08:15 +0200 (Sa, 31 Jul 2010) | 1 line
  
  #1286: allow using fileinput.FileInput as context manager.
................
  r83360 | georg.brandl | 2010-07-31 22:13:44 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Clarify comment in comments test case explaining comment semantics.
................
  r83361 | georg.brandl | 2010-07-31 23:04:00 +0200 (Sa, 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 23:12:15 +0200 (Sa, 31 Jul 2010) | 1 line
  
  #8910: add a file explaining why Lib/test/data is there.
................
  r83366 | georg.brandl | 2010-07-31 23:26:40 +0200 (Sa, 31 Jul 2010) | 1 line
  
  There always is a False and True now.
................
  r83368 | georg.brandl | 2010-07-31 23:40:15 +0200 (Sa, 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 23:41:42 +0200 (Sa, 31 Jul 2010) | 1 line
  
  Fix "Berkeley" name.
................
  r83370 | georg.brandl | 2010-07-31 23:51:48 +0200 (Sa, 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 23:54:24 +0200 (Sa, 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-08-01 00:05:54 +0200 (So, 01 Aug 2010) | 1 line
  
  #4007: remove *.a and *.so.X.Y files in "make clean".
................
  r83373 | georg.brandl | 2010-08-01 00:11:11 +0200 (So, 01 Aug 2010) | 1 line
  
  #5147: revert accidental indentation of header constant for MozillaCookieJar.
................
  r83374 | georg.brandl | 2010-08-01 00:32:52 +0200 (So, 01 Aug 2010) | 1 line
  
  #5146: handle UID THREAD command correctly.
................
  r83375 | antoine.pitrou | 2010-08-01 00:48:02 +0200 (So, 01 Aug 2010) | 3 lines
  
  Reorder entries by module lexicographic order
................
  r83376 | raymond.hettinger | 2010-08-01 01:33:22 +0200 (So, 01 Aug 2010) | 1 line
  
  Fix build on VS8.
................
  r83380 | r.david.murray | 2010-08-01 05:31:09 +0200 (So, 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 08:32:55 +0200 (So, 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 08:42:45 +0200 (So, 01 Aug 2010) | 1 line
  
  #8773: mailbox.py does not need to be executable.
................
  r83386 | georg.brandl | 2010-08-01 08:44:46 +0200 (So, 01 Aug 2010) | 1 line
  
  #8768: name test method properly so that it gets executed.
................
  r83387 | georg.brandl | 2010-08-01 08:53:28 +0200 (So, 01 Aug 2010) | 1 line
  
  #8735: better explain semantics of *values* argument for parse().
................
  r83388 | georg.brandl | 2010-08-01 09:48:43 +0200 (So, 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 09:57:47 +0200 (So, 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 10:07:49 +0200 (So, 01 Aug 2010) | 1 line
  
  #8230: make Lib/test/sortperf.py run on Python 3.
................
  r83391 | georg.brandl | 2010-08-01 10:10:08 +0200 (So, 01 Aug 2010) | 1 line
  
  Add another news entry.
................
  r83393 | georg.brandl | 2010-08-01 10:35:29 +0200 (So, 01 Aug 2010) | 1 line
  
  #1690103: fix initial namespace for code run with trace.main().
................
  r83394 | georg.brandl | 2010-08-01 10:46:24 +0200 (So, 01 Aug 2010) | 1 line
  
  No need to split this, there are enough long lines.
................
  r83395 | georg.brandl | 2010-08-01 10:49:18 +0200 (So, 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 10:52:32 +0200 (So, 01 Aug 2010) | 1 line
  
  #4810: document "--" option separator in timeit help.
................
  r83397 | ronald.oussoren | 2010-08-01 11:02:50 +0200 (So, 01 Aug 2010) | 1 line
  
  Ensure that test_site actually passes with a framework build
................
  r83398 | georg.brandl | 2010-08-01 11:06:34 +0200 (So, 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 11:17:53 +0200 (So, 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 12:41:49 +0200 (So, 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 13:10:28 +0200 (So, 01 Aug 2010) | 1 line
  
  Add test for memory leak reported in issue 9422.
................
  r83404 | georg.brandl | 2010-08-01 16:25:22 +0200 (So, 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 16:38:17 +0200 (So, 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 16:50:00 +0200 (So, 01 Aug 2010) | 1 line
  
  #8046: add context manager protocol support to mmap objects.  Also add closed property.
................
  r83407 | brian.curtin | 2010-08-01 17:26:26 +0200 (So, 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 17:30:56 +0200 (So, 01 Aug 2010) | 1 line
  
  #5551: symbolic links never can be mount points.  Fixes the fix for #1713.
................
  r83411 | antoine.pitrou | 2010-08-01 18:53:42 +0200 (So, 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 19:53:37 +0200 (So, 01 Aug 2010) | 3 lines
  
  Fix Issue8123 - TypeError in urllib when trying to use HTTP authentication
................
  r83417 | georg.brandl | 2010-08-01 20:38:26 +0200 (So, 01 Aug 2010) | 1 line
  
  #5776: fix mistakes in python specfile.  (Nobody probably uses it anyway.)
................
  r83431 | ronald.oussoren | 2010-08-01 21:18:13 +0200 (So, 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 22:08:46 +0200 (So, 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 22:51:02 +0200 (So, 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 23:10:35 +0200 (So, 01 Aug 2010) | 1 line
  
  Issue 9445: Fix undefined symbols on VS8.0 build.
................
  r83479 | mark.dickinson | 2010-08-01 23:33:01 +0200 (So, 01 Aug 2010) | 1 line
  
  Don't delete Lib/test/data/README when doing 'make distclean'
................
  r83488 | raymond.hettinger | 2010-08-01 23:50:38 +0200 (So, 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-02 00:10:57 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Update OrderedDict implementation to match that in Py2.7.
................
  r83501 | georg.brandl | 2010-08-02 00:31:05 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Fix style of referring to issues.
................
  r83506 | r.david.murray | 2010-08-02 01:43:28 +0200 (Mo, 02 Aug 2010) | 2 lines
  
  Fix ACKS alphabetization.
................
  r83513 | raymond.hettinger | 2010-08-02 02:59:14 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Add example applications for the LRU and LFU cache docs.
................
  r83516 | raymond.hettinger | 2010-08-02 03:43:41 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Demonstrate the caching decorators in whatsnew.
................
  r83521 | senthil.kumaran | 2010-08-02 13:04:58 +0200 (Mo, 02 Aug 2010) | 3 lines
  
  Fix Issue8572  - httplib getheader() throws error instead of default
................
  r83523 | georg.brandl | 2010-08-02 14:06:18 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9209 and #7781: fix two crashes in pstats interactive browser.
................
  r83524 | georg.brandl | 2010-08-02 14:20:23 +0200 (Mo, 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 14:36:24 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Get rid of spurious "threading" entries in trace output.
................
  r83526 | georg.brandl | 2010-08-02 14:40:22 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Fix softspace relic.
................
  r83527 | georg.brandl | 2010-08-02 14:48:46 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #3821: beginnings of a trace.py unittest.
................
  r83528 | georg.brandl | 2010-08-02 14:54:24 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Document how to refer to decorators and decorator methods.
................
  r83529 | senthil.kumaran | 2010-08-02 19:09:02 +0200 (Mo, 02 Aug 2010) | 3 lines
  
  Rewording the getheader method of HTTPResponse.
................
  r83531 | georg.brandl | 2010-08-02 19:24:49 +0200 (Mo, 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 19:49:25 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #8578: mention danger of not incref'ing weak referenced object.
................
  r83538 | georg.brandl | 2010-08-02 20:10:13 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #6928: fix class docs w.r.t. new metaclasses.
................
  r83542 | georg.brandl | 2010-08-02 20:56:54 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Move test_SimpleHTTPServer into test_httpservers.
................
  r83543 | georg.brandl | 2010-08-02 20:59:52 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #8560: add progress indicator to regrtest.
................
  r83546 | georg.brandl | 2010-08-02 21:16:34 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #7973: Fix distutils options spelling.
................
  r83547 | georg.brandl | 2010-08-02 21:19:26 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #7386: add example that shows that trailing path separators are stripped.
................
  r83548 | georg.brandl | 2010-08-02 21:23:34 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #8172: how does one use a property?
................
  r83550 | georg.brandl | 2010-08-02 21:32:43 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9451: strengthen warning about __*__ special name usage.
................
  r83551 | georg.brandl | 2010-08-02 21:35:06 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Remove XXX comment that was displayed.
................
  r83552 | georg.brandl | 2010-08-02 21:36:36 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9438: clarify that constant names also cannot be assigned as attributes.
................
  r83553 | georg.brandl | 2010-08-02 21:39:17 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Remove redundant information.
................
  r83554 | georg.brandl | 2010-08-02 21:43:05 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #7280: note about nasmw.exe.
................
  r83555 | georg.brandl | 2010-08-02 21:44:48 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #8861: remove unused variable.
................
  r83558 | georg.brandl | 2010-08-02 22:05:19 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #8648: document UTF-7 codec functions.
................
  r83560 | georg.brandl | 2010-08-02 22:16:18 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9087: update json docstrings -- unicode and long do not exist anymore.
................
  r83561 | georg.brandl | 2010-08-02 22:17:50 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #4280: remove outdated "versionchecker" tool.
................
  r83563 | georg.brandl | 2010-08-02 22:21:21 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9037: add example how to raise custom exceptions from C code.
................
  r83565 | georg.brandl | 2010-08-02 22:27:20 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9111: document that do_help() looks at docstrings.
................
  r83566 | georg.brandl | 2010-08-02 22:30:57 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9019: remove false (in 3k) claim about Headers updates.
................
  r83569 | georg.brandl | 2010-08-02 22:39:35 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #7797: be explicit about bytes-oriented interface of base64 functions.
................
  r83571 | georg.brandl | 2010-08-02 22:44:34 +0200 (Mo, 02 Aug 2010) | 1 line
  
  Clarify that abs() is not a namespace.
................
  r83574 | georg.brandl | 2010-08-02 22:47:56 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #6867: epoll.register() returns None.
................
  r83575 | georg.brandl | 2010-08-02 22:52:10 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9238: zipfile does handle archive comments.
................
  r83580 | georg.brandl | 2010-08-02 23:02:36 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #8119: fix copy-paste error.
................
  r83584 | georg.brandl | 2010-08-02 23:07:14 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9457: fix documentation links for 3.2.
................
  r83599 | georg.brandl | 2010-08-02 23:51:18 +0200 (Mo, 02 Aug 2010) | 1 line
  
  #9061: warn that single quotes are never escaped.
................
  r83605 | georg.brandl | 2010-08-03 00:08:58 +0200 (Di, 03 Aug 2010) | 1 line
  
  Make the Pynche tool work with Python 3.
................
  r83606 | georg.brandl | 2010-08-03 00:25:16 +0200 (Di, 03 Aug 2010) | 1 line
  
  Minimum fixes to make freeze.py do something useful.
................
  r83607 | georg.brandl | 2010-08-03 00:28:01 +0200 (Di, 03 Aug 2010) | 1 line
  
  Remove faqwiz tool.
................
  r83608 | georg.brandl | 2010-08-03 00:31:22 +0200 (Di, 03 Aug 2010) | 1 line
  
  Update README for Tools.
................
  r83609 | georg.brandl | 2010-08-03 00:53:22 +0200 (Di, 03 Aug 2010) | 1 line
  
  Update README, remove obsolete scripts.
................
  r83610 | georg.brandl | 2010-08-03 00:55:17 +0200 (Di, 03 Aug 2010) | 1 line
  
  Update README, remove obsolete script.
................
  r83611 | georg.brandl | 2010-08-03 00:58:25 +0200 (Di, 03 Aug 2010) | 1 line
  
  Make the framer run (still generates wrong code for module creation though.)
................
  r83612 | georg.brandl | 2010-08-03 00:59:44 +0200 (Di, 03 Aug 2010) | 1 line
  
  Fix unicode literal.
................
  r83613 | georg.brandl | 2010-08-03 01:13:12 +0200 (Di, 03 Aug 2010) | 1 line
  
  Update Demo README.
................
  r83614 | georg.brandl | 2010-08-03 01:13:24 +0200 (Di, 03 Aug 2010) | 1 line
  
  Make minigzip work again.
................
  r83615 | georg.brandl | 2010-08-03 01:15:58 +0200 (Di, 03 Aug 2010) | 1 line
  
  Another demo that at least runs again.
................
  r83616 | georg.brandl | 2010-08-03 01:17:21 +0200 (Di, 03 Aug 2010) | 1 line
  
  Remove obsolete pdist demo.
................
  r83617 | georg.brandl | 2010-08-03 01:18:35 +0200 (Di, 03 Aug 2010) | 1 line
  
  Remove reference to removed faqwiz tool.
................
  r83618 | georg.brandl | 2010-08-03 01:30:09 +0200 (Di, 03 Aug 2010) | 1 line
  
  Fix-up some tkinter demos.
................
  r83636 | richard.jones | 2010-08-03 08:39:33 +0200 (Di, 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 09:42:42 +0200 (Di, 03 Aug 2010) | 2 lines
  
  Fix for issue 9455: platform.mac_ver() broken on OSX/ppc
................
  r83649 | georg.brandl | 2010-08-03 09:56:50 +0200 (Di, 03 Aug 2010) | 1 line
  
  Fix regrtest -F.
................
  r83659 | georg.brandl | 2010-08-03 14:06:29 +0200 (Di, 03 Aug 2010) | 1 line
  
  Terminology fix: exceptions are raised, except in generator.throw().
................
  r83660 | georg.brandl | 2010-08-03 14:31:59 +0200 (Di, 03 Aug 2010) | 1 line
  
  Get rid of UserWarnings when running Sphinx from tools dir.
................
  r83663 | georg.brandl | 2010-08-03 14:36:57 +0200 (Di, 03 Aug 2010) | 1 line
  
  A couple of nits how to ignore errors.
................
  r83667 | mark.dickinson | 2010-08-03 18:08:16 +0200 (Di, 03 Aug 2010) | 2 lines
  
  Issue #9450:  Fix memory leaks in readline.remove/replace_history_entry.
................
  r83670 | mark.dickinson | 2010-08-03 18:49:49 +0200 (Di, 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 19:09:36 +0200 (Di, 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 19:56:09 +0200 (Di, 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 20:31:54 +0200 (Di, 03 Aug 2010) | 1 line
  
  Fix memory leak in ssl module.
................
  r83678 | antoine.pitrou | 2010-08-03 20:32:26 +0200 (Di, 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 20:35:55 +0200 (Di, 03 Aug 2010) | 2 lines
  
  Add various missing files.
  Improve detection of unpackaged files.
................
  r83683 | mark.dickinson | 2010-08-03 20:44:16 +0200 (Di, 03 Aug 2010) | 1 line
  
  Misc/NEWS entry for r83677.
................
  r83690 | r.david.murray | 2010-08-04 00:14:10 +0200 (Mi, 04 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 02:18:49 +0200 (Mi, 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 03:19:22 +0200 (Mi, 04 Aug 2010) | 1 line
  
  note smtpd module changes in NEWS
................
  r83699 | richard.jones | 2010-08-04 03:20:14 +0200 (Mi, 04 Aug 2010) | 1 line
  
  improve smtpd module test coverage
................
  r83701 | senthil.kumaran | 2010-08-04 06:50:44 +0200 (Mi, 04 Aug 2010) | 3 lines
  
  Fix Issue754016 - urlparse goes wrong with IP:port without scheme
................
  r83705 | giampaolo.rodola | 2010-08-04 11:02:27 +0200 (Mi, 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 11:28:05 +0200 (Mi, 04 Aug 2010) | 1 line
  
  issue #8687: provides a test suite for sched.py module
................
  r83708 | giampaolo.rodola | 2010-08-04 12:12:00 +0200 (Mi, 04 Aug 2010) | 1 line
  
  fix issue #6822: ftplib's storline method doesn't work with text files
................
  r83709 | antoine.pitrou | 2010-08-04 12:26:30 +0200 (Mi, 04 Aug 2010) | 3 lines
  
  Something fun to maintain
................
  r83712 | giampaolo.rodola | 2010-08-04 12:36:18 +0200 (Mi, 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 13:48:56 +0200 (Mi, 04 Aug 2010) | 3 lines
  
  Factor out stripping of interpreter debug output in test.support.strip_python_stderr()
................
  r83714 | richard.jones | 2010-08-04 14:27:36 +0200 (Mi, 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 15:24:41 +0200 (Mi, 04 Aug 2010) | 3 lines
  
  I'm interested in threading issues as well
................
  r83719 | antoine.pitrou | 2010-08-04 17:43:16 +0200 (Mi, 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 17:47:24 +0200 (Mi, 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 18:45:21 +0200 (Mi, 04 Aug 2010) | 3 lines
  
  In verbose mode, identify OpenSSL build and platform more precisely
................
  r83727 | antoine.pitrou | 2010-08-04 19:14:06 +0200 (Mi, 04 Aug 2010) | 3 lines
  
  Try to fix issue #9415: skip some tests on broken Ubuntu OpenSSL
................
  r83729 | senthil.kumaran | 2010-08-04 19:46:23 +0200 (Mi, 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 20:28:02 +0200 (Mi, 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 20:42:43 +0200 (Mi, 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 21:08:20 +0200 (Mi, 04 Aug 2010) | 2 lines
  
  Add Terry Reedy.
................
  r83736 | mark.dickinson | 2010-08-04 22:56:28 +0200 (Mi, 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 09:12:18 +0200 (Do, 05 Aug 2010) | 4 lines
  
  Issue 5077: Add documentation for operator fixer.
  
  Patch by Meador Inge.
................
  r83742 | gerhard.haering | 2010-08-05 16:08:44 +0200 (Do, 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 19:34:27 +0200 (Do, 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 20:56:00 +0200 (Do, 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 08:12:05 +0200 (Fr, 06 Aug 2010) | 2 lines
  
  Issue #3854: Documented using the sqlite3 module with multiple threads.
................
  r83750 | raymond.hettinger | 2010-08-06 11:22:46 +0200 (Fr, 06 Aug 2010) | 1 line
  
  Fix the VS8.0 build
................
  r83751 | mark.dickinson | 2010-08-06 11:36:57 +0200 (Fr, 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 11:38:58 +0200 (Fr, 06 Aug 2010) | 1 line
  
  Misc/NEWS entry for r83751.
................
  r83755 | raymond.hettinger | 2010-08-06 11:52:17 +0200 (Fr, 06 Aug 2010) | 1 line
  
  Issue8757:  Implicit set-to-frozenset conversion not thread-safe.
................
  r83758 | martin.v.loewis | 2010-08-06 12:43:31 +0200 (Fr, 06 Aug 2010) | 1 line
  
  Change pyc removal to support __pycache__.
................
  r83759 | tim.golden | 2010-08-06 15:03:56 +0200 (Fr, 06 Aug 2010) | 1 line
  
  Issue #3210: Ensure stdio handles are closed if CreateProcess fails
................
  r83762 | mark.dickinson | 2010-08-06 20:55:26 +0200 (Fr, 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 21:27:32 +0200 (Fr, 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 23:18:49 +0200 (Fr, 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 23:33:18 +0200 (Fr, 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 01:23:49 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Improve the whatsnew article on the lru/lfu cache decorators.
................
  r83771 | brian.curtin | 2010-08-07 05:47:21 +0200 (Sa, 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 06:19:49 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Fix markup
................
  r83775 | raymond.hettinger | 2010-08-07 07:36:53 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Add partition recipe to itertools docs.
................
  r83776 | raymond.hettinger | 2010-08-07 07:54:08 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Fix nit (sentinel on lhs of comparison).
................
  r83777 | raymond.hettinger | 2010-08-07 09:36:55 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Improve the docs for bisect to cover common searching tasks.
................
  r83778 | victor.stinner | 2010-08-07 12:09:35 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Issue #9425: skip tests if a filename is not encodable
................
  r83779 | victor.stinner | 2010-08-07 12:57:17 +0200 (Sa, 07 Aug 2010) | 3 lines
  
  Issue #9425: Create run_command() subfunction
  
  Use PyUnicode_AsUTF8String() instead of _PyUnicode_AsString()
................
  r83780 | mark.dickinson | 2010-08-07 14:33:36 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Issue #8433: Fix test_curses failure for platforms with recent versions of ncurses.
................
  r83783 | victor.stinner | 2010-08-07 18:34:25 +0200 (Sa, 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 23:31:55 +0200 (Sa, 07 Aug 2010) | 1 line
  
  Clean-up docstring in examples.
................
  r83785 | benjamin.peterson | 2010-08-07 23:32:12 +0200 (Sa, 07 Aug 2010) | 1 line
  
  kill outdated comment
................
  r83792 | raymond.hettinger | 2010-08-08 01:31:27 +0200 (So, 08 Aug 2010) | 1 line
  
  Document implementation notes for priority queues
................
  r83795 | raymond.hettinger | 2010-08-08 01:37:37 +0200 (So, 08 Aug 2010) | 1 line
  
  Fix typo
................
  r83802 | benjamin.peterson | 2010-08-08 02:04:26 +0200 (So, 08 Aug 2010) | 1 line
  
  set svn:eol-style
................
  r83804 | raymond.hettinger | 2010-08-08 02:29:08 +0200 (So, 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 03:13:42 +0200 (So, 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 03:30:45 +0200 (So, 08 Aug 2010) | 1 line
  
  Issue #4570:  Clean-up tutorial example
................
  r83816 | tim.golden | 2010-08-08 13:18:16 +0200 (So, 08 Aug 2010) | 1 line
  
  Issue #3210: Revert C module changes and apply patch from Hirokazu Yamamoto instead
................
  r83818 | senthil.kumaran | 2010-08-08 13:27:53 +0200 (So, 08 Aug 2010) | 4 lines
  
  Fix Issue8280 - urllib2's Request method will remove fragements in the url.
  This is how it should work,wget and curl work like this way too. Old behavior was wrong.
................
  r83822 | senthil.kumaran | 2010-08-08 13:50:22 +0200 (So, 08 Aug 2010) | 3 lines
  
  Add a news entry for Issue8280.
................
  r83828 | benjamin.peterson | 2010-08-08 15:17:07 +0200 (So, 08 Aug 2010) | 1 line
  
  use same quoting as the rest of the file
................
  r83829 | florent.xicluna | 2010-08-08 18:16:07 +0200 (So, 08 Aug 2010) | 2 lines
  
  Use unittest specific methods for some urllib test cases.  And replace urllib2 with urllib.request in comments.
................
  r83830 | tim.golden | 2010-08-08 18:17:48 +0200 (So, 08 Aug 2010) | 1 line
  
  Issue #2304: Add additional quotes when using cmd shell on Windows. Original patch from Gabriel Genellina
................
  r83833 | florent.xicluna | 2010-08-08 18:25:27 +0200 (So, 08 Aug 2010) | 2 lines
  
  Add test case for the HTTPResponse being an iterable.  Follow-up of issue #4608.
................
  r83834 | benjamin.peterson | 2010-08-08 18:54:58 +0200 (So, 08 Aug 2010) | 1 line
  
  remove dead code #9292
................
  r83835 | mark.dickinson | 2010-08-08 19:12:46 +0200 (So, 08 Aug 2010) | 1 line
  
  Remove unused import.
................
  r83837 | thomas.heller | 2010-08-08 19:58:53 +0200 (So, 08 Aug 2010) | 3 lines
  
  Fix issue5504: ctypes does now work with systems where mmap can't be
  PROT_WRITE and PROT_EXEC.
................
  r83838 | florent.xicluna | 2010-08-08 20:03:44 +0200 (So, 08 Aug 2010) | 2 lines
  
  Typo.
................
  r83839 | florent.xicluna | 2010-08-08 20:06:13 +0200 (So, 08 Aug 2010) | 2 lines
  
  Issue #7564: Skip test_ioctl if another process is attached to /dev/tty.
................
  r83841 | thomas.heller | 2010-08-08 20:16:20 +0200 (So, 08 Aug 2010) | 2 lines
  
  Fix issue6869: refcount problem in the _ctypes extension.
................
  r83845 | benjamin.peterson | 2010-08-08 21:01:25 +0200 (So, 08 Aug 2010) | 69 lines
  
  Merged revisions 82779,82855,83740,83789-83791,83797-83801,83803,83811,83827,83844 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r82779 | benjamin.peterson | 2010-07-10 14:45:08 -0500 (Sat, 10 Jul 2010) | 1 line
    
    typo in attribute name #9217
  ........
    r82855 | benjamin.peterson | 2010-07-13 16:27:38 -0500 (Tue, 13 Jul 2010) | 1 line
    
    remove more extraneous commas #9245
  ........
    r83740 | alexandre.vassalotti | 2010-08-05 01:58:36 -0500 (Thu, 05 Aug 2010) | 4 lines
    
    Issue 5077: Update fixer for the other functions gone from the operator module.
    
    Patch by Meador Inge.
  ........
    r83789 | benjamin.peterson | 2010-08-07 17:45:14 -0500 (Sat, 07 Aug 2010) | 1 line
    
    cleanup and use unicode consistently
  ........
    r83790 | benjamin.peterson | 2010-08-07 17:52:06 -0500 (Sat, 07 Aug 2010) | 1 line
    
    unicode literal
  ........
    r83791 | benjamin.peterson | 2010-08-07 17:52:55 -0500 (Sat, 07 Aug 2010) | 1 line
    
    .get() is pointless here
  ........
    r83797 | benjamin.peterson | 2010-08-07 18:54:51 -0500 (Sat, 07 Aug 2010) | 1 line
    
    add a function to find how a node is indented
  ........
    r83798 | benjamin.peterson | 2010-08-07 18:55:28 -0500 (Sat, 07 Aug 2010) | 1 line
    
    when splitting import statements, use correct indentation #9386
  ........
    r83799 | benjamin.peterson | 2010-08-07 18:57:43 -0500 (Sat, 07 Aug 2010) | 1 line
    
    double quotes
  ........
    r83800 | benjamin.peterson | 2010-08-07 18:58:52 -0500 (Sat, 07 Aug 2010) | 1 line
    
    add another test
  ........
    r83801 | benjamin.peterson | 2010-08-07 19:02:10 -0500 (Sat, 07 Aug 2010) | 1 line
    
    cleanup; style-nits
  ........
    r83803 | benjamin.peterson | 2010-08-07 19:05:08 -0500 (Sat, 07 Aug 2010) | 1 line
    
    slightly more explicit
  ........
    r83811 | benjamin.peterson | 2010-08-07 22:56:44 -0500 (Sat, 07 Aug 2010) | 4 lines
    
    Fix node.pre_order() to call the right method on its children.
    
    This was a rather tragic copy-paste error.
  ........
    r83827 | benjamin.peterson | 2010-08-08 08:12:48 -0500 (Sun, 08 Aug 2010) | 1 line
    
    cause test to actually run and fix it
  ........
    r83844 | benjamin.peterson | 2010-08-08 13:46:37 -0500 (Sun, 08 Aug 2010) | 1 line
    
    fix whitespace
  ........
................
  r83846 | benjamin.peterson | 2010-08-08 21:08:44 +0200 (So, 08 Aug 2010) | 1 line
  
  revert r83830, breaks tests on unixes
................
  r83851 | florent.xicluna | 2010-08-08 21:48:29 +0200 (So, 08 Aug 2010) | 4 lines
  
  Issue #8047: Fix the xml.etree serializer to return bytes by default.
  Use ``encoding="unicode"`` to generate a Unicode string.
................
  r83854 | antoine.pitrou | 2010-08-08 22:46:42 +0200 (So, 08 Aug 2010) | 4 lines
  
  Issue #5319: Print an error if flushing stdout fails at interpreter
  shutdown.
................
  r83859 | florent.xicluna | 2010-08-09 00:07:16 +0200 (Mo, 09 Aug 2010) | 2 lines
  
  Fix #8530: Prevent stringlib fastsearch from reading beyond the front of an array.
................
  r83860 | victor.stinner | 2010-08-09 00:12:45 +0200 (Mo, 09 Aug 2010) | 9 lines
  
  Issue #9425: fix setup_context() for non-ascii filenames
  
  setup_context() replaces .pyc or .pyo filename suffix by .py, but it
  didn't work if the filename contains a non-ascii character because the
  function used the wrong unit for the length (number of characters
  instead of the number of bytes).
  
  With this patch, it uses unicode filenames instead of bytes filenames,
  to fix the bug and to be fully unicode compliant.
................
  r83861 | antoine.pitrou | 2010-08-09 00:18:46 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Issue #477863: Print a warning at shutdown if gc.garbage is not empty.
................
  r83862 | victor.stinner | 2010-08-09 00:31:44 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Issue #9425: file system encoding is not always utf-8
  
  Fix a regression introduced in test_sys by r83778.
................
  r83863 | florent.xicluna | 2010-08-09 00:58:56 +0200 (Mo, 09 Aug 2010) | 2 lines
  
  Fix BytesWarning in test_xml_etree, introduced with r83851.
................
  r83864 | florent.xicluna | 2010-08-09 01:08:41 +0200 (Mo, 09 Aug 2010) | 2 lines
  
  Fix xml.etree.ElementInclude to include the tail of the current node.  Issue #6231
................
  r83869 | antoine.pitrou | 2010-08-09 01:24:50 +0200 (Mo, 09 Aug 2010) | 6 lines
  
  Issue #8524: Add a forget() method to socket objects, so as to put the
  socket into the closed state without closing the underlying file
  descriptor.
................
  r83870 | victor.stinner | 2010-08-09 02:59:10 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Issue #9425: Create load_builtin() subfunction
  
  Just move the code and some variables.
................
  r83871 | raymond.hettinger | 2010-08-09 04:07:15 +0200 (Mo, 09 Aug 2010) | 7 lines
  
  Issue 7846:  fnmatch cache can grow without bound
  
  Updated to solution to use the functools.lru_cache().
  Restores the API so that purge() is not needed
  (because the cache never gets big).
................
  r83872 | benjamin.peterson | 2010-08-09 04:13:10 +0200 (Mo, 09 Aug 2010) | 1 line
  
  use 3 space indents
................
  r83874 | raymond.hettinger | 2010-08-09 06:24:42 +0200 (Mo, 09 Aug 2010) | 4 lines
  
  Issue 9396.   Apply functools.lru_cache in the place of the
  random flushing cache in the re module.
................
  r83875 | raymond.hettinger | 2010-08-09 07:56:50 +0200 (Mo, 09 Aug 2010) | 13 lines
  
  Revert 83784 adding functools.lru_cache() to the re module.
  
  The problem is that the re module is imported by sysconfig
  and re needs functools which uses collections.OrderedDict()
  but the _collectionsmodule.c code is not yet constructed
  at this point in the build.
  
  The likely best solution will be to include _collections
  as part of the static build before the rest of the
  boot-strapping.
................
  r83876 | senthil.kumaran | 2010-08-09 09:24:50 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Fix Issue9545  - Adding _collections to static build.
................
  r83877 | senthil.kumaran | 2010-08-09 09:30:53 +0200 (Mo, 09 Aug 2010) | 10 lines
  
  reapply the revert made in r83875
  
  Now the _collections is statically built, the build dependencies are in proper
  order and build works fine.
  
  Commit Log from r83874:
  Issue 9396.   Apply functools.lru_cache in the place of the
  random flushing cache in the re module.
................
  r83878 | florent.xicluna | 2010-08-09 10:29:08 +0200 (Mo, 09 Aug 2010) | 1 line
  
  Merge the 2to3 script from /sandbox/trunk/2to3/2to3, revision 72867 (latest).
................
  r83880 | senthil.kumaran | 2010-08-09 10:56:25 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Fix Issue5416 - explain negative value for count in bytes object replace.
................
  r83882 | senthil.kumaran | 2010-08-09 11:03:57 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  spelling mistake.
................
  r83885 | antoine.pitrou | 2010-08-09 12:47:46 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Revert r83877 in order to fix compilation
................
  r83886 | florent.xicluna | 2010-08-09 14:24:20 +0200 (Mo, 09 Aug 2010) | 2 lines
  
  Clean up syntax for some scripts.
................
  r83887 | florent.xicluna | 2010-08-09 14:26:44 +0200 (Mo, 09 Aug 2010) | 1 line
  
  Fix ``Tools/scripts/checkpyc.py`` after PEP 3147.
................
  r83888 | antoine.pitrou | 2010-08-09 14:47:33 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Also temporarily revert r83871, to fix compilation on buildbots
................
  r83889 | fred.drake | 2010-08-09 14:52:45 +0200 (Mo, 09 Aug 2010) | 4 lines
  
  issue #9452:
  Add read_file, read_string, and read_dict to the configparser API;
  new source attribute to exceptions.
................
  r83890 | benjamin.peterson | 2010-08-09 15:05:35 +0200 (Mo, 09 Aug 2010) | 1 line
  
  don't alias directly, so that extra arguments don't appear #6678
................
  r83891 | benjamin.peterson | 2010-08-09 17:49:56 +0200 (Mo, 09 Aug 2010) | 1 line
  
  typo
................
  r83892 | benjamin.peterson | 2010-08-09 17:53:58 +0200 (Mo, 09 Aug 2010) | 1 line
  
  correct comment
................
  r83894 | florent.xicluna | 2010-08-09 18:56:43 +0200 (Mo, 09 Aug 2010) | 21 lines
  
  Merged manually from 2.7 branch to 3.x trunk.
  
    ------------------------------------------------------------------------
    r80411 | florent.xicluna | 2010-04-23 19:59:10 +0200 (ven. 23 avril 2010) | 2 lignes
  
    Remove ImportWarnings filters.  They become obsolete after r79310, issue #8205.
    ------------------------------------------------------------------------
    r80412 | florent.xicluna | 2010-04-23 20:10:12 +0200 (ven. 23 avril 2010) | 2 lignes
  
    Fix the "regrtest -s" switch.
    ------------------------------------------------------------------------
    r81140 | florent.xicluna | 2010-05-13 19:05:29 +0200 (jeu. 13 mai 2010) | 3 lignes
  
    Add sensible information about the OS X platform to diagnose issue #8423:
    test_pep277 fails on "x86 Tiger" buildbot but not on "PPC Tiger".
    ------------------------------------------------------------------------
    r81141 | florent.xicluna | 2010-05-13 20:16:06 +0200 (jeu. 13 mai 2010) | 2 lignes
  
    Revert the additional OS X information (r81140).  Keep the endianness information.
    ------------------------------------------------------------------------
................
  r83895 | florent.xicluna | 2010-08-09 19:18:05 +0200 (Mo, 09 Aug 2010) | 20 lines
  
  Merged manually from 2.7 branch to 3.x trunk.
  
    ------------------------------------------------------------------------
    r81149 | florent.xicluna | 2010-05-13 23:40:01 +0200 (jeu. 13 mai 2010) | 2 lignes
  
    Better test skipping, with message in the log.
    ------------------------------------------------------------------------
    r81150 | florent.xicluna | 2010-05-13 23:41:05 +0200 (jeu. 13 mai 2010) | 2 lignes
  
    Improve test feedback to troubleshoot issue #8423 on OS X.
    ------------------------------------------------------------------------
    r81151 | florent.xicluna | 2010-05-14 01:46:48 +0200 (ven. 14 mai 2010) | 2 lignes
  
    Revert changeset r81150 which helped diagnose issue #8423 on some OS X buildbot.
    ------------------------------------------------------------------------
    r82056 | florent.xicluna | 2010-06-17 22:30:56 +0200 (jeu. 17 juin 2010) | 2 lignes
  
    Add few words about test.test_genericpath.CommonTest
    ------------------------------------------------------------------------
................
  r83900 | senthil.kumaran | 2010-08-09 21:53:52 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Fix Issue7007 -  Use percent-encoded consistently instead of URL Encoded variations. Docs changed.
................
  r83901 | senthil.kumaran | 2010-08-09 22:01:35 +0200 (Mo, 09 Aug 2010) | 3 lines
  
  Fix Issue7007 -  Use percent-encoded consistently instead of URL Encoded variations. Changes in Modules.
................
  r83908 | antoine.pitrou | 2010-08-09 22:39:54 +0200 (Mo, 09 Aug 2010) | 4 lines
  
  Followup to r83869 and issue #8524: rename socket.forget() to socket.detach()
  and make it return the file descriptor.
................
  r83918 | antoine.pitrou | 2010-08-10 00:38:19 +0200 (Di, 10 Aug 2010) | 5 lines
  
  Issue #3757: thread-local objects now support cyclic garbage collection.
  Thread-local objects involved in reference cycles will be deallocated
  timely by the cyclic GC, even if the underlying thread is still running.
................
  r83921 | antoine.pitrou | 2010-08-10 01:39:31 +0200 (Di, 10 Aug 2010) | 4 lines
  
  Issue #6915: Under Windows, os.listdir() didn't release the Global
  Interpreter Lock around all system calls.  Original patch by Ryan Kelly.
................
  r83927 | antoine.pitrou | 2010-08-10 02:45:32 +0200 (Di, 10 Aug 2010) | 3 lines
  
  test_winsound shouldn't crash when ctypes isn't available
................
  r83932 | antoine.pitrou | 2010-08-10 15:48:51 +0200 (Di, 10 Aug 2010) | 5 lines
  
  Issue #8411: new condition variable emulation under Windows for the new GIL,
  by Kristján.  Unfortunately the 3.x Windows buildbots are in a wreck, so we'll
  have to watch them when they become fit again.
................
  r83933 | victor.stinner | 2010-08-10 18:37:20 +0200 (Di, 10 Aug 2010) | 1 line
  
  Issue #9425: create Py_UNICODE_strrchr() function
................
  r83936 | mark.dickinson | 2010-08-10 20:35:01 +0200 (Di, 10 Aug 2010) | 1 line
  
  Issue #9530:  Fix undefined-behaviour-inducing overflow checks in bytes and bytearray implementations.
................
  r83937 | alexander.belopolsky | 2010-08-10 23:54:48 +0200 (Di, 10 Aug 2010) | 3 lines
  
  Issue #8834: Added a comment describing the order of entries in Misc/ACKS.
  Added names from release27-maint branch that were missing from py3k.
................
  r83939 | brett.cannon | 2010-08-11 02:18:19 +0200 (Mi, 11 Aug 2010) | 2 lines
  
  Note that Éric Araujo has been given commit privileges.
................
  r83943 | martin.v.loewis | 2010-08-11 07:48:57 +0200 (Mi, 11 Aug 2010) | 2 lines
  
  Add George Boutsioukis, from the GSoC project.
................
  r83944 | antoine.pitrou | 2010-08-11 15:31:33 +0200 (Mi, 11 Aug 2010) | 6 lines
  
  Issue #9550: a BufferedReader could issue an additional read when the
  original read request had been satisfied, which can block indefinitely
  when the underlying raw IO channel is e.g. a socket.  Report and original
  patch by Jason V. Miller.
................
  r83947 | tim.golden | 2010-08-11 16:20:40 +0200 (Mi, 11 Aug 2010) | 1 line
  
  #2304: fix incorporating Eric Smith's .format suggestion and tested on Ubuntu as well as Windows
................
  r83948 | tim.golden | 2010-08-11 17:59:57 +0200 (Mi, 11 Aug 2010) | 1 line
  
  #9055: remove assertion at the end of test_8959_b since the test is about crashing, not about counting and is difficult to manage when run as a service
................
  r83949 | alexander.belopolsky | 2010-08-11 19:31:17 +0200 (Mi, 11 Aug 2010) | 4 lines
  
  Issue #2443: Added a new macro, Py_VA_COPY, which is equivalent to C99
  va_copy, but available on all python platforms.  Untabified a few
  unrelated files.
................
  r83951 | benjamin.peterson | 2010-08-11 21:20:42 +0200 (Mi, 11 Aug 2010) | 4 lines
  
  use pep 383 decoding for mknod and mkfifo #9570
  
  Patch by David Watson.
................
  r83959 | antoine.pitrou | 2010-08-12 17:11:50 +0200 (Do, 12 Aug 2010) | 5 lines
  
  Issue #7467: when a file from a ZIP archive, its CRC is checked and a
  BadZipfile error is raised if it doesn't match (as used to be the
  case in Python 2.5 and earlier).
................
  r83960 | antoine.pitrou | 2010-08-12 17:15:01 +0200 (Do, 12 Aug 2010) | 3 lines
  
  Typo.
................
  r83966 | eric.smith | 2010-08-12 23:55:30 +0200 (Do, 12 Aug 2010) | 1 line
  
  Remove unused test class.
................
  r83971 | victor.stinner | 2010-08-13 15:02:04 +0200 (Fr, 13 Aug 2010) | 7 lines
  
  Set TESTFN_UNENCODEABLE on non-Windows OSes
  
   * Use 0xff byte on non-Windows OSes
   * mbcs is now really strict by default: i closed the issue #850997, so use the
     filesystem encoding and not Latin-1
   * Rename TESTFN_UNICODE_UNENCODEABLE to TESTFN_UNENCODEABLE
................
  r83972 | victor.stinner | 2010-08-13 15:07:29 +0200 (Fr, 13 Aug 2010) | 6 lines
  
  Issue #9425: NullImporter constructor is fully unicode compliant
  
   * On non-Windows OSes: the constructor accepts bytes filenames
     and use surrogateescape for unicode filenames
   * On Windows: use GetFileAttributesW() instead of GetFileAttributesA()
................
  r83973 | victor.stinner | 2010-08-13 15:34:52 +0200 (Fr, 13 Aug 2010) | 5 lines
  
  Issue #9425: PyFile_FromFd() ignores the name argument
  
  This function is only by imp.find_module() which does return the filename in a
  separated variable.
................
  r83974 | victor.stinner | 2010-08-13 15:45:00 +0200 (Fr, 13 Aug 2010) | 5 lines
  
  Oops, create TESTFN_UNENCODEABLE from TEST_FN, not TESTFN_UNICODE
  
  test_imp fails on Linux with C locale because TESTFN_UNICODE is not encodable
  to ascii.
................
  r83975 | victor.stinner | 2010-08-13 15:47:18 +0200 (Fr, 13 Aug 2010) | 2 lines
  
  Oops, I did it again: add missing \ removed in previous commit
................
  r83976 | victor.stinner | 2010-08-13 16:03:48 +0200 (Fr, 13 Aug 2010) | 7 lines
  
  Issue #9425: Create PyErr_WarnFormat() function
  
  Similar to PyErr_WarnEx() but use PyUnicode_FromFormatV() to format the warning
  message.
  
  Strip also some trailing spaces.
................
  r83977 | georg.brandl | 2010-08-13 17:10:49 +0200 (Fr, 13 Aug 2010) | 1 line
  
  Fix copy-paste error.
................
  r83978 | antoine.pitrou | 2010-08-13 17:25:56 +0200 (Fr, 13 Aug 2010) | 3 lines
  
  De-duplicate contents of pytime.h
................
  r83979 | antoine.pitrou | 2010-08-13 18:26:40 +0200 (Fr, 13 Aug 2010) | 3 lines
  
  Re-apply r83871.
................
  r83980 | antoine.pitrou | 2010-08-13 18:27:38 +0200 (Fr, 13 Aug 2010) | 3 lines
  
  Reapply r83877.
................
  r83981 | victor.stinner | 2010-08-13 18:30:15 +0200 (Fr, 13 Aug 2010) | 5 lines
  
  Issue #9560: Use -b option of the file command in _syscmd_file()
  
  Omit the filename to avoid enconding issues, especially with non encodable
  characters in the Python full path.
................
  r83982 | r.david.murray | 2010-08-13 20:16:35 +0200 (Fr, 13 Aug 2010) | 4 lines
  
  Per request, make 'nosy' vs 'assign' explicit in maintainers.rst.
  
  Also add myself as assignable for email issues.
................
  r83983 | brian.curtin | 2010-08-13 22:42:57 +0200 (Fr, 13 Aug 2010) | 3 lines
  
  Fix #9588. Add sys.executable to two shell=True tests.
................
  r83986 | antoine.pitrou | 2010-08-13 23:15:58 +0200 (Fr, 13 Aug 2010) | 5 lines
  
  Issue #9203: Computed gotos are now enabled by default on supported
  compilers (which are detected by the configure script).  They can still
  be disable selectively by specifying --without-computed-gotos.
................
  r83987 | victor.stinner | 2010-08-14 00:23:24 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Fix a typo: TESTFN_UNENCODEABLE => TESTFN_UNENCODABLE
................
  r83988 | antoine.pitrou | 2010-08-14 00:25:01 +0200 (Sa, 14 Aug 2010) | 5 lines
  
  Reimplement addbuilddir() in C inside getpath.c, so as to execute it
  at interpreter startup before importing any non-builtin modules.
  Should fix #9589.
................
  r83989 | victor.stinner | 2010-08-14 01:29:08 +0200 (Sa, 14 Aug 2010) | 5 lines
  
  Create _Py_wchar2char() function, reverse of _Py_char2wchar()
  
   * Use _Py_wchar2char() in _wstat() and _Py_wfopen()
   * Document _Py_char2wchar()
................
  r83990 | victor.stinner | 2010-08-14 01:59:58 +0200 (Sa, 14 Aug 2010) | 12 lines
  
  Issue #9542: Create PyUnicode_FSDecoder() function
  
  It's a ParseTuple converter: decode bytes objects to unicode using
  PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is.
  
   * Don't specify surrogateescape error handler in the comments nor the
     documentation, but PyUnicode_DecodeFSDefaultAndSize() and
     PyUnicode_EncodeFSDefault() because these functions use strict error handler
     for the mbcs encoding (on Windows).
   * Remove PyUnicode_FSConverter() comment in unicodeobject.c to avoid
     inconsistency with unicodeobject.h.
................
  r83991 | victor.stinner | 2010-08-14 02:07:14 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Kill a gcc warning introduced by r83988
................
  r83993 | eric.araujo | 2010-08-14 04:30:34 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Use a marker in generated MANIFEST files, don't touch files without it. Fixes #8688.
................
  r83998 | eric.araujo | 2010-08-14 05:59:54 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Manually merge r83995: Fix version{added,changed} and spacing in NEWS
................
  r83999 | eric.araujo | 2010-08-14 06:55:45 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Fix reference (follow-up to #9061)
................
  r84000 | eric.araujo | 2010-08-14 06:56:48 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Let's commit
................
  r84001 | eric.araujo | 2010-08-14 07:00:18 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Oops, fix typo
................
  r84005 | ezio.melotti | 2010-08-14 10:54:33 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Revert r82831 as discussed at EP now that the wording of maintainers.rst has been clarified.
................
  r84006 | ezio.melotti | 2010-08-14 11:02:36 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Add myself for the bug tracker (and for re).
................
  r84007 | antoine.pitrou | 2010-08-14 14:06:40 +0200 (Sa, 14 Aug 2010) | 3 lines
  
  Add myself to threads topic (suggested by Ezio)
................
  r84008 | antoine.pitrou | 2010-08-14 14:33:18 +0200 (Sa, 14 Aug 2010) | 3 lines
  
  Add comments about Windows in Modules/getpath.c
................
  r84009 | antoine.pitrou | 2010-08-14 14:34:41 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Fix indentation in Modules/getpath.c
................
  r84011 | georg.brandl | 2010-08-14 15:43:37 +0200 (Sa, 14 Aug 2010) | 1 line
  
  There are no *.doc files anymore. Also update "funny" target.
................
  r84012 | victor.stinner | 2010-08-14 16:50:26 +0200 (Sa, 14 Aug 2010) | 4 lines
  
  Issue #9425: Create private _Py_stat() function
  
  Use stat() or _wstat() depending on the OS.
................
  r84013 | victor.stinner | 2010-08-14 16:54:10 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Issue #9425: zipimporter_init() is fully unicode compliant
................
  r84015 | georg.brandl | 2010-08-14 17:44:34 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Add some maintainers.
................
  r84016 | georg.brandl | 2010-08-14 17:46:15 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Wording fix.
................
  r84017 | georg.brandl | 2010-08-14 17:46:59 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Typo fix.
................
  r84018 | georg.brandl | 2010-08-14 17:48:49 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Typo fix.
................
  r84019 | florent.xicluna | 2010-08-14 17:56:42 +0200 (Sa, 14 Aug 2010) | 11 lines
  
  Merged manually from 2.7 branch to 3.x trunk.
  
    ------------------------------------------------------------------------
    r79925 | nick.coghlan | 2010-04-10 16:24:36 +0200 (sam. 10 avril 2010)
  
    Try to turn some buildbots green by allowing test_multiprocessing to
    pass even if it hits the sys.exc_clear code in the threading module, and
    improve the test coverage by making the ctypes dependencies a bit more
    granular (two of the cited ctypes objects don't exist on my system)
    ------------------------------------------------------------------------
................
  r84020 | georg.brandl | 2010-08-14 17:57:20 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Fix format.
................
  r84021 | antoine.pitrou | 2010-08-14 18:24:38 +0200 (Sa, 14 Aug 2010) | 4 lines
  
  Add a reasonable timeout to network SSL tests, so as to avoid buildbot timeouts
  when the remote server doesn't answer.
................
  r84022 | antoine.pitrou | 2010-08-14 18:32:10 +0200 (Sa, 14 Aug 2010) | 4 lines
  
  This is a better resolution than r84021 (because it will also affect
  ssl.get_server_certificate()).
................
  r84023 | antoine.pitrou | 2010-08-14 18:33:38 +0200 (Sa, 14 Aug 2010) | 3 lines
  
  There doesn't seem to be a reason for this test to be disabled.
................
  r84024 | giampaolo.rodola | 2010-08-14 18:45:41 +0200 (Sa, 14 Aug 2010) | 1 line
  
  fix issue #8857: provide a test case for socket.getaddrinfo
................
  r84025 | florent.xicluna | 2010-08-14 18:56:27 +0200 (Sa, 14 Aug 2010) | 1 line
  
  List Misc/python-config.in in Misc/README.  Fix few typos.
................
  r84026 | victor.stinner | 2010-08-14 18:59:08 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  _Py_stat(): ensure that path ends with a nul character
................
  r84028 | florent.xicluna | 2010-08-14 19:02:49 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Fix order.
................
  r84030 | victor.stinner | 2010-08-14 19:06:04 +0200 (Sa, 14 Aug 2010) | 6 lines
  
  Create _Py_fopen() for PyUnicodeObject path
  
  Call _wfopen() on Windows, or fopen() otherwise. Return the new file object on
  success, or NULL if the file cannot be open or (if PyErr_Occurred()) on unicode
  error.
................
  r84032 | florent.xicluna | 2010-08-14 19:15:31 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Convert to spaces.
................
  r84035 | victor.stinner | 2010-08-14 19:35:20 +0200 (Sa, 14 Aug 2010) | 2 lines
  
  Mac OS X denies unencodable filenames (invalid utf-8)
................
  r84036 | florent.xicluna | 2010-08-14 20:03:19 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Remove bad merge (from svnmerge r82301)
................
  r84038 | florent.xicluna | 2010-08-14 20:30:35 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Silence the BytesWarning, due to patch r83294 for #9301
................
  r84039 | florent.xicluna | 2010-08-14 22:51:58 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Silence BytesWarning while testing exception
................
  r84043 | raymond.hettinger | 2010-08-14 23:17:48 +0200 (Sa, 14 Aug 2010) | 1 line
  
  Clean-up the cache patch for the re module.
................
  r84045 | raymond.hettinger | 2010-08-15 00:22:10 +0200 (So, 15 Aug 2010) | 5 lines
  
  Add locks to make the caches well behaved in multi-threaded code.
  Store builtins in cell variables to speed-up the common path,
  reducing the chance of a lock needing to block at all.
................
  r84047 | raymond.hettinger | 2010-08-15 00:29:52 +0200 (So, 15 Aug 2010) | 1 line
  
  Localize one more builtin lookup.
................
  r84050 | eric.araujo | 2010-08-15 01:44:13 +0200 (So, 15 Aug 2010) | 1 line
  
  Fix typo
................
  r84054 | raymond.hettinger | 2010-08-15 01:52:08 +0200 (So, 15 Aug 2010) | 1 line
  
  Support cache sizes.
................
  r84056 | raymond.hettinger | 2010-08-15 05:30:45 +0200 (So, 15 Aug 2010) | 1 line
  
  Remove the lfu_cache.  Add more tests.
................
  r84057 | raymond.hettinger | 2010-08-15 05:35:24 +0200 (So, 15 Aug 2010) | 1 line
  
  Remove unused imports
................
  r84058 | senthil.kumaran | 2010-08-15 05:59:07 +0200 (So, 15 Aug 2010) | 3 lines
  
  Removing the comment lines for the modules which were made to build statically.
................
  r84059 | raymond.hettinger | 2010-08-15 09:41:40 +0200 (So, 15 Aug 2010) | 1 line
  
  Fix __all__.
................
  r84060 | victor.stinner | 2010-08-15 11:12:51 +0200 (So, 15 Aug 2010) | 4 lines
  
  Issue #9603: posix.ttyname() and posix.ctermid() decode the terminal name
  using the filesystem encoding and surrogateescape error handler. Patch
  written by David Watson.
................
  r84062 | victor.stinner | 2010-08-15 11:22:44 +0200 (So, 15 Aug 2010) | 3 lines
  
  Issue #9604: posix.initgroups() encodes the username using the fileystem
  encoding and surrogateescape error handler. Patch written by David Watson.
................
  r84063 | victor.stinner | 2010-08-15 11:33:08 +0200 (So, 15 Aug 2010) | 5 lines
  
  Issue #9605: posix.getlogin() decodes the username with file filesystem
  encoding and surrogateescape error handler. Patch written by David Watson.
  
  Reindent also posix_getlogin(), and fix a typo in the NEWS file.
................
  r84065 | mark.dickinson | 2010-08-15 11:43:29 +0200 (So, 15 Aug 2010) | 1 line
  
  Clarify whatsnew entry for short float repr:  roundtripping is not a new feature in 2.7.
................
  r84067 | victor.stinner | 2010-08-15 11:56:07 +0200 (So, 15 Aug 2010) | 2 lines
  
  Oops, fix a typo in NEWS: surrogateespace => surrogateescape
................
  r84068 | martin.v.loewis | 2010-08-15 17:47:25 +0200 (So, 15 Aug 2010) | 2 lines
  
  Don't run pgen twice when using make -j.
................
  r84069 | antoine.pitrou | 2010-08-15 18:26:49 +0200 (So, 15 Aug 2010) | 3 lines
  
  Add pgen.stamp to svn:ignore and friends
................
  r84070 | antoine.pitrou | 2010-08-15 19:12:55 +0200 (So, 15 Aug 2010) | 5 lines
  
  Fix some compilation warnings under 64-bit Windows (issue #9566).
  Some of these are genuine bugs with objects bigger than 2GB, but
  my system doesn't allow me to write tests for it.
................
  r84072 | antoine.pitrou | 2010-08-15 19:38:46 +0200 (So, 15 Aug 2010) | 3 lines
  
  Fix indentation and remove dead code.
................
  r84074 | antoine.pitrou | 2010-08-15 19:41:31 +0200 (So, 15 Aug 2010) | 3 lines
  
  Fix (harmless) warning with MSVC.
................
  r84076 | antoine.pitrou | 2010-08-15 20:07:50 +0200 (So, 15 Aug 2010) | 4 lines
  
  Fix other warnings under 64-bit Windows.
................
  r84078 | antoine.pitrou | 2010-08-15 20:51:10 +0200 (So, 15 Aug 2010) | 3 lines
  
  Fix more 64-bit warnings.
................
  r84080 | victor.stinner | 2010-08-15 21:28:21 +0200 (So, 15 Aug 2010) | 2 lines
  
  Fix TESTFN_UNENCODABLE of test.support on Mac OS X
................
  r84081 | florent.xicluna | 2010-08-15 22:16:27 +0200 (So, 15 Aug 2010) | 1 line
  
  Replace the deprecated ConfigParser.readfp() method, and fix the incomplete merge in r82293.
................
  r84082 | florent.xicluna | 2010-08-15 22:21:26 +0200 (So, 15 Aug 2010) | 1 line
  
  Replace readfp() with read_file() in configparser documentation.
................
  r84083 | antoine.pitrou | 2010-08-16 00:16:23 +0200 (Mo, 16 Aug 2010) | 3 lines
  
  Following Ezio's suggestion, force verbose mode on test_ssl to diagnose freezes on 3.x
................
  r84084 | antoine.pitrou | 2010-08-16 01:02:22 +0200 (Mo, 16 Aug 2010) | 3 lines
  
  Put test_ciphers in NetworkedTests
................
  r84085 | antoine.pitrou | 2010-08-16 01:28:10 +0200 (Mo, 16 Aug 2010) | 3 lines
  
  Add debug output to the asyncore test
................
  r84086 | antoine.pitrou | 2010-08-16 02:28:05 +0200 (Mo, 16 Aug 2010) | 3 lines
  
  Save and restore the global asyncore.socket_map, and warn if a test modified it
................
  r84088 | richard.jones | 2010-08-16 03:48:14 +0200 (Mo, 16 Aug 2010) | 1 line
  
  close down sockets held by asyncore at end of test; closes issue9619
................
  r84089 | giampaolo.rodola | 2010-08-16 07:08:11 +0200 (Mo, 16 Aug 2010) | 1 line
  
  fix getaddrinfo test failure on OSX caused by AI_CANNAME erroneously used as the value for 'proto'
................
  r84092 | antoine.pitrou | 2010-08-16 16:33:42 +0200 (Mo, 16 Aug 2010) | 3 lines
  
  Remove debug hack
................
  r84094 | victor.stinner | 2010-08-16 19:36:42 +0200 (Mo, 16 Aug 2010) | 4 lines
  
  Issue #9599: Create PySys_FormatStdout() and PySys_FormatStderr()
  
  Write a message formatted by PyUnicode_FromFormatV() to sys.stdout and
  sys.stderr.
................
  r84095 | victor.stinner | 2010-08-16 19:54:28 +0200 (Mo, 16 Aug 2010) | 3 lines
  
  Issue #9425: read_directory() is fully unicode compliant
  
  zipimport is now able to load a module with an unencodable filename.
................
  r84096 | victor.stinner | 2010-08-16 20:39:49 +0200 (Mo, 16 Aug 2010) | 1 line
  
  Add versionadded tag to PySys_FormatStd*() functions doc
................
  r84097 | florent.xicluna | 2010-08-16 20:41:19 +0200 (Mo, 16 Aug 2010) | 1 line
  
  Use test.support and unittest features.  Fix duplicated test (bad merge in r79033).  Fix comment for issue #7902.
................
  r84098 | alexander.belopolsky | 2010-08-16 20:55:46 +0200 (Mo, 16 Aug 2010) | 4 lines
  
  Issue #665761: functools.reduce() will no longer mask exceptions other
  than TypeError raised by the iterator argument.  Also added a test to
  check that zip() already behaves similarly.
................
  r84099 | florent.xicluna | 2010-08-16 21:03:05 +0200 (Mo, 16 Aug 2010) | 1 line
  
  I get it wrong in r84097: s/relative/absolute/
................
  r84105 | tim.golden | 2010-08-16 22:10:39 +0200 (Mo, 16 Aug 2010) | 1 line
  
  Add Tim Golden as interested in Windows
................
  r84106 | alexander.belopolsky | 2010-08-16 22:17:07 +0200 (Mo, 16 Aug 2010) | 1 line
  
  Issue #8983: Corrected docstrings.
................
  r84109 | brian.curtin | 2010-08-16 22:50:03 +0200 (Mo, 16 Aug 2010) | 2 lines
  
  Mark myself as assignable for winreg, and put myself down for Windows.
................
  r84111 | victor.stinner | 2010-08-17 00:03:11 +0200 (Di, 17 Aug 2010) | 4 lines
  
  Issue #9425: Create Py_UNICODE_strncmp() function
  
  The code is based on strncmp() of the libiberty library,
  function in the public domain.
................
  r84112 | amaury.forgeotdarc | 2010-08-17 00:11:29 +0200 (Di, 17 Aug 2010) | 2 lines
  
  Fix compilation warning on Windows
................
  r84113 | amaury.forgeotdarc | 2010-08-17 00:16:51 +0200 (Di, 17 Aug 2010) | 2 lines
  
  r82659 reintroduced some tab characters. Untabify again.
................
  r84120 | victor.stinner | 2010-08-17 01:48:11 +0200 (Di, 17 Aug 2010) | 1 line
  
  Issue #9425: get_data() uses an unicode path
................
  r84121 | victor.stinner | 2010-08-17 02:04:48 +0200 (Di, 17 Aug 2010) | 1 line
  
  Issue #9425: zipimporter_repr() uses unicode
................
  r84122 | victor.stinner | 2010-08-17 02:39:57 +0200 (Di, 17 Aug 2010) | 3 lines
  
  Issue #9425: save/restore exception on filename encoding
  
  _PyUnicode_AsString() raises an exception on unencodable filename.
................
  r84123 | victor.stinner | 2010-08-17 02:44:11 +0200 (Di, 17 Aug 2010) | 1 line
  
  test_zipimport: fix test name
................
  r84124 | benjamin.peterson | 2010-08-17 02:52:52 +0200 (Di, 17 Aug 2010) | 1 line
  
  add support for abstract class and static methods #5867
................
  r84125 | benjamin.peterson | 2010-08-17 03:07:53 +0200 (Di, 17 Aug 2010) | 1 line
  
  use assertTrue/assertFalse
................
  r84126 | benjamin.peterson | 2010-08-17 03:08:46 +0200 (Di, 17 Aug 2010) | 1 line
  
  remove test for oldstyle classes
................
  r84129 | benjamin.peterson | 2010-08-17 03:27:09 +0200 (Di, 17 Aug 2010) | 1 line
  
  add tests for mknod() and mkfifo() #9569
................
  r84130 | benjamin.peterson | 2010-08-17 05:37:20 +0200 (Di, 17 Aug 2010) | 1 line
  
  added versionadded
................
  r84131 | nick.coghlan | 2010-08-17 07:22:50 +0200 (Di, 17 Aug 2010) | 1 line
  
  Remove some lingering remnants of the short-lived functools.lfu_cache
................
  r84132 | nick.coghlan | 2010-08-17 08:17:18 +0200 (Di, 17 Aug 2010) | 1 line
  
  Document and test the resolution of issue 3445 (tolerate missing attributes in functools.update_wrapper, previously implemented as a side effect of the __annotations__ copying patch) and implement issue 9567 (add a __wrapped__ attribute when using update_wrapper)
................
  r84133 | nick.coghlan | 2010-08-17 10:03:36 +0200 (Di, 17 Aug 2010) | 1 line
  
  Issue 9147: Add dis.code_info()
................
  r84134 | ezio.melotti | 2010-08-17 10:35:41 +0200 (Di, 17 Aug 2010) | 1 line
  
  Correct a couple of assert* methods. Patch by Dave Malcolm.
................
  r84137 | nick.coghlan | 2010-08-17 11:25:57 +0200 (Di, 17 Aug 2010) | 1 line
  
  Ignore the exact ID value for the nested function in the dis.code_info tests
................
  r84138 | nick.coghlan | 2010-08-17 12:18:16 +0200 (Di, 17 Aug 2010) | 1 line
  
  Address XXX comment in dis.py: inspect.py now attempts to reuse the dis.py compiler flag values before resorting to defining its own
................
  r84139 | nick.coghlan | 2010-08-17 13:28:07 +0200 (Di, 17 Aug 2010) | 1 line
  
  Another attempt at pacifying the windows buildbots by ignoring all the variable information in the dis.code_info tests
................
  r84140 | nick.coghlan | 2010-08-17 15:06:11 +0200 (Di, 17 Aug 2010) | 1 line
  
  Issue #8202: Set sys.argv[0] to -m rather than -c while searching for the module to execute. Also updates all the cmd_line_script tests to validate the setting of sys.path[0] and the current working directory
................
  r84141 | georg.brandl | 2010-08-17 16:11:59 +0200 (Di, 17 Aug 2010) | 1 line
  
  Markup nits.
................
  r84142 | georg.brandl | 2010-08-17 17:07:14 +0200 (Di, 17 Aug 2010) | 1 line
  
  Consistency check for versionadded/changed directives.
................
  r84143 | giampaolo.rodola | 2010-08-17 17:30:23 +0200 (Di, 17 Aug 2010) | 1 line
  
  fix issue #8866: parameters passed to socket.getaddrinfo can now be specified as single keyword arguments.
................
  r84144 | giampaolo.rodola | 2010-08-17 18:09:53 +0200 (Di, 17 Aug 2010) | 1 line
  
  fix issue #8807: adds a context parameter to POP3_SSL class.
................
  r84145 | benjamin.peterson | 2010-08-17 19:52:02 +0200 (Di, 17 Aug 2010) | 1 line
  
  wrap
................
  r84146 | antoine.pitrou | 2010-08-17 19:55:07 +0200 (Di, 17 Aug 2010) | 4 lines
  
  Issue #9612: The set object is now 64-bit clean under Windows.
................
  r84147 | antoine.pitrou | 2010-08-17 20:30:06 +0200 (Di, 17 Aug 2010) | 3 lines
  
  Fix <deque iterator>.__length_hint__() under 64-bit Windows.
................
  r84149 | raymond.hettinger | 2010-08-17 21:19:29 +0200 (Di, 17 Aug 2010) | 1 line
  
  Minor rewording to docs for the lru_cache decorator
................
  r84150 | antoine.pitrou | 2010-08-17 21:33:30 +0200 (Di, 17 Aug 2010) | 3 lines
  
  Clean some 64-bit issues. Also, always spell "ssize_t" "Py_ssize_t".
................
  r84153 | brian.curtin | 2010-08-17 22:08:40 +0200 (Di, 17 Aug 2010) | 2 lines
  
  Properly downcast from size_t/Py_ssize_t in a few places.
................
  r84154 | brian.curtin | 2010-08-17 22:49:09 +0200 (Di, 17 Aug 2010) | 2 lines
  
  Cleanup and correct a few ints to be Py_ssize_t.
................
  r84155 | antoine.pitrou | 2010-08-17 23:10:05 +0200 (Di, 17 Aug 2010) | 5 lines
  
  Issue #3488: Provide convenient shorthand functions `gzip.compress`
  and `gzip.decompress`.  Original patch by Anand B. Pillai.
................
  r84156 | antoine.pitrou | 2010-08-17 23:11:49 +0200 (Di, 17 Aug 2010) | 3 lines
  
  Modernize gzip examples
................
  r84157 | antoine.pitrou | 2010-08-17 23:15:00 +0200 (Di, 17 Aug 2010) | 3 lines
  
  Add versionadded tags
................
  r84159 | eric.araujo | 2010-08-17 23:24:05 +0200 (Di, 17 Aug 2010) | 1 line
  
  Fix example
................
  r84162 | victor.stinner | 2010-08-18 00:01:02 +0200 (Mi, 18 Aug 2010) | 3 lines
  
  Replace :func: by :cfunc:
  
  To get links to the C functions
................
  r84163 | victor.stinner | 2010-08-18 00:26:51 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Issue #8063: Call _PyGILState_Init() earlier in Py_InitializeEx().
................
  r84164 | victor.stinner | 2010-08-18 00:49:25 +0200 (Mi, 18 Aug 2010) | 7 lines
  
  libpython.py: py-bt commands escape unencodable characters
  
  Encode unicode strings to the terminal encoding with backslashreplace error (as
  Python does for sys.stderr) before writing them to sys.stdout. It fixes
  UnicodeEncodeError on writing non-ascii characters in an ascii terminal (C
  locale: ASCII encoding).
................
  r84165 | victor.stinner | 2010-08-18 00:54:21 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Remove unused functions _PyImport_FindModule and _PyImport_IsScript
................
  r84166 | martin.v.loewis | 2010-08-18 00:58:42 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Add Ask Solem.
................
  r84167 | martin.v.loewis | 2010-08-18 01:16:51 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Correct library name that Ask will work on.
................
  r84168 | victor.stinner | 2010-08-18 01:37:11 +0200 (Mi, 18 Aug 2010) | 6 lines
  
  Issue #9425: Create PyModule_GetFilenameObject() function
  
  ... to get the filename as a unicode object, instead of a byte string. Function
  needed to support unencodable filenames. Deprecate PyModule_GetFilename() in
  favor on the new function.
................
  r84170 | victor.stinner | 2010-08-18 12:56:19 +0200 (Mi, 18 Aug 2010) | 11 lines
  
  Improve PEP 383 tests (in test_os)
  
   * Use the current filesystem encoding instead of always using utf-8
   * Enable the test on Mac OS X
   * Use TESTFN_UNENCODABLE and TESTFN_UNICODE instead of arbitrary filenames
   * To decode a filename, use strict error handler instead surrogateescape for
     mbcs encoding (on Windows)
   * Use TESTFN_UNENCODABLE (if available) for the directory name
  
  Skip the test if no non-ascii filename can be created.
................
  r84171 | victor.stinner | 2010-08-18 12:57:33 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Add versionadded tag to PyModule_GetFilenameObject() doc
................
  r84172 | martin.v.loewis | 2010-08-18 18:12:23 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Restore GIL in nis_cat in case of error.
................
  r84173 | senthil.kumaran | 2010-08-18 21:32:21 +0200 (Mi, 18 Aug 2010) | 3 lines
  
  Fix Issue672656 - Securing pydoc server.
................
  r84176 | antoine.pitrou | 2010-08-18 22:44:14 +0200 (Mi, 18 Aug 2010) | 5 lines
  
  Issue #9433: The "-j" option to regrtest now works under Windows too.
  It is not sure it will be beneficial, though, since process launching is
  more expensive under Windows than it is under Linux.
................
  r84177 | amaury.forgeotdarc | 2010-08-18 22:44:58 +0200 (Mi, 18 Aug 2010) | 9 lines
  
  #5127: Even on narrow unicode builds, the C functions that access the Unicode
  Database (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and others) now accept
  and return characters from the full Unicode range (Py_UCS4).
  
  The differences from Python code are few:
  - unicodedata.numeric(), unicodedata.decimal() and unicodedata.digit()
    now return the correct value for large code points
  - repr() may consider more characters as printable.
................
  r84179 | antoine.pitrou | 2010-08-18 23:05:19 +0200 (Mi, 18 Aug 2010) | 4 lines
  
  Issue #5737: Add Solaris-specific mnemonics in the errno module.  Patch by
  Matthew Ahrens.
................
  r84180 | victor.stinner | 2010-08-18 23:06:23 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Decompose TESTFN_UNICODE on Mac OS X
................
  r84181 | amaury.forgeotdarc | 2010-08-18 23:12:52 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Fix stupid typo in test.
................
  r84182 | victor.stinner | 2010-08-18 23:23:25 +0200 (Mi, 18 Aug 2010) | 5 lines
  
  Issue #8622: Add PYTHONFSENCODING environment variable to override the
  filesystem encoding.
  
  initfsencoding() displays also a better error message if get_codeset() failed.
................
  r84183 | victor.stinner | 2010-08-18 23:59:12 +0200 (Mi, 18 Aug 2010) | 2 lines
  
  Fix reindent-rst.py: it works on binary files
................
  r84184 | amaury.forgeotdarc | 2010-08-19 00:07:15 +0200 (Do, 19 Aug 2010) | 3 lines
  
  Add more tests to unicodedata with large code points
  (the other functions where not affected by the recent change)
................
  r84185 | victor.stinner | 2010-08-19 00:23:22 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Improve error message if the command is not decodable
................
  r84186 | victor.stinner | 2010-08-19 00:26:50 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Fix PyUnicode_EncodeFSDefault() indentation
................
  r84187 | eric.araujo | 2010-08-19 00:29:54 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Fix indentation level
................
  r84188 | andrew.kuchling | 2010-08-19 00:30:34 +0200 (Do, 19 Aug 2010) | 2 lines
  
  #7647: add ST_RDONLY, ST_NOSUID constants to os module.
  (Also fix a name ordering in the ACKS file.)
................
  r84189 | eric.araujo | 2010-08-19 00:35:23 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Fix typo
................
  r84191 | victor.stinner | 2010-08-19 00:44:15 +0200 (Do, 19 Aug 2010) | 4 lines
  
  test_sys: move tests at the right place
  
  filesystem encoding is not related to sys.sizeof()
................
  r84193 | victor.stinner | 2010-08-19 01:41:33 +0200 (Do, 19 Aug 2010) | 2 lines
  
  what's new 3.2: use :mod:
................
  r84194 | victor.stinner | 2010-08-19 03:05:19 +0200 (Do, 19 Aug 2010) | 7 lines
  
  Create os.fsdecode(): decode from the filesystem encoding with surrogateescape
  error handler, or strict error handler on Windows.
  
   * Rewrite os.fsencode() documentation
   * Improve os.fsencode and os.fsdecode() tests using the new PYTHONFSENCODING
     environment variable
................
  r84195 | senthil.kumaran | 2010-08-19 09:02:20 +0200 (Do, 19 Aug 2010) | 3 lines
  
  Fix Issue9638 - remove dead code from py3k imaplib
................
  r84199 | martin.v.loewis | 2010-08-19 11:11:51 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Decode NIS data to fs encoding, using the surrogate error handler.
................
  r84200 | victor.stinner | 2010-08-19 13:17:12 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Fix test_os: workaround #8611 bug
................
  r84201 | victor.stinner | 2010-08-19 13:23:47 +0200 (Do, 19 Aug 2010) | 6 lines
  
  Fix test_sys about fs encoding for Windows and Mac OS X
  
   * Check fs encoding value on Windows
   * Ignore LANG= test on Windows and Mac OS X (fs encoding is hardcoded on these
     platforms)
................
  r84202 | victor.stinner | 2010-08-19 13:30:09 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Ooops, finish test_sys fix: use expected variable
................
  r84203 | victor.stinner | 2010-08-19 13:36:43 +0200 (Do, 19 Aug 2010) | 2 lines
  
  PYTHONFSENCODING is not available on Windows or Mac OS X
................
  r84204 | victor.stinner | 2010-08-19 19:10:18 +0200 (Do, 19 Aug 2010) | 4 lines
  
  Fix os.get_exec_path() (code and tests) for python -bb
  
  Catch BytesWarning exceptions.
................
  r84205 | victor.stinner | 2010-08-19 19:18:12 +0200 (Do, 19 Aug 2010) | 2 lines
  
  test_main_invalid_unicode() of test_sys displays stderr on failure
................
  r84206 | victor.stinner | 2010-08-19 19:22:57 +0200 (Do, 19 Aug 2010) | 2 lines
  
  Skip test_encodings() of test_os on Windows and Mac OS X
................
  r84208 | victor.stinner | 2010-08-19 19:35:00 +0200 (Do, 19 Aug 2010) | 2 lines
  
  test_pep277: display the filename as ascii on failure
................
  r84209 | amaury.forgeotdarc | 2010-08-19 19:43:15 +0200 (Do, 19 Aug 2010) | 5 lines
  
  Check the return values for all functions returning an ast node.
  Failure to do it may result in strange error messages or even crashes,
  in admittedly convoluted cases that are normally syntax errors, like:
      def f(*xx, __debug__): pass
................
  r84210 | senthil.kumaran | 2010-08-19 19:50:31 +0200 (Do, 19 Aug 2010) | 3 lines
  
  Fix Issue9639 - reset the retry count on successful auth.
................
  r84212 | vinay.sajip | 2010-08-19 21:17:41 +0200 (Do, 19 Aug 2010) | 1 line
  
  Issue #9606: Updated documentation for Filter objects.
................
  r84214 | amaury.forgeotdarc | 2010-08-19 23:32:38 +0200 (Do, 19 Aug 2010) | 3 lines
  
  Add tests for r84209 (crashes in the Ast builder)
  Also remove one tab, and move a check closer to the possible failure.
................
  r84218 | vinay.sajip | 2010-08-20 00:20:22 +0200 (Fr, 20 Aug 2010) | 1 line
  
  Issue #7077: Fixed SysLogHandler implementation of Unicode handling.
................
  r84221 | tim.golden | 2010-08-20 10:31:26 +0200 (Fr, 20 Aug 2010) | 1 line
  
  Remove long-redundant plat-win from sys.path on Windows
................
  r84222 | vinay.sajip | 2010-08-20 10:43:22 +0200 (Fr, 20 Aug 2010) | 1 line
  
  Issue #7077: Fixed bug in previous fix.
................
  r84223 | victor.stinner | 2010-08-20 13:08:18 +0200 (Fr, 20 Aug 2010) | 9 lines
  
  test_main_invalid_unicode() of test_sys: print string as ascii
  
  There are buildbot failures on "x86 FreeBSD 3.x" and "sparc solaris10 gcc 3.x".
  I suppose that _Py_char2wchar() doesn't fail even if the locale encoding is
  unable to decode the byte string, because _Py_char2wchar() has a special mode
  for platform without mbrtowc() (ISO C99) function.
  
  Let's check my theory by avoid error on the Python print() instruction.
................
  r84224 | victor.stinner | 2010-08-20 18:38:14 +0200 (Fr, 20 Aug 2010) | 10 lines
  
  test_undecodable_code(): set locale to C
  
  The test is still failing on "x86 FreeBSD 7.2 3.x" and "sparc solaris10 gcc
  3.x" buildbots. It looks like the locale encoding is able to decode b'\xff'. I
  suppose that it is an encoding like 'iso-8859-1'.
  
  Use C locale to set, I hope, the locale encoding to 'ascii'. Display also the
  encoding so if the test fails, at least I will learn the locale encoding
  choosen for the C locale.
................
  r84225 | victor.stinner | 2010-08-20 18:52:14 +0200 (Fr, 20 Aug 2010) | 5 lines
  
  Workaround issue #8611 in test_undecodable_code() of test_sys
  
  Write test.support.workaroundIssue8611() function so it will be easier to
  remove this workaround from all tests.
................
  r84226 | benjamin.peterson | 2010-08-21 04:41:33 +0200 (Sa, 21 Aug 2010) | 1 line
  
  remove outdated comment
................
  r84227 | benjamin.peterson | 2010-08-21 04:43:31 +0200 (Sa, 21 Aug 2010) | 1 line
  
  use blank object instead
................
  r84228 | benjamin.peterson | 2010-08-21 04:45:15 +0200 (Sa, 21 Aug 2010) | 1 line
  
  speed hack can be implemented more cleanly by directly calling __new__
................
  r84229 | benjamin.peterson | 2010-08-21 04:54:44 +0200 (Sa, 21 Aug 2010) | 1 line
  
  alias macintosh to mac_roman #843590
................
  r84231 | marc-andre.lemburg | 2010-08-21 12:58:31 +0200 (Sa, 21 Aug 2010) | 3 lines
  
  Fix a typo in the alias target name for 'macintosh'.
................
  r84234 | senthil.kumaran | 2010-08-21 18:08:32 +0200 (Sa, 21 Aug 2010) | 3 lines
  
  Add info about HTTP/1.1 and Connection:Close header.
................
  r84236 | giampaolo.rodola | 2010-08-21 20:35:05 +0200 (Sa, 21 Aug 2010) | 1 line
  
  fix issue #9129: added proper error handling when accepting new connections in SMTPServer.handle_accept
................
  r84237 | giampaolo.rodola | 2010-08-21 20:47:59 +0200 (Sa, 21 Aug 2010) | 1 line
  
  revert changes made in r84236 committed by accident
................
  r84238 | giampaolo.rodola | 2010-08-21 20:58:21 +0200 (Sa, 21 Aug 2010) | 1 line
  
  fix smtpd.py I accidentally broke in my previous commit
................
  r84239 | antoine.pitrou | 2010-08-21 21:09:32 +0200 (Sa, 21 Aug 2010) | 4 lines
  
  Issue #9617: Signals received during a low-level write operation aren't
  ignored by the buffered IO layer anymore.
................
  r84242 | benjamin.peterson | 2010-08-21 22:01:28 +0200 (Sa, 21 Aug 2010) | 1 line
  
  indent properly
................
  r84243 | benjamin.peterson | 2010-08-21 22:03:15 +0200 (Sa, 21 Aug 2010) | 1 line
  
  fix more indentation
................
  r84244 | benjamin.peterson | 2010-08-21 22:08:36 +0200 (Sa, 21 Aug 2010) | 1 line
  
  provide sample implementations for attrgetter and methodcaller
................
  r84247 | giampaolo.rodola | 2010-08-21 22:34:37 +0200 (Sa, 21 Aug 2010) | 1 line
  
  remove obsolete 'import SOCKS' statement
................
  r84248 | benjamin.peterson | 2010-08-21 23:23:28 +0200 (Sa, 21 Aug 2010) | 1 line
  
  fix old markup
................
  r84249 | georg.brandl | 2010-08-22 01:20:01 +0200 (So, 22 Aug 2010) | 1 line
  
  Remove usage of rexec in tkinter demo.
................
  r84252 | raymond.hettinger | 2010-08-22 09:44:24 +0200 (So, 22 Aug 2010) | 1 line
  
  Issue #9214:  Fix set operations on KeysView and ItemsView.
................
  r84256 | raymond.hettinger | 2010-08-22 10:39:49 +0200 (So, 22 Aug 2010) | 1 line
  
  Issue 8403:  Don't mask KeyboardInterrupt during peephole operation.
................
  r84257 | martin.v.loewis | 2010-08-22 10:46:19 +0200 (So, 22 Aug 2010) | 2 lines
  
  Add Daniel Stutzbach.
................
  r84258 | antoine.pitrou | 2010-08-22 12:18:36 +0200 (So, 22 Aug 2010) | 4 lines
  
  Test that calls to path hooks and meta_path entries are serialized by the import lock.
  (part of issue #9251)
................
  r84259 | vinay.sajip | 2010-08-22 20:11:02 +0200 (So, 22 Aug 2010) | 1 line
  
  Issue #9512: Made comment more informative.
................
  r84260 | vinay.sajip | 2010-08-22 20:41:24 +0200 (So, 22 Aug 2010) | 1 line
  
  Updated maintainers.rst to reflect correct Roundup name.
................
  r84261 | martin.v.loewis | 2010-08-22 21:33:47 +0200 (So, 22 Aug 2010) | 3 lines
  
  Issue #1027206: Support IDNA in gethostbyname, gethostbyname_ex and
  getaddrinfo. Patch by David Watson.
................
  r84262 | martin.v.loewis | 2010-08-22 21:38:04 +0200 (So, 22 Aug 2010) | 2 lines
  
  Mention that gethostbyaddr now also supports IDNA.
................
  r84263 | daniel.stutzbach | 2010-08-22 21:41:04 +0200 (So, 22 Aug 2010) | 1 line
  
  Added myself to Misc/maintainers.rst for topics on which I'd like to be added to the nosy list
................
  r84264 | georg.brandl | 2010-08-22 22:23:38 +0200 (So, 22 Aug 2010) | 1 line
  
  #9649: fix default value description.
................
  r84265 | brett.cannon | 2010-08-22 22:36:25 +0200 (So, 22 Aug 2010) | 6 lines
  
  Under OS X, history_get from readline returns a const char *, but the local
  variable the return value is assigned to is char *. Since the assigned-to
  variable is never changed, simply make that a const char * and cast all calls
  to get_history to const char * to silence the compiler warning (found with
  LLVM).
................
  r84267 | brett.cannon | 2010-08-22 22:38:47 +0200 (So, 22 Aug 2010) | 4 lines
  
  While not strictly necessary thanks to the odd ABC inheritance done through
  importlib._bootstrap, add the optional methods for importlib.abc.SourceLoader
  for completeness.
................
  r84268 | antoine.pitrou | 2010-08-22 22:43:26 +0200 (So, 22 Aug 2010) | 4 lines
  
  Add an import lock test for multithreaded circular imports.
  (part of #9657)
................
  r84270 | brett.cannon | 2010-08-23 00:11:06 +0200 (Mo, 23 Aug 2010) | 3 lines
  
  Make sure that no __pycache__ directory is needlessly left behind when testing
  imports with an empty string in sys.path.
................
  r84271 | brett.cannon | 2010-08-23 00:19:11 +0200 (Mo, 23 Aug 2010) | 11 lines
  
  One of the joys of having test_multiprocessing occasionally execute after
  test_importlib is that it discovers special little race conditions. For
  instance, it turns out that importlib would throw an exception if two different
  Python processes both tried to create the __pycache__ directory as one process
  would succeed, causing the other process to fail as it didn't expect to get any
  "help". So now importlib simply stays calm and just accepts someone else did
  the work of creating the __pycache__ directory for it, moving on with life.
  
  Closes issue #9572.
................
  r84277 | martin.v.loewis | 2010-08-23 17:27:26 +0200 (Mo, 23 Aug 2010) | 5 lines
  
  Explicitly pass socket type and family for getaddrinfo,
  to make test work on Solaris.
  Disable gethostbyaddr IDNA test for now as there is no
  reverse DNS entry for the IPv6 address of the test name.
................
  r84278 | matthias.klose | 2010-08-23 18:47:09 +0200 (Mo, 23 Aug 2010) | 4 lines
  
  Fix builds with builddir != srcdir, introduced in r83988.
  os.path.dirname(__file__) points to the scrdir, not the builddir.
  Use os.getcwd() instead.
................
  r84279 | benjamin.peterson | 2010-08-23 19:40:33 +0200 (Mo, 23 Aug 2010) | 1 line
  
  run total_ordering() tests, and fix the function (default comparisons shouldn't be considered)
................
  r84281 | benjamin.peterson | 2010-08-23 19:47:43 +0200 (Mo, 23 Aug 2010) | 1 line
  
  news note for last change
................
  r84282 | vinay.sajip | 2010-08-23 19:50:30 +0200 (Mo, 23 Aug 2010) | 1 line
  
  Issue #9501: Fixed logging regressions in cleanup code.
................
  r84283 | benjamin.peterson | 2010-08-23 21:35:39 +0200 (Mo, 23 Aug 2010) | 1 line
  
  reorder and save a comparison
................
  r84284 | giampaolo.rodola | 2010-08-23 23:53:41 +0200 (Mo, 23 Aug 2010) | 1 line
  
  fix issue 658749: correctly interprets asyncore's windows errors on connect()
................
  r84287 | benjamin.peterson | 2010-08-23 23:58:59 +0200 (Mo, 23 Aug 2010) | 1 line
  
  cleanup imports
................
  r84288 | giampaolo.rodola | 2010-08-24 00:10:32 +0200 (Di, 24 Aug 2010) | 1 line
  
  fix issue 9601: ftplib now provides a workaround for invalid response code returned on MKD and PWD by non-compliant FTPserver implementations such as ISS shipped with Windows server 2003
................
  r84289 | giampaolo.rodola | 2010-08-24 00:28:13 +0200 (Di, 24 Aug 2010) | 1 line
  
  fix issue 9129: adds proper error handling on accept() when smtpd accepts new incoming connections.
................
  r84294 | benjamin.peterson | 2010-08-24 05:26:23 +0200 (Di, 24 Aug 2010) | 1 line
  
  only catch AttributeError in hasattr() #9666
................
  r84295 | brian.curtin | 2010-08-24 07:20:30 +0200 (Di, 24 Aug 2010) | 2 lines
  
  Fix #7579. Add docstrings to msvcrt and adjust some wording for bytes.
................
  r84299 | benjamin.peterson | 2010-08-24 20:08:22 +0200 (Di, 24 Aug 2010) | 1 line
  
  tabbing no longer applicable
................
  r84301 | daniel.stutzbach | 2010-08-24 22:49:57 +0200 (Di, 24 Aug 2010) | 1 line
  
  Issue 8750: Fixed MutableSet's methods to correctly handle reflexive operations, namely x -= x and x ^= x
................
  r84303 | benjamin.peterson | 2010-08-24 23:03:37 +0200 (Di, 24 Aug 2010) | 1 line
  
  further clarify
................
  r84304 | brett.cannon | 2010-08-24 23:04:05 +0200 (Di, 24 Aug 2010) | 5 lines
  
  Fix a bug where an attribute was lacking an object to work off of.
  
  Related to the fix for issue #9572. Thanks to Łukasz Czuja for catching the
  bug.
................
  r84306 | benjamin.peterson | 2010-08-24 23:30:14 +0200 (Di, 24 Aug 2010) | 1 line
  
  remove parens
................
  r84307 | daniel.stutzbach | 2010-08-24 23:57:33 +0200 (Di, 24 Aug 2010) | 1 line
  
  Issue 8781: On systems a signed 4-byte wchar_t and a 4-byte Py_UNICODE, use memcpy to convert between the two (as already done when wchar_t is unsigned)
................
  r84308 | victor.stinner | 2010-08-25 01:05:51 +0200 (Mi, 25 Aug 2010) | 7 lines
  
  Fix test_sys for FreeBSD, Solaris and Mac OS X
  
  _Py_char2wchar() (mbctowcs) decodes b'\xff' to '\xff' on FreeBSD, Solaris and
  Mac OS X, even if the locale is C (and the locale encoding is ASCII). Patch
  test_undecodable_code() to support this output and document the two different
  kinds of outputs.
................
  r84309 | victor.stinner | 2010-08-25 02:20:27 +0200 (Mi, 25 Aug 2010) | 4 lines
  
  Disable test_undecodable_code() of test_sys on Windows
  
  This test is irrevelant on Windows
................
  r84310 | r.david.murray | 2010-08-25 02:45:55 +0200 (Mi, 25 Aug 2010) | 8 lines
  
  #1194222: make parsedate always return RFC2822 four character years.
  
  Two character years are now converted to four character years using
  the Posix standard rule (<68 == 2000, >=68==1900).  This makes the
  parsed date RFC2822 compliant even if the input is not.
  
  Patch and test by Jeffrey Finkelstein.
................
  r84313 | martin.v.loewis | 2010-08-25 09:38:15 +0200 (Mi, 25 Aug 2010) | 2 lines
  
  Issue #1027206: getnameinfo is now restricted to numeric addresses as input.
................
  r84314 | victor.stinner | 2010-08-25 10:33:34 +0200 (Mi, 25 Aug 2010) | 5 lines
  
  Fix test_sys: set LC_ALL instead of LANG
  
  LC_ALL is read before LANG to choose the locale encoding (LC_ALL, LANG and then
  LC_CTYPE: use the first non empty variable).
................
  r84315 | benjamin.peterson | 2010-08-25 19:02:22 +0200 (Mi, 25 Aug 2010) | 1 line
  
  this test is only valid when sizeof(wchar) == Py_UNICODE_SIZE
................
  r84316 | benjamin.peterson | 2010-08-25 19:57:04 +0200 (Mi, 25 Aug 2010) | 1 line
  
  apparently this test should be gated, too
................
  r84317 | daniel.stutzbach | 2010-08-25 21:18:59 +0200 (Mi, 25 Aug 2010) | 1 line
  
  Issue 8781: Define SIZEOF_WCHAR_T on Windows
................
  r84319 | martin.v.loewis | 2010-08-26 00:15:18 +0200 (Do, 26 Aug 2010) | 2 lines
  
  Disable deletion of openssl again.
................
  r84320 | benjamin.peterson | 2010-08-26 01:13:17 +0200 (Do, 26 Aug 2010) | 1 line
  
  basicsize and itemsize are Py_ssize_t #9688
................
  r84323 | senthil.kumaran | 2010-08-26 08:16:22 +0200 (Do, 26 Aug 2010) | 3 lines
  
  Fix Issue8797 - Reset the basic auth retry count when response code is not 401.
................
  r84326 | georg.brandl | 2010-08-26 16:30:15 +0200 (Do, 26 Aug 2010) | 1 line
  
  #9689: add links from overview to in-depth class API descriptions.
................
  r84327 | georg.brandl | 2010-08-26 16:30:56 +0200 (Do, 26 Aug 2010) | 1 line
  
  #9681: typo.
................
  r84329 | brett.cannon | 2010-08-26 23:07:13 +0200 (Do, 26 Aug 2010) | 5 lines
  
  OSError is the exception raised when one tries to create a directory that
  already exists, not IOError.
  
  Part of the continuing saga of issue #9572.
................


Added:
   python/branches/pep-0384/Include/pytime.h
      - copied unchanged from r84329, /python/branches/py3k/Include/pytime.h
   python/branches/pep-0384/Lib/datetime.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/datetime.py
   python/branches/pep-0384/Lib/test/cfgparser.2
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/cfgparser.2
   python/branches/pep-0384/Lib/test/cfgparser.3
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/cfgparser.3
   python/branches/pep-0384/Lib/test/data/README
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/data/README
   python/branches/pep-0384/Lib/test/datetimetester.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/datetimetester.py
   python/branches/pep-0384/Lib/test/mock_socket.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/mock_socket.py
   python/branches/pep-0384/Lib/test/test_rlcompleter.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/test_rlcompleter.py
   python/branches/pep-0384/Lib/test/test_sched.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/test_sched.py
   python/branches/pep-0384/Lib/test/test_smtpd.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/test_smtpd.py
   python/branches/pep-0384/Lib/test/test_sys_setprofile.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/test_sys_setprofile.py
   python/branches/pep-0384/Lib/test/test_sys_settrace.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/test_sys_settrace.py
   python/branches/pep-0384/Lib/test/test_trace.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/test/test_trace.py
   python/branches/pep-0384/Lib/tkinter/__main__.py
      - copied unchanged from r84329, /python/branches/py3k/Lib/tkinter/__main__.py
   python/branches/pep-0384/Modules/_datetimemodule.c
      - copied unchanged from r84329, /python/branches/py3k/Modules/_datetimemodule.c
   python/branches/pep-0384/Python/pytime.c
      - copied unchanged from r84329, /python/branches/py3k/Python/pytime.c
Removed:
   python/branches/pep-0384/Demo/pdist/
   python/branches/pep-0384/Demo/scripts/toaiff.py
   python/branches/pep-0384/Lib/test/test_SimpleHTTPServer.py
   python/branches/pep-0384/Lib/test/test_line_tracing.py
   python/branches/pep-0384/Lib/test/test_profilehooks.py
   python/branches/pep-0384/Modules/datetimemodule.c
   python/branches/pep-0384/Tools/faqwiz/
   python/branches/pep-0384/Tools/scripts/checkappend.py
   python/branches/pep-0384/Tools/scripts/classfix.py
   python/branches/pep-0384/Tools/scripts/cvsfiles.py
   python/branches/pep-0384/Tools/scripts/logmerge.py
   python/branches/pep-0384/Tools/scripts/methfix.py
   python/branches/pep-0384/Tools/scripts/setup.py
   python/branches/pep-0384/Tools/scripts/xxci.py
   python/branches/pep-0384/Tools/versioncheck/
Modified:
   python/branches/pep-0384/   (props changed)
   python/branches/pep-0384/.bzrignore
   python/branches/pep-0384/.hgignore
   python/branches/pep-0384/Demo/README
   python/branches/pep-0384/Demo/embed/Makefile
   python/branches/pep-0384/Demo/embed/demo.c
   python/branches/pep-0384/Demo/embed/loop.c
   python/branches/pep-0384/Demo/scripts/README
   python/branches/pep-0384/Demo/tkinter/guido/AttrDialog.py
   python/branches/pep-0384/Demo/tkinter/guido/ManPage.py
   python/branches/pep-0384/Demo/tkinter/guido/brownian2.py
   python/branches/pep-0384/Demo/tkinter/guido/kill.py
   python/branches/pep-0384/Demo/tkinter/guido/ss1.py
   python/branches/pep-0384/Demo/zlib/minigzip.py
   python/branches/pep-0384/Demo/zlib/zlibdemo.py
   python/branches/pep-0384/Doc/Makefile
   python/branches/pep-0384/Doc/README.txt
   python/branches/pep-0384/Doc/c-api/abstract.rst
   python/branches/pep-0384/Doc/c-api/arg.rst
   python/branches/pep-0384/Doc/c-api/bytes.rst
   python/branches/pep-0384/Doc/c-api/dict.rst
   python/branches/pep-0384/Doc/c-api/exceptions.rst
   python/branches/pep-0384/Doc/c-api/file.rst
   python/branches/pep-0384/Doc/c-api/import.rst
   python/branches/pep-0384/Doc/c-api/init.rst
   python/branches/pep-0384/Doc/c-api/long.rst
   python/branches/pep-0384/Doc/c-api/module.rst
   python/branches/pep-0384/Doc/c-api/sys.rst
   python/branches/pep-0384/Doc/c-api/unicode.rst
   python/branches/pep-0384/Doc/c-api/weakref.rst
   python/branches/pep-0384/Doc/conf.py
   python/branches/pep-0384/Doc/distutils/apiref.rst
   python/branches/pep-0384/Doc/distutils/builtdist.rst
   python/branches/pep-0384/Doc/distutils/commandref.rst
   python/branches/pep-0384/Doc/distutils/examples.rst
   python/branches/pep-0384/Doc/distutils/extending.rst
   python/branches/pep-0384/Doc/distutils/sourcedist.rst
   python/branches/pep-0384/Doc/distutils/uploading.rst
   python/branches/pep-0384/Doc/documenting/building.rst   (props changed)
   python/branches/pep-0384/Doc/documenting/markup.rst
   python/branches/pep-0384/Doc/extending/extending.rst
   python/branches/pep-0384/Doc/faq/library.rst
   python/branches/pep-0384/Doc/howto/descriptor.rst   (props changed)
   python/branches/pep-0384/Doc/howto/doanddont.rst
   python/branches/pep-0384/Doc/install/index.rst
   python/branches/pep-0384/Doc/library/2to3.rst
   python/branches/pep-0384/Doc/library/abc.rst
   python/branches/pep-0384/Doc/library/argparse.rst
   python/branches/pep-0384/Doc/library/base64.rst
   python/branches/pep-0384/Doc/library/bdb.rst
   python/branches/pep-0384/Doc/library/binascii.rst
   python/branches/pep-0384/Doc/library/bisect.rst
   python/branches/pep-0384/Doc/library/cgi.rst
   python/branches/pep-0384/Doc/library/cmd.rst
   python/branches/pep-0384/Doc/library/codecs.rst
   python/branches/pep-0384/Doc/library/collections.rst
   python/branches/pep-0384/Doc/library/configparser.rst
   python/branches/pep-0384/Doc/library/constants.rst
   python/branches/pep-0384/Doc/library/contextlib.rst
   python/branches/pep-0384/Doc/library/datetime.rst
   python/branches/pep-0384/Doc/library/dbm.rst
   python/branches/pep-0384/Doc/library/decimal.rst
   python/branches/pep-0384/Doc/library/dis.rst
   python/branches/pep-0384/Doc/library/doctest.rst
   python/branches/pep-0384/Doc/library/email.errors.rst
   python/branches/pep-0384/Doc/library/fileinput.rst
   python/branches/pep-0384/Doc/library/fnmatch.rst
   python/branches/pep-0384/Doc/library/ftplib.rst
   python/branches/pep-0384/Doc/library/functions.rst
   python/branches/pep-0384/Doc/library/functools.rst
   python/branches/pep-0384/Doc/library/gc.rst
   python/branches/pep-0384/Doc/library/gzip.rst
   python/branches/pep-0384/Doc/library/hashlib.rst
   python/branches/pep-0384/Doc/library/heapq.rst
   python/branches/pep-0384/Doc/library/html.parser.rst
   python/branches/pep-0384/Doc/library/http.client.rst
   python/branches/pep-0384/Doc/library/importlib.rst
   python/branches/pep-0384/Doc/library/io.rst
   python/branches/pep-0384/Doc/library/itertools.rst
   python/branches/pep-0384/Doc/library/json.rst
   python/branches/pep-0384/Doc/library/linecache.rst
   python/branches/pep-0384/Doc/library/locale.rst
   python/branches/pep-0384/Doc/library/logging.rst
   python/branches/pep-0384/Doc/library/mmap.rst
   python/branches/pep-0384/Doc/library/msvcrt.rst
   python/branches/pep-0384/Doc/library/operator.rst
   python/branches/pep-0384/Doc/library/optparse.rst
   python/branches/pep-0384/Doc/library/os.path.rst
   python/branches/pep-0384/Doc/library/os.rst
   python/branches/pep-0384/Doc/library/parser.rst
   python/branches/pep-0384/Doc/library/pdb.rst
   python/branches/pep-0384/Doc/library/pickletools.rst
   python/branches/pep-0384/Doc/library/poplib.rst
   python/branches/pep-0384/Doc/library/pyexpat.rst
   python/branches/pep-0384/Doc/library/re.rst
   python/branches/pep-0384/Doc/library/runpy.rst
   python/branches/pep-0384/Doc/library/signal.rst
   python/branches/pep-0384/Doc/library/smtpd.rst
   python/branches/pep-0384/Doc/library/smtplib.rst
   python/branches/pep-0384/Doc/library/socket.rst
   python/branches/pep-0384/Doc/library/sqlite3.rst
   python/branches/pep-0384/Doc/library/stdtypes.rst
   python/branches/pep-0384/Doc/library/string.rst
   python/branches/pep-0384/Doc/library/subprocess.rst
   python/branches/pep-0384/Doc/library/sys.rst
   python/branches/pep-0384/Doc/library/test.rst
   python/branches/pep-0384/Doc/library/threading.rst
   python/branches/pep-0384/Doc/library/tkinter.rst
   python/branches/pep-0384/Doc/library/unittest.rst
   python/branches/pep-0384/Doc/library/urllib.parse.rst
   python/branches/pep-0384/Doc/library/urllib.request.rst
   python/branches/pep-0384/Doc/library/wsgiref.rst
   python/branches/pep-0384/Doc/library/xml.dom.minidom.rst
   python/branches/pep-0384/Doc/library/xml.dom.rst
   python/branches/pep-0384/Doc/library/xml.etree.elementtree.rst
   python/branches/pep-0384/Doc/library/xml.sax.reader.rst
   python/branches/pep-0384/Doc/library/zipfile.rst
   python/branches/pep-0384/Doc/library/zipimport.rst
   python/branches/pep-0384/Doc/license.rst
   python/branches/pep-0384/Doc/make.bat
   python/branches/pep-0384/Doc/reference/compound_stmts.rst
   python/branches/pep-0384/Doc/reference/lexical_analysis.rst
   python/branches/pep-0384/Doc/tools/sphinx-build.py
   python/branches/pep-0384/Doc/tools/sphinxext/pyspecific.py
   python/branches/pep-0384/Doc/tutorial/classes.rst
   python/branches/pep-0384/Doc/tutorial/datastructures.rst
   python/branches/pep-0384/Doc/tutorial/floatingpoint.rst
   python/branches/pep-0384/Doc/using/cmdline.rst
   python/branches/pep-0384/Doc/whatsnew/2.0.rst
   python/branches/pep-0384/Doc/whatsnew/2.4.rst
   python/branches/pep-0384/Doc/whatsnew/2.5.rst
   python/branches/pep-0384/Doc/whatsnew/2.7.rst
   python/branches/pep-0384/Doc/whatsnew/3.2.rst
   python/branches/pep-0384/Include/Python.h
   python/branches/pep-0384/Include/floatobject.h
   python/branches/pep-0384/Include/moduleobject.h
   python/branches/pep-0384/Include/patchlevel.h
   python/branches/pep-0384/Include/pyport.h
   python/branches/pep-0384/Include/pythonrun.h
   python/branches/pep-0384/Include/setobject.h
   python/branches/pep-0384/Include/structseq.h
   python/branches/pep-0384/Include/sysmodule.h
   python/branches/pep-0384/Include/unicodeobject.h
   python/branches/pep-0384/Include/warnings.h
   python/branches/pep-0384/LICENSE
   python/branches/pep-0384/Lib/_abcoll.py
   python/branches/pep-0384/Lib/abc.py
   python/branches/pep-0384/Lib/argparse.py
   python/branches/pep-0384/Lib/asyncore.py
   python/branches/pep-0384/Lib/base64.py
   python/branches/pep-0384/Lib/bdb.py
   python/branches/pep-0384/Lib/cProfile.py
   python/branches/pep-0384/Lib/cgi.py
   python/branches/pep-0384/Lib/cmd.py
   python/branches/pep-0384/Lib/collections.py
   python/branches/pep-0384/Lib/configparser.py
   python/branches/pep-0384/Lib/ctypes/__init__.py
   python/branches/pep-0384/Lib/ctypes/test/test_arrays.py
   python/branches/pep-0384/Lib/ctypes/test/test_bitfields.py
   python/branches/pep-0384/Lib/ctypes/test/test_buffers.py
   python/branches/pep-0384/Lib/ctypes/test/test_bytes.py
   python/branches/pep-0384/Lib/ctypes/test/test_callbacks.py
   python/branches/pep-0384/Lib/ctypes/test/test_cast.py
   python/branches/pep-0384/Lib/ctypes/test/test_cfuncs.py
   python/branches/pep-0384/Lib/ctypes/test/test_errno.py
   python/branches/pep-0384/Lib/ctypes/test/test_internals.py
   python/branches/pep-0384/Lib/ctypes/test/test_keeprefs.py
   python/branches/pep-0384/Lib/ctypes/test/test_libc.py
   python/branches/pep-0384/Lib/ctypes/test/test_loading.py
   python/branches/pep-0384/Lib/ctypes/test/test_objects.py
   python/branches/pep-0384/Lib/ctypes/test/test_parameters.py
   python/branches/pep-0384/Lib/ctypes/test/test_prototypes.py
   python/branches/pep-0384/Lib/ctypes/test/test_python_api.py
   python/branches/pep-0384/Lib/ctypes/test/test_random_things.py
   python/branches/pep-0384/Lib/ctypes/test/test_repr.py
   python/branches/pep-0384/Lib/ctypes/test/test_returnfuncptrs.py
   python/branches/pep-0384/Lib/ctypes/test/test_stringptr.py
   python/branches/pep-0384/Lib/ctypes/test/test_strings.py
   python/branches/pep-0384/Lib/ctypes/test/test_structures.py
   python/branches/pep-0384/Lib/ctypes/test/test_unicode.py
   python/branches/pep-0384/Lib/curses/wrapper.py
   python/branches/pep-0384/Lib/dbm/__init__.py
   python/branches/pep-0384/Lib/dis.py
   python/branches/pep-0384/Lib/distutils/__init__.py
   python/branches/pep-0384/Lib/distutils/command/bdist_msi.py
   python/branches/pep-0384/Lib/distutils/command/bdist_wininst.py
   python/branches/pep-0384/Lib/distutils/command/sdist.py
   python/branches/pep-0384/Lib/distutils/sysconfig.py
   python/branches/pep-0384/Lib/distutils/tests/test_log.py   (props changed)
   python/branches/pep-0384/Lib/distutils/tests/test_sdist.py
   python/branches/pep-0384/Lib/distutils/tests/test_sysconfig.py
   python/branches/pep-0384/Lib/doctest.py
   python/branches/pep-0384/Lib/email/_parseaddr.py
   python/branches/pep-0384/Lib/email/base64mime.py
   python/branches/pep-0384/Lib/email/header.py
   python/branches/pep-0384/Lib/email/message.py
   python/branches/pep-0384/Lib/email/test/test_email.py
   python/branches/pep-0384/Lib/encodings/aliases.py
   python/branches/pep-0384/Lib/fileinput.py
   python/branches/pep-0384/Lib/fnmatch.py
   python/branches/pep-0384/Lib/ftplib.py
   python/branches/pep-0384/Lib/functools.py
   python/branches/pep-0384/Lib/getopt.py
   python/branches/pep-0384/Lib/gzip.py
   python/branches/pep-0384/Lib/hmac.py
   python/branches/pep-0384/Lib/http/client.py
   python/branches/pep-0384/Lib/http/cookiejar.py
   python/branches/pep-0384/Lib/http/cookies.py
   python/branches/pep-0384/Lib/http/server.py
   python/branches/pep-0384/Lib/idlelib/NEWS.txt
   python/branches/pep-0384/Lib/idlelib/PyShell.py
   python/branches/pep-0384/Lib/idlelib/idlever.py
   python/branches/pep-0384/Lib/imaplib.py
   python/branches/pep-0384/Lib/importlib/_bootstrap.py
   python/branches/pep-0384/Lib/importlib/abc.py
   python/branches/pep-0384/Lib/importlib/test/source/test_file_loader.py
   python/branches/pep-0384/Lib/inspect.py
   python/branches/pep-0384/Lib/json/__init__.py
   python/branches/pep-0384/Lib/json/decoder.py
   python/branches/pep-0384/Lib/json/encoder.py
   python/branches/pep-0384/Lib/lib2to3/   (props changed)
   python/branches/pep-0384/Lib/lib2to3/fixer_util.py
   python/branches/pep-0384/Lib/lib2to3/fixes/fix_itertools_imports.py
   python/branches/pep-0384/Lib/lib2to3/fixes/fix_operator.py
   python/branches/pep-0384/Lib/lib2to3/fixes/fix_urllib.py
   python/branches/pep-0384/Lib/lib2to3/pytree.py
   python/branches/pep-0384/Lib/lib2to3/refactor.py
   python/branches/pep-0384/Lib/lib2to3/tests/test_fixers.py
   python/branches/pep-0384/Lib/lib2to3/tests/test_pytree.py
   python/branches/pep-0384/Lib/lib2to3/tests/test_util.py
   python/branches/pep-0384/Lib/logging/__init__.py
   python/branches/pep-0384/Lib/logging/config.py
   python/branches/pep-0384/Lib/logging/handlers.py
   python/branches/pep-0384/Lib/mailbox.py   (props changed)
   python/branches/pep-0384/Lib/multiprocessing/connection.py
   python/branches/pep-0384/Lib/multiprocessing/forking.py
   python/branches/pep-0384/Lib/multiprocessing/heap.py
   python/branches/pep-0384/Lib/multiprocessing/reduction.py
   python/branches/pep-0384/Lib/ntpath.py
   python/branches/pep-0384/Lib/os.py
   python/branches/pep-0384/Lib/pdb.py
   python/branches/pep-0384/Lib/pickle.py
   python/branches/pep-0384/Lib/pickletools.py
   python/branches/pep-0384/Lib/platform.py
   python/branches/pep-0384/Lib/poplib.py
   python/branches/pep-0384/Lib/posixpath.py
   python/branches/pep-0384/Lib/profile.py
   python/branches/pep-0384/Lib/pstats.py
   python/branches/pep-0384/Lib/pydoc.py
   python/branches/pep-0384/Lib/pydoc_data/topics.py
   python/branches/pep-0384/Lib/re.py
   python/branches/pep-0384/Lib/site.py
   python/branches/pep-0384/Lib/smtpd.py
   python/branches/pep-0384/Lib/smtplib.py
   python/branches/pep-0384/Lib/ssl.py
   python/branches/pep-0384/Lib/string.py
   python/branches/pep-0384/Lib/subprocess.py
   python/branches/pep-0384/Lib/sysconfig.py
   python/branches/pep-0384/Lib/test/formatfloat_testcases.txt
   python/branches/pep-0384/Lib/test/regrtest.py
   python/branches/pep-0384/Lib/test/script_helper.py
   python/branches/pep-0384/Lib/test/sortperf.py
   python/branches/pep-0384/Lib/test/support.py
   python/branches/pep-0384/Lib/test/test_abc.py
   python/branches/pep-0384/Lib/test/test_argparse.py
   python/branches/pep-0384/Lib/test/test_asyncore.py
   python/branches/pep-0384/Lib/test/test_binascii.py
   python/branches/pep-0384/Lib/test/test_binop.py
   python/branches/pep-0384/Lib/test/test_builtin.py
   python/branches/pep-0384/Lib/test/test_bytes.py
   python/branches/pep-0384/Lib/test/test_bz2.py
   python/branches/pep-0384/Lib/test/test_calendar.py
   python/branches/pep-0384/Lib/test/test_cfgparser.py
   python/branches/pep-0384/Lib/test/test_cmd.py
   python/branches/pep-0384/Lib/test/test_cmd_line.py
   python/branches/pep-0384/Lib/test/test_cmd_line_script.py
   python/branches/pep-0384/Lib/test/test_collections.py
   python/branches/pep-0384/Lib/test/test_complex.py
   python/branches/pep-0384/Lib/test/test_curses.py
   python/branches/pep-0384/Lib/test/test_datetime.py
   python/branches/pep-0384/Lib/test/test_dis.py
   python/branches/pep-0384/Lib/test/test_doctest.py
   python/branches/pep-0384/Lib/test/test_fileinput.py
   python/branches/pep-0384/Lib/test/test_float.py
   python/branches/pep-0384/Lib/test/test_fnmatch.py
   python/branches/pep-0384/Lib/test/test_ftplib.py
   python/branches/pep-0384/Lib/test/test_functools.py
   python/branches/pep-0384/Lib/test/test_gc.py
   python/branches/pep-0384/Lib/test/test_genericpath.py
   python/branches/pep-0384/Lib/test/test_getopt.py
   python/branches/pep-0384/Lib/test/test_gzip.py
   python/branches/pep-0384/Lib/test/test_http_cookies.py
   python/branches/pep-0384/Lib/test/test_httplib.py
   python/branches/pep-0384/Lib/test/test_httpservers.py
   python/branches/pep-0384/Lib/test/test_imp.py
   python/branches/pep-0384/Lib/test/test_import.py
   python/branches/pep-0384/Lib/test/test_io.py
   python/branches/pep-0384/Lib/test/test_ioctl.py
   python/branches/pep-0384/Lib/test/test_logging.py
   python/branches/pep-0384/Lib/test/test_minidom.py
   python/branches/pep-0384/Lib/test/test_mmap.py
   python/branches/pep-0384/Lib/test/test_multiprocessing.py
   python/branches/pep-0384/Lib/test/test_ntpath.py
   python/branches/pep-0384/Lib/test/test_numeric_tower.py   (props changed)
   python/branches/pep-0384/Lib/test/test_optparse.py
   python/branches/pep-0384/Lib/test/test_os.py
   python/branches/pep-0384/Lib/test/test_osx_env.py
   python/branches/pep-0384/Lib/test/test_pdb.py
   python/branches/pep-0384/Lib/test/test_pep277.py
   python/branches/pep-0384/Lib/test/test_platform.py
   python/branches/pep-0384/Lib/test/test_poplib.py
   python/branches/pep-0384/Lib/test/test_posix.py
   python/branches/pep-0384/Lib/test/test_pow.py
   python/branches/pep-0384/Lib/test/test_pstats.py
   python/branches/pep-0384/Lib/test/test_queue.py
   python/branches/pep-0384/Lib/test/test_re.py
   python/branches/pep-0384/Lib/test/test_robotparser.py
   python/branches/pep-0384/Lib/test/test_sax.py
   python/branches/pep-0384/Lib/test/test_set.py
   python/branches/pep-0384/Lib/test/test_signal.py
   python/branches/pep-0384/Lib/test/test_site.py
   python/branches/pep-0384/Lib/test/test_smtplib.py
   python/branches/pep-0384/Lib/test/test_sndhdr.py   (props changed)
   python/branches/pep-0384/Lib/test/test_socket.py
   python/branches/pep-0384/Lib/test/test_ssl.py
   python/branches/pep-0384/Lib/test/test_strtod.py
   python/branches/pep-0384/Lib/test/test_struct.py
   python/branches/pep-0384/Lib/test/test_subprocess.py
   python/branches/pep-0384/Lib/test/test_sunau.py   (props changed)
   python/branches/pep-0384/Lib/test/test_sundry.py
   python/branches/pep-0384/Lib/test/test_syntax.py
   python/branches/pep-0384/Lib/test/test_sys.py
   python/branches/pep-0384/Lib/test/test_tcl.py
   python/branches/pep-0384/Lib/test/test_threaded_import.py
   python/branches/pep-0384/Lib/test/test_threading.py
   python/branches/pep-0384/Lib/test/test_threading_local.py
   python/branches/pep-0384/Lib/test/test_tokenize.py
   python/branches/pep-0384/Lib/test/test_types.py
   python/branches/pep-0384/Lib/test/test_unicode.py
   python/branches/pep-0384/Lib/test/test_unicode_file.py
   python/branches/pep-0384/Lib/test/test_unicodedata.py
   python/branches/pep-0384/Lib/test/test_urllib.py
   python/branches/pep-0384/Lib/test/test_urllib2.py
   python/branches/pep-0384/Lib/test/test_urllib2_localnet.py
   python/branches/pep-0384/Lib/test/test_urllib2net.py
   python/branches/pep-0384/Lib/test/test_urlparse.py
   python/branches/pep-0384/Lib/test/test_winsound.py
   python/branches/pep-0384/Lib/test/test_xml_etree.py
   python/branches/pep-0384/Lib/test/test_zipfile.py
   python/branches/pep-0384/Lib/test/test_zipimport.py
   python/branches/pep-0384/Lib/threading.py
   python/branches/pep-0384/Lib/timeit.py
   python/branches/pep-0384/Lib/trace.py
   python/branches/pep-0384/Lib/urllib/parse.py
   python/branches/pep-0384/Lib/urllib/request.py
   python/branches/pep-0384/Lib/urllib/robotparser.py
   python/branches/pep-0384/Lib/xml/dom/minidom.py
   python/branches/pep-0384/Lib/xml/etree/ElementInclude.py
   python/branches/pep-0384/Lib/xml/etree/ElementTree.py
   python/branches/pep-0384/Lib/xmlrpc/client.py
   python/branches/pep-0384/Lib/zipfile.py
   python/branches/pep-0384/Makefile.pre.in
   python/branches/pep-0384/Misc/ACKS
   python/branches/pep-0384/Misc/NEWS
   python/branches/pep-0384/Misc/README
   python/branches/pep-0384/Misc/RPM/python-3.2.spec
   python/branches/pep-0384/Misc/developers.txt
   python/branches/pep-0384/Misc/maintainers.rst
   python/branches/pep-0384/Misc/python-wing.wpr
   python/branches/pep-0384/Modules/Setup.dist
   python/branches/pep-0384/Modules/_collectionsmodule.c
   python/branches/pep-0384/Modules/_csv.c
   python/branches/pep-0384/Modules/_ctypes/_ctypes.c
   python/branches/pep-0384/Modules/_ctypes/callbacks.c
   python/branches/pep-0384/Modules/_ctypes/callproc.c
   python/branches/pep-0384/Modules/_ctypes/cfield.c
   python/branches/pep-0384/Modules/_ctypes/ctypes.h
   python/branches/pep-0384/Modules/_ctypes/libffi/fficonfig.py.in
   python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.c
   python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.h
   python/branches/pep-0384/Modules/_ctypes/malloc_closure.c
   python/branches/pep-0384/Modules/_cursesmodule.c
   python/branches/pep-0384/Modules/_elementtree.c
   python/branches/pep-0384/Modules/_functoolsmodule.c
   python/branches/pep-0384/Modules/_hashopenssl.c
   python/branches/pep-0384/Modules/_io/bufferedio.c
   python/branches/pep-0384/Modules/_json.c
   python/branches/pep-0384/Modules/_localemodule.c
   python/branches/pep-0384/Modules/_randommodule.c
   python/branches/pep-0384/Modules/_ssl.c
   python/branches/pep-0384/Modules/_struct.c
   python/branches/pep-0384/Modules/_threadmodule.c
   python/branches/pep-0384/Modules/_time.c   (props changed)
   python/branches/pep-0384/Modules/_time.h   (props changed)
   python/branches/pep-0384/Modules/arraymodule.c
   python/branches/pep-0384/Modules/binascii.c
   python/branches/pep-0384/Modules/bz2module.c
   python/branches/pep-0384/Modules/errnomodule.c
   python/branches/pep-0384/Modules/gcmodule.c
   python/branches/pep-0384/Modules/getpath.c
   python/branches/pep-0384/Modules/main.c
   python/branches/pep-0384/Modules/mmapmodule.c
   python/branches/pep-0384/Modules/nismodule.c
   python/branches/pep-0384/Modules/posixmodule.c
   python/branches/pep-0384/Modules/pwdmodule.c
   python/branches/pep-0384/Modules/pyexpat.c
   python/branches/pep-0384/Modules/readline.c
   python/branches/pep-0384/Modules/selectmodule.c
   python/branches/pep-0384/Modules/sha1module.c
   python/branches/pep-0384/Modules/signalmodule.c
   python/branches/pep-0384/Modules/socketmodule.c
   python/branches/pep-0384/Modules/timemodule.c
   python/branches/pep-0384/Modules/zipimport.c
   python/branches/pep-0384/Modules/zlib/ChangeLog
   python/branches/pep-0384/Modules/zlib/FAQ
   python/branches/pep-0384/Modules/zlib/INDEX
   python/branches/pep-0384/Modules/zlib/Makefile
   python/branches/pep-0384/Modules/zlib/Makefile.in
   python/branches/pep-0384/Modules/zlib/README
   python/branches/pep-0384/Modules/zlib/adler32.c
   python/branches/pep-0384/Modules/zlib/compress.c
   python/branches/pep-0384/Modules/zlib/configure
   python/branches/pep-0384/Modules/zlib/crc32.c
   python/branches/pep-0384/Modules/zlib/deflate.c
   python/branches/pep-0384/Modules/zlib/deflate.h
   python/branches/pep-0384/Modules/zlib/example.c
   python/branches/pep-0384/Modules/zlib/infback.c
   python/branches/pep-0384/Modules/zlib/inffast.c
   python/branches/pep-0384/Modules/zlib/inffast.h
   python/branches/pep-0384/Modules/zlib/inflate.c
   python/branches/pep-0384/Modules/zlib/inflate.h
   python/branches/pep-0384/Modules/zlib/inftrees.c
   python/branches/pep-0384/Modules/zlib/inftrees.h
   python/branches/pep-0384/Modules/zlib/make_vms.com
   python/branches/pep-0384/Modules/zlib/minigzip.c
   python/branches/pep-0384/Modules/zlib/trees.c
   python/branches/pep-0384/Modules/zlib/trees.h
   python/branches/pep-0384/Modules/zlib/uncompr.c
   python/branches/pep-0384/Modules/zlib/zconf.h
   python/branches/pep-0384/Modules/zlib/zlib.3
   python/branches/pep-0384/Modules/zlib/zlib.h
   python/branches/pep-0384/Modules/zlib/zutil.c
   python/branches/pep-0384/Modules/zlib/zutil.h
   python/branches/pep-0384/Objects/abstract.c
   python/branches/pep-0384/Objects/bytearrayobject.c
   python/branches/pep-0384/Objects/bytes_methods.c
   python/branches/pep-0384/Objects/bytesobject.c
   python/branches/pep-0384/Objects/capsule.c
   python/branches/pep-0384/Objects/complexobject.c
   python/branches/pep-0384/Objects/fileobject.c
   python/branches/pep-0384/Objects/floatobject.c
   python/branches/pep-0384/Objects/iterobject.c
   python/branches/pep-0384/Objects/listobject.c
   python/branches/pep-0384/Objects/memoryobject.c
   python/branches/pep-0384/Objects/moduleobject.c
   python/branches/pep-0384/Objects/object.c
   python/branches/pep-0384/Objects/setobject.c
   python/branches/pep-0384/Objects/sliceobject.c
   python/branches/pep-0384/Objects/stringlib/fastsearch.h
   python/branches/pep-0384/Objects/stringlib/formatter.h
   python/branches/pep-0384/Objects/typeobject.c
   python/branches/pep-0384/Objects/unicodectype.c
   python/branches/pep-0384/Objects/unicodeobject.c
   python/branches/pep-0384/Objects/unicodetype_db.h
   python/branches/pep-0384/PC/VS8.0/pythoncore.vcproj
   python/branches/pep-0384/PC/_subprocess.c
   python/branches/pep-0384/PC/config.c
   python/branches/pep-0384/PC/msvcrtmodule.c
   python/branches/pep-0384/PC/pyconfig.h
   python/branches/pep-0384/PC/python_nt.rc
   python/branches/pep-0384/PC/winreg.c
   python/branches/pep-0384/PCbuild/build_ssl.py
   python/branches/pep-0384/PCbuild/pyproject.vsprops
   python/branches/pep-0384/PCbuild/pythoncore.vcproj
   python/branches/pep-0384/PCbuild/readme.txt
   python/branches/pep-0384/Parser/   (props changed)
   python/branches/pep-0384/Python/_warnings.c
   python/branches/pep-0384/Python/ast.c
   python/branches/pep-0384/Python/bltinmodule.c
   python/branches/pep-0384/Python/ceval.c
   python/branches/pep-0384/Python/ceval_gil.h
   python/branches/pep-0384/Python/getargs.c
   python/branches/pep-0384/Python/getcopyright.c
   python/branches/pep-0384/Python/getversion.c
   python/branches/pep-0384/Python/import.c
   python/branches/pep-0384/Python/modsupport.c
   python/branches/pep-0384/Python/peephole.c
   python/branches/pep-0384/Python/pythonrun.c
   python/branches/pep-0384/Python/sysmodule.c
   python/branches/pep-0384/README
   python/branches/pep-0384/Tools/README
   python/branches/pep-0384/Tools/buildbot/external-common.bat
   python/branches/pep-0384/Tools/framer/framer/bases.py
   python/branches/pep-0384/Tools/framer/framer/template.py
   python/branches/pep-0384/Tools/freeze/freeze.py
   python/branches/pep-0384/Tools/freeze/makeconfig.py
   python/branches/pep-0384/Tools/gdb/libpython.py
   python/branches/pep-0384/Tools/msi/msi.py
   python/branches/pep-0384/Tools/msi/msilib.py
   python/branches/pep-0384/Tools/msi/uuids.py
   python/branches/pep-0384/Tools/pynche/ChipViewer.py
   python/branches/pep-0384/Tools/pynche/DetailsViewer.py
   python/branches/pep-0384/Tools/pynche/ListViewer.py
   python/branches/pep-0384/Tools/pynche/PyncheWidget.py
   python/branches/pep-0384/Tools/pynche/StripViewer.py
   python/branches/pep-0384/Tools/pynche/Switchboard.py
   python/branches/pep-0384/Tools/pynche/TextViewer.py
   python/branches/pep-0384/Tools/pynche/TypeinViewer.py
   python/branches/pep-0384/Tools/scripts/2to3
   python/branches/pep-0384/Tools/scripts/README
   python/branches/pep-0384/Tools/scripts/byext.py
   python/branches/pep-0384/Tools/scripts/checkpyc.py
   python/branches/pep-0384/Tools/scripts/patchcheck.py
   python/branches/pep-0384/Tools/scripts/reindent-rst.py
   python/branches/pep-0384/Tools/scripts/reindent.py
   python/branches/pep-0384/Tools/scripts/rgrep.py
   python/branches/pep-0384/Tools/scripts/serve.py
   python/branches/pep-0384/Tools/scripts/suff.py
   python/branches/pep-0384/Tools/scripts/svneol.py
   python/branches/pep-0384/Tools/scripts/untabify.py
   python/branches/pep-0384/Tools/scripts/win_add2path.py
   python/branches/pep-0384/Tools/unicode/makeunicodedata.py
   python/branches/pep-0384/configure
   python/branches/pep-0384/configure.in
   python/branches/pep-0384/pyconfig.h.in
   python/branches/pep-0384/setup.py

Modified: python/branches/pep-0384/.bzrignore
==============================================================================
--- python/branches/pep-0384/.bzrignore	(original)
+++ python/branches/pep-0384/.bzrignore	Fri Aug 27 21:11:11 2010
@@ -11,6 +11,7 @@
 build
 Makefile.pre
 platform
+pybuilddir.txt
 pyconfig.h
 libpython*.a
 python.exe
@@ -30,6 +31,7 @@
 Modules/Setup.local
 Modules/config.c
 Parser/pgen
+Parser/pgen.stamp
 Lib/test/data/*
 Lib/lib2to3/Grammar*.pickle
 Lib/lib2to3/PatternGrammar*.pickle

Modified: python/branches/pep-0384/.hgignore
==============================================================================
--- python/branches/pep-0384/.hgignore	(original)
+++ python/branches/pep-0384/.hgignore	Fri Aug 27 21:11:11 2010
@@ -30,8 +30,10 @@
 Modules/Setup.local
 Modules/config.c
 Parser/pgen$
+Parser/pgen.stamp$
 ^core
 ^python-gdb.py
+^pybuilddir.txt
 
 syntax: glob
 libpython*.a

Modified: python/branches/pep-0384/Demo/README
==============================================================================
--- python/branches/pep-0384/Demo/README	(original)
+++ python/branches/pep-0384/Demo/README	Fri Aug 27 21:11:11 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/pep-0384/Demo/embed/Makefile
==============================================================================
--- python/branches/pep-0384/Demo/embed/Makefile	(original)
+++ python/branches/pep-0384/Demo/embed/Makefile	Fri Aug 27 21:11:11 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/pep-0384/Demo/embed/demo.c
==============================================================================
--- python/branches/pep-0384/Demo/embed/demo.c	(original)
+++ python/branches/pep-0384/Demo/embed/demo.c	Fri Aug 27 21:11:11 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/pep-0384/Demo/embed/loop.c
==============================================================================
--- python/branches/pep-0384/Demo/embed/loop.c	(original)
+++ python/branches/pep-0384/Demo/embed/loop.c	Fri Aug 27 21:11:11 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/pep-0384/Demo/scripts/README
==============================================================================
--- python/branches/pep-0384/Demo/scripts/README	(original)
+++ python/branches/pep-0384/Demo/scripts/README	Fri Aug 27 21:11:11 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/pep-0384/Demo/scripts/toaiff.py
==============================================================================
--- python/branches/pep-0384/Demo/scripts/toaiff.py	Fri Aug 27 21:11:11 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/pep-0384/Demo/tkinter/guido/AttrDialog.py
==============================================================================
--- python/branches/pep-0384/Demo/tkinter/guido/AttrDialog.py	(original)
+++ python/branches/pep-0384/Demo/tkinter/guido/AttrDialog.py	Fri Aug 27 21:11:11 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/pep-0384/Demo/tkinter/guido/ManPage.py
==============================================================================
--- python/branches/pep-0384/Demo/tkinter/guido/ManPage.py	(original)
+++ python/branches/pep-0384/Demo/tkinter/guido/ManPage.py	Fri Aug 27 21:11:11 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/pep-0384/Demo/tkinter/guido/brownian2.py
==============================================================================
--- python/branches/pep-0384/Demo/tkinter/guido/brownian2.py	(original)
+++ python/branches/pep-0384/Demo/tkinter/guido/brownian2.py	Fri Aug 27 21:11:11 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/pep-0384/Demo/tkinter/guido/kill.py
==============================================================================
--- python/branches/pep-0384/Demo/tkinter/guido/kill.py	(original)
+++ python/branches/pep-0384/Demo/tkinter/guido/kill.py	Fri Aug 27 21:11:11 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/pep-0384/Demo/tkinter/guido/ss1.py
==============================================================================
--- python/branches/pep-0384/Demo/tkinter/guido/ss1.py	(original)
+++ python/branches/pep-0384/Demo/tkinter/guido/ss1.py	Fri Aug 27 21:11:11 2010
@@ -4,7 +4,6 @@
 import re
 import sys
 import cgi
-import rexec
 from xml.parsers import expat
 
 LEFT, CENTER, RIGHT = "LEFT", "CENTER", "RIGHT"
@@ -33,16 +32,16 @@
 
     def __init__(self):
         self.cells = {} # {(x, y): cell, ...}
-        self.rexec = rexec.RExec()
-        m = self.rexec.add_module('__main__')
-        m.cell = self.cellvalue
-        m.cells = self.multicellvalue
-        m.sum = sum
+        self.ns = dict(
+            cell = self.cellvalue,
+            cells = self.multicellvalue,
+            sum = sum,
+        )
 
     def cellvalue(self, x, y):
         cell = self.getcell(x, y)
         if hasattr(cell, 'recalc'):
-            return cell.recalc(self.rexec)
+            return cell.recalc(self.ns)
         else:
             return cell
 
@@ -144,7 +143,7 @@
         self.reset()
         for cell in self.cells.values():
             if hasattr(cell, 'recalc'):
-                cell.recalc(self.rexec)
+                cell.recalc(self.ns)
 
     def display(self):
         maxx, maxy = self.getsize()
@@ -164,7 +163,7 @@
             if x <= 0 or y <= 0:
                 continue
             if hasattr(cell, 'recalc'):
-                cell.recalc(self.rexec)
+                cell.recalc(self.ns)
             if hasattr(cell, 'format'):
                 text, alignment = cell.format()
                 assert isinstance(text, str)
@@ -317,7 +316,7 @@
     Subclasses may but needn't provide the following APIs:
 
     cell.reset() -- prepare for recalculation
-    cell.recalc(rexec) -> value -- recalculate formula
+    cell.recalc(ns) -> value -- recalculate formula
     cell.format() -> (value, alignment) -- return formatted value
     cell.xml() -> string -- return XML
     """
@@ -331,7 +330,7 @@
         self.fmt = fmt
         self.alignment = alignment
 
-    def recalc(self, rexec):
+    def recalc(self, ns):
         return self.value
 
     def format(self):
@@ -372,7 +371,7 @@
         self.fmt = fmt
         self.alignment = alignment
 
-    def recalc(self, rexec):
+    def recalc(self, ns):
         return self.text
 
     def format(self):
@@ -398,13 +397,11 @@
     def reset(self):
         self.value = None
 
-    def recalc(self, rexec):
+    def recalc(self, ns):
         if self.value is None:
             try:
                 # A hack to evaluate expressions using true division
-                rexec.r_exec("from __future__ import division\n" +
-                             "__value__ = eval(%s)" % repr(self.translated))
-                self.value = rexec.r_eval("__value__")
+                self.value = eval(self.translated, ns)
             except:
                 exc = sys.exc_info()[0]
                 if hasattr(exc, "__name__"):

Modified: python/branches/pep-0384/Demo/zlib/minigzip.py
==============================================================================
--- python/branches/pep-0384/Demo/zlib/minigzip.py	(original)
+++ python/branches/pep-0384/Demo/zlib/minigzip.py	Fri Aug 27 21:11:11 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/pep-0384/Demo/zlib/zlibdemo.py
==============================================================================
--- python/branches/pep-0384/Demo/zlib/zlibdemo.py	(original)
+++ python/branches/pep-0384/Demo/zlib/zlibdemo.py	Fri Aug 27 21:11:11 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/pep-0384/Doc/Makefile
==============================================================================
--- python/branches/pep-0384/Doc/Makefile	(original)
+++ python/branches/pep-0384/Doc/Makefile	Fri Aug 27 21:11:11 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,7 +142,7 @@
 	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)
@@ -150,7 +150,7 @@
 	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)

Modified: python/branches/pep-0384/Doc/README.txt
==============================================================================
--- python/branches/pep-0384/Doc/README.txt	(original)
+++ python/branches/pep-0384/Doc/README.txt	Fri Aug 27 21:11:11 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/pep-0384/Doc/c-api/abstract.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/abstract.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/abstract.rst	Fri Aug 27 21:11:11 2010
@@ -12,7 +12,7 @@
 will raise a Python exception.
 
 It is not possible to use these functions on objects that are not properly
-initialized, such as a list object that has been created by :cfunc:`PyList_New`,
+initialized, such as a list object that has been created by :c:func:`PyList_New`,
 but whose items have not been set to some non-\ ``NULL`` value yet.
 
 .. toctree::

Modified: python/branches/pep-0384/Doc/c-api/arg.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/arg.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/arg.rst	Fri Aug 27 21:11:11 2010
@@ -305,13 +305,14 @@
    the conversion has failed.  When the conversion fails, the *converter* function
    should raise an exception and leave the content of *address* unmodified.
 
-   If the *converter* returns Py_CLEANUP_SUPPORTED, it may get called a second time
-   if the argument parsing eventually fails, giving the converter a chance to release
-   any memory that it had already allocated. In this second call, the *object* parameter
-   will be NULL; *address* will have the same value as in the original call.
+   If the *converter* returns ``Py_CLEANUP_SUPPORTED``, it may get called a
+   second time if the argument parsing eventually fails, giving the converter a
+   chance to release any memory that it had already allocated. In this second
+   call, the *object* parameter will be NULL; *address* will have the same value
+   as in the original call.
 
    .. versionchanged:: 3.1
-      Py_CLEANUP_SUPPORTED was added.
+      ``Py_CLEANUP_SUPPORTED`` was added.
 
 ``(items)`` (:class:`tuple`) [*matching-items*]
    The object must be a Python sequence whose length is the number of format units

Modified: python/branches/pep-0384/Doc/c-api/bytes.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/bytes.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/bytes.rst	Fri Aug 27 21:11:11 2010
@@ -114,7 +114,7 @@
 
 .. cfunction:: PyObject* PyBytes_FromFormatV(const char *format, va_list vargs)
 
-   Identical to :func:`PyBytes_FromFormat` except that it takes exactly two
+   Identical to :cfunc:`PyBytes_FromFormat` except that it takes exactly two
    arguments.
 
 

Modified: python/branches/pep-0384/Doc/c-api/dict.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/dict.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/dict.rst	Fri Aug 27 21:11:11 2010
@@ -190,8 +190,8 @@
 .. cfunction:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
 
    Iterate over mapping object *b* adding key-value pairs to dictionary *a*.
-   *b* may be a dictionary, or any object supporting :func:`PyMapping_Keys`
-   and :func:`PyObject_GetItem`. If *override* is true, existing pairs in *a*
+   *b* may be a dictionary, or any object supporting :cfunc:`PyMapping_Keys`
+   and :cfunc:`PyObject_GetItem`. If *override* is true, existing pairs in *a*
    will be replaced if a matching key is found in *b*, otherwise pairs will
    only be added if there is not a matching key in *a*. Return ``0`` on
    success or ``-1`` if an exception was raised.

Modified: python/branches/pep-0384/Doc/c-api/exceptions.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/exceptions.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/exceptions.rst	Fri Aug 27 21:11:11 2010
@@ -302,12 +302,12 @@
    use.
 
 
-.. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel)
+.. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stack_level)
 
    Issue a warning message.  The *category* argument is a warning category (see
-   below) or *NULL*; the *message* argument is a message string.  *stacklevel* is a
+   below) or *NULL*; the *message* argument is a message string.  *stack_level* is a
    positive number giving a number of stack frames; the warning will be issued from
-   the  currently executing line of code in that stack frame.  A *stacklevel* of 1
+   the  currently executing line of code in that stack frame.  A *stack_level* of 1
    is the function calling :cfunc:`PyErr_WarnEx`, 2 is  the function above that,
    and so forth.
 
@@ -348,6 +348,13 @@
    described there.
 
 
+.. cfunction:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
+
+   Function similar to :cfunc:`PyErr_WarnEx`, but use
+   :cfunc:`PyUnicode_FromFormatV` to format the warning message.
+
+   .. versionadded:: 3.2
+
 .. cfunction:: int PyErr_CheckSignals()
 
    .. index::

Modified: python/branches/pep-0384/Doc/c-api/file.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/file.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/file.rst	Fri Aug 27 21:11:11 2010
@@ -22,8 +22,9 @@
    Create a Python file object from the file descriptor of an already
    opened file *fd*.  The arguments *name*, *encoding*, *errors* and *newline*
    can be *NULL* to use the defaults; *buffering* can be *-1* to use the
-   default.  Return *NULL* on failure.  For a more comprehensive description of
-   the arguments, please refer to the :func:`io.open` function documentation.
+   default. *name* is ignored and kept for backward compatibility. Return
+   *NULL* on failure. For a more comprehensive description of the arguments,
+   please refer to the :func:`io.open` function documentation.
 
    .. warning::
 
@@ -31,6 +32,9 @@
      OS-level file descriptors can produce various issues (such as unexpected
      ordering of data).
 
+   .. versionchanged:: 3.2
+      Ignore *name* attribute.
+
 
 .. cfunction:: int PyObject_AsFileDescriptor(PyObject *p)
 

Modified: python/branches/pep-0384/Doc/c-api/import.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/import.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/import.rst	Fri Aug 27 21:11:11 2010
@@ -124,8 +124,8 @@
    If *name* points to a dotted name of the form ``package.module``, any package
    structures not already created will still not be created.
 
-   See also :func:`PyImport_ExecCodeModuleEx` and
-   :func:`PyImport_ExecCodeModuleWithPathnames`.
+   See also :cfunc:`PyImport_ExecCodeModuleEx` and
+   :cfunc:`PyImport_ExecCodeModuleWithPathnames`.
 
 
 .. cfunction:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
@@ -133,7 +133,7 @@
    Like :cfunc:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of
    the module object is set to *pathname* if it is non-``NULL``.
 
-   See also :func:`PyImport_ExecCodeModuleWithPathnames`.
+   See also :cfunc:`PyImport_ExecCodeModuleWithPathnames`.
 
 
 .. cfunction:: PyObject* PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname, char *cpathname)

Modified: python/branches/pep-0384/Doc/c-api/init.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/init.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/init.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/c-api/long.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/long.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/long.rst	Fri Aug 27 21:11:11 2010
@@ -181,6 +181,7 @@
    cannot be represented as a :ctype:`long long`, an
    :exc:`OverflowError` is raised and ``-1`` is returned.
 
+
 .. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong)
 
    .. index::
@@ -192,8 +193,8 @@
    returned.
 
    .. versionchanged:: 3.1
-      A negative *pylong* now raises :exc:`OverflowError`, not
-      :exc:`TypeError`.
+      A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`.
+
 
 .. cfunction:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io)
 

Modified: python/branches/pep-0384/Doc/c-api/module.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/module.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/module.rst	Fri Aug 27 21:11:11 2010
@@ -64,13 +64,26 @@
 
 .. cfunction:: char* PyModule_GetFilename(PyObject *module)
 
+   Similar to :cfunc:`PyModule_GetFilenameObject` but return the filename
+   encoded to 'utf-8'.
+
+   .. deprecated:: 3.2
+      :cfunc:`PyModule_GetFilename` raises :ctype:`UnicodeEncodeError` on
+      unencodable filenames, use :cfunc:`PyModule_GetFilenameObject` instead.
+
+
+.. cfunction:: PyObject* PyModule_GetFilenameObject(PyObject *module)
+
    .. index::
       single: __file__ (module attribute)
       single: SystemError (built-in exception)
 
    Return the name of the file from which *module* was loaded using *module*'s
-   :attr:`__file__` attribute.  If this is not defined, or if it is not a string,
-   raise :exc:`SystemError` and return *NULL*.
+   :attr:`__file__` attribute.  If this is not defined, or if it is not a
+   unicode string, raise :exc:`SystemError` and return *NULL*; otherwise return
+   a reference to a :ctype:`PyUnicodeObject`.
+
+   .. versionadded:: 3.2
 
 
 .. cfunction:: void* PyModule_GetState(PyObject *module)

Modified: python/branches/pep-0384/Doc/c-api/sys.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/sys.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/sys.rst	Fri Aug 27 21:11:11 2010
@@ -109,7 +109,23 @@
 
 .. cfunction:: void PySys_WriteStderr(const char *format, ...)
 
-   As above, but write to :data:`sys.stderr` or *stderr* instead.
+   As :cfunc:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr*
+   instead.
+
+.. cfunction:: void PySys_FormatStdout(const char *format, ...)
+
+   Function similar to PySys_WriteStdout() but format the message using
+   :cfunc:`PyUnicode_FromFormatV` and don't truncate the message to an
+   arbitrary length.
+
+   .. versionadded:: 3.2
+
+.. cfunction:: void PySys_FormatStderr(const char *format, ...)
+
+   As :cfunc:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr*
+   instead.
+
+   .. versionadded:: 3.2
 
 
 .. _processcontrol:

Modified: python/branches/pep-0384/Doc/c-api/unicode.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/unicode.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/unicode.rst	Fri Aug 27 21:11:11 2010
@@ -305,10 +305,10 @@
    |                   |                     | *NULL*).                       |
    +-------------------+---------------------+--------------------------------+
    | :attr:`%S`        | PyObject\*          | The result of calling          |
-   |                   |                     | :func:`PyObject_Str`.          |
+   |                   |                     | :cfunc:`PyObject_Str`.         |
    +-------------------+---------------------+--------------------------------+
    | :attr:`%R`        | PyObject\*          | The result of calling          |
-   |                   |                     | :func:`PyObject_Repr`.         |
+   |                   |                     | :cfunc:`PyObject_Repr`.        |
    +-------------------+---------------------+--------------------------------+
 
    An unrecognized format character causes all the rest of the format string to be
@@ -320,13 +320,12 @@
       when :const:`HAVE_LONG_LONG` is defined.
 
    .. versionchanged:: 3.2
-      Support for `"%lld"` and `"%llu"` added.
-
+      Support for ``"%lld"`` and ``"%llu"`` added.
 
 
 .. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
 
-   Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two
+   Identical to :cfunc:`PyUnicode_FromFormat` except that it takes exactly two
    arguments.
 
 
@@ -376,17 +375,31 @@
 :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 :cfunc:`PyUnicode_FSConverter` as the conversion function:
 
 .. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result)
 
-   Convert *obj* into *result*, using :cdata:`Py_FileSystemDefaultEncoding`,
-   and the ``"surrogateescape"`` error handler. *result* must be a
-   ``PyObject*``, return a :func:`bytes` object which must be released if it
-   is no longer used.
+   ParseTuple converter: encode :class:`str` objects to :class:`bytes` using
+   :cfunc:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is.
+   *result* must be a :ctype:`PyBytesObject*` which must be released when it is
+   no longer used.
 
    .. versionadded:: 3.1
 
+
+To decode file names during argument parsing, the ``"O&"`` converter should be
+used, passsing :cfunc:`PyUnicode_FSDecoder` as the conversion function:
+
+.. cfunction:: int PyUnicode_FSDecoder(PyObject* obj, void* result)
+
+   ParseTuple converter: decode :class:`bytes` objects to :class:`str` using
+   :cfunc:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` objects are output
+   as-is. *result* must be a :ctype:`PyUnicodeObject*` which must be released
+   when it is no longer used.
+
+   .. versionadded:: 3.2
+
+
 .. cfunction:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
 
    Decode a null-terminated string using :cdata:`Py_FileSystemDefaultEncoding`
@@ -394,7 +407,7 @@
 
    If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8.
 
-   Use :func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length.
+   Use :cfunc:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length.
 
 
 .. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s)
@@ -670,6 +683,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_DecodeUTF7Stateful(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/pep-0384/Doc/c-api/weakref.rst
==============================================================================
--- python/branches/pep-0384/Doc/c-api/weakref.rst	(original)
+++ python/branches/pep-0384/Doc/c-api/weakref.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/conf.py
==============================================================================
--- python/branches/pep-0384/Doc/conf.py	(original)
+++ python/branches/pep-0384/Doc/conf.py	Fri Aug 27 21:11:11 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/pep-0384/Doc/distutils/apiref.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/apiref.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/apiref.rst	Fri Aug 27 21:11:11 2010
@@ -21,9 +21,7 @@
 .. function:: setup(arguments)
 
    The basic do-everything function that does most everything you could ever ask
-   for from a Distutils method.
-
-   .. See XXXXX
+   for from a Distutils method. See XXXXX
 
    The setup function takes a large number of arguments. These are laid out in the
    following table.
@@ -149,11 +147,11 @@
 In addition, the :mod:`distutils.core` module exposed a number of  classes that
 live elsewhere.
 
-* :class:`~distutils.extension.Extension` from :mod:`distutils.extension`
+* :class:`Extension` from :mod:`distutils.extension`
 
-* :class:`~distutils.cmd.Command` from :mod:`distutils.cmd`
+* :class:`Command` from :mod:`distutils.cmd`
 
-* :class:`~distutils.dist.Distribution` from :mod:`distutils.dist`
+* :class:`Distribution` from :mod:`distutils.dist`
 
 A short description of each of these follows, but see the relevant module for
 the full reference.
@@ -1313,8 +1311,7 @@
   the "negative alias" of :option:`--verbose`, then :option:`--quiet` on the
   command line sets *verbose* to false.
 
-.. XXX Should be replaced with :mod:`optparse`.
-
+.. XXX Should be replaced with optparse
 
 .. function:: fancy_getopt(options, negative_opt, object, args)
 
@@ -1681,8 +1678,8 @@
 ===================================================================
 
 .. module:: distutils.cmd
-   :synopsis: This module provides the abstract base class Command. This class
-              is subclassed by the modules in the distutils.command subpackage.
+   :synopsis: This module provides the abstract base class Command. This class is subclassed
+              by the modules in the distutils.command  subpackage.
 
 
 This module supplies the abstract base class :class:`Command`.
@@ -1692,84 +1689,20 @@
 
    Abstract base class for defining command classes, the "worker bees" of the
    Distutils.  A useful analogy for command classes is to think of them as
-   subroutines with local variables called *options*.  The options are declared
-   in :meth:`initialize_options` and defined (given their final values) in
-   :meth:`finalize_options`, both of which must be defined by every command
-   class.  The distinction between the two is necessary because option values
-   might come from the outside world (command line, config file, ...), and any
-   options dependent on other options must be computed after these outside
-   influences have been processed --- hence :meth:`finalize_options`.  The body
-   of the subroutine, where it does all its work based on the values of its
-   options, is the :meth:`run` method, which must also be implemented by every
-   command class.
+   subroutines with local variables called *options*.  The options are declared in
+   :meth:`initialize_options` and defined (given their final values) in
+   :meth:`finalize_options`, both of which must be defined by every command class.
+   The distinction between the two is necessary because option values might come
+   from the outside world (command line, config file, ...), and any options
+   dependent on other options must be computed after these outside influences have
+   been processed --- hence :meth:`finalize_options`.  The body of the subroutine,
+   where it does all its work based on the values of its options, is the
+   :meth:`run` method, which must also be implemented by every command class.
 
-   The class constructor takes a single argument *dist*, a :class:`Distribution`
+   The class constructor takes a single argument *dist*, a  :class:`Distribution`
    instance.
 
 
-Creating a new Distutils command
-================================
-
-This section outlines the steps to create a new Distutils command.
-
-A new command lives in a module in the :mod:`distutils.command` package. There
-is a sample template in that directory called :file:`command_template`.  Copy
-this file to a new module with the same name as the new command you're
-implementing.  This module should implement a class with the same name as the
-module (and the command).  So, for instance, to create the command
-``peel_banana`` (so that users can run ``setup.py peel_banana``), you'd copy
-:file:`command_template` to :file:`distutils/command/peel_banana.py`, then edit
-it so that it's implementing the class :class:`peel_banana`, a subclass of
-:class:`distutils.cmd.Command`.
-
-Subclasses of :class:`Command` must define the following methods.
-
-.. method:: Command.initialize_options()
-
-   Set default values for all the options that this command supports.  Note that
-   these defaults may be overridden by other commands, by the setup script, by
-   config files, or by the command-line.  Thus, this is not the place to code
-   dependencies between options; generally, :meth:`initialize_options`
-   implementations are just a bunch of ``self.foo = None`` assignments.
-
-
-.. method:: Command.finalize_options()
-
-   Set final values for all the options that this command supports. This is
-   always called as late as possible, ie.  after any option assignments from the
-   command-line or from other commands have been done.  Thus, this is the place
-   to to code option dependencies: if *foo* depends on *bar*, then it is safe to
-   set *foo* from *bar* as long as *foo* still has the same value it was
-   assigned in :meth:`initialize_options`.
-
-
-.. method:: Command.run()
-
-   A command's raison d'etre: carry out the action it exists to perform,
-   controlled by the options initialized in :meth:`initialize_options`,
-   customized by other commands, the setup script, the command-line, and config
-   files, and finalized in :meth:`finalize_options`.  All terminal output and
-   filesystem interaction should be done by :meth:`run`.
-
-
-.. attribute:: Command.sub_commands
-
-   *sub_commands* formalizes the notion of a "family" of commands,
-   e.g. ``install`` as the parent with sub-commands ``install_lib``,
-   ``install_headers``, etc.  The parent of a family of commands defines
-   *sub_commands* as a class attribute; it's a list of 2-tuples ``(command_name,
-   predicate)``, with *command_name* a string and *predicate* a function, a
-   string or ``None``.  *predicate* is a method of the parent command that
-   determines whether the corresponding command is applicable in the current
-   situation.  (E.g. we ``install_headers`` is only applicable if we have any C
-   header files to install.)  If *predicate* is ``None``, that command is always
-   applicable.
-
-   *sub_commands* is usually defined at the *end* of a class, because
-   predicates can be methods of the class, so they must already have been
-   defined.  The canonical example is the :command:`install` command.
-
-
 :mod:`distutils.command` --- Individual Distutils commands
 ==========================================================
 
@@ -2008,3 +1941,76 @@
 This is described in more detail in :pep:`301`.
 
 .. % 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
+================================
+
+This section outlines the steps to create a new Distutils command.
+
+A new command lives in a module in the :mod:`distutils.command` package. There
+is a sample template in that directory called  :file:`command_template`. Copy
+this file to a new module with the same name as the new command you're
+implementing. This module should implement a class with the same name as the
+module (and the command). So, for instance, to create the command
+``peel_banana`` (so that users can run ``setup.py peel_banana``), you'd copy
+:file:`command_template`  to :file:`distutils/command/peel_banana.py`, then edit
+it so that it's implementing the class :class:`peel_banana`, a subclass of
+:class:`distutils.cmd.Command`.
+
+Subclasses of :class:`Command` must define the following methods.
+
+
+.. method:: Command.initialize_options()
+
+   Set default values for all the options that this command supports.  Note that
+   these defaults may be overridden by other commands, by the setup script, by
+   config files, or by the command-line.  Thus, this is not the place to code
+   dependencies between options; generally, :meth:`initialize_options`
+   implementations are just a bunch of ``self.foo = None`` assignments.
+
+
+.. method:: Command.finalize_options()
+
+   Set final values for all the options that this command supports. This is
+   always called as late as possible, ie.  after any option assignments from the
+   command-line or from other commands have been done.  Thus, this is the place
+   to to code option dependencies: if *foo* depends on *bar*, then it is safe to
+   set *foo* from *bar* as long as *foo* still has the same value it was
+   assigned in :meth:`initialize_options`.
+
+
+.. method:: Command.run()
+
+   A command's raison d'etre: carry out the action it exists to perform, controlled
+   by the options initialized in :meth:`initialize_options`, customized by other
+   commands, the setup script, the command-line, and config files, and finalized in
+   :meth:`finalize_options`.  All terminal output and filesystem interaction should
+   be done by :meth:`run`.
+
+*sub_commands* formalizes the notion of a "family" of commands, eg. ``install``
+as the parent with sub-commands ``install_lib``, ``install_headers``, etc.  The
+parent of a family of commands defines *sub_commands* as a class attribute; it's
+a list of 2-tuples ``(command_name, predicate)``, with *command_name* a string
+and *predicate* a function, a string or None. *predicate* is a method of
+the parent command that determines whether the corresponding command is
+applicable in the current situation.  (Eg. we ``install_headers`` is only
+applicable if we have any C header files to install.)  If *predicate* is None,
+that command is always applicable.
+
+*sub_commands* is usually defined at the \*end\* of a class, because predicates
+can be methods of the class, so they must already have been defined.  The
+canonical example is the :command:`install` command.

Modified: python/branches/pep-0384/Doc/distutils/builtdist.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/builtdist.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/builtdist.rst	Fri Aug 27 21:11:11 2010
@@ -141,13 +141,13 @@
 commands.
 
 
-.. _creating-dumb:
+.. .. _creating-dumb:
 
-Creating dumb built distributions
-=================================
+.. Creating dumb built distributions
+.. =================================
 
 .. XXX Need to document absolute vs. prefix-relative packages here, but first
-       I have to implement it!
+   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/pep-0384/Doc/distutils/commandref.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/commandref.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/commandref.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/distutils/examples.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/examples.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/examples.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/distutils/extending.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/extending.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/extending.rst	Fri Aug 27 21:11:11 2010
@@ -15,8 +15,8 @@
 should be copied into packages in addition to :file:`.py` files as a
 convenience.
 
-Most distutils command implementations are subclasses of the
-:class:`distutils.cmd.Command` class.  New commands may directly inherit from
+Most distutils command implementations are subclasses of the :class:`Command`
+class from :mod:`distutils.cmd`.  New commands may directly inherit from
 :class:`Command`, while replacements often derive from :class:`Command`
 indirectly, directly subclassing the command they are replacing.  Commands are
 required to derive from :class:`Command`.

Modified: python/branches/pep-0384/Doc/distutils/sourcedist.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/sourcedist.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/sourcedist.rst	Fri Aug 27 21:11:11 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:
@@ -76,10 +68,10 @@
   :option:`packages` options
 
 * all C source files mentioned in the :option:`ext_modules` or
-  :option:`libraries` options
+  :option:`libraries` options (
 
-  .. XXX Getting C library sources is 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,13 @@
 :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
----------
+.. versionadded:: 3.1
+   :file:`MANIFEST` files start with a comment indicating they are generated.
+   Files without this comment are not overwritten or removed.
 
 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 +121,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 +177,35 @@
 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
+
+* 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
 
-+-------------------------------------------+-----------------------------------------------+
-| 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.
+:option:`-o` is a shortcut for :option:`--manifest-only`.
 
+.. versionchanged:: 3.1
+   An existing generated :file:`MANIFEST` will be regenerated without
+   :command:`sdist` comparing its modification time to the one of
+   :file:`MANIFEST.in` or :file:`setup.py`.

Modified: python/branches/pep-0384/Doc/distutils/uploading.rst
==============================================================================
--- python/branches/pep-0384/Doc/distutils/uploading.rst	(original)
+++ python/branches/pep-0384/Doc/distutils/uploading.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/documenting/markup.rst
==============================================================================
--- python/branches/pep-0384/Doc/documenting/markup.rst	(original)
+++ python/branches/pep-0384/Doc/documenting/markup.rst	Fri Aug 27 21:11:11 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>
 

Modified: python/branches/pep-0384/Doc/extending/extending.rst
==============================================================================
--- python/branches/pep-0384/Doc/extending/extending.rst	(original)
+++ python/branches/pep-0384/Doc/extending/extending.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/faq/library.rst
==============================================================================
--- python/branches/pep-0384/Doc/faq/library.rst	(original)
+++ python/branches/pep-0384/Doc/faq/library.rst	Fri Aug 27 21:11:11 2010
@@ -666,8 +666,8 @@
                                 '/cgi-bin/some-cgi-script', data=qs)
    msg, hdrs = req.read(), req.info()
 
-Note that in general for URL-encoded POST operations, query strings must be
-quoted by using :func:`urllib.parse.urlencode`.  For example to send name="Guy Steele,
+Note that in general for percent-encoded POST operations, query strings must be
+quoted using :func:`urllib.parse.urlencode`.  For example to send name="Guy Steele,
 Jr."::
 
    >>> import urllib.parse

Modified: python/branches/pep-0384/Doc/howto/doanddont.rst
==============================================================================
--- python/branches/pep-0384/Doc/howto/doanddont.rst	(original)
+++ python/branches/pep-0384/Doc/howto/doanddont.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/install/index.rst
==============================================================================
--- python/branches/pep-0384/Doc/install/index.rst	(original)
+++ python/branches/pep-0384/Doc/install/index.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/2to3.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/2to3.rst	(original)
+++ python/branches/pep-0384/Doc/library/2to3.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/abc.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/abc.rst	(original)
+++ python/branches/pep-0384/Doc/library/abc.rst	Fri Aug 27 21:11:11 2010
@@ -122,7 +122,7 @@
 
 It also provides the following decorators:
 
-.. function:: abstractmethod(function)
+.. decorator:: abstractmethod(function)
 
    A decorator indicating abstract methods.
 
@@ -157,6 +157,36 @@
       multiple-inheritance.
 
 
+.. decorator:: abstractclassmethod(function)
+
+   A subclass of the built-in :func:`classmethod`, indicating an abstract
+   classmethod. Otherwise it is similar to :func:`abstractmethod`.
+
+   Usage::
+
+      class C(metaclass=ABCMeta):
+          @abstractclassmethod
+          def my_abstract_classmethod(cls, ...):
+              ...
+
+   .. versionadded:: 3.2
+
+
+.. decorator:: abstractstaticmethod(function)
+
+   A subclass of the built-in :func:`staticmethod`, indicating an abstract
+   staticmethod. Otherwise it is similar to :func:`abstractmethod`.
+
+   Usage::
+
+      class C(metaclass=ABCMeta):
+          @abstractstaticmethod
+          def my_abstract_staticmethod(...):
+              ...
+
+   .. versionadded:: 3.2
+
+
 .. function:: abstractproperty(fget=None, fset=None, fdel=None, doc=None)
 
    A subclass of the built-in :func:`property`, indicating an abstract property.

Modified: python/branches/pep-0384/Doc/library/argparse.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/argparse.rst	(original)
+++ python/branches/pep-0384/Doc/library/argparse.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/base64.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/base64.rst	(original)
+++ python/branches/pep-0384/Doc/library/base64.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/bdb.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/bdb.rst	(original)
+++ python/branches/pep-0384/Doc/library/bdb.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/binascii.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/binascii.rst	(original)
+++ python/branches/pep-0384/Doc/library/binascii.rst	Fri Aug 27 21:11:11 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 objects 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 objects 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 objects as input.
+
 
 .. exception:: Error
 
@@ -164,4 +178,3 @@
 
    Module :mod:`quopri`
       Support for quoted-printable encoding used in MIME email messages.
-

Modified: python/branches/pep-0384/Doc/library/bisect.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/bisect.rst	(original)
+++ python/branches/pep-0384/Doc/library/bisect.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/cgi.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/cgi.rst	(original)
+++ python/branches/pep-0384/Doc/library/cgi.rst	Fri Aug 27 21:11:11 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:`~xml.sax.saxutils.quoteattr` function in the
+   :mod:`xml.sax.saxutils` module instead.
 
 
 .. _cgi-security:

Modified: python/branches/pep-0384/Doc/library/cmd.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/cmd.rst	(original)
+++ python/branches/pep-0384/Doc/library/cmd.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/codecs.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/codecs.rst	(original)
+++ python/branches/pep-0384/Doc/library/codecs.rst	Fri Aug 27 21:11:11 2010
@@ -1090,7 +1090,7 @@
 +-----------------+--------------------------------+--------------------------------+
 | mac_latin2      | maclatin2, maccentraleurope    | Central and Eastern Europe     |
 +-----------------+--------------------------------+--------------------------------+
-| mac_roman       | macroman                       | Western Europe                 |
+| mac_roman       | macroman, macintosh            | Western Europe                 |
 +-----------------+--------------------------------+--------------------------------+
 | mac_turkish     | macturkish                     | Turkish                        |
 +-----------------+--------------------------------+--------------------------------+

Modified: python/branches/pep-0384/Doc/library/collections.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/collections.rst	(original)
+++ python/branches/pep-0384/Doc/library/collections.rst	Fri Aug 27 21:11:11 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
@@ -373,6 +266,7 @@
 
       .. versionadded:: 3.2
 
+
    .. method:: extend(iterable)
 
       Extend the right side of the deque by appending elements from the iterable
@@ -403,12 +297,14 @@
       Removed the first occurrence of *value*.  If not found, raises a
       :exc:`ValueError`.
 
+
    .. method:: reverse()
 
       Reverse the elements of the deque in-place and then return ``None``.
 
       .. versionadded:: 3.2
 
+
    .. method:: rotate(n)
 
       Rotate the deque *n* steps to the right.  If *n* is negative, rotate to
@@ -683,7 +579,7 @@
    lightweight and require no more memory than regular tuples.
 
    .. versionchanged:: 3.1
-      added support for *rename*.
+      Added support for *rename*.
 
 Example:
 
@@ -712,7 +608,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'
@@ -938,6 +834,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
 -------------------------
@@ -1024,3 +932,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/pep-0384/Doc/library/configparser.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/configparser.rst	(original)
+++ python/branches/pep-0384/Doc/library/configparser.rst	Fri Aug 27 21:11:11 2010
@@ -15,105 +15,176 @@
    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 key/value entries separated by a specific string (``=`` or ``:`` by
+default). By default, section names are case sensitive but keys are not. Leading
+und trailing whitespace is removed from keys and 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, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
 
    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
-   presented for these is ``None``.
+   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 *strict* is ``True`` (default: ``False``), the parser won't allow for
+   any section or option duplicates while reading from a single source (file,
+   string or dictionary), raising :exc:`DuplicateSectionError` or
+   :exc:`DuplicateOptionError`. 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.
+      *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
+      *empty_lines_in_values* were added.
 
 
-.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict,
-                        allow_no_value=False)
+.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), strict=False, empty_lines_in_values=True)
 
-   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.
+      *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
+      *empty_lines_in_values* were added.
 
 
-.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict,
-                            allow_no_value=False)
+.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), strict=False, empty_lines_in_values=True)
 
-   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.
+
+   :class:`SafeConfigParser` is generally recommended over this class if you
+   need interpolation.
 
-   .. XXX Need to explain what's safer/more predictable about it.
+   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.
+      *allow_no_value*, *delimiters*, *comment_prefixes*,
+      *strict* and *empty_lines_in_values* were added.
+
+
+.. exception:: Error
+
+   Base class for all other configparser exceptions.
 
 
 .. exception:: NoSectionError
@@ -124,12 +195,26 @@
 .. exception:: DuplicateSectionError
 
    Exception raised if :meth:`add_section` is called with the name of a section
-   that is already present.
+   that is already present or in strict parsers when a section if found more
+   than once in a single input file, string or dictionary.
+
+   .. versionadded:: 3.2
+      Optional ``source`` and ``lineno`` attributes and arguments to
+      :meth:`__init__` were added.
+
+
+.. exception:: DuplicateOptionError
+
+   Exception raised by strict parsers if a single option appears twice during
+   reading from a single file, string or dictionary. This catches misspellings
+   and case sensitivity-related errors, e.g. a dictionary may have two keys
+   representing the same case-insensitive configuration key.
 
 
 .. exception:: NoOptionError
 
-   Exception raised when a specified option is not found in the specified  section.
+   Exception raised when a specified option is not found in the specified
+   section.
 
 
 .. exception:: InterpolationError
@@ -166,6 +251,9 @@
 
    Exception raised when errors occur attempting to parse a file.
 
+   .. versionchanged:: 3.2
+      The ``filename`` attribute and :meth:`__init__` argument were renamed to
+      ``source`` for consistency.
 
 .. data:: MAX_INTERPOLATION_DEPTH
 
@@ -223,35 +311,67 @@
    :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:`read_file` 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_file(open('defaults.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)
 
-   Read and parse configuration data from the file or file-like object in *fp*
+.. method:: RawConfigParser.read_file(f, source=None)
+
+   Read and parse configuration data from the file or file-like object in *f*
    (only the :meth:`readline` method is used).  The file-like object must
    operate in text mode, i.e. return strings from :meth:`readline`.
 
-   If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used
-   for *filename*; the default is ``<???>``.
+   Optional argument *source* specifies the name of the file being read. It not
+   given and *f* has a :attr:`name` attribute, that is used for *source*; the
+   default is ``<???>``.
+
+   .. versionadded:: 3.2
+      Renamed from :meth:`readfp` (with the ``filename`` attribute renamed to
+      ``source`` for consistency with other ``read_*`` methods).
+
+
+.. method:: RawConfigParser.read_string(string, source='<string>')
+
+   Parse configuration data from a given string.
+
+   Optional argument *source* specifies a context-specific name of the string
+   passed. If not given, ``<string>`` is used.
+
+   .. versionadded:: 3.2
+
+
+.. method:: RawConfigParser.read_dict(dictionary, source='<dict>')
+
+   Load configuration from a dictionary. Keys are section names, values are
+   dictionaries with keys and values that should be present in the section. If
+   the used dictionary type preserves order, sections and their keys will be
+   added in order.
+
+   Optional argument *source* specifies a context-specific name of the
+   dictionary passed.  If not given, ``<dict>`` is used.
+
+   .. versionadded:: 3.2
 
 
 .. method:: RawConfigParser.get(section, option)
@@ -295,11 +415,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)
@@ -336,27 +458,39 @@
    option names are stripped before :meth:`optionxform` is called.
 
 
+.. method:: RawConfigParser.readfp(fp, filename=None)
+
+   .. deprecated:: 3.2
+      Please use :meth:`read_file` instead.
+
+
 .. _configparser-objects:
 
 ConfigParser Objects
 --------------------
 
 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 +600,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,15 +610,15 @@
 
    >>> 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))
+   >>> config.read_file(io.BytesIO(sample_config))
 
    >>> # Settings with values are treated as before:
    >>> config.get("mysqld", "user")

Modified: python/branches/pep-0384/Doc/library/constants.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/constants.rst	(original)
+++ python/branches/pep-0384/Doc/library/constants.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/contextlib.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/contextlib.rst	(original)
+++ python/branches/pep-0384/Doc/library/contextlib.rst	Fri Aug 27 21:11:11 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

Modified: python/branches/pep-0384/Doc/library/datetime.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/datetime.rst	(original)
+++ python/branches/pep-0384/Doc/library/datetime.rst	Fri Aug 27 21:11:11 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,16 +288,25 @@
 (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).
 
-.. versionadded:: 3.2
-   Floor division and true division of a :class:`timedelta` object by
-   another :class:`timedelta` object are now supported, as are
-   remainder operations and the :func:`divmod` function.  True
-   division and multiplication of a :class:`timedelta` object by
-   a :class:`float` object are now supported.
+.. versionchanged:: 3.2
+   Floor division and true division of a :class:`timedelta` object by another
+   :class:`timedelta` object are now supported, as are remainder operations and
+   the :func:`divmod` function.  True division and multiplication of a
+   :class:`timedelta` object by a :class:`float` object are now supported.
 
 
 Comparisons of :class:`timedelta` objects are supported with the
@@ -1761,9 +1778,7 @@
    For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
    ``%z`` is replaced with the string ``'-0330'``.
 
-.. versionadded:: 3.2
-
-   When the ``%z`` directive is provided to the :meth:`strptime`
-   method, an aware :class:`datetime` object will be produced.  The
-   ``tzinfo`` of the result will be set to a :class:`timezone`
-   instance.
+.. versionchanged:: 3.2
+   When the ``%z`` directive is provided to the :meth:`strptime` method, an
+   aware :class:`datetime` object will be produced.  The ``tzinfo`` of the
+   result will be set to a :class:`timezone` instance.

Modified: python/branches/pep-0384/Doc/library/dbm.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/dbm.rst	(original)
+++ python/branches/pep-0384/Doc/library/dbm.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/decimal.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/decimal.rst	(original)
+++ python/branches/pep-0384/Doc/library/decimal.rst	Fri Aug 27 21:11:11 2010
@@ -354,7 +354,8 @@
    Once constructed, :class:`Decimal` objects are immutable.
 
    .. versionchanged:: 3.2
-      The argument to the constructor is now permitted to be a :class:`float` instance.
+      The argument to the constructor is now permitted to be a :class:`float`
+      instance.
 
    Decimal floating point objects share many properties with the other built-in
    numeric types such as :class:`float` and :class:`int`.  All of the usual math
@@ -372,8 +373,8 @@
    when doing equality comparisons between numbers of different types.
 
    .. versionchanged:: 3.2
-      Mixed-type comparisons between :class:`Decimal` instances and
-      other numeric types are now fully supported.
+      Mixed-type comparisons between :class:`Decimal` instances and other
+      numeric types are now fully supported.
 
    In addition to the standard numeric properties, decimal floating point
    objects also have a number of specialized methods:
@@ -1007,7 +1008,6 @@
       value for subnormal results.  When underflow occurs, the exponent is set
       to :const:`Etiny`.
 
-
    .. method:: Etop()
 
       Returns a value equal to ``Emax - prec + 1``.

Modified: python/branches/pep-0384/Doc/library/dis.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/dis.rst	(original)
+++ python/branches/pep-0384/Doc/library/dis.rst	Fri Aug 27 21:11:11 2010
@@ -36,16 +36,28 @@
 The :mod:`dis` module defines the following functions and constants:
 
 
+.. function:: code_info(x=None)
+
+   Return a formatted multi-line string with detailed code object information
+   for the supplied function, method, source code string or code object.
+
+   Note that the exact contents of code info strings are highly implementation
+   dependent and they may change arbitrarily across Python VMs or Python
+   releases.
+
+   .. versionadded:: 3.2
+
+
 .. function:: dis(x=None)
 
-   Disassemble the *x* object.  *x* can denote either a module, a
-   class, a method, a function, a code object, a string of source code or a
-   byte sequence of raw bytecode.  For a module, it disassembles all
-   functions.  For a class, it disassembles all methods.  For a code object
-   or sequence of raw bytecode, it prints one line per bytecode instruction.
-   Strings are first compiled to code objects with the :func:`compile`
-   built-in function before being disassembled.  If no object is provided,
-   this function disassembles the last traceback.
+   Disassemble the *x* object.  *x* can denote either a module, a class, a
+   method, a function, a code object, a string of source code or a byte sequence
+   of raw bytecode.  For a module, it disassembles all functions.  For a class,
+   it disassembles all methods.  For a code object or sequence of raw bytecode,
+   it prints one line per bytecode instruction.  Strings are first compiled to
+   code objects with the :func:`compile` built-in function before being
+   disassembled.  If no object is provided, this function disassembles the last
+   traceback.
 
 
 .. function:: distb(tb=None)

Modified: python/branches/pep-0384/Doc/library/doctest.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/doctest.rst	(original)
+++ python/branches/pep-0384/Doc/library/doctest.rst	Fri Aug 27 21:11:11 2010
@@ -574,8 +574,8 @@
    changed in Python 2.4 to say "does not" instead of "doesn't".
 
    .. versionchanged:: 3.2
-      :const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information
-      relating to the module containing the exception under test
+      :const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information relating
+      to the module containing the exception under test.
 
 
 .. data:: SKIP
@@ -1673,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.
 
@@ -1697,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/pep-0384/Doc/library/email.errors.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/email.errors.rst	(original)
+++ python/branches/pep-0384/Doc/library/email.errors.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/fileinput.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/fileinput.rst	(original)
+++ python/branches/pep-0384/Doc/library/fileinput.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/fnmatch.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/fnmatch.rst	(original)
+++ python/branches/pep-0384/Doc/library/fnmatch.rst	Fri Aug 27 21:11:11 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,13 +84,6 @@
       <_sre.SRE_Match object at 0x...>
 
 
-.. function:: purge()
-
-   Clear the internal pattern cache.
-
-   .. versionadded:: 3.2
-
-
 .. seealso::
 
    Module :mod:`glob`

Modified: python/branches/pep-0384/Doc/library/ftplib.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/ftplib.rst	(original)
+++ python/branches/pep-0384/Doc/library/ftplib.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/functions.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/functions.rst	(original)
+++ python/branches/pep-0384/Doc/library/functions.rst	Fri Aug 27 21:11:11 2010
@@ -181,7 +181,6 @@
       character.  This is to facilitate detection of incomplete and complete
       statements in the :mod:`code` module.
 
-
    .. versionchanged:: 3.2
       Allowed use of Windows and Mac newlines.  Also input in ``'exec'`` mode
       does not have to end in a newline anymore.
@@ -464,10 +463,10 @@
 
 .. function:: hasattr(object, name)
 
-   The arguments are an object and a string.  The result is ``True`` if the string
-   is the name of one of the object's attributes, ``False`` if not. (This is
-   implemented by calling ``getattr(object, name)`` and seeing whether it raises an
-   exception or not.)
+   The arguments are an object and a string.  The result is ``True`` if the
+   string is the name of one of the object's attributes, ``False`` if not. (This
+   is implemented by calling ``getattr(object, name)`` and seeing whether it
+   raises an :exc:`AttributeError` or not.)
 
 
 .. function:: hash(object)
@@ -847,7 +846,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):
@@ -861,6 +860,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`::
@@ -936,8 +938,8 @@
       []
 
    .. versionchanged:: 3.2
-      Testing integers for membership takes constant time instead of
-      iterating through all items.
+      Testing integers for membership takes constant time instead of iterating
+      through all items.
 
 
 .. function:: repr(object)
@@ -972,6 +974,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:
@@ -1017,8 +1026,8 @@
    *reverse* is a boolean value.  If set to ``True``, then the list elements are
    sorted as if each comparison were reversed.
 
-   Use :func:`functools.cmp_to_key` to convert an
-   old-style *cmp* function to a *key* function.
+   Use :func:`functools.cmp_to_key` to convert an old-style *cmp* function to a
+   *key* function.
 
    For sorting examples and a brief sorting tutorial, see `Sorting HowTo
    <http://wiki.python.org/moin/HowTo/Sorting/>`_\.

Modified: python/branches/pep-0384/Doc/library/functools.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/functools.rst	(original)
+++ python/branches/pep-0384/Doc/library/functools.rst	Fri Aug 27 21:11:11 2010
@@ -17,27 +17,59 @@
 
 ..  function:: cmp_to_key(func)
 
-    Transform an old-style comparison function to a key-function.  Used with
-    tools that accept key functions (such as :func:`sorted`, :func:`min`,
-    :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
-    :func:`itertools.groupby`).
-    This function is primarily used as a transition tool for programs
-    being converted from Py2.x which supported the use of comparison
-    functions.
-
-    A compare function is any callable that accept two arguments, compares
-    them, and returns a negative number for less-than, zero for equality,
-    or a positive number for greater-than.  A key function is a callable
-    that accepts one argument and returns another value that indicates
-    the position in the desired collation sequence.
+   Transform an old-style comparison function to a key-function.  Used with
+   tools that accept key functions (such as :func:`sorted`, :func:`min`,
+   :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
+   :func:`itertools.groupby`).  This function is primarily used as a transition
+   tool for programs being converted from Py2.x which supported the use of
+   comparison functions.
+
+   A compare function is any callable that accept two arguments, compares them,
+   and returns a negative number for less-than, zero for equality, or a positive
+   number for greater-than.  A key function is a callable that accepts one
+   argument and returns another value that indicates the position in the desired
+   collation sequence.
 
-    Example::
+   Example::
 
-        sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
+       sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
 
    .. versionadded:: 3.2
 
-.. function:: total_ordering(cls)
+
+.. 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.
+
+   The original underlying function is accessible through the
+   :attr:`__wrapped__` attribute.  This allows introspection, bypassing
+   the cache, or rewrapping the function with a different caching tool.
+
+   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
@@ -60,6 +92,7 @@
 
    .. versionadded:: 3.2
 
+
 .. function:: partial(func, *args, **keywords)
 
    Return a new :class:`partial` object which when called will behave like *func*
@@ -111,9 +144,14 @@
    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).
+
+   To allow access to the original function for introspection and other purposes
+   (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
+   automatically adds a __wrapped__ attribute to the the wrapped that refers to
+   the original function.
 
    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
@@ -121,8 +159,23 @@
    definition rather than the original function definition, which is typically less
    than helpful.
 
+   :func:`update_wrapper` may be used with callables other than functions. Any
+   attributes named in *assigned* or *updated* that are missing from the object
+   being wrapped are ignored (i.e. this function will not attempt to set them
+   on the wrapper function). :exc:`AttributeError` is still raised if the
+   wrapper function itself is missing any attributes named in *updated*.
+
+   .. versionadded:: 3.2
+      Automatic addition of the ``__wrapped__`` attribute.
+
+   .. versionadded:: 3.2
+      Copying of the ``__annotations__`` attribute by default.
+
+   .. versionchanged:: 3.2
+      Missing attributes no longer trigger an :exc:`AttributeError`.
+
 
-.. 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/pep-0384/Doc/library/gc.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/gc.rst	(original)
+++ python/branches/pep-0384/Doc/library/gc.rst	Fri Aug 27 21:11:11 2010
@@ -177,6 +177,15 @@
    If :const:`DEBUG_SAVEALL` is set, then all unreachable objects will be added to
    this list rather than freed.
 
+   .. versionchanged:: 3.2
+      If this list is non-empty at interpreter shutdown, a warning message
+      gets printed.
+
+   ::
+
+       gc: 2 uncollectable objects at shutdown:
+             Use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them.
+
 The following constants are provided for use with :func:`set_debug`:
 
 
@@ -197,6 +206,9 @@
    reachable but cannot be freed by the collector).  These objects will be added to
    the ``garbage`` list.
 
+   .. versionchanged:: 3.2
+      Also print the contents of the :data:`garbage` list at interpreter
+      shutdown (rather than just its length), if it isn't empty.
 
 .. data:: DEBUG_SAVEALL
 

Modified: python/branches/pep-0384/Doc/library/gzip.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/gzip.rst	(original)
+++ python/branches/pep-0384/Doc/library/gzip.rst	Fri Aug 27 21:11:11 2010
@@ -82,6 +82,21 @@
    The *filename* argument is required; *mode* defaults to ``'rb'`` and
    *compresslevel* defaults to ``9``.
 
+.. function:: compress(data, compresslevel=9)
+
+   Compress the *data*, returning a :class:`bytes` object containing
+   the compressed data.  *compresslevel* has the same meaning as in
+   the :class:`GzipFile` constructor above.
+
+   .. versionadded:: 3.2
+
+.. function:: decompress(data)
+
+   Decompress the *data*, returning a :class:`bytes` object containing the
+   uncompressed data.
+
+   .. versionadded:: 3.2
+
 
 .. _gzip-usage-examples:
 
@@ -91,27 +106,28 @@
 Example of how to read a compressed file::
 
    import gzip
-   f = gzip.open('/home/joe/file.txt.gz', 'rb')
-   file_content = f.read()
-   f.close()
+   with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
+       file_content = f.read()
 
 Example of how to create a compressed GZIP file::
 
    import gzip
-   content = "Lots of content here"
-   f = gzip.open('/home/joe/file.txt.gz', 'wb')
-   f.write(content)
-   f.close()
+   content = b"Lots of content here"
+   with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
+       f.write(content)
 
 Example of how to GZIP compress an existing file::
 
    import gzip
-   f_in = open('/home/joe/file.txt', 'rb')
-   f_out = gzip.open('/home/joe/file.txt.gz', 'wb')
-   f_out.writelines(f_in)
-   f_out.close()
-   f_in.close()
+   with open('/home/joe/file.txt', 'rb') as f_in:
+       with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
+           f_out.writelines(f_in)
 
+Example of how to GZIP compress a binary string::
+
+   import gzip
+   s_in = b"Lots of content here"
+   s_out = gzip.compress(s_in)
 
 .. seealso::
 

Modified: python/branches/pep-0384/Doc/library/hashlib.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/hashlib.rst	(original)
+++ python/branches/pep-0384/Doc/library/hashlib.rst	Fri Aug 27 21:11:11 2010
@@ -114,10 +114,9 @@
    equivalent to ``m.update(a+b)``.
 
    .. versionchanged:: 3.1
-
-      The Python GIL is released to allow other threads to run while
-      hash updates on data larger than 2048 bytes is taking place when
-      using hash algorithms supplied by OpenSSL.
+      The Python GIL is released to allow other threads to run while hash
+      updates on data larger than 2048 bytes is taking place when using hash
+      algorithms supplied by OpenSSL.
 
 
 .. method:: hash.digest()

Modified: python/branches/pep-0384/Doc/library/heapq.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/heapq.rst	(original)
+++ python/branches/pep-0384/Doc/library/heapq.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/html.parser.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/html.parser.rst	(original)
+++ python/branches/pep-0384/Doc/library/html.parser.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/http.client.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/http.client.rst	(original)
+++ python/branches/pep-0384/Doc/library/http.client.rst	Fri Aug 27 21:11:11 2010
@@ -394,6 +394,7 @@
 
    .. versionadded:: 3.1
 
+
 .. method:: HTTPConnection.set_tunnel(host, port=None, headers=None)
 
    Set the host and the port for HTTP Connect Tunnelling. Normally used when it
@@ -404,6 +405,7 @@
 
    .. versionadded:: 3.2
 
+
 .. method:: HTTPConnection.connect()
 
    Connect to the server specified when the object was created.
@@ -465,8 +467,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/pep-0384/Doc/library/importlib.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/importlib.rst	(original)
+++ python/branches/pep-0384/Doc/library/importlib.rst	Fri Aug 27 21:11:11 2010
@@ -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/pep-0384/Doc/library/io.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/io.rst	(original)
+++ python/branches/pep-0384/Doc/library/io.rst	Fri Aug 27 21:11:11 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
@@ -301,7 +301,7 @@
       Return the new absolute position.
 
       .. versionadded:: 3.1
-         The ``SEEK_*`` constants
+         The ``SEEK_*`` constants.
 
    .. method:: seekable()
 

Modified: python/branches/pep-0384/Doc/library/itertools.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/itertools.rst	(original)
+++ python/branches/pep-0384/Doc/library/itertools.rst	Fri Aug 27 21:11:11 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::
@@ -207,6 +207,7 @@
 
    .. versionadded:: 3.1
 
+
 .. function:: compress(data, selectors)
 
    Make an iterator that filters elements from *data* returning only those that
@@ -240,7 +241,7 @@
    for i in count())``.
 
    .. versionchanged:: 3.1
-      added *step* argument and allowed non-integer arguments.
+      Added *step* argument and allowed non-integer arguments.
 
 .. function:: cycle(iterable)
 
@@ -653,6 +654,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/pep-0384/Doc/library/json.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/json.rst	(original)
+++ python/branches/pep-0384/Doc/library/json.rst	Fri Aug 27 21:11:11 2010
@@ -339,7 +339,7 @@
    encoders and decoders.  Otherwise, it will be a :exc:`ValueError` to encode
    such floats.
 
-   If *sort_keys* is ``True`` (the default), then the output of dictionaries
+   If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
    will be sorted by key; this is useful for regression tests to ensure that
    JSON serializations can be compared on a day-to-day basis.
 

Modified: python/branches/pep-0384/Doc/library/linecache.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/linecache.rst	(original)
+++ python/branches/pep-0384/Doc/library/linecache.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/locale.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/locale.rst	(original)
+++ python/branches/pep-0384/Doc/library/locale.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/logging.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/logging.rst	(original)
+++ python/branches/pep-0384/Doc/library/logging.rst	Fri Aug 27 21:11:11 2010
@@ -440,8 +440,6 @@
 class defined in package `mypackage` and module `mymodule`, where `mypackage`
 is available on the Python import path).
 
-.. versionchanged:: 3.2
-
 In Python 3.2, a new means of configuring logging has been introduced, using
 dictionaries to hold configuration information. This provides a superset of the
 functionality of the config-file-based approach outlined above, and is the
@@ -521,9 +519,8 @@
 just "foo".
 
 .. versionadded:: 3.1
-
-The :class:`NullHandler` class was not present in previous versions, but is now
-included, so that it need not be defined in library code.
+   The :class:`NullHandler` class was not present in previous versions, but is
+   now included, so that it need not be defined in library code.
 
 
 
@@ -953,6 +950,7 @@
 
    .. versionadded:: 3.2
 
+
 .. method:: Logger.debug(msg, *args, **kwargs)
 
    Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
@@ -2373,7 +2371,7 @@
 
    .. method:: emit(record)
 
-      Sends the record to the Web server as an URL-encoded dictionary.
+      Sends the record to the Web server as a percent-encoded dictionary.
 
 
 .. _formatter-objects:
@@ -2523,6 +2521,13 @@
       yes. If deemed appropriate, the record may be modified in-place by this
       method.
 
+Note that filters attached to handlers are consulted whenever an event is
+emitted by the handler, whereas filters attached to loggers are consulted
+whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
+etc.) This means that events which have been generated by descendant loggers
+will not be filtered by a logger's filter setting, unless the filter has also
+been applied to those descendant loggers.
+
 .. _log-record:
 
 LogRecord Objects
@@ -2586,9 +2591,8 @@
 you can use the two types of instances interchangeably.
 
 .. versionchanged:: 3.2
-
-The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This method
-delegates to the underlying logger.
+   The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`.  This
+   method delegates to the underlying logger.
 
 
 Thread Safety

Modified: python/branches/pep-0384/Doc/library/mmap.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/mmap.rst	(original)
+++ python/branches/pep-0384/Doc/library/mmap.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/msvcrt.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/msvcrt.rst	(original)
+++ python/branches/pep-0384/Doc/library/msvcrt.rst	Fri Aug 27 21:11:11 2010
@@ -90,12 +90,12 @@
 
 .. function:: getch()
 
-   Read a keypress and return the resulting character.  Nothing is echoed to the
-   console.  This call will block if a keypress is not already available, but will
-   not wait for :kbd:`Enter` to be pressed. If the pressed key was a special
-   function key, this will return ``'\000'`` or ``'\xe0'``; the next call will
-   return the keycode.  The :kbd:`Control-C` keypress cannot be read with this
-   function.
+   Read a keypress and return the resulting character as a byte string.
+   Nothing is echoed to the console.  This call will block if a keypress
+   is not already available, but will not wait for :kbd:`Enter` to be
+   pressed. If the pressed key was a special function key, this will
+   return ``'\000'`` or ``'\xe0'``; the next call will return the keycode.
+   The :kbd:`Control-C` keypress cannot be read with this function.
 
 
 .. function:: getwch()
@@ -116,7 +116,7 @@
 
 .. function:: putch(char)
 
-   Print the character *char* to the console without buffering.
+   Print the byte string *char* to the console without buffering.
 
 
 .. function:: putwch(unicode_char)
@@ -126,8 +126,8 @@
 
 .. function:: ungetch(char)
 
-   Cause the character *char* to be "pushed back" into the console buffer; it will
-   be the next character read by :func:`getch` or :func:`getche`.
+   Cause the byte string *char* to be "pushed back" into the console buffer;
+   it will be the next character read by :func:`getch` or :func:`getche`.
 
 
 .. function:: ungetwch(unicode_char)

Modified: python/branches/pep-0384/Doc/library/operator.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/operator.rst	(original)
+++ python/branches/pep-0384/Doc/library/operator.rst	Fri Aug 27 21:11:11 2010
@@ -333,7 +333,23 @@
    attribute is requested, returns a tuple of attributes. After,
    ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``.  After,
    ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
-   b.date)``.
+   b.date)``.  Equivalent to::
+
+      def attrgetter(*items):
+          if len(items) == 1:
+              attr = items[0]
+              def g(obj):
+                  return resolve_attr(obj, attr)
+          else:
+              def g(obj):
+                  return tuple(resolve_att(obj, attr) for attr in items)
+          return g
+
+      def resolve_attr(obj, attr):
+          for name in attr.split("."):
+              obj = getattr(obj, name)
+          return obj
+
 
    The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
    the call ``f(b)`` returns ``b.date.month``.
@@ -344,15 +360,15 @@
    operand's :meth:`__getitem__` method.  If multiple items are specified,
    returns a tuple of lookup values.  Equivalent to::
 
-        def itemgetter(*items):
-            if len(items) == 1:
-                item = items[0]
-                def g(obj):
-                    return obj[item]
-            else:
-                def g(obj):
-                    return tuple(obj[item] for item in items)
-            return g
+      def itemgetter(*items):
+          if len(items) == 1:
+              item = items[0]
+              def g(obj):
+                  return obj[item]
+          else:
+              def g(obj):
+                  return tuple(obj[item] for item in items)
+          return g
 
    The items can be any type accepted by the operand's :meth:`__getitem__`
    method.  Dictionaries accept any hashable value.  Lists, tuples, and
@@ -369,12 +385,12 @@
    Example of using :func:`itemgetter` to retrieve specific fields from a
    tuple record:
 
-       >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
-       >>> getcount = itemgetter(1)
-       >>> map(getcount, inventory)
-       [3, 2, 5, 1]
-       >>> sorted(inventory, key=getcount)
-       [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
+      >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
+      >>> getcount = itemgetter(1)
+      >>> map(getcount, inventory)
+      [3, 2, 5, 1]
+      >>> sorted(inventory, key=getcount)
+      [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
 
 
 .. function:: methodcaller(name[, args...])
@@ -383,7 +399,12 @@
    additional arguments and/or keyword arguments are given, they will be given
    to the method as well.  After ``f = methodcaller('name')``, the call ``f(b)``
    returns ``b.name()``.  After ``f = methodcaller('name', 'foo', bar=1)``, the
-   call ``f(b)`` returns ``b.name('foo', bar=1)``.
+   call ``f(b)`` returns ``b.name('foo', bar=1)``.  Equivalent to::
+
+      def methodcaller(name, *args, **kwargs):
+          def caller(obj):
+              return getattr(obj, name)(*args, **kwargs)
+          return caller
 
 
 .. _operator-map:

Modified: python/branches/pep-0384/Doc/library/optparse.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/optparse.rst	(original)
+++ python/branches/pep-0384/Doc/library/optparse.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/os.path.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/os.path.rst	(original)
+++ python/branches/pep-0384/Doc/library/os.path.rst	Fri Aug 27 21:11:11 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!

Modified: python/branches/pep-0384/Doc/library/os.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/os.rst	(original)
+++ python/branches/pep-0384/Doc/library/os.rst	Fri Aug 27 21:11:11 2010
@@ -67,23 +67,22 @@
 File Names, Command Line Arguments, and Environment Variables
 -------------------------------------------------------------
 
-In Python, file names, command line arguments, and environment
-variables are represented using the string type. On some systems,
-decoding these strings to and from bytes is necessary before passing
-them to the operating system. Python uses the file system encoding to
-perform this conversion (see :func:`sys.getfilesystemencoding`).
+In Python, file names, command line arguments, and environment variables are
+represented using the string type. On some systems, decoding these strings to
+and from bytes is necessary before passing them to the operating system. Python
+uses the file system encoding to perform this conversion (see
+:func:`sys.getfilesystemencoding`).
 
 .. versionchanged:: 3.1
-   On some systems, conversion using the file system encoding may
-   fail. In this case, Python uses the ``surrogateescape`` encoding
-   error handler, which means that undecodable bytes are replaced by a
-   Unicode character U+DCxx on decoding, and these are again
-   translated to the original byte on encoding.
+   On some systems, conversion using the file system encoding may fail. In this
+   case, Python uses the ``surrogateescape`` encoding error handler, which means
+   that undecodable bytes are replaced by a Unicode character U+DCxx on
+   decoding, and these are again translated to the original byte on encoding.
 
 
-The file system encoding must guarantee to successfully decode all
-bytes below 128. If the file system encoding fails to provide this
-guarantee, API functions may raise UnicodeErrors.
+The file system encoding must guarantee to successfully decode all bytes
+below 128. If the file system encoding fails to provide this guarantee, API
+functions may raise UnicodeErrors.
 
 
 .. _os-procinfo:
@@ -156,13 +155,26 @@
    These functions are described in :ref:`os-file-dir`.
 
 
-.. function:: fsencode(value)
+.. function:: fsencode(filename)
 
-   Encode *value* to bytes for use in the file system, environment variables or
-   the command line. Use :func:`sys.getfilesystemencoding` and
-   ``'surrogateescape'`` error handler for strings and return bytes unchanged.
-   On Windows, use ``'strict'`` error handler for strings if the file system
-   encoding is ``'mbcs'`` (which is the default encoding).
+   Encode *filename* to the filesystem encoding with ``'surrogateescape'``
+   error handler, return :class:`bytes` unchanged. On Windows, use ``'strict'``
+   error handler if the filesystem encoding is ``'mbcs'`` (which is the default
+   encoding).
+
+   :func:`fsdencode` is the reverse function.
+
+   .. versionadded:: 3.2
+
+
+.. function:: fsdecode(filename)
+
+   Decode *filename* from the filesystem encoding with ``'surrogateescape'``
+   error handler, return :class:`str` unchanged. On Windows, use ``'strict'``
+   error handler if the filesystem encoding is ``'mbcs'`` (which is the default
+   encoding).
+
+   :func:`fsencode` is the reverse function.
 
    .. versionadded:: 3.2
 
@@ -1049,10 +1061,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,6 +1072,8 @@
 
    Availability: Unix, Windows.
 
+   .. versionchanged:: 3.2
+      The *path* parameter became optional.
 
 .. function:: lstat(path)
 
@@ -1341,6 +1355,14 @@
    :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
    :attr:`f_flag`, :attr:`f_namemax`.
 
+   Two module-level constants are defined for the :attr:`f_flag` attribute's
+   bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
+   read-only, and if :const:`ST_NOSUID` is set, the semantics of
+   setuid/setgid bits are disabled or not supported.
+
+   .. versionchanged:: 3.2
+      The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
+
    Availability: Unix.
 
 
@@ -1742,7 +1764,8 @@
    will be set to *sig*. The Windows version of :func:`kill` additionally takes
    process handles to be killed.
 
-   .. versionadded:: 3.2 Windows support
+   .. versionadded:: 3.2
+      Windows support.
 
 
 .. function:: killpg(pgid, sig)
@@ -1921,8 +1944,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/pep-0384/Doc/library/parser.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/parser.rst	(original)
+++ python/branches/pep-0384/Doc/library/parser.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/pdb.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/pdb.rst	(original)
+++ python/branches/pep-0384/Doc/library/pdb.rst	Fri Aug 27 21:11:11 2010
@@ -44,11 +44,15 @@
    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 ::
 
@@ -81,21 +85,21 @@
 
 .. 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 :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.)
+   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)
@@ -202,6 +206,11 @@
 in the home directory is read first and aliases defined there can be overridden
 by the local file.
 
+.. 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]
 
@@ -321,10 +330,17 @@
    executes called functions at (nearly) full speed, only stopping at the next
    line in the current function.)
 
-.. pdbcommand:: unt(il)
+.. pdbcommand:: unt(il) [lineno]
+
+   Without argument, continue execution until the line with a number greater
+   than the current one is reached.
 
-   Continue execution until the line with the line number greater than the
-   current one is reached or when returning from current frame.
+   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)
 
@@ -347,10 +363,26 @@
 .. 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 one argument,
+   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)
 
    Print the argument list of the current function.
@@ -368,6 +400,12 @@
 
    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]]
@@ -387,9 +425,9 @@
    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
 
 .. pdbcommand:: unalias name

Modified: python/branches/pep-0384/Doc/library/pickletools.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/pickletools.rst	(original)
+++ python/branches/pep-0384/Doc/library/pickletools.rst	Fri Aug 27 21:11:11 2010
@@ -26,6 +26,9 @@
    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)
 
    Provides an :term:`iterator` over all of the opcodes in a pickle, returning a

Modified: python/branches/pep-0384/Doc/library/poplib.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/poplib.rst	(original)
+++ python/branches/pep-0384/Doc/library/poplib.rst	Fri Aug 27 21:11:11 2010
@@ -32,13 +32,19 @@
    be used).
 
 
-.. class:: POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None[, timeout])
+.. class:: POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None)
 
    This is a subclass of :class:`POP3` that connects to the server over an SSL
    encrypted socket.  If *port* is not specified, 995, the standard POP3-over-SSL
    port is used.  *keyfile* and *certfile* are also optional - they can contain a
    PEM formatted private key and certificate chain file for the SSL connection.
-   *timeout* works as in the :class:`POP3` constructor.
+   *timeout* works as in the :class:`POP3` constructor. *context* parameter is a
+   :class:`ssl.SSLContext` object which allows bundling SSL configuration
+   options, certificates and private keys into a single (potentially long-lived)
+   structure.
+
+   .. versionchanged:: 3.2
+      *context* parameter added.
 
 
 One exception is defined as an attribute of the :mod:`poplib` module:

Modified: python/branches/pep-0384/Doc/library/pyexpat.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/pyexpat.rst	(original)
+++ python/branches/pep-0384/Doc/library/pyexpat.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/re.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/re.rst	(original)
+++ python/branches/pep-0384/Doc/library/re.rst	Fri Aug 27 21:11:11 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.
 
@@ -710,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:
@@ -818,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)
-
-      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.
+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``.
 
+   For example:
 
-   .. 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:
-
-         >>> 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
@@ -1038,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::
 
@@ -1114,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
 
@@ -1253,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/pep-0384/Doc/library/runpy.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/runpy.rst	(original)
+++ python/branches/pep-0384/Doc/library/runpy.rst	Fri Aug 27 21:11:11 2010
@@ -68,8 +68,7 @@
 
 
    .. versionchanged:: 3.1
-         Added ability to execute packages by looking for a ``__main__``
-         submodule
+      Added ability to execute packages by looking for a ``__main__`` submodule.
 
 
 .. function:: run_path(file_path, init_globals=None, run_name=None)

Modified: python/branches/pep-0384/Doc/library/signal.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/signal.rst	(original)
+++ python/branches/pep-0384/Doc/library/signal.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/smtpd.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/smtpd.rst	(original)
+++ python/branches/pep-0384/Doc/library/smtpd.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/smtplib.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/smtplib.rst	(original)
+++ python/branches/pep-0384/Doc/library/smtplib.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/socket.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/socket.rst	(original)
+++ python/branches/pep-0384/Doc/library/socket.rst	Fri Aug 27 21:11:11 2010
@@ -214,7 +214,7 @@
       *source_address* was added.
 
 
-.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)
+.. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
 
    Translate the *host*/*port* argument into a sequence of 5-tuples that contain
    all the necessary arguments for creating a socket connected to that service.
@@ -223,7 +223,7 @@
    port number or ``None``.  By passing ``None`` as the value of *host*
    and *port*, you can pass ``NULL`` to the underlying C API.
 
-   The *family*, *socktype* and *proto* arguments can be optionally specified
+   The *family*, *type* and *proto* arguments can be optionally specified
    in order to narrow the list of addresses returned.  Passing zero as a
    value for each of these arguments selects the full range of results.
    The *flags* argument can be one or several of the ``AI_*`` constants,
@@ -233,9 +233,9 @@
 
    The function returns a list of 5-tuples with the following structure:
 
-   ``(family, socktype, proto, canonname, sockaddr)``
+   ``(family, type, proto, canonname, sockaddr)``
 
-   In these tuples, *family*, *socktype*, *proto* are all integers and are
+   In these tuples, *family*, *type*, *proto* are all integers and are
    meant to be passed to the :func:`socket` function.  *canonname* will be
    a string representing the canonical name of the *host* if
    :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
@@ -249,10 +249,13 @@
    connection to ``www.python.org`` on port 80 (results may differ on your
    system if IPv6 isn't enabled)::
 
-      >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP)
+      >>> socket.getaddrinfo("www.python.org", 80, proto=socket.SOL_TCP)
       [(2, 1, 6, '', ('82.94.164.162', 80)),
        (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
 
+   .. versionchanged:: 3.2
+      parameters can now be passed as single keyword arguments.
+
 .. function:: getfqdn([name])
 
    Return a fully qualified domain name for *name*. If *name* is omitted or empty,
@@ -538,6 +541,15 @@
    connects.
 
 
+.. method:: socket.detach()
+
+   Put the socket object into closed state without actually closing the
+   underlying file descriptor.  The file descriptor is returned, and can
+   be reused for other purposes.
+
+   .. versionadded:: 3.2
+
+
 .. method:: socket.fileno()
 
    Return the socket's file descriptor (a small integer).  This is useful with

Modified: python/branches/pep-0384/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/sqlite3.rst	(original)
+++ python/branches/pep-0384/Doc/library/sqlite3.rst	Fri Aug 27 21:11:11 2010
@@ -229,11 +229,10 @@
 
 .. attribute:: Connection.in_transaction
 
-   .. versionadded:: 3.2
-
    :const:`True` if a transaction is active (there are uncommitted changes),
    :const:`False` otherwise.  Read-only attribute.
 
+   .. versionadded:: 3.2
 
 .. method:: Connection.cursor([cursorClass])
 
@@ -241,7 +240,6 @@
    supplied, this must be a custom cursor class that extends
    :class:`sqlite3.Cursor`.
 
-
 .. method:: Connection.commit()
 
    This method commits the current transaction. If you don't call this method,
@@ -374,23 +372,23 @@
 
 .. method:: Connection.enable_load_extension(enabled)
 
-   .. versionadded:: 3.2
-
    This routine allows/disallows the SQLite engine to load SQLite extensions
    from shared libraries.  SQLite extensions can define new functions,
    aggregates or whole new virtual table implementations. One well-known
    extension is the fulltext-search extension distributed with SQLite.
 
+   .. versionadded:: 3.2
+
    .. literalinclude:: ../includes/sqlite3/load_extension.py
 
 .. method:: Connection.load_extension(path)
 
-   .. versionadded:: 3.2
-
    This routine loads a SQLite extension from a shared library. You have to
    enable extension loading with ``enable_load_extension`` before you can use
    this routine.
 
+   .. versionadded:: 3.2
+
 .. attribute:: Connection.row_factory
 
    You can change this attribute to a callable that accepts the cursor and the
@@ -867,3 +865,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/pep-0384/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/stdtypes.rst	(original)
+++ python/branches/pep-0384/Doc/library/stdtypes.rst	Fri Aug 27 21:11:11 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
@@ -458,7 +459,7 @@
 
     .. versionadded:: 3.1
 
-    .. method:: int.to_bytes(length, byteorder, \*, signed=False)
+.. method:: int.to_bytes(length, byteorder, \*, signed=False)
 
     Return an array of bytes representing an integer.
 
@@ -490,7 +491,7 @@
 
     .. versionadded:: 3.2
 
-    .. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False)
+.. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False)
 
     Return the integer represented by the given array of bytes.
 
@@ -995,7 +996,8 @@
    list of possible encodings, see section :ref:`standard-encodings`.
 
    .. versionchanged:: 3.1
-      Added support for keyword arguments added.
+      Support for keyword arguments added.
+
 
 .. method:: str.endswith(suffix[, start[, end]])
 
@@ -1330,10 +1332,6 @@
    You can use :meth:`str.maketrans` to create a translation map from
    character-to-character mappings in different formats.
 
-   You can use the :func:`~string.maketrans` helper function in the :mod:`string`
-   module to create a translation table. For string objects, set the *table*
-   argument to ``None`` for translations that only delete characters:
-
    .. note::
 
       An even more flexible approach is to create a custom character mapping
@@ -2141,8 +2139,8 @@
 
    .. method:: update([other])
 
-     Update the dictionary with the key/value pairs from *other*, overwriting
-     existing keys.  Return ``None``.
+      Update the dictionary with the key/value pairs from *other*, overwriting
+      existing keys.  Return ``None``.
 
       :meth:`update` accepts either another dictionary object or an iterable of
       key/value pairs (as a tuple or other iterable of length two).  If keyword

Modified: python/branches/pep-0384/Doc/library/string.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/string.rst	(original)
+++ python/branches/pep-0384/Doc/library/string.rst	Fri Aug 27 21:11:11 2010
@@ -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/pep-0384/Doc/library/subprocess.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/subprocess.rst	(original)
+++ python/branches/pep-0384/Doc/library/subprocess.rst	Fri Aug 27 21:11:11 2010
@@ -307,7 +307,7 @@
 Exceptions raised in the child process, before the new program has started to
 execute, will be re-raised in the parent.  Additionally, the exception object
 will have one extra attribute called :attr:`child_traceback`, which is a string
-containing traceback information from the childs point of view.
+containing traceback information from the child's point of view.
 
 The most common exception raised is :exc:`OSError`.  This occurs, for example,
 when trying to execute a non-existent file.  Applications should prepare for

Modified: python/branches/pep-0384/Doc/library/sys.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/sys.rst	(original)
+++ python/branches/pep-0384/Doc/library/sys.rst	Fri Aug 27 21:11:11 2010
@@ -707,9 +707,9 @@
    every virtual instruction, maximizing responsiveness as well as overhead.
 
    .. deprecated:: 3.2
-      This function doesn't have an effect anymore, as the internal logic
-      for thread switching and asynchronous tasks has been rewritten.
-      Use :func:`setswitchinterval` instead.
+      This function doesn't have an effect anymore, as the internal logic for
+      thread switching and asynchronous tasks has been rewritten.  Use
+      :func:`setswitchinterval` instead.
 
 
 .. function:: setdefaultencoding(name)
@@ -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
@@ -962,7 +958,7 @@
    and so on.
 
    .. versionchanged:: 3.1
-      Added named component attributes
+      Added named component attributes.
 
 .. data:: warnoptions
 

Modified: python/branches/pep-0384/Doc/library/test.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/test.rst	(original)
+++ python/branches/pep-0384/Doc/library/test.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/threading.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/threading.rst	(original)
+++ python/branches/pep-0384/Doc/library/threading.rst	Fri Aug 27 21:11:11 2010
@@ -33,6 +33,8 @@
    variable allows one or more threads to wait until they are notified by another
    thread.
 
+   See :ref:`condition-objects`.
+
 
 .. function:: current_thread()
 
@@ -58,6 +60,8 @@
    with the :meth:`clear` method.  The :meth:`wait` method blocks until the flag
    is true.
 
+   See :ref:`event-objects`.
+
 
 .. class:: local
 
@@ -80,6 +84,8 @@
    acquired it, subsequent attempts to acquire it block, until it is released; any
    thread may release it.
 
+   See :ref:`lock-objects`.
+
 
 .. function:: RLock()
 
@@ -88,6 +94,8 @@
    reentrant lock, the same thread may acquire it again without blocking; the
    thread must release it once for each time it has acquired it.
 
+   See :ref:`rlock-objects`.
+
 
 .. function:: Semaphore(value=1)
    :noindex:
@@ -98,6 +106,8 @@
    if necessary until it can return without making the counter negative.  If not
    given, *value* defaults to 1.
 
+   See :ref:`semaphore-objects`.
+
 
 .. function:: BoundedSemaphore(value=1)
 
@@ -109,15 +119,21 @@
 
 
 .. class:: Thread
+   :noindex:
 
    A class that represents a thread of control.  This class can be safely
    subclassed in a limited fashion.
 
+   See :ref:`thread-objects`.
+
 
 .. class:: Timer
+   :noindex:
 
    A thread that executes a function after a specified interval has passed.
 
+   See :ref:`timer-objects`.
+
 
 .. function:: settrace(func)
 
@@ -166,6 +182,7 @@
 
    .. versionadded:: 3.2
 
+
 Detailed interfaces for the objects are documented below.
 
 The design of this module is loosely based on Java's threading model. However,
@@ -310,8 +327,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
@@ -386,6 +403,7 @@
    .. versionchanged:: 3.2
       The *timeout* parameter is new.
 
+
 .. method:: Lock.release()
 
    Release a lock.

Modified: python/branches/pep-0384/Doc/library/tkinter.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/tkinter.rst	(original)
+++ python/branches/pep-0384/Doc/library/tkinter.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/unittest.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/unittest.rst	(original)
+++ python/branches/pep-0384/Doc/library/unittest.rst	Fri Aug 27 21:11:11 2010
@@ -210,7 +210,7 @@
 
    python -m unittest -h
 
-..  versionchanged:: 3.2
+.. versionchanged:: 3.2
    In earlier versions it was only possible to run individual test methods and
    not modules or classes.
 
@@ -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.
@@ -861,8 +861,8 @@
       Supplying both *delta* and *places* raises a ``TypeError``.
 
       .. versionchanged:: 3.2
-         Objects that compare equal automatically fail.
-         Added the ``delta`` keyword argument.
+         Objects that compare equal automatically fail.  Added the ``delta``
+         keyword argument.
 
       .. deprecated:: 3.1
          :meth:`failIfAlmostEqual`; use :meth:`assertNotAlmostEqual`.
@@ -941,9 +941,9 @@
       If specified, *msg* will be used as the error message on failure.
 
       .. versionadded:: 3.1
-
       .. deprecated:: 3.2
 
+
    .. method:: assertItemsEqual(actual, expected, msg=None)
 
       Test that sequence *expected* contains the same elements as *actual*,
@@ -960,6 +960,7 @@
 
       .. versionadded:: 3.2
 
+
    .. method:: assertSetEqual(set1, set2, msg=None)
 
       Tests that two sets are equal.  If not, an error message is constructed
@@ -1048,11 +1049,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.
@@ -1683,14 +1684,16 @@
       The default implementation appends the test to the instance's
       :attr:`unexpectedSuccesses` attribute.
 
+
 .. class:: TextTestResult(stream, descriptions, verbosity)
 
-    A concrete implementation of :class:`TestResult` used by the
-    :class:`TextTestRunner`.
+   A concrete implementation of :class:`TestResult` used by the
+   :class:`TextTestRunner`.
+
+   .. versionadded:: 3.2
+      This class was previously named ``_TextTestResult``. The old name still
+      exists as an alias but is deprecated.
 
-    .. versionadded:: 3.2
-        This class was previously named ``_TextTestResult``. The old name still
-        exists as an alias but is deprecated.
 
 .. data:: defaultTestLoader
 

Modified: python/branches/pep-0384/Doc/library/urllib.parse.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/urllib.parse.rst	(original)
+++ python/branches/pep-0384/Doc/library/urllib.parse.rst	Fri Aug 27 21:11:11 2010
@@ -48,6 +48,23 @@
       >>> o.geturl()
       'http://www.cwi.nl:80/%7Eguido/Python.html'
 
+   If the scheme value is not specified, urlparse expects the netloc value to
+   start with '//', following the syntax specifications from :rfc:`1808`.
+   Otherwise, it is not possible to distinguish between netloc and path
+   components, and would the indistinguishable component would be classified
+   as the 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.
@@ -100,7 +117,7 @@
    values are lists of values for each name.
 
    The optional argument *keep_blank_values* is a flag indicating whether blank
-   values in URL encoded queries should be treated as blank strings.   A true value
+   values in percent-encoded queries should be treated as blank strings. A true value
    indicates that blanks should be retained as  blank strings.  The default false
    value indicates that blank values are to be ignored and treated as if they were
    not included.
@@ -120,7 +137,7 @@
    name, value pairs.
 
    The optional argument *keep_blank_values* is a flag indicating whether blank
-   values in URL encoded queries should be treated as blank strings.   A true value
+   values in percent-encoded queries should be treated as blank strings. A true value
    indicates that blanks should be retained as  blank strings.  The default false
    value indicates that blank values are to be ignored and treated as if they were
    not included.
@@ -313,7 +330,7 @@
 .. function:: urlencode(query, doseq=False, safe='', encoding=None, errors=None)
 
    Convert a mapping object or a sequence of two-element tuples, which may
-   either be a :class:`str` or a :class:`bytes`,  to a "url-encoded" string,
+   either be a :class:`str` or a :class:`bytes`,  to a "percent-encoded" string,
    suitable to pass to :func:`urlopen` above as the optional *data* argument.
    This is useful to pass a dictionary of form fields to a ``POST`` request.
    The resulting string is a series of ``key=value`` pairs separated by ``'&'``
@@ -332,7 +349,7 @@
    parameters are sent the :func:`quote_plus` for encoding.
 
    .. versionchanged:: 3.2
-      query paramater supports bytes and string.
+      Query parameter supports bytes and string objects.
 
 
 .. seealso::

Modified: python/branches/pep-0384/Doc/library/urllib.request.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/urllib.request.rst	(original)
+++ python/branches/pep-0384/Doc/library/urllib.request.rst	Fri Aug 27 21:11:11 2010
@@ -26,7 +26,8 @@
    *data* should be a buffer in the standard
    :mimetype:`application/x-www-form-urlencoded` format.  The
    :func:`urllib.parse.urlencode` function takes a mapping or sequence
-   of 2-tuples and returns a string in this format.
+   of 2-tuples and returns a string in this format. urllib.request module uses
+   HTTP/1.1 and includes `Connection:close` header in its HTTP requests.
 
    The optional *timeout* parameter specifies a timeout in seconds for
    blocking operations like the connection attempt (if not specified,
@@ -140,7 +141,7 @@
 
 .. function:: url2pathname(path)
 
-   Convert the path component *path* from an encoded URL to the local syntax for a
+   Convert the path component *path* from a percent-encoded URL to the local syntax for a
    path.  This does not accept a complete URL.  This function uses :func:`unquote`
    to decode *path*.
 
@@ -638,7 +639,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/pep-0384/Doc/library/wsgiref.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/wsgiref.rst	(original)
+++ python/branches/pep-0384/Doc/library/wsgiref.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/xml.dom.minidom.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/xml.dom.minidom.rst	(original)
+++ python/branches/pep-0384/Doc/library/xml.dom.minidom.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/xml.dom.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/xml.dom.rst	(original)
+++ python/branches/pep-0384/Doc/library/xml.dom.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/xml.etree.elementtree.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/xml.etree.elementtree.rst	(original)
+++ python/branches/pep-0384/Doc/library/xml.etree.elementtree.rst	Fri Aug 27 21:11:11 2010
@@ -148,20 +148,22 @@
    arguments.  Returns an element instance.
 
 
-.. function:: tostring(element, encoding=None, method="xml")
+.. function:: tostring(element, encoding="us-ascii", method="xml")
 
    Generates a string representation of an XML element, including all
    subelements.  *element* is an :class:`Element` instance.  *encoding* [1]_ is
-   the output encoding (default is None).  *method* is either ``"xml"``,
+   the output encoding (default is US-ASCII).  Use ``encoding="unicode"`` to
+   generate a Unicode string.  *method* is either ``"xml"``,
    ``"html"`` or ``"text"`` (default is ``"xml"``).  Returns an (optionally)
    encoded string containing the XML data.
 
 
-.. function:: tostringlist(element, encoding=None, method="xml")
+.. function:: tostringlist(element, encoding="us-ascii", method="xml")
 
    Generates a string representation of an XML element, including all
    subelements.  *element* is an :class:`Element` instance.  *encoding* [1]_ is
-   the output encoding (default is None).   *method* is either ``"xml"``,
+   the output encoding (default is US-ASCII).  Use ``encoding="unicode"`` to
+   generate a Unicode string.  *method* is either ``"xml"``,
    ``"html"`` or ``"text"`` (default is ``"xml"``).  Returns a list of
    (optionally) encoded strings containing the XML data.  It does not guarantee
    any specific sequence, except that ``"".join(tostringlist(element)) ==
@@ -307,13 +309,13 @@
 
    .. method:: getchildren()
 
-      .. deprecated:: 2.7
+      .. deprecated:: 3.2
          Use ``list(elem)`` or iteration.
 
 
    .. method:: getiterator(tag=None)
 
-      .. deprecated:: 2.7
+      .. deprecated:: 3.2
          Use method :meth:`Element.iter` instead.
 
 
@@ -425,11 +427,12 @@
 
    .. method:: getiterator(tag=None)
 
-      .. deprecated:: 2.7
+      .. deprecated:: 3.2
          Use method :meth:`ElementTree.iter` instead.
 
 
    .. method:: getroot()
+
       Returns the root element for this tree.
 
 
@@ -457,15 +460,16 @@
       root element.
 
 
-   .. method:: write(file, encoding=None, xml_declaration=None, method="xml")
+   .. method:: write(file, encoding="us-ascii", xml_declaration=None, method="xml")
 
       Writes the element tree to a file, as XML.  *file* is a file name, or a
       file object opened for writing.  *encoding* [1]_ is the output encoding
-      (default is None).  *xml_declaration* controls if an XML declaration
+      (default is US-ASCII).  Use ``encoding="unicode"`` to write a Unicode string.
+      *xml_declaration* controls if an XML declaration
       should be added to the file.  Use False for never, True for always, None
-      for only if not US-ASCII or UTF-8 (default is None).  *method* is either
-      ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``).  Returns an
-      (optionally) encoded string.
+      for only if not US-ASCII or UTF-8 or Unicode (default is None).  *method* is
+      either ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``).
+      Returns an (optionally) encoded string.
 
 This is the XML file that is going to be manipulated::
 
@@ -585,7 +589,7 @@
 
    .. method:: doctype(name, pubid, system)
 
-      .. deprecated:: 2.7
+      .. deprecated:: 3.2
          Define the :meth:`TreeBuilder.doctype` method on a custom TreeBuilder
          target.
 

Modified: python/branches/pep-0384/Doc/library/xml.sax.reader.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/xml.sax.reader.rst	(original)
+++ python/branches/pep-0384/Doc/library/xml.sax.reader.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/library/zipfile.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/zipfile.rst	(original)
+++ python/branches/pep-0384/Doc/library/zipfile.rst	Fri Aug 27 21:11:11 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,11 +62,11 @@
 
    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.
 
+
 .. data:: ZIP_STORED
 
    The numeric constant for an uncompressed archive member.

Modified: python/branches/pep-0384/Doc/library/zipimport.rst
==============================================================================
--- python/branches/pep-0384/Doc/library/zipimport.rst	(original)
+++ python/branches/pep-0384/Doc/library/zipimport.rst	Fri Aug 27 21:11:11 2010
@@ -95,7 +95,7 @@
       was imported. Raise :exc:`ZipImportError` if the module couldn't be
       found.
 
-   .. versionadded:: 3.1
+      .. versionadded:: 3.1
 
 
    .. method:: get_source(fullname)

Modified: python/branches/pep-0384/Doc/license.rst
==============================================================================
--- python/branches/pep-0384/Doc/license.rst	(original)
+++ python/branches/pep-0384/Doc/license.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/make.bat
==============================================================================
--- python/branches/pep-0384/Doc/make.bat	(original)
+++ python/branches/pep-0384/Doc/make.bat	Fri Aug 27 21:11:11 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/pep-0384/Doc/reference/compound_stmts.rst
==============================================================================
--- python/branches/pep-0384/Doc/reference/compound_stmts.rst	(original)
+++ python/branches/pep-0384/Doc/reference/compound_stmts.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/reference/lexical_analysis.rst
==============================================================================
--- python/branches/pep-0384/Doc/reference/lexical_analysis.rst	(original)
+++ python/branches/pep-0384/Doc/reference/lexical_analysis.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/tools/sphinx-build.py
==============================================================================
--- python/branches/pep-0384/Doc/tools/sphinx-build.py	(original)
+++ python/branches/pep-0384/Doc/tools/sphinx-build.py	Fri Aug 27 21:11:11 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/pep-0384/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/pep-0384/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/pep-0384/Doc/tools/sphinxext/pyspecific.py	Fri Aug 27 21:11:11 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*\((.*)\))?')
 
@@ -197,3 +222,5 @@
     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/pep-0384/Doc/tutorial/classes.rst
==============================================================================
--- python/branches/pep-0384/Doc/tutorial/classes.rst	(original)
+++ python/branches/pep-0384/Doc/tutorial/classes.rst	Fri Aug 27 21:11:11 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

Modified: python/branches/pep-0384/Doc/tutorial/datastructures.rst
==============================================================================
--- python/branches/pep-0384/Doc/tutorial/datastructures.rst	(original)
+++ python/branches/pep-0384/Doc/tutorial/datastructures.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/tutorial/floatingpoint.rst
==============================================================================
--- python/branches/pep-0384/Doc/tutorial/floatingpoint.rst	(original)
+++ python/branches/pep-0384/Doc/tutorial/floatingpoint.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/using/cmdline.rst
==============================================================================
--- python/branches/pep-0384/Doc/using/cmdline.rst	(original)
+++ python/branches/pep-0384/Doc/using/cmdline.rst	Fri Aug 27 21:11:11 2010
@@ -95,8 +95,9 @@
       file is not available.
 
    If this option is given, the first element of :data:`sys.argv` will be the
-   full path to the module file. As with the :option:`-c` option, the current
-   directory will be added to the start of :data:`sys.path`.
+   full path to the module file (while the module file is being located, the
+   first element will be set to ``"-m"``). As with the :option:`-c` option,
+   the current directory will be added to the start of :data:`sys.path`.
 
    Many standard library modules contain code that is invoked on their execution
    as a script.  An example is the :mod:`timeit` module::
@@ -114,6 +115,7 @@
    .. versionchanged:: 3.1
       Supply the package name to run a ``__main__`` submodule.
 
+
 .. describe:: -
 
    Read commands from standard input (:data:`sys.stdin`).  If standard input is
@@ -440,11 +442,24 @@
    import of source modules.
 
 
+.. envvar:: PYTHONFSENCODING
+
+   If this is set before running the interpreter, it overrides the encoding used
+   for the filesystem encoding (see :func:`sys.getfilesystemencoding`).
+
+   This variable is not available (ignored) on Windows and Mac OS X: the
+   filesystem encoding is pinned to ``'mbcs'`` on Windows and ``'utf-8'`` on
+   Mac OS X.
+
+   .. versionadded:: 3.2
+
+
 .. envvar:: PYTHONIOENCODING
 
-   Overrides the encoding used for stdin/stdout/stderr, in the syntax
-   ``encodingname:errorhandler``.  The ``:errorhandler`` part is optional and
-   has the same meaning as in :func:`str.encode`.
+   If this is set before running the interpreter, it overrides the encoding used
+   for stdin/stdout/stderr, in the syntax ``encodingname:errorhandler``. The
+   ``:errorhandler`` part is optional and has the same meaning as in
+   :func:`str.encode`.
 
    For stderr, the ``:errorhandler`` part is ignored; the handler will always be
    ``'backslashreplace'``.

Modified: python/branches/pep-0384/Doc/whatsnew/2.0.rst
==============================================================================
--- python/branches/pep-0384/Doc/whatsnew/2.0.rst	(original)
+++ python/branches/pep-0384/Doc/whatsnew/2.0.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/whatsnew/2.4.rst
==============================================================================
--- python/branches/pep-0384/Doc/whatsnew/2.4.rst	(original)
+++ python/branches/pep-0384/Doc/whatsnew/2.4.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/whatsnew/2.5.rst
==============================================================================
--- python/branches/pep-0384/Doc/whatsnew/2.5.rst	(original)
+++ python/branches/pep-0384/Doc/whatsnew/2.5.rst	Fri Aug 27 21:11:11 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/pep-0384/Doc/whatsnew/2.7.rst
==============================================================================
--- python/branches/pep-0384/Doc/whatsnew/2.7.rst	(original)
+++ python/branches/pep-0384/Doc/whatsnew/2.7.rst	Fri Aug 27 21:11:11 2010
@@ -143,10 +143,12 @@
 * The :class:`memoryview` object.
 * A small subset of the :mod:`importlib` module,
   `described below <#importlib-section>`__.
-* 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 float.
+* The :func:`repr` of a float ``x`` is shorter in many cases: it's now
+  based on the shortest decimal string that's guaranteed to round back
+  to ``x``.  As in previous versions of Python, it's guaranteed that
+  ``float(repr(x))`` recovers ``x``.
+* Float-to-string and string-to-float conversions are correctly rounded.
+  The :func:`round` function is also now correctly rounded.
 * The :ctype:`PyCapsule` type, used to provide a C API for extension modules.
 * The :cfunc:`PyLong_AsLongAndOverflow` C API function.
 

Modified: python/branches/pep-0384/Doc/whatsnew/3.2.rst
==============================================================================
--- python/branches/pep-0384/Doc/whatsnew/3.2.rst	(original)
+++ python/branches/pep-0384/Doc/whatsnew/3.2.rst	Fri Aug 27 21:11:11 2010
@@ -66,18 +66,33 @@
 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 :mod:`functools` module now includes a new decorator for caching
+  function calls. :func:`functools.lru_cache` can save repeated queries to an
+  external resource whenever the results are expected to be the same.
 
-* 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.
+  For example, adding a caching decorator to a database query function can save
+  database accesses for popular searches::
 
-  (Contributed by Georg Brandl; :issue:`5675`.)
+      @functools.lru_cache(maxsize=300)
+      def get_phone_number(name):
+          c = conn.cursor()
+          c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
+          return c.fetchone()[0]
+
+  To help with choosing an effective cache size, the wrapped function is
+  instrumented with two attributes *hits* and *misses*::
+
+        >>> for name in user_requests:
+        ...     get_phone_number(name)
+        >>> print(get_phone_number.hits, get_phone_number.misses)
+        4805 980
+
+  If the phonelist table gets updated, the outdated contents of the cache can be
+  cleared with::
+
+        >>> get_phone_number.clear()
+
+  (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,19 +103,37 @@
   (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`.)
+
+* A warning message will now get printed at interpreter shutdown if
+  the :data:`gc.garbage` list isn't empty.  This is meant to make the
+  programmer aware that his code contains object finalization issues.
+  (Added by Antoine Pitrou; :issue:`477863`.)
+
+* The :mod:`os` module now has the :const:`ST_RDONLY` and :const:`ST_NOSUID`
+  constants, for use with the :func:`~os.statvfs` function.
+  (Patch by Adam Jackson; :issue:`7647`.)
+
 * 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é.)
+
+* Socket objects now have a :meth:`~socket.socket.detach()` method which
+  puts the socket into closed state without actually closing the underlying
+  file descriptor.  The latter can then be reused for other purposes.
+
+  (Added by Antoine Pitrou; :issue:`8524`.)
 
-* The *sqlite3* module has some new features:
+* The :mod:`sqlite3` module has some new features:
 
   * XXX *enable_load_extension*
 
@@ -111,6 +144,58 @@
     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`.)
+
+* Parameters passed to :func:`socket.getaddrinfo()` function can now be
+  specified as single keyword arguments.
+
+  (Contributed by Giampaolo Rodolà; :issue:`8866`.)
+
+* :class:`~poplib.POP3_SSL` class now accepts a *context* parameter, which is a
+  :class:`ssl.SSLContext` object allowing bundling SSL configuration options,
+  certificates and private keys into a single (potentially long-lived)
+  structure.
+
+  (Contributed by Giampaolo Rodolà; :issue:`8807`.)
 
 Multi-threading
 ===============
@@ -151,6 +236,20 @@
 
 * Stub
 
+
+Filenames and unicode
+=====================
+
+The filesystem encoding can be specified by setting the
+:envvar:`PYTHONFSENCODING` environment variable before running the interpreter.
+The value is an encoding name, e.g. ``iso-8859-1``. This variable is not
+available (ignored) on Windows and Mac OS X: the filesystem encoding is pinned
+to ``'mbcs'`` on Windows and ``'utf-8'`` on Mac OS X.
+
+The :mod:`os` module has two new functions: :func:`os.fsencode` and
+:func:`os.fsdecode`.
+
+
 IDLE
 ====
 

Modified: python/branches/pep-0384/Include/Python.h
==============================================================================
--- python/branches/pep-0384/Include/Python.h	(original)
+++ python/branches/pep-0384/Include/Python.h	Fri Aug 27 21:11:11 2010
@@ -61,6 +61,7 @@
 #error "PYMALLOC_DEBUG requires WITH_PYMALLOC"
 #endif
 #include "pymath.h"
+#include "pytime.h"
 #include "pymem.h"
 
 #include "object.h"
@@ -126,11 +127,21 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
+
 /* _Py_Mangle is defined in compile.c */
 PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name);
 
-/* _Py_char2wchar lives in main.c */
+/* These functions live in main.c */
 PyAPI_FUNC(wchar_t *) _Py_char2wchar(char *);
+PyAPI_FUNC(char*) _Py_wchar2char(const wchar_t *text);
+PyAPI_FUNC(FILE *) _Py_wfopen(const wchar_t *path, const wchar_t *mode);
+
+/* These functions live in import.c */
+PyAPI_FUNC(FILE*) _Py_fopen(PyObject *unicode, const char *mode);
+#ifdef HAVE_STAT
+int _Py_stat(PyObject *unicode, struct stat *statbuf);
+#endif
+
 #ifdef __cplusplus
 }
 #endif

Modified: python/branches/pep-0384/Include/floatobject.h
==============================================================================
--- python/branches/pep-0384/Include/floatobject.h	(original)
+++ python/branches/pep-0384/Include/floatobject.h	Fri Aug 27 21:11:11 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/pep-0384/Include/moduleobject.h
==============================================================================
--- python/branches/pep-0384/Include/moduleobject.h	(original)
+++ python/branches/pep-0384/Include/moduleobject.h	Fri Aug 27 21:11:11 2010
@@ -16,6 +16,7 @@
 PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *);
 PyAPI_FUNC(const char *) PyModule_GetName(PyObject *);
 PyAPI_FUNC(const char *) PyModule_GetFilename(PyObject *);
+PyAPI_FUNC(PyObject *) PyModule_GetFilenameObject(PyObject *);
 PyAPI_FUNC(void) _PyModule_Clear(PyObject *);
 PyAPI_FUNC(struct PyModuleDef*) PyModule_GetDef(PyObject*);
 PyAPI_FUNC(void*) PyModule_GetState(PyObject*);

Modified: python/branches/pep-0384/Include/patchlevel.h
==============================================================================
--- python/branches/pep-0384/Include/patchlevel.h	(original)
+++ python/branches/pep-0384/Include/patchlevel.h	Fri Aug 27 21:11:11 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/pep-0384/Include/pyport.h
==============================================================================
--- python/branches/pep-0384/Include/pyport.h	(original)
+++ python/branches/pep-0384/Include/pyport.h	Fri Aug 27 21:11:11 2010
@@ -822,4 +822,14 @@
 #define Py_ULL(x) Py_LL(x##U)
 #endif
 
+#ifdef VA_LIST_IS_ARRAY
+#define Py_VA_COPY(x, y) Py_MEMCPY((x), (y), sizeof(va_list))
+#else
+#ifdef __va_copy
+#define Py_VA_COPY __va_copy
+#else
+#define Py_VA_COPY(x, y) (x) = (y)
+#endif
+#endif
+
 #endif /* Py_PYPORT_H */

Modified: python/branches/pep-0384/Include/pythonrun.h
==============================================================================
--- python/branches/pep-0384/Include/pythonrun.h	(original)
+++ python/branches/pep-0384/Include/pythonrun.h	Fri Aug 27 21:11:11 2010
@@ -161,6 +161,7 @@
 PyAPI_FUNC(void) PyByteArray_Fini(void);
 PyAPI_FUNC(void) PyFloat_Fini(void);
 PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
+PyAPI_FUNC(void) _PyGC_Fini(void);
 
 /* Stuff with no proper home (yet) */
 #ifndef Py_LIMITED_API

Modified: python/branches/pep-0384/Include/setobject.h
==============================================================================
--- python/branches/pep-0384/Include/setobject.h	(original)
+++ python/branches/pep-0384/Include/setobject.h	Fri Aug 27 21:11:11 2010
@@ -22,7 +22,11 @@
 #define PySet_MINSIZE 8
 
 typedef struct {
-    long hash;      /* cached hash code for the entry key */
+    /* Cached hash code of the key.  Note that hash codes are C longs.
+     * We have to use Py_ssize_t instead because set_pop() abuses
+     * the hash field to hold a search finger.
+     */
+    Py_ssize_t hash;
     PyObject *key;
 } setentry;
 

Modified: python/branches/pep-0384/Include/structseq.h
==============================================================================
--- python/branches/pep-0384/Include/structseq.h	(original)
+++ python/branches/pep-0384/Include/structseq.h	Fri Aug 27 21:11:11 2010
@@ -1,5 +1,5 @@
 
-/* Tuple object interface */
+/* Named tuple object interface */
 
 #ifndef Py_STRUCTSEQ_H
 #define Py_STRUCTSEQ_H

Modified: python/branches/pep-0384/Include/sysmodule.h
==============================================================================
--- python/branches/pep-0384/Include/sysmodule.h	(original)
+++ python/branches/pep-0384/Include/sysmodule.h	Fri Aug 27 21:11:11 2010
@@ -14,9 +14,11 @@
 PyAPI_FUNC(void) PySys_SetPath(const wchar_t *);
 
 PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...)
-			Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+                 Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
 PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
-			Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+                 Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
+PyAPI_FUNC(void) PySys_FormatStdout(const char *format, ...);
+PyAPI_FUNC(void) PySys_FormatStderr(const char *format, ...);
 
 PyAPI_DATA(PyObject *) _PySys_TraceFunc, *_PySys_ProfileFunc;
 

Modified: python/branches/pep-0384/Include/unicodeobject.h
==============================================================================
--- python/branches/pep-0384/Include/unicodeobject.h	(original)
+++ python/branches/pep-0384/Include/unicodeobject.h	Fri Aug 27 21:11:11 2010
@@ -200,6 +200,7 @@
 # define PyUnicode_FromUnicode PyUnicodeUCS2_FromUnicode
 # define PyUnicode_FromWideChar PyUnicodeUCS2_FromWideChar
 # define PyUnicode_FSConverter PyUnicodeUCS2_FSConverter
+# define PyUnicode_FSDecoder PyUnicodeUCS2_FSDecoder
 # define PyUnicode_GetDefaultEncoding PyUnicodeUCS2_GetDefaultEncoding
 # define PyUnicode_GetMax PyUnicodeUCS2_GetMax
 # define PyUnicode_GetSize PyUnicodeUCS2_GetSize
@@ -220,24 +221,6 @@
 # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString
 # define _PyUnicode_Fini _PyUnicodeUCS2_Fini
 # define _PyUnicode_Init _PyUnicodeUCS2_Init
-# define _PyUnicode_IsAlpha _PyUnicodeUCS2_IsAlpha
-# define _PyUnicode_IsDecimalDigit _PyUnicodeUCS2_IsDecimalDigit
-# define _PyUnicode_IsDigit _PyUnicodeUCS2_IsDigit
-# define _PyUnicode_IsLinebreak _PyUnicodeUCS2_IsLinebreak
-# define _PyUnicode_IsLowercase _PyUnicodeUCS2_IsLowercase
-# define _PyUnicode_IsNumeric _PyUnicodeUCS2_IsNumeric
-# define _PyUnicode_IsPrintable _PyUnicodeUCS2_IsPrintable
-# define _PyUnicode_IsTitlecase _PyUnicodeUCS2_IsTitlecase
-# define _PyUnicode_IsXidStart _PyUnicodeUCS2_IsXidStart
-# define _PyUnicode_IsXidContinue _PyUnicodeUCS2_IsXidContinue
-# define _PyUnicode_IsUppercase _PyUnicodeUCS2_IsUppercase
-# define _PyUnicode_IsWhitespace _PyUnicodeUCS2_IsWhitespace
-# define _PyUnicode_ToDecimalDigit _PyUnicodeUCS2_ToDecimalDigit
-# define _PyUnicode_ToDigit _PyUnicodeUCS2_ToDigit
-# define _PyUnicode_ToLowercase _PyUnicodeUCS2_ToLowercase
-# define _PyUnicode_ToNumeric _PyUnicodeUCS2_ToNumeric
-# define _PyUnicode_ToTitlecase _PyUnicodeUCS2_ToTitlecase
-# define _PyUnicode_ToUppercase _PyUnicodeUCS2_ToUppercase
 
 #else
 
@@ -300,6 +283,7 @@
 # define PyUnicode_FromUnicode PyUnicodeUCS4_FromUnicode
 # define PyUnicode_FromWideChar PyUnicodeUCS4_FromWideChar
 # define PyUnicode_FSConverter PyUnicodeUCS4_FSConverter
+# define PyUnicode_FSDecoder PyUnicodeUCS4_FSDecoder
 # define PyUnicode_GetDefaultEncoding PyUnicodeUCS4_GetDefaultEncoding
 # define PyUnicode_GetMax PyUnicodeUCS4_GetMax
 # define PyUnicode_GetSize PyUnicodeUCS4_GetSize
@@ -320,24 +304,6 @@
 # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString
 # define _PyUnicode_Fini _PyUnicodeUCS4_Fini
 # define _PyUnicode_Init _PyUnicodeUCS4_Init
-# define _PyUnicode_IsAlpha _PyUnicodeUCS4_IsAlpha
-# define _PyUnicode_IsDecimalDigit _PyUnicodeUCS4_IsDecimalDigit
-# define _PyUnicode_IsDigit _PyUnicodeUCS4_IsDigit
-# define _PyUnicode_IsLinebreak _PyUnicodeUCS4_IsLinebreak
-# define _PyUnicode_IsLowercase _PyUnicodeUCS4_IsLowercase
-# define _PyUnicode_IsNumeric _PyUnicodeUCS4_IsNumeric
-# define _PyUnicode_IsPrintable _PyUnicodeUCS4_IsPrintable
-# define _PyUnicode_IsTitlecase _PyUnicodeUCS4_IsTitlecase
-# define _PyUnicode_IsXidStart _PyUnicodeUCS4_IsXidStart
-# define _PyUnicode_IsXidContinue _PyUnicodeUCS4_IsXidContinue
-# define _PyUnicode_IsUppercase _PyUnicodeUCS4_IsUppercase
-# define _PyUnicode_IsWhitespace _PyUnicodeUCS4_IsWhitespace
-# define _PyUnicode_ToDecimalDigit _PyUnicodeUCS4_ToDecimalDigit
-# define _PyUnicode_ToDigit _PyUnicodeUCS4_ToDigit
-# define _PyUnicode_ToLowercase _PyUnicodeUCS4_ToLowercase
-# define _PyUnicode_ToNumeric _PyUnicodeUCS4_ToNumeric
-# define _PyUnicode_ToTitlecase _PyUnicodeUCS4_ToTitlecase
-# define _PyUnicode_ToUppercase _PyUnicodeUCS4_ToUppercase
 
 
 #endif
@@ -349,7 +315,7 @@
    configure Python using --with-wctype-functions.  This reduces the
    interpreter's code size. */
 
-#if defined(HAVE_USABLE_WCHAR_T) && defined(WANT_WCTYPE_FUNCTIONS)
+#if defined(Py_UNICODE_WIDE) && defined(HAVE_USABLE_WCHAR_T) && defined(WANT_WCTYPE_FUNCTIONS)
 
 #include <wctype.h>
 
@@ -1239,12 +1205,16 @@
 
 /* --- File system encoding ---------------------------------------------- */
 
-/* ParseTuple converter which converts a Unicode object into the file
-   system encoding as a bytes object, using the "surrogateescape" error
-   handler; bytes objects are output as-is. */
+/* ParseTuple converter: encode str objects to bytes using
+   PyUnicode_EncodeFSDefault(); bytes objects are output as-is. */
 
 PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*);
 
+/* ParseTuple converter: decode bytes objects to unicode using
+   PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. */
+
+PyAPI_FUNC(int) PyUnicode_FSDecoder(PyObject*, void*);
+
 /* Decode a null-terminated string using Py_FileSystemDefaultEncoding
    and the "surrogateescape" error handler.
 
@@ -1536,90 +1506,109 @@
 */
 
 PyAPI_FUNC(int) _PyUnicode_IsLowercase(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsUppercase(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsTitlecase(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsXidStart(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsXidContinue(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsWhitespace(
-    const Py_UNICODE ch         /* Unicode character */
+    const Py_UCS4 ch         /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsLinebreak(
-    const Py_UNICODE ch         /* Unicode character */
+    const Py_UCS4 ch         /* Unicode character */
     );
 
-PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToLowercase(
-    Py_UNICODE ch       /* Unicode character */
+PyAPI_FUNC(Py_UCS4) _PyUnicode_ToLowercase(
+    Py_UCS4 ch       /* Unicode character */
     );
 
-PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToUppercase(
-    Py_UNICODE ch       /* Unicode character */
+PyAPI_FUNC(Py_UCS4) _PyUnicode_ToUppercase(
+    Py_UCS4 ch       /* Unicode character */
     );
 
-PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToTitlecase(
-    Py_UNICODE ch       /* Unicode character */
+PyAPI_FUNC(Py_UCS4) _PyUnicode_ToTitlecase(
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_ToDigit(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(double) _PyUnicode_ToNumeric(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsDigit(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsNumeric(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsPrintable(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
 PyAPI_FUNC(int) _PyUnicode_IsAlpha(
-    Py_UNICODE ch       /* Unicode character */
+    Py_UCS4 ch       /* Unicode character */
     );
 
-PyAPI_FUNC(size_t) Py_UNICODE_strlen(const Py_UNICODE *u);
+PyAPI_FUNC(size_t) Py_UNICODE_strlen(
+    const Py_UNICODE *u
+    );
 
 PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strcpy(
-    Py_UNICODE *s1, const Py_UNICODE *s2);
+    Py_UNICODE *s1,
+    const Py_UNICODE *s2);
 
 PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strncpy(
-    Py_UNICODE *s1, const Py_UNICODE *s2, size_t n);
+    Py_UNICODE *s1,
+    const Py_UNICODE *s2,
+    size_t n);
 
 PyAPI_FUNC(int) Py_UNICODE_strcmp(
-    const Py_UNICODE *s1, const Py_UNICODE *s2);
+    const Py_UNICODE *s1,
+    const Py_UNICODE *s2
+    );
+
+PyAPI_FUNC(int) Py_UNICODE_strncmp(
+    const Py_UNICODE *s1,
+    const Py_UNICODE *s2,
+    size_t n
+    );
 
 PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strchr(
-    const Py_UNICODE *s, Py_UNICODE c
+    const Py_UNICODE *s,
+    Py_UNICODE c
+    );
+
+PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strrchr(
+    const Py_UNICODE *s,
+    Py_UNICODE c
     );
 
 #ifdef __cplusplus

Modified: python/branches/pep-0384/Include/warnings.h
==============================================================================
--- python/branches/pep-0384/Include/warnings.h	(original)
+++ python/branches/pep-0384/Include/warnings.h	Fri Aug 27 21:11:11 2010
@@ -7,6 +7,7 @@
 PyAPI_FUNC(PyObject*) _PyWarnings_Init(void);
 
 PyAPI_FUNC(int) PyErr_WarnEx(PyObject *, const char *, Py_ssize_t);
+PyAPI_FUNC(int) PyErr_WarnFormat(PyObject *, Py_ssize_t, const char *, ...);
 PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, const char *, int,
                                     const char *, PyObject *);
 

Modified: python/branches/pep-0384/LICENSE
==============================================================================
--- python/branches/pep-0384/LICENSE	(original)
+++ python/branches/pep-0384/LICENSE	Fri Aug 27 21:11:11 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/pep-0384/Lib/_abcoll.py
==============================================================================
--- python/branches/pep-0384/Lib/_abcoll.py	(original)
+++ python/branches/pep-0384/Lib/_abcoll.py	Fri Aug 27 21:11:11 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",
            ]
 
 
@@ -326,18 +321,24 @@
         return self
 
     def __ixor__(self, it: Iterable):
-        if not isinstance(it, Set):
-            it = self._from_iterable(it)
-        for value in it:
-            if value in self:
-                self.discard(value)
-            else:
-                self.add(value)
+        if it is self:
+            self.clear()
+        else:
+            if not isinstance(it, Set):
+                it = self._from_iterable(it)
+            for value in it:
+                if value in self:
+                    self.discard(value)
+                else:
+                    self.add(value)
         return self
 
     def __isub__(self, it: Iterable):
-        for value in it:
-            self.discard(value)
+        if it is self:
+            self.clear()
+        else:
+            for value in it:
+                self.discard(value)
         return self
 
 MutableSet.register(set)
@@ -398,6 +399,10 @@
 
 class KeysView(MappingView, Set):
 
+    @classmethod
+    def _from_iterable(self, it):
+        return set(it)
+
     def __contains__(self, key):
         return key in self._mapping
 
@@ -410,6 +415,10 @@
 
 class ItemsView(MappingView, Set):
 
+    @classmethod
+    def _from_iterable(self, it):
+        return set(it)
+
     def __contains__(self, item):
         key, value = item
         try:

Modified: python/branches/pep-0384/Lib/abc.py
==============================================================================
--- python/branches/pep-0384/Lib/abc.py	(original)
+++ python/branches/pep-0384/Lib/abc.py	Fri Aug 27 21:11:11 2010
@@ -25,6 +25,46 @@
     return funcobj
 
 
+class abstractclassmethod(classmethod):
+    """A decorator indicating abstract classmethods.
+
+    Similar to abstractmethod.
+
+    Usage:
+
+        class C(metaclass=ABCMeta):
+            @abstractclassmethod
+            def my_abstract_classmethod(cls, ...):
+                ...
+    """
+
+    __isabstractmethod__ = True
+
+    def __init__(self, callable):
+        callable.__isabstractmethod__ = True
+        super().__init__(callable)
+
+
+class abstractstaticmethod(staticmethod):
+    """A decorator indicating abstract staticmethods.
+
+    Similar to abstractmethod.
+
+    Usage:
+
+        class C(metaclass=ABCMeta):
+            @abstractstaticmethod
+            def my_abstract_staticmethod(...):
+                ...
+    """
+
+    __isabstractmethod__ = True
+
+    def __init__(self, callable):
+        callable.__isabstractmethod__ = True
+        super().__init__(callable)
+
+
 class abstractproperty(property):
     """A decorator indicating abstract properties.
 

Modified: python/branches/pep-0384/Lib/argparse.py
==============================================================================
--- python/branches/pep-0384/Lib/argparse.py	(original)
+++ python/branches/pep-0384/Lib/argparse.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/asyncore.py
==============================================================================
--- python/branches/pep-0384/Lib/asyncore.py	(original)
+++ python/branches/pep-0384/Lib/asyncore.py	Fri Aug 27 21:11:11 2010
@@ -53,7 +53,7 @@
 import warnings
 
 import os
-from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
+from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, \
      ENOTCONN, ESHUTDOWN, EINTR, EISCONN, EBADF, ECONNABORTED, errorcode
 
 try:
@@ -337,8 +337,8 @@
     def connect(self, address):
         self.connected = False
         err = self.socket.connect_ex(address)
-        # XXX Should interpret Winsock return values
-        if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
+        if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \
+        or err == EINVAL and os.name in ('nt', 'ce'):
             return
         if err in (0, EISCONN):
             self.addr = address
@@ -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/pep-0384/Lib/base64.py
==============================================================================
--- python/branches/pep-0384/Lib/base64.py	(original)
+++ python/branches/pep-0384/Lib/base64.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/bdb.py
==============================================================================
--- python/branches/pep-0384/Lib/bdb.py	(original)
+++ python/branches/pep-0384/Lib/bdb.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/cProfile.py
==============================================================================
--- python/branches/pep-0384/Lib/cProfile.py	(original)
+++ python/branches/pep-0384/Lib/cProfile.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/cgi.py
==============================================================================
--- python/branches/pep-0384/Lib/cgi.py	(original)
+++ python/branches/pep-0384/Lib/cgi.py	Fri Aug 27 21:11:11 2010
@@ -114,7 +114,7 @@
         environ         : environment dictionary; default: os.environ
 
         keep_blank_values: flag indicating whether blank values in
-            URL encoded forms should be treated as blank strings.
+            percent-encoded forms should be treated as blank strings.
             A true value indicates that blanks should be retained as
             blank strings.  The default false value indicates that
             blank values are to be ignored and treated as if they were
@@ -394,7 +394,7 @@
         environ         : environment dictionary; default: os.environ
 
         keep_blank_values: flag indicating whether blank values in
-            URL encoded forms should be treated as blank strings.
+            percent-encoded forms should be treated as blank strings.
             A true value indicates that blanks should be retained as
             blank strings.  The default false value indicates that
             blank values are to be ignored and treated as if they were

Modified: python/branches/pep-0384/Lib/cmd.py
==============================================================================
--- python/branches/pep-0384/Lib/cmd.py	(original)
+++ python/branches/pep-0384/Lib/cmd.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/collections.py
==============================================================================
--- python/branches/pep-0384/Lib/collections.py	(original)
+++ python/branches/pep-0384/Lib/collections.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/configparser.py
==============================================================================
--- python/branches/pep-0384/Lib/configparser.py	(original)
+++ python/branches/pep-0384/Lib/configparser.py	Fri Aug 27 21:11:11 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,101 @@
 
     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=('#', ';'),
+             strict=False, 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 `strict` is True, the parser won't allow for any section or option
+        duplicates while reading from a single source (file, string or
+        dictionary). Default is False.
+
+        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.
-        The filename defaults to fp.name; it is only used in error
-        messages (if fp has no `name' attribute, the string `<???>' is used).
+    read_file(f, filename=None)
+        Read and parse one configuration file, given as a file object.
+        The filename defaults to f.name; it is only used in error
+        messages (if f has no `name' attribute, the string `<???>' is used).
+
+    read_string(string)
+        Read configuration from a given string.
+
+    read_dict(dictionary)
+        Read configuration from a dictionary. Keys are section names,
+        values are dictionaries with keys and values that should be present
+        in the section. If the used dictionary type preserves order, sections
+        and their keys will be added in order.
 
     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:
@@ -93,10 +127,13 @@
     # fallback for setup.py which hasn't yet built _collections
     _default_dict = dict
 
+import io
 import re
+import sys
+import warnings
 
-__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
-           "InterpolationError", "InterpolationDepthError",
+__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
+           "NoOptionError", "InterpolationError", "InterpolationDepthError",
            "InterpolationSyntaxError", "ParsingError",
            "MissingSectionHeaderError",
            "ConfigParser", "SafeConfigParser", "RawConfigParser",
@@ -114,12 +151,14 @@
 
     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
@@ -136,19 +175,68 @@
 
     __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."""
+    """Raised when a section is repeated in an input source.
 
-    def __init__(self, section):
-        Error.__init__(self, "Section %r already exists" % section)
+    Possible repetitions that raise this exception are: multiple creation
+    using the API or in strict parsers when a section is found more than once
+    in a single input file, string or dictionary.
+    """
+
+    def __init__(self, section, source=None, lineno=None):
+        msg = [repr(section), " already exists"]
+        if source is not None:
+            message = ["While reading from ", source]
+            if lineno is not None:
+                message.append(" [line {0:2d}]".format(lineno))
+            message.append(": section ")
+            message.extend(msg)
+            msg = message
+        else:
+            msg.insert(0, "Section ")
+        Error.__init__(self, "".join(msg))
+        self.section = section
+        self.source = source
+        self.lineno = lineno
+        self.args = (section, source, lineno)
+
+
+class DuplicateOptionError(Error):
+    """Raised by strict parsers when an option is repeated in an input source.
+
+    Current implementation raises this exception only when an option is found
+    more than once in a single file, string or dictionary.
+    """
+
+    def __init__(self, section, option, source=None, lineno=None):
+        msg = [repr(option), " in section ", repr(section),
+               " already exists"]
+        if source is not None:
+            message = ["While reading from ", source]
+            if lineno is not None:
+                message.append(" [line {0:2d}]".format(lineno))
+            message.append(": option ")
+            message.extend(msg)
+            msg = message
+        else:
+            msg.insert(0, "Option ")
+        Error.__init__(self, "".join(msg))
         self.section = section
+        self.option = option
+        self.source = source
+        self.lineno = lineno
+        self.args = (section, option, source, lineno)
+
 
 class NoOptionError(Error):
     """A requested option was not found."""
@@ -158,6 +246,8 @@
                        (option, section))
         self.option = option
         self.section = section
+        self.args = (option, section)
+
 
 class InterpolationError(Error):
     """Base class for interpolation-related exceptions."""
@@ -166,6 +256,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,10 +271,17 @@
                % (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."""
+    """Raised when the source text contains invalid syntax.
+
+    Current implementation raises this exception only for SafeConfigParser
+    instances 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,19 +293,52 @@
                "\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."""
 
-    def __init__(self, filename):
-        Error.__init__(self, 'File contains parsing errors: %s' % filename)
-        self.filename = filename
+    def __init__(self, source=None, filename=None):
+        # Exactly one of `source'/`filename' arguments has to be given.
+        # `filename' kept for compatibility.
+        if filename and source:
+            raise ValueError("Cannot specify both `filename' and `source'. "
+                             "Use `source'.")
+        elif not filename and not source:
+            raise ValueError("Required argument `source' not given.")
+        elif filename:
+            source = filename
+        Error.__init__(self, 'Source contains parsing errors: %s' % source)
+        self.source = source
         self.errors = []
+        self.args = (source, )
+
+    @property
+    def filename(self):
+        """Deprecated, use `source'."""
+        warnings.warn(
+            "This 'filename' attribute will be removed in future versions.  "
+            "Use 'source' instead.",
+            PendingDeprecationWarning, stacklevel=2
+        )
+        return self.source
+
+    @filename.setter
+    def filename(self, value):
+        """Deprecated, user `source'."""
+        warnings.warn(
+            "The 'filename' attribute will be removed in future versions.  "
+            "Use 'source' instead.",
+            PendingDeprecationWarning, stacklevel=2
+        )
+        self.source = value
 
     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."""
 
@@ -215,24 +347,81 @@
             self,
             'File contains no section headers.\nfile: %s, line: %d\n%r' %
             (filename, lineno, line))
-        self.filename = filename
+        self.source = 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):
+                 allow_no_value=False, *, delimiters=('=', ':'),
+                 comment_prefixes=_COMPATIBLE, strict=False,
+                 empty_lines_in_values=True):
         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:
+            d = "|".join(re.escape(d) for d in delimiters)
+            if allow_no_value:
+                self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
+                                          re.VERBOSE)
+            else:
+                self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
+                                          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._strict = strict
+        self._empty_lines_in_values = empty_lines_in_values
 
     def defaults(self):
         return self._defaults
@@ -274,7 +463,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 +480,7 @@
         read_ok = []
         for filename in filenames:
             try:
-                fp = open(filename)
+                fp = open(filename, encoding=encoding)
             except IOError:
                 continue
             self._read(fp, filename)
@@ -299,21 +488,59 @@
             read_ok.append(filename)
         return read_ok
 
-    def readfp(self, fp, filename=None):
+    def read_file(self, f, source=None):
         """Like read() but the argument must be a file-like object.
 
-        The `fp' argument must have a `readline' method.  Optional
-        second argument is the `filename', which if not given, is
-        taken from fp.name.  If fp has no `name' attribute, `<???>' is
-        used.
-
+        The `f' argument must have a `readline' method.  Optional second
+        argument is the `source' specifying the name of the file being read. If
+        not given, it is taken from f.name. If `f' has no `name' attribute,
+        `<???>' is used.
         """
-        if filename is None:
+        if source is None:
             try:
-                filename = fp.name
+                srouce = f.name
             except AttributeError:
-                filename = '<???>'
-        self._read(fp, filename)
+                source = '<???>'
+        self._read(f, source)
+
+    def read_string(self, string, source='<string>'):
+        """Read configuration from a given string."""
+        sfile = io.StringIO(string)
+        self.read_file(sfile, source)
+
+    def read_dict(self, dictionary, source='<dict>'):
+        """Read configuration from a dictionary.
+
+        Keys are section names, values are dictionaries with keys and values
+        that should be present in the section. If the used dictionary type
+        preserves order, sections and their keys will be added in order.
+
+        Optional second argument is the `source' specifying the name of the
+        dictionary being read.
+        """
+        elements_added = set()
+        for section, keys in dictionary.items():
+            try:
+                self.add_section(section)
+            except DuplicateSectionError:
+                if self._strict and section in elements_added:
+                    raise
+                elements_added.add(section)
+            for key, value in keys.items():
+                key = self.optionxform(key)
+                if self._strict and (section, key) in elements_added:
+                    raise DuplicateOptionError(section, key, source)
+                elements_added.add((section, key))
+                self.set(section, key, value)
+
+    def readfp(self, fp, filename=None):
+        """Deprecated, use read_file instead."""
+        warnings.warn(
+            "This method will be removed in future versions.  "
+            "Use 'parser.read_file()' instead.",
+            PendingDeprecationWarning, stacklevel=2
+        )
+        self.read_file(fp, source=filename)
 
     def get(self, section, option):
         opt = self.optionxform(option)
@@ -388,23 +615,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,76 +666,83 @@
             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
+        elements_added = set()
+        cursect = None                        # None, or a dictionary
+        sectname = None
         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:
+                        if self._strict and sectname in elements_added:
+                            raise DuplicateSectionError(sectname, fpname,
+                                                        lineno)
                         cursect = self._sections[sectname]
+                        elements_added.add(sectname)
                     elif sectname == DEFAULTSECT:
                         cursect = self._defaults
                     else:
                         cursect = self._dict()
                         cursect['__name__'] = sectname
                         self._sections[sectname] = cursect
+                        elements_added.add(sectname)
                     # So sections can't start with a continuation line
                     optname = None
                 # no section header in the file?
@@ -505,47 +750,66 @@
                     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())
+                        if (self._strict and
+                            (sectname, optname) in elements_added):
+                            raise DuplicateOptionError(sectname, optname,
+                                                       fpname, lineno)
+                        elements_added.add((sectname, optname))
                         # 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.
         """
@@ -571,8 +835,7 @@
             return self._interpolate(section, option, value, d)
 
     def items(self, section, raw=False, vars=None):
-        """Return a list of tuples with (name, value) for each option
-        in the section.
+        """Return a list of (name, value) tuples for each option in a section.
 
         All % interpolations are expanded in the return values, based on the
         defaults passed into the constructor, unless the optional argument
@@ -632,6 +895,7 @@
 
 
 class SafeConfigParser(ConfigParser):
+    """ConfigParser implementing sane interpolation."""
 
     def _interpolate(self, section, option, rawval, vars):
         # do the string interpolation
@@ -677,7 +941,8 @@
             else:
                 raise InterpolationSyntaxError(
                     option, section,
-                    "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
+                    "'%%' must be followed by '%%' or '(', "
+                    "found: %r" % (rest,))
 
     def set(self, section, option, value=None):
         """Set an option.  Extend ConfigParser.set: check for string values."""
@@ -689,13 +954,11 @@
         if self._optcre is self.OPTCRE or value:
             if not isinstance(value, str):
                 raise TypeError("option values must be strings")
-        # check for bad percent signs:
-        # first, replace all "good" interpolations
-        tmp_value = value.replace('%%', '')
-        tmp_value = self._interpvar_re.sub('', tmp_value)
-        # then, check if there's a lone percent sign left
-        percent_index = tmp_value.find('%')
-        if percent_index != -1:
-            raise ValueError("invalid interpolation syntax in %r at "
-                             "position %d" % (value, percent_index))
+        # check for bad percent signs
+        if value:
+            tmp_value = value.replace('%%', '') # escaped percent signs
+            tmp_value = self._interpvar_re.sub('', tmp_value) # valid syntax
+            if '%' in tmp_value:
+                raise ValueError("invalid interpolation syntax in %r at "
+                                "position %d" % (value, tmp_value.find('%')))
         ConfigParser.set(self, section, option, value)

Modified: python/branches/pep-0384/Lib/ctypes/__init__.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/__init__.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/__init__.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_arrays.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_arrays.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_arrays.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_bitfields.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_bitfields.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_bitfields.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_buffers.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_buffers.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_buffers.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_bytes.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_bytes.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_bytes.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_callbacks.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_callbacks.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_callbacks.py	Fri Aug 27 21:11:11 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
@@ -199,7 +199,6 @@
                 return True #Allow windows to keep enumerating
 
             windll.user32.EnumWindows(EnumWindowsCallbackFunc, 0)
-            self.assertFalse(windowCount == 0)
 
 ################################################################
 

Modified: python/branches/pep-0384/Lib/ctypes/test/test_cast.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_cast.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_cast.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_cfuncs.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_cfuncs.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_cfuncs.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_errno.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_errno.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_errno.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_internals.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_internals.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_internals.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_keeprefs.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_keeprefs.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_keeprefs.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_libc.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_libc.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_libc.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_loading.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_loading.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_loading.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_objects.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_objects.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_objects.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_parameters.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_parameters.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_parameters.py	Fri Aug 27 21:11:11 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,31 +57,31 @@
         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):
-        from ctypes import byref
+        from ctypes import byref, sizeof
         try:
-            from ctypes import c_wchar_p
+            from ctypes import c_wchar, c_wchar_p
         except ImportError:
 ##            print "(No c_wchar_p)"
             return
         s = "123"
         if sys.platform == "win32":
-            self.assertTrue(c_wchar_p.from_param(s)._obj is s)
+            unisize = 8 if sys.maxunicode == 1114111 else 4
+            if unisize == sizeof(c_wchar):
+                self.assertIs(c_wchar_p.from_param(s)._obj, s)
+                # new in 0.9.1: convert (decode) ascii to unicode
+                self.assertEqual(c_wchar_p.from_param("123")._obj, "123")
             self.assertRaises(TypeError, c_wchar_p.from_param, 42)
-
-            # 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/pep-0384/Lib/ctypes/test/test_prototypes.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_prototypes.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_prototypes.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_python_api.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_python_api.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_python_api.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_random_things.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_random_things.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_random_things.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_repr.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_repr.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_repr.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_returnfuncptrs.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_returnfuncptrs.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_returnfuncptrs.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_stringptr.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_stringptr.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_stringptr.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_strings.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_strings.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_strings.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_structures.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_structures.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_structures.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ctypes/test/test_unicode.py
==============================================================================
--- python/branches/pep-0384/Lib/ctypes/test/test_unicode.py	(original)
+++ python/branches/pep-0384/Lib/ctypes/test/test_unicode.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/curses/wrapper.py
==============================================================================
--- python/branches/pep-0384/Lib/curses/wrapper.py	(original)
+++ python/branches/pep-0384/Lib/curses/wrapper.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/dbm/__init__.py
==============================================================================
--- python/branches/pep-0384/Lib/dbm/__init__.py	(original)
+++ python/branches/pep-0384/Lib/dbm/__init__.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/dis.py
==============================================================================
--- python/branches/pep-0384/Lib/dis.py	(original)
+++ python/branches/pep-0384/Lib/dis.py	Fri Aug 27 21:11:11 2010
@@ -19,9 +19,6 @@
        Utility function to accept strings in functions that otherwise
        expect code objects
     """
-    # ncoghlan: currently only used by dis(), but plan to add an
-    # equivalent for show_code() as well (but one that returns a
-    # string rather than printing directly to the console)
     try:
         c = compile(source, name, 'eval')
     except SyntaxError:
@@ -37,11 +34,11 @@
     if x is None:
         distb()
         return
-    if hasattr(x, '__func__'):
+    if hasattr(x, '__func__'):  # Method
         x = x.__func__
-    if hasattr(x, '__code__'):
+    if hasattr(x, '__code__'):  # Function
         x = x.__code__
-    if hasattr(x, '__dict__'):
+    if hasattr(x, '__dict__'):  # Class or module
         items = sorted(x.__dict__.items())
         for name, x1 in items:
             if isinstance(x1, _have_code):
@@ -51,11 +48,11 @@
                 except TypeError as msg:
                     print("Sorry:", msg)
                 print()
-    elif hasattr(x, 'co_code'):
+    elif hasattr(x, 'co_code'): # Code object
         disassemble(x)
-    elif isinstance(x, (bytes, bytearray)):
+    elif isinstance(x, (bytes, bytearray)): # Raw bytecode
         _disassemble_bytes(x)
-    elif isinstance(x, str):
+    elif isinstance(x, str):    # Source code
         _disassemble_str(x)
     else:
         raise TypeError("don't know how to disassemble %s objects" %
@@ -71,9 +68,10 @@
         while tb.tb_next: tb = tb.tb_next
     disassemble(tb.tb_frame.f_code, tb.tb_lasti)
 
-# XXX This duplicates information from code.h, also duplicated in inspect.py.
-# XXX Maybe this ought to be put in a central location, like opcode.py?
-flag2name = {
+# The inspect module interrogates this dictionary to build its
+# list of CO_* constants. It is also used by pretty_flags to
+# turn the co_flags field into a human readable list.
+COMPILER_FLAG_NAMES = {
      1: "OPTIMIZED",
      2: "NEWLOCALS",
      4: "VARARGS",
@@ -89,7 +87,7 @@
     for i in range(32):
         flag = 1<<i
         if flags & flag:
-            names.append(flag2name.get(flag, hex(flag)))
+            names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
             flags ^= flag
             if not flags:
                 break
@@ -97,35 +95,54 @@
         names.append(hex(flags))
     return ", ".join(names)
 
-def show_code(co):
-    """Show details about a code object."""
-    print("Name:             ", co.co_name)
-    print("Filename:         ", co.co_filename)
-    print("Argument count:   ", co.co_argcount)
-    print("Kw-only arguments:", co.co_kwonlyargcount)
-    print("Number of locals: ", co.co_nlocals)
-    print("Stack size:       ", co.co_stacksize)
-    print("Flags:            ", pretty_flags(co.co_flags))
+def code_info(x):
+    """Formatted details of methods, functions, or code."""
+    if hasattr(x, '__func__'): # Method
+        x = x.__func__
+    if hasattr(x, '__code__'): # Function
+        x = x.__code__
+    if isinstance(x, str):     # Source code
+        x = _try_compile(x, "<code_info>")
+    if hasattr(x, 'co_code'):  # Code object
+        return _format_code_info(x)
+    else:
+        raise TypeError("don't know how to disassemble %s objects" %
+                        type(x).__name__)
+
+def _format_code_info(co):
+    lines = []
+    lines.append("Name:              %s" % co.co_name)
+    lines.append("Filename:          %s" % co.co_filename)
+    lines.append("Argument count:    %s" % co.co_argcount)
+    lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
+    lines.append("Number of locals:  %s" % co.co_nlocals)
+    lines.append("Stack size:        %s" % co.co_stacksize)
+    lines.append("Flags:             %s" % pretty_flags(co.co_flags))
     if co.co_consts:
-        print("Constants:")
+        lines.append("Constants:")
         for i_c in enumerate(co.co_consts):
-            print("%4d: %r" % i_c)
+            lines.append("%4d: %r" % i_c)
     if co.co_names:
-        print("Names:")
+        lines.append("Names:")
         for i_n in enumerate(co.co_names):
-            print("%4d: %s" % i_n)
+            lines.append("%4d: %s" % i_n)
     if co.co_varnames:
-        print("Variable names:")
+        lines.append("Variable names:")
         for i_n in enumerate(co.co_varnames):
-            print("%4d: %s" % i_n)
+            lines.append("%4d: %s" % i_n)
     if co.co_freevars:
-        print("Free variables:")
+        lines.append("Free variables:")
         for i_n in enumerate(co.co_freevars):
-            print("%4d: %s" % i_n)
+            lines.append("%4d: %s" % i_n)
     if co.co_cellvars:
-        print("Cell variables:")
+        lines.append("Cell variables:")
         for i_n in enumerate(co.co_cellvars):
-            print("%4d: %s" % i_n)
+            lines.append("%4d: %s" % i_n)
+    return "\n".join(lines)
+
+def show_code(co):
+    """Show details about a code object."""
+    print(code_info(co))
 
 def disassemble(co, lasti=-1):
     """Disassemble a code object."""

Modified: python/branches/pep-0384/Lib/distutils/__init__.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/__init__.py	(original)
+++ python/branches/pep-0384/Lib/distutils/__init__.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/distutils/command/bdist_msi.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/command/bdist_msi.py	(original)
+++ python/branches/pep-0384/Lib/distutils/command/bdist_msi.py	Fri Aug 27 21:11:11 2010
@@ -148,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)

Modified: python/branches/pep-0384/Lib/distutils/command/bdist_wininst.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/command/bdist_wininst.py	(original)
+++ python/branches/pep-0384/Lib/distutils/command/bdist_wininst.py	Fri Aug 27 21:11:11 2010
@@ -89,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/pep-0384/Lib/distutils/command/sdist.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/command/sdist.py	(original)
+++ python/branches/pep-0384/Lib/distutils/command/sdist.py	Fri Aug 27 21:11:11 2010
@@ -240,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
@@ -336,8 +335,21 @@
         by 'add_defaults()' and 'read_template()') to the manifest file
         named by 'self.manifest'.
         """
-        self.execute(file_util.write_file,
-                     (self.manifest, self.filelist.files),
+        if os.path.isfile(self.manifest):
+            fp = open(self.manifest)
+            try:
+                first_line = fp.readline()
+            finally:
+                fp.close()
+
+            if first_line != '# file GENERATED by distutils, do NOT edit\n':
+                log.info("not writing to manually maintained "
+                         "manifest file '%s'" % self.manifest)
+                return
+
+        content = self.filelist.files[:]
+        content.insert(0, '# file GENERATED by distutils, do NOT edit')
+        self.execute(file_util.write_file, (self.manifest, content),
                      "writing manifest file '%s'" % self.manifest)
 
     def read_manifest(self):

Modified: python/branches/pep-0384/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/sysconfig.py	(original)
+++ python/branches/pep-0384/Lib/distutils/sysconfig.py	Fri Aug 27 21:11:11 2010
@@ -300,6 +300,12 @@
                 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):
@@ -316,6 +322,16 @@
                 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:
@@ -330,6 +346,13 @@
                         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]

Modified: python/branches/pep-0384/Lib/distutils/tests/test_sdist.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/tests/test_sdist.py	(original)
+++ python/branches/pep-0384/Lib/distutils/tests/test_sdist.py	Fri Aug 27 21:11:11 2010
@@ -29,6 +29,7 @@
 """
 
 MANIFEST = """\
+# file GENERATED by distutils, do NOT edit
 README
 inroot.txt
 setup.py
@@ -294,7 +295,7 @@
         finally:
             f.close()
 
-        self.assertEquals(len(manifest), 4)
+        self.assertEquals(len(manifest), 5)
 
         # adding a file
         self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
@@ -314,9 +315,40 @@
             f.close()
 
         # do we have the new file in MANIFEST ?
-        self.assertEquals(len(manifest2), 5)
+        self.assertEquals(len(manifest2), 6)
         self.assertIn('doc2.txt', manifest2[-1])
 
+    def test_manifest_marker(self):
+        # check that autogenerated MANIFESTs have a marker
+        dist, cmd = self.get_cmd()
+        cmd.ensure_finalized()
+        cmd.run()
+
+        f = open(cmd.manifest)
+        try:
+            manifest = [line.strip() for line in f.read().split('\n')
+                        if line.strip() != '']
+        finally:
+            f.close()
+
+        self.assertEqual(manifest[0],
+                         '# file GENERATED by distutils, do NOT edit')
+
+    def test_manual_manifest(self):
+        # check that a MANIFEST without a marker is left alone
+        dist, cmd = self.get_cmd()
+        cmd.ensure_finalized()
+        self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
+        cmd.run()
+
+        f = open(cmd.manifest)
+        try:
+            manifest = [line.strip() for line in f.read().split('\n')
+                        if line.strip() != '']
+        finally:
+            f.close()
+
+        self.assertEqual(manifest, ['README.manual'])
 
 def test_suite():
     return unittest.makeSuite(SDistTestCase)

Modified: python/branches/pep-0384/Lib/distutils/tests/test_sysconfig.py
==============================================================================
--- python/branches/pep-0384/Lib/distutils/tests/test_sysconfig.py	(original)
+++ python/branches/pep-0384/Lib/distutils/tests/test_sysconfig.py	Fri Aug 27 21:11:11 2010
@@ -93,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/pep-0384/Lib/doctest.py
==============================================================================
--- python/branches/pep-0384/Lib/doctest.py	(original)
+++ python/branches/pep-0384/Lib/doctest.py	Fri Aug 27 21:11:11 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
@@ -1779,7 +1786,7 @@
 
     Return (#failures, #tests).
 
-    See doctest.__doc__ for an overview.
+    See help(doctest) for an overview.
 
     Optional keyword arg "name" gives the name of the module; by default
     use m.__name__.

Modified: python/branches/pep-0384/Lib/email/_parseaddr.py
==============================================================================
--- python/branches/pep-0384/Lib/email/_parseaddr.py	(original)
+++ python/branches/pep-0384/Lib/email/_parseaddr.py	Fri Aug 27 21:11:11 2010
@@ -107,6 +107,18 @@
         tss = int(tss)
     except ValueError:
         return None
+    # Check for a yy specified in two-digit format, then convert it to the
+    # appropriate four-digit format, according to the POSIX standard. RFC 822
+    # calls for a two-digit yy, but RFC 2822 (which obsoletes RFC 822)
+    # mandates a 4-digit yy. For more information, see the documentation for
+    # the time module.
+    if yy < 100:
+        # The year is between 1969 and 1999 (inclusive).
+        if yy > 68:
+            yy += 1900
+        # The year is between 2000 and 2068 (inclusive).
+        else:
+            yy += 2000
     tzoffset = None
     tz = tz.upper()
     if tz in _timezones:

Modified: python/branches/pep-0384/Lib/email/base64mime.py
==============================================================================
--- python/branches/pep-0384/Lib/email/base64mime.py	(original)
+++ python/branches/pep-0384/Lib/email/base64mime.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/email/header.py
==============================================================================
--- python/branches/pep-0384/Lib/email/header.py	(original)
+++ python/branches/pep-0384/Lib/email/header.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/email/message.py
==============================================================================
--- python/branches/pep-0384/Lib/email/message.py	(original)
+++ python/branches/pep-0384/Lib/email/message.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/email/test/test_email.py
==============================================================================
--- python/branches/pep-0384/Lib/email/test/test_email.py	(original)
+++ python/branches/pep-0384/Lib/email/test/test_email.py	Fri Aug 27 21:11:11 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
@@ -2225,6 +2234,19 @@
         eq(time.localtime(t)[:6], timetup[:6])
         eq(int(time.strftime('%Y', timetup[:9])), 2003)
 
+    def test_parsedate_y2k(self):
+        """Test for parsing a date with a two-digit year.
+
+        Parsing a date with a two-digit year should return the correct
+        four-digit year. RFC822 allows two-digit years, but RFC2822 (which
+        obsoletes RFC822) requires four-digit years.
+
+        """
+        self.assertEqual(utils.parsedate_tz('25 Feb 03 13:47:26 -0800'),
+                         utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'))
+        self.assertEqual(utils.parsedate_tz('25 Feb 71 13:47:26 -0800'),
+                         utils.parsedate_tz('25 Feb 1971 13:47:26 -0800'))
+
     def test_parseaddr_empty(self):
         self.assertEqual(utils.parseaddr('<>'), ('', ''))
         self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '')
@@ -3176,7 +3198,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/pep-0384/Lib/encodings/aliases.py
==============================================================================
--- python/branches/pep-0384/Lib/encodings/aliases.py	(original)
+++ python/branches/pep-0384/Lib/encodings/aliases.py	Fri Aug 27 21:11:11 2010
@@ -435,6 +435,7 @@
     'maclatin2'          : 'mac_latin2',
 
     # mac_roman codec
+    'macintosh'          : 'mac_roman',
     'macroman'           : 'mac_roman',
 
     # mac_turkish codec

Modified: python/branches/pep-0384/Lib/fileinput.py
==============================================================================
--- python/branches/pep-0384/Lib/fileinput.py	(original)
+++ python/branches/pep-0384/Lib/fileinput.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/fnmatch.py
==============================================================================
--- python/branches/pep-0384/Lib/fnmatch.py	(original)
+++ python/branches/pep-0384/Lib/fnmatch.py	Fri Aug 27 21:11:11 2010
@@ -9,19 +9,12 @@
 The function translate(PATTERN) returns a regular expression
 corresponding to PATTERN.  (It does not compile it.)
 """
-
+import os
+import posixpath
 import re
+import functools
 
-__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()
+__all__ = ["filter", "fnmatch", "fnmatchcase", "translate"]
 
 def fnmatch(name, pat):
     """Test whether FILENAME matches PATTERN.
@@ -38,33 +31,25 @@
     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)
-    if regex is None:
-        if isinstance(pat, bytes):
-            pat_str = str(pat, 'ISO-8859-1')
-            res_str = translate(pat_str)
-            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
+ at functools.lru_cache(maxsize=250)
+def _compile_pattern(pat, is_bytes=False):
+    if is_bytes:
+        pat_str = str(pat, 'ISO-8859-1')
+        res_str = translate(pat_str)
+        res = bytes(res_str, 'ISO-8859-1')
+    else:
+        res = translate(pat)
+    return re.compile(res).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)
+    match = _compile_pattern(pat, isinstance(pat, bytes))
     if os.path is posixpath:
         # normcase on posix is NOP. Optimize it away from the loop.
         for name in names:
@@ -82,10 +67,10 @@
     This is a version of fnmatch() which doesn't case-normalize
     its arguments.
     """
-
-    match = _compile_pattern(pat)
+    match = _compile_pattern(pat, isinstance(pat, bytes))
     return match(name) is not None
 
+
 def translate(pat):
     """Translate a shell PATTERN to a regular expression.
 

Modified: python/branches/pep-0384/Lib/ftplib.py
==============================================================================
--- python/branches/pep-0384/Lib/ftplib.py	(original)
+++ python/branches/pep-0384/Lib/ftplib.py	Fri Aug 27 21:11:11 2010
@@ -38,13 +38,7 @@
 
 import os
 import sys
-
-# Import SOCKS module if it exists, else standard socket module socket
-try:
-    import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket
-    from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn
-except ImportError:
-    import socket
+import socket
 from socket import _GLOBAL_DEFAULT_TIMEOUT
 
 __all__ = ["FTP","Netrc"]
@@ -571,7 +565,11 @@
 
     def mkd(self, dirname):
         '''Make a directory, return its full pathname.'''
-        resp = self.sendcmd('MKD ' + dirname)
+        resp = self.voidcmd('MKD ' + dirname)
+        # fix around non-compliant implementations such as IIS shipped
+        # with Windows server 2003
+        if not resp.startswith('257'):
+            return ''
         return parse257(resp)
 
     def rmd(self, dirname):
@@ -580,7 +578,11 @@
 
     def pwd(self):
         '''Return current working directory.'''
-        resp = self.sendcmd('PWD')
+        resp = self.voidcmd('PWD')
+        # fix around non-compliant implementations such as IIS shipped
+        # with Windows server 2003
+        if not resp.startswith('257'):
+            return ''
         return parse257(resp)
 
     def quit(self):

Modified: python/branches/pep-0384/Lib/functools.py
==============================================================================
--- python/branches/pep-0384/Lib/functools.py	(original)
+++ python/branches/pep-0384/Lib/functools.py	Fri Aug 27 21:11:11 2010
@@ -4,15 +4,24 @@
 # 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', 'lru_cache']
+
 from _functools import partial, reduce
+from collections import OrderedDict
+try:
+    from _thread import allocate_lock as Lock
+except:
+    from _dummy_thread import allocate_lock as Lock
 
 # 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,
@@ -29,8 +38,14 @@
        are updated with the corresponding attribute from the wrapped
        function (defaults to functools.WRAPPER_UPDATES)
     """
+    wrapper.__wrapped__ = wrapped
     for attr in assigned:
-        setattr(wrapper, attr, getattr(wrapped, attr))
+        try:
+            value = getattr(wrapped, attr)
+        except AttributeError:
+            pass
+        else:
+            setattr(wrapper, attr, value)
     for attr in updated:
         getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
     # Return the wrapper so this can be used as a decorator via partial()
@@ -50,6 +65,7 @@
     return partial(update_wrapper, wrapped=wrapped,
                    assigned=assigned, updated=updated)
 
+_object_defaults = {object.__lt__, object.__le__, object.__gt__, object.__ge__}
 def total_ordering(cls):
     """Class decorator that fills in missing ordering methods"""
     convert = {
@@ -67,6 +83,8 @@
                    ('__lt__', lambda self, other: not self >= other)]
     }
     roots = set(dir(cls)) & set(convert)
+    # Remove default comparison operations defined on object.
+    roots -= {meth for meth in roots if getattr(cls, meth) in _object_defaults}
     if not roots:
         raise ValueError('must define at least one ordering operation: < > <= >=')
     root = max(roots)       # prefer __lt__ to __le__ to __gt__ to __ge__
@@ -97,3 +115,49 @@
         def __hash__(self):
             raise TypeError('hash not implemented')
     return K
+
+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, tuple=tuple, sorted=sorted,
+                            len=len, KeyError=KeyError):
+        cache = OrderedDict()           # ordered least recent to most recent
+        kwd_mark = object()             # separate positional and keyword args
+        lock = Lock()
+
+        @wraps(user_function)
+        def wrapper(*args, **kwds):
+            key = args
+            if kwds:
+                key += (kwd_mark,) + tuple(sorted(kwds.items()))
+            try:
+                with lock:
+                    result = cache[key]
+                    del cache[key]
+                    cache[key] = result         # record recent use of this key
+                    wrapper.hits += 1
+            except KeyError:
+                result = user_function(*args, **kwds)
+                with lock:
+                    cache[key] = result         # record recent use of this key
+                    wrapper.misses += 1
+                    if len(cache) > maxsize:
+                        cache.popitem(0)        # purge least recently used cache entry
+            return result
+
+        def clear():
+            """Clear the cache and cache statistics"""
+            with lock:
+                cache.clear()
+                wrapper.hits = wrapper.misses = 0
+
+        wrapper.hits = wrapper.misses = 0
+        wrapper.clear = clear
+        return wrapper
+    return decorating_function

Modified: python/branches/pep-0384/Lib/getopt.py
==============================================================================
--- python/branches/pep-0384/Lib/getopt.py	(original)
+++ python/branches/pep-0384/Lib/getopt.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/gzip.py
==============================================================================
--- python/branches/pep-0384/Lib/gzip.py	(original)
+++ python/branches/pep-0384/Lib/gzip.py	Fri Aug 27 21:11:11 2010
@@ -10,7 +10,7 @@
 import builtins
 import io
 
-__all__ = ["GzipFile","open"]
+__all__ = ["GzipFile", "open", "compress", "decompress"]
 
 FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
 
@@ -476,6 +476,23 @@
         return b''.join(bufs) # Return resulting line
 
 
+def compress(data, compresslevel=9):
+    """Compress data in one shot and return the compressed string.
+    Optional argument is the compression level, in range of 1-9.
+    """
+    buf = io.BytesIO()
+    with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f:
+        f.write(data)
+    return buf.getvalue()
+
+def decompress(data):
+    """Decompress a gzip compressed string in one shot.
+    Return the decompressed string.
+    """
+    with GzipFile(fileobj=io.BytesIO(data)) as f:
+        return f.read()
+
+
 def _test():
     # Act like gzip; with -d, act like gunzip.
     # The input file is not deleted, however, nor are any other gzip

Modified: python/branches/pep-0384/Lib/hmac.py
==============================================================================
--- python/branches/pep-0384/Lib/hmac.py	(original)
+++ python/branches/pep-0384/Lib/hmac.py	Fri Aug 27 21:11:11 2010
@@ -12,10 +12,6 @@
 # hashing module used.  Use digest_size from the instance of HMAC instead.
 digest_size = None
 
-# A unique object passed by HMAC.copy() to the HMAC constructor, in order
-# that the latter return very quickly.  HMAC("") in contrast is quite
-# expensive.
-_secret_backdoor_key = []
 
 class HMAC:
     """RFC 2104 HMAC class.  Also complies with RFC 4231.
@@ -36,9 +32,6 @@
         Note: key and msg must be bytes objects.
         """
 
-        if key is _secret_backdoor_key: # cheap
-            return
-
         if not isinstance(key, bytes):
             raise TypeError("expected bytes, but got %r" % type(key).__name__)
 
@@ -58,8 +51,6 @@
         if hasattr(self.inner, 'block_size'):
             blocksize = self.inner.block_size
             if blocksize < 16:
-                # Very low blocksize, most likely a legacy value like
-                # Lib/sha.py and Lib/md5.py have.
                 _warnings.warn('block_size of %d seems too small; using our '
                                'default of %d.' % (blocksize, self.blocksize),
                                RuntimeWarning, 2)
@@ -79,9 +70,6 @@
         if msg is not None:
             self.update(msg)
 
-##    def clear(self):
-##        raise NotImplementedError, "clear() method not available in HMAC."
-
     def update(self, msg):
         """Update this hashing object with the string msg.
         """
@@ -94,7 +82,8 @@
 
         An update to this copy won't affect the original object.
         """
-        other = self.__class__(_secret_backdoor_key)
+        # Call __new__ directly to avoid the expensive __init__.
+        other = self.__class__.__new__(self.__class__)
         other.digest_cons = self.digest_cons
         other.digest_size = self.digest_size
         other.inner = self.inner.copy()

Modified: python/branches/pep-0384/Lib/http/client.py
==============================================================================
--- python/branches/pep-0384/Lib/http/client.py	(original)
+++ python/branches/pep-0384/Lib/http/client.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/http/cookiejar.py
==============================================================================
--- python/branches/pep-0384/Lib/http/cookiejar.py	(original)
+++ python/branches/pep-0384/Lib/http/cookiejar.py	Fri Aug 27 21:11:11 2010
@@ -1974,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/pep-0384/Lib/http/cookies.py
==============================================================================
--- python/branches/pep-0384/Lib/http/cookies.py	(original)
+++ python/branches/pep-0384/Lib/http/cookies.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/http/server.py
==============================================================================
--- python/branches/pep-0384/Lib/http/server.py	(original)
+++ python/branches/pep-0384/Lib/http/server.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/idlelib/NEWS.txt
==============================================================================
--- python/branches/pep-0384/Lib/idlelib/NEWS.txt	(original)
+++ python/branches/pep-0384/Lib/idlelib/NEWS.txt	Fri Aug 27 21:11:11 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/pep-0384/Lib/idlelib/PyShell.py
==============================================================================
--- python/branches/pep-0384/Lib/idlelib/PyShell.py	(original)
+++ python/branches/pep-0384/Lib/idlelib/PyShell.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/idlelib/idlever.py
==============================================================================
--- python/branches/pep-0384/Lib/idlelib/idlever.py	(original)
+++ python/branches/pep-0384/Lib/idlelib/idlever.py	Fri Aug 27 21:11:11 2010
@@ -1 +1 @@
-IDLE_VERSION = "3.2a0"
+IDLE_VERSION = "3.2a1"

Modified: python/branches/pep-0384/Lib/imaplib.py
==============================================================================
--- python/branches/pep-0384/Lib/imaplib.py	(original)
+++ python/branches/pep-0384/Lib/imaplib.py	Fri Aug 27 21:11:11 2010
@@ -147,8 +147,6 @@
     class abort(error): pass        # Service errors - close and retry
     class readonly(abort): pass     # Mailbox status changed to READ-ONLY
 
-    mustquote = re.compile(br"[^\w!#$%&'*+,.:;<=>?^`|~-]", re.ASCII)
-
     def __init__(self, host = '', port = IMAP4_PORT):
         self.debug = Debug
         self.state = 'LOGOUT'
@@ -765,7 +763,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'
@@ -846,7 +844,6 @@
             if arg is None: continue
             if isinstance(arg, str):
                 arg = bytes(arg, "ASCII")
-            #data = data + b' ' + self._checkquote(arg)
             data = data + b' ' + arg
 
         literal = self.literal
@@ -1055,18 +1052,6 @@
         return tag
 
 
-    def _checkquote(self, arg):
-
-        # Must quote command args if non-alphanumeric chars present,
-        # and not already quoted.
-
-        if len(arg) >= 2 and (arg[0],arg[-1]) in (('(',')'),('"','"')):
-            return arg
-        if arg and self.mustquote.search(arg) is None:
-            return arg
-        return self._quote(arg)
-
-
     def _quote(self, arg):
 
         arg = arg.replace(b'\\', b'\\\\')

Modified: python/branches/pep-0384/Lib/importlib/_bootstrap.py
==============================================================================
--- python/branches/pep-0384/Lib/importlib/_bootstrap.py	(original)
+++ python/branches/pep-0384/Lib/importlib/_bootstrap.py	Fri Aug 27 21:11:11 2010
@@ -482,27 +482,38 @@
 
     def set_data(self, path, data):
         """Write bytes data to a file."""
+        parent, _, filename = path.rpartition(path_sep)
+        path_parts = []
+        # Figure out what directories are missing.
+        while parent and not _path_isdir(parent):
+            parent, _, part = parent.rpartition(path_sep)
+            path_parts.append(part)
+        # Create needed directories.
+        for part in reversed(path_parts):
+            parent = _path_join(parent, part)
+            try:
+                _os.mkdir(parent)
+            except OSError as exc:
+                # Probably another Python process already created the dir.
+                if exc.errno == errno.EEXIST:
+                    continue
+                else:
+                    raise
+            except IOError as exc:
+                # If can't get proper access, then just forget about writing
+                # the data.
+                if exc.errno == errno.EACCES:
+                    return
+                else:
+                    raise
         try:
-            with _closing(_io.FileIO(path, 'wb')) as file:
+            with _io.FileIO(path, 'wb') as file:
                 file.write(data)
         except IOError as exc:
-            if exc.errno == errno.ENOENT:
-                directory, _, filename = path.rpartition(path_sep)
-                sub_directories = []
-                while not _path_isdir(directory):
-                    directory, _, sub_dir = directory.rpartition(path_sep)
-                    sub_directories.append(sub_dir)
-                    for part in reversed(sub_directories):
-                        directory = _path_join(directory, part)
-                        try:
-                            _os.mkdir(directory)
-                        except IOError as exc:
-                            if exc.errno != errno.EACCES:
-                                raise
-                            else:
-                                return
-                return self.set_data(path, data)
-            elif exc.errno != errno.EACCES:
+            # Don't worry if you can't write bytecode.
+            if exc.errno == errno.EACCES:
+                return
+            else:
                 raise
 
 

Modified: python/branches/pep-0384/Lib/importlib/abc.py
==============================================================================
--- python/branches/pep-0384/Lib/importlib/abc.py	(original)
+++ python/branches/pep-0384/Lib/importlib/abc.py	Fri Aug 27 21:11:11 2010
@@ -117,6 +117,20 @@
 
     """
 
+    def path_mtime(self, path:str) -> int:
+        """Return the modification time for the path."""
+        raise NotImplementedError
+
+    def set_data(self, path:str, data:bytes) -> None:
+        """Write the bytes to the path (if possible).
+
+        Any needed intermediary directories are to be created. If for some
+        reason the file cannot be written because of permissions, fail
+        silently.
+
+        """
+        raise NotImplementedError
+
 
 class PyLoader(SourceLoader):
 

Modified: python/branches/pep-0384/Lib/importlib/test/source/test_file_loader.py
==============================================================================
--- python/branches/pep-0384/Lib/importlib/test/source/test_file_loader.py	(original)
+++ python/branches/pep-0384/Lib/importlib/test/source/test_file_loader.py	Fri Aug 27 21:11:11 2010
@@ -8,6 +8,7 @@
 import marshal
 import os
 import py_compile
+import shutil
 import stat
 import sys
 import unittest
@@ -112,18 +113,20 @@
     def test_file_from_empty_string_dir(self):
         # Loading a module found from an empty string entry on sys.path should
         # not only work, but keep all attributes relative.
-        with open('_temp.py', 'w') as file:
+        file_path = '_temp.py'
+        with open(file_path, 'w') as file:
             file.write("# test file for importlib")
         try:
             with util.uncache('_temp'):
-                loader = _bootstrap._SourceFileLoader('_temp', '_temp.py')
+                loader = _bootstrap._SourceFileLoader('_temp', file_path)
                 mod = loader.load_module('_temp')
-                self.assertEqual('_temp.py', mod.__file__)
-                self.assertEqual(imp.cache_from_source('_temp.py'),
+                self.assertEqual(file_path, mod.__file__)
+                self.assertEqual(imp.cache_from_source(file_path),
                                  mod.__cached__)
-
         finally:
-            os.unlink('_temp.py')
+            os.unlink(file_path)
+            pycache = os.path.dirname(imp.cache_from_source(file_path))
+            shutil.rmtree(pycache)
 
 
 class BadBytecodeTest(unittest.TestCase):
@@ -380,7 +383,7 @@
     run_unittest(SimpleTest,
                  SourceLoaderBadBytecodeTest,
                  SourcelessLoaderBadBytecodeTest
-                 )
+                )
 
 
 if __name__ == '__main__':

Modified: python/branches/pep-0384/Lib/inspect.py
==============================================================================
--- python/branches/pep-0384/Lib/inspect.py	(original)
+++ python/branches/pep-0384/Lib/inspect.py	Fri Aug 27 21:11:11 2010
@@ -36,15 +36,25 @@
 import itertools
 import string
 import re
-import dis
 import imp
 import tokenize
 import linecache
 from operator import attrgetter
 from collections import namedtuple
-# These constants are from Include/code.h.
-CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 0x1, 0x2, 0x4, 0x8
-CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
+
+# Create constants for the compiler flags in Include/code.h
+# We try to get them from dis to avoid duplication, but fall
+# back to hardcording so the dependency is optional
+try:
+    from dis import COMPILER_FLAG_NAMES as _flag_names
+except ImportError:
+    CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
+    CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
+    CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
+else:
+    mod_dict = globals()
+    for k, v in _flag_names.items():
+        mod_dict["CO_" + v] = k
 
 # See Include/object.h
 TPFLAGS_IS_ABSTRACT = 1 << 20
@@ -159,7 +169,7 @@
 
     Generator function objects provides same attributes as functions.
 
-    See isfunction.__doc__ for attributes listing."""
+    See help(isfunction) for attributes listing."""
     return bool((isfunction(object) or ismethod(object)) and
                 object.__code__.co_flags & CO_GENERATOR)
 
@@ -1062,10 +1072,9 @@
         tb = tb.tb_next
     return framelist
 
-if hasattr(sys, '_getframe'):
-    currentframe = sys._getframe
-else:
-    currentframe = lambda _=None: None
+def currentframe():
+    """Return the frame of the caller or None if this is not possible."""
+    return sys._getframe(1) if hasattr(sys, "_getframe") else None
 
 def stack(context=1):
     """Return a list of records for the stack above the caller's frame."""

Modified: python/branches/pep-0384/Lib/json/__init__.py
==============================================================================
--- python/branches/pep-0384/Lib/json/__init__.py	(original)
+++ python/branches/pep-0384/Lib/json/__init__.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/json/decoder.py
==============================================================================
--- python/branches/pep-0384/Lib/json/decoder.py	(original)
+++ python/branches/pep-0384/Lib/json/decoder.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/json/encoder.py
==============================================================================
--- python/branches/pep-0384/Lib/json/encoder.py	(original)
+++ python/branches/pep-0384/Lib/json/encoder.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/lib2to3/fixer_util.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/fixer_util.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/fixer_util.py	Fri Aug 27 21:11:11 2010
@@ -1,6 +1,8 @@
 """Utility functions, node construction macros, etc."""
 # Author: Collin Winter
 
+from itertools import islice
+
 # Local imports
 from .pgen2 import token
 from .pytree import Leaf, Node
@@ -14,7 +16,7 @@
 
 def KeywordArg(keyword, value):
     return Node(syms.argument,
-                [keyword, Leaf(token.EQUAL, '='), value])
+                [keyword, Leaf(token.EQUAL, "="), value])
 
 def LParen():
     return Leaf(token.LPAR, "(")
@@ -76,9 +78,9 @@
 
 def Subscript(index_node):
     """A numeric or string subscript"""
-    return Node(syms.trailer, [Leaf(token.LBRACE, '['),
+    return Node(syms.trailer, [Leaf(token.LBRACE, "["),
                                index_node,
-                               Leaf(token.RBRACE, ']')])
+                               Leaf(token.RBRACE, "]")])
 
 def String(string, prefix=None):
     """A string leaf"""
@@ -120,9 +122,9 @@
         # Pull the leaves out of their old tree
         leaf.remove()
 
-    children = [Leaf(token.NAME, 'from'),
+    children = [Leaf(token.NAME, "from"),
                 Leaf(token.NAME, package_name, prefix=" "),
-                Leaf(token.NAME, 'import', prefix=" "),
+                Leaf(token.NAME, "import", prefix=" "),
                 Node(syms.import_as_names, name_leafs)]
     imp = Node(syms.import_from, children)
     return imp
@@ -245,6 +247,16 @@
         return False
     return True
 
+def find_indentation(node):
+    """Find the indentation of *node*."""
+    while node is not None:
+        if node.type == syms.suite and len(node.children) > 2:
+            indent = node.children[1]
+            if indent.type == token.INDENT:
+                return indent.value
+        node = node.parent
+    return ""
+
 ###########################################################
 ### The following functions are to find bindings in a suite
 ###########################################################
@@ -314,11 +326,11 @@
 
     if package is None:
         import_ = Node(syms.import_name, [
-            Leaf(token.NAME, 'import'),
-            Leaf(token.NAME, name, prefix=' ')
+            Leaf(token.NAME, "import"),
+            Leaf(token.NAME, name, prefix=" ")
         ])
     else:
-        import_ = FromImport(package, [Leaf(token.NAME, name, prefix=' ')])
+        import_ = FromImport(package, [Leaf(token.NAME, name, prefix=" ")])
 
     children = [import_, Newline()]
     root.insert_child(insert_pos, Node(syms.simple_stmt, children))
@@ -404,7 +416,7 @@
         if package and str(node.children[1]).strip() != package:
             return None
         n = node.children[3]
-        if package and _find('as', n):
+        if package and _find("as", n):
             # See test_from_import_as for explanation
             return None
         elif n.type == syms.import_as_names and _find(name, n):

Modified: python/branches/pep-0384/Lib/lib2to3/fixes/fix_itertools_imports.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/fixes/fix_itertools_imports.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/fixes/fix_itertools_imports.py	Fri Aug 27 21:11:11 2010
@@ -43,8 +43,8 @@
             else:
                 remove_comma ^= True
 
-        if children[-1].type == token.COMMA:
-            children[-1].remove()
+        while children and children[-1].type == token.COMMA:
+            children.pop().remove()
 
         # If there are no imports left, just get rid of the entire statement
         if (not (imports.children or getattr(imports, 'value', None)) or

Modified: python/branches/pep-0384/Lib/lib2to3/fixes/fix_operator.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/fixes/fix_operator.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/fixes/fix_operator.py	Fri Aug 27 21:11:11 2010
@@ -1,40 +1,89 @@
-"""Fixer for operator.{isCallable,sequenceIncludes}
+"""Fixer for operator functions.
 
-operator.isCallable(obj) -> hasattr(obj, '__call__')
+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)
 """
 
+import collections
+
 # Local imports
-from .. import fixer_base
-from ..fixer_util import Call, Name, String
+from lib2to3 import fixer_base
+from lib2to3.fixer_util import Call, Name, String, touch_import
+
 
 class FixOperator(fixer_base.BaseFix):
 
-    methods = "method=('isCallable'|'sequenceIncludes')"
-    func = "'(' func=any ')'"
+    methods = """
+              method=('isCallable'|'sequenceIncludes'
+                     |'isSequenceType'|'isMappingType'|'isNumberType'
+                     |'repeat'|'irepeat')
+              """
+    obj = "'(' obj=any ')'"
     PATTERN = """
               power< module='operator'
-                trailer< '.' %(methods)s > trailer< %(func)s > >
+                trailer< '.' %(methods)s > trailer< %(obj)s > >
               |
-              power< %(methods)s trailer< %(func)s > >
-              """ % dict(methods=methods, func=func)
+              power< %(methods)s trailer< %(obj)s > >
+              """ % dict(methods=methods, obj=obj)
 
     def transform(self, node, results):
+        method = self._check_method(node, results)
+        if method is not None:
+            return method(node, results)
+
+    def _sequenceIncludes(self, node, results):
+        """operator.contains(%s)"""
+        return self._handle_rename(node, results, "contains")
+
+    def _isCallable(self, node, results):
+        """hasattr(%s, '__call__')"""
+        obj = results["obj"]
+        args = [obj.clone(), String(", "), String("'__call__'")]
+        return Call(Name("hasattr"), args, prefix=node.prefix)
+
+    def _repeat(self, node, results):
+        """operator.mul(%s)"""
+        return self._handle_rename(node, results, "mul")
+
+    def _irepeat(self, node, results):
+        """operator.imul(%s)"""
+        return self._handle_rename(node, results, "imul")
+
+    def _isSequenceType(self, node, results):
+        """isinstance(%s, collections.Sequence)"""
+        return self._handle_type2abc(node, results, "collections", "Sequence")
+
+    def _isMappingType(self, node, results):
+        """isinstance(%s, collections.Mapping)"""
+        return self._handle_type2abc(node, results, "collections", "Mapping")
+
+    def _isNumberType(self, node, results):
+        """isinstance(%s, numbers.Number)"""
+        return self._handle_type2abc(node, results, "numbers", "Number")
+
+    def _handle_rename(self, node, results, name):
         method = results["method"][0]
+        method.value = name
+        method.changed()
 
-        if method.value == "sequenceIncludes":
-            if "module" not in results:
-                # operator may not be in scope, so we can't make a change.
-                self.warning(node, "You should use operator.contains here.")
-            else:
-                method.value = "contains"
-                method.changed()
-        elif method.value == "isCallable":
-            if "module" not in results:
-                self.warning(node,
-                             "You should use hasattr(%s, '__call__') here." %
-                             results["func"].value)
+    def _handle_type2abc(self, node, results, module, abc):
+        touch_import(None, module, node)
+        obj = results["obj"]
+        args = [obj.clone(), String(", " + ".".join([module, abc]))]
+        return Call(Name("isinstance"), args, prefix=node.prefix)
+
+    def _check_method(self, node, results):
+        method = getattr(self, "_" + results["method"][0].value)
+        if isinstance(method, collections.Callable):
+            if "module" in results:
+                return method
             else:
-                func = results["func"]
-                args = [func.clone(), String(", "), String("'__call__'")]
-                return Call(Name("hasattr"), args, prefix=node.prefix)
+                sub = (str(results["obj"]),)
+                invocation_str = str(method.__doc__) % sub
+                self.warning(node, "You should use '%s' here." % invocation_str)
+        return None

Modified: python/branches/pep-0384/Lib/lib2to3/fixes/fix_urllib.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/fixes/fix_urllib.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/fixes/fix_urllib.py	Fri Aug 27 21:11:11 2010
@@ -5,39 +5,40 @@
 # Author: Nick Edds
 
 # Local imports
-from .fix_imports import alternates, FixImports
-from .. import fixer_base
-from ..fixer_util import Name, Comma, FromImport, Newline, attr_chain
-
-MAPPING = {'urllib':  [
-                ('urllib.request',
-                    ['URLOpener', 'FancyURLOpener', 'urlretrieve',
-                     '_urlopener', 'urlopen', 'urlcleanup',
-                     'pathname2url', 'url2pathname']),
-                ('urllib.parse',
-                    ['quote', 'quote_plus', 'unquote', 'unquote_plus',
-                     'urlencode', 'splitattr', 'splithost', 'splitnport',
-                     'splitpasswd', 'splitport', 'splitquery', 'splittag',
-                     'splittype', 'splituser', 'splitvalue', ]),
-                ('urllib.error',
-                    ['ContentTooShortError'])],
-           'urllib2' : [
-                ('urllib.request',
-                    ['urlopen', 'install_opener', 'build_opener',
-                     'Request', 'OpenerDirector', 'BaseHandler',
-                     'HTTPDefaultErrorHandler', 'HTTPRedirectHandler',
-                     'HTTPCookieProcessor', 'ProxyHandler',
-                     'HTTPPasswordMgr',
-                     'HTTPPasswordMgrWithDefaultRealm',
-                     'AbstractBasicAuthHandler',
-                     'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
-                     'AbstractDigestAuthHandler',
-                     'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
-                     'HTTPHandler', 'HTTPSHandler', 'FileHandler',
-                     'FTPHandler', 'CacheFTPHandler',
-                     'UnknownHandler']),
-                ('urllib.error',
-                    ['URLError', 'HTTPError']),
+from lib2to3.fixes.fix_imports import alternates, FixImports
+from lib2to3 import fixer_base
+from lib2to3.fixer_util import (Name, Comma, FromImport, Newline,
+                                find_indentation)
+
+MAPPING = {"urllib":  [
+                ("urllib.request",
+                    ["URLOpener", "FancyURLOpener", "urlretrieve",
+                     "_urlopener", "urlopen", "urlcleanup",
+                     "pathname2url", "url2pathname"]),
+                ("urllib.parse",
+                    ["quote", "quote_plus", "unquote", "unquote_plus",
+                     "urlencode", "splitattr", "splithost", "splitnport",
+                     "splitpasswd", "splitport", "splitquery", "splittag",
+                     "splittype", "splituser", "splitvalue", ]),
+                ("urllib.error",
+                    ["ContentTooShortError"])],
+           "urllib2" : [
+                ("urllib.request",
+                    ["urlopen", "install_opener", "build_opener",
+                     "Request", "OpenerDirector", "BaseHandler",
+                     "HTTPDefaultErrorHandler", "HTTPRedirectHandler",
+                     "HTTPCookieProcessor", "ProxyHandler",
+                     "HTTPPasswordMgr",
+                     "HTTPPasswordMgrWithDefaultRealm",
+                     "AbstractBasicAuthHandler",
+                     "HTTPBasicAuthHandler", "ProxyBasicAuthHandler",
+                     "AbstractDigestAuthHandler",
+                     "HTTPDigestAuthHandler", "ProxyDigestAuthHandler",
+                     "HTTPHandler", "HTTPSHandler", "FileHandler",
+                     "FTPHandler", "CacheFTPHandler",
+                     "UnknownHandler"]),
+                ("urllib.error",
+                    ["URLError", "HTTPError"]),
            ]
 }
 
@@ -78,7 +79,7 @@
            import name with a comma separated list of its
            replacements.
         """
-        import_mod = results.get('module')
+        import_mod = results.get("module")
         pref = import_mod.prefix
 
         names = []
@@ -94,9 +95,9 @@
            the module to be imported from with the appropriate new
            module.
         """
-        mod_member = results.get('mod_member')
+        mod_member = results.get("mod_member")
         pref = mod_member.prefix
-        member = results.get('member')
+        member = results.get("member")
 
         # Simple case with only a single member being imported
         if member:
@@ -111,19 +112,18 @@
             if new_name:
                 mod_member.replace(Name(new_name, prefix=pref))
             else:
-                self.cannot_convert(node,
-                                    'This is an invalid module element')
+                self.cannot_convert(node, "This is an invalid module element")
 
         # Multiple members being imported
         else:
             # a dictionary for replacements, order matters
             modules = []
             mod_dict = {}
-            members = results.get('members')
+            members = results["members"]
             for member in members:
                 member = member.value
                 # we only care about the actual members
-                if member != ',':
+                if member != ",":
                     for change in MAPPING[mod_member.value]:
                         if member in change[1]:
                             if change[0] in mod_dict:
@@ -133,13 +133,19 @@
                                 modules.append(change[0])
 
             new_nodes = []
+            indentation = find_indentation(node)
+            first = True
             for module in modules:
                 elts = mod_dict[module]
                 names = []
                 for elt in elts[:-1]:
                     names.extend([Name(elt, prefix=pref), Comma()])
                 names.append(Name(elts[-1], prefix=pref))
-                new_nodes.append(FromImport(module, names))
+                new = FromImport(module, names)
+                if not first or node.parent.prefix.endswith(indentation):
+                    new.prefix = indentation
+                new_nodes.append(new)
+                first = False
             if new_nodes:
                 nodes = []
                 for new_node in new_nodes[:-1]:
@@ -147,12 +153,12 @@
                 nodes.append(new_nodes[-1])
                 node.replace(nodes)
             else:
-                self.cannot_convert(node, 'All module elements are invalid')
+                self.cannot_convert(node, "All module elements are invalid")
 
     def transform_dot(self, node, results):
         """Transform for calls to module members in code."""
-        module_dot = results.get('bare_with_attr')
-        member = results.get('member')
+        module_dot = results.get("bare_with_attr")
+        member = results.get("member")
         new_name = None
         if isinstance(member, list):
             member = member[0]
@@ -164,17 +170,17 @@
             module_dot.replace(Name(new_name,
                                     prefix=module_dot.prefix))
         else:
-            self.cannot_convert(node, 'This is an invalid module element')
+            self.cannot_convert(node, "This is an invalid module element")
 
     def transform(self, node, results):
-        if results.get('module'):
+        if results.get("module"):
             self.transform_import(node, results)
-        elif results.get('mod_member'):
+        elif results.get("mod_member"):
             self.transform_member(node, results)
-        elif results.get('bare_with_attr'):
+        elif results.get("bare_with_attr"):
             self.transform_dot(node, results)
         # Renaming and star imports are not supported for these modules.
-        elif results.get('module_star'):
-            self.cannot_convert(node, 'Cannot handle star imports.')
-        elif results.get('module_as'):
-            self.cannot_convert(node, 'This module is now multiple modules')
+        elif results.get("module_star"):
+            self.cannot_convert(node, "Cannot handle star imports.")
+        elif results.get("module_as"):
+            self.cannot_convert(node, "This module is now multiple modules")

Modified: python/branches/pep-0384/Lib/lib2to3/pytree.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/pytree.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/pytree.py	Fri Aug 27 21:11:11 2010
@@ -286,7 +286,7 @@
         """Return a pre-order iterator for the tree."""
         yield self
         for child in self.children:
-            for node in child.post_order():
+            for node in child.pre_order():
                 yield node
 
     def _prefix_getter(self):

Modified: python/branches/pep-0384/Lib/lib2to3/refactor.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/refactor.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/refactor.py	Fri Aug 27 21:11:11 2010
@@ -517,7 +517,7 @@
         try:
             tree = self.parse_block(block, lineno, indent)
         except Exception as err:
-            if self.log.isEnabledFor(logging.DEBUG):
+            if self.logger.isEnabledFor(logging.DEBUG):
                 for line in block:
                     self.log_debug("Source: %s", line.rstrip("\n"))
             self.log_error("Can't parse docstring in %s line %s: %s: %s",

Modified: python/branches/pep-0384/Lib/lib2to3/tests/test_fixers.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/tests/test_fixers.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/tests/test_fixers.py	Fri Aug 27 21:11:11 2010
@@ -1818,6 +1818,33 @@
             s = "from %s import *" % old
             self.warns_unchanged(s, "Cannot handle star imports")
 
+    def test_indented(self):
+        b = """
+def foo():
+    from urllib import urlencode, urlopen
+"""
+        a = """
+def foo():
+    from urllib.parse import urlencode
+    from urllib.request import urlopen
+"""
+        self.check(b, a)
+
+        b = """
+def foo():
+    other()
+    from urllib import urlencode, urlopen
+"""
+        a = """
+def foo():
+    other()
+    from urllib.parse import urlencode
+    from urllib.request import urlopen
+"""
+        self.check(b, a)
+
+
+
     def test_import_module_usage(self):
         for old, changes in self.modules.items():
             for new, members in changes:
@@ -3623,6 +3650,10 @@
         a = "from itertools import bar, foo"
         self.check(b, a)
 
+        b = "from itertools import chain, imap, izip"
+        a = "from itertools import chain"
+        self.check(b, a)
+
     def test_comments(self):
         b = "#foo\nfrom itertools import imap, izip"
         a = "#foo\n"
@@ -4303,13 +4334,89 @@
         a = "operator.contains(x, y)"
         self.check(b, a)
 
+        b = "operator .sequenceIncludes(x, y)"
+        a = "operator .contains(x, y)"
+        self.check(b, a)
+
+        b = "operator.  sequenceIncludes(x, y)"
+        a = "operator.  contains(x, y)"
+        self.check(b, a)
+
+    def test_operator_isSequenceType(self):
+        b = "operator.isSequenceType(x)"
+        a = "import collections\nisinstance(x, collections.Sequence)"
+        self.check(b, a)
+
+    def test_operator_isMappingType(self):
+        b = "operator.isMappingType(x)"
+        a = "import collections\nisinstance(x, collections.Mapping)"
+        self.check(b, a)
+
+    def test_operator_isNumberType(self):
+        b = "operator.isNumberType(x)"
+        a = "import numbers\nisinstance(x, numbers.Number)"
+        self.check(b, a)
+
+    def test_operator_repeat(self):
+        b = "operator.repeat(x, n)"
+        a = "operator.mul(x, n)"
+        self.check(b, a)
+
+        b = "operator .repeat(x, n)"
+        a = "operator .mul(x, n)"
+        self.check(b, a)
+
+        b = "operator.  repeat(x, n)"
+        a = "operator.  mul(x, n)"
+        self.check(b, a)
+
+    def test_operator_irepeat(self):
+        b = "operator.irepeat(x, n)"
+        a = "operator.imul(x, n)"
+        self.check(b, a)
+
+        b = "operator .irepeat(x, n)"
+        a = "operator .imul(x, n)"
+        self.check(b, a)
+
+        b = "operator.  irepeat(x, n)"
+        a = "operator.  imul(x, n)"
+        self.check(b, a)
+
     def test_bare_isCallable(self):
         s = "isCallable(x)"
-        self.warns_unchanged(s, "You should use hasattr(x, '__call__') here.")
+        t = "You should use 'hasattr(x, '__call__')' here."
+        self.warns_unchanged(s, t)
 
     def test_bare_sequenceIncludes(self):
         s = "sequenceIncludes(x, y)"
-        self.warns_unchanged(s, "You should use operator.contains here.")
+        t = "You should use 'operator.contains(x, y)' here."
+        self.warns_unchanged(s, t)
+
+    def test_bare_operator_isSequenceType(self):
+        s = "isSequenceType(z)"
+        t = "You should use 'isinstance(z, collections.Sequence)' here."
+        self.warns_unchanged(s, t)
+
+    def test_bare_operator_isMappingType(self):
+        s = "isMappingType(x)"
+        t = "You should use 'isinstance(x, collections.Mapping)' here."
+        self.warns_unchanged(s, t)
+
+    def test_bare_operator_isNumberType(self):
+        s = "isNumberType(y)"
+        t = "You should use 'isinstance(y, numbers.Number)' here."
+        self.warns_unchanged(s, t)
+
+    def test_bare_operator_repeat(self):
+        s = "repeat(x, n)"
+        t = "You should use 'operator.mul(x, n)' here."
+        self.warns_unchanged(s, t)
+
+    def test_bare_operator_irepeat(self):
+        s = "irepeat(y, 187)"
+        t = "You should use 'operator.imul(y, 187)' here."
+        self.warns_unchanged(s, t)
 
 
 class Test_exitfunc(FixerTestCase):

Modified: python/branches/pep-0384/Lib/lib2to3/tests/test_pytree.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/tests/test_pytree.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/tests/test_pytree.py	Fri Aug 27 21:11:11 2010
@@ -181,14 +181,18 @@
     def test_post_order(self):
         l1 = pytree.Leaf(100, "foo")
         l2 = pytree.Leaf(100, "bar")
-        n1 = pytree.Node(1000, [l1, l2])
-        self.assertEqual(list(n1.post_order()), [l1, l2, n1])
+        l3 = pytree.Leaf(100, "fooey")
+        c1 = pytree.Node(1000, [l1, l2])
+        n1 = pytree.Node(1000, [c1, l3])
+        self.assertEqual(list(n1.post_order()), [l1, l2, c1, l3, n1])
 
     def test_pre_order(self):
         l1 = pytree.Leaf(100, "foo")
         l2 = pytree.Leaf(100, "bar")
-        n1 = pytree.Node(1000, [l1, l2])
-        self.assertEqual(list(n1.pre_order()), [n1, l1, l2])
+        l3 = pytree.Leaf(100, "fooey")
+        c1 = pytree.Node(1000, [l1, l2])
+        n1 = pytree.Node(1000, [c1, l3])
+        self.assertEqual(list(n1.pre_order()), [n1, c1, l1, l2, l3])
 
     def test_changed(self):
         l1 = pytree.Leaf(100, "f")

Modified: python/branches/pep-0384/Lib/lib2to3/tests/test_util.py
==============================================================================
--- python/branches/pep-0384/Lib/lib2to3/tests/test_util.py	(original)
+++ python/branches/pep-0384/Lib/lib2to3/tests/test_util.py	Fri Aug 27 21:11:11 2010
@@ -575,3 +575,20 @@
         node = parse('bar()')
         fixer_util.touch_import(None, "cgi", node)
         self.assertEqual(str(node), 'import cgi\nbar()\n\n')
+
+class Test_find_indentation(support.TestCase):
+
+    def test_nothing(self):
+        fi = fixer_util.find_indentation
+        node = parse("node()")
+        self.assertEqual(fi(node), "")
+        node = parse("")
+        self.assertEqual(fi(node), "")
+
+    def test_simple(self):
+        fi = fixer_util.find_indentation
+        node = parse("def f():\n    x()")
+        self.assertEqual(fi(node), "")
+        self.assertEqual(fi(node.children[0].children[4].children[2]), "    ")
+        node = parse("def f():\n    x()\n    y()")
+        self.assertEqual(fi(node.children[0].children[4].children[4]), "    ")

Modified: python/branches/pep-0384/Lib/logging/__init__.py
==============================================================================
--- python/branches/pep-0384/Lib/logging/__init__.py	(original)
+++ python/branches/pep-0384/Lib/logging/__init__.py	Fri Aug 27 21:11:11 2010
@@ -609,12 +609,16 @@
     """
     Remove a handler reference from the internal cleanup list.
     """
-    _acquireLock()
-    try:
-        if wr in _handlerList:
-            _handlerList.remove(wr)
-    finally:
-        _releaseLock()
+    # This function can be called during module teardown, when globals are
+    # set to None. If _acquireLock is None, assume this is the case and do
+    # nothing.
+    if _acquireLock is not None:
+        _acquireLock()
+        try:
+            if wr in _handlerList:
+                _handlerList.remove(wr)
+        finally:
+            _releaseLock()
 
 def _addHandlerRef(handler):
     """
@@ -1604,8 +1608,16 @@
         #we just ignore them if raiseExceptions is not set
         try:
             h = wr()
-            h.flush()
-            h.close()
+            if h:
+                try:
+                    h.flush()
+                    h.close()
+                except (IOError, ValueError):
+                    # Ignore errors which might be caused
+                    # because handlers have been closed but
+                    # references to them are still around at
+                    # application exit.
+                    pass
         except:
             if raiseExceptions:
                 raise

Modified: python/branches/pep-0384/Lib/logging/config.py
==============================================================================
--- python/branches/pep-0384/Lib/logging/config.py	(original)
+++ python/branches/pep-0384/Lib/logging/config.py	Fri Aug 27 21:11:11 2010
@@ -63,7 +63,7 @@
 
     cp = configparser.ConfigParser(defaults)
     if hasattr(fname, 'readline'):
-        cp.readfp(fname)
+        cp.read_file(fname)
     else:
         cp.read(fname)
 

Modified: python/branches/pep-0384/Lib/logging/handlers.py
==============================================================================
--- python/branches/pep-0384/Lib/logging/handlers.py	(original)
+++ python/branches/pep-0384/Lib/logging/handlers.py	Fri Aug 27 21:11:11 2010
@@ -103,8 +103,13 @@
 
         If maxBytes is zero, rollover never occurs.
         """
+        # If rotation/rollover is wanted, it doesn't make sense to use another
+        # mode. If for example 'w' were specified, then if there were multiple
+        # runs of the calling application, the logs from previous runs would be
+        # lost if the 'w' is respected, because the log file would be truncated
+        # on each run.
         if maxBytes > 0:
-            mode = 'a' # doesn't make sense otherwise!
+            mode = 'a'
         BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
         self.maxBytes = maxBytes
         self.backupCount = backupCount
@@ -732,12 +737,6 @@
             self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
             self.socket.connect(address)
 
-    # curious: when talking to the unix-domain '/dev/log' socket, a
-    #   zero-terminator seems to be required.  this string is placed
-    #   into a class variable so that it can be overridden if
-    #   necessary.
-    log_format_string = '<%d>%s\000'
-
     def encodePriority(self, facility, priority):
         """
         Encode the facility and priority. You can pass in strings or
@@ -776,19 +775,19 @@
         The record is formatted, and then sent to the syslog server. If
         exception information is present, it is NOT sent to the server.
         """
-        msg = self.format(record)
+        msg = self.format(record) + '\000'
         """
         We need to convert record level to lowercase, maybe this will
         change in the future.
         """
-        msg = self.log_format_string % (
-            self.encodePriority(self.facility,
-                                self.mapPriority(record.levelname)),
-                                msg)
+        prio = '<%d>' % self.encodePriority(self.facility,
+                                            self.mapPriority(record.levelname))
+        prio = prio.encode('utf-8')
         #Message is a string. Convert to bytes as required by RFC 5424
         msg = msg.encode('utf-8')
         if codecs:
             msg = codecs.BOM_UTF8 + msg
+        msg = prio + msg
         try:
             if self.unixsocket:
                 try:
@@ -1012,7 +1011,7 @@
         """
         Emit a record.
 
-        Send the record to the Web server as an URL-encoded dictionary
+        Send the record to the Web server as a percent-encoded dictionary
         """
         try:
             import http.client, urllib.parse

Modified: python/branches/pep-0384/Lib/multiprocessing/connection.py
==============================================================================
--- python/branches/pep-0384/Lib/multiprocessing/connection.py	(original)
+++ python/branches/pep-0384/Lib/multiprocessing/connection.py	Fri Aug 27 21:11:11 2010
@@ -173,7 +173,7 @@
 
 else:
 
-    from ._multiprocessing import win32
+    from _multiprocessing import win32
 
     def Pipe(duplex=True):
         '''

Modified: python/branches/pep-0384/Lib/multiprocessing/forking.py
==============================================================================
--- python/branches/pep-0384/Lib/multiprocessing/forking.py	(original)
+++ python/branches/pep-0384/Lib/multiprocessing/forking.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/multiprocessing/heap.py
==============================================================================
--- python/branches/pep-0384/Lib/multiprocessing/heap.py	(original)
+++ python/branches/pep-0384/Lib/multiprocessing/heap.py	Fri Aug 27 21:11:11 2010
@@ -26,7 +26,7 @@
 
 if sys.platform == 'win32':
 
-    from ._multiprocessing import win32
+    from _multiprocessing import win32
 
     class Arena(object):
 

Modified: python/branches/pep-0384/Lib/multiprocessing/reduction.py
==============================================================================
--- python/branches/pep-0384/Lib/multiprocessing/reduction.py	(original)
+++ python/branches/pep-0384/Lib/multiprocessing/reduction.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ntpath.py
==============================================================================
--- python/branches/pep-0384/Lib/ntpath.py	(original)
+++ python/branches/pep-0384/Lib/ntpath.py	Fri Aug 27 21:11:11 2010
@@ -71,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).
@@ -275,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
@@ -366,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']
@@ -435,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]
@@ -461,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)
@@ -483,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]
@@ -507,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
 
 
@@ -524,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)

Modified: python/branches/pep-0384/Lib/os.py
==============================================================================
--- python/branches/pep-0384/Lib/os.py	(original)
+++ python/branches/pep-0384/Lib/os.py	Fri Aug 27 21:11:11 2010
@@ -387,13 +387,13 @@
 
     try:
         path_list = env.get('PATH')
-    except TypeError:
+    except (TypeError, BytesWarning):
         path_list = None
 
     if supports_bytes_environ:
         try:
             path_listb = env[b'PATH']
-        except (KeyError, TypeError):
+        except (KeyError, TypeError, BytesWarning):
             pass
         else:
             if path_list is not None:
@@ -402,8 +402,7 @@
             path_list = path_listb
 
         if path_list is not None and isinstance(path_list, bytes):
-            path_list = path_list.decode(sys.getfilesystemencoding(),
-                                         'surrogateescape')
+            path_list = fsdecode(path_list)
 
     if path_list is None:
         path_list = defpath
@@ -446,7 +445,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,21 +532,42 @@
         The optional second argument can specify an alternate default.
         key, default and the result are bytes."""
         return environb.get(key, default)
-    __all__.append("getenvb")
 
-def fsencode(value):
-    """Encode value for use in the file system, environment variables
-    or the command line."""
-    if isinstance(value, bytes):
-        return value
-    elif isinstance(value, str):
+    __all__.extend(("environb", "getenvb"))
+
+def fsencode(filename):
+    """
+    Encode filename to the filesystem encoding with 'surrogateescape' error
+    handler, return bytes unchanged. On Windows, use 'strict' error handler if
+    the file system encoding is 'mbcs' (which is the default encoding).
+    """
+    if isinstance(filename, bytes):
+        return filename
+    elif isinstance(filename, str):
+        encoding = sys.getfilesystemencoding()
+        if encoding == 'mbcs':
+            return filename.encode(encoding)
+        else:
+            return filename.encode(encoding, 'surrogateescape')
+    else:
+        raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
+
+def fsdecode(filename):
+    """
+    Decode filename from the filesystem encoding with 'surrogateescape' error
+    handler, return str unchanged. On Windows, use 'strict' error handler if
+    the file system encoding is 'mbcs' (which is the default encoding).
+    """
+    if isinstance(filename, str):
+        return filename
+    elif isinstance(filename, bytes):
         encoding = sys.getfilesystemencoding()
         if encoding == 'mbcs':
-            return value.encode(encoding)
+            return filename.decode(encoding)
         else:
-            return value.encode(encoding, 'surrogateescape')
+            return filename.decode(encoding, 'surrogateescape')
     else:
-        raise TypeError("expect bytes or str, not %s" % type(value).__name__)
+        raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
 
 def _exists(name):
     return name in globals()

Modified: python/branches/pep-0384/Lib/pdb.py
==============================================================================
--- python/branches/pep-0384/Lib/pdb.py	(original)
+++ python/branches/pep-0384/Lib/pdb.py	Fri Aug 27 21:11:11 2010
@@ -62,178 +62,28 @@
 Debugger commands
 =================
 
-h(elp)
-        Without argument, print the list of available commands.  With
-        a command name as argument, print help about that command.
-
-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:lineno 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 for 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 ...]
-        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.
-
-enable bpnumber [bpnumber ...]
-        Enable the breakpoints specified.
-
-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.
-
-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.
-
-commands [bpnumber]
-        Specify a list of commands for the breakpoint.  Type a line
-        containing just 'end' to terminate the commands.  The commands
-        are executed when the breakpoint is hit.
-
-        With no breakpoint number argument, refers to the last
-        breakpoint set.
-
-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
-        Print 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
-        Delete the specified alias.
-
-q(uit)
-        Quit from the debugger. The program being executed is aborted.
 """
+# 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"]
 
@@ -257,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
@@ -276,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
@@ -322,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
 
@@ -353,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):
@@ -366,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).
 
@@ -392,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()
@@ -419,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:]
@@ -440,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."""
@@ -483,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
@@ -493,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)
@@ -509,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.
+        """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.
 
-        Those commands will be executed whenever the breakpoint causes
-        the program to stop 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 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
@@ -566,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
@@ -575,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
@@ -601,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)
@@ -615,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):
@@ -633,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):
@@ -674,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? ')
@@ -789,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"
@@ -801,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
@@ -836,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
@@ -852,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
@@ -868,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
@@ -920,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
@@ -944,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
@@ -957,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
@@ -1021,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']
 
@@ -1107,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:
-            print(' ', end=' ', file=self.stdout)
-        print(self.format_stack_entry(frame_lineno,
-                                                     prompt_prefix), file=self.stdout)
-
-
-    # Help methods (derived from docstring)
-
-    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" shows the full pdb documentation
-"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)
+            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:
+            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.
 
@@ -1443,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):
@@ -1469,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()
@@ -1493,17 +1406,42 @@
     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)
@@ -1513,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:
@@ -1521,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/pep-0384/Lib/pickle.py
==============================================================================
--- python/branches/pep-0384/Lib/pickle.py	(original)
+++ python/branches/pep-0384/Lib/pickle.py	Fri Aug 27 21:11:11 2010
@@ -1322,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/pep-0384/Lib/pickletools.py
==============================================================================
--- python/branches/pep-0384/Lib/pickletools.py	(original)
+++ python/branches/pep-0384/Lib/pickletools.py	Fri Aug 27 21:11:11 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.")
 

Modified: python/branches/pep-0384/Lib/platform.py
==============================================================================
--- python/branches/pep-0384/Lib/platform.py	(original)
+++ python/branches/pep-0384/Lib/platform.py	Fri Aug 27 21:11:11 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):
@@ -951,9 +990,8 @@
     """ Interface to the system's file command.
 
         The function uses the -b option of the file command to have it
-        ommit the filename in its output and if possible the -L option
-        to have the command follow symlinks. It returns default in
-        case the command should fail.
+        omit the filename in its output. Follow the symlinks. It returns
+        default in case the command should fail.
 
     """
     if sys.platform in ('dos','win32','win16','os2'):
@@ -961,7 +999,7 @@
         return default
     target = _follow_symlinks(target).replace('"', '\\"')
     try:
-        f = os.popen('file "%s" 2> %s' % (target, DEV_NULL))
+        f = os.popen('file -b "%s" 2> %s' % (target, DEV_NULL))
     except (AttributeError,os.error):
         return default
     output = f.read().strip()
@@ -981,8 +1019,6 @@
     'dos': ('','MSDOS'),
 }
 
-_architecture_split = re.compile(r'[\s,]').split
-
 def architecture(executable=sys.executable,bits='',linkage=''):
 
     """ Queries the given executable (defaults to the Python interpreter
@@ -1017,11 +1053,11 @@
 
     # Get data from the 'file' system command
     if executable:
-        output = _syscmd_file(executable, '')
+        fileout = _syscmd_file(executable, '')
     else:
-        output = ''
+        fileout = ''
 
-    if not output and \
+    if not fileout and \
        executable == sys.executable:
         # "file" command did not return anything; we'll try to provide
         # some sensible defaults then...
@@ -1033,9 +1069,6 @@
                 linkage = l
         return bits,linkage
 
-    # Split the output into a list of strings omitting the filename
-    fileout = _architecture_split(output)[1:]
-
     if 'executable' not in fileout:
         # Format not supported
         return bits,linkage
@@ -1098,7 +1131,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/pep-0384/Lib/poplib.py
==============================================================================
--- python/branches/pep-0384/Lib/poplib.py	(original)
+++ python/branches/pep-0384/Lib/poplib.py	Fri Aug 27 21:11:11 2010
@@ -331,16 +331,26 @@
         See the methods of the parent class POP3 for more documentation.
         """
 
-        def __init__(self, host, port=POP3_SSL_PORT,
-        keyfile=None, certfile=None,
-        timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
+        def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None,
+                     timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=None):
+            if context is not None and keyfile is not None:
+                raise ValueError("context and keyfile arguments are mutually "
+                                 "exclusive")
+            if context is not None and certfile is not None:
+                raise ValueError("context and certfile arguments are mutually "
+                                 "exclusive")
             self.keyfile = keyfile
             self.certfile = certfile
+            self.context = context
             POP3.__init__(self, host, port, timeout)
 
         def _create_socket(self, timeout):
             sock = POP3._create_socket(self, timeout)
-            return ssl.wrap_socket(sock, self.keyfile, self.certfile)
+            if self.context is not None:
+                sock = self.context.wrap_socket(sock)
+            else:
+                sock = ssl.wrap_socket(sock, self.keyfile, self.certfile)
+            return sock
 
     __all__.append("POP3_SSL")
 

Modified: python/branches/pep-0384/Lib/posixpath.py
==============================================================================
--- python/branches/pep-0384/Lib/posixpath.py	(original)
+++ python/branches/pep-0384/Lib/posixpath.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/profile.py
==============================================================================
--- python/branches/pep-0384/Lib/profile.py	(original)
+++ python/branches/pep-0384/Lib/profile.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/pstats.py
==============================================================================
--- python/branches/pep-0384/Lib/pstats.py	(original)
+++ python/branches/pep-0384/Lib/pstats.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/pydoc.py
==============================================================================
--- python/branches/pep-0384/Lib/pydoc.py	(original)
+++ python/branches/pep-0384/Lib/pydoc.py	Fri Aug 27 21:11:11 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."""
@@ -2026,7 +2029,7 @@
     class DocServer(http.server.HTTPServer):
         def __init__(self, port, callback):
             host = 'localhost'
-            self.address = ('', port)
+            self.address = (host, port)
             self.url = 'http://%s:%d/' % (host, port)
             self.callback = callback
             self.base.__init__(self, self.address, self.handler)

Modified: python/branches/pep-0384/Lib/pydoc_data/topics.py
==============================================================================
--- python/branches/pep-0384/Lib/pydoc_data/topics.py	(original)
+++ python/branches/pep-0384/Lib/pydoc_data/topics.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/re.py
==============================================================================
--- python/branches/pep-0384/Lib/re.py	(original)
+++ python/branches/pep-0384/Lib/re.py	Fri Aug 27 21:11:11 2010
@@ -118,6 +118,7 @@
 import sys
 import sre_compile
 import sre_parse
+import functools
 
 # public symbols
 __all__ = [ "match", "search", "sub", "subn", "split", "findall",
@@ -205,9 +206,9 @@
     return _compile(pattern, flags)
 
 def purge():
-    "Clear the regular expression cache"
-    _cache.clear()
-    _cache_repl.clear()
+    "Clear the regular expression caches"
+    _compile_typed.clear()
+    _compile_repl.clear()
 
 def template(pattern, flags=0):
     "Compile a template pattern, returning a pattern object"
@@ -249,20 +250,14 @@
 # --------------------------------------------------------------------
 # internals
 
-_cache = {}
-_cache_repl = {}
-
 _pattern_type = type(sre_compile.compile("", 0))
 
-_MAXCACHE = 100
+def _compile(pattern, flags):
+    return _compile_typed(type(pattern), pattern, flags)
 
-def _compile(*key):
+ at functools.lru_cache(maxsize=500)
+def _compile_typed(text_bytes_type, pattern, flags):
     # internal: compile pattern
-    cachekey = (type(key[0]),) + key
-    p = _cache.get(cachekey)
-    if p is not None:
-        return p
-    pattern, flags = key
     if isinstance(pattern, _pattern_type):
         if flags:
             raise ValueError(
@@ -270,23 +265,12 @@
         return pattern
     if not sre_compile.isstring(pattern):
         raise TypeError("first argument must be string or compiled pattern")
-    p = sre_compile.compile(pattern, flags)
-    if len(_cache) >= _MAXCACHE:
-        _cache.clear()
-    _cache[cachekey] = p
-    return p
+    return sre_compile.compile(pattern, flags)
 
-def _compile_repl(*key):
+ at functools.lru_cache(maxsize=500)
+def _compile_repl(repl, pattern):
     # internal: compile replacement pattern
-    p = _cache_repl.get(key)
-    if p is not None:
-        return p
-    repl, pattern = key
-    p = sre_parse.parse_template(repl, pattern)
-    if len(_cache_repl) >= _MAXCACHE:
-        _cache_repl.clear()
-    _cache_repl[key] = p
-    return p
+    return sre_parse.parse_template(repl, pattern)
 
 def _expand(pattern, match, template):
     # internal: match.expand implementation hook

Modified: python/branches/pep-0384/Lib/site.py
==============================================================================
--- python/branches/pep-0384/Lib/site.py	(original)
+++ python/branches/pep-0384/Lib/site.py	Fri Aug 27 21:11:11 2010
@@ -107,18 +107,6 @@
     sys.path[:] = L
     return known_paths
 
-# XXX This should not be part of site.py, since it is needed even when
-# using the -S option for Python.  See http://www.python.org/sf/586680
-def addbuilddir():
-    """Append ./build/lib.<platform> in case we're running in the build dir
-    (especially for Guido :-)"""
-    from sysconfig import get_platform
-    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
-    if hasattr(sys, 'gettotalrefcount'):
-        s += '-pydebug'
-    s = os.path.join(os.path.dirname(sys.path.pop()), s)
-    sys.path.append(s)
-
 
 def _init_pathinfo():
     """Return a set containing all existing directory entries from sys.path"""
@@ -295,7 +283,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"))
@@ -529,9 +517,6 @@
 
     abs_paths()
     known_paths = removeduppaths()
-    if (os.name == "posix" and sys.path and
-        os.path.basename(sys.path[-1]) == "Modules"):
-        addbuilddir()
     if ENABLE_USER_SITE is None:
         ENABLE_USER_SITE = check_enableusersite()
     known_paths = addusersitepackages(known_paths)

Modified: python/branches/pep-0384/Lib/smtpd.py
==============================================================================
--- python/branches/pep-0384/Lib/smtpd.py	(original)
+++ python/branches/pep-0384/Lib/smtpd.py	Fri Aug 27 21:11:11 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,165 @@
 
     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()
+        try:
+            self.peer = conn.getpeername()
+        except socket.error as err:
+            # a race condition  may occur if the other end is closing
+            # before we can get the peername
+            self.close()
+            if err.args[0] != errno.ENOTCONN:
+                raise
+            return
+        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 +288,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 +299,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 +318,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 +355,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 +380,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
@@ -289,9 +422,22 @@
                 localaddr, remoteaddr), file=DEBUGSTREAM)
 
     def handle_accept(self):
-        conn, addr = self.accept()
+        try:
+            conn, addr = self.accept()
+        except TypeError:
+            # sometimes accept() might return None
+            return
+        except socket.error as err:
+            # ECONNABORTED might be thrown
+            if err.args[0] != errno.ECONNABORTED:
+                raise
+            return
+        else:
+            # sometimes addr == None instead of (ip, port)
+            if addr == None:
+                return
         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/pep-0384/Lib/smtplib.py
==============================================================================
--- python/branches/pep-0384/Lib/smtplib.py	(original)
+++ python/branches/pep-0384/Lib/smtplib.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/ssl.py
==============================================================================
--- python/branches/pep-0384/Lib/ssl.py	(original)
+++ python/branches/pep-0384/Lib/ssl.py	Fri Aug 27 21:11:11 2010
@@ -79,7 +79,6 @@
 
 from socket import getnameinfo as _getnameinfo
 from socket import error as socket_error
-from socket import dup as _dup
 from socket import socket, AF_INET, SOCK_STREAM
 import base64        # for DER-to-PEM translation
 import traceback
@@ -148,7 +147,7 @@
                             family=sock.family,
                             type=sock.type,
                             proto=sock.proto,
-                            fileno=_dup(sock.fileno()))
+                            fileno=sock.fileno())
             self.settimeout(sock.gettimeout())
             # see if it's connected
             try:
@@ -158,7 +157,7 @@
                     raise
             else:
                 connected = True
-            sock.close()
+            sock.detach()
         elif fileno is not None:
             socket.__init__(self, fileno=fileno)
         else:

Modified: python/branches/pep-0384/Lib/string.py
==============================================================================
--- python/branches/pep-0384/Lib/string.py	(original)
+++ python/branches/pep-0384/Lib/string.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/subprocess.py
==============================================================================
--- python/branches/pep-0384/Lib/subprocess.py	(original)
+++ python/branches/pep-0384/Lib/subprocess.py	Fri Aug 27 21:11:11 2010
@@ -853,7 +853,7 @@
                 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
                 startupinfo.wShowWindow = _subprocess.SW_HIDE
                 comspec = os.environ.get("COMSPEC", "cmd.exe")
-                args = comspec + " /c " + args
+                args = '{} /c "{}"'.format (comspec, args)
                 if (_subprocess.GetVersion() >= 0x80000000 or
                         os.path.basename(comspec).lower() == "command.com"):
                     # Win9x, or using command.com on NT. We need to
@@ -886,6 +886,19 @@
                 # translate errno using _sys_errlist (or simliar), but
                 # how can this be done from Python?
                 raise WindowsError(*e.args)
+            finally:
+                # Child is launched. Close the parent's copy of those pipe
+                # handles that only the child should have open.  You need
+                # to make sure that no handles to the write end of the
+                # output pipe are maintained in this process or else the
+                # pipe will not close when the child process exits and the
+                # ReadFile will hang.
+                if p2cread != -1:
+                    p2cread.Close()
+                if c2pwrite != -1:
+                    c2pwrite.Close()
+                if errwrite != -1:
+                    errwrite.Close()
 
             # Retain the process handle, but close the thread handle
             self._child_created = True
@@ -893,20 +906,6 @@
             self.pid = pid
             ht.Close()
 
-            # Child is launched. Close the parent's copy of those pipe
-            # handles that only the child should have open.  You need
-            # to make sure that no handles to the write end of the
-            # output pipe are maintained in this process or else the
-            # pipe will not close when the child process exits and the
-            # ReadFile will hang.
-            if p2cread != -1:
-                p2cread.Close()
-            if c2pwrite != -1:
-                c2pwrite.Close()
-            if errwrite != -1:
-                errwrite.Close()
-
-
         def _internal_poll(self, _deadstate=None,
                 _WaitForSingleObject=_subprocess.WaitForSingleObject,
                 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,

Modified: python/branches/pep-0384/Lib/sysconfig.py
==============================================================================
--- python/branches/pep-0384/Lib/sysconfig.py	(original)
+++ python/branches/pep-0384/Lib/sysconfig.py	Fri Aug 27 21:11:11 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")

Modified: python/branches/pep-0384/Lib/test/formatfloat_testcases.txt
==============================================================================
--- python/branches/pep-0384/Lib/test/formatfloat_testcases.txt	(original)
+++ python/branches/pep-0384/Lib/test/formatfloat_testcases.txt	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/regrtest.py
==============================================================================
--- python/branches/pep-0384/Lib/test/regrtest.py	(original)
+++ python/branches/pep-0384/Lib/test/regrtest.py	Fri Aug 27 21:11:11 2010
@@ -187,14 +187,6 @@
         module.__file__ = os.path.abspath(module.__file__)
 
 
-# Ignore ImportWarnings that only occur in the source tree,
-# (because of modules with the same name as source-directories in Modules/)
-for mod in ("ctypes", "gzip", "zipfile", "tarfile", "encodings.zlib_codec",
-            "test.test_zipimport", "test.test_zlib", "test.test_zipfile",
-            "test.test_codecs", "test.string_tests"):
-    warnings.filterwarnings(module=".*%s$" % (mod,),
-                            action="ignore", category=ImportWarning)
-
 # MacOSX (a.k.a. Darwin) has a default stack size that is too small
 # for deeply recursive regular expressions.  We see this as crashes in
 # the Python test suite when running test_re.py and test_sre.py.  The
@@ -224,6 +216,7 @@
 RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network',
                   'decimal', 'compiler', 'subprocess', 'urlfetch', 'gui')
 
+TEMPDIR = os.path.abspath(tempfile.gettempdir())
 
 def usage(msg):
     print(msg, file=sys.stderr)
@@ -390,7 +383,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!")
@@ -423,7 +416,7 @@
             found_garbage = []
 
     if single:
-        filename = 'pynexttest'
+        filename = os.path.join(TEMPDIR, 'pynexttest')
         try:
             fp = open(filename, 'r')
             next_test = fp.read().strip()
@@ -455,10 +448,11 @@
         args = []
 
     # For a partial run, we do not need to clutter the output.
-    if verbose or not (quiet or tests or args):
+    if verbose or not (quiet or single or tests or args):
         # Print basic platform information
         print("==", platform.python_implementation(), *sys.version.split())
-        print("==  ", platform.platform(aliased=True))
+        print("==  ", platform.platform(aliased=True),
+                      "%s-endian" % sys.byteorder)
         print("==  ", os.getcwd())
 
     alltests = findtests(testdir, stdtests, nottests)
@@ -514,8 +508,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:
@@ -549,7 +547,8 @@
                     popen = Popen([sys.executable, '-E', '-m', 'test.regrtest',
                                    '--slaveargs', json.dumps(args_tuple)],
                                    stdout=PIPE, stderr=PIPE,
-                                   universal_newlines=True, close_fds=True)
+                                   universal_newlines=True,
+                                   close_fds=(os.name != 'nt'))
                     stdout, stderr = popen.communicate()
                     # Strip last refcount output line if it exists, since it
                     # comes from the shutdown of the interpreter in the subcommand.
@@ -559,8 +558,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 +566,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 +584,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
@@ -812,7 +815,7 @@
 
     resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
                  'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
-                 'warnings.filters')
+                 'warnings.filters', 'asyncore.socket_map')
 
     def get_sys_argv(self):
         return id(sys.argv), sys.argv, sys.argv[:]
@@ -870,6 +873,15 @@
         warnings.filters = saved_filters[1]
         warnings.filters[:] = saved_filters[2]
 
+    def get_asyncore_socket_map(self):
+        asyncore = sys.modules.get('asyncore')
+        return asyncore and asyncore.socket_map or {}
+    def restore_asyncore_socket_map(self, saved_map):
+        asyncore = sys.modules.get('asyncore')
+        if asyncore is not None:
+            asyncore.socket_map.clear()
+            asyncore.socket_map.update(saved_map)
+
     def resource_info(self):
         for name in self.resources:
             method_suffix = name.replace('.', '_')
@@ -1453,18 +1465,17 @@
     # to keep the test files in a subfolder.  It eases the cleanup of leftover
     # files using command "make distclean".
     if sysconfig.is_python_build():
-        parent_dir = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
-        if not os.path.exists(parent_dir):
-            os.mkdir(parent_dir)
-    else:
-        parent_dir = os.path.abspath(tempfile.gettempdir())
+        TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
+        TEMPDIR = os.path.abspath(TEMPDIR)
+        if not os.path.exists(TEMPDIR):
+            os.mkdir(TEMPDIR)
 
     # Define a writable temp dir that will be used as cwd while running
     # the tests. The name of the dir includes the pid to allow parallel
     # testing (see the -j option).
     TESTCWD = 'test_python_{}'.format(os.getpid())
 
-    TESTCWD = os.path.join(parent_dir, TESTCWD)
+    TESTCWD = os.path.join(TEMPDIR, TESTCWD)
 
     # Run the tests in a context manager that temporary changes the CWD to a
     # temporary and writable directory. If it's not possible to create or

Modified: python/branches/pep-0384/Lib/test/script_helper.py
==============================================================================
--- python/branches/pep-0384/Lib/test/script_helper.py	(original)
+++ python/branches/pep-0384/Lib/test/script_helper.py	Fri Aug 27 21:11:11 2010
@@ -79,16 +79,16 @@
             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()
     #    zip_file.close()
     return zip_name, os.path.join(zip_name, name_in_zip)
 
-def make_pkg(pkg_dir):
+def make_pkg(pkg_dir, init_source=''):
     os.mkdir(pkg_dir)
-    make_script(pkg_dir, '__init__', '')
+    make_script(pkg_dir, '__init__', init_source)
 
 def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
                  source, depth=1, compiled=False):
@@ -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/pep-0384/Lib/test/sortperf.py
==============================================================================
--- python/branches/pep-0384/Lib/test/sortperf.py	(original)
+++ python/branches/pep-0384/Lib/test/sortperf.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/support.py
==============================================================================
--- python/branches/pep-0384/Lib/test/support.py	(original)
+++ python/branches/pep-0384/Lib/test/support.py	Fri Aug 27 21:11:11 2010
@@ -377,54 +377,78 @@
 TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
 
 
-# Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
-# TESTFN_UNICODE is a filename that can be encoded using the
-# file system encoding, but *not* with the default (ascii) encoding
-TESTFN_UNICODE = TESTFN + "-\xe0\xf2"
+# TESTFN_UNICODE is a non-ascii filename
+TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
+if sys.platform == 'darwin':
+    # In Mac OS X's VFS API file names are, by definition, canonically
+    # decomposed Unicode, encoded using UTF-8. See QA1173:
+    # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
+    import unicodedata
+    TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
 TESTFN_ENCODING = sys.getfilesystemencoding()
-# TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
-# able to be encoded by *either* the default or filesystem encoding.
-# This test really only makes sense on Windows NT platforms
-# which have special Unicode support in posixmodule.
-if (not hasattr(sys, "getwindowsversion") or
-        sys.getwindowsversion()[3] < 2): #  0=win32s or 1=9x/ME
-    TESTFN_UNICODE_UNENCODEABLE = None
-else:
-    # Japanese characters (I think - from bug 846133)
-    TESTFN_UNICODE_UNENCODEABLE = TESTFN + "-\u5171\u6709\u3055\u308c\u308b"
+
+# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
+# encoded by the filesystem encoding (in strict mode). It can be None if we
+# cannot generate such filename.
+TESTFN_UNENCODABLE = None
+if os.name in ('nt', 'ce'):
+    # skip win32s (0) or Windows 9x/ME (1)
+    if sys.getwindowsversion().platform >= 2:
+        # Japanese characters (I think - from bug 846133)
+        TESTFN_UNENCODABLE = TESTFN + "-\u5171\u6709\u3055\u308c\u308b"
+        try:
+            TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
+        except UnicodeEncodeError:
+            pass
+        else:
+            print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
+                  'Unicode filename tests may not be effective'
+                  % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
+            TESTFN_UNENCODABLE = None
+# Mac OS X denies unencodable filenames (invalid utf-8)
+elif sys.platform != 'darwin':
     try:
-        # XXX - Note - should be using TESTFN_ENCODING here - but for
-        # Windows, "mbcs" currently always operates as if in
-        # errors=ignore' mode - hence we get '?' characters rather than
-        # the exception.  'Latin1' operates as we expect - ie, fails.
-        # See [ 850997 ] mbcs encoding ignores errors
-        TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
-    except UnicodeEncodeError:
-        pass
+        # ascii and utf-8 cannot encode the byte 0xff
+        b'\xff'.decode(TESTFN_ENCODING)
+    except UnicodeDecodeError:
+        # 0xff will be encoded using the surrogate character u+DCFF
+        TESTFN_UNENCODABLE = TESTFN \
+            + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
     else:
-        print('WARNING: The filename %r CAN be encoded by the filesystem.  '
-              'Unicode filename tests may not be effective'
-              % TESTFN_UNICODE_UNENCODEABLE)
+        # File system encoding (eg. ISO-8859-* encodings) can encode
+        # the byte 0xff. Skip some unicode filename tests.
+        pass
 
 # Save the initial cwd
 SAVEDCWD = os.getcwd()
 
 @contextlib.contextmanager
-def temp_cwd(name='tempcwd', quiet=False):
+def temp_cwd(name='tempcwd', quiet=False, path=None):
     """
-    Context manager that creates a temporary directory and set it as CWD.
+    Context manager that temporarily changes the CWD.
 
-    The new CWD is created in the current directory and it's named *name*.
-    If *quiet* is False (default) and it's not possible to create or change
-    the CWD, an error is raised.  If it's True, only a warning is raised
-    and the original CWD is used.
+    An existing path may be provided as *path*, in which case this
+    function makes no changes to the file system.
+
+    Otherwise, the new CWD is created in the current directory and it's
+    named *name*. If *quiet* is False (default) and it's not possible to
+    create or change the CWD, an error is raised.  If it's True, only a
+    warning is raised and the original CWD is used.
     """
     saved_dir = os.getcwd()
     is_temporary = False
+    if path is None:
+        path = name
+        try:
+            os.mkdir(name)
+            is_temporary = True
+        except OSError:
+            if not quiet:
+                raise
+            warnings.warn('tests may fail, unable to create temp CWD ' + name,
+                          RuntimeWarning, stacklevel=3)
     try:
-        os.mkdir(name)
-        os.chdir(name)
-        is_temporary = True
+        os.chdir(path)
     except OSError:
         if not quiet:
             raise
@@ -1243,3 +1267,21 @@
             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
+
+def workaroundIssue8611():
+    try:
+        sys.executable.encode('ascii')
+    except UnicodeEncodeError:
+        raise unittest.SkipTest(
+            "Issue #8611: Python doesn't support ascii locale encoding "
+            "with an non-ascii path")

Deleted: python/branches/pep-0384/Lib/test/test_SimpleHTTPServer.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_SimpleHTTPServer.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_abc.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_abc.py	(original)
+++ python/branches/pep-0384/Lib/test/test_abc.py	Fri Aug 27 21:11:11 2010
@@ -15,16 +15,16 @@
     def test_abstractmethod_basics(self):
         @abc.abstractmethod
         def foo(self): pass
-        self.assertEqual(foo.__isabstractmethod__, True)
+        self.assertTrue(foo.__isabstractmethod__)
         def bar(self): pass
-        self.assertEqual(hasattr(bar, "__isabstractmethod__"), False)
+        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
 
     def test_abstractproperty_basics(self):
         @abc.abstractproperty
         def foo(self): pass
-        self.assertEqual(foo.__isabstractmethod__, True)
+        self.assertTrue(foo.__isabstractmethod__)
         def bar(self): pass
-        self.assertEqual(hasattr(bar, "__isabstractmethod__"), False)
+        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
 
         class C(metaclass=abc.ABCMeta):
             @abc.abstractproperty
@@ -34,8 +34,46 @@
             def foo(self): return super().foo
         self.assertEqual(D().foo, 3)
 
+    def test_abstractclassmethod_basics(self):
+        @abc.abstractclassmethod
+        def foo(cls): pass
+        self.assertTrue(foo.__isabstractmethod__)
+        @classmethod
+        def bar(cls): pass
+        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
+
+        class C(metaclass=abc.ABCMeta):
+            @abc.abstractclassmethod
+            def foo(cls): return cls.__name__
+        self.assertRaises(TypeError, C)
+        class D(C):
+            @classmethod
+            def foo(cls): return super().foo()
+        self.assertEqual(D.foo(), 'D')
+        self.assertEqual(D().foo(), 'D')
+
+    def test_abstractstaticmethod_basics(self):
+        @abc.abstractstaticmethod
+        def foo(): pass
+        self.assertTrue(foo.__isabstractmethod__)
+        @staticmethod
+        def bar(): pass
+        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
+
+        class C(metaclass=abc.ABCMeta):
+            @abc.abstractstaticmethod
+            def foo(): return 3
+        self.assertRaises(TypeError, C)
+        class D(C):
+            @staticmethod
+            def foo(): return 4
+        self.assertEqual(D.foo(), 4)
+        self.assertEqual(D().foo(), 4)
+
     def test_abstractmethod_integration(self):
-        for abstractthing in [abc.abstractmethod, abc.abstractproperty]:
+        for abstractthing in [abc.abstractmethod, abc.abstractproperty,
+                              abc.abstractclassmethod,
+                              abc.abstractstaticmethod]:
             class C(metaclass=abc.ABCMeta):
                 @abstractthing
                 def foo(self): pass  # abstract
@@ -60,34 +98,26 @@
             self.assertRaises(TypeError, F)  # because bar is abstract now
             self.assertTrue(isabstract(F))
 
-    def test_subclass_oldstyle_class(self):
-        class A:
-            __metaclass__ = abc.ABCMeta
-        class OldstyleClass:
-            pass
-        self.assertFalse(issubclass(OldstyleClass, A))
-        self.assertFalse(issubclass(A, OldstyleClass))
-
     def test_registration_basics(self):
         class A(metaclass=abc.ABCMeta):
             pass
         class B(object):
             pass
         b = B()
-        self.assertEqual(issubclass(B, A), False)
-        self.assertEqual(issubclass(B, (A,)), False)
+        self.assertFalse(issubclass(B, A))
+        self.assertFalse(issubclass(B, (A,)))
         self.assertNotIsInstance(b, A)
         self.assertNotIsInstance(b, (A,))
         A.register(B)
-        self.assertEqual(issubclass(B, A), True)
-        self.assertEqual(issubclass(B, (A,)), True)
+        self.assertTrue(issubclass(B, A))
+        self.assertTrue(issubclass(B, (A,)))
         self.assertIsInstance(b, A)
         self.assertIsInstance(b, (A,))
         class C(B):
             pass
         c = C()
-        self.assertEqual(issubclass(C, A), True)
-        self.assertEqual(issubclass(C, (A,)), True)
+        self.assertTrue(issubclass(C, A))
+        self.assertTrue(issubclass(C, (A,)))
         self.assertIsInstance(c, A)
         self.assertIsInstance(c, (A,))
 
@@ -97,11 +127,11 @@
         class B:
             pass
         b = B()
-        self.assertEqual(isinstance(b, A), False)
-        self.assertEqual(isinstance(b, (A,)), False)
+        self.assertFalse(isinstance(b, A))
+        self.assertFalse(isinstance(b, (A,)))
         A.register(B)
-        self.assertEqual(isinstance(b, A), True)
-        self.assertEqual(isinstance(b, (A,)), True)
+        self.assertTrue(isinstance(b, A))
+        self.assertTrue(isinstance(b, (A,)))
 
     def test_registration_builtins(self):
         class A(metaclass=abc.ABCMeta):
@@ -109,18 +139,18 @@
         A.register(int)
         self.assertIsInstance(42, A)
         self.assertIsInstance(42, (A,))
-        self.assertEqual(issubclass(int, A), True)
-        self.assertEqual(issubclass(int, (A,)), True)
+        self.assertTrue(issubclass(int, A))
+        self.assertTrue(issubclass(int, (A,)))
         class B(A):
             pass
         B.register(str)
         class C(str): pass
         self.assertIsInstance("", A)
         self.assertIsInstance("", (A,))
-        self.assertEqual(issubclass(str, A), True)
-        self.assertEqual(issubclass(str, (A,)), True)
-        self.assertEqual(issubclass(C, A), True)
-        self.assertEqual(issubclass(C, (A,)), True)
+        self.assertTrue(issubclass(str, A))
+        self.assertTrue(issubclass(str, (A,)))
+        self.assertTrue(issubclass(C, A))
+        self.assertTrue(issubclass(C, (A,)))
 
     def test_registration_edge_cases(self):
         class A(metaclass=abc.ABCMeta):

Modified: python/branches/pep-0384/Lib/test/test_argparse.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_argparse.py	(original)
+++ python/branches/pep-0384/Lib/test/test_argparse.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_asyncore.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_asyncore.py	(original)
+++ python/branches/pep-0384/Lib/test/test_asyncore.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_binascii.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_binascii.py	(original)
+++ python/branches/pep-0384/Lib/test/test_binascii.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_binop.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_binop.py	(original)
+++ python/branches/pep-0384/Lib/test/test_binop.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_builtin.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_builtin.py	(original)
+++ python/branches/pep-0384/Lib/test/test_builtin.py	Fri Aug 27 21:11:11 2010
@@ -2,12 +2,16 @@
 
 import platform
 import unittest
+import sys
+import warnings
+import collections
+import io
+import types
+import builtins
+import random
 from test.support import fcmp, TESTFN, unlink,  run_unittest, check_warnings
 from operator import neg
 
-import sys, warnings, random, collections, io
-
-import builtins
 
 class Squares:
 
@@ -243,7 +247,6 @@
         self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
 
     def test_delattr(self):
-        import sys
         sys.spam = 1
         delattr(sys, 'spam')
         self.assertRaises(TypeError, delattr)
@@ -257,11 +260,9 @@
         self.assertIn('local_var', dir())
 
         # dir(module)
-        import sys
         self.assertIn('exit', dir(sys))
 
         # dir(module_with_invalid__dict__)
-        import types
         class Foo(types.ModuleType):
             __dict__ = 8
         f = Foo("foo")
@@ -480,7 +481,6 @@
         self.assertRaises(TypeError, list, filter(42, (1, 2)))
 
     def test_getattr(self):
-        import sys
         self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
         self.assertRaises(TypeError, getattr, sys, 1)
         self.assertRaises(TypeError, getattr, sys, 1, "foo")
@@ -490,21 +490,21 @@
         self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
 
     def test_hasattr(self):
-        import sys
         self.assertTrue(hasattr(sys, 'stdout'))
         self.assertRaises(TypeError, hasattr, sys, 1)
         self.assertRaises(TypeError, hasattr)
         self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
 
-        # Check that hasattr allows SystemExit and KeyboardInterrupts by
+        # Check that hasattr propagates all exceptions outside of
+        # AttributeError.
         class A:
             def __getattr__(self, what):
-                raise KeyboardInterrupt
-        self.assertRaises(KeyboardInterrupt, hasattr, A(), "b")
+                raise SystemExit
+        self.assertRaises(SystemExit, hasattr, A(), "b")
         class B:
             def __getattr__(self, what):
-                raise SystemExit
-        self.assertRaises(SystemExit, hasattr, B(), "b")
+                raise ValueError
+        self.assertRaises(ValueError, hasattr, B(), "b")
 
     def test_hash(self):
         hash(None)
@@ -1206,7 +1206,6 @@
 
     def test_vars(self):
         self.assertEqual(set(vars()), set(dir()))
-        import sys
         self.assertEqual(set(vars(sys)), set(dir(sys)))
         self.assertEqual(self.get_vars_f0(), {})
         self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
@@ -1234,6 +1233,7 @@
         class G:
             pass
         self.assertRaises(TypeError, zip, a, G())
+        self.assertRaises(RuntimeError, zip, a, TestFailingIter())
 
         # Make sure zip doesn't try to allocate a billion elements for the
         # result list when one of its arguments doesn't say how long it is.

Modified: python/branches/pep-0384/Lib/test/test_bytes.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_bytes.py	(original)
+++ python/branches/pep-0384/Lib/test/test_bytes.py	Fri Aug 27 21:11:11 2010
@@ -220,8 +220,10 @@
             self.assertRaises(TypeError, lambda: b * 3.14)
             self.assertRaises(TypeError, lambda: 3.14 * b)
             # XXX Shouldn't bytes and bytearray agree on what to raise?
-            self.assertRaises((OverflowError, MemoryError),
-                              lambda: b * sys.maxsize)
+            with self.assertRaises((OverflowError, MemoryError)):
+                c = b * sys.maxsize
+            with self.assertRaises((OverflowError, MemoryError)):
+                b *= sys.maxsize
 
     def test_repeat_1char(self):
         self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100))

Modified: python/branches/pep-0384/Lib/test/test_bz2.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_bz2.py	(original)
+++ python/branches/pep-0384/Lib/test/test_bz2.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_calendar.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_calendar.py	(original)
+++ python/branches/pep-0384/Lib/test/test_calendar.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_cfgparser.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_cfgparser.py	(original)
+++ python/branches/pep-0384/Lib/test/test_cfgparser.py	Fri Aug 27 21:11:11 2010
@@ -1,7 +1,9 @@
+import collections
 import configparser
 import io
+import os
 import unittest
-import collections
+import textwrap
 
 from test import support
 
@@ -22,60 +24,44 @@
     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
+    strict = False
 
     def newconfig(self, defaults=None):
-        if defaults is None:
-            self.cf = self.config_class(allow_no_value=self.allow_no_value)
-        else:
-            self.cf = self.config_class(defaults,
-                                        allow_no_value=self.allow_no_value)
-        return self.cf
+        arguments = dict(
+            defaults=defaults,
+            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,
+            strict=self.strict,
+        )
+        return self.config_class(**arguments)
 
     def fromstring(self, string, defaults=None):
         cf = self.newconfig(defaults)
-        sio = io.StringIO(string)
-        cf.readfp(sio)
+        cf.read_string(string)
         return cf
 
-    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"
-            )
-        if self.allow_no_value:
-            config_string += (
-                "[NoValue]\n"
-                "option-without-value\n"
-                )
+class BasicTestCase(CfgParserTestCaseClass):
 
-        cf = self.fromstring(config_string)
+    def basic_test(self, cf):
         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 +74,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,12 +96,132 @@
                     "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.')
 
+    def test_basic(self):
+        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"
+                "option-without-value\n"
+                )
+        cf = self.fromstring(config_string)
+        self.basic_test(cf)
+        if self.strict:
+            with self.assertRaises(configparser.DuplicateOptionError):
+                cf.read_string(textwrap.dedent("""\
+                    [Duplicate Options Here]
+                    option {0[0]} with a value
+                    option {0[1]} with another value
+                """.format(self.delimiters)))
+            with self.assertRaises(configparser.DuplicateSectionError):
+                cf.read_string(textwrap.dedent("""\
+                    [And Now For Something]
+                    completely different {0[0]} True
+                    [And Now For Something]
+                    the larch {0[1]} 1
+                """.format(self.delimiters)))
+        else:
+            cf.read_string(textwrap.dedent("""\
+                [Duplicate Options Here]
+                option {0[0]} with a value
+                option {0[1]} with another value
+            """.format(self.delimiters)))
+
+            cf.read_string(textwrap.dedent("""\
+                [And Now For Something]
+                completely different {0[0]} True
+                [And Now For Something]
+                the larch {0[1]} 1
+            """.format(self.delimiters)))
+
+    def test_basic_from_dict(self):
+        config = {
+            "Foo Bar": {
+                "foo": "bar",
+            },
+            "Spacey Bar": {
+                "foo": "bar",
+            },
+            "Spacey Bar From The Beginning": {
+                "foo": "bar",
+                "baz": "qwe",
+            },
+            "Commented Bar": {
+                "foo": "bar",
+                "baz": "qwe",
+            },
+            "Long Line": {
+                "foo": "this line is much, much longer than my editor\nlikes "
+                       "it.",
+            },
+            "Section\\with$weird%characters[\t": {
+            },
+            "Internationalized Stuff": {
+                "foo[bg]": "Bulgarian",
+                "foo": "Default",
+                "foo[en]": "English",
+                "foo[de]": "Deutsch",
+            },
+            "Spaces": {
+                "key with spaces": "value",
+                "another with spaces": "splat!",
+            }
+        }
+        if self.allow_no_value:
+            config.update({
+                "NoValue": {
+                    "option-without-value": None,
+                }
+            })
+        cf = self.newconfig()
+        cf.read_dict(config)
+        self.basic_test(cf)
+        if self.strict:
+            with self.assertRaises(configparser.DuplicateOptionError):
+                cf.read_dict({
+                    "Duplicate Options Here": {
+                        'option': 'with a value',
+                        'OPTION': 'with another value',
+                    },
+                })
+        else:
+            cf.read_dict({
+                "Duplicate Options Here": {
+                    'option': 'with a value',
+                    'OPTION': 'with another value',
+                },
+            })
+
+
     def test_case_sensitivity(self):
         cf = self.newconfig()
         cf.add_section("A")
@@ -138,12 +247,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"))
 
@@ -159,39 +270,47 @@
             "could not locate option, expecting case-insensitive defaults")
 
     def test_parse_errors(self):
-        self.newconfig()
-        self.parse_error(configparser.ParsingError,
-                         "[Foo]\n  extra-spaces: splat\n")
-        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")
+        cf = self.newconfig()
+        self.parse_error(cf, configparser.ParsingError,
+                         "[Foo]\n"
+                         "{}val-without-opt-name\n".format(self.delimiters[0]))
+        self.parse_error(cf, configparser.ParsingError,
+                         "[Foo]\n"
+                         "{}val-without-opt-name\n".format(self.delimiters[1]))
+        e = self.parse_error(cf, configparser.MissingSectionHeaderError,
+                             "No Section!\n")
+        self.assertEqual(e.args, ('<???>', 1, "No Section!\n"))
+        if not self.allow_no_value:
+            e = self.parse_error(cf, configparser.ParsingError,
+                                "[Foo]\n  wrong-indent\n")
+            self.assertEqual(e.args, ('<???>',))
 
-    def parse_error(self, exc, src):
+    def parse_error(self, cf, exc, src):
         sio = io.StringIO(src)
-        self.assertRaises(exc, self.cf.readfp, sio)
+        with self.assertRaises(exc) as cm:
+            cf.read_file(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(cf, configparser.NoSectionError, "foo", "bar")
+        self.assertEqual(e.args, ("foo",))
         cf.add_section("foo")
-        self.get_error(configparser.NoOptionError, "foo", "bar")
+        e = self.get_error(cf, configparser.NoOptionError, "foo", "bar")
+        self.assertEqual(e.args, ("bar", "foo"))
 
-    def get_error(self, exc, section, option):
+    def get_error(self, cf, exc, section, option):
         try:
-            self.cf.get(section, option)
+            cf.get(section, option)
         except exc as e:
             return e
         else:
@@ -201,21 +320,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 +345,48 @@
     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")
+        e = cm.exception
+        self.assertEqual(str(e), "Section 'Foo' already exists")
+        self.assertEqual(e.args, ("Foo", None, None))
+
+        if self.strict:
+            with self.assertRaises(configparser.DuplicateSectionError) as cm:
+                cf.read_string(textwrap.dedent("""\
+                    [Foo]
+                    will this be added{equals}True
+                    [Bar]
+                    what about this{equals}True
+                    [Foo]
+                    oops{equals}this won't
+                """.format(equals=self.delimiters[0])), source='<foo-bar>')
+            e = cm.exception
+            self.assertEqual(str(e), "While reading from <foo-bar> [line  5]: "
+                                     "section 'Foo' already exists")
+            self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))
+
+            with self.assertRaises(configparser.DuplicateOptionError) as cm:
+                cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
+            e = cm.exception
+            self.assertEqual(str(e), "While reading from <dict>: option 'opt' "
+                                     "in section 'Bar' already exists")
+            self.assertEqual(e.args, ("Bar", "opt", "<dict>", None))
 
     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 +399,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 +423,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 +436,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 +463,58 @@
     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 StrictTestCase(BasicTestCase):
+    config_class = configparser.RawConfigParser
+    strict = True
+
+
+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 +523,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(cf, configparser.InterpolationDepthError, "Foo", "bar11")
+        self.assertEqual(e.args, ("bar11", "Foo", rawval[self.config_class]))
 
     def test_interpolation_missing_value(self):
-        self.get_interpolation_config()
-        e = self.get_error(configparser.InterpolationError,
+        rawval = {
+            configparser.ConfigParser: '%(reference)s',
+            configparser.SafeConfigParser: '',
+        }
+        cf = self.get_interpolation_config()
+        e = self.get_error(cf, 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 +568,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.read_file(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 +634,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 +663,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 +689,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,26 +707,67 @@
         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"
-                        "o4=1\n"
-                        "o3=2\n"
-                        "o2=3\n"
-                        "o1=4\n"
-                        "[a]\n"
-                        "k=v\n")
+        cf = self.fromstring("[b]\n"
+                             "o4=1\n"
+                             "o3=2\n"
+                             "o2=3\n"
+                             "o1=4\n"
+                             "[a]\n"
+                             "k=v\n")
         output = io.StringIO()
-        self.cf.write(output)
+        cf.write(output)
         self.assertEquals(output.getvalue(),
                           "[a]\n"
                           "k = v\n\n"
@@ -507,13 +778,41 @@
                           "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,
+        StrictTestCase,
+        CompatibleTestCase,
         )
 
 

Modified: python/branches/pep-0384/Lib/test/test_cmd.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_cmd.py	(original)
+++ python/branches/pep-0384/Lib/test/test_cmd.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_cmd_line.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_cmd_line.py	(original)
+++ python/branches/pep-0384/Lib/test/test_cmd_line.py	Fri Aug 27 21:11:11 2010
@@ -1,5 +1,5 @@
 # Tests invocation of the interpreter with various command line arguments
-# All tests are executed with environment variables ignored
+# Most tests are executed with environment variables ignored
 # See test_cmd_line_script.py for testing of script execution
 
 import test.support, unittest
@@ -7,10 +7,6 @@
 import sys
 from test.script_helper import spawn_python, kill_python, python_exit_code
 
-# XXX (ncoghlan): there are assorted gratuitous inconsistencies between the
-# support code in the Py3k version and the 2.x version that unnecessarily
-# complicate test suite merges. See issue 7331
-
 # spawn_python normally enforces use of -E to avoid environmental effects
 # but one test checks PYTHONPATH behaviour explicitly
 # XXX (ncoghlan): Give script_helper.spawn_python an option to switch

Modified: python/branches/pep-0384/Lib/test/test_cmd_line_script.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_cmd_line_script.py	(original)
+++ python/branches/pep-0384/Lib/test/test_cmd_line_script.py	Fri Aug 27 21:11:11 2010
@@ -5,12 +5,12 @@
 import os.path
 import py_compile
 
-import test.support
+from test import support
 from test.script_helper import (
     make_pkg, make_script, make_zip_pkg, make_zip_script, run_python,
     temp_dir)
 
-verbose = test.support.verbose
+verbose = support.verbose
 
 test_source = """\
 # Script may be run with optimisation enabled, so don't rely on assert
@@ -36,6 +36,10 @@
 import sys
 assertIdentical(globals(), sys.modules[__name__].__dict__)
 print('sys.argv[0]==%r' % sys.argv[0])
+print('sys.path[0]==%r' % sys.path[0])
+# Check the working directory
+import os
+print('cwd==%r' % os.getcwd())
 """
 
 def _make_test_script(script_dir, script_basename, source=test_source):
@@ -65,32 +69,44 @@
     return make_script(script_dir, script_basename, source)
 
 class CmdLineTest(unittest.TestCase):
-    def _check_script(self, script_name, expected_file,
-                            expected_argv0, expected_package,
-                            *cmd_line_switches):
-        run_args = cmd_line_switches + (script_name,)
-        exit_code, data = run_python(*run_args)
-        if verbose:
+    def _check_output(self, script_name, exit_code, data,
+                             expected_file, expected_argv0,
+                             expected_path0, expected_package):
+        if verbose > 1:
             print("Output from test script %r:" % script_name)
             print(data)
         self.assertEqual(exit_code, 0)
         printed_file = '__file__==%r' % expected_file
-        printed_argv0 = 'sys.argv[0]==%r' % expected_argv0
         printed_package = '__package__==%r' % expected_package
-        if verbose:
+        printed_argv0 = 'sys.argv[0]==%r' % expected_argv0
+        printed_path0 = 'sys.path[0]==%r' % expected_path0
+        printed_cwd = 'cwd==%r' % os.getcwd()
+        if verbose > 1:
             print('Expected output:')
             print(printed_file)
             print(printed_package)
             print(printed_argv0)
+            print(printed_cwd)
         self.assertIn(printed_file.encode('utf-8'), data)
         self.assertIn(printed_package.encode('utf-8'), data)
         self.assertIn(printed_argv0.encode('utf-8'), data)
+        self.assertIn(printed_path0.encode('utf-8'), data)
+        self.assertIn(printed_cwd.encode('utf-8'), data)
+
+    def _check_script(self, script_name, expected_file,
+                            expected_argv0, expected_path0,
+                            expected_package,
+                            *cmd_line_switches):
+        run_args = cmd_line_switches + (script_name,)
+        exit_code, data = run_python(*run_args)
+        self._check_output(script_name, exit_code, data, expected_file,
+                           expected_argv0, expected_path0, expected_package)
 
     def _check_import_error(self, script_name, expected_msg,
                             *cmd_line_switches):
         run_args = cmd_line_switches + (script_name,)
         exit_code, data = run_python(*run_args)
-        if verbose:
+        if verbose > 1:
             print('Output from test script %r:' % script_name)
             print(data)
             print('Expected output: %r' % expected_msg)
@@ -99,28 +115,32 @@
     def test_basic_script(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, 'script')
-            self._check_script(script_name, script_name, script_name, None)
+            self._check_script(script_name, script_name, script_name,
+                               script_dir, None)
 
     def test_script_compiled(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, 'script')
-            compiled_name = py_compile.compile(script_name, doraise=True)
+            py_compile.compile(script_name, doraise=True)
             os.remove(script_name)
-            self._check_script(compiled_name, compiled_name,
-                               compiled_name, None)
+            pyc_file = support.make_legacy_pyc(script_name)
+            self._check_script(pyc_file, pyc_file,
+                               pyc_file, script_dir, None)
 
     def test_directory(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
-            self._check_script(script_dir, script_name, script_dir, '')
+            self._check_script(script_dir, script_name, script_dir,
+                               script_dir, '')
 
     def test_directory_compiled(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
-            compiled_name = py_compile.compile(script_name, doraise=True)
+            py_compile.compile(script_name, doraise=True)
             os.remove(script_name)
-            pyc_file = test.support.make_legacy_pyc(script_name)
-            self._check_script(script_dir, pyc_file, script_dir, '')
+            pyc_file = support.make_legacy_pyc(script_name)
+            self._check_script(script_dir, pyc_file, script_dir,
+                               script_dir, '')
 
     def test_directory_error(self):
         with temp_dir() as script_dir:
@@ -131,14 +151,14 @@
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
             zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name)
-            self._check_script(zip_name, run_name, zip_name, '')
+            self._check_script(zip_name, run_name, zip_name, zip_name, '')
 
     def test_zipfile_compiled(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
             compiled_name = py_compile.compile(script_name, doraise=True)
             zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name)
-            self._check_script(zip_name, run_name, zip_name, '')
+            self._check_script(zip_name, run_name, zip_name, zip_name, '')
 
     def test_zipfile_error(self):
         with temp_dir() as script_dir:
@@ -153,19 +173,19 @@
             make_pkg(pkg_dir)
             script_name = _make_test_script(pkg_dir, 'script')
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script')
-            self._check_script(launch_name, script_name, script_name, 'test_pkg')
+            self._check_script(launch_name, script_name, script_name, script_dir, 'test_pkg')
 
     def test_module_in_package_in_zipfile(self):
         with temp_dir() as script_dir:
             zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
-            self._check_script(launch_name, run_name, run_name, 'test_pkg')
+            self._check_script(launch_name, run_name, run_name, zip_name, 'test_pkg')
 
     def test_module_in_subpackage_in_zipfile(self):
         with temp_dir() as script_dir:
             zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
-            self._check_script(launch_name, run_name, run_name, 'test_pkg.test_pkg')
+            self._check_script(launch_name, run_name, run_name, zip_name, 'test_pkg.test_pkg')
 
     def test_package(self):
         with temp_dir() as script_dir:
@@ -174,7 +194,7 @@
             script_name = _make_test_script(pkg_dir, '__main__')
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
             self._check_script(launch_name, script_name,
-                               script_name, 'test_pkg')
+                               script_name, script_dir, 'test_pkg')
 
     def test_package_compiled(self):
         with temp_dir() as script_dir:
@@ -183,10 +203,10 @@
             script_name = _make_test_script(pkg_dir, '__main__')
             compiled_name = py_compile.compile(script_name, doraise=True)
             os.remove(script_name)
-            pyc_file = test.support.make_legacy_pyc(script_name)
+            pyc_file = support.make_legacy_pyc(script_name)
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
             self._check_script(launch_name, pyc_file,
-                               pyc_file, 'test_pkg')
+                               pyc_file, script_dir, 'test_pkg')
 
     def test_package_error(self):
         with temp_dir() as script_dir:
@@ -209,10 +229,53 @@
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
             self._check_import_error(launch_name, msg)
 
+    def test_issue8202(self):
+        # Make sure package __init__ modules see "-m" in sys.argv0 while
+        # searching for the module to execute
+        with temp_dir() as script_dir:
+            with support.temp_cwd(path=script_dir):
+                pkg_dir = os.path.join(script_dir, 'test_pkg')
+                make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
+                script_name = _make_test_script(pkg_dir, 'script')
+                exit_code, data = run_python('-m', 'test_pkg.script')
+                if verbose > 1:
+                    print(data)
+                self.assertEqual(exit_code, 0)
+                expected = "init_argv0==%r" % '-m'
+                self.assertIn(expected.encode('utf-8'), data)
+                self._check_output(script_name, exit_code, data,
+                                   script_name, script_name, '', 'test_pkg')
+
+    def test_issue8202_dash_c_file_ignored(self):
+        # Make sure a "-c" file in the current directory
+        # does not alter the value of sys.path[0]
+        with temp_dir() as script_dir:
+            with support.temp_cwd(path=script_dir):
+                with open("-c", "w") as f:
+                    f.write("data")
+                    exit_code, data = run_python('-c',
+                        'import sys; print("sys.path[0]==%r" % sys.path[0])')
+                    if verbose > 1:
+                        print(data)
+                    self.assertEqual(exit_code, 0)
+                    expected = "sys.path[0]==%r" % ''
+                    self.assertIn(expected.encode('utf-8'), data)
+
+    def test_issue8202_dash_m_file_ignored(self):
+        # Make sure a "-m" file in the current directory
+        # does not alter the value of sys.path[0]
+        with temp_dir() as script_dir:
+            script_name = _make_test_script(script_dir, 'other')
+            with support.temp_cwd(path=script_dir):
+                with open("-m", "w") as f:
+                    f.write("data")
+                    exit_code, data = run_python('-m', 'other')
+                    self._check_output(script_name, exit_code, data,
+                                      script_name, script_name, '', '')
 
 def test_main():
-    test.support.run_unittest(CmdLineTest)
-    test.support.reap_children()
+    support.run_unittest(CmdLineTest)
+    support.reap_children()
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/pep-0384/Lib/test/test_collections.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_collections.py	(original)
+++ python/branches/pep-0384/Lib/test/test_collections.py	Fri Aug 27 21:11:11 2010
@@ -13,7 +13,7 @@
 from collections import Hashable, Iterable, Iterator
 from collections import Sized, Container, Callable
 from collections import Set, MutableSet
-from collections import Mapping, MutableMapping
+from collections import Mapping, MutableMapping, KeysView, ItemsView, UserDict
 from collections import Sequence, MutableSequence
 from collections import ByteString
 
@@ -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):
@@ -516,6 +526,21 @@
         s = MySet([5,43,2,1])
         self.assertEqual(s.pop(), 1)
 
+    def test_issue8750(self):
+        empty = WithSet()
+        full = WithSet(range(10))
+        s = WithSet(full)
+        s -= s
+        self.assertEqual(s, empty)
+        s = WithSet(full)
+        s ^= s
+        self.assertEqual(s, empty)
+        s = WithSet(full)
+        s &= s
+        self.assertEqual(s, full)
+        s |= s
+        self.assertEqual(s, full)
+
     def test_Mapping(self):
         for sample in [dict]:
             self.assertIsInstance(sample(), Mapping)
@@ -538,6 +563,31 @@
         self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
             '__getitem__', '__setitem__', '__delitem__')
 
+    def test_MutableMapping_subclass(self):
+        # Test issue 9214
+        mymap = UserDict()
+        mymap['red'] = 5
+        self.assertIsInstance(mymap.keys(), Set)
+        self.assertIsInstance(mymap.keys(), KeysView)
+        self.assertIsInstance(mymap.items(), Set)
+        self.assertIsInstance(mymap.items(), ItemsView)
+
+        mymap = UserDict()
+        mymap['red'] = 5
+        z = mymap.keys() | {'orange'}
+        self.assertIsInstance(z, set)
+        list(z)
+        mymap['blue'] = 7               # Shouldn't affect 'z'
+        self.assertEqual(sorted(z), ['orange', 'red'])
+
+        mymap = UserDict()
+        mymap['red'] = 5
+        z = mymap.items() | {('orange', 3)}
+        self.assertIsInstance(z, set)
+        list(z)
+        mymap['blue'] = 7               # Shouldn't affect 'z'
+        self.assertEqual(sorted(z), [('orange', 3), ('red', 5)])
+
     def test_Sequence(self):
         for sample in [tuple, list, bytes, str]:
             self.assertIsInstance(sample(), Sequence)

Modified: python/branches/pep-0384/Lib/test/test_complex.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_complex.py	(original)
+++ python/branches/pep-0384/Lib/test/test_complex.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_curses.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_curses.py	(original)
+++ python/branches/pep-0384/Lib/test/test_curses.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_datetime.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_datetime.py	(original)
+++ python/branches/pep-0384/Lib/test/test_datetime.py	Fri Aug 27 21:11:11 2010
@@ -1,3668 +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_repr(self):
-        import datetime
-        for tz in [self.ACDT, self.EST, timezone.utc,
-                   timezone.min, timezone.max]:
-            # test round-trip
-            tzrep = repr(tz)
-            self.assertEqual(tz, eval(tzrep))
-
-
-    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/pep-0384/Lib/test/test_dis.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_dis.py	(original)
+++ python/branches/pep-0384/Lib/test/test_dis.py	Fri Aug 27 21:11:11 2010
@@ -1,6 +1,6 @@
 # Minimal tests for dis module
 
-from test.support import run_unittest
+from test.support import run_unittest, captured_stdout
 import unittest
 import sys
 import dis
@@ -211,8 +211,160 @@
         self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str)
         self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str)
 
+code_info_code_info = """\
+Name:              code_info
+Filename:          (.*)
+Argument count:    1
+Kw-only arguments: 0
+Number of locals:  1
+Stack size:        4
+Flags:             OPTIMIZED, NEWLOCALS, NOFREE
+Constants:
+   0: 'Formatted details of methods, functions, or code.'
+   1: '__func__'
+   2: '__code__'
+   3: '<code_info>'
+   4: 'co_code'
+   5: "don't know how to disassemble %s objects"
+   6: None
+Names:
+   0: hasattr
+   1: __func__
+   2: __code__
+   3: isinstance
+   4: str
+   5: _try_compile
+   6: _format_code_info
+   7: TypeError
+   8: type
+   9: __name__
+Variable names:
+   0: x"""
+
+ at staticmethod
+def tricky(x, y, z=True, *args, c, d, e=[], **kwds):
+    def f(c=c):
+        print(x, y, z, c, d, e, f)
+    yield x, y, z, c, d, e, f
+
+code_info_tricky = """\
+Name:              tricky
+Filename:          (.*)
+Argument count:    3
+Kw-only arguments: 3
+Number of locals:  8
+Stack size:        7
+Flags:             OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR
+Constants:
+   0: None
+   1: <code object f at (.*), file "(.*)", line (.*)>
+Variable names:
+   0: x
+   1: y
+   2: z
+   3: c
+   4: d
+   5: e
+   6: args
+   7: kwds
+Cell variables:
+   0: e
+   1: d
+   2: f
+   3: y
+   4: x
+   5: z"""
+
+co_tricky_nested_f = tricky.__func__.__code__.co_consts[1]
+
+code_info_tricky_nested_f = """\
+Name:              f
+Filename:          (.*)
+Argument count:    1
+Kw-only arguments: 0
+Number of locals:  1
+Stack size:        8
+Flags:             OPTIMIZED, NEWLOCALS, NESTED
+Constants:
+   0: None
+Names:
+   0: print
+Variable names:
+   0: c
+Free variables:
+   0: e
+   1: d
+   2: f
+   3: y
+   4: x
+   5: z"""
+
+code_info_expr_str = """\
+Name:              <module>
+Filename:          <code_info>
+Argument count:    0
+Kw-only arguments: 0
+Number of locals:  0
+Stack size:        2
+Flags:             NOFREE
+Constants:
+   0: 1
+Names:
+   0: x"""
+
+code_info_simple_stmt_str = """\
+Name:              <module>
+Filename:          <code_info>
+Argument count:    0
+Kw-only arguments: 0
+Number of locals:  0
+Stack size:        2
+Flags:             NOFREE
+Constants:
+   0: 1
+   1: None
+Names:
+   0: x"""
+
+code_info_compound_stmt_str = """\
+Name:              <module>
+Filename:          <code_info>
+Argument count:    0
+Kw-only arguments: 0
+Number of locals:  0
+Stack size:        2
+Flags:             NOFREE
+Constants:
+   0: 0
+   1: 1
+   2: None
+Names:
+   0: x"""
+
+class CodeInfoTests(unittest.TestCase):
+    test_pairs = [
+      (dis.code_info, code_info_code_info),
+      (tricky, code_info_tricky),
+      (co_tricky_nested_f, code_info_tricky_nested_f),
+      (expr_str, code_info_expr_str),
+      (simple_stmt_str, code_info_simple_stmt_str),
+      (compound_stmt_str, code_info_compound_stmt_str),
+    ]
+
+    def test_code_info(self):
+        self.maxDiff = 1000
+        for x, expected in self.test_pairs:
+            self.assertRegexpMatches(dis.code_info(x), expected)
+
+    def test_show_code(self):
+        self.maxDiff = 1000
+        for x, expected in self.test_pairs:
+            with captured_stdout() as output:
+                dis.show_code(x)
+            self.assertRegexpMatches(output.getvalue(), expected+"\n")
+
 def test_main():
-    run_unittest(DisTests)
+    run_unittest(DisTests, CodeInfoTests)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-0384/Lib/test/test_doctest.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_doctest.py	(original)
+++ python/branches/pep-0384/Lib/test/test_doctest.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_fileinput.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_fileinput.py	(original)
+++ python/branches/pep-0384/Lib/test/test_fileinput.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_float.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_float.py	(original)
+++ python/branches/pep-0384/Lib/test/test_float.py	Fri Aug 27 21:11:11 2010
@@ -617,7 +617,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/pep-0384/Lib/test/test_fnmatch.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_fnmatch.py	(original)
+++ python/branches/pep-0384/Lib/test/test_fnmatch.py	Fri Aug 27 21:11:11 2010
@@ -3,14 +3,10 @@
 from test import support
 import unittest
 
-from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _cacheb, purge
-
+from fnmatch import fnmatch, fnmatchcase, 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),
@@ -64,24 +60,29 @@
         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/pep-0384/Lib/test/test_ftplib.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_ftplib.py	(original)
+++ python/branches/pep-0384/Lib/test/test_ftplib.py	Fri Aug 27 21:11:11 2010
@@ -606,6 +606,18 @@
         self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
         self.assertFalse(is_client_connected())
 
+    def test_parse257(self):
+        self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
+        self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
+        self.assertEqual(ftplib.parse257('257 ""'), '')
+        self.assertEqual(ftplib.parse257('257 "" created'), '')
+        self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
+        # The 257 response is supposed to include the directory
+        # name and in case it contains embedded double-quotes
+        # they must be doubled (see RFC-959, chapter 7, appendix 2).
+        self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
+        self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
+
 
 class TestIPv6Environment(TestCase):
 

Modified: python/branches/pep-0384/Lib/test/test_functools.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_functools.py	(original)
+++ python/branches/pep-0384/Lib/test/test_functools.py	Fri Aug 27 21:11:11 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
@@ -193,8 +194,11 @@
     def test_default_update(self):
         wrapper, f = self._default_update()
         self.check_wrapper(wrapper, f)
+        self.assertIs(wrapper.__wrapped__, 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 +217,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):
@@ -232,6 +237,28 @@
         self.assertEqual(wrapper.attr, 'This is a different test')
         self.assertEqual(wrapper.dict_attr, f.dict_attr)
 
+    def test_missing_attributes(self):
+        def f():
+            pass
+        def wrapper():
+            pass
+        wrapper.dict_attr = {}
+        assign = ('attr',)
+        update = ('dict_attr',)
+        # Missing attributes on wrapped object are ignored
+        functools.update_wrapper(wrapper, f, assign, update)
+        self.assertNotIn('attr', wrapper.__dict__)
+        self.assertEqual(wrapper.dict_attr, {})
+        # Wrapper must have expected attributes for updating
+        del wrapper.dict_attr
+        with self.assertRaises(AttributeError):
+            functools.update_wrapper(wrapper, f, assign, update)
+        wrapper.dict_attr = 1
+        with self.assertRaises(AttributeError):
+            functools.update_wrapper(wrapper, f, assign, update)
+
+    @unittest.skipIf(sys.flags.optimize >= 2,
+                     "Docstrings are omitted with -O2 and above")
     def test_builtin_update(self):
         # Test for bug #1576241
         def wrapper():
@@ -239,6 +266,7 @@
         functools.update_wrapper(wrapper, max)
         self.assertEqual(wrapper.__name__, 'max')
         self.assertTrue(wrapper.__doc__.startswith('max('))
+        self.assertEqual(wrapper.__annotations__, {})
 
 class TestWraps(TestUpdateWrapper):
 
@@ -316,10 +344,11 @@
                     self.sofar.append(n*n)
                     n += 1
                 return self.sofar[i]
-
-        self.assertEqual(self.func(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc')
+        def add(x, y):
+            return x + y
+        self.assertEqual(self.func(add, ['a', 'b', 'c'], ''), 'abc')
         self.assertEqual(
-            self.func(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []),
+            self.func(add, [['a', 'c'], [], ['d', 'w']], []),
             ['a','c','d','w']
         )
         self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040)
@@ -327,15 +356,27 @@
             self.func(lambda x, y: x*y, range(2,21), 1),
             2432902008176640000
         )
-        self.assertEqual(self.func(lambda x, y: x+y, Squares(10)), 285)
-        self.assertEqual(self.func(lambda x, y: x+y, Squares(10), 0), 285)
-        self.assertEqual(self.func(lambda x, y: x+y, Squares(0), 0), 0)
+        self.assertEqual(self.func(add, Squares(10)), 285)
+        self.assertEqual(self.func(add, Squares(10), 0), 285)
+        self.assertEqual(self.func(add, Squares(0), 0), 0)
         self.assertRaises(TypeError, self.func)
         self.assertRaises(TypeError, self.func, 42, 42)
         self.assertRaises(TypeError, self.func, 42, 42, 42)
         self.assertEqual(self.func(42, "1"), "1") # func is never called with one item
         self.assertEqual(self.func(42, "", "1"), "1") # func is never called with one item
         self.assertRaises(TypeError, self.func, 42, (42, 42))
+        self.assertRaises(TypeError, self.func, add, []) # arg 2 must not be empty sequence with no initial value
+        self.assertRaises(TypeError, self.func, add, "")
+        self.assertRaises(TypeError, self.func, add, ())
+        self.assertRaises(TypeError, self.func, add, object())
+
+        class TestFailingIter:
+            def __iter__(self):
+                raise RuntimeError
+        self.assertRaises(RuntimeError, self.func, add, TestFailingIter())
+
+        self.assertEqual(self.func(add, [], None), None)
+        self.assertEqual(self.func(add, [], 42), 42)
 
         class BadSeq:
             def __getitem__(self, index):
@@ -440,7 +481,7 @@
         # new methods should not overwrite existing
         @functools.total_ordering
         class A(int):
-            raise Exception()
+            pass
         self.assert_(A(1) < A(2))
         self.assert_(A(2) > A(1))
         self.assert_(A(1) <= A(2))
@@ -454,14 +495,79 @@
             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)
+
+        # Test bypassing the cache
+        self.assertIs(f.__wrapped__, orig)
+        f.__wrapped__(x, y)
+        self.assertEqual(f.hits, 0)
+        self.assertEqual(f.misses, 1)
+
+        # test size zero (which means "never-cache")
+        @functools.lru_cache(0)
+        def f():
+            nonlocal f_cnt
+            f_cnt += 1
+            return 20
+        f_cnt = 0
+        for i in range(5):
+            self.assertEqual(f(), 20)
+        self.assertEqual(f_cnt, 5)
+
+        # test size one
+        @functools.lru_cache(1)
+        def f():
+            nonlocal f_cnt
+            f_cnt += 1
+            return 20
+        f_cnt = 0
+        for i in range(5):
+            self.assertEqual(f(), 20)
+        self.assertEqual(f_cnt, 1)
+
+        # test size two
+        @functools.lru_cache(2)
+        def f(x):
+            nonlocal f_cnt
+            f_cnt += 1
+            return x*10
+        f_cnt = 0
+        for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7:
+            #    *  *              *                          *
+            self.assertEqual(f(x), x*10)
+        self.assertEqual(f_cnt, 4)
+
 def test_main(verbose=None):
     test_classes = (
         TestPartial,
         TestPartialSubclass,
         TestPythonPartial,
         TestUpdateWrapper,
+        TestTotalOrdering,
         TestWraps,
-        TestReduce
+        TestReduce,
+        TestLRU,
     )
     support.run_unittest(*test_classes)
 

Modified: python/branches/pep-0384/Lib/test/test_gc.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_gc.py	(original)
+++ python/branches/pep-0384/Lib/test/test_gc.py	Fri Aug 27 21:11:11 2010
@@ -1,5 +1,5 @@
 import unittest
-from test.support import verbose, run_unittest
+from test.support import verbose, run_unittest, strip_python_stderr
 import sys
 import gc
 import weakref
@@ -466,6 +466,42 @@
             # would be damaged, with an empty __dict__.
             self.assertEqual(x, None)
 
+    def test_garbage_at_shutdown(self):
+        import subprocess
+        code = """if 1:
+            import gc
+            class X:
+                def __init__(self, name):
+                    self.name = name
+                def __repr__(self):
+                    return "<X %%r>" %% self.name
+                def __del__(self):
+                    pass
+
+            x = X('first')
+            x.x = x
+            x.y = X('second')
+            del x
+            if %d:
+                gc.set_debug(gc.DEBUG_UNCOLLECTABLE)
+        """
+        def run_command(code):
+            p = subprocess.Popen([sys.executable, "-c", code],
+                stdout=subprocess.PIPE,
+                stderr=subprocess.PIPE)
+            stdout, stderr = p.communicate()
+            self.assertEqual(p.returncode, 0)
+            self.assertEqual(stdout.strip(), b"")
+            return strip_python_stderr(stderr)
+
+        stderr = run_command(code % 0)
+        self.assertIn(b"gc: 2 uncollectable objects at shutdown", stderr)
+        self.assertNotIn(b"[<X 'first'>, <X 'second'>]", stderr)
+        # With DEBUG_UNCOLLECTABLE, the garbage list gets printed
+        stderr = run_command(code % 1)
+        self.assertIn(b"gc: 2 uncollectable objects at shutdown", stderr)
+        self.assertIn(b"[<X 'first'>, <X 'second'>]", stderr)
+
 class GCTogglingTests(unittest.TestCase):
     def setUp(self):
         gc.enable()

Modified: python/branches/pep-0384/Lib/test/test_genericpath.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_genericpath.py	(original)
+++ python/branches/pep-0384/Lib/test/test_genericpath.py	Fri Aug 27 21:11:11 2010
@@ -180,6 +180,9 @@
             safe_rmdir(support.TESTFN)
 
 
+# Following TestCase is not supposed to be run from test_genericpath.
+# It is inherited by other test modules (macpath, ntpath, posixpath).
+
 class CommonTest(GenericTest):
     # The path module to be tested
     pathmodule = None

Modified: python/branches/pep-0384/Lib/test/test_getopt.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_getopt.py	(original)
+++ python/branches/pep-0384/Lib/test/test_getopt.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_gzip.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_gzip.py	(original)
+++ python/branches/pep-0384/Lib/test/test_gzip.py	Fri Aug 27 21:11:11 2010
@@ -265,6 +265,26 @@
             d = f.read()
             self.assertEqual(d, data1 * 50, "Incorrect data in file")
 
+    # Testing compress/decompress shortcut functions
+
+    def test_compress(self):
+        for data in [data1, data2]:
+            for args in [(), (1,), (6,), (9,)]:
+                datac = gzip.compress(data, *args)
+                self.assertEqual(type(datac), bytes)
+                with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
+                    self.assertEqual(f.read(), data)
+
+    def test_decompress(self):
+        for data in (data1, data2):
+            buf = io.BytesIO()
+            with gzip.GzipFile(fileobj=buf, mode="wb") as f:
+                f.write(data)
+            self.assertEqual(gzip.decompress(buf.getvalue()), data)
+            # Roundtrip with compress
+            datac = gzip.compress(data)
+            self.assertEqual(gzip.decompress(datac), data)
+
 def test_main(verbose=None):
     support.run_unittest(TestGzip)
 

Modified: python/branches/pep-0384/Lib/test/test_http_cookies.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_http_cookies.py	(original)
+++ python/branches/pep-0384/Lib/test/test_http_cookies.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_httplib.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_httplib.py	(original)
+++ python/branches/pep-0384/Lib/test/test_httplib.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_httpservers.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_httpservers.py	(original)
+++ python/branches/pep-0384/Lib/test/test_httpservers.py	Fri Aug 27 21:11:11 2010
@@ -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/pep-0384/Lib/test/test_imp.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_imp.py	(original)
+++ python/branches/pep-0384/Lib/test/test_imp.py	Fri Aug 27 21:11:11 2010
@@ -306,11 +306,24 @@
                          os.sep.join(('.', 'pep3147', '__init__.py')))
 
 
+class NullImporterTests(unittest.TestCase):
+    @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
+                     "Need an undecodeable filename")
+    def test_unencodeable(self):
+        name = support.TESTFN_UNENCODABLE
+        os.mkdir(name)
+        try:
+            self.assertRaises(ImportError, imp.NullImporter, name)
+        finally:
+            os.rmdir(name)
+
+
 def test_main():
     tests = [
         ImportTests,
         PEP3147Tests,
         ReloadTests,
+        NullImporterTests,
         ]
     try:
         import _thread

Modified: python/branches/pep-0384/Lib/test/test_import.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_import.py	(original)
+++ python/branches/pep-0384/Lib/test/test_import.py	Fri Aug 27 21:11:11 2010
@@ -1,11 +1,11 @@
 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
 import random
-import shutil
 import stat
 import sys
 import unittest
@@ -23,11 +23,7 @@
               name + ".pyw",
               name + "$py.class"):
         unlink(f)
-    try:
-        shutil.rmtree('__pycache__')
-    except OSError as error:
-        if error.errno != errno.ENOENT:
-            raise
+    rmtree('__pycache__')
 
 
 class ImportTests(unittest.TestCase):
@@ -203,13 +199,6 @@
         import test.support as y
         self.assertTrue(y is test.support, y.__name__)
 
-    def test_import_initless_directory_warning(self):
-        with warnings.catch_warnings():
-            # Just a random non-package directory we always expect to be
-            # somewhere in sys.path...
-            warnings.simplefilter('error', ImportWarning)
-            self.assertRaises(ImportWarning, __import__, "site-packages")
-
     def test_failing_reload(self):
         # A failing reload should leave the module object in sys.modules.
         source = TESTFN + os.extsep + "py"
@@ -289,6 +278,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.",
@@ -330,8 +324,7 @@
             unload(self.module_name)
         unlink(self.file_name)
         unlink(self.compiled_name)
-        if os.path.exists(self.dir_name):
-            shutil.rmtree(self.dir_name)
+        rmtree(self.dir_name)
 
     def import_module(self):
         ns = globals()
@@ -398,7 +391,7 @@
         self.syspath = sys.path[:]
 
     def tearDown(self):
-        shutil.rmtree(self.path)
+        rmtree(self.path)
         sys.path[:] = self.syspath
 
     # Regression test for http://bugs.python.org/issue1293.
@@ -471,16 +464,14 @@
         self.assertRaises(ValueError, check_relative)
 
     def test_absolute_import_without_future(self):
-        # If absolute import syntax is used, then do not try to perform
-        # a relative import in the face of failure.
+        # If explicit relative import syntax is used, then do not try
+        # to perform an absolute import in the face of failure.
         # Issue #7902.
-        try:
+        with self.assertRaises(ImportError):
             from .os import sep
-        except ImportError:
-            pass
-        else:
             self.fail("explicit relative import triggered an "
-                      "implicit relative import")
+                      "implicit absolute import")
+
 
 class OverridingImportBuiltinTests(unittest.TestCase):
     def test_override_builtin(self):
@@ -589,7 +580,7 @@
     def test_package___cached__(self):
         # Like test___cached__ but for packages.
         def cleanup():
-            shutil.rmtree('pep3147')
+            rmtree('pep3147')
         os.mkdir('pep3147')
         self.addCleanup(cleanup)
         # Touch the __init__.py
@@ -611,7 +602,7 @@
         # Like test___cached__ but ensuring __cached__ when imported from a
         # PEP 3147 pyc file.
         def cleanup():
-            shutil.rmtree('pep3147')
+            rmtree('pep3147')
         os.mkdir('pep3147')
         self.addCleanup(cleanup)
         unload('pep3147.foo')
@@ -633,10 +624,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/pep-0384/Lib/test/test_io.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_io.py	(original)
+++ python/branches/pep-0384/Lib/test/test_io.py	Fri Aug 27 21:11:11 2010
@@ -27,6 +27,8 @@
 import unittest
 import weakref
 import abc
+import signal
+import errno
 from itertools import cycle, count
 from collections import deque
 from test import support
@@ -52,12 +54,14 @@
         self._read_stack = list(read_stack)
         self._write_stack = []
         self._reads = 0
+        self._extraneous_reads = 0
 
     def read(self, n=None):
         self._reads += 1
         try:
             return self._read_stack.pop(0)
         except:
+            self._extraneous_reads += 1
             return b""
 
     def write(self, b):
@@ -88,6 +92,7 @@
         try:
             data = self._read_stack[0]
         except IndexError:
+            self._extraneous_reads += 1
             return 0
         if data is None:
             del self._read_stack[0]
@@ -824,6 +829,27 @@
         self.assertRaises(IOError, bufio.seek, 0)
         self.assertRaises(IOError, bufio.tell)
 
+    def test_no_extraneous_read(self):
+        # Issue #9550; when the raw IO object has satisfied the read request,
+        # we should not issue any additional reads, otherwise it may block
+        # (e.g. socket).
+        bufsize = 16
+        for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2):
+            rawio = self.MockRawIO([b"x" * n])
+            bufio = self.tp(rawio, bufsize)
+            self.assertEqual(bufio.read(n), b"x" * n)
+            # Simple case: one raw read is enough to satisfy the request.
+            self.assertEqual(rawio._extraneous_reads, 0,
+                             "failed for {}: {} != 0".format(n, rawio._extraneous_reads))
+            # A more complex case where two raw reads are needed to satisfy
+            # the request.
+            rawio = self.MockRawIO([b"x" * (n - 1), b"x"])
+            bufio = self.tp(rawio, bufsize)
+            self.assertEqual(bufio.read(n), b"x" * n)
+            self.assertEqual(rawio._extraneous_reads, 0,
+                             "failed for {}: {} != 0".format(n, rawio._extraneous_reads))
+
+
 class CBufferedReaderTest(BufferedReaderTest):
     tp = io.BufferedReader
 
@@ -2439,6 +2465,75 @@
 class PyMiscIOTest(MiscIOTest):
     io = pyio
 
+
+ at unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.')
+class SignalsTest(unittest.TestCase):
+
+    def setUp(self):
+        self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
+
+    def tearDown(self):
+        signal.signal(signal.SIGALRM, self.oldalrm)
+
+    def alarm_interrupt(self, sig, frame):
+        1/0
+
+    @unittest.skipUnless(threading, 'Threading required for this test.')
+    def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
+        """Check that a partial write, when it gets interrupted, properly
+        invokes the signal handler."""
+        read_results = []
+        def _read():
+            s = os.read(r, 1)
+            read_results.append(s)
+        t = threading.Thread(target=_read)
+        t.daemon = True
+        r, w = os.pipe()
+        try:
+            wio = self.io.open(w, **fdopen_kwargs)
+            t.start()
+            signal.alarm(1)
+            # Fill the pipe enough that the write will be blocking.
+            # It will be interrupted by the timer armed above.  Since the
+            # other thread has read one byte, the low-level write will
+            # return with a successful (partial) result rather than an EINTR.
+            # The buffered IO layer must check for pending signal
+            # handlers, which in this case will invoke alarm_interrupt().
+            self.assertRaises(ZeroDivisionError,
+                              wio.write, item * (1024 * 1024))
+            t.join()
+            # We got one byte, get another one and check that it isn't a
+            # repeat of the first one.
+            read_results.append(os.read(r, 1))
+            self.assertEqual(read_results, [bytes[0:1], bytes[1:2]])
+        finally:
+            os.close(w)
+            os.close(r)
+            # This is deliberate. If we didn't close the file descriptor
+            # before closing wio, wio would try to flush its internal
+            # buffer, and block again.
+            try:
+                wio.close()
+            except IOError as e:
+                if e.errno != errno.EBADF:
+                    raise
+
+    def test_interrupted_write_unbuffered(self):
+        self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0)
+
+    def test_interrupted_write_buffered(self):
+        self.check_interrupted_write(b"xy", b"xy", mode="wb")
+
+    def test_interrupted_write_text(self):
+        self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii")
+
+class CSignalsTest(SignalsTest):
+    io = io
+
+class PySignalsTest(SignalsTest):
+    io = pyio
+
+
 def test_main():
     tests = (CIOTest, PyIOTest,
              CBufferedReaderTest, PyBufferedReaderTest,
@@ -2448,7 +2543,9 @@
              StatefulIncrementalDecoderTest,
              CIncrementalNewlineDecoderTest, PyIncrementalNewlineDecoderTest,
              CTextIOWrapperTest, PyTextIOWrapperTest,
-             CMiscIOTest, PyMiscIOTest,)
+             CMiscIOTest, PyMiscIOTest,
+             CSignalsTest, PySignalsTest,
+             )
 
     # Put the namespaces of the IO module we are testing and some useful mock
     # classes in the __dict__ of each test.

Modified: python/branches/pep-0384/Lib/test/test_ioctl.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_ioctl.py	(original)
+++ python/branches/pep-0384/Lib/test/test_ioctl.py	Fri Aug 27 21:11:11 2010
@@ -7,9 +7,17 @@
 
 try:
     tty = open("/dev/tty", "r")
-    tty.close()
 except IOError:
     raise unittest.SkipTest("Unable to open /dev/tty")
+else:
+    # Skip if another process is in foreground
+    r = fcntl.ioctl(tty, termios.TIOCGPGRP, "    ")
+    tty.close()
+    rpgrp = struct.unpack("i", r)[0]
+    if rpgrp not in (os.getpgrp(), os.getsid(0)):
+        raise unittest.SkipTest("Neither the process group nor the session "
+                                "are attached to /dev/tty")
+    del tty, r, rpgrp
 
 try:
     import pty

Deleted: python/branches/pep-0384/Lib/test/test_line_tracing.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_line_tracing.py	Fri Aug 27 21:11:11 2010
+++ (empty file)
@@ -1,790 +0,0 @@
-# Testing the line trace facility.
-
-from test import support
-import unittest
-import sys
-import difflib
-import gc
-
-# A very basic example.  If this fails, we're in deep trouble.
-def basic():
-    return 1
-
-basic.events = [(0, 'call'),
-                (1, 'line'),
-                (1, 'return')]
-
-# Many of the tests below are tricky because they involve pass statements.
-# If there is implicit control flow around a pass statement (in an except
-# clause or else caluse) under what conditions do you set a line number
-# following that clause?
-
-
-# The entire "while 0:" statement is optimized away.  No code
-# exists for it, so the line numbers skip directly from "del x"
-# to "x = 1".
-def arigo_example():
-    x = 1
-    del x
-    while 0:
-        pass
-    x = 1
-
-arigo_example.events = [(0, 'call'),
-                        (1, 'line'),
-                        (2, 'line'),
-                        (5, 'line'),
-                        (5, 'return')]
-
-# check that lines consisting of just one instruction get traced:
-def one_instr_line():
-    x = 1
-    del x
-    x = 1
-
-one_instr_line.events = [(0, 'call'),
-                         (1, 'line'),
-                         (2, 'line'),
-                         (3, 'line'),
-                         (3, 'return')]
-
-def no_pop_tops():      # 0
-    x = 1               # 1
-    for a in range(2):  # 2
-        if a:           # 3
-            x = 1       # 4
-        else:           # 5
-            x = 1       # 6
-
-no_pop_tops.events = [(0, 'call'),
-                      (1, 'line'),
-                      (2, 'line'),
-                      (3, 'line'),
-                      (6, 'line'),
-                      (2, 'line'),
-                      (3, 'line'),
-                      (4, 'line'),
-                      (2, 'line'),
-                      (2, 'return')]
-
-def no_pop_blocks():
-    y = 1
-    while not y:
-        bla
-    x = 1
-
-no_pop_blocks.events = [(0, 'call'),
-                        (1, 'line'),
-                        (2, 'line'),
-                        (4, 'line'),
-                        (4, 'return')]
-
-def called(): # line -3
-    x = 1
-
-def call():   # line 0
-    called()
-
-call.events = [(0, 'call'),
-               (1, 'line'),
-               (-3, 'call'),
-               (-2, 'line'),
-               (-2, 'return'),
-               (1, 'return')]
-
-def raises():
-    raise Exception
-
-def test_raise():
-    try:
-        raises()
-    except Exception as exc:
-        x = 1
-
-test_raise.events = [(0, 'call'),
-                     (1, 'line'),
-                     (2, 'line'),
-                     (-3, 'call'),
-                     (-2, 'line'),
-                     (-2, 'exception'),
-                     (-2, 'return'),
-                     (2, 'exception'),
-                     (3, 'line'),
-                     (4, 'line'),
-                     (4, 'return')]
-
-def _settrace_and_return(tracefunc):
-    sys.settrace(tracefunc)
-    sys._getframe().f_back.f_trace = tracefunc
-def settrace_and_return(tracefunc):
-    _settrace_and_return(tracefunc)
-
-settrace_and_return.events = [(1, 'return')]
-
-def _settrace_and_raise(tracefunc):
-    sys.settrace(tracefunc)
-    sys._getframe().f_back.f_trace = tracefunc
-    raise RuntimeError
-def settrace_and_raise(tracefunc):
-    try:
-        _settrace_and_raise(tracefunc)
-    except RuntimeError as exc:
-        pass
-
-settrace_and_raise.events = [(2, 'exception'),
-                             (3, 'line'),
-                             (4, 'line'),
-                             (4, 'return')]
-
-# implicit return example
-# This test is interesting because of the else: pass
-# part of the code.  The code generate for the true
-# part of the if contains a jump past the else branch.
-# The compiler then generates an implicit "return None"
-# Internally, the compiler visits the pass statement
-# and stores its line number for use on the next instruction.
-# The next instruction is the implicit return None.
-def ireturn_example():
-    a = 5
-    b = 5
-    if a == b:
-        b = a+1
-    else:
-        pass
-
-ireturn_example.events = [(0, 'call'),
-                          (1, 'line'),
-                          (2, 'line'),
-                          (3, 'line'),
-                          (4, 'line'),
-                          (6, 'line'),
-                          (6, 'return')]
-
-# Tight loop with while(1) example (SF #765624)
-def tightloop_example():
-    items = range(0, 3)
-    try:
-        i = 0
-        while 1:
-            b = items[i]; i+=1
-    except IndexError:
-        pass
-
-tightloop_example.events = [(0, 'call'),
-                            (1, 'line'),
-                            (2, 'line'),
-                            (3, 'line'),
-                            (4, 'line'),
-                            (5, 'line'),
-                            (5, 'line'),
-                            (5, 'line'),
-                            (5, 'line'),
-                            (5, 'exception'),
-                            (6, 'line'),
-                            (7, 'line'),
-                            (7, 'return')]
-
-def tighterloop_example():
-    items = range(1, 4)
-    try:
-        i = 0
-        while 1: i = items[i]
-    except IndexError:
-        pass
-
-tighterloop_example.events = [(0, 'call'),
-                            (1, 'line'),
-                            (2, 'line'),
-                            (3, 'line'),
-                            (4, 'line'),
-                            (4, 'line'),
-                            (4, 'line'),
-                            (4, 'line'),
-                            (4, 'exception'),
-                            (5, 'line'),
-                            (6, 'line'),
-                            (6, 'return')]
-
-def generator_function():
-    try:
-        yield True
-        "continued"
-    finally:
-        "finally"
-def generator_example():
-    # any() will leave the generator before its end
-    x = any(generator_function())
-
-    # the following lines were not traced
-    for x in range(10):
-        y = x
-
-generator_example.events = ([(0, 'call'),
-                             (2, 'line'),
-                             (-6, 'call'),
-                             (-5, 'line'),
-                             (-4, 'line'),
-                             (-4, 'return'),
-                             (-4, 'call'),
-                             (-4, 'exception'),
-                             (-1, 'line'),
-                             (-1, 'return')] +
-                            [(5, 'line'), (6, 'line')] * 10 +
-                            [(5, 'line'), (5, 'return')])
-
-
-class Tracer:
-    def __init__(self):
-        self.events = []
-    def trace(self, frame, event, arg):
-        self.events.append((frame.f_lineno, event))
-        return self.trace
-    def traceWithGenexp(self, frame, event, arg):
-        (o for o in [1])
-        self.events.append((frame.f_lineno, event))
-        return self.trace
-
-class TraceTestCase(unittest.TestCase):
-
-    # Disable gc collection when tracing, otherwise the
-    # deallocators may be traced as well.
-    def setUp(self):
-        self.using_gc = gc.isenabled()
-        gc.disable()
-
-    def tearDown(self):
-        if self.using_gc:
-            gc.enable()
-
-    def compare_events(self, line_offset, events, expected_events):
-        events = [(l - line_offset, e) for (l, e) in events]
-        if events != expected_events:
-            self.fail(
-                "events did not match expectation:\n" +
-                "\n".join(difflib.ndiff([str(x) for x in expected_events],
-                                        [str(x) for x in events])))
-
-    def run_and_compare(self, func, events):
-        tracer = Tracer()
-        sys.settrace(tracer.trace)
-        func()
-        sys.settrace(None)
-        self.compare_events(func.__code__.co_firstlineno,
-                            tracer.events, events)
-
-    def run_test(self, func):
-        self.run_and_compare(func, func.events)
-
-    def run_test2(self, func):
-        tracer = Tracer()
-        func(tracer.trace)
-        sys.settrace(None)
-        self.compare_events(func.__code__.co_firstlineno,
-                            tracer.events, func.events)
-
-    def set_and_retrieve_none(self):
-        sys.settrace(None)
-        assert sys.gettrace() is None
-
-    def set_and_retrieve_func(self):
-        def fn(*args):
-            pass
-
-        sys.settrace(fn)
-        try:
-            assert sys.gettrace() is fn
-        finally:
-            sys.settrace(None)
-
-    def test_01_basic(self):
-        self.run_test(basic)
-    def test_02_arigo(self):
-        self.run_test(arigo_example)
-    def test_03_one_instr(self):
-        self.run_test(one_instr_line)
-    def test_04_no_pop_blocks(self):
-        self.run_test(no_pop_blocks)
-    def test_05_no_pop_tops(self):
-        self.run_test(no_pop_tops)
-    def test_06_call(self):
-        self.run_test(call)
-    def test_07_raise(self):
-        self.run_test(test_raise)
-
-    def test_08_settrace_and_return(self):
-        self.run_test2(settrace_and_return)
-    def test_09_settrace_and_raise(self):
-        self.run_test2(settrace_and_raise)
-    def test_10_ireturn(self):
-        self.run_test(ireturn_example)
-    def test_11_tightloop(self):
-        self.run_test(tightloop_example)
-    def test_12_tighterloop(self):
-        self.run_test(tighterloop_example)
-
-    def test_13_genexp(self):
-        self.run_test(generator_example)
-        # issue1265: if the trace function contains a generator,
-        # and if the traced function contains another generator
-        # that is not completely exhausted, the trace stopped.
-        # Worse: the 'finally' clause was not invoked.
-        tracer = Tracer()
-        sys.settrace(tracer.traceWithGenexp)
-        generator_example()
-        sys.settrace(None)
-        self.compare_events(generator_example.__code__.co_firstlineno,
-                            tracer.events, generator_example.events)
-
-    def test_14_onliner_if(self):
-        def onliners():
-            if True: False
-            else: True
-            return 0
-        self.run_and_compare(
-            onliners,
-            [(0, 'call'),
-             (1, 'line'),
-             (3, 'line'),
-             (3, 'return')])
-
-    def test_15_loops(self):
-        # issue1750076: "while" expression is skipped by debugger
-        def for_example():
-            for x in range(2):
-                pass
-        self.run_and_compare(
-            for_example,
-            [(0, 'call'),
-             (1, 'line'),
-             (2, 'line'),
-             (1, 'line'),
-             (2, 'line'),
-             (1, 'line'),
-             (1, 'return')])
-
-        def while_example():
-            # While expression should be traced on every loop
-            x = 2
-            while x > 0:
-                x -= 1
-        self.run_and_compare(
-            while_example,
-            [(0, 'call'),
-             (2, 'line'),
-             (3, 'line'),
-             (4, 'line'),
-             (3, 'line'),
-             (4, 'line'),
-             (3, 'line'),
-             (3, 'return')])
-
-    def test_16_blank_lines(self):
-        namespace = {}
-        exec("def f():\n" + "\n" * 256 + "    pass", namespace)
-        self.run_and_compare(
-            namespace["f"],
-            [(0, 'call'),
-             (257, 'line'),
-             (257, 'return')])
-
-
-class RaisingTraceFuncTestCase(unittest.TestCase):
-    def trace(self, frame, event, arg):
-        """A trace function that raises an exception in response to a
-        specific trace event."""
-        if event == self.raiseOnEvent:
-            raise ValueError # just something that isn't RuntimeError
-        else:
-            return self.trace
-
-    def f(self):
-        """The function to trace; raises an exception if that's the case
-        we're testing, so that the 'exception' trace event fires."""
-        if self.raiseOnEvent == 'exception':
-            x = 0
-            y = 1/x
-        else:
-            return 1
-
-    def run_test_for_event(self, event):
-        """Tests that an exception raised in response to the given event is
-        handled OK."""
-        self.raiseOnEvent = event
-        try:
-            for i in range(sys.getrecursionlimit() + 1):
-                sys.settrace(self.trace)
-                try:
-                    self.f()
-                except ValueError:
-                    pass
-                else:
-                    self.fail("exception not thrown!")
-        except RuntimeError:
-            self.fail("recursion counter not reset")
-
-    # Test the handling of exceptions raised by each kind of trace event.
-    def test_call(self):
-        self.run_test_for_event('call')
-    def test_line(self):
-        self.run_test_for_event('line')
-    def test_return(self):
-        self.run_test_for_event('return')
-    def test_exception(self):
-        self.run_test_for_event('exception')
-
-    def test_trash_stack(self):
-        def f():
-            for i in range(5):
-                print(i)  # line tracing will raise an exception at this line
-
-        def g(frame, why, extra):
-            if (why == 'line' and
-                frame.f_lineno == f.__code__.co_firstlineno + 2):
-                raise RuntimeError("i am crashing")
-            return g
-
-        sys.settrace(g)
-        try:
-            f()
-        except RuntimeError:
-            # the test is really that this doesn't segfault:
-            import gc
-            gc.collect()
-        else:
-            self.fail("exception not propagated")
-
-
-# 'Jump' tests: assigning to frame.f_lineno within a trace function
-# moves the execution position - it's how debuggers implement a Jump
-# command (aka. "Set next statement").
-
-class JumpTracer:
-    """Defines a trace function that jumps from one place to another,
-    with the source and destination lines of the jump being defined by
-    the 'jump' property of the function under test."""
-
-    def __init__(self, function):
-        self.function = function
-        self.jumpFrom = function.jump[0]
-        self.jumpTo = function.jump[1]
-        self.done = False
-
-    def trace(self, frame, event, arg):
-        if not self.done and frame.f_code == self.function.__code__:
-            firstLine = frame.f_code.co_firstlineno
-            if event == 'line' and frame.f_lineno == firstLine + self.jumpFrom:
-                # Cope with non-integer self.jumpTo (because of
-                # no_jump_to_non_integers below).
-                try:
-                    frame.f_lineno = firstLine + self.jumpTo
-                except TypeError:
-                    frame.f_lineno = self.jumpTo
-                self.done = True
-        return self.trace
-
-# The first set of 'jump' tests are for things that are allowed:
-
-def jump_simple_forwards(output):
-    output.append(1)
-    output.append(2)
-    output.append(3)
-
-jump_simple_forwards.jump = (1, 3)
-jump_simple_forwards.output = [3]
-
-def jump_simple_backwards(output):
-    output.append(1)
-    output.append(2)
-
-jump_simple_backwards.jump = (2, 1)
-jump_simple_backwards.output = [1, 1, 2]
-
-def jump_out_of_block_forwards(output):
-    for i in 1, 2:
-        output.append(2)
-        for j in [3]:  # Also tests jumping over a block
-            output.append(4)
-    output.append(5)
-
-jump_out_of_block_forwards.jump = (3, 5)
-jump_out_of_block_forwards.output = [2, 5]
-
-def jump_out_of_block_backwards(output):
-    output.append(1)
-    for i in [1]:
-        output.append(3)
-        for j in [2]:  # Also tests jumping over a block
-            output.append(5)
-        output.append(6)
-    output.append(7)
-
-jump_out_of_block_backwards.jump = (6, 1)
-jump_out_of_block_backwards.output = [1, 3, 5, 1, 3, 5, 6, 7]
-
-def jump_to_codeless_line(output):
-    output.append(1)
-    # Jumping to this line should skip to the next one.
-    output.append(3)
-
-jump_to_codeless_line.jump = (1, 2)
-jump_to_codeless_line.output = [3]
-
-def jump_to_same_line(output):
-    output.append(1)
-    output.append(2)
-    output.append(3)
-
-jump_to_same_line.jump = (2, 2)
-jump_to_same_line.output = [1, 2, 3]
-
-# Tests jumping within a finally block, and over one.
-def jump_in_nested_finally(output):
-    try:
-        output.append(2)
-    finally:
-        output.append(4)
-        try:
-            output.append(6)
-        finally:
-            output.append(8)
-        output.append(9)
-
-jump_in_nested_finally.jump = (4, 9)
-jump_in_nested_finally.output = [2, 9]
-
-# The second set of 'jump' tests are for things that are not allowed:
-
-def no_jump_too_far_forwards(output):
-    try:
-        output.append(2)
-        output.append(3)
-    except ValueError as e:
-        output.append('after' in str(e))
-
-no_jump_too_far_forwards.jump = (3, 6)
-no_jump_too_far_forwards.output = [2, True]
-
-def no_jump_too_far_backwards(output):
-    try:
-        output.append(2)
-        output.append(3)
-    except ValueError as e:
-        output.append('before' in str(e))
-
-no_jump_too_far_backwards.jump = (3, -1)
-no_jump_too_far_backwards.output = [2, True]
-
-# Test each kind of 'except' line.
-def no_jump_to_except_1(output):
-    try:
-        output.append(2)
-    except:
-        e = sys.exc_info()[1]
-        output.append('except' in str(e))
-
-no_jump_to_except_1.jump = (2, 3)
-no_jump_to_except_1.output = [True]
-
-def no_jump_to_except_2(output):
-    try:
-        output.append(2)
-    except ValueError:
-        e = sys.exc_info()[1]
-        output.append('except' in str(e))
-
-no_jump_to_except_2.jump = (2, 3)
-no_jump_to_except_2.output = [True]
-
-def no_jump_to_except_3(output):
-    try:
-        output.append(2)
-    except ValueError as e:
-        output.append('except' in str(e))
-
-no_jump_to_except_3.jump = (2, 3)
-no_jump_to_except_3.output = [True]
-
-def no_jump_to_except_4(output):
-    try:
-        output.append(2)
-    except (ValueError, RuntimeError) as e:
-        output.append('except' in str(e))
-
-no_jump_to_except_4.jump = (2, 3)
-no_jump_to_except_4.output = [True]
-
-def no_jump_forwards_into_block(output):
-    try:
-        output.append(2)
-        for i in 1, 2:
-            output.append(4)
-    except ValueError as e:
-        output.append('into' in str(e))
-
-no_jump_forwards_into_block.jump = (2, 4)
-no_jump_forwards_into_block.output = [True]
-
-def no_jump_backwards_into_block(output):
-    try:
-        for i in 1, 2:
-            output.append(3)
-        output.append(4)
-    except ValueError as e:
-        output.append('into' in str(e))
-
-no_jump_backwards_into_block.jump = (4, 3)
-no_jump_backwards_into_block.output = [3, 3, True]
-
-def no_jump_into_finally_block(output):
-    try:
-        try:
-            output.append(3)
-            x = 1
-        finally:
-            output.append(6)
-    except ValueError as e:
-        output.append('finally' in str(e))
-
-no_jump_into_finally_block.jump = (4, 6)
-no_jump_into_finally_block.output = [3, 6, True]  # The 'finally' still runs
-
-def no_jump_out_of_finally_block(output):
-    try:
-        try:
-            output.append(3)
-        finally:
-            output.append(5)
-            output.append(6)
-    except ValueError as e:
-        output.append('finally' in str(e))
-
-no_jump_out_of_finally_block.jump = (5, 1)
-no_jump_out_of_finally_block.output = [3, True]
-
-# This verifies the line-numbers-must-be-integers rule.
-def no_jump_to_non_integers(output):
-    try:
-        output.append(2)
-    except ValueError as e:
-        output.append('integer' in str(e))
-
-no_jump_to_non_integers.jump = (2, "Spam")
-no_jump_to_non_integers.output = [True]
-
-# This verifies that you can't set f_lineno via _getframe or similar
-# trickery.
-def no_jump_without_trace_function():
-    try:
-        previous_frame = sys._getframe().f_back
-        previous_frame.f_lineno = previous_frame.f_lineno
-    except ValueError as e:
-        # This is the exception we wanted; make sure the error message
-        # talks about trace functions.
-        if 'trace' not in str(e):
-            raise
-    else:
-        # Something's wrong - the expected exception wasn't raised.
-        raise RuntimeError("Trace-function-less jump failed to fail")
-
-
-class JumpTestCase(unittest.TestCase):
-    def compare_jump_output(self, expected, received):
-        if received != expected:
-            self.fail( "Outputs don't match:\n" +
-                       "Expected: " + repr(expected) + "\n" +
-                       "Received: " + repr(received))
-
-    def run_test(self, func):
-        tracer = JumpTracer(func)
-        sys.settrace(tracer.trace)
-        output = []
-        func(output)
-        sys.settrace(None)
-        self.compare_jump_output(func.output, output)
-
-    def test_01_jump_simple_forwards(self):
-        self.run_test(jump_simple_forwards)
-    def test_02_jump_simple_backwards(self):
-        self.run_test(jump_simple_backwards)
-    def test_03_jump_out_of_block_forwards(self):
-        self.run_test(jump_out_of_block_forwards)
-    def test_04_jump_out_of_block_backwards(self):
-        self.run_test(jump_out_of_block_backwards)
-    def test_05_jump_to_codeless_line(self):
-        self.run_test(jump_to_codeless_line)
-    def test_06_jump_to_same_line(self):
-        self.run_test(jump_to_same_line)
-    def test_07_jump_in_nested_finally(self):
-        self.run_test(jump_in_nested_finally)
-    def test_08_no_jump_too_far_forwards(self):
-        self.run_test(no_jump_too_far_forwards)
-    def test_09_no_jump_too_far_backwards(self):
-        self.run_test(no_jump_too_far_backwards)
-    def test_10_no_jump_to_except_1(self):
-        self.run_test(no_jump_to_except_1)
-    def test_11_no_jump_to_except_2(self):
-        self.run_test(no_jump_to_except_2)
-    def test_12_no_jump_to_except_3(self):
-        self.run_test(no_jump_to_except_3)
-    def test_13_no_jump_to_except_4(self):
-        self.run_test(no_jump_to_except_4)
-    def test_14_no_jump_forwards_into_block(self):
-        self.run_test(no_jump_forwards_into_block)
-    def test_15_no_jump_backwards_into_block(self):
-        self.run_test(no_jump_backwards_into_block)
-    def test_16_no_jump_into_finally_block(self):
-        self.run_test(no_jump_into_finally_block)
-    def test_17_no_jump_out_of_finally_block(self):
-        self.run_test(no_jump_out_of_finally_block)
-    def test_18_no_jump_to_non_integers(self):
-        self.run_test(no_jump_to_non_integers)
-    def test_19_no_jump_without_trace_function(self):
-        no_jump_without_trace_function()
-
-    def test_20_large_function(self):
-        d = {}
-        exec("""def f(output):        # line 0
-            x = 0                     # line 1
-            y = 1                     # line 2
-            '''                       # line 3
-            %s                        # lines 4-1004
-            '''                       # line 1005
-            x += 1                    # line 1006
-            output.append(x)          # line 1007
-            return""" % ('\n' * 1000,), d)
-        f = d['f']
-
-        f.jump = (2, 1007)
-        f.output = [0]
-        self.run_test(f)
-
-    def test_jump_to_firstlineno(self):
-        # This tests that PDB can jump back to the first line in a
-        # file.  See issue #1689458.  It can only be triggered in a
-        # function call if the function is defined on a single line.
-        code = compile("""
-# Comments don't count.
-output.append(2)  # firstlineno is here.
-output.append(3)
-output.append(4)
-""", "<fake module>", "exec")
-        class fake_function:
-            __code__ = code
-            jump = (2, 0)
-        tracer = JumpTracer(fake_function)
-        sys.settrace(tracer.trace)
-        namespace = {"output": []}
-        exec(code, namespace)
-        sys.settrace(None)
-        self.compare_jump_output([2, 3, 2, 3, 4], namespace["output"])
-
-
-def test_main():
-    support.run_unittest(
-        TraceTestCase,
-        RaisingTraceFuncTestCase,
-        JumpTestCase
-    )
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/pep-0384/Lib/test/test_logging.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_logging.py	(original)
+++ python/branches/pep-0384/Lib/test/test_logging.py	Fri Aug 27 21:11:11 2010
@@ -38,8 +38,7 @@
 import struct
 import sys
 import tempfile
-from test.support import captured_stdout, run_with_locale, run_unittest,\
-     find_unused_port
+from test.support import captured_stdout, run_with_locale, run_unittest
 import textwrap
 import unittest
 import warnings
@@ -1666,8 +1665,8 @@
     @unittest.skipUnless(threading, 'listen() needs threading to work')
     def setup_via_listener(self, text):
         text = text.encode("utf-8")
-        port = find_unused_port()
-        t = logging.config.listen(port)
+        # Ask for a randomly assigned port (by using port 0)
+        t = logging.config.listen(0)
         t.start()
         t.ready.wait()
         # Now get the port allocated

Modified: python/branches/pep-0384/Lib/test/test_minidom.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_minidom.py	(original)
+++ python/branches/pep-0384/Lib/test/test_minidom.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_mmap.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_mmap.py	(original)
+++ python/branches/pep-0384/Lib/test/test_mmap.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_multiprocessing.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_multiprocessing.py	(original)
+++ python/branches/pep-0384/Lib/test/test_multiprocessing.py	Fri Aug 27 21:11:11 2010
@@ -13,7 +13,6 @@
 import gc
 import signal
 import array
-import copy
 import socket
 import random
 import logging
@@ -71,11 +70,21 @@
 #
 
 try:
-    from ctypes import Structure, Value, copy, c_int, c_double
+    from ctypes import Structure, c_int, c_double
 except ImportError:
     Structure = object
     c_int = c_double = None
 
+try:
+    from ctypes import Value
+except ImportError:
+    Value = None
+
+try:
+    from ctypes import copy as ctypes_copy
+except ImportError:
+    ctypes_copy = None
+
 #
 # Creates a wrapper for a function which records the time it takes to finish
 #
@@ -1138,12 +1147,10 @@
         yield i*i
 
 class IteratorProxy(BaseProxy):
-    _exposed_ = ('next', '__next__')
+    _exposed_ = ('__next__',)
     def __iter__(self):
         return self
     def __next__(self):
-        return self._callmethod('next')
-    def __next__(self):
         return self._callmethod('__next__')
 
 class MyManager(BaseManager):
@@ -1600,7 +1607,7 @@
         for i in range(len(arr)):
             arr[i] *= 2
 
-    @unittest.skipIf(c_int is None, "requires _ctypes")
+    @unittest.skipIf(Value is None, "requires ctypes.Value")
     def test_sharedctypes(self, lock=False):
         x = Value('i', 7, lock=lock)
         y = Value(c_double, 1.0/3.0, lock=lock)
@@ -1621,13 +1628,14 @@
             self.assertAlmostEqual(arr[i], i*2)
         self.assertEqual(string.value, latin('hellohello'))
 
+    @unittest.skipIf(Value is None, "requires ctypes.Value")
     def test_synchronize(self):
         self.test_sharedctypes(lock=True)
 
-    @unittest.skipIf(c_int is None, "requires _ctypes")
+    @unittest.skipIf(ctypes_copy is None, "requires ctypes.copy")
     def test_copy(self):
         foo = _Foo(2, 5.0)
-        bar = copy(foo)
+        bar = ctypes_copy(foo)
         foo.x = 0
         foo.y = 0
         self.assertEqual(bar.x, 2)

Modified: python/branches/pep-0384/Lib/test/test_ntpath.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_ntpath.py	(original)
+++ python/branches/pep-0384/Lib/test/test_ntpath.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_optparse.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_optparse.py	(original)
+++ python/branches/pep-0384/Lib/test/test_optparse.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_os.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_os.py	(original)
+++ python/branches/pep-0384/Lib/test/test_os.py	Fri Aug 27 21:11:11 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)
@@ -448,8 +450,12 @@
 
         if os.supports_bytes_environ:
             # env cannot contain 'PATH' and b'PATH' keys
-            self.assertRaises(ValueError,
-                os.get_exec_path, {'PATH': '1', b'PATH': b'2'})
+            try:
+                mixed_env = {'PATH': '1', b'PATH': b'2'}
+            except BytesWarning:
+                pass
+            else:
+                self.assertRaises(ValueError, os.get_exec_path, mixed_env)
 
             # bytes key and/or value
             self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
@@ -721,7 +727,10 @@
         # os.get_exec_path() reads the 'PATH' variable
         with _execvpe_mockup() as calls:
             env_path = env.copy()
-            env_path['PATH'] = program_path
+            if test_type is bytes:
+                env_path[b'PATH'] = program_path
+            else:
+                env_path['PATH'] = program_path
             self.assertRaises(OSError,
                 os._execvpe, program, arguments, env=env_path)
             self.assertEqual(len(calls), 1)
@@ -893,29 +902,47 @@
                         sys.executable, '-c',
                         'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
 
-    @unittest.skipIf(sys.platform == 'darwin', "tests don't apply to OS X")
     class Pep383Tests(unittest.TestCase):
-        filenames = [b'foo\xf6bar', 'foo\xf6bar'.encode("utf-8")]
-
         def setUp(self):
-            self.fsencoding = sys.getfilesystemencoding()
-            sys.setfilesystemencoding("utf-8")
-            self.dir = support.TESTFN
-            self.bdir = self.dir.encode("utf-8", "surrogateescape")
+            if support.TESTFN_UNENCODABLE:
+                self.dir = support.TESTFN_UNENCODABLE
+            else:
+                self.dir = support.TESTFN
+            self.bdir = os.fsencode(self.dir)
+
+            bytesfn = []
+            def add_filename(fn):
+                try:
+                    fn = os.fsencode(fn)
+                except UnicodeEncodeError:
+                    return
+                bytesfn.append(fn)
+            add_filename(support.TESTFN_UNICODE)
+            if support.TESTFN_UNENCODABLE:
+                add_filename(support.TESTFN_UNENCODABLE)
+            if not bytesfn:
+                self.skipTest("couldn't create any non-ascii filename")
+
+            self.unicodefn = set()
             os.mkdir(self.dir)
-            self.unicodefn = []
-            for fn in self.filenames:
-                f = open(os.path.join(self.bdir, fn), "w")
-                f.close()
-                self.unicodefn.append(fn.decode("utf-8", "surrogateescape"))
+            try:
+                for fn in bytesfn:
+                    f = open(os.path.join(self.bdir, fn), "w")
+                    f.close()
+                    fn = os.fsdecode(fn)
+                    if fn in self.unicodefn:
+                        raise ValueError("duplicate filename")
+                    self.unicodefn.add(fn)
+            except:
+                shutil.rmtree(self.dir)
+                raise
 
         def tearDown(self):
             shutil.rmtree(self.dir)
-            sys.setfilesystemencoding(self.fsencoding)
 
         def test_listdir(self):
-            expected = set(self.unicodefn)
-            found = set(os.listdir(support.TESTFN))
+            expected = self.unicodefn
+            found = set(os.listdir(self.dir))
             self.assertEquals(found, expected)
 
         def test_open(self):
@@ -1111,12 +1138,49 @@
         self.assertNotEqual(os.lstat(link), os.stat(link))
 
 
-class MiscTests(unittest.TestCase):
+class FSEncodingTests(unittest.TestCase):
+    def test_nop(self):
+        self.assertEquals(os.fsencode(b'abc\xff'), b'abc\xff')
+        self.assertEquals(os.fsdecode('abc\u0141'), 'abc\u0141')
+
+    def test_identity(self):
+        # assert fsdecode(fsencode(x)) == x
+        for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
+            try:
+                bytesfn = os.fsencode(fn)
+            except UnicodeEncodeError:
+                continue
+            self.assertEquals(os.fsdecode(bytesfn), fn)
+
+    def get_output(self, fs_encoding, func):
+        env = os.environ.copy()
+        env['PYTHONIOENCODING'] = 'utf-8'
+        env['PYTHONFSENCODING'] = fs_encoding
+        code = 'import os; print(%s, end="")' % func
+        process = subprocess.Popen(
+            [sys.executable, "-c", code],
+            stdout=subprocess.PIPE, env=env)
+        stdout, stderr = process.communicate()
+        self.assertEqual(process.returncode, 0)
+        return stdout.decode('utf-8')
+
+    @unittest.skipIf(sys.platform in ('win32', 'darwin'),
+                     'PYTHONFSENCODING is ignored on Windows and Mac OS X')
+    def test_encodings(self):
+        def check(encoding, bytesfn, unicodefn):
+            encoded = self.get_output(encoding, 'repr(os.fsencode(%a))' % unicodefn)
+            self.assertEqual(encoded, repr(bytesfn))
+
+            decoded = self.get_output(encoding, 'repr(os.fsdecode(%a))' % bytesfn)
+            self.assertEqual(decoded, repr(unicodefn))
+
+        check('utf-8', b'\xc3\xa9\x80', '\xe9\udc80')
+
+        # Raise SkipTest() if sys.executable is not encodable to ascii
+        support.workaroundIssue8611()
 
-    @unittest.skipIf(os.name == "nt", "POSIX specific test")
-    def test_fsencode(self):
-        self.assertEquals(os.fsencode(b'ab\xff'), b'ab\xff')
-        self.assertEquals(os.fsencode('ab\uDCFF'), b'ab\xff')
+        check('ascii', b'abc\xff', 'abc\udcff')
+        check('iso-8859-15', b'\xef\xa4', '\xef\u20ac')
 
 
 def test_main():
@@ -1135,7 +1199,7 @@
         Pep383Tests,
         Win32KillTests,
         Win32SymlinkTests,
-        MiscTests,
+        FSEncodingTests,
     )
 
 if __name__ == "__main__":

Modified: python/branches/pep-0384/Lib/test/test_osx_env.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_osx_env.py	(original)
+++ python/branches/pep-0384/Lib/test/test_osx_env.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_pdb.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_pdb.py	(original)
+++ python/branches/pep-0384/Lib/test/test_pdb.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_pep277.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_pep277.py	(original)
+++ python/branches/pep-0384/Lib/test/test_pep277.py	Fri Aug 27 21:11:11 2010
@@ -40,6 +40,18 @@
                                 #  NFKC('\u2001') == NFKC('\u2003')
 ])
 
+
+# Is it Unicode-friendly?
+if not os.path.supports_unicode_filenames:
+    fsencoding = sys.getfilesystemencoding()
+    try:
+        for name in filenames:
+            name.encode(fsencoding)
+    except UnicodeEncodeError:
+        raise unittest.SkipTest("only NT+ and systems with "
+                                "Unicode-friendly filesystem encoding")
+
+
 # Destroy directory dirname and all files under it, to one level.
 def deltree(dirname):
     # Don't hide legitimate errors:  if one of these suckers exists, it's
@@ -63,14 +75,8 @@
         files = set()
         for name in self.files:
             name = os.path.join(support.TESTFN, self.norm(name))
-            try:
-                f = open(name, 'wb')
-            except UnicodeEncodeError:
-                if not os.path.supports_unicode_filenames:
-                    self.skipTest("only NT+ and systems with Unicode-friendly"
-                                  "filesystem encoding")
-            f.write((name+'\n').encode("utf-8"))
-            f.close()
+            with open(name, 'wb') as f:
+                f.write((name+'\n').encode("utf-8"))
             os.stat(name)
             files.add(name)
         self.files = files
@@ -126,7 +132,10 @@
         for name in others:
             if sys.platform == 'darwin' and normalize('NFD', name) in files:
                 # Mac OS X decomposes Unicode names.  See comment above.
-                os.stat(name)
+                try:
+                    os.stat(name)
+                except OSError as err:
+                    raise AssertionError("File %a doesn't exist" % name)
                 continue
             self._apply_failure(open, name, IOError)
             self._apply_failure(os.stat, name, OSError)

Modified: python/branches/pep-0384/Lib/test/test_platform.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_platform.py	(original)
+++ python/branches/pep-0384/Lib/test/test_platform.py	Fri Aug 27 21:11:11 2010
@@ -194,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/pep-0384/Lib/test/test_poplib.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_poplib.py	(original)
+++ python/branches/pep-0384/Lib/test/test_poplib.py	Fri Aug 27 21:11:11 2010
@@ -122,6 +122,7 @@
         self.active = False
         self.active_lock = threading.Lock()
         self.host, self.port = self.socket.getsockname()[:2]
+        self.handler_instance = None
 
     def start(self):
         assert not self.active
@@ -145,8 +146,7 @@
 
     def handle_accept(self):
         conn, addr = self.accept()
-        self.handler = self.handler(conn)
-        self.close()
+        self.handler_instance = self.handler(conn)
 
     def handle_connect(self):
         self.close()
@@ -287,6 +287,23 @@
         def test__all__(self):
             self.assertIn('POP3_SSL', poplib.__all__)
 
+        def test_context(self):
+            ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+            self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
+                              self.server.port, keyfile=CERTFILE, context=ctx)
+            self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
+                              self.server.port, certfile=CERTFILE, context=ctx)
+            self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
+                              self.server.port, keyfile=CERTFILE,
+                              certfile=CERTFILE, context=ctx)
+
+            self.client.quit()
+            self.client = poplib.POP3_SSL(self.server.host, self.server.port,
+                                          context=ctx)
+            self.assertIsInstance(self.client.sock, ssl.SSLSocket)
+            self.assertIs(self.client.sock.context, ctx)
+            self.assertTrue(self.client.noop().startswith(b'+OK'))
+
 
 class TestTimeouts(TestCase):
 

Modified: python/branches/pep-0384/Lib/test/test_posix.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_posix.py	(original)
+++ python/branches/pep-0384/Lib/test/test_posix.py	Fri Aug 27 21:11:11 2010
@@ -6,10 +6,12 @@
 posix = support.import_module('posix')
 
 import errno
+import sys
 import time
 import os
 import pwd
 import shutil
+import stat
 import unittest
 import warnings
 
@@ -198,6 +200,28 @@
         if hasattr(posix, 'stat'):
             self.assertTrue(posix.stat(support.TESTFN))
 
+    @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
+    def test_mkfifo(self):
+        support.unlink(support.TESTFN)
+        posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
+        self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
+
+    @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
+                         "don't have mknod()/S_IFIFO")
+    def test_mknod(self):
+        # Test using mknod() to create a FIFO (the only use specified
+        # by POSIX).
+        support.unlink(support.TESTFN)
+        mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
+        try:
+            posix.mknod(support.TESTFN, mode, 0)
+        except OSError as e:
+            # Some old systems don't allow unprivileged users to use
+            # mknod(), or only support creating device nodes.
+            self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
+        else:
+            self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
+
     def _test_all_chown_common(self, chown_func, first_param):
         """Common code for chown, fchown and lchown tests."""
         if os.getuid() == 0:
@@ -252,9 +276,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 +373,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/pep-0384/Lib/test/test_pow.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_pow.py	(original)
+++ python/branches/pep-0384/Lib/test/test_pow.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_profilehooks.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_profilehooks.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_pstats.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_pstats.py	(original)
+++ python/branches/pep-0384/Lib/test/test_pstats.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_queue.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_queue.py	(original)
+++ python/branches/pep-0384/Lib/test/test_queue.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_re.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_re.py	(original)
+++ python/branches/pep-0384/Lib/test/test_re.py	Fri Aug 27 21:11:11 2010
@@ -874,6 +874,7 @@
                 if result is None:
                     print('=== Fails on unicode-sensitive match', t)
 
+
 def test_main():
     run_unittest(ReTests)
     run_re_tests()

Modified: python/branches/pep-0384/Lib/test/test_robotparser.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_robotparser.py	(original)
+++ python/branches/pep-0384/Lib/test/test_robotparser.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_sax.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_sax.py	(original)
+++ python/branches/pep-0384/Lib/test/test_sax.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_set.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_set.py	(original)
+++ python/branches/pep-0384/Lib/test/test_set.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_signal.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_signal.py	(original)
+++ python/branches/pep-0384/Lib/test/test_signal.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_site.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_site.py	(original)
+++ python/branches/pep-0384/Lib/test/test_site.py	Fri Aug 27 21:11:11 2010
@@ -168,14 +168,14 @@
             wanted = os.path.join('xoxo', 'Lib', 'site-packages')
             self.assertEquals(dirs[0], wanted)
         elif os.sep == '/':
-            self.assertTrue(len(dirs), 2)
+            self.assertEqual(len(dirs), 2)
             wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
                                   'site-packages')
             self.assertEquals(dirs[0], wanted)
             wanted = os.path.join('xoxo', 'lib', 'site-python')
             self.assertEquals(dirs[1], wanted)
         else:
-            self.assertTrue(len(dirs), 2)
+            self.assertEqual(len(dirs), 2)
             self.assertEquals(dirs[0], 'xoxo')
             wanted = os.path.join('xoxo', 'lib', 'site-packages')
             self.assertEquals(dirs[1], wanted)
@@ -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/pep-0384/Lib/test/test_smtplib.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_smtplib.py	(original)
+++ python/branches/pep-0384/Lib/test/test_smtplib.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_socket.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_socket.py	(original)
+++ python/branches/pep-0384/Lib/test/test_socket.py	Fri Aug 27 21:11:11 2010
@@ -16,8 +16,21 @@
 from weakref import proxy
 import signal
 
+def try_address(host, port=0, family=socket.AF_INET):
+    """Try to bind a socket on the given host:port and return True
+    if that has been possible."""
+    try:
+        sock = socket.socket(family, socket.SOCK_STREAM)
+        sock.bind((host, port))
+    except (socket.error, socket.gaierror):
+        return False
+    else:
+        sock.close()
+        return True
+
 HOST = support.HOST
 MSG = b'Michael Gilfix was here\n'
+SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
 
 try:
     import _thread as thread
@@ -564,6 +577,78 @@
         self.assertRaises(ValueError, s.ioctl, -1, None)
         s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
 
+    def testGetaddrinfo(self):
+        try:
+            socket.getaddrinfo('localhost', 80)
+        except socket.gaierror as err:
+            if err.errno == socket.EAI_SERVICE:
+                # see http://bugs.python.org/issue1282647
+                self.skipTest("buggy libc version")
+            raise
+        # len of every sequence is supposed to be == 5
+        for info in socket.getaddrinfo(HOST, None):
+            self.assertEqual(len(info), 5)
+        # host can be a domain name, a string representation of an
+        # IPv4/v6 address or None
+        socket.getaddrinfo('localhost', 80)
+        socket.getaddrinfo('127.0.0.1', 80)
+        socket.getaddrinfo(None, 80)
+        if SUPPORTS_IPV6:
+            socket.getaddrinfo('::1', 80)
+        # port can be a string service name such as "http", a numeric
+        # port number or None
+        socket.getaddrinfo(HOST, "http")
+        socket.getaddrinfo(HOST, 80)
+        socket.getaddrinfo(HOST, None)
+        # test family and socktype filters
+        infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
+        for family, _, _, _, _ in infos:
+            self.assertEqual(family, socket.AF_INET)
+        infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
+        for _, socktype, _, _, _ in infos:
+            self.assertEqual(socktype, socket.SOCK_STREAM)
+        # test proto and flags arguments
+        socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
+        socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
+        # a server willing to support both IPv4 and IPv6 will
+        # usually do this
+        socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
+                           socket.AI_PASSIVE)
+        # test keyword arguments
+        a = socket.getaddrinfo(HOST, None)
+        b = socket.getaddrinfo(host=HOST, port=None)
+        self.assertEqual(a, b)
+        a = socket.getaddrinfo(HOST, None, socket.AF_INET)
+        b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
+        self.assertEqual(a, b)
+        a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
+        b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
+        self.assertEqual(a, b)
+        a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
+        b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
+        self.assertEqual(a, b)
+        a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
+        b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
+        self.assertEqual(a, b)
+        a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
+                               socket.AI_PASSIVE)
+        b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
+                               type=socket.SOCK_STREAM, proto=0,
+                               flags=socket.AI_PASSIVE)
+        self.assertEqual(a, b)
+
+    def test_getnameinfo(self):
+        # only IP addresses are allowed
+        self.assertRaises(socket.error, socket.getnameinfo, ('mail.python.org',0), 0)
+
+    def test_idna(self):
+        # these should all be successful
+        socket.gethostbyname('испытание.python.org')
+        socket.gethostbyname_ex('испытание.python.org')
+        socket.getaddrinfo('испытание.python.org',0,socket.AF_UNSPEC,socket.SOCK_STREAM)
+        # this may not work if the forward lookup choses the IPv6 address, as that doesn't
+        # have a reverse entry yet
+        # socket.gethostbyaddr('испытание.python.org')
 
 @unittest.skipUnless(thread, 'Threading required for this test.')
 class BasicTCPTest(SocketConnectedTest):
@@ -655,6 +740,23 @@
         self.serv_conn.send(MSG)
         self.serv_conn.shutdown(2)
 
+    def testDetach(self):
+        # Testing detach()
+        fileno = self.cli_conn.fileno()
+        f = self.cli_conn.detach()
+        self.assertEqual(f, fileno)
+        # cli_conn cannot be used anymore...
+        self.assertRaises(socket.error, self.cli_conn.recv, 1024)
+        self.cli_conn.close()
+        # ...but we can create another socket using the (still open)
+        # file descriptor
+        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
+        msg = sock.recv(1024)
+        self.assertEqual(msg, MSG)
+
+    def _testDetach(self):
+        self.serv_conn.send(MSG)
+
 @unittest.skipUnless(thread, 'Threading required for this test.')
 class BasicUDPTest(ThreadedUDPSocketTest):
 

Modified: python/branches/pep-0384/Lib/test/test_ssl.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_ssl.py	(original)
+++ python/branches/pep-0384/Lib/test/test_ssl.py	Fri Aug 27 21:11:11 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):
@@ -137,22 +153,6 @@
         self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
                         (s, t))
 
-    def test_ciphers(self):
-        if not support.is_resource_enabled('network'):
-            return
-        remote = ("svn.python.org", 443)
-        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
-                            cert_reqs=ssl.CERT_NONE, ciphers="ALL")
-        s.connect(remote)
-        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
-                            cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")
-        s.connect(remote)
-        # Error checking can happen at instantiation or when connecting
-        with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
-            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
-                                cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
-            s.connect(remote)
-
     @support.cpython_only
     def test_refcycle(self):
         # Issue #7943: an SSL object doesn't create reference cycles with
@@ -175,6 +175,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 +185,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 +198,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
@@ -276,6 +279,12 @@
 
 
 class NetworkedTests(unittest.TestCase):
+    def setUp(self):
+        self.old_timeout = socket.getdefaulttimeout()
+        socket.setdefaulttimeout(30)
+
+    def tearDown(self):
+        socket.setdefaulttimeout(self.old_timeout)
 
     def test_connect(self):
         s = ssl.wrap_socket(socket.socket(socket.AF_INET),
@@ -404,8 +413,6 @@
         if not pem:
             self.fail("No server certificate on svn.python.org:443!")
 
-        return
-
         try:
             pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=CERTFILE)
         except ssl.SSLError as x:
@@ -421,6 +428,20 @@
         if support.verbose:
             sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem)
 
+    def test_ciphers(self):
+        remote = ("svn.python.org", 443)
+        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
+                            cert_reqs=ssl.CERT_NONE, ciphers="ALL")
+        s.connect(remote)
+        s = ssl.wrap_socket(socket.socket(socket.AF_INET),
+                            cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")
+        s.connect(remote)
+        # Error checking can happen at instantiation or when connecting
+        with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
+            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
+                                cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
+            s.connect(remote)
+
     def test_algorithms(self):
         # Issue #8484: all algorithms should be available when verifying a
         # certificate.
@@ -937,6 +958,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 +1061,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 +1082,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 +1117,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 +1133,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:
@@ -1253,9 +1279,17 @@
                 if support.verbose:
                     sys.stdout.write(" client:  closing connection.\n")
                 s.close()
+                if support.verbose:
+                    sys.stdout.write(" client:  connection closed.\n")
             finally:
+                if support.verbose:
+                    sys.stdout.write(" cleanup: stopping server.\n")
                 server.stop()
+                if support.verbose:
+                    sys.stdout.write(" cleanup: joining server thread.\n")
                 server.join()
+                if support.verbose:
+                    sys.stdout.write(" cleanup: successfully joined.\n")
 
         def test_recv_send(self):
             """Test recv(), send() and friends."""
@@ -1424,6 +1458,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/pep-0384/Lib/test/test_strtod.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_strtod.py	(original)
+++ python/branches/pep-0384/Lib/test/test_strtod.py	Fri Aug 27 21:11:11 2010
@@ -2,7 +2,6 @@
 # introduced in Python 2.7 and 3.1.
 
 import random
-import struct
 import unittest
 import re
 import sys

Modified: python/branches/pep-0384/Lib/test/test_struct.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_struct.py	(original)
+++ python/branches/pep-0384/Lib/test/test_struct.py	Fri Aug 27 21:11:11 2010
@@ -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)
@@ -559,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/pep-0384/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_subprocess.py	(original)
+++ python/branches/pep-0384/Lib/test/test_subprocess.py	Fri Aug 27 21:11:11 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:
@@ -1052,6 +1087,48 @@
         self.assertEqual([(256, 999), (666,), (666,)], record_calls)
 
 
+ at unittest.skipUnless(mswindows, "Windows-specific tests")
+class CommandsWithSpaces (BaseTestCase):
+
+    def setUp(self):
+        super().setUp()
+        f, fname = mkstemp(".py", "te st")
+        self.fname = fname.lower ()
+        os.write(f, b"import sys;"
+                    b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
+        )
+        os.close(f)
+
+    def tearDown(self):
+        os.remove(self.fname)
+        super().tearDown()
+
+    def with_spaces(self, *args, **kwargs):
+        kwargs['stdout'] = subprocess.PIPE
+        p = subprocess.Popen(*args, **kwargs)
+        self.assertEqual(
+          p.stdout.read ().decode("mbcs"),
+          "2 [%r, 'ab cd']" % self.fname
+        )
+
+    def test_shell_string_with_spaces(self):
+        # call() function with string argument with spaces on Windows
+        self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
+                                             "ab cd"), shell=1)
+
+    def test_shell_sequence_with_spaces(self):
+        # call() function with sequence argument with spaces on Windows
+        self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
+
+    def test_noshell_string_with_spaces(self):
+        # call() function with string argument with spaces on Windows
+        self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
+                             "ab cd"))
+
+    def test_noshell_sequence_with_spaces(self):
+        # call() function with sequence argument with spaces on Windows
+        self.with_spaces([sys.executable, self.fname, "ab cd"])
+
 def test_main():
     unit_tests = (ProcessTestCase,
                   POSIXProcessTestCase,
@@ -1059,7 +1136,8 @@
                   ProcessTestCasePOSIXPurePython,
                   CommandTests,
                   ProcessTestCaseNoPoll,
-                  HelperFunctionTests)
+                  HelperFunctionTests,
+                  CommandsWithSpaces)
 
     support.run_unittest(*unit_tests)
     support.reap_children()

Modified: python/branches/pep-0384/Lib/test/test_sundry.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_sundry.py	(original)
+++ python/branches/pep-0384/Lib/test/test_sundry.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_syntax.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_syntax.py	(original)
+++ python/branches/pep-0384/Lib/test/test_syntax.py	Fri Aug 27 21:11:11 2010
@@ -484,6 +484,34 @@
 Traceback (most recent call last):
 SyntaxError: can't assign to literal
 
+Corner-cases that used to fail to raise the correct error:
+
+    >>> def f(*, x=lambda __debug__:0): pass
+    Traceback (most recent call last):
+    SyntaxError: assignment to keyword
+
+    >>> def f(*args:(lambda __debug__:0)): pass
+    Traceback (most recent call last):
+    SyntaxError: assignment to keyword
+
+    >>> def f(**kwargs:(lambda __debug__:0)): pass
+    Traceback (most recent call last):
+    SyntaxError: assignment to keyword
+
+    >>> with (lambda *:0): pass
+    Traceback (most recent call last):
+    SyntaxError: named arguments must follow bare *
+
+Corner-cases that used to crash:
+
+    >>> def f(**__debug__): pass
+    Traceback (most recent call last):
+    SyntaxError: assignment to keyword
+
+    >>> def f(*xx, __debug__): pass
+    Traceback (most recent call last):
+    SyntaxError: assignment to keyword
+
 """
 
 import re

Modified: python/branches/pep-0384/Lib/test/test_sys.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_sys.py	(original)
+++ python/branches/pep-0384/Lib/test/test_sys.py	Fri Aug 27 21:11:11 2010
@@ -6,6 +6,7 @@
 import textwrap
 import warnings
 import operator
+import codecs
 
 # count the number of test runs, used to create unique
 # strings to intern in test_intern()
@@ -86,7 +87,6 @@
     # Python/pythonrun.c::PyErr_PrintEx() is tricky.
 
     def test_exit(self):
-        import subprocess
 
         self.assertRaises(TypeError, sys.exit, 42, 42)
 
@@ -179,8 +179,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():
@@ -495,23 +495,46 @@
 
         self.assertRaises(TypeError, sys.intern, S("abc"))
 
-    def test_main_invalid_unicode(self):
-        import locale
-        non_decodable = b"\xff"
-        encoding = locale.getpreferredencoding()
-        try:
-            non_decodable.decode(encoding)
-        except UnicodeDecodeError:
-            pass
-        else:
-            self.skipTest('%r is decodable with encoding %s'
-                % (non_decodable, encoding))
-        code = b'print("' + non_decodable + b'")'
-        p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE)
+    # On Windows, pass bytes to subprocess doesn't test how Python decodes the
+    # command line, but how subprocess does decode bytes to unicode. Python
+    # doesn't decode the command line because Windows provides directly the
+    # arguments as unicode (using wmain() instead of main()).
+    @unittest.skipIf(sys.platform == 'win32',
+                     'Windows has a native unicode API')
+    def test_undecodable_code(self):
+        # Raise SkipTest() if sys.executable is not encodable to ascii
+        test.support.workaroundIssue8611()
+
+        undecodable = b"\xff"
+        env = os.environ.copy()
+        # Use C locale to get ascii for the locale encoding
+        env['LC_ALL'] = 'C'
+        code = (
+            b'import locale; '
+            b'print(ascii("' + undecodable + b'"), '
+                b'locale.getpreferredencoding())')
+        p = subprocess.Popen(
+            [sys.executable, "-c", code],
+            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+            env=env)
         stdout, stderr = p.communicate()
-        self.assertEqual(p.returncode, 1)
-        self.assert_(b"UnicodeEncodeError:" in stderr,
-            "%r not in %s" % (b"UniodeEncodeError:", ascii(stderr)))
+        if p.returncode == 1:
+            # _Py_char2wchar() decoded b'\xff' as '\udcff' (b'\xff' is not
+            # decodable from ASCII) and run_command() failed on
+            # PyUnicode_AsUTF8String(). This is the expected behaviour on
+            # Linux.
+            pattern = b"Unable to decode the command from the command line:"
+        elif p.returncode == 0:
+            # _Py_char2wchar() decoded b'\xff' as '\xff' even if the locale is
+            # C and the locale encoding is ASCII. It occurs on FreeBSD, Solaris
+            # and Mac OS X.
+            pattern = b"'\\xff' "
+            # The output is followed by the encoding name, an alias to ASCII.
+            # Examples: "US-ASCII" or "646" (ISO 646, on Solaris).
+        else:
+            raise AssertionError("Unknown exit code: %s, output=%a" % (p.returncode, stdout))
+        if not stdout.startswith(pattern):
+            raise AssertionError("%a doesn't start with %a" % (stdout, pattern))
 
     def test_sys_flags(self):
         self.assertTrue(sys.flags)
@@ -529,7 +552,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 +573,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))
@@ -564,6 +586,62 @@
         p.wait()
         self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))])
 
+    def check_fsencoding(self, fs_encoding, expected=None):
+        self.assertIsNotNone(fs_encoding)
+        codecs.lookup(fs_encoding)
+        if expected:
+            self.assertEqual(fs_encoding, expected)
+
+    def test_getfilesystemencoding(self):
+        fs_encoding = sys.getfilesystemencoding()
+        if sys.platform == 'darwin':
+            expected = 'utf-8'
+        elif sys.platform == 'win32':
+            expected = 'mbcs'
+        else:
+            expected = None
+        self.check_fsencoding(fs_encoding, expected)
+
+    @unittest.skipIf(sys.platform in ('win32', 'darwin'),
+                     'PYTHONFSENCODING is ignored on Windows and Mac OS X')
+    def test_pythonfsencoding(self):
+        def get_fsencoding(env):
+            output = subprocess.check_output(
+                [sys.executable, "-c",
+                 "import sys; print(sys.getfilesystemencoding())"],
+                env=env)
+            return output.rstrip().decode('ascii')
+
+        # Raise SkipTest() if sys.executable is not encodable to ascii
+        test.support.workaroundIssue8611()
+
+        # Use C locale to get ascii for the locale encoding
+        env = os.environ.copy()
+        env['LC_ALL'] = 'C'
+        try:
+            del env['PYTHONFSENCODING']
+        except KeyError:
+            pass
+        self.check_fsencoding(get_fsencoding(env), 'ascii')
+
+        # Filesystem encoding is hardcoded on Windows and Mac OS X
+        for encoding in ('ascii', 'cp850', 'iso8859-1', 'utf-8'):
+            env = os.environ.copy()
+            env['PYTHONFSENCODING'] = encoding
+            self.check_fsencoding(get_fsencoding(env), encoding)
+
+    def test_setfilesystemencoding(self):
+        old = sys.getfilesystemencoding()
+        try:
+            sys.setfilesystemencoding("iso-8859-1")
+            self.assertEqual(sys.getfilesystemencoding(), "iso-8859-1")
+        finally:
+            sys.setfilesystemencoding(old)
+        try:
+            self.assertRaises(LookupError, sys.setfilesystemencoding, "xxx")
+        finally:
+            sys.setfilesystemencoding(old)
+
 
 class SizeofTest(unittest.TestCase):
 
@@ -863,46 +941,6 @@
         # sys.flags
         check(sys.flags, size(vh) + self.P * len(sys.flags))
 
-    def test_getfilesystemencoding(self):
-        import codecs
-
-        def check_fsencoding(fs_encoding):
-            self.assertIsNotNone(fs_encoding)
-            if sys.platform == 'darwin':
-                self.assertEqual(fs_encoding, 'utf-8')
-            codecs.lookup(fs_encoding)
-
-        fs_encoding = sys.getfilesystemencoding()
-        check_fsencoding(fs_encoding)
-
-        # Even in C locale
-        try:
-            sys.executable.encode('ascii')
-        except UnicodeEncodeError:
-            # Python doesn't start with ASCII locale if its path is not ASCII,
-            # see issue #8611
-            pass
-        else:
-            env = os.environ.copy()
-            env['LANG'] = 'C'
-            output = subprocess.check_output(
-                [sys.executable, "-c",
-                 "import sys; print(sys.getfilesystemencoding())"],
-                env=env)
-            fs_encoding = output.rstrip().decode('ascii')
-            check_fsencoding(fs_encoding)
-
-    def test_setfilesystemencoding(self):
-        old = sys.getfilesystemencoding()
-        try:
-            sys.setfilesystemencoding("iso-8859-1")
-            self.assertEqual(sys.getfilesystemencoding(), "iso-8859-1")
-        finally:
-            sys.setfilesystemencoding(old)
-        try:
-            self.assertRaises(LookupError, sys.setfilesystemencoding, "xxx")
-        finally:
-            sys.setfilesystemencoding(old)
 
 def test_main():
     test.support.run_unittest(SysModuleTest, SizeofTest)

Modified: python/branches/pep-0384/Lib/test/test_tcl.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_tcl.py	(original)
+++ python/branches/pep-0384/Lib/test/test_tcl.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_threaded_import.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_threaded_import.py	(original)
+++ python/branches/pep-0384/Lib/test/test_threaded_import.py	Fri Aug 27 21:11:11 2010
@@ -5,15 +5,26 @@
 # complains several times about module random having no attribute
 # randrange, and then Python hangs.
 
+import os
 import imp
 import sys
+import time
+import shutil
 import unittest
-from test.support import verbose, TestFailed, import_module, run_unittest
+from test.support import verbose, import_module, run_unittest, TESTFN
 thread = import_module('_thread')
+threading = import_module('threading')
 
 def task(N, done, done_tasks, errors):
     try:
-        import random
+        # We don't use modulefinder but still import it in order to stress
+        # importing of different modules from several threads.
+        if len(done_tasks) % 2:
+            import modulefinder
+            import random
+        else:
+            import random
+            import modulefinder
         # This will fail if random is not completely initialized
         x = random.randrange(1, 3)
     except Exception as e:
@@ -24,6 +35,52 @@
         if finished:
             done.release()
 
+# Create a circular import structure: A -> C -> B -> D -> A
+# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
+
+circular_imports_modules = {
+    'A': """if 1:
+        import time
+        time.sleep(%(delay)s)
+        x = 'a'
+        import C
+        """,
+    'B': """if 1:
+        import time
+        time.sleep(%(delay)s)
+        x = 'b'
+        import D
+        """,
+    'C': """import B""",
+    'D': """import A""",
+}
+
+class Finder:
+    """A dummy finder to detect concurrent access to its find_module()
+    method."""
+
+    def __init__(self):
+        self.numcalls = 0
+        self.x = 0
+        self.lock = thread.allocate_lock()
+
+    def find_module(self, name, path=None):
+        # Simulate some thread-unsafe behaviour. If calls to find_module()
+        # are properly serialized, `x` will end up the same as `numcalls`.
+        # Otherwise not.
+        with self.lock:
+            self.numcalls += 1
+        x = self.x
+        time.sleep(0.1)
+        self.x = x + 1
+
+class FlushingFinder:
+    """A dummy finder which flushes sys.path_importer_cache when it gets
+    called."""
+
+    def find_module(self, name, path=None):
+        sys.path_importer_cache.clear()
+
 
 class ThreadedImportTests(unittest.TestCase):
 
@@ -37,7 +94,7 @@
         if self.old_random is not None:
             sys.modules['random'] = self.old_random
 
-    def test_parallel_module_init(self):
+    def check_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")
@@ -47,11 +104,12 @@
         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
+            # Make sure that random and modulefinder get reimported freshly
+            for modname in ['random', 'modulefinder']:
+                try:
+                    del sys.modules[modname]
+                except KeyError:
+                    pass
             errors = []
             done_tasks = []
             for i in range(N):
@@ -62,6 +120,42 @@
                 print("OK.")
         done.release()
 
+    def test_parallel_module_init(self):
+        self.check_parallel_module_init()
+
+    def test_parallel_meta_path(self):
+        finder = Finder()
+        sys.meta_path.append(finder)
+        try:
+            self.check_parallel_module_init()
+            self.assertGreater(finder.numcalls, 0)
+            self.assertEqual(finder.x, finder.numcalls)
+        finally:
+            sys.meta_path.remove(finder)
+
+    def test_parallel_path_hooks(self):
+        # Here the Finder instance is only used to check concurrent calls
+        # to path_hook().
+        finder = Finder()
+        # In order for our path hook to be called at each import, we need
+        # to flush the path_importer_cache, which we do by registering a
+        # dedicated meta_path entry.
+        flushing_finder = FlushingFinder()
+        def path_hook(path):
+            finder.find_module('')
+            raise ImportError
+        sys.path_hooks.append(path_hook)
+        sys.meta_path.append(flushing_finder)
+        try:
+            # Flush the cache a first time
+            flushing_finder.find_module('')
+            numtests = self.check_parallel_module_init()
+            self.assertGreater(finder.numcalls, 0)
+            self.assertEqual(finder.x, finder.numcalls)
+        finally:
+            sys.meta_path.remove(flushing_finder)
+            sys.path_hooks.remove(path_hook)
+
     def test_import_hangers(self):
         # In case this test is run again, make sure the helper module
         # gets loaded from scratch again.
@@ -72,10 +166,46 @@
         import test.threaded_import_hangers
         self.assertFalse(test.threaded_import_hangers.errors)
 
+    def test_circular_imports(self):
+        # The goal of this test is to exercise implementations of the import
+        # lock which use a per-module lock, rather than a global lock.
+        # In these implementations, there is a possible deadlock with
+        # circular imports, for example:
+        # - thread 1 imports A (grabbing the lock for A) which imports B
+        # - thread 2 imports B (grabbing the lock for B) which imports A
+        # Such implementations should be able to detect such situations and
+        # resolve them one way or the other, without freezing.
+        # NOTE: our test constructs a slightly less trivial import cycle,
+        # in order to better stress the deadlock avoidance mechanism.
+        delay = 0.5
+        os.mkdir(TESTFN)
+        self.addCleanup(shutil.rmtree, TESTFN)
+        sys.path.insert(0, TESTFN)
+        self.addCleanup(sys.path.remove, TESTFN)
+        for name, contents in circular_imports_modules.items():
+            contents = contents % {'delay': delay}
+            with open(os.path.join(TESTFN, name + ".py"), "wb") as f:
+                f.write(contents.encode('utf-8'))
+            self.addCleanup(sys.modules.pop, name, None)
+
+        results = []
+        def import_ab():
+            import A
+            results.append(getattr(A, 'x', None))
+        def import_ba():
+            import B
+            results.append(getattr(B, 'x', None))
+        t1 = threading.Thread(target=import_ab)
+        t2 = threading.Thread(target=import_ba)
+        t1.start()
+        t2.start()
+        t1.join()
+        t2.join()
+        self.assertEqual(set(results), {'a', 'b'})
+
 
 def test_main():
     run_unittest(ThreadedImportTests)
 
-
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-0384/Lib/test/test_threading.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_threading.py	(original)
+++ python/branches/pep-0384/Lib/test/test_threading.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_threading_local.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_threading_local.py	(original)
+++ python/branches/pep-0384/Lib/test/test_threading_local.py	Fri Aug 27 21:11:11 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))
@@ -32,9 +38,9 @@
         gc.collect()
         self.assertEqual(len(weaklist), n)
 
-        # XXX threading.local keeps the local of the last stopped thread alive.
+        # XXX _threading_local keeps the local of the last stopped thread alive.
         deadlist = [weak for weak in weaklist if weak() is None]
-        self.assertEqual(len(deadlist), n-1)
+        self.assertIn(len(deadlist), (n-1, n))
 
         # Assignment to the same thread local frees it sometimes (!)
         local.someothervar = None
@@ -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,51 @@
 
     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
+
+    # Fails for the pure Python implementation
+    def test_cycle_collection(self):
+        class X:
+            pass
+
+        x = X()
+        x.local = self._local()
+        x.local.x = x
+        wr = weakref.ref(x)
+        del x
+        gc.collect()
+        self.assertIs(wr(), None)
+
 
-        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/pep-0384/Lib/test/test_tokenize.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_tokenize.py	(original)
+++ python/branches/pep-0384/Lib/test/test_tokenize.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/test/test_types.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_types.py	(original)
+++ python/branches/pep-0384/Lib/test/test_types.py	Fri Aug 27 21:11:11 2010
@@ -550,6 +550,11 @@
         for code in 'xXobns':
             self.assertRaises(ValueError, format, 0, ',' + code)
 
+    def test_internal_sizes(self):
+        self.assertGreater(object.__basicsize__, 0)
+        self.assertGreater(tuple.__itemsize__, 0)
+
+
 def test_main():
     run_unittest(TypesTests)
 

Modified: python/branches/pep-0384/Lib/test/test_unicode.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_unicode.py	(original)
+++ python/branches/pep-0384/Lib/test/test_unicode.py	Fri Aug 27 21:11:11 2010
@@ -519,11 +519,6 @@
                     return 'G(' + self.x + ')'
                 return object.__format__(self, format_spec)
 
-        # class that returns a bad type from __format__
-        class H:
-            def __format__(self, format_spec):
-                return 1.0
-
         class I(datetime.date):
             def __format__(self, format_spec):
                 return self.strftime(format_spec)
@@ -1358,6 +1353,10 @@
         self.assertEqual(repr(s1()), '\\n')
         self.assertEqual(repr(s2()), '\\n')
 
+    def test_printable_repr(self):
+        self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
+        self.assertEqual(repr('\U00011000'), "'\\U00011000'")     # nonprintable
+
     def test_expandtabs_overflows_gracefully(self):
         # This test only affects 32-bit platforms because expandtabs can only take
         # an int as the max value, not a 64-bit C long.  If expandtabs is changed

Modified: python/branches/pep-0384/Lib/test/test_unicode_file.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_unicode_file.py	(original)
+++ python/branches/pep-0384/Lib/test/test_unicode_file.py	Fri Aug 27 21:11:11 2010
@@ -5,8 +5,9 @@
 import unicodedata
 
 import unittest
-from test.support import run_unittest, TESTFN_UNICODE, rmtree
-from test.support import TESTFN_ENCODING, TESTFN_UNICODE_UNENCODEABLE
+from test.support import (run_unittest, rmtree,
+    TESTFN_ENCODING, TESTFN_UNICODE, TESTFN_UNENCODABLE)
+
 try:
     TESTFN_UNICODE.encode(TESTFN_ENCODING)
 except (UnicodeError, TypeError):
@@ -146,8 +147,8 @@
     # _test functions with each of the filename combinations we wish to test
     def test_single_files(self):
         self._test_single(TESTFN_UNICODE)
-        if TESTFN_UNICODE_UNENCODEABLE is not None:
-            self._test_single(TESTFN_UNICODE_UNENCODEABLE)
+        if TESTFN_UNENCODABLE is not None:
+            self._test_single(TESTFN_UNENCODABLE)
 
     def test_directories(self):
         # For all 'equivalent' combinations:
@@ -156,9 +157,9 @@
         ext = ".dir"
         self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext, False)
         # Our directory name that can't use a non-unicode name.
-        if TESTFN_UNICODE_UNENCODEABLE is not None:
-            self._do_directory(TESTFN_UNICODE_UNENCODEABLE+ext,
-                               TESTFN_UNICODE_UNENCODEABLE+ext,
+        if TESTFN_UNENCODABLE is not None:
+            self._do_directory(TESTFN_UNENCODABLE+ext,
+                               TESTFN_UNENCODABLE+ext,
                                False)
 
 def test_main():

Modified: python/branches/pep-0384/Lib/test/test_unicodedata.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_unicodedata.py	(original)
+++ python/branches/pep-0384/Lib/test/test_unicodedata.py	Fri Aug 27 21:11:11 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),
@@ -295,6 +294,14 @@
                 self.assertEqual(len(lines), 1,
                                  r"\u%.4x should not be a linebreak" % i)
 
+    def test_UCS4(self):
+        # unicodedata should work with code points outside the BMP
+        # even on a narrow Unicode build
+        self.assertEqual(self.db.category("\U0001012A"), "No")
+        self.assertEqual(self.db.numeric("\U0001012A"), 9000)
+        self.assertEqual(self.db.decimal("\U0001D7FD"), 7)
+        self.assertEqual(self.db.digit("\U0001D7FD"), 7)
+
 def test_main():
     test.support.run_unittest(
         UnicodeMiscTest,

Modified: python/branches/pep-0384/Lib/test/test_urllib.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_urllib.py	(original)
+++ python/branches/pep-0384/Lib/test/test_urllib.py	Fri Aug 27 21:11:11 2010
@@ -102,7 +102,7 @@
         self.assertEqual(self.returned_obj.geturl(), self.pathname)
 
     def test_getcode(self):
-        self.assertEqual(self.returned_obj.getcode(), None)
+        self.assertIsNone(self.returned_obj.getcode())
 
     def test_iter(self):
         # Test iterator
@@ -131,7 +131,7 @@
         self.env.set('NO_PROXY', 'localhost')
         proxies = urllib.request.getproxies_environment()
         # getproxies_environment use lowered case truncated (no '_proxy') keys
-        self.assertEquals('localhost', proxies['no'])
+        self.assertEqual('localhost', proxies['no'])
 
 
 class urlopen_HttpTests(unittest.TestCase):
@@ -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,7 +570,10 @@
         self.assertEqual(result.count('%'), 1,
                          "using unquote(): not all characters escaped: "
                          "%s" % result)
-        self.assertRaises(TypeError, urllib.parse.unquote, None)
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
+        self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
+        with support.check_warnings(('', BytesWarning), quiet=True):
+            self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, b'')
 
     def test_unquoting_badpercent(self):
         # Test unquoting on bad percent-escapes
@@ -589,8 +608,8 @@
         result = urllib.parse.unquote_to_bytes(given)
         self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
                          % (expect, result))
-
-        self.assertRaises(TypeError, urllib.parse.unquote_to_bytes, None)
+        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/pep-0384/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_urllib2.py	(original)
+++ python/branches/pep-0384/Lib/test/test_urllib2.py	Fri Aug 27 21:11:11 2010
@@ -41,7 +41,7 @@
             ('a="b\\"c", d="e\\,f", g="h\\\\i"',
              ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
         for string, list in tests:
-            self.assertEquals(urllib.request.parse_http_list(string), list)
+            self.assertEqual(urllib.request.parse_http_list(string), list)
 
 
 def test_request_headers_dict():
@@ -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:]
@@ -739,9 +743,9 @@
                 h.file_open(req)
             # XXXX remove OSError when bug fixed
             except (urllib.error.URLError, OSError):
-                self.assertTrue(not ftp)
+                self.assertFalse(ftp)
             else:
-                self.assertTrue(o.req is req)
+                self.assertIs(o.req, req)
                 self.assertEqual(req.type, "ftp")
             self.assertEqual(req.type is "ftp", ftp)
 
@@ -844,19 +848,19 @@
         # all 2xx are passed through
         r = MockResponse(200, "OK", {}, "", url)
         newr = h.http_response(req, r)
-        self.assertTrue(r is newr)
-        self.assertTrue(not hasattr(o, "proto"))  # o.error not called
+        self.assertIs(r, newr)
+        self.assertFalse(hasattr(o, "proto"))  # o.error not called
         r = MockResponse(202, "Accepted", {}, "", url)
         newr = h.http_response(req, r)
-        self.assertTrue(r is newr)
-        self.assertTrue(not hasattr(o, "proto"))  # o.error not called
+        self.assertIs(r, newr)
+        self.assertFalse(hasattr(o, "proto"))  # o.error not called
         r = MockResponse(206, "Partial content", {}, "", url)
         newr = h.http_response(req, r)
-        self.assertTrue(r is newr)
-        self.assertTrue(not hasattr(o, "proto"))  # o.error not called
+        self.assertIs(r, newr)
+        self.assertFalse(hasattr(o, "proto"))  # o.error not called
         # anything else calls o.error (and MockOpener returns None, here)
         r = MockResponse(502, "Bad gateway", {}, "", url)
-        self.assertTrue(h.http_response(req, r) is None)
+        self.assertIsNone(h.http_response(req, r))
         self.assertEqual(o.proto, "http")  # o.error called
         self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
 
@@ -868,12 +872,14 @@
         req = Request("http://example.com/")
         r = MockResponse(200, "OK", {}, "")
         newreq = h.http_request(req)
-        self.assertTrue(cj.ach_req is req is newreq)
-        self.assertEquals(req.get_origin_req_host(), "example.com")
-        self.assertTrue(not req.is_unverifiable())
+        self.assertIs(cj.ach_req, req)
+        self.assertIs(cj.ach_req, newreq)
+        self.assertEqual(req.get_origin_req_host(), "example.com")
+        self.assertFalse(req.is_unverifiable())
         newr = h.http_response(req, r)
-        self.assertTrue(cj.ec_req is req)
-        self.assertTrue(cj.ec_r is r is newr)
+        self.assertIs(cj.ec_req, req)
+        self.assertIs(cj.ec_r, r)
+        self.assertIs(r, newr)
 
     def test_redirect(self):
         from_url = "http://example.com/a.html"
@@ -901,7 +907,7 @@
                 try:
                     self.assertEqual(o.req.get_method(), "GET")
                 except AttributeError:
-                    self.assertTrue(not o.req.has_data())
+                    self.assertFalse(o.req.has_data())
 
                 # now it's a GET, there should not be headers regarding content
                 # (possibly dragged from before being a POST)
@@ -960,7 +966,7 @@
         cp = urllib.request.HTTPCookieProcessor(cj)
         o = build_test_opener(hh, hdeh, hrh, cp)
         o.open("http://www.example.com/")
-        self.assertTrue(not hh.req.has_header("Cookie"))
+        self.assertFalse(hh.req.has_header("Cookie"))
 
     def test_proxy(self):
         o = OpenerDirector()
@@ -1194,11 +1200,8 @@
         self.opener_has_handler(o, MyOtherHTTPHandler)
 
     def opener_has_handler(self, opener, handler_class):
-        for h in opener.handlers:
-            if h.__class__ == handler_class:
-                break
-        else:
-            self.assertTrue(False)
+        self.assertTrue(any(h.__class__ == handler_class
+                            for h in opener.handlers))
 
 class RequestTests(unittest.TestCase):
 
@@ -1213,7 +1216,7 @@
         self.assertEqual("GET", self.get.get_method())
 
     def test_add_data(self):
-        self.assertTrue(not self.get.has_data())
+        self.assertFalse(self.get.has_data())
         self.assertEqual("GET", self.get.get_method())
         self.get.add_data("spam")
         self.assertTrue(self.get.has_data())
@@ -1239,12 +1242,22 @@
         self.assertEqual("www.python.org", req.get_host())
 
     def test_proxy(self):
-        self.assertTrue(not self.get.has_proxy())
+        self.assertFalse(self.get.has_proxy())
         self.get.set_proxy("www.perl.org", "http")
         self.assertTrue(self.get.has_proxy())
         self.assertEqual("www.python.org", self.get.get_origin_req_host())
         self.assertEqual("www.perl.org", self.get.get_host())
 
+    def test_wrapped_url(self):
+        req = Request("<URL:http://www.python.org>")
+        self.assertEqual("www.python.org", req.get_host())
+
+    def test_urlwith_fragment(self):
+        req = Request("http://www.python.org/?qs=query#fragment=true")
+        self.assertEqual("/?qs=query", req.get_selector())
+        req = Request("http://www.python.org/#fun=true")
+        self.assertEqual("/", req.get_selector())
+
 
 def test_main(verbose=None):
     from test import test_urllib2

Modified: python/branches/pep-0384/Lib/test/test_urllib2_localnet.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_urllib2_localnet.py	(original)
+++ python/branches/pep-0384/Lib/test/test_urllib2_localnet.py	Fri Aug 27 21:11:11 2010
@@ -172,7 +172,7 @@
             auth_validated = False
 
             # MSIE uses short_path in its validation, but Python's
-            # urllib2 uses the full path, so we're going to see if
+            # urllib.request uses the full path, so we're going to see if
             # either of them works here.
 
             for path in [request_handler.path, request_handler.short_path]:
@@ -308,8 +308,9 @@
 
         def do_GET(self):
             body = self.send_head()
-            if body:
-                self.wfile.write(body)
+            while body:
+                done = self.wfile.write(body)
+                body = body[done:]
 
         def do_POST(self):
             content_length = self.headers["Content-Length"]
@@ -340,7 +341,7 @@
 
 
 class TestUrlopen(BaseTestCase):
-    """Tests urllib2.urlopen using the network.
+    """Tests urllib.request.urlopen using the network.
 
     These tests are not exhaustive.  Assuming that testing using files does a
     good job overall of some of the basic interface features.  There are no
@@ -392,8 +393,8 @@
 
         handler = self.start_server(responses)
         data = self.urlopen("http://localhost:%s/" % handler.port)
-        self.assertEquals(data, expected_response)
-        self.assertEquals(handler.requests, ["/", "/somewhere_else"])
+        self.assertEqual(data, expected_response)
+        self.assertEqual(handler.requests, ["/", "/somewhere_else"])
 
     def test_chunked(self):
         expected_response = b"hello world"
@@ -407,7 +408,7 @@
         response = [(200, [("Transfer-Encoding", "chunked")], chunked_start)]
         handler = self.start_server(response)
         data = self.urlopen("http://localhost:%s/" % handler.port)
-        self.assertEquals(data, expected_response)
+        self.assertEqual(data, expected_response)
 
     def test_404(self):
         expected_response = b"Bad bad bad..."
@@ -421,23 +422,23 @@
         else:
             self.fail("404 should raise URLError")
 
-        self.assertEquals(data, expected_response)
-        self.assertEquals(handler.requests, ["/weeble"])
+        self.assertEqual(data, expected_response)
+        self.assertEqual(handler.requests, ["/weeble"])
 
     def test_200(self):
         expected_response = b"pycon 2008..."
         handler = self.start_server([(200, [], expected_response)])
         data = self.urlopen("http://localhost:%s/bizarre" % handler.port)
-        self.assertEquals(data, expected_response)
-        self.assertEquals(handler.requests, ["/bizarre"])
+        self.assertEqual(data, expected_response)
+        self.assertEqual(handler.requests, ["/bizarre"])
 
     def test_200_with_parameters(self):
         expected_response = b"pycon 2008..."
         handler = self.start_server([(200, [], expected_response)])
         data = self.urlopen("http://localhost:%s/bizarre" % handler.port,
                              b"get=with_feeling")
-        self.assertEquals(data, expected_response)
-        self.assertEquals(handler.requests, ["/bizarre", b"get=with_feeling"])
+        self.assertEqual(data, expected_response)
+        self.assertEqual(handler.requests, ["/bizarre", b"get=with_feeling"])
 
     def test_sending_headers(self):
         handler = self.start_server()
@@ -501,6 +502,25 @@
                           urllib.request.urlopen,
                           "http://sadflkjsasf.i.nvali.d./")
 
+    def test_iteration(self):
+        expected_response = b"pycon 2008..."
+        handler = self.start_server([(200, [], expected_response)])
+        data = urllib.request.urlopen("http://localhost:%s" % handler.port)
+        for line in data:
+            self.assertEqual(line, expected_response)
+
+    def test_line_iteration(self):
+        lines = [b"We\n", b"got\n", b"here\n", b"verylong " * 8192 + b"\n"]
+        expected_response = b"".join(lines)
+        handler = self.start_server([(200, [], expected_response)])
+        data = urllib.request.urlopen("http://localhost:%s" % handler.port)
+        for index, line in enumerate(data):
+            self.assertEqual(line, lines[index],
+                             "Fetched line number %s doesn't match expected:\n"
+                             "    Expected length was %s, got %s" %
+                             (index, len(lines[index]), len(line)))
+        self.assertEqual(index + 1, len(lines))
+
 def test_main():
     support.run_unittest(ProxyAuthTests, TestUrlopen)
 

Modified: python/branches/pep-0384/Lib/test/test_urllib2net.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_urllib2net.py	(original)
+++ python/branches/pep-0384/Lib/test/test_urllib2net.py	Fri Aug 27 21:11:11 2010
@@ -149,6 +149,13 @@
 
 ##             self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
 
+    def test_urlwithfrag(self):
+        urlwith_frag = "http://docs.python.org/glossary.html#glossary"
+        req = urllib.request.Request(urlwith_frag)
+        res = urllib.request.urlopen(req)
+        self.assertEqual(res.geturl(),
+                "http://docs.python.org/glossary.html")
+
     def _test_urls(self, urls, handlers, retry=True):
         import time
         import logging

Modified: python/branches/pep-0384/Lib/test/test_urlparse.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_urlparse.py	(original)
+++ python/branches/pep-0384/Lib/test/test_urlparse.py	Fri Aug 27 21:11:11 2010
@@ -461,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/pep-0384/Lib/test/test_winsound.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_winsound.py	(original)
+++ python/branches/pep-0384/Lib/test/test_winsound.py	Fri Aug 27 21:11:11 2010
@@ -6,9 +6,9 @@
 import time
 import os
 import subprocess
-import ctypes
 
 winsound = support.import_module('winsound')
+ctypes = support.import_module('ctypes')
 import winreg
 
 def has_sound(sound):

Modified: python/branches/pep-0384/Lib/test/test_xml_etree.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_xml_etree.py	(original)
+++ python/branches/pep-0384/Lib/test/test_xml_etree.py	Fri Aug 27 21:11:11 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 = """\
@@ -66,14 +71,14 @@
     if not hasattr(method, '__call__'):
         print(method, "not callable")
 
-def serialize(elem, to_string=True, **options):
+def serialize(elem, to_string=True, encoding='unicode', **options):
     import io
-    if options.get("encoding"):
+    if encoding != 'unicode':
         file = io.BytesIO()
     else:
         file = io.StringIO()
     tree = ET.ElementTree(elem)
-    tree.write(file, **options)
+    tree.write(file, encoding=encoding, **options)
     if to_string:
         return file.getvalue()
     else:
@@ -532,7 +537,7 @@
     >>> elem.set('testa', 'testval')
     >>> elem.set('testb', 'test2')
     >>> ET.tostring(elem)
-    '<test testa="testval" testb="test2">aa</test>'
+    b'<test testa="testval" testb="test2">aa</test>'
     >>> sorted(elem.keys())
     ['testa', 'testb']
     >>> sorted(elem.items())
@@ -542,7 +547,7 @@
     >>> elem.attrib['testb'] = 'test1'
     >>> elem.attrib['testc'] = 'test2'
     >>> ET.tostring(elem)
-    '<test testa="testval" testb="test1" testc="test2">aa</test>'
+    b'<test testa="testval" testb="test1" testc="test2">aa</test>'
     """
 
 def makeelement():
@@ -582,7 +587,7 @@
 
     >>> tree = ET.parse(SIMPLE_XMLFILE)
     >>> normalize_crlf(tree)
-    >>> tree.write(sys.stdout)
+    >>> tree.write(sys.stdout, encoding='unicode')
     <root>
        <element key="value">text</element>
        <element>text</element>tail
@@ -590,7 +595,7 @@
     </root>
     >>> tree = ET.parse(SIMPLE_NS_XMLFILE)
     >>> normalize_crlf(tree)
-    >>> tree.write(sys.stdout)
+    >>> tree.write(sys.stdout, encoding='unicode')
     <ns0:root xmlns:ns0="namespace">
        <ns0:element key="value">text</ns0:element>
        <ns0:element>text</ns0:element>tail
@@ -631,17 +636,17 @@
 def parseliteral():
     """
     >>> element = ET.XML("<html><body>text</body></html>")
-    >>> ET.ElementTree(element).write(sys.stdout)
+    >>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
     <html><body>text</body></html>
     >>> element = ET.fromstring("<html><body>text</body></html>")
-    >>> ET.ElementTree(element).write(sys.stdout)
+    >>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
     <html><body>text</body></html>
     >>> sequence = ["<html><body>", "text</bo", "dy></html>"]
     >>> element = ET.fromstringlist(sequence)
-    >>> print(ET.tostring(element))
-    <html><body>text</body></html>
-    >>> print("".join(ET.tostringlist(element)))
-    <html><body>text</body></html>
+    >>> ET.tostring(element)
+    b'<html><body>text</body></html>'
+    >>> b"".join(ET.tostringlist(element))
+    b'<html><body>text</body></html>'
     >>> ET.tostring(element, "ascii")
     b"<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
     >>> _, ids = ET.XMLID("<html><body>text</body></html>")
@@ -870,10 +875,10 @@
     """
     >>> elem = ET.XML("<html><body>text</body></html>")
     >>> ET.tostring(elem)
-    '<html><body>text</body></html>'
+    b'<html><body>text</body></html>'
     >>> elem = ET.fromstring("<html><body>text</body></html>")
     >>> ET.tostring(elem)
-    '<html><body>text</body></html>'
+    b'<html><body>text</body></html>'
     """
 
 def check_encoding(encoding):
@@ -1228,14 +1233,14 @@
     Test ProcessingInstruction directly
 
     >>> ET.tostring(ET.ProcessingInstruction('test', 'instruction'))
-    '<?test instruction?>'
+    b'<?test instruction?>'
     >>> ET.tostring(ET.PI('test', 'instruction'))
-    '<?test instruction?>'
+    b'<?test instruction?>'
 
     Issue #2746
 
     >>> ET.tostring(ET.PI('test', '<testing&>'))
-    '<?test <testing&>?>'
+    b'<?test <testing&>?>'
     >>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin1')
     b"<?xml version='1.0' encoding='latin1'?>\\n<?test <testing&>\\xe3?>"
     """
@@ -1272,6 +1277,14 @@
 
 XINCLUDE["count.txt"] = "324387"
 
+XINCLUDE["C2b.xml"] = """\
+<?xml version='1.0'?>
+<document xmlns:xi="http://www.w3.org/2001/XInclude">
+  <p>This document has been <em>accessed</em>
+  <xi:include href="count.txt" parse="text"/> times.</p>
+</document>
+"""
+
 XINCLUDE["C3.xml"] = """\
 <?xml version='1.0'?>
 <document xmlns:xi="http://www.w3.org/2001/XInclude">
@@ -1347,6 +1360,16 @@
       324387 times.</p>
     </document>
 
+    Textual inclusion after sibling element (based on modified XInclude C.2)
+
+    >>> document = xinclude_loader("C2b.xml")
+    >>> ElementInclude.include(document, xinclude_loader)
+    >>> print(serialize(document)) # C2b
+    <document>
+      <p>This document has been <em>accessed</em>
+      324387 times.</p>
+    </document>
+
     Textual inclusion of XML example (XInclude C.3)
 
     >>> document = xinclude_loader("C3.xml")
@@ -1638,11 +1661,11 @@
 
     >>> e = ET.Element('SomeTag', text="def _f():\n  return 3\n")
     >>> ET.tostring(e)
-    '<SomeTag text="def _f():&#10;  return 3&#10;" />'
+    b'<SomeTag text="def _f():&#10;  return 3&#10;" />'
     >>> ET.XML(ET.tostring(e)).get("text")
     'def _f():\n  return 3\n'
     >>> ET.tostring(ET.XML(ET.tostring(e)))
-    '<SomeTag text="def _f():&#10;  return 3&#10;" />'
+    b'<SomeTag text="def _f():&#10;  return 3&#10;" />'
 
     """
 
@@ -1693,15 +1716,15 @@
     """
 
     >>> ET.tostring(ET.Element("{http://namespace.invalid/does/not/exist/}title"))
-    '<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />'
+    b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />'
     >>> ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/")
     >>> ET.tostring(ET.Element("{http://namespace.invalid/does/not/exist/}title"))
-    '<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />'
+    b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />'
 
     And the Dublin Core namespace is in the default list:
 
     >>> ET.tostring(ET.Element("{http://purl.org/dc/elements/1.1/}title"))
-    '<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />'
+    b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />'
 
     """
 
@@ -1787,7 +1810,7 @@
     '{${stuff}}localname'
     >>> t = ET.ElementTree(e)
     >>> ET.tostring(e)
-    '<ns0:localname xmlns:ns0="${stuff}" />'
+    b'<ns0:localname xmlns:ns0="${stuff}" />'
 
     """
 

Modified: python/branches/pep-0384/Lib/test/test_zipfile.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_zipfile.py	(original)
+++ python/branches/pep-0384/Lib/test/test_zipfile.py	Fri Aug 27 21:11:11 2010
@@ -662,6 +662,27 @@
 
 
 class OtherTests(unittest.TestCase):
+    zips_with_bad_crc = {
+        zipfile.ZIP_STORED: (
+            b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
+            b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
+            b'ilehello,AworldP'
+            b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
+            b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
+            b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
+            b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
+            b'\0\0/\0\0\0\0\0'),
+        zipfile.ZIP_DEFLATED: (
+            b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
+            b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
+            b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
+            b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
+            b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
+            b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
+            b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
+            b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
+    }
+
     def test_unicode_filenames(self):
         with zipfile.ZipFile(TESTFN, "w") as zf:
             zf.writestr("foo.txt", "Test for unicode filename")
@@ -875,6 +896,49 @@
         with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
             self.assertEqual(zipfr.comment, comment2)
 
+    def check_testzip_with_bad_crc(self, compression):
+        """Tests that files with bad CRCs return their name from testzip."""
+        zipdata = self.zips_with_bad_crc[compression]
+
+        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
+            # testzip returns the name of the first corrupt file, or None
+            self.assertEqual('afile', zipf.testzip())
+
+    def test_testzip_with_bad_crc_stored(self):
+        self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
+
+    @skipUnless(zlib, "requires zlib")
+    def test_testzip_with_bad_crc_deflated(self):
+        self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
+
+    def check_read_with_bad_crc(self, compression):
+        """Tests that files with bad CRCs raise a BadZipfile exception when read."""
+        zipdata = self.zips_with_bad_crc[compression]
+
+        # Using ZipFile.read()
+        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
+            self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
+
+        # Using ZipExtFile.read()
+        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
+            with zipf.open('afile', 'r') as corrupt_file:
+                self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
+
+        # Same with small reads (in order to exercise the buffering logic)
+        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
+            with zipf.open('afile', 'r') as corrupt_file:
+                corrupt_file.MIN_READ_SIZE = 2
+                with self.assertRaises(zipfile.BadZipfile):
+                    while corrupt_file.read(2):
+                        pass
+
+    def test_read_with_bad_crc_stored(self):
+        self.check_read_with_bad_crc(zipfile.ZIP_STORED)
+
+    @skipUnless(zlib, "requires zlib")
+    def test_read_with_bad_crc_deflated(self):
+        self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
+
     def tearDown(self):
         unlink(TESTFN)
         unlink(TESTFN2)
@@ -974,6 +1038,11 @@
         for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
             self.zip_test(f, zipfile.ZIP_STORED)
 
+    @skipUnless(zlib, "requires zlib")
+    def test_deflated(self):
+        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
+            self.zip_test(f, zipfile.ZIP_DEFLATED)
+
     def zip_open_test(self, f, compression):
         self.make_test_archive(f, compression)
 
@@ -1007,6 +1076,11 @@
         for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
             self.zip_open_test(f, zipfile.ZIP_STORED)
 
+    @skipUnless(zlib, "requires zlib")
+    def test_open_deflated(self):
+        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
+            self.zip_open_test(f, zipfile.ZIP_DEFLATED)
+
     def zip_random_open_test(self, f, compression):
         self.make_test_archive(f, compression)
 
@@ -1028,6 +1102,11 @@
         for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
             self.zip_random_open_test(f, zipfile.ZIP_STORED)
 
+    @skipUnless(zlib, "requires zlib")
+    def test_random_open_deflated(self):
+        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
+            self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
+
 
 @skipUnless(zlib, "requires zlib")
 class TestsWithMultipleOpens(unittest.TestCase):

Modified: python/branches/pep-0384/Lib/test/test_zipimport.py
==============================================================================
--- python/branches/pep-0384/Lib/test/test_zipimport.py	(original)
+++ python/branches/pep-0384/Lib/test/test_zipimport.py	Fri Aug 27 21:11:11 2010
@@ -382,6 +382,20 @@
         files = {TESTMOD + ".py": (NOW, raise_src)}
         self.doTest(None, files, TESTMOD, call=self.doTraceback)
 
+    @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
+                     "need an unencodable filename")
+    def testUnencodable(self):
+        filename = support.TESTFN_UNENCODABLE + ".zip"
+        z = ZipFile(filename, "w")
+        zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
+        zinfo.compress_type = self.compression
+        z.writestr(zinfo, test_src)
+        z.close()
+        try:
+            zipimport.zipimporter(filename)
+        finally:
+            os.remove(filename)
+
 
 @unittest.skipUnless(zlib, "requires zlib")
 class CompressedZipImportTestCase(UncompressedZipImportTestCase):

Modified: python/branches/pep-0384/Lib/threading.py
==============================================================================
--- python/branches/pep-0384/Lib/threading.py	(original)
+++ python/branches/pep-0384/Lib/threading.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/timeit.py
==============================================================================
--- python/branches/pep-0384/Lib/timeit.py	(original)
+++ python/branches/pep-0384/Lib/timeit.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/trace.py
==============================================================================
--- python/branches/pep-0384/Lib/trace.py	(original)
+++ python/branches/pep-0384/Lib/trace.py	Fri Aug 27 21:11:11 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,
@@ -491,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:
@@ -504,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:
@@ -624,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):
@@ -637,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):
@@ -799,7 +801,14 @@
         try:
             with open(progname) as fp:
                 code = compile(fp.read(), progname, 'exec')
-            t.run(code)
+            # 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/pep-0384/Lib/urllib/parse.py
==============================================================================
--- python/branches/pep-0384/Lib/urllib/parse.py	(original)
+++ python/branches/pep-0384/Lib/urllib/parse.py	Fri Aug 27 21:11:11 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
@@ -314,8 +315,8 @@
     # 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 is None:
-            raise TypeError('None object is invalid for unquote_to_bytes()')
+        # Is it a string-like object?
+        string.split
         return b''
     if isinstance(string, str):
         string = string.encode('utf-8')
@@ -340,9 +341,7 @@
 
     unquote('abc%20def') -> 'abc def'.
     """
-    if not string:
-        if string is None:
-            raise TypeError('None object is invalid for unquote() function.')
+    if string == '':
         return string
     res = string.split('%')
     if len(res) == 1:
@@ -381,10 +380,10 @@
 
         Arguments:
 
-        qs: URL-encoded query string to be parsed
+        qs: percent-encoded query string to be parsed
 
         keep_blank_values: flag indicating whether blank values in
-            URL encoded queries should be treated as blank strings.
+            percent-encoded queries should be treated as blank strings.
             A true value indicates that blanks should be retained as
             blank strings.  The default false value indicates that
             blank values are to be ignored and treated as if they were
@@ -407,10 +406,10 @@
 
     Arguments:
 
-    qs: URL-encoded query string to be parsed
+    qs: percent-encoded query string to be parsed
 
     keep_blank_values: flag indicating whether blank values in
-        URL encoded queries should be treated as blank strings.  A
+        percent-encoded queries should be treated as blank strings.  A
         true value indicates that blanks should be retained as blank
         strings.  The default false value indicates that blank values
         are to be ignored and treated as if they were  not included.

Modified: python/branches/pep-0384/Lib/urllib/request.py
==============================================================================
--- python/branches/pep-0384/Lib/urllib/request.py	(original)
+++ python/branches/pep-0384/Lib/urllib/request.py	Fri Aug 27 21:11:11 2010
@@ -99,7 +99,7 @@
 from urllib.parse import (
     urlparse, urlsplit, urljoin, unwrap, quote, unquote,
     splittype, splithost, splitport, splituser, splitpasswd,
-    splitattr, splitquery, splitvalue, to_bytes, urlunparse)
+    splitattr, splitquery, splitvalue, splittag, to_bytes, urlunparse)
 from urllib.response import addinfourl, addclosehook
 
 # check for SSL
@@ -163,6 +163,7 @@
                  origin_req_host=None, unverifiable=False):
         # unwrap('<URL:type://host/path>') --> 'type://host/path'
         self.full_url = unwrap(url)
+        self.full_url, fragment = splittag(self.full_url)
         self.data = data
         self.headers = {}
         self._tunnel_host = None
@@ -777,6 +778,9 @@
         self.add_password = self.passwd.add_password
         self.retried = 0
 
+    def reset_retry_count(self):
+        self.retried = 0
+
     def http_error_auth_reqed(self, authreq, host, req, headers):
         # host may be an authority (without userinfo) or a URL with an
         # authority
@@ -795,7 +799,10 @@
             if mo:
                 scheme, quote, realm = mo.groups()
                 if scheme.lower() == 'basic':
-                    return self.retry_http_basic_auth(host, req, realm)
+                    response = self.retry_http_basic_auth(host, req, realm)
+                    if response and response.code != 401:
+                        self.retried = 0
+                    return response
 
     def retry_http_basic_auth(self, host, req, realm):
         user, pw = self.passwd.find_user_password(realm, host)
@@ -816,8 +823,10 @@
 
     def http_error_401(self, req, fp, code, msg, headers):
         url = req.full_url
-        return self.http_error_auth_reqed('www-authenticate',
+        response = self.http_error_auth_reqed('www-authenticate',
                                           url, req, headers)
+        self.reset_retry_count()
+        return response
 
 
 class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
@@ -830,8 +839,10 @@
         # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
         # userinfo.
         authority = req.host
-        return self.http_error_auth_reqed('proxy-authenticate',
+        response = self.http_error_auth_reqed('proxy-authenticate',
                                           authority, req, headers)
+        self.reset_retry_count()
+        return response
 
 
 def randombytes(n):
@@ -1591,13 +1602,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)

Modified: python/branches/pep-0384/Lib/urllib/robotparser.py
==============================================================================
--- python/branches/pep-0384/Lib/urllib/robotparser.py	(original)
+++ python/branches/pep-0384/Lib/urllib/robotparser.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/xml/dom/minidom.py
==============================================================================
--- python/branches/pep-0384/Lib/xml/dom/minidom.py	(original)
+++ python/branches/pep-0384/Lib/xml/dom/minidom.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/xml/etree/ElementInclude.py
==============================================================================
--- python/branches/pep-0384/Lib/xml/etree/ElementInclude.py	(original)
+++ python/branches/pep-0384/Lib/xml/etree/ElementInclude.py	Fri Aug 27 21:11:11 2010
@@ -125,7 +125,7 @@
                         )
                 if i:
                     node = elem[i-1]
-                    node.tail = (node.tail or "") + text
+                    node.tail = (node.tail or "") + text + (e.tail or "")
                 else:
                     elem.text = (elem.text or "") + text + (e.tail or "")
                 del elem[i]

Modified: python/branches/pep-0384/Lib/xml/etree/ElementTree.py
==============================================================================
--- python/branches/pep-0384/Lib/xml/etree/ElementTree.py	(original)
+++ python/branches/pep-0384/Lib/xml/etree/ElementTree.py	Fri Aug 27 21:11:11 2010
@@ -792,12 +792,13 @@
     # @def write(file, **options)
     # @param file A file name, or a file object opened for writing.
     # @param **options Options, given as keyword arguments.
-    # @keyparam encoding Optional output encoding (default is None).
+    # @keyparam encoding Optional output encoding (default is US-ASCII).
+    #     Use "unicode" to return a Unicode string.
     # @keyparam method Optional output method ("xml", "html", "text" or
     #     "c14n"; default is "xml").
     # @keyparam xml_declaration Controls if an XML declaration should
     #     be added to the file.  Use False for never, True for always,
-    #     None for only if not US-ASCII or UTF-8.  None is default.
+    #     None for only if not US-ASCII or UTF-8 or Unicode.  None is default.
 
     def write(self, file_or_filename,
               # keyword arguments
@@ -811,14 +812,23 @@
         elif method not in _serialize:
             # FIXME: raise an ImportError for c14n if ElementC14N is missing?
             raise ValueError("unknown method %r" % method)
+        if not encoding:
+            if method == "c14n":
+                encoding = "utf-8"
+            else:
+                encoding = "us-ascii"
+        elif encoding == str:  # lxml.etree compatibility.
+            encoding = "unicode"
+        else:
+            encoding = encoding.lower()
         if hasattr(file_or_filename, "write"):
             file = file_or_filename
         else:
-            if encoding:
+            if encoding != "unicode":
                 file = open(file_or_filename, "wb")
             else:
                 file = open(file_or_filename, "w")
-        if encoding:
+        if encoding != "unicode":
             def write(text):
                 try:
                     return file.write(text.encode(encoding,
@@ -827,20 +837,15 @@
                     _raise_serialization_error(text)
         else:
             write = file.write
-        if not encoding:
-            if method == "c14n":
-                encoding = "utf-8"
-            else:
-                encoding = None
-        elif xml_declaration or (xml_declaration is None and
-                                 encoding not in ("utf-8", "us-ascii")):
-            if method == "xml":
-                encoding_ = encoding
-                if not encoding:
-                    # Retrieve the default encoding for the xml declaration
-                    import locale
-                    encoding_ = locale.getpreferredencoding()
-                write("<?xml version='1.0' encoding='%s'?>\n" % encoding_)
+        if method == "xml" and (xml_declaration or
+                (xml_declaration is None and
+                 encoding not in ("utf-8", "us-ascii", "unicode"))):
+            declared_encoding = encoding
+            if encoding == "unicode":
+                # Retrieve the default encoding for the xml declaration
+                import locale
+                declared_encoding = locale.getpreferredencoding()
+            write("<?xml version='1.0' encoding='%s'?>\n" % declared_encoding)
         if method == "text":
             _serialize_text(write, self._root)
         else:
@@ -1127,11 +1132,12 @@
 
 ##
 # Generates a string representation of an XML element, including all
-# subelements.  If encoding is None, the return type is a string;
+# subelements.  If encoding is "unicode", the return type is a string;
 # otherwise it is a bytes array.
 #
 # @param element An Element instance.
-# @keyparam encoding Optional output encoding (default is None).
+# @keyparam encoding Optional output encoding (default is US-ASCII).
+#     Use "unicode" to return a Unicode string.
 # @keyparam method Optional output method ("xml", "html", "text" or
 #     "c14n"; default is "xml").
 # @return An (optionally) encoded string containing the XML data.
@@ -1144,17 +1150,20 @@
     file = dummy()
     file.write = data.append
     ElementTree(element).write(file, encoding, method=method)
-    if encoding:
-        return b"".join(data)
-    else:
+    if encoding in (str, "unicode"):
         return "".join(data)
+    else:
+        return b"".join(data)
 
 ##
 # Generates a string representation of an XML element, including all
-# subelements.  The string is returned as a sequence of string fragments.
+# subelements.  If encoding is False, the string is returned as a
+# sequence of string fragments; otherwise it is a sequence of
+# bytestrings.
 #
 # @param element An Element instance.
 # @keyparam encoding Optional output encoding (default is US-ASCII).
+#     Use "unicode" to return a Unicode string.
 # @keyparam method Optional output method ("xml", "html", "text" or
 #     "c14n"; default is "xml").
 # @return A sequence object containing the XML data.
@@ -1184,7 +1193,7 @@
     # debugging
     if not isinstance(elem, ElementTree):
         elem = ElementTree(elem)
-    elem.write(sys.stdout)
+    elem.write(sys.stdout, encoding="unicode")
     tail = elem.getroot().tail
     if not tail or tail[-1] != "\n":
         sys.stdout.write("\n")

Modified: python/branches/pep-0384/Lib/xmlrpc/client.py
==============================================================================
--- python/branches/pep-0384/Lib/xmlrpc/client.py	(original)
+++ python/branches/pep-0384/Lib/xmlrpc/client.py	Fri Aug 27 21:11:11 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/pep-0384/Lib/zipfile.py
==============================================================================
--- python/branches/pep-0384/Lib/zipfile.py	(original)
+++ python/branches/pep-0384/Lib/zipfile.py	Fri Aug 27 21:11:11 2010
@@ -492,6 +492,12 @@
         self.mode = mode
         self.name = zipinfo.filename
 
+        if hasattr(zipinfo, 'CRC'):
+            self._expected_crc = zipinfo.CRC
+            self._running_crc = crc32(b'') & 0xffffffff
+        else:
+            self._expected_crc = None
+
     def readline(self, limit=-1):
         """Read and return a line from the stream.
 
@@ -569,6 +575,16 @@
 
         return buf
 
+    def _update_crc(self, newdata, eof):
+        # Update the CRC using the given data.
+        if self._expected_crc is None:
+            # No need to compute the CRC if we don't have a reference value
+            return
+        self._running_crc = crc32(newdata, self._running_crc) & 0xffffffff
+        # Check the CRC if we're at the end of the file
+        if eof and self._running_crc != self._expected_crc:
+            raise BadZipfile("Bad CRC-32 for file %r" % self.name)
+
     def read1(self, n):
         """Read up to n bytes with at most one read() system call."""
 
@@ -592,6 +608,7 @@
                 data = bytes(map(self._decrypter, data))
 
             if self._compress_type == ZIP_STORED:
+                self._update_crc(data, eof=(self._compress_left==0))
                 self._readbuffer = self._readbuffer[self._offset:] + data
                 self._offset = 0
             else:
@@ -607,9 +624,11 @@
             )
 
             self._unconsumed = self._decompressor.unconsumed_tail
-            if len(self._unconsumed) == 0 and self._compress_left == 0:
+            eof = len(self._unconsumed) == 0 and self._compress_left == 0
+            if eof:
                 data += self._decompressor.flush()
 
+            self._update_crc(data, eof=eof)
             self._readbuffer = self._readbuffer[self._offset:] + data
             self._offset = 0
 
@@ -1380,7 +1399,9 @@
             print(USAGE)
             sys.exit(1)
         zf = ZipFile(args[1], 'r')
-        zf.testzip()
+        badfile = zf.testzip()
+        if badfile:
+            print("The following enclosed file is corrupted: {!r}".format(badfile))
         print("Done testing")
 
     elif args[0] == '-e':

Modified: python/branches/pep-0384/Makefile.pre.in
==============================================================================
--- python/branches/pep-0384/Makefile.pre.in	(original)
+++ python/branches/pep-0384/Makefile.pre.in	Fri Aug 27 21:11:11 2010
@@ -314,6 +314,7 @@
 		Python/pymath.o \
 		Python/pystate.o \
 		Python/pythonrun.o \
+		Python/pytime.o \
 		Python/structmember.o \
 		Python/symtable.o \
 		Python/sysmodule.o \
@@ -417,9 +418,7 @@
 
 # Build the interpreter
 $(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY)
-		$(LINKCC) $(PY_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
@@ -562,9 +561,12 @@
 
 $(IO_OBJS): $(IO_H)
 
-$(GRAMMAR_H) $(GRAMMAR_C): $(PGEN) $(GRAMMAR_INPUT)
+# Use a stamp file to prevent make -j invoking pgen twice
+$(GRAMMAR_H) $(GRAMMAR_C): Parser/pgen.stamp
+Parser/pgen.stamp: $(PGEN) $(GRAMMAR_INPUT)
 		-@$(INSTALL) -d Include
 		-$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
+		-touch Parser/pgen.stamp
 
 $(PGEN):	$(PGENOBJS)
 		$(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
@@ -701,6 +703,7 @@
 		Include/pystrtod.h \
 		Include/pythonrun.h \
 		Include/pythread.h \
+		Include/pytime.h \
 		Include/rangeobject.h \
 		Include/setobject.h \
 		Include/sliceobject.h \
@@ -900,7 +903,7 @@
 		else	true; \
 		fi; \
 	done
-	@for i in $(srcdir)/Lib/*.py $(srcdir)/Lib/*.doc $(srcdir)/Lib/*.egg-info ; \
+	@for i in $(srcdir)/Lib/*.py $(srcdir)/Lib/*.egg-info ; \
 	do \
 		if test -x $$i; then \
 			$(INSTALL_SCRIPT) $$i $(DESTDIR)$(LIBDEST); \
@@ -1188,8 +1191,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 +1203,7 @@
 
 clobber: clean profile-removal
 	-rm -f $(BUILDPYTHON) $(PGEN) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \
-		tags TAGS \
+		tags TAGS Parser/pgen.stamp \
 		config.cache config.log pyconfig.h Modules/config.c
 	-rm -rf build platform
 	-rm -rf $(PYTHONFRAMEWORKDIR)
@@ -1208,11 +1212,14 @@
 # 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
 	-rm -f python*-gdb.py
+	-rm -f pybuilddir.txt
 	find $(srcdir) '(' -name '*.fdc' -o -name '*~' \
 			   -o -name '[@,#]*' -o -name '*.old' \
 			   -o -name '*.orig' -o -name '*.rej' \
@@ -1231,7 +1238,7 @@
 		-o -type d \
 		-o -name '*.[chs]' \
 		-o -name '*.py' \
-		-o -name '*.doc' \
+		-o -name '*.pyw' \
 		-o -name '*.dat' \
 		-o -name '*.el' \
 		-o -name '*.fd' \
@@ -1243,20 +1250,18 @@
 		-o -name '*.xpm' \
 		-o -name '*.uue' \
 		-o -name '*.decTest' \
-		-o -name '*,[vpt]' \
+		-o -name '*.tmCommand' \
+		-o -name '*.tmSnippet' \
 		-o -name 'Setup' \
 		-o -name 'Setup.*' \
 		-o -name regen \
 		-o -name README \
+		-o -name NEWS \
+		-o -name HISTORY \
 		-o -name Makefile \
 		-o -name ChangeLog \
-		-o -name Repository \
-		-o -name Root \
-		-o -name Entries \
-		-o -name Tag \
-		-o -name tags \
-		-o -name TAGS \
-		-o -name .cvsignore \
+		-o -name .hgignore \
+		-o -name .bzrignore \
 		-o -name MANIFEST \
 		-o -print
 

Modified: python/branches/pep-0384/Misc/ACKS
==============================================================================
--- python/branches/pep-0384/Misc/ACKS	(original)
+++ python/branches/pep-0384/Misc/ACKS	Fri Aug 27 21:11:11 2010
@@ -1,4 +1,5 @@
-
+Acknowledgements
+----------------
 
 This list is not complete and not in any useful order, but I would
 like to thank everybody who contributed in any way, with code, hints,
@@ -7,11 +8,13 @@
 
 	--Guido
 
-PS: In the standard Python distribution, this file is encoded in UTF-8.
+PS: In the standard Python distribution, this file is encoded in UTF-8
+and the list is in rough alphabetical order by last names.
 
 David Abrahams
 Jim Ahlstrom
 Farhan Ahmad
+Matthew Ahrens
 Nir Aides
 Yaniv Aknin
 Jyrki Alakuijala
@@ -62,7 +65,7 @@
 Reimer Behrends
 Ben Bell
 Thomas Bellman
-Alexander Belopolsky
+Alexander “Саша” Belopolsky
 Eli Bendersky
 Andrew Bennetts
 Andy Bensky
@@ -98,6 +101,7 @@
 Georg Brandl
 Christopher Brannon
 Terrence Brannon
+Brian Brazil
 Dave Brennan
 Tom Bridgman
 Richard Brodie
@@ -129,6 +133,7 @@
 Per Cederqvist
 Octavian Cerna
 Pascal Chambon
+John Chandler
 Hye-Shik Chang
 Jeffrey Chang
 Mitch Chapman
@@ -152,6 +157,7 @@
 Nick Coghlan
 Josh Cogliati
 Dave Cole
+Terrence Cole
 Benjamin Collar
 Jeffery Collins
 Robert Collins
@@ -178,6 +184,7 @@
 Joaquin Cuenca Abela
 John Cugini
 Tom Culliton
+Antonio Cuni
 Brian Curtin
 Lisandro Dalcin
 Andrew Dalke
@@ -194,6 +201,8 @@
 Roger Dev
 Raghuram Devarakonda
 Caleb Deveraux
+Catherine Devlin
+Scott Dial
 Toby Dickenson
 Mark Dickinson
 Jack Diederich
@@ -251,6 +260,7 @@
 Sebastian Fernandez
 Vincent Fiack
 Tomer Filiba
+Jeffrey Finkelstein
 Russell Finn
 Nils Fischbeck
 Frederik Fix
@@ -361,6 +371,7 @@
 Brian Hooper
 Randall Hopper
 Nadav Horesh
+Jan Hosang
 Ken Howard
 Brad Howes
 Chih-Hao Huang
@@ -379,8 +390,9 @@
 John Interrante
 Bob Ippolito
 Atsuo Ishimoto
-Paul Jackson
+Adam Jackson
 Ben Jackson
+Paul Jackson
 David Jacobs
 Kevin Jacobs
 Kjetil Jacobsen
@@ -414,6 +426,7 @@
 Lou Kates
 Hiroaki Kawai
 Sebastien Keim
+Ryan Kelly
 Robert Kern
 Randall Kern
 Magnus Kessler
@@ -441,11 +454,13 @@
 Michael Kremer
 Fabian Kreutz
 Hannu Krosing
+Andrej Krpic
 Ivan Krstić
 Andrew Kuchling
 Vladimir Kushnir
 Cameron Laird
 Torsten Landschoff
+Łukasz Langa
 Tino Lange
 Andrew Langmead
 Detlef Lannert
@@ -476,6 +491,7 @@
 Ross Light
 Shawn Ligocki
 Martin Ligr
+Grant Limberg
 Christopher Lindblad
 Bjorn Lindqvist
 Per Lindqvist
@@ -535,6 +551,7 @@
 Aristotelis Mikropoulos
 Damien Miller
 Chad Miller
+Jason V. Miller
 Jay T. Miller
 Roman Milner
 Andrii V. Mishkovskyi
@@ -585,6 +602,7 @@
 Piet van Oostrum
 Jason Orendorff
 Douglas Orr
+Michele Orrù
 Denis S. Otkidach
 Michael Otteneder
 R. M. Oudkerk
@@ -619,6 +637,7 @@
 Jim St. Pierre
 Dan Pierson
 Martijn Pieters
+Anand B. Pillai
 François Pinard
 Zach Pincus
 Michael Piotrowski
@@ -712,6 +731,7 @@
 Barry Scott
 Nick Seidenman
 Žiga Seilnach
+Yury Selivanov
 Fred Sells
 Jiwon Seo
 Roger D. Serwy
@@ -721,6 +741,7 @@
 Ha Shao
 Richard Shapiro
 Bruce Sherwood
+Alexander Shigin
 Pete Shinners
 Michael Shiplett
 John W. Shipman
@@ -769,6 +790,7 @@
 Andrew Svetlov
 Paul Swartz
 Thenault Sylvain
+Péter Szabó
 Arfrever Frehtes Taifersar Arahesis
 Geoff Talvola
 Musashi Tamura
@@ -796,6 +818,7 @@
 Jason Trowbridge
 Anthony Tuininga
 Stephen Turner
+Theodore Turocy
 Bill Tutt
 Doobee R. Tzeck
 Eren Türkay
@@ -847,6 +870,7 @@
 Gerry Wiener
 Frank Wierzbicki
 Bryce "Zooko" Wilcox-O'Hearn
+Jason Williams
 John Williams
 Sue Williams
 Gerald S. Williams

Modified: python/branches/pep-0384/Misc/NEWS
==============================================================================
--- python/branches/pep-0384/Misc/NEWS	(original)
+++ python/branches/pep-0384/Misc/NEWS	Fri Aug 27 21:11:11 2010
@@ -4,30 +4,362 @@
 
 (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 #9688: __basicsize__ and __itemsize__ must be accessed as Py_ssize_t.
+
+- Issue #9684: Added a definition for SIZEOF_WCHAR_T to PC/pyconfig.h,
+  to match the pyconfig.h generated by configure on other systems.
+
+- Issue #9666: Only catch AttributeError in hasattr(). All other exceptions that
+  occur during attribute lookup are now propagated to the caller.
+
+- Issue #8622: Add PYTHONFSENCODING environment variable to override the
+  filesystem encoding.
+
+- Issue #5127: The C functions that access the Unicode Database now accept and
+  return characters from the full Unicode range, even on narrow unicode builds
+  (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and others).  A visible difference
+  in Python is that unicodedata.numeric() now returns the correct value for
+  large code points, and repr() may consider more characters as printable.
+
+- Issue #9425: Create PyModule_GetFilenameObject() function to get the filename
+  as a unicode object, instead of a byte string. Function needed to support
+  unencodable filenames. Deprecate PyModule_GetFilename() in favor on the new
+  function.
+
+- Issue #8063: Call _PyGILState_Init() earlier in Py_InitializeEx().
+
+- Issue #9612: The set object is now 64-bit clean under Windows.
+
+- Issue #8202: sys.argv[0] is now set to '-m' instead of '-c' when searching
+  for the module file to be executed with the -m command  line option.
+
+- Issue #9599: Create PySys_FormatStdout() and PySys_FormatStderr() functions
+  to write a message formatted by PyUnicode_FromFormatV() to sys.stdout and
+  sys.stderr.
+
+- Issue #9542: Create PyUnicode_FSDecoder() function, a ParseTuple converter:
+  decode bytes objects to unicode using PyUnicode_DecodeFSDefaultAndSize();
+  str objects are output as-is.
+
+- Issue #9203: Computed gotos are now enabled by default on supported
+  compilers (which are detected by the configure script).  They can still
+  be disable selectively by specifying --without-computed-gotos.
+
+- Issue #9425: Create PyErr_WarnFormat() function, similar to PyErr_WarnEx()
+  but use PyUnicode_FromFormatV() to format the warning message.
+
+- Issue #8530: Prevent stringlib fastsearch from reading beyond the front
+  of an array.
+
+- Issue #5319: Print an error if flushing stdout fails at interpreter
+  shutdown.
+
+- 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 #1027206: Support IDNA in gethostbyname, gethostbyname_ex, 
+  getaddrinfo and gethostbyaddr. getnameinfo is now restricted to numeric
+  addresses as input.
+
+- Issue #9214: Set operations on a KeysView or ItemsView in collections
+  now correctly return a set.  (Patch by Eli Bendersky.)
+
+- Issue #5737: Add Solaris-specific mnemonics in the errno module.  Patch by
+  Matthew Ahrens.
+
+- Restore GIL in nis_cat in case of error. Decode NIS data to fs encoding,
+  using the surrogate error handler.
+
+- Issue #665761: ``functools.reduce()`` will no longer mask exceptions
+  other than ``TypeError`` raised by the iterator argument.
+
+- Issue #9570: Use PEP 383 decoding in os.mknod and os.mkfifo.
+
+- Issue #6915: Under Windows, os.listdir() didn't release the Global
+  Interpreter Lock around all system calls.  Original patch by Ryan Kelly.
+
+- Issue #8524: Add a detach() method to socket objects, so as to put the
+  socket into the closed state without closing the underlying file
+  descriptor.
+
+- Issue #477863: Print a warning at shutdown if gc.garbage is not empty.
+
+- Issue #6869: Fix a refcount problem in the _ctypes extension.
+
+- Issue #5504: ctypes should now work with systems where mmap can't
+  be PROT_WRITE and PROT_EXEC.
+
+- 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 #8797: urllib2 does a retry for Basic Authentication failure instead of
+  falling into recursion.
+
+- Issue #1194222: email.utils.parsedate now returns RFC2822 compliant four
+  character years even if the message contains RFC822 two character years.
+
+- Issue #8750: Fixed MutableSet's methods to correctly handle reflexive
+  operations on its self, namely x -= x and x ^= x.
+
+- Issue #9129: smtpd.py is vulnerable to DoS attacks deriving from missing 
+  error handling when accepting a new connection.
+
+- Issue #9601: ftplib now provides a workaround for non-compliant 
+  implementations such as IIS shipped with Windows server 2003 returning invalid 
+  response codes for MKD and PWD commands.
+
+- Issue #658749: asyncore's connect() method now correctly interprets winsock
+  errors.
+
+- Issue #9501: Fixed logging regressions in cleanup code.
+
+- Fix functools.total_ordering() to actually work.
+
+- Issue #9572: Importlib should not raise an exception if a directory it
+  thought it needed to create was done concurrently by another process.
+
+- Issue #9617: Signals received during a low-level write operation aren't
+  ignored by the buffered IO layer anymore.
+
+- Issue #843590: Make "macintosh" an alias to the "mac_roman" encoding.
+
+- Create os.fsdecode(): decode from the filesystem encoding with
+  surrogateescape error handler, or strict error handler on Windows.
+
+- Issue #3488: Provide convenient shorthand functions ``gzip.compress``
+  and ``gzip.decompress``.  Original patch by Anand B. Pillai.
+
+- Issue #8807: poplib.POP3_SSL class now accepts a context parameter, which is a
+  ssl.SSLContext object allowing bundling SSL configuration options,
+  certificates and private keys into a single (potentially long-lived)
+  structure.
+
+- Issue #8866: parameters passed to socket.getaddrinfo can now be specified as
+  single keyword arguments.
+
+- Address XXX comment in dis.py by having inspect.py prefer to reuse the
+  dis.py compiler flag values over defining its own
+
+- Issue #9147: Added dis.code_info() which is similar to show_code()
+  but returns formatted code information in a string rather than
+  displaying on screen.
+
+- Issue #9567: functools.update_wrapper now adds a __wrapped__ attribute
+  pointing to the original callable
+
+- Issue #3445: functools.update_wrapper now tolerates missing attributes
+  on wrapped callables
+
+- Issue #5867: Add abc.abstractclassmethod and abc.abstractstaticmethod.
+
+- Issue #9605: posix.getlogin() decodes the username with file filesystem
+  encoding and surrogateescape error handler. Patch written by David Watson.
+
+- Issue #9604: posix.initgroups() encodes the username using the fileystem
+  encoding and surrogateescape error handler. Patch written by David Watson.
+
+- Issue #9603: posix.ttyname() and posix.ctermid() decode the terminal name
+  using the filesystem encoding and surrogateescape error handler. Patch
+  written by David Watson.
+
+- Issue #7647: The posix module now has the ST_RDONLY and ST_NOSUID
+  constants, for use with the statvfs() function.  Patch by Adam Jackson.
+
+- Issue #8688: MANIFEST files created by distutils now include a magic
+  comment indicating they are generated.  Manually maintained MANIFESTs
+  without this marker will not be overwritten or removed.
+
+- Issue #7467: when reading a file from a ZIP archive, its CRC is checked
+  and a BadZipfile error is raised if it doesn't match (as used to be the
+  case in Python 2.5 and earlier).
+
+- Issue #9550: a BufferedReader could issue an additional read when the
+  original read request had been satisfied, which could block indefinitely
+  when the underlying raw IO channel was e.g. a socket.  Report and original
+  patch by Jason V. Miller.
+
+- Issue #3757: thread-local objects now support cyclic garbage collection.
+  Thread-local objects involved in reference cycles will be deallocated
+  timely by the cyclic GC, even if the underlying thread is still running.
+
+- Issue #9452: Add read_file, read_string, and read_dict to the configparser
+  API; new source attribute to exceptions.
+
+- Issue #6231: Fix xml.etree.ElementInclude to include the tail of the
+  current node.
+
+- Issue #8047: Fix the xml.etree serializer to return bytes by default.  Use
+  ``encoding="unicode"`` to generate a Unicode string.
+
+- Issue #8280: urllib2's Request method will remove fragments in the url.
+  This is how it is supposed to work, wget and curl do the same.  Previous
+  behavior was wrong.
+
+- Issue #6683: For SMTP logins we now try all authentication methods advertised
+  by the server.  Many servers are buggy and advertise authentication methods
+  they do 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 lru_cache() decorator to the functools module.
+
+Tools/Demos
+-----------
+
+- Fix ``Tools/scripts/checkpyc.py`` after PEP 3147.
+
+- Issue #8867: Fix ``Tools/scripts/serve.py`` to work with files containing
+  non-ASCII content.
+
+Tests
+-----
+
+- Issue #9601: Provide a test case for ftplib.parse257.
+
+- Issue #8857: Provide a test case for socket.getaddrinfo.
+
+- Issue #7564: Skip test_ioctl if another process is attached to /dev/tty.
+
+- 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.
+
+Build
+-----
+
+- Don't run pgen twice when using make -j.
+
+
 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.
 
@@ -35,27 +367,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.
 
@@ -64,94 +395,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.
+  encoding and surrogateescape error handler instead of the locale encoding to
+  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.
@@ -161,9 +491,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.
 
@@ -171,16 +501,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
@@ -189,72 +519,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.
@@ -265,24 +589,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.
@@ -290,22 +613,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.
@@ -322,7 +645,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.
 
@@ -333,26 +656,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.
 
@@ -362,8 +685,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.
 
@@ -372,85 +695,89 @@
 - 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
+- Issue #2443: A new macro, `Py_VA_COPY`, copies the state of the
+  variable argument list.  `Py_VA_COPY` is equivalent to C99
+  `va_copy`, but available on all python platforms.
+
+- 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.
 
@@ -465,36 +792,129 @@
 - 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
 -------
 
-- Issue #9323: Fixed a bug in trace.py that resulted in loosing the
-  name of the script being traced.  Patch by Eli Bendersky.
+- 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 #9282: Fixed --listfuncs option of trace.py.  Thanks Eli
-  Bendersky for the patch.
+- 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 forgetting the least recently
+  used 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 #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 #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.
+- Issue #9137: Fix issue in MutableMapping.update, which incorrectly treated
+  keyword arguments called 'self' or 'other' specially.
 
 - ``ast.literal_eval()`` now allows set literals.
 
@@ -502,13 +922,13 @@
 
 - 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 #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.
 
@@ -516,18 +936,18 @@
 
 - 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.
@@ -536,73 +956,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.
@@ -611,25 +1030,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.
@@ -638,11 +1056,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.
 
@@ -664,15 +1082,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.
@@ -683,9 +1101,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
@@ -694,46 +1111,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)
+- Issue #8390: tarfile uses surrogateescape as the default error handler
+  (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.
 
@@ -748,36 +1165,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.
 
@@ -787,25 +1204,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.
@@ -820,95 +1236,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
@@ -932,31 +1345,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.
@@ -986,16 +1399,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.
 
@@ -1005,48 +1418,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.
 
@@ -1060,21 +1471,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.
 
@@ -1082,63 +1493,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.
@@ -1146,26 +1555,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.
 
@@ -1173,66 +1582,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
@@ -1244,20 +1651,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.
@@ -1279,31 +1685,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.
 
@@ -1313,22 +1719,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.
@@ -1337,8 +1742,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.
 
@@ -1360,50 +1764,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.
@@ -1419,38 +1823,47 @@
 
 - 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 #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 #9422: Fix memory leak when re-initializing a struct.Struct object.
 
-- Issue #5180: Fixed a bug that prevented loading 2.x pickles in 3.x
-  python when they contain instances of old-style classes.
+- 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 #9165: Add new functions math.isfinite and cmath.isfinite, to
-  accompany existing isinf and isnan functions.
+- Issue #6095: Make directory argument to os.listdir optional.
 
-- Issue #1578269: Implement os.symlink for Windows 6.0+. Patch by
-  Jason R. Coombs
+- 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.
@@ -1460,58 +1873,56 @@
 - 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.
 
@@ -1524,7 +1935,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
@@ -1536,80 +1947,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 #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.
 
@@ -1628,21 +2041,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.
@@ -1651,21 +2064,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).
@@ -1676,19 +2094,19 @@
 Tests
 -----
 
-- Issue #9251: test_threaded_import didn't fail when run through regrtest
-  if the import lock was 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 #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.
@@ -1696,14 +2114,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.
 
@@ -1715,37 +2133,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.
@@ -1753,20 +2171,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.
 
@@ -1782,29 +2200,29 @@
   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
 -----------
@@ -1812,8 +2230,7 @@
 - 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?
@@ -2029,7 +2446,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
@@ -2062,7 +2479,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.
@@ -2178,7 +2595,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.
@@ -2299,8 +2716,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
 -----
@@ -2672,7 +3089,7 @@
 
 - Issue #6314: logging: Extra checks on the "level" argument in more places.
 
-- Issue #2622: Fixed an ImportError when importing email.messsage from a
+- Issue #2622: Fixed an ImportError when importing email.message from a
   standalone application built with py2exe or py2app.
 
 - Issue #6455: Fixed test_build_ext under win32.

Modified: python/branches/pep-0384/Misc/README
==============================================================================
--- python/branches/pep-0384/Misc/README	(original)
+++ python/branches/pep-0384/Misc/README	Fri Aug 27 21:11:11 2010
@@ -7,34 +7,35 @@
 Files found here
 ----------------
 
-ACKS		Acknowledgements
-AIX-NOTES	Notes for building Python on AIX
-build.sh	Script to build and test latest Python from the repository
-cheatsheet	Quick summary of Python by Ken Manheimer
-developers.txt	A history of who got developer permissions, and why
-gdbinit		Handy stuff to put in your .gdbinit file, if you use gdb
-HISTORY		News from previous releases -- oldest last
-indent.pro	GNU indent profile approximating my C style
-maintainers.txt	A list of maintainers for library modules
-NEWS		News for this release (for some meaning of "this")
-NEWS.help	How to edit NEWS
-Porting		Mini-FAQ on porting to new platforms
-PURIFY.README	Information for Purify users
-pymemcompat.h	Memory interface compatibility file.
-python.man	UNIX man page for the python interpreter
-python-mode.el	Emacs mode for editing Python programs
-python.pc.in	Package configuration info template for pkg-config
-python-wing.wpr Wing IDE project file
-README		The file you're reading now
-README.coverity	Information about running Coverity's Prevent on Python
-README.klocwork	Information about running Klocwork's K7 on Python
-README.OpenBSD	Help for building problems on OpenBSD
-README.valgrind	Information for Valgrind users, see valgrind-python.supp
-RFD		Request For Discussion about a Python newsgroup
-RPM		(Old) tools to build RPMs
-setuid-prog.c	C helper program for set-uid Python scripts
-SpecialBuilds.txt     Describes extra symbols you can set for debug builds
-TextMate	A TextMate bundle for Python development
-valgrind-python.supp  Valgrind suppression file, see README.valgrind
-vgrindefs	Python configuration for vgrind (a generic pretty printer)
-Vim		Python development utilities for the Vim editor
\ No newline at end of file
+ACKS                    Acknowledgements
+AIX-NOTES               Notes for building Python on AIX
+build.sh                Script to build and test latest Python from the repository
+cheatsheet              Quick summary of Python by Ken Manheimer
+developers.txt          A history of who got developer permissions, and why
+gdbinit                 Handy stuff to put in your .gdbinit file, if you use gdb
+HISTORY                 News from previous releases -- oldest last
+indent.pro              GNU indent profile approximating my C style
+maintainers.rst         A list of maintainers for library modules
+NEWS                    News for this release (for some meaning of "this")
+NEWS.help               How to edit NEWS
+Porting                 Mini-FAQ on porting to new platforms
+PURIFY.README           Information for Purify users
+pymemcompat.h           Memory interface compatibility file.
+python-config.in        Python script template for python-config
+python.man              UNIX man page for the python interpreter
+python-mode.el          Emacs mode for editing Python programs
+python.pc.in            Package configuration info template for pkg-config
+python-wing.wpr         Wing IDE project file
+README                  The file you're reading now
+README.coverity         Information about running Coverity's Prevent on Python
+README.klocwork         Information about running Klocwork's K7 on Python
+README.OpenBSD          Help for building problems on OpenBSD
+README.valgrind         Information for Valgrind users, see valgrind-python.supp
+RFD                     Request For Discussion about a Python newsgroup
+RPM                     (Old) tools to build RPMs
+setuid-prog.c           C helper program for set-uid Python scripts
+SpecialBuilds.txt       Describes extra symbols you can set for debug builds
+TextMate                A TextMate bundle for Python development
+valgrind-python.supp    Valgrind suppression file, see README.valgrind
+vgrindefs               Python configuration for vgrind (a generic pretty printer)
+Vim                     Python development utilities for the Vim editor

Modified: python/branches/pep-0384/Misc/RPM/python-3.2.spec
==============================================================================
--- python/branches/pep-0384/Misc/RPM/python-3.2.spec	(original)
+++ python/branches/pep-0384/Misc/RPM/python-3.2.spec	Fri Aug 27 21:11:11 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/pep-0384/Misc/developers.txt
==============================================================================
--- python/branches/pep-0384/Misc/developers.txt	(original)
+++ python/branches/pep-0384/Misc/developers.txt	Fri Aug 27 21:11:11 2010
@@ -20,6 +20,29 @@
 Permissions History
 -------------------
 
+- Daniel Stutzbach was given commit access on Aug 22 2010 by MvL,
+  for general bug fixing.
+
+- Ask Solem was given commit access on Aug 17 2010 by MvL,
+  on recommendation by Jesse Noller, for work on the multiprocessing
+  library.
+
+- George Boutsioukis was given commit access on Aug 10 2010
+  by MvL, for work on 2to3.
+
+- Éric Araujo was given commit access on Aug 10 2010 by BAC,
+  at suggestion of Tarek Ziadé.
+
+- 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/pep-0384/Misc/maintainers.rst
==============================================================================
--- python/branches/pep-0384/Misc/maintainers.rst	(original)
+++ python/branches/pep-0384/Misc/maintainers.rst	Fri Aug 27 21:11:11 2010
@@ -11,6 +11,10 @@
 a given module, then questionable changes should go to python-dev, while
 any other issues can and should be decided by any committer.
 
+Unless a name is followed by a '*', you should never assign an issue to
+that person, only make them nosy.  Names followed by a '*' may be assigned
+issues involving the module or topic for which the name has a '*'.
+
 The Platform and Interest Area tables list broader fields in which various
 people have expertise.  These people can also be contacted for help,
 opinions, and decisions when issues involve their areas.
@@ -21,8 +25,8 @@
 tracker id.  They are of course free to remove that inactive mark at
 any time.
 
-Committers should update this table as their areas of expertise widen.
-New topics may be added to the third table at will.
+Committers should update these tables as their areas of expertise widen.
+New topics may be added to the Interest Area table at will.
 
 The existence of this list is not meant to indicate that these people
 *must* be contacted for decisions; it is, rather, a resource to be used
@@ -42,14 +46,14 @@
 __future__
 __main__            gvanrossum
 _dummy_thread       brett.cannon
-_thread
+_thread             pitrou
 abc
 aifc                r.david.murray
 argparse            bethard
 array
 ast
-asynchat            josiahcarlson, giampaolo.rodola
-asyncore            josiahcarlson, giampaolo.rodola
+asynchat            josiahcarlson, giampaolo.rodola, stutzbach
+asyncore            josiahcarlson, giampaolo.rodola, stutzbach
 atexit
 audioop
 base64
@@ -68,7 +72,7 @@
 code
 codecs              lemburg, doerwalter
 codeop
-collections         rhettinger
+collections         rhettinger, stutzbach
 colorsys
 compileall
 configparser
@@ -85,11 +89,11 @@
 decimal             facundobatista, rhettinger, mark.dickinson
 difflib             tim_one
 dis
-distutils           tarek
+distutils           tarek*, eric.araujo*
 doctest             tim_one (inactive)
 dummy_threading     brett.cannon
-email               barry, r.david.murray
-encodings           lemburg
+email               barry, r.david.murray*
+encodings           lemburg, loewis
 errno
 exceptions
 fcntl
@@ -104,12 +108,12 @@
 gc                  pitrou
 getopt
 getpass
-gettext
+gettext             loewis
 glob
 grp
 gzip
 hashlib
-heapq               rhettinger
+heapq               rhettinger, stutzbach
 hmac
 html
 http
@@ -119,23 +123,23 @@
 imp
 importlib           brett.cannon
 inspect
-io                  pitrou, benjamin.peterson
+io                  pitrou, benjamin.peterson, stutzbach
 itertools           rhettinger
 json                bob.ippolito (inactive)
 keyword
 lib2to3             benjamin.peterson
 linecache
-locale              lemburg
-logging             vsajip
+locale              loewis, lemburg
+logging             vinay.sajip
 macpath
 mailbox             andrew.kuchling
 mailcap
 marshal
-math                mark.dickinson, rhettinger
+math                mark.dickinson, rhettinger, stutzbach
 mimetypes
 mmap
 modulefinder        theller, jvr
-msilib
+msilib              loewis
 msvcrt
 multiprocessing     jnoller
 netrc
@@ -144,10 +148,10 @@
 numbers
 operator
 optparse            aronacher
-os
+os                  loewis
 ossaudiodev
 parser
-pdb
+pdb                 georg.brandl*
 pickle              alexandre.vassalotti, pitrou
 pickletools         alexandre.vassalotti
 pipes
@@ -157,7 +161,8 @@
 poplib
 posix
 pprint              fdrake
-pstats
+profile             georg.brandl
+pstats              georg.brandl
 pty
 pwd
 py_compile
@@ -167,7 +172,7 @@
 queue               rhettinger
 quopri
 random              rhettinger
-re                  effbot (inactive), pitrou
+re                  effbot (inactive), pitrou, ezio.melotti
 readline
 reprlib
 resource
@@ -189,7 +194,7 @@
 sqlite3             ghaering
 ssl                 janssen, pitrou, giampaolo.rodola
 stat
-string
+string              georg.brandl*
 stringprep
 struct              mark.dickinson
 subprocess          astrand (inactive)
@@ -202,38 +207,45 @@
 tabnanny            tim_one
 tarfile             lars.gustaebel
 telnetlib
-tempfile
+tempfile            georg.brandl
 termios
 test
-textwrap
-threading
+textwrap            georg.brandl
+threading           pitrou
 time                alexander.belopolsky
-timeit
+timeit              georg.brandl
 tkinter             gpolo
 token               georg.brandl
 tokenize
 trace               alexander.belopolsky
-traceback           georg.brandl
+traceback           georg.brandl*
 tty
 turtle              gregorlingl
 types
-unicodedata         lemburg, ezio.melotti
+unicodedata         loewis, lemburg, ezio.melotti
 unittest            michael.foord
 urllib              orsenthil
 uu
 uuid
 warnings            brett.cannon
 wave
-weakref             fdrake
+weakref             fdrake, pitrou
 webbrowser          georg.brandl
-winreg              brian.curtin
+winreg              brian.curtin*, stutzbach
 winsound            effbot (inactive)
 wsgiref             pje
 xdrlib
-xml
+xml.dom
+xml.dom.minidom
+xml.dom.pulldom
 xml.etree           effbot (inactive)
-xmlrpc
-zipfile
+xml.parsers.expat
+xml.sax
+xml.sax.handler
+xml.sax.saxutils
+xml.sax.xmlreader
+xmlrpc              loewis
+zipfile             alanmcintyre
 zipimport
 zlib
 ==================  ===========
@@ -243,13 +255,14 @@
 Tool                Maintainers
 ------------------  -----------
 pybench             lemburg
+==================  ===========
 
 
 ==================  ===========
 Platform            Maintainers
 ------------------  -----------
 AIX
-Cygwin              jlt63
+Cygwin              jlt63, stutzbach
 FreeBSD
 HP-UX
 Linux
@@ -257,7 +270,7 @@
 NetBSD1
 OS2/EMX             aimacintyre
 Solaris
-Windows
+Windows             tim.golden, brian.curtin
 ==================  ===========
 
 
@@ -268,6 +281,7 @@
 ast/compiler        ncoghlan, benjamin.peterson, brett.cannon, georg.brandl
 autoconf/makefiles
 bsd
+bug tracker         ezio.melotti
 buildbots
 bytecode            pitrou
 data formats        mark.dickinson, georg.brandl
@@ -276,20 +290,19 @@
 GUI
 i18n                lemburg
 import machinery    brett.cannon, ncoghlan
-io                  pitrou, benjamin.peterson
-locale              lemburg
-mathematics         mark.dickinson, eric.smith, lemburg
+io                  pitrou, benjamin.peterson, stutzbach
+locale              lemburg, loewis
+mathematics         mark.dickinson, eric.smith, lemburg, stutzbach
 memory management   tim_one, lemburg
 networking          giampaolo.rodola
 packaging           tarek, lemburg
 py3 transition      benjamin.peterson
-release management  tarek, lemburg, benjamin.peterson, barry,
+release management  tarek, lemburg, benjamin.peterson, barry, loewis,
                     gvanrossum, anthonybaxter
 str.format          eric.smith
-time and dates      lemburg
 testing             michael.foord, pitrou, giampaolo.rodola
-threads
-tracker
+threads             pitrou
+time and dates      lemburg
 unicode             lemburg, ezio.melotti, haypo
 version control
 ==================  ===========

Modified: python/branches/pep-0384/Misc/python-wing.wpr
==============================================================================
--- python/branches/pep-0384/Misc/python-wing.wpr	(original)
+++ python/branches/pep-0384/Misc/python-wing.wpr	Fri Aug 27 21:11:11 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/pep-0384/Modules/Setup.dist
==============================================================================
--- python/branches/pep-0384/Modules/Setup.dist	(original)
+++ python/branches/pep-0384/Modules/Setup.dist	Fri Aug 27 21:11:11 2010
@@ -113,6 +113,9 @@
 _codecs _codecsmodule.c		# access to the builtin codecs and codec registry
 _weakref _weakref.c		# weak references
 _functools _functoolsmodule.c   # Tools for working with functions and callable objects
+operator operator.c	        # operator.add() and similar goodies
+_collections _collectionsmodule.c # Container types
+itertools itertoolsmodule.c    # Functions creating iterators for efficient looping 
 
 # access to ISO C locale support
 _locale _localemodule.c  # -lintl
@@ -161,16 +164,13 @@
 #math mathmodule.c _math.c # -lm # math library functions, e.g. sin()
 #_struct _struct.c	# binary structure packing/unpacking
 #time timemodule.c # -lm # time operations and variables
-#operator operator.c	# operator.add() and similar goodies
 #_weakref _weakref.c	# basic weak reference support
 #_testcapi _testcapimodule.c    # Python C API test module
 #_random _randommodule.c	# Random number generator
-#_collections _collectionsmodule.c # Container types
-#itertools itertoolsmodule.c	# Functions creating iterators for efficient looping 
 #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/pep-0384/Modules/_collectionsmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/_collectionsmodule.c	(original)
+++ python/branches/pep-0384/Modules/_collectionsmodule.c	Fri Aug 27 21:11:11 2010
@@ -1121,7 +1121,7 @@
 static PyObject *
 dequeiter_len(dequeiterobject *it)
 {
-    return PyLong_FromLong(it->counter);
+    return PyLong_FromSsize_t(it->counter);
 }
 
 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");

Modified: python/branches/pep-0384/Modules/_csv.c
==============================================================================
--- python/branches/pep-0384/Modules/_csv.c	(original)
+++ python/branches/pep-0384/Modules/_csv.c	Fri Aug 27 21:11:11 2010
@@ -6,10 +6,6 @@
 module.  Users should not use this module directly, but import the csv.py
 module instead.
 
-**** For people modifying this code, please note that as of this writing
-**** (2003-03-23), it is intended that this code should work with Python
-**** 2.2.
-
 */
 
 #define MODULE_VERSION "1.0"
@@ -73,7 +69,7 @@
     PyObject *fields;           /* field list for current record */
     ParserState state;          /* current CSV parse state */
     Py_UNICODE *field;          /* build current field in here */
-    int field_size;             /* size of allocated buffer */
+    Py_ssize_t field_size;      /* size of allocated buffer */
     Py_ssize_t field_len;       /* length of current field */
     int numeric_field;          /* treat field as numeric */
     unsigned long line_num;     /* Source-file line number */
@@ -91,7 +87,7 @@
     DialectObj *dialect;    /* parsing dialect */
 
     Py_UNICODE *rec;            /* buffer for parser.join */
-    int rec_size;               /* size of allocated record */
+    Py_ssize_t rec_size;        /* size of allocated record */
     Py_ssize_t rec_len;         /* length of record */
     int num_fields;             /* number of fields in record */
 } WriterObj;
@@ -533,7 +529,7 @@
         self->field = PyMem_New(Py_UNICODE, self->field_size);
     }
     else {
-        if (self->field_size > INT_MAX / 2) {
+        if (self->field_size > PY_SSIZE_T_MAX / 2) {
             PyErr_NoMemory();
             return 0;
         }
@@ -948,13 +944,13 @@
 /* Calculate new record length or append field to record.  Return new
  * record length.
  */
-static int
+static Py_ssize_t
 join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty,
                  int *quoted, int copy_phase)
 {
     DialectObj *dialect = self->dialect;
     int i;
-    int rec_len;
+    Py_ssize_t rec_len;
     Py_UNICODE *lineterm;
 
 #define ADDCH(c) \
@@ -1040,10 +1036,10 @@
 }
 
 static int
-join_check_rec_size(WriterObj *self, int rec_len)
+join_check_rec_size(WriterObj *self, Py_ssize_t rec_len)
 {
 
-    if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) {
+    if (rec_len < 0 || rec_len > PY_SSIZE_T_MAX - MEM_INCR) {
         PyErr_NoMemory();
         return 0;
     }
@@ -1075,7 +1071,7 @@
 static int
 join_append(WriterObj *self, Py_UNICODE *field, int *quoted, int quote_empty)
 {
-    int rec_len;
+    Py_ssize_t rec_len;
 
     rec_len = join_append_data(self, field, quote_empty, quoted, 0);
     if (rec_len < 0)
@@ -1094,7 +1090,7 @@
 static int
 join_append_lineterminator(WriterObj *self)
 {
-    int terminator_len;
+    Py_ssize_t terminator_len;
     Py_UNICODE *terminator;
 
     terminator_len = PyUnicode_GetSize(self->dialect->lineterminator);
@@ -1125,7 +1121,7 @@
 csv_writerow(WriterObj *self, PyObject *seq)
 {
     DialectObj *dialect = self->dialect;
-    int len, i;
+    Py_ssize_t len, i;
 
     if (!PySequence_Check(seq))
         return PyErr_Format(error_obj, "sequence expected");

Modified: python/branches/pep-0384/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/_ctypes.c	(original)
+++ python/branches/pep-0384/Modules/_ctypes/_ctypes.c	Fri Aug 27 21:11:11 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");
 
@@ -3367,7 +3353,7 @@
     self->callable = callable;
 
     self->thunk = thunk;
-    *(void **)self->b_ptr = (void *)thunk->pcl;
+    *(void **)self->b_ptr = (void *)thunk->pcl_exec;
 
     Py_INCREF((PyObject *)thunk); /* for KeepRef */
     if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
@@ -5326,36 +5312,42 @@
     Struct_Type.tp_base = &PyCData_Type;
     if (PyType_Ready(&Struct_Type) < 0)
         return NULL;
+    Py_INCREF(&Struct_Type);
     PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
 
     Py_TYPE(&Union_Type) = &UnionType_Type;
     Union_Type.tp_base = &PyCData_Type;
     if (PyType_Ready(&Union_Type) < 0)
         return NULL;
+    Py_INCREF(&Union_Type);
     PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
 
     Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type;
     PyCPointer_Type.tp_base = &PyCData_Type;
     if (PyType_Ready(&PyCPointer_Type) < 0)
         return NULL;
+    Py_INCREF(&PyCPointer_Type);
     PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type);
 
     Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type;
     PyCArray_Type.tp_base = &PyCData_Type;
     if (PyType_Ready(&PyCArray_Type) < 0)
         return NULL;
+    Py_INCREF(&PyCArray_Type);
     PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type);
 
     Py_TYPE(&Simple_Type) = &PyCSimpleType_Type;
     Simple_Type.tp_base = &PyCData_Type;
     if (PyType_Ready(&Simple_Type) < 0)
         return NULL;
+    Py_INCREF(&Simple_Type);
     PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
 
     Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type;
     PyCFuncPtr_Type.tp_base = &PyCData_Type;
     if (PyType_Ready(&PyCFuncPtr_Type) < 0)
         return NULL;
+    Py_INCREF(&PyCFuncPtr_Type);
     PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type);
 
     /*************************************************

Modified: python/branches/pep-0384/Modules/_ctypes/callbacks.c
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/callbacks.c	(original)
+++ python/branches/pep-0384/Modules/_ctypes/callbacks.c	Fri Aug 27 21:11:11 2010
@@ -16,8 +16,8 @@
     Py_XDECREF(self->converters);
     Py_XDECREF(self->callable);
     Py_XDECREF(self->restype);
-    if (self->pcl)
-        _ctypes_free_closure(self->pcl);
+    if (self->pcl_write)
+        ffi_closure_free(self->pcl_write);
     PyObject_GC_Del(self);
 }
 
@@ -338,7 +338,8 @@
         return NULL;
     }
 
-    p->pcl = NULL;
+    p->pcl_exec = NULL;
+    p->pcl_write = NULL;
     memset(&p->cif, 0, sizeof(p->cif));
     p->converters = NULL;
     p->callable = NULL;
@@ -368,8 +369,9 @@
 
     assert(CThunk_CheckExact((PyObject *)p));
 
-    p->pcl = _ctypes_alloc_closure();
-    if (p->pcl == NULL) {
+    p->pcl_write = ffi_closure_alloc(sizeof(ffi_closure),
+									 &p->pcl_exec);
+    if (p->pcl_write == NULL) {
         PyErr_NoMemory();
         goto error;
     }
@@ -414,7 +416,9 @@
                      "ffi_prep_cif failed with %d", result);
         goto error;
     }
-    result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
+    result = ffi_prep_closure_loc(p->pcl_write, &p->cif, closure_fcn,
+				  p,
+				  p->pcl_exec);
     if (result != FFI_OK) {
         PyErr_Format(PyExc_RuntimeError,
                      "ffi_prep_closure failed with %d", result);

Modified: python/branches/pep-0384/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/callproc.c	(original)
+++ python/branches/pep-0384/Modules/_ctypes/callproc.c	Fri Aug 27 21:11:11 2010
@@ -658,7 +658,7 @@
 
 #ifdef CTYPES_UNICODE
     if (PyUnicode_Check(obj)) {
-#ifdef HAVE_USABLE_WCHAR_T
+#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
         pa->ffi_type = &ffi_type_pointer;
         pa->value.p = PyUnicode_AS_UNICODE(obj);
         Py_INCREF(obj);
@@ -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/pep-0384/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/cfield.c	(original)
+++ python/branches/pep-0384/Modules/_ctypes/cfield.c	Fri Aug 27 21:11:11 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,25 +1413,18 @@
         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);
         return NULL;
     } else
         Py_INCREF(value);
-#ifdef HAVE_USABLE_WCHAR_T
-    /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
-       type.  So we can copy directly.  Hm, are unicode objects always NUL
+#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
+    /* We can copy directly.  Hm, are unicode objects always NUL
        terminated in Python, internally?
      */
-    *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
+    *(wchar_t **)ptr = (wchar_t *) PyUnicode_AS_UNICODE(value);
     return value;
 #else
     {
@@ -1540,12 +1492,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/pep-0384/Modules/_ctypes/ctypes.h
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/ctypes.h	(original)
+++ python/branches/pep-0384/Modules/_ctypes/ctypes.h	Fri Aug 27 21:11:11 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))
@@ -54,7 +58,8 @@
 
 typedef struct {
     PyObject_VAR_HEAD
-    ffi_closure *pcl; /* the C callable */
+    ffi_closure *pcl_write; /* the C callable, writeable */
+    void *pcl_exec;         /* the C callable, executable */
     ffi_cif cif;
     int flags;
     PyObject *converters;

Modified: python/branches/pep-0384/Modules/_ctypes/libffi/fficonfig.py.in
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/libffi/fficonfig.py.in	(original)
+++ python/branches/pep-0384/Modules/_ctypes/libffi/fficonfig.py.in	Fri Aug 27 21:11:11 2010
@@ -1,5 +1,7 @@
 ffi_sources = """
 src/prep_cif.c
+src/closures.c
+src/dlmalloc.c
 """.split()
 
 ffi_platforms = {

Modified: python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.c
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.c	(original)
+++ python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.c	Fri Aug 27 21:11:11 2010
@@ -371,10 +371,11 @@
 extern void ffi_closure_OUTER();
 
 ffi_status
-ffi_prep_closure (ffi_closure* closure,
-		  ffi_cif* cif,
-		  void (*fun)(ffi_cif*,void*,void**,void*),
-		  void *user_data)
+ffi_prep_closure_loc (ffi_closure* closure,
+					  ffi_cif* cif,
+					  void (*fun)(ffi_cif*,void*,void**,void*),
+					  void *user_data,
+					  void *codeloc)
 {
   short bytes;
   char *tramp;
@@ -452,6 +453,5 @@
   closure->cif  = cif;
   closure->user_data = user_data;
   closure->fun  = fun;
-
   return FFI_OK;
 }

Modified: python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.h
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.h	(original)
+++ python/branches/pep-0384/Modules/_ctypes/libffi_msvc/ffi.h	Fri Aug 27 21:11:11 2010
@@ -221,11 +221,15 @@
   void      *user_data;
 } ffi_closure;
 
+void ffi_closure_free(void *);
+void *ffi_closure_alloc (size_t size, void **code);
+
 ffi_status
-ffi_prep_closure (ffi_closure*,
+ffi_prep_closure_loc (ffi_closure*,
 		  ffi_cif *,
 		  void (*fun)(ffi_cif*,void*,void**,void*),
-		  void *user_data);
+		  void *user_data,
+		  void *codeloc);
 
 typedef struct {
   char tramp[FFI_TRAMPOLINE_SIZE];

Modified: python/branches/pep-0384/Modules/_ctypes/malloc_closure.c
==============================================================================
--- python/branches/pep-0384/Modules/_ctypes/malloc_closure.c	(original)
+++ python/branches/pep-0384/Modules/_ctypes/malloc_closure.c	Fri Aug 27 21:11:11 2010
@@ -89,7 +89,7 @@
 /******************************************************************/
 
 /* put the item back into the free list */
-void _ctypes_free_closure(void *p)
+void ffi_closure_free(void *p)
 {
     ITEM *item = (ITEM *)p;
     item->next = free_list;
@@ -97,7 +97,7 @@
 }
 
 /* return one item from the free list, allocating more if needed */
-void *_ctypes_alloc_closure(void)
+void *ffi_closure_alloc(size_t ignored, void** codeloc)
 {
     ITEM *item;
     if (!free_list)
@@ -106,5 +106,7 @@
         return NULL;
     item = free_list;
     free_list = item->next;
-    return item;
+	*codeloc = (void *)item;
+    return (void *)item;
 }
+

Modified: python/branches/pep-0384/Modules/_cursesmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/_cursesmodule.c	(original)
+++ python/branches/pep-0384/Modules/_cursesmodule.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/_elementtree.c
==============================================================================
--- python/branches/pep-0384/Modules/_elementtree.c	(original)
+++ python/branches/pep-0384/Modules/_elementtree.c	Fri Aug 27 21:11:11 2010
@@ -2870,15 +2870,15 @@
 
 
 static struct PyModuleDef _elementtreemodule = {
-	PyModuleDef_HEAD_INIT,
-	"_elementtree",
-	NULL,
-	-1,
-	_functions,
-	NULL,
-	NULL,
-	NULL,
-	NULL
+        PyModuleDef_HEAD_INIT,
+        "_elementtree",
+        NULL,
+        -1,
+        _functions,
+        NULL,
+        NULL,
+        NULL,
+        NULL
 };
 
 PyMODINIT_FUNC
@@ -2890,12 +2890,12 @@
 
     /* Initialize object types */
     if (PyType_Ready(&TreeBuilder_Type) < 0)
-	return NULL;
+        return NULL;
     if (PyType_Ready(&Element_Type) < 0)
-	return NULL;
+        return NULL;
 #if defined(USE_EXPAT)
     if (PyType_Ready(&XMLParser_Type) < 0)
-	return NULL;
+        return NULL;
 #endif
 
     m = PyModule_Create(&_elementtreemodule);
@@ -2905,8 +2905,8 @@
     /* The code below requires that the module gets already added
        to sys.modules. */
     PyDict_SetItemString(PyImport_GetModuleDict(),
-			 _elementtreemodule.m_name,
-			 m);
+                         _elementtreemodule.m_name,
+                         m);
 
     /* python glue code */
 

Modified: python/branches/pep-0384/Modules/_functoolsmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/_functoolsmodule.c	(original)
+++ python/branches/pep-0384/Modules/_functoolsmodule.c	Fri Aug 27 21:11:11 2010
@@ -302,8 +302,9 @@
 
     it = PyObject_GetIter(seq);
     if (it == NULL) {
-        PyErr_SetString(PyExc_TypeError,
-            "reduce() arg 2 must support iteration");
+        if (PyErr_ExceptionMatches(PyExc_TypeError))
+            PyErr_SetString(PyExc_TypeError,
+                            "reduce() arg 2 must support iteration");
         Py_XDECREF(result);
         return NULL;
     }

Modified: python/branches/pep-0384/Modules/_hashopenssl.c
==============================================================================
--- python/branches/pep-0384/Modules/_hashopenssl.c	(original)
+++ python/branches/pep-0384/Modules/_hashopenssl.c	Fri Aug 27 21:11:11 2010
@@ -559,7 +559,7 @@
     CONSTRUCTOR_METH_DEF(sha384),
     CONSTRUCTOR_METH_DEF(sha512),
 #endif
-    {NULL,	NULL}		 /* Sentinel */
+    {NULL,      NULL}            /* Sentinel */
 };
 
 

Modified: python/branches/pep-0384/Modules/_io/bufferedio.c
==============================================================================
--- python/branches/pep-0384/Modules/_io/bufferedio.c	(original)
+++ python/branches/pep-0384/Modules/_io/bufferedio.c	Fri Aug 27 21:11:11 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");
@@ -1381,7 +1383,10 @@
     self->pos = 0;
     self->raw_pos = 0;
     self->read_end = 0;
-    while (self->read_end < self->buffer_size) {
+    /* NOTE: when the read is satisfied, we avoid issuing any additional
+       reads, which could block indefinitely (e.g. on a socket).
+       See issue #9550. */
+    while (remaining > 0 && self->read_end < self->buffer_size) {
         Py_ssize_t r = _bufferedreader_fill_buffer(self);
         if (r == -1)
             goto error;
@@ -1660,6 +1665,11 @@
         self->write_pos += n;
         self->raw_pos = self->write_pos;
         written += Py_SAFE_DOWNCAST(n, Py_off_t, Py_ssize_t);
+        /* Partial writes can return successfully when interrupted by a
+           signal (see write(2)).  We must run signal handlers before
+           blocking another time, possibly indefinitely. */
+        if (PyErr_CheckSignals() < 0)
+            goto error;
     }
 
     if (restore_pos) {
@@ -1797,6 +1807,11 @@
         }
         written += n;
         remaining -= n;
+        /* Partial writes can return successfully when interrupted by a
+           signal (see write(2)).  We must run signal handlers before
+           blocking another time, possibly indefinitely. */
+        if (PyErr_CheckSignals() < 0)
+            goto error;
     }
     if (self->readable)
         _bufferedreader_reset_buf(self);

Modified: python/branches/pep-0384/Modules/_json.c
==============================================================================
--- python/branches/pep-0384/Modules/_json.c	(original)
+++ python/branches/pep-0384/Modules/_json.c	Fri Aug 27 21:11:11 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"
 );

Modified: python/branches/pep-0384/Modules/_localemodule.c
==============================================================================
--- python/branches/pep-0384/Modules/_localemodule.c	(original)
+++ python/branches/pep-0384/Modules/_localemodule.c	Fri Aug 27 21:11:11 2010
@@ -289,15 +289,15 @@
     wchar_t *s, *buf = NULL;
     size_t n1, n2;
     PyObject *result = NULL;
-#ifndef HAVE_USABLE_WCHAR_T
+#if Py_UNICODE_SIZE != SIZEOF_WCHAR_T
     Py_ssize_t i;
 #endif
 
     if (!PyArg_ParseTuple(args, "u#:strxfrm", &s0, &n0))
         return NULL;
 
-#ifdef HAVE_USABLE_WCHAR_T
-    s = s0;
+#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
+    s = (wchar_t *) s0;
 #else
     s = PyMem_Malloc((n0+1)*sizeof(wchar_t));
     if (!s)
@@ -326,7 +326,7 @@
     result = PyUnicode_FromWideChar(buf, n2);
  exit:
     if (buf) PyMem_Free(buf);
-#ifndef HAVE_USABLE_WCHAR_T
+#if Py_UNICODE_SIZE != SIZEOF_WCHAR_T
     PyMem_Free(s);
 #endif
     return result;

Modified: python/branches/pep-0384/Modules/_randommodule.c
==============================================================================
--- python/branches/pep-0384/Modules/_randommodule.c	(original)
+++ python/branches/pep-0384/Modules/_randommodule.c	Fri Aug 27 21:11:11 2010
@@ -6,7 +6,7 @@
 
    It was modified in 2002 by Raymond Hettinger as follows:
 
-    * the principal computational lines untouched except for tabbing.
+    * the principal computational lines untouched.
 
     * renamed genrand_res53() to random_random() and wrapped
       in python calling/return code.

Modified: python/branches/pep-0384/Modules/_ssl.c
==============================================================================
--- python/branches/pep-0384/Modules/_ssl.c	(original)
+++ python/branches/pep-0384/Modules/_ssl.c	Fri Aug 27 21:11:11 2010
@@ -857,6 +857,7 @@
     }
 
     retval = _decode_certificate(x, verbose);
+    X509_free(x);
 
   fail0:
     Py_DECREF(filename);

Modified: python/branches/pep-0384/Modules/_struct.c
==============================================================================
--- python/branches/pep-0384/Modules/_struct.c	(original)
+++ python/branches/pep-0384/Modules/_struct.c	Fri Aug 27 21:11:11 2010
@@ -1247,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/pep-0384/Modules/_threadmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/_threadmodule.c	(original)
+++ python/branches/pep-0384/Modules/_threadmodule.c	Fri Aug 27 21:11:11 2010
@@ -499,19 +499,163 @@
 
 #include "structmember.h"
 
+/* Quick overview:
+
+   We need to be able to reclaim reference cycles as soon as possible
+   (both when a thread is being terminated, or a thread-local object
+    becomes unreachable from user data).  Constraints:
+   - it must not be possible for thread-state dicts to be involved in
+     reference cycles (otherwise the cyclic GC will refuse to consider
+     objects referenced from a reachable thread-state dict, even though
+     local_dealloc would clear them)
+   - the death of a thread-state dict must still imply destruction of the
+     corresponding local dicts in all thread-local objects.
+
+   Our implementation uses small "localdummy" objects in order to break
+   the reference chain. These trivial objects are hashable (using the
+   default scheme of identity hashing) and weakrefable.
+   Each thread-state holds a separate localdummy for each local object
+   (as a /strong reference/),
+   and each thread-local object holds a dict mapping /weak references/
+   of localdummies to local dicts.
+
+   Therefore:
+   - only the thread-state dict holds a strong reference to the dummies
+   - only the thread-local object holds a strong reference to the local dicts
+   - only outside objects (application- or library-level) hold strong
+     references to the thread-local objects
+   - as soon as a thread-state dict is destroyed, the weakref callbacks of all
+     dummies attached to that thread are called, and destroy the corresponding
+     local dicts from thread-local objects
+   - as soon as a thread-local object is destroyed, its local dicts are
+     destroyed and its dummies are manually removed from all thread states
+   - the GC can do its work correctly when a thread-local object is dangling,
+     without any interference from the thread-state dicts
+
+   As an additional optimization, each localdummy holds a borrowed reference
+   to the corresponding localdict.  This borrowed reference is only used
+   by the thread-local object which has created the localdummy, which should
+   guarantee that the localdict still exists when accessed.
+*/
+
+typedef struct {
+    PyObject_HEAD
+    PyObject *localdict;        /* Borrowed reference! */
+    PyObject *weakreflist;      /* List of weak references to self */
+} localdummyobject;
+
+static void
+localdummy_dealloc(localdummyobject *self)
+{
+    if (self->weakreflist != NULL)
+        PyObject_ClearWeakRefs((PyObject *) self);
+    Py_TYPE(self)->tp_free((PyObject*)self);
+}
+
+static PyTypeObject localdummytype = {
+    PyVarObject_HEAD_INIT(NULL, 0)
+    /* tp_name           */ "_thread._localdummy",
+    /* tp_basicsize      */ sizeof(localdummyobject),
+    /* tp_itemsize       */ 0,
+    /* tp_dealloc        */ (destructor)localdummy_dealloc,
+    /* 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            */ 0,
+    /* tp_getattro       */ 0,
+    /* tp_setattro       */ 0,
+    /* tp_as_buffer      */ 0,
+    /* tp_flags          */ Py_TPFLAGS_DEFAULT,
+    /* tp_doc            */ "Thread-local dummy",
+    /* tp_traverse       */ 0,
+    /* tp_clear          */ 0,
+    /* tp_richcompare    */ 0,
+    /* tp_weaklistoffset */ offsetof(localdummyobject, weakreflist)
+};
+
+
 typedef struct {
     PyObject_HEAD
     PyObject *key;
     PyObject *args;
     PyObject *kw;
+    /* The current thread's local dict (necessary for tp_dictoffset) */
     PyObject *dict;
+    PyObject *weakreflist;      /* List of weak references to self */
+    /* A {localdummy weakref -> localdict} dict */
+    PyObject *dummies;
+    /* The callback for weakrefs to localdummies */
+    PyObject *wr_callback;
 } localobject;
 
+/* Forward declaration */
+static PyObject *_ldict(localobject *self);
+static PyObject *_localdummy_destroyed(PyObject *meth_self, PyObject *dummyweakref);
+
+/* Create and register the dummy for the current thread, as well as the
+   corresponding local dict */
+static int
+_local_create_dummy(localobject *self)
+{
+    PyObject *tdict, *ldict = NULL, *wr = NULL;
+    localdummyobject *dummy = NULL;
+    int r;
+
+    tdict = PyThreadState_GetDict();
+    if (tdict == NULL) {
+        PyErr_SetString(PyExc_SystemError,
+                        "Couldn't get thread-state dictionary");
+        goto err;
+    }
+
+    ldict = PyDict_New();
+    if (ldict == NULL)
+        goto err;
+    dummy = (localdummyobject *) localdummytype.tp_alloc(&localdummytype, 0);
+    if (dummy == NULL)
+        goto err;
+    dummy->localdict = ldict;
+    wr = PyWeakref_NewRef((PyObject *) dummy, self->wr_callback);
+    if (wr == NULL)
+        goto err;
+
+    /* As a side-effect, this will cache the weakref's hash before the
+       dummy gets deleted */
+    r = PyDict_SetItem(self->dummies, wr, ldict);
+    if (r < 0)
+        goto err;
+    Py_CLEAR(wr);
+    r = PyDict_SetItem(tdict, self->key, (PyObject *) dummy);
+    if (r < 0)
+        goto err;
+    Py_CLEAR(dummy);
+
+    Py_CLEAR(self->dict);
+    self->dict = ldict;
+    return 0;
+
+err:
+    Py_XDECREF(ldict);
+    Py_XDECREF(wr);
+    Py_XDECREF(dummy);
+    return -1;
+}
+
 static PyObject *
 local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
 {
     localobject *self;
-    PyObject *tdict;
+    PyObject *wr;
+    static PyMethodDef wr_callback_def = {
+        "_localdummy_destroyed", (PyCFunction) _localdummy_destroyed, METH_O
+    };
 
     if (type->tp_init == PyBaseObject_Type.tp_init
         && ((args && PyObject_IsTrue(args))
@@ -529,23 +673,25 @@
     self->args = args;
     Py_XINCREF(kw);
     self->kw = kw;
-    self->dict = NULL;          /* making sure */
     self->key = PyUnicode_FromFormat("thread.local.%p", self);
     if (self->key == NULL)
         goto err;
 
-    self->dict = PyDict_New();
-    if (self->dict == NULL)
+    self->dummies = PyDict_New();
+    if (self->dummies == NULL)
         goto err;
 
-    tdict = PyThreadState_GetDict();
-    if (tdict == NULL) {
-        PyErr_SetString(PyExc_SystemError,
-                        "Couldn't get thread-state dictionary");
+    /* We use a weak reference to self in the callback closure
+       in order to avoid spurious reference cycles */
+    wr = PyWeakref_NewRef((PyObject *) self, NULL);
+    if (wr == NULL)
+        goto err;
+    self->wr_callback = PyCFunction_New(&wr_callback_def, wr);
+    Py_DECREF(wr);
+    if (self->wr_callback == NULL)
         goto err;
-    }
 
-    if (PyDict_SetItem(tdict, self->key, self->dict) < 0)
+    if (_local_create_dummy(self) < 0)
         goto err;
 
     return (PyObject *)self;
@@ -560,6 +706,7 @@
 {
     Py_VISIT(self->args);
     Py_VISIT(self->kw);
+    Py_VISIT(self->dummies);
     Py_VISIT(self->dict);
     return 0;
 }
@@ -567,16 +714,13 @@
 static int
 local_clear(localobject *self)
 {
+    PyThreadState *tstate;
     Py_CLEAR(self->args);
     Py_CLEAR(self->kw);
+    Py_CLEAR(self->dummies);
     Py_CLEAR(self->dict);
-    return 0;
-}
-
-static void
-local_dealloc(localobject *self)
-{
-    PyThreadState *tstate;
+    Py_CLEAR(self->wr_callback);
+    /* Remove all strong references to dummies from the thread states */
     if (self->key
         && (tstate = PyThreadState_Get())
         && tstate->interp) {
@@ -587,16 +731,29 @@
                 PyDict_GetItem(tstate->dict, self->key))
                 PyDict_DelItem(tstate->dict, self->key);
     }
+    return 0;
+}
+
+static void
+local_dealloc(localobject *self)
+{
+    /* Weakrefs must be invalidated right now, otherwise they can be used
+       from code called below, which is very dangerous since Py_REFCNT(self) == 0 */
+    if (self->weakreflist != NULL)
+        PyObject_ClearWeakRefs((PyObject *) self);
+
+    PyObject_GC_UnTrack(self);
 
-    Py_XDECREF(self->key);
     local_clear(self);
+    Py_XDECREF(self->key);
     Py_TYPE(self)->tp_free((PyObject*)self);
 }
 
+/* Returns a borrowed reference to the local dict, creating it if necessary */
 static PyObject *
 _ldict(localobject *self)
 {
-    PyObject *tdict, *ldict;
+    PyObject *tdict, *ldict, *dummy;
 
     tdict = PyThreadState_GetDict();
     if (tdict == NULL) {
@@ -605,22 +762,11 @@
         return NULL;
     }
 
-    ldict = PyDict_GetItem(tdict, self->key);
-    if (ldict == NULL) {
-        ldict = PyDict_New(); /* we own ldict */
-
-        if (ldict == NULL)
+    dummy = PyDict_GetItem(tdict, self->key);
+    if (dummy == NULL) {
+        if (_local_create_dummy(self) < 0)
             return NULL;
-        else {
-            int i = PyDict_SetItem(tdict, self->key, ldict);
-            Py_DECREF(ldict); /* now ldict is borrowed */
-            if (i < 0)
-                return NULL;
-        }
-
-        Py_CLEAR(self->dict);
-        Py_INCREF(ldict);
-        self->dict = ldict; /* still borrowed */
+        ldict = self->dict;
 
         if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
             Py_TYPE(self)->tp_init((PyObject*)self,
@@ -631,14 +777,17 @@
             PyDict_DelItem(tdict, self->key);
             return NULL;
         }
-
+    }
+    else {
+        assert(Py_TYPE(dummy) == &localdummytype);
+        ldict = ((localdummyobject *) dummy)->localdict;
     }
 
     /* The call to tp_init above may have caused another thread to run.
        Install our ldict again. */
     if (self->dict != ldict) {
-        Py_CLEAR(self->dict);
         Py_INCREF(ldict);
+        Py_CLEAR(self->dict);
         self->dict = ldict;
     }
 
@@ -660,13 +809,10 @@
 static PyObject *
 local_getdict(localobject *self, void *closure)
 {
-    if (self->dict == NULL) {
-        PyErr_SetString(PyExc_AttributeError, "__dict__");
-        return NULL;
-    }
-
-    Py_INCREF(self->dict);
-    return self->dict;
+    PyObject *ldict;
+    ldict = _ldict(self);
+    Py_XINCREF(ldict);
+    return ldict;
 }
 
 static PyGetSetDef local_getset[] = {
@@ -697,12 +843,13 @@
     /* tp_getattro       */ (getattrofunc)local_getattro,
     /* tp_setattro       */ (setattrofunc)local_setattro,
     /* tp_as_buffer      */ 0,
-    /* tp_flags          */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+    /* tp_flags          */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
+                                               | Py_TPFLAGS_HAVE_GC,
     /* tp_doc            */ "Thread-local data",
     /* tp_traverse       */ (traverseproc)local_traverse,
     /* tp_clear          */ (inquiry)local_clear,
     /* tp_richcompare    */ 0,
-    /* tp_weaklistoffset */ 0,
+    /* tp_weaklistoffset */ offsetof(localobject, weakreflist),
     /* tp_iter           */ 0,
     /* tp_iternext       */ 0,
     /* tp_methods        */ 0,
@@ -743,6 +890,36 @@
     return value;
 }
 
+/* Called when a dummy is destroyed. */
+static PyObject *
+_localdummy_destroyed(PyObject *localweakref, PyObject *dummyweakref)
+{
+    PyObject *obj;
+    localobject *self;
+    assert(PyWeakref_CheckRef(localweakref));
+    obj = PyWeakref_GET_OBJECT(localweakref);
+    if (obj == Py_None)
+        Py_RETURN_NONE;
+    Py_INCREF(obj);
+    assert(PyObject_TypeCheck(obj, &localtype));
+    /* If the thread-local object is still alive and not being cleared,
+       remove the corresponding local dict */
+    self = (localobject *) obj;
+    if (self->dummies != NULL) {
+        PyObject *ldict;
+        ldict = PyDict_GetItem(self->dummies, dummyweakref);
+        if (ldict != NULL) {
+            if (ldict == self->dict)
+                Py_CLEAR(self->dict);
+            PyDict_DelItem(self->dummies, dummyweakref);
+        }
+        if (PyErr_Occurred())
+            PyErr_WriteUnraisable(obj);
+    }
+    Py_DECREF(obj);
+    Py_RETURN_NONE;
+}
+
 /* Module functions */
 
 struct bootstate {
@@ -901,7 +1078,7 @@
 "allocate_lock() -> lock object\n\
 (allocate() is an obsolete synonym)\n\
 \n\
-Create a new lock object.  See LockType.__doc__ for information about locks.");
+Create a new lock object.  See help(LockType) for information about locks.");
 
 static PyObject *
 thread_get_ident(PyObject *self)
@@ -1063,6 +1240,8 @@
     PyObject *m, *d, *timeout_max;
 
     /* Initialize types: */
+    if (PyType_Ready(&localdummytype) < 0)
+        return NULL;
     if (PyType_Ready(&localtype) < 0)
         return NULL;
     if (PyType_Ready(&Locktype) < 0)

Modified: python/branches/pep-0384/Modules/arraymodule.c
==============================================================================
--- python/branches/pep-0384/Modules/arraymodule.c	(original)
+++ python/branches/pep-0384/Modules/arraymodule.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/binascii.c
==============================================================================
--- python/branches/pep-0384/Modules/binascii.c	(original)
+++ python/branches/pep-0384/Modules/binascii.c	Fri Aug 27 21:11:11 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;
@@ -664,7 +664,7 @@
                 /* More than 3 in a row. Output RLE. */
                 *out_data++ = ch;
                 *out_data++ = RUNCHAR;
-                *out_data++ = inend-in;
+                *out_data++ = (unsigned char) (inend-in);
                 in = inend-1;
             } else {
                 /* Less than 3. Output the byte itself */
@@ -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/pep-0384/Modules/bz2module.c
==============================================================================
--- python/branches/pep-0384/Modules/bz2module.c	(original)
+++ python/branches/pep-0384/Modules/bz2module.c	Fri Aug 27 21:11:11 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;
 

Deleted: python/branches/pep-0384/Modules/datetimemodule.c
==============================================================================
--- python/branches/pep-0384/Modules/datetimemodule.c	Fri Aug 27 21:11:11 2010
+++ (empty file)
@@ -1,5488 +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)
-#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
-                            ((PyDateTime_Time *)(p))->tzinfo : Py_None)
-#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
-                          ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
-/* 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;
-
-PyObject *PyDateTime_TimeZone_UTC;
-
-/* 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;
-}
-
-/* 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 check the result.  tzinfo must
- * be an instance of the tzinfo class.  If the method returns None, this
- * returns None.  If the method doesn't return None or timedelta, TypeError is
- * raised and this returns NULL.  If it returns a timedelta and the value is
- * out of range or isn't a whole number of minutes, ValueError is raised and
- * this returns NULL.  Else result is returned.
- */
-static PyObject *
-call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
-{
-    PyObject *offset;
-
-    assert(tzinfo != NULL);
-    assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
-    assert(tzinfoarg != NULL);
-
-    if (tzinfo == Py_None)
-        Py_RETURN_NONE;
-    offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
-    if (offset == Py_None || offset == NULL)
-        return offset;
-    if (PyDelta_Check(offset)) {
-        if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
-            Py_DECREF(offset);
-            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) {
-            Py_DECREF(offset);
-            PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
-                         " strictly between -timedelta(hours=24) and"
-                         " timedelta(hours=24).");
-            return NULL;
-        }
-    }
-    else {
-        Py_DECREF(offset);
-        PyErr_Format(PyExc_TypeError,
-                     "tzinfo.%s() must return None or "
-                     "timedelta, not '%.200s'",
-                     name, Py_TYPE(offset)->tp_name);
-        return NULL;
-    }
-
-    return offset;
-}
-
-/* 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 PyObject *
-call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
-}
-
-/* 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 PyObject *
-call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
-{
-    return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
-}
-
-/* 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)
-        Py_RETURN_NONE;
-
-    result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
-
-    if (result == NULL || result == Py_None)
-        return result;
-
-    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;
-}
-
-/* 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));
-}
-
-static PyObject *delta_negative(PyDateTime_Delta *self);
-
-/* 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)
-{
-    PyObject *offset;
-    int hours, minutes, seconds;
-    char sign;
-
-    assert(buflen >= 1);
-
-    offset = call_utcoffset(tzinfo, tzinfoarg);
-    if (offset == NULL)
-        return -1;
-    if (offset == Py_None) {
-        Py_DECREF(offset);
-        *buf = '\0';
-        return 0;
-    }
-    /* Offset is normalized, so it is negative if days < 0 */
-    if (GET_TD_DAYS(offset) < 0) {
-        PyObject *temp = offset;
-        sign = '-';
-        offset = delta_negative((PyDateTime_Delta *)offset);
-        Py_DECREF(temp);
-        if (offset == NULL)
-            return -1;
-    }
-    else {
-        sign = '+';
-    }
-    /* 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, 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, NULL);
-            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 int
-delta_cmp(PyObject *self, PyObject *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;
-}
-
-static PyObject *
-delta_richcompare(PyObject *self, PyObject *other, int op)
-{
-    if (PyDelta_Check(other)) {
-        int diff = delta_cmp(self, 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 *add_datetime_timedelta(PyDateTime_DateTime *date,
-                                        PyDateTime_Delta *delta,
-                                        int factor);
-static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
-static PyObject *datetime_dst(PyObject *self, PyObject *);
-
-static PyObject *
-tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
-{
-    PyObject *result = NULL;
-    PyObject *off = NULL, *dst = NULL;
-    PyDateTime_Delta *delta = NULL;
-
-    if (!PyDateTime_Check(dt)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "fromutc: argument must be a datetime");
-        return NULL;
-    }
-    if (GET_DT_TZINFO(dt) != (PyObject *)self) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
-                        "is not self");
-        return NULL;
-    }
-
-    off = datetime_utcoffset(dt, NULL);
-    if (off == NULL)
-        return NULL;
-    if (off == Py_None) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
-                        "utcoffset() result required");
-        goto Fail;
-    }
-
-    dst = datetime_dst(dt, NULL);
-    if (dst == NULL)
-        goto Fail;
-    if (dst == Py_None) {
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
-                        "dst() result required");
-        goto Fail;
-    }
-
-    delta = (PyDateTime_Delta *)delta_subtract(off, dst);
-    if (delta == NULL)
-        goto Fail;
-    result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
-    if (result == NULL)
-        goto Fail;
-
-    Py_DECREF(dst);
-    dst = call_dst(GET_DT_TZINFO(dt), result);
-    if (dst == NULL)
-        goto Fail;
-    if (dst == Py_None)
-        goto Inconsistent;
-    if (delta_bool(delta) != 0) {
-        PyObject *temp = result;
-        result = add_datetime_timedelta((PyDateTime_DateTime *)result,
-                                        (PyDateTime_Delta *)dst, 1);
-        Py_DECREF(temp);
-        if (result == NULL)
-            goto Fail;
-    }
-    Py_DECREF(delta);
-    Py_DECREF(dst);
-    Py_DECREF(off);
-    return result;
-
-Inconsistent:
-    PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
-                    "inconsistent results; cannot convert");
-
-    /* fall thru to failure */
-Fail:
-    Py_XDECREF(off);
-    Py_XDECREF(dst);
-    Py_XDECREF(delta);
-    Py_XDECREF(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_repr(PyDateTime_TimeZone *self)
-{
-    /* Note that although timezone is not subclassable, it is convenient
-       to use Py_TYPE(self)->tp_name here. */
-    const char *type_name = Py_TYPE(self)->tp_name;
-
-    if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
-        return PyUnicode_FromFormat("%s.utc", type_name);
-
-    if (self->name == NULL)
-        return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
-
-    return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
-                                self->name);
-}
-
-
-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 *
-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 */
-    (reprfunc)timezone_repr,          /* 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(PyObject *self, PyObject *unused) {
-    return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
-}
-
-static PyObject *
-time_dst(PyObject *self, PyObject *unused) {
-    return call_dst(GET_TIME_TZINFO(self), Py_None);
-}
-
-static PyObject *
-time_tzname(PyDateTime_Time *self, PyObject *unused) {
-    return call_tzname(GET_TIME_TZINFO(self), 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)
-{
-    PyObject *result = NULL;
-    PyObject *offset1, *offset2;
-    int diff;
-
-    if (! PyTime_Check(other)) {
-        Py_INCREF(Py_NotImplemented);
-        return Py_NotImplemented;
-    }
-
-    if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
-        diff = memcmp(((PyDateTime_Time *)self)->data,
-                      ((PyDateTime_Time *)other)->data,
-                      _PyDateTime_TIME_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-    offset1 = time_utcoffset(self, NULL);
-    if (offset1 == NULL)
-        return NULL;
-    offset2 = time_utcoffset(other, NULL);
-    if (offset2 == NULL)
-        goto done;
-    /* 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 == Py_None at this point.
-     */
-    if ((offset1 == offset2) ||
-        (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
-         delta_cmp(offset1, offset2) == 0)) {
-        diff = memcmp(((PyDateTime_Time *)self)->data,
-                      ((PyDateTime_Time *)other)->data,
-                      _PyDateTime_TIME_DATASIZE);
-        result = diff_to_bool(diff, op);
-    }
-    /* The hard case: both aware with different UTC offsets */
-    else if (offset1 != Py_None && offset2 != Py_None) {
-        int offsecs1, offsecs2;
-        assert(offset1 != offset2); /* else last "if" handled it */
-        offsecs1 = TIME_GET_HOUR(self) * 3600 +
-                   TIME_GET_MINUTE(self) * 60 +
-                   TIME_GET_SECOND(self) -
-                   GET_TD_DAYS(offset1) * 86400 -
-                   GET_TD_SECONDS(offset1);
-        offsecs2 = TIME_GET_HOUR(other) * 3600 +
-                   TIME_GET_MINUTE(other) * 60 +
-                   TIME_GET_SECOND(other) -
-                   GET_TD_DAYS(offset2) * 86400 -
-                   GET_TD_SECONDS(offset2);
-        diff = offsecs1 - offsecs2;
-        if (diff == 0)
-            diff = TIME_GET_MICROSECOND(self) -
-                   TIME_GET_MICROSECOND(other);
-        result = diff_to_bool(diff, op);
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "can't compare offset-naive and "
-                        "offset-aware times");
-    }
- done:
-    Py_DECREF(offset1);
-    Py_XDECREF(offset2);
-    return result;
-}
-
-static long
-time_hash(PyDateTime_Time *self)
-{
-    if (self->hashcode == -1) {
-        PyObject *offset;
-
-        offset = time_utcoffset((PyObject *)self, NULL);
-
-        if (offset == NULL)
-            return -1;
-
-        /* Reduce this to a hash of another object. */
-        if (offset == Py_None)
-            self->hashcode = generic_hash(
-                (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
-        else {
-            PyObject *temp1, *temp2;
-            int seconds, microseconds;
-            assert(HASTZINFO(self));
-            seconds = TIME_GET_HOUR(self) * 3600 +
-                      TIME_GET_MINUTE(self) * 60 +
-                      TIME_GET_SECOND(self);
-            microseconds = TIME_GET_MICROSECOND(self);
-            temp1 = new_delta(0, seconds, microseconds, 1);
-            if (temp1 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            temp2 = delta_subtract(temp1, offset);
-            Py_DECREF(temp1);
-            if (temp2 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            self->hashcode = PyObject_Hash(temp2);
-            Py_DECREF(temp2);
-        }
-        Py_DECREF(offset);
-    }
-    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(PyObject *self)
-{
-    PyObject *offset, *tzinfo;
-    int offsecs = 0;
-
-    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;
-    }
-    tzinfo = GET_TIME_TZINFO(self);
-    if (tzinfo != Py_None) {
-        offset = call_utcoffset(tzinfo, Py_None);
-        if (offset == NULL)
-            return -1;
-        offsecs = GET_TD_DAYS(offset)*86400 + GET_TD_SECONDS(offset);
-        Py_DECREF(offset);
-    }
-    return (TIME_GET_MINUTE(self)*60 - offsecs + TIME_GET_HOUR(self)*3600) != 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(PyObject *self, PyObject *unused) {
-    return call_utcoffset(GET_DT_TZINFO(self), self);
-}
-
-static PyObject *
-datetime_dst(PyObject *self, PyObject *unused) {
-    return call_dst(GET_DT_TZINFO(self), self);
-}
-
-static PyObject *
-datetime_tzname(PyObject *self, PyObject *unused) {
-    return call_tzname(GET_DT_TZINFO(self), 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 */
-            PyObject *offset1, *offset2, *offdiff = NULL;
-            int delta_d, delta_s, delta_us;
-
-            if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
-                offset2 = offset1 = Py_None;
-                Py_INCREF(offset1);
-                Py_INCREF(offset2);
-            }
-            else {
-                offset1 = datetime_utcoffset(left, NULL);
-                if (offset1 == NULL)
-                    return NULL;
-                offset2 = datetime_utcoffset(right, NULL);
-                if (offset2 == NULL) {
-                    Py_DECREF(offset1);
-                    return NULL;
-                }
-                if ((offset1 != Py_None) != (offset2 != Py_None)) {
-                    PyErr_SetString(PyExc_TypeError,
-                                    "can't subtract offset-naive and "
-                                    "offset-aware datetimes");
-                    Py_DECREF(offset1);
-                    Py_DECREF(offset2);
-                    return NULL;
-                }
-            }
-            if ((offset1 != offset2) &&
-                delta_cmp(offset1, offset2) != 0) {
-                offdiff = delta_subtract(offset1, offset2);
-                if (offdiff == NULL) {
-                    Py_DECREF(offset1);
-                    Py_DECREF(offset2);
-                    return NULL;
-                }
-            }
-            Py_DECREF(offset1);
-            Py_DECREF(offset2);
-            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);
-            result = new_delta(delta_d, delta_s, delta_us, 1);
-            if (offdiff != NULL) {
-                PyObject *temp = result;
-                result = delta_subtract(result, offdiff);
-                Py_DECREF(temp);
-                Py_DECREF(offdiff);
-            }
-        }
-        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)
-{
-    PyObject *result = NULL;
-    PyObject *offset1, *offset2;
-    int diff;
-
-    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 (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
-        diff = memcmp(((PyDateTime_DateTime *)self)->data,
-                      ((PyDateTime_DateTime *)other)->data,
-                      _PyDateTime_DATETIME_DATASIZE);
-        return diff_to_bool(diff, op);
-    }
-    offset1 = datetime_utcoffset(self, NULL);
-    if (offset1 == NULL)
-        return NULL;
-    offset2 = datetime_utcoffset(other, NULL);
-    if (offset2 == NULL)
-        goto done;
-    /* 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 == Py_None at this point.
-     */
-    if ((offset1 == offset2) ||
-        (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
-         delta_cmp(offset1, offset2) == 0)) {
-        diff = memcmp(((PyDateTime_DateTime *)self)->data,
-                      ((PyDateTime_DateTime *)other)->data,
-                      _PyDateTime_DATETIME_DATASIZE);
-        result = diff_to_bool(diff, op);
-    }
-    else if (offset1 != Py_None && offset2 != Py_None) {
-        PyDateTime_Delta *delta;
-
-        assert(offset1 != offset2); /* else last "if" handled it */
-        delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
-                                                       other);
-        if (delta == NULL)
-            goto done;
-        diff = GET_TD_DAYS(delta);
-        if (diff == 0)
-            diff = GET_TD_SECONDS(delta) |
-                   GET_TD_MICROSECONDS(delta);
-        Py_DECREF(delta);
-        result = diff_to_bool(diff, op);
-    }
-    else {
-        PyErr_SetString(PyExc_TypeError,
-                        "can't compare offset-naive and "
-                        "offset-aware datetimes");
-    }
- done:
-    Py_DECREF(offset1);
-    Py_XDECREF(offset2);
-    return result;
-}
-
-static long
-datetime_hash(PyDateTime_DateTime *self)
-{
-    if (self->hashcode == -1) {
-        PyObject *offset;
-
-        offset = datetime_utcoffset((PyObject *)self, NULL);
-
-        if (offset == NULL)
-            return -1;
-
-        /* Reduce this to a hash of another object. */
-        if (offset == Py_None)
-            self->hashcode = generic_hash(
-                (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
-        else {
-            PyObject *temp1, *temp2;
-            int days, seconds;
-
-            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) * 60 +
-                      DATE_GET_SECOND(self);
-            temp1 = new_delta(days, seconds,
-                              DATE_GET_MICROSECOND(self),
-                              1);
-            if (temp1 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            temp2 = delta_subtract(temp1, offset);
-            Py_DECREF(temp1);
-            if (temp2 == NULL) {
-                Py_DECREF(offset);
-                return -1;
-            }
-            self->hashcode = PyObject_Hash(temp2);
-            Py_DECREF(temp2);
-        }
-        Py_DECREF(offset);
-    }
-    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)
-{
-    PyObject *result;
-    PyObject *offset;
-    PyObject *temp;
-    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 = datetime_utcoffset((PyObject *)self, NULL);
-    if (offset == NULL)
-        return NULL;
-    if (offset == Py_None) {
-        Py_DECREF(offset);
-      NeedAware:
-        PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
-                        "a naive datetime");
-        return NULL;
-    }
-
-    /* result = self - offset */
-    result = add_datetime_timedelta(self,
-                (PyDateTime_Delta *)offset, -1);
-    Py_DECREF(offset);
-    if (result == NULL)
-        return NULL;
-
-    /* Attach new tzinfo and let fromutc() do the rest. */
-    temp = ((PyDateTime_DateTime *)result)->tzinfo;
-    ((PyDateTime_DateTime *)result)->tzinfo = tzinfo;
-    Py_INCREF(tzinfo);
-    Py_DECREF(temp);
-
-    temp = result;
-    result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
-    Py_DECREF(temp);
-
-    return result;
-}
-
-static PyObject *
-datetime_timetuple(PyDateTime_DateTime *self)
-{
-    int dstflag = -1;
-
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        PyObject * dst;
-
-        dst = call_dst(self->tzinfo, (PyObject *)self);
-        if (dst == NULL)
-            return NULL;
-
-        if (dst != Py_None)
-            dstflag = delta_bool((PyDateTime_Delta *)dst);
-        Py_DECREF(dst);
-    }
-    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),
-                    GET_DT_TZINFO(self));
-}
-
-static PyObject *
-datetime_utctimetuple(PyDateTime_DateTime *self)
-{
-    int y, m, d, hh, mm, ss;
-    PyObject *tzinfo;
-    PyDateTime_DateTime *utcself;
-
-    tzinfo = GET_DT_TZINFO(self);
-    if (tzinfo == Py_None) {
-        utcself = self;
-        Py_INCREF(utcself);
-    }
-    else {
-        PyObject *offset;
-        offset = call_utcoffset(tzinfo, (PyObject *)self);
-        if (offset == NULL)
-            return NULL;
-        if (offset == Py_None) {
-            Py_DECREF(offset);
-            utcself = self;
-            Py_INCREF(utcself);
-        }
-        else {
-            utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
-                                                (PyDateTime_Delta *)offset, -1);
-            Py_DECREF(offset);
-            if (utcself == NULL)
-                return NULL;
-        }
-    }
-    y = GET_YEAR(utcself);
-    m = GET_MONTH(utcself);
-    d = GET_DAY(utcself);
-    hh = DATE_GET_HOUR(utcself);
-    mm = DATE_GET_MINUTE(utcself);
-    ss = DATE_GET_SECOND(utcself);
-
-    Py_DECREF(utcself);
-    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;
-    PyDateTime_TimeZone_UTC = 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/pep-0384/Modules/errnomodule.c
==============================================================================
--- python/branches/pep-0384/Modules/errnomodule.c	(original)
+++ python/branches/pep-0384/Modules/errnomodule.c	Fri Aug 27 21:11:11 2010
@@ -82,7 +82,8 @@
 
     /*
      * The names and comments are borrowed from linux/include/errno.h,
-     * which should be pretty all-inclusive
+     * which should be pretty all-inclusive.  However, the Solaris specific
+     * names and comments are borrowed from sys/errno.h in Solaris.
      */
 
 #ifdef ENODEV
@@ -797,6 +798,26 @@
     inscode(d, ds, de, "WSAN", WSAN, "Error WSAN");
 #endif
 
+    /* Solaris-specific errnos */
+#ifdef ECANCELED
+    inscode(d, ds, de, "ECANCELED", ECANCELED, "Operation canceled");
+#endif
+#ifdef ENOTSUP
+    inscode(d, ds, de, "ENOTSUP", ENOTSUP, "Operation not supported");
+#endif
+#ifdef EOWNERDEAD
+    inscode(d, ds, de, "EOWNERDEAD", EOWNERDEAD, "Process died with the lock");
+#endif
+#ifdef ENOTRECOVERABLE
+    inscode(d, ds, de, "ENOTRECOVERABLE", ENOTRECOVERABLE, "Lock is not recoverable");
+#endif
+#ifdef ELOCKUNMAPPED
+    inscode(d, ds, de, "ELOCKUNMAPPED", ELOCKUNMAPPED, "Locked lock was unmapped");
+#endif
+#ifdef ENOTACTIVE
+    inscode(d, ds, de, "ENOTACTIVE", ENOTACTIVE, "Facility is not active");
+#endif
+
     Py_DECREF(de);
     return m;
 }

Modified: python/branches/pep-0384/Modules/gcmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/gcmodule.c	(original)
+++ python/branches/pep-0384/Modules/gcmodule.c	Fri Aug 27 21:11:11 2010
@@ -1295,17 +1295,16 @@
 
 static struct PyModuleDef gcmodule = {
     PyModuleDef_HEAD_INIT,
-    "gc",
-    gc__doc__,
-    -1,
-    GcMethods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
+    "gc",              /* m_name */
+    gc__doc__,         /* m_doc */
+    -1,                /* m_size */
+    GcMethods,         /* m_methods */
+    NULL,              /* m_reload */
+    NULL,              /* m_traverse */
+    NULL,              /* m_clear */
+    NULL               /* m_free */
 };
 
-
 PyMODINIT_FUNC
 PyInit_gc(void)
 {
@@ -1364,6 +1363,37 @@
     return n;
 }
 
+void
+_PyGC_Fini(void)
+{
+    if (garbage != NULL && PyList_GET_SIZE(garbage) > 0) {
+        PySys_WriteStderr(
+            "gc: "
+            "%" PY_FORMAT_SIZE_T "d uncollectable objects at shutdown:\n",
+            PyList_GET_SIZE(garbage)
+            );
+        if (debug & DEBUG_UNCOLLECTABLE) {
+            PyObject *repr = NULL, *bytes = NULL;
+            repr = PyObject_Repr(garbage);
+            if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
+                PyErr_WriteUnraisable(garbage);
+            else {
+                PySys_WriteStderr(
+                    "    %s\n",
+                    PyBytes_AS_STRING(bytes)
+                    );
+            }
+            Py_XDECREF(repr);
+            Py_XDECREF(bytes);
+        }
+        else {
+            PySys_WriteStderr(
+                "    Use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them.\n"
+                );
+        }
+    }
+}
+
 /* for debugging */
 void
 _PyGC_Dump(PyGC_Head *g)

Modified: python/branches/pep-0384/Modules/getpath.c
==============================================================================
--- python/branches/pep-0384/Modules/getpath.c	(original)
+++ python/branches/pep-0384/Modules/getpath.c	Fri Aug 27 21:11:11 2010
@@ -48,7 +48,7 @@
  * argv0_path.  For prefix, the landmark's path is derived from the VPATH
  * preprocessor variable (taking into account that its value is almost, but
  * not quite, what we need).  For exec_prefix, the landmark is
- * Modules/Setup.  If the landmark is found, we're done.
+ * pybuilddir.txt.  If the landmark is found, we're done.
  *
  * For the remaining steps, the prefix landmark will always be
  * lib/python$VERSION/os.py and the exec_prefix will always be
@@ -89,6 +89,8 @@
  * directory).  This seems to make more sense given that currently the only
  * known use of sys.prefix and sys.exec_prefix is for the ILU installation
  * process to find the installed Python tree.
+ *
+ * NOTE: Windows MSVC builds use PC/getpathp.c instead!
  */
 
 #ifdef __cplusplus
@@ -134,18 +136,24 @@
 /* In principle, this should use HAVE__WSTAT, and _wstat
    should be detected by autoconf. However, no current
    POSIX system provides that function, so testing for
-   it is pointless. */
+   it is pointless.
+   Not sure whether the MS_WINDOWS guards are necessary:
+   perhaps for cygwin/mingw builds?
+*/
 #ifndef MS_WINDOWS
 static int
 _wstat(const wchar_t* path, struct stat *buf)
 {
-    char fname[PATH_MAX];
-    size_t res = wcstombs(fname, path, sizeof(fname));
-    if (res == (size_t)-1) {
+    int err;
+    char *fname;
+    fname = _Py_wchar2char(path);
+    if (fname == NULL) {
         errno = EINVAL;
         return -1;
     }
-    return stat(fname, buf);
+    err = stat(fname, buf);
+    PyMem_Free(fname);
+    return err;
 }
 #endif
 
@@ -394,12 +402,36 @@
         return 1;
     }
 
-    /* Check to see if argv[0] is in the build directory */
+    /* Check to see if argv[0] is in the build directory. "pybuilddir.txt"
+       is written by setup.py and contains the relative path to the location
+       of shared library modules. */
     wcscpy(exec_prefix, argv0_path);
-    joinpath(exec_prefix, L"Modules/Setup");
+    joinpath(exec_prefix, L"pybuilddir.txt");
     if (isfile(exec_prefix)) {
-        reduce(exec_prefix);
-        return -1;
+        FILE *f = _Py_wfopen(exec_prefix, L"rb");
+        if (f == NULL)
+            errno = 0;
+        else {
+            char buf[MAXPATHLEN+1];
+            PyObject *decoded;
+            wchar_t rel_builddir_path[MAXPATHLEN+1];
+            size_t n;
+            n = fread(buf, 1, MAXPATHLEN, f);
+            buf[n] = '\0';
+            fclose(f);
+            decoded = PyUnicode_DecodeUTF8(buf, n, "surrogateescape");
+            if (decoded != NULL) {
+                n = PyUnicode_AsWideChar((PyUnicodeObject*)decoded,
+                                         rel_builddir_path, MAXPATHLEN);
+                Py_DECREF(decoded);
+                if (n >= 0) {
+                    rel_builddir_path[n] = L'\0';
+                    wcscpy(exec_prefix, argv0_path);
+                    joinpath(exec_prefix, rel_builddir_path);
+                    return -1;
+                }
+            }
+        }
     }
 
     /* Search from argv0_path, until root is found */
@@ -461,21 +493,21 @@
 #endif
 
     if (_path) {
-            size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1);
-            path = wpath;
-            if (r == (size_t)-1 || r > MAXPATHLEN) {
-                    /* Could not convert PATH, or it's too long. */
-                    path = NULL;
-            }
+        size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1);
+        path = wpath;
+        if (r == (size_t)-1 || r > MAXPATHLEN) {
+            /* Could not convert PATH, or it's too long. */
+            path = NULL;
+        }
     }
 
-        /* If there is no slash in the argv0 path, then we have to
-         * assume python is on the user's $PATH, since there's no
-         * other way to find a directory to start the search from.  If
-         * $PATH isn't exported, you lose.
-         */
-        if (wcschr(prog, SEP))
-                wcsncpy(progpath, prog, MAXPATHLEN);
+    /* If there is no slash in the argv0 path, then we have to
+     * assume python is on the user's $PATH, since there's no
+     * other way to find a directory to start the search from.  If
+     * $PATH isn't exported, you lose.
+     */
+    if (wcschr(prog, SEP))
+        wcsncpy(progpath, prog, MAXPATHLEN);
 #ifdef __APPLE__
      /* On Mac OS X, if a script uses an interpreter of the form
       * "#!/opt/python2.3/bin/python", the kernel only passes "python"
@@ -487,52 +519,52 @@
       * will fail if a relative path was used. but in that case,
       * absolutize() should help us out below
       */
-        else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) {
-                size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1);
-                if (r == (size_t)-1 || r > MAXPATHLEN) {
-                        /* Could not convert execpath, or it's too long. */
-                        progpath[0] = '\0';
-                }
+    else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) {
+        size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1);
+        if (r == (size_t)-1 || r > MAXPATHLEN) {
+            /* Could not convert execpath, or it's too long. */
+            progpath[0] = '\0';
         }
+    }
 #endif /* __APPLE__ */
-        else if (path) {
-                while (1) {
-                        wchar_t *delim = wcschr(path, DELIM);
-
-                        if (delim) {
-                                size_t len = delim - path;
-                                if (len > MAXPATHLEN)
-                                        len = MAXPATHLEN;
-                                wcsncpy(progpath, path, len);
-                                *(progpath + len) = '\0';
-                        }
-                        else
-                                wcsncpy(progpath, path, MAXPATHLEN);
-
-                        joinpath(progpath, prog);
-                        if (isxfile(progpath))
-                                break;
-
-                        if (!delim) {
-                                progpath[0] = L'\0';
-                                break;
-                        }
-                        path = delim + 1;
-                }
+    else if (path) {
+        while (1) {
+            wchar_t *delim = wcschr(path, DELIM);
+
+            if (delim) {
+                size_t len = delim - path;
+                if (len > MAXPATHLEN)
+                    len = MAXPATHLEN;
+                wcsncpy(progpath, path, len);
+                *(progpath + len) = '\0';
+            }
+            else
+                wcsncpy(progpath, path, MAXPATHLEN);
+
+            joinpath(progpath, prog);
+            if (isxfile(progpath))
+                break;
+
+            if (!delim) {
+                progpath[0] = L'\0';
+                break;
+            }
+            path = delim + 1;
         }
-        else
-                progpath[0] = '\0';
-        if (progpath[0] != SEP && progpath[0] != '\0')
-                absolutize(progpath);
-        wcsncpy(argv0_path, progpath, MAXPATHLEN);
-        argv0_path[MAXPATHLEN] = '\0';
+    }
+    else
+        progpath[0] = '\0';
+    if (progpath[0] != SEP && progpath[0] != '\0')
+        absolutize(progpath);
+    wcsncpy(argv0_path, progpath, MAXPATHLEN);
+    argv0_path[MAXPATHLEN] = '\0';
 
 #ifdef WITH_NEXT_FRAMEWORK
-        /* On Mac OS X we have a special case if we're running from a framework.
-        ** This is because the python home should be set relative to the library,
-        ** which is in the framework, not relative to the executable, which may
-        ** be outside of the framework. Except when we're in the build directory...
-        */
+    /* On Mac OS X we have a special case if we're running from a framework.
+    ** This is because the python home should be set relative to the library,
+    ** which is in the framework, not relative to the executable, which may
+    ** be outside of the framework. Except when we're in the build directory...
+    */
     pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize"));
     /* Use dylib functions to find out where the framework was loaded from */
     buf = (wchar_t *)NSLibraryNameForModule(pythonModule);
@@ -550,13 +582,13 @@
         joinpath(argv0_path, lib_python);
         joinpath(argv0_path, LANDMARK);
         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);
+            /* We are in the build directory so use the name of the
+               executable - we know that the absolute path is passed */
+            wcsncpy(argv0_path, progpath, MAXPATHLEN);
         }
         else {
-                /* Use the location of the library as the progpath */
-                wcsncpy(argv0_path, buf, MAXPATHLEN);
+            /* Use the location of the library as the progpath */
+            wcsncpy(argv0_path, buf, MAXPATHLEN);
         }
     }
 #endif

Modified: python/branches/pep-0384/Modules/main.c
==============================================================================
--- python/branches/pep-0384/Modules/main.c	(original)
+++ python/branches/pep-0384/Modules/main.c	Fri Aug 27 21:11:11 2010
@@ -94,33 +94,39 @@
 PYTHONPATH   : '%c'-separated list of directories prefixed to the\n\
                default module search path.  The result is sys.path.\n\
 ";
-static char *usage_5 = "\
-PYTHONHOME   : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
-               The default module search path uses %s.\n\
-PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
-PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
-";
+static char *usage_5 =
+"PYTHONHOME   : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n"
+"               The default module search path uses %s.\n"
+"PYTHONCASEOK : ignore case in 'import' statements (Windows).\n"
+"PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n"
+#if !(defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)) && !defined(__APPLE__)
+"PYTHONFSENCODING: Encoding used for the filesystem.\n"
+#endif
+;
 
-#ifndef MS_WINDOWS
-static FILE*
-_wfopen(const wchar_t *path, const wchar_t *mode)
+FILE *
+_Py_wfopen(const wchar_t *path, const wchar_t *mode)
 {
-    char cpath[PATH_MAX];
+#ifndef MS_WINDOWS
+    FILE *f;
+    char *cpath;
     char cmode[10];
     size_t r;
-    r = wcstombs(cpath, path, PATH_MAX);
-    if (r == (size_t)-1 || r >= PATH_MAX) {
-        errno = EINVAL;
-        return NULL;
-    }
     r = wcstombs(cmode, mode, 10);
     if (r == (size_t)-1 || r >= 10) {
         errno = EINVAL;
         return NULL;
     }
-    return fopen(cpath, cmode);
-}
+    cpath = _Py_wchar2char(path);
+    if (cpath == NULL)
+        return NULL;
+    f = fopen(cpath, cmode);
+    PyMem_Free(cpath);
+    return f;
+#else
+    return _wfopen(path, mode);
 #endif
+}
 
 
 static int
@@ -253,6 +259,63 @@
     }
 }
 
+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:
+    PySys_WriteStderr("Unable to decode the command from the command line:\n");
+    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 */
 
@@ -545,10 +608,9 @@
     }
 
     if (module != NULL) {
-        /* Backup _PyOS_optind and force sys.argv[0] = '-c'
-           so that PySys_SetArgv correctly sets sys.path[0] to ''*/
+        /* Backup _PyOS_optind and force sys.argv[0] = '-m'*/
         _PyOS_optind--;
-        argv[_PyOS_optind] = L"-c";
+        argv[_PyOS_optind] = L"-m";
     }
 
     PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
@@ -564,22 +626,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);
     }
@@ -598,7 +646,7 @@
         }
 
         if (sts==-1 && filename!=NULL) {
-            if ((fp = _wfopen(filename, L"r")) == NULL) {
+            if ((fp = _Py_wfopen(filename, L"r")) == NULL) {
                 char cfilename[PATH_MAX];
                 size_t r = wcstombs(cfilename, filename, PATH_MAX);
                 if (r == PATH_MAX)
@@ -636,30 +684,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
@@ -712,6 +738,85 @@
 }
 
 
+/* Encode a (wide) character string to the locale encoding with the
+   surrogateescape error handler (characters in range U+DC80..U+DCFF are
+   converted to bytes 0x80..0xFF).
+
+   This function is the reverse of _Py_char2wchar().
+
+   Return a pointer to a newly allocated byte string (use PyMem_Free() to free
+   the memory), or NULL on error (conversion error or memory error). */
+char*
+_Py_wchar2char(const wchar_t *text)
+{
+    const size_t len = wcslen(text);
+    char *result = NULL, *bytes = NULL;
+    size_t i, size, converted;
+    wchar_t c, buf[2];
+
+    /* The function works in two steps:
+       1. compute the length of the output buffer in bytes (size)
+       2. outputs the bytes */
+    size = 0;
+    buf[1] = 0;
+    while (1) {
+        for (i=0; i < len; i++) {
+            c = text[i];
+            if (c >= 0xdc80 && c <= 0xdcff) {
+                /* UTF-8b surrogate */
+                if (bytes != NULL) {
+                    *bytes++ = c - 0xdc00;
+                    size--;
+                }
+                else
+                    size++;
+                continue;
+            }
+            else {
+                buf[0] = c;
+                if (bytes != NULL)
+                    converted = wcstombs(bytes, buf, size);
+                else
+                    converted = wcstombs(NULL, buf, 0);
+                if (converted == (size_t)-1) {
+                    if (result != NULL)
+                        PyMem_Free(result);
+                    return NULL;
+                }
+                if (bytes != NULL) {
+                    bytes += converted;
+                    size -= converted;
+                }
+                else
+                    size += converted;
+            }
+        }
+        if (result != NULL) {
+            *bytes = 0;
+            break;
+        }
+
+        size += 1; /* nul byte at the end */
+        result = PyMem_Malloc(size);
+        if (result == NULL)
+            return NULL;
+        bytes = result;
+    }
+    return result;
+}
+
+
+/* Decode a byte string from the locale encoding with the
+   surrogateescape error handler (undecodable bytes are decoded as characters
+   in range U+DC80..U+DCFF). If a byte sequence can be decoded as a surrogate
+   character, escape the bytes using the surrogateescape error handler instead
+   of decoding them.
+
+   Use _Py_wchar2char() to encode the character string back to a byte string.
+
+   Return a pointer to a newly allocated (wide) character string (use
+   PyMem_Free() to free the memory), or NULL on error (conversion error or
+   memory error). */
 wchar_t*
 _Py_char2wchar(char* arg)
 {

Modified: python/branches/pep-0384/Modules/mmapmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/mmapmodule.c	(original)
+++ python/branches/pep-0384/Modules/mmapmodule.c	Fri Aug 27 21:11:11 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
@@ -845,7 +878,7 @@
                             "in range(0, 256)");
             return -1;
         }
-        self->data[i] = v;
+        self->data[i] = (char) v;
         return 0;
     }
     else if (PySlice_Check(item)) {
@@ -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/pep-0384/Modules/nismodule.c
==============================================================================
--- python/branches/pep-0384/Modules/nismodule.c	(original)
+++ python/branches/pep-0384/Modules/nismodule.c	Fri Aug 27 21:11:11 2010
@@ -117,13 +117,14 @@
             if (invallen > 0 && inval[invallen-1] == '\0')
             invallen--;
         }
-        key = PyUnicode_FromStringAndSize(inkey, inkeylen);
-        val = PyUnicode_FromStringAndSize(inval, invallen);
+        key = PyUnicode_DecodeFSDefaultAndSize(inkey, inkeylen);
+        val = PyUnicode_DecodeFSDefaultAndSize(inval, invallen);
         if (key == NULL || val == NULL) {
             /* XXX error -- don't know how to handle */
             PyErr_Clear();
             Py_XDECREF(key);
             Py_XDECREF(val);
+            indata->state = PyEval_SaveThread();
             return 1;
         }
         err = PyDict_SetItem(indata->dict, key, val);
@@ -158,30 +159,40 @@
 {
     char *match;
     char *domain = NULL;
-    int keylen, len;
+    Py_ssize_t keylen;
+    int len;
     char *key, *map;
     int err;
-    PyObject *res;
+    PyObject *ukey, *bkey, *res;
     int fix;
     static char *kwlist[] = {"key", "map", "domain", NULL};
 
     if (!PyArg_ParseTupleAndKeywords(args, kwdict,
-                                     "s#s|s:match", kwlist,
-                                     &key, &keylen, &map, &domain))
+                                     "Us|s:match", kwlist,
+                                     &ukey, &map, &domain))
         return NULL;
-    if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
+    if ((bkey = PyUnicode_EncodeFSDefault(ukey)) == NULL)
+        return NULL;
+    if (PyBytes_AsStringAndSize(bkey, &key, &keylen) == -1) {
+        Py_DECREF(bkey);
+        return NULL;
+    }
+    if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) {
+        Py_DECREF(bkey);
         return nis_error(err);
+    }
     map = nis_mapname (map, &fix);
     if (fix)
         keylen++;
     Py_BEGIN_ALLOW_THREADS
     err = yp_match (domain, map, key, keylen, &match, &len);
     Py_END_ALLOW_THREADS
+    Py_DECREF(bkey);
     if (fix)
         len--;
     if (err != 0)
         return nis_error(err);
-    res = PyUnicode_FromStringAndSize (match, len);
+    res = PyUnicode_DecodeFSDefaultAndSize(match, len);
     free (match);
     return res;
 }

Modified: python/branches/pep-0384/Modules/posixmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/posixmodule.c	(original)
+++ python/branches/pep-0384/Modules/posixmodule.c	Fri Aug 27 21:11:11 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>
@@ -376,7 +385,7 @@
     const int i1 = fd >> IOINFO_L2E;
     const int i2 = fd & ((1 << IOINFO_L2E) - 1);
 
-    static int sizeof_ioinfo = 0;
+    static size_t sizeof_ioinfo = 0;
 
     /* Determine the actual size of the ioinfo structure,
      * as used by the CRT loaded in memory
@@ -1220,7 +1229,7 @@
         /* 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.
@@ -1840,7 +1849,7 @@
 #endif
     if (ret == NULL)
         return posix_error();
-    return PyUnicode_FromString(ret);
+    return PyUnicode_DecodeFSDefault(ret);
 }
 #endif
 
@@ -1862,7 +1871,7 @@
 #endif
     if (ret == NULL)
         return posix_error();
-    return PyUnicode_FromString(buffer);
+    return PyUnicode_DecodeFSDefault(buffer);
 }
 #endif
 
@@ -2291,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.");
@@ -2315,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':')
@@ -2337,7 +2353,9 @@
             free(wnamebuf);
             return NULL;
         }
+        Py_BEGIN_ALLOW_THREADS
         hFindFile = FindFirstFileW(wnamebuf, &wFileData);
+        Py_END_ALLOW_THREADS
         if (hFindFile == INVALID_HANDLE_VALUE) {
             int error = GetLastError();
             if (error == ERROR_FILE_NOT_FOUND) {
@@ -2414,7 +2432,9 @@
     if ((d = PyList_New(0)) == NULL)
         return NULL;
 
+    Py_BEGIN_ALLOW_THREADS
     hFindFile = FindFirstFile(namebuf, &FileData);
+    Py_END_ALLOW_THREADS
     if (hFindFile == INVALID_HANDLE_VALUE) {
         int error = GetLastError();
         if (error == ERROR_FILE_NOT_FOUND)
@@ -2548,12 +2568,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);
@@ -3630,8 +3655,8 @@
     char **argvlist;
     char **envlist;
     PyObject *res = NULL;
-    int mode, envc;
-    Py_ssize_t argc, i;
+    int mode;
+    Py_ssize_t argc, i, envc;
     Py_intptr_t spawnval;
     PyObject *(*getitem)(PyObject *, Py_ssize_t);
     Py_ssize_t lastarg = 0;
@@ -3816,7 +3841,8 @@
     char **argvlist;
     char **envlist;
     PyObject *res=NULL;
-    int mode, i, argc, envc;
+    int mode;
+    Py_ssize_t argc, i, envc;
     Py_intptr_t spawnval;
     PyObject *(*getitem)(PyObject *, Py_ssize_t);
     int lastarg = 0;
@@ -4154,17 +4180,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;
@@ -4172,7 +4230,10 @@
             }
             PyList_SET_ITEM(result, i, o);
         }
-        }
+    }
+
+    if (alt_grouplist != grouplist) {
+        PyMem_Free(alt_grouplist);
     }
 
     return result;
@@ -4189,13 +4250,19 @@
 static PyObject *
 posix_initgroups(PyObject *self, PyObject *args)
 {
+    PyObject *oname;
     char *username;
+    int res;
     long gid;
 
-    if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid))
+    if (!PyArg_ParseTuple(args, "O&l:initgroups",
+                          PyUnicode_FSConverter, &oname, &gid))
         return NULL;
+    username = PyBytes_AS_STRING(oname);
 
-    if (initgroups(username, (gid_t) gid) == -1)
+    res = initgroups(username, (gid_t) gid);
+    Py_DECREF(oname);
+    if (res == -1)
         return PyErr_SetFromErrno(PyExc_OSError);
 
     Py_INCREF(Py_None);
@@ -4288,13 +4355,12 @@
     name = getlogin();
     if (name == NULL) {
         if (errno)
-        posix_error();
+            posix_error();
         else
-        PyErr_SetString(PyExc_OSError,
-                        "unable to determine login name");
+            PyErr_SetString(PyExc_OSError, "unable to determine login name");
     }
     else
-        result = PyUnicode_FromString(name);
+        result = PyUnicode_DecodeFSDefault(name);
     errno = old_errno;
 
     return result;
@@ -5642,14 +5708,18 @@
 static PyObject *
 posix_mkfifo(PyObject *self, PyObject *args)
 {
+    PyObject *opath;
     char *filename;
     int mode = 0666;
     int res;
-    if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode))
+    if (!PyArg_ParseTuple(args, "O&|i:mkfifo", PyUnicode_FSConverter, &opath,
+                          &mode))
         return NULL;
+    filename = PyBytes_AS_STRING(opath);
     Py_BEGIN_ALLOW_THREADS
     res = mkfifo(filename, mode);
     Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
     if (res < 0)
         return posix_error();
     Py_INCREF(Py_None);
@@ -5672,15 +5742,19 @@
 static PyObject *
 posix_mknod(PyObject *self, PyObject *args)
 {
+    PyObject *opath;
     char *filename;
     int mode = 0600;
     int device = 0;
     int res;
-    if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))
+    if (!PyArg_ParseTuple(args, "O&|ii:mknod", PyUnicode_FSConverter, &opath,
+                          &mode, &device))
         return NULL;
+    filename = PyBytes_AS_STRING(opath);
     Py_BEGIN_ALLOW_THREADS
     res = mknod(filename, mode, device);
     Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
     if (res < 0)
         return posix_error();
     Py_INCREF(Py_None);
@@ -7587,11 +7661,11 @@
     {"readlink",        posix_readlink, METH_VARARGS, posix_readlink__doc__},
 #endif /* HAVE_READLINK */
 #if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
-    {"readlink",	win_readlink, METH_VARARGS, win_readlink__doc__},
+    {"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__},
+    {"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__},
@@ -8095,6 +8169,14 @@
     if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
 #endif /* EX_NOTFOUND */
 
+	/* statvfs */
+#ifdef ST_RDONLY
+	if (ins(d, "ST_RDONLY", (long)ST_RDONLY)) return -1;
+#endif /* ST_RDONLY */
+#ifdef ST_NOSUID
+	if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1;
+#endif /* ST_NOSUID */
+
 #ifdef HAVE_SPAWNV
 #if defined(PYOS_OS2) && defined(PYCC_GCC)
     if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;

Modified: python/branches/pep-0384/Modules/pwdmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/pwdmodule.c	(original)
+++ python/branches/pep-0384/Modules/pwdmodule.c	Fri Aug 27 21:11:11 2010
@@ -100,7 +100,7 @@
 "getpwuid(uid) -> (pw_name,pw_passwd,pw_uid,\n\
                   pw_gid,pw_gecos,pw_dir,pw_shell)\n\
 Return the password database entry for the given numeric user ID.\n\
-See pwd.__doc__ for more on password database entries.");
+See help(pwd) for more on password database entries.");
 
 static PyObject *
 pwd_getpwuid(PyObject *self, PyObject *args)
@@ -121,7 +121,7 @@
 "getpwnam(name) -> (pw_name,pw_passwd,pw_uid,\n\
                     pw_gid,pw_gecos,pw_dir,pw_shell)\n\
 Return the password database entry for the given user name.\n\
-See pwd.__doc__ for more on password database entries.");
+See help(pwd) for more on password database entries.");
 
 static PyObject *
 pwd_getpwnam(PyObject *self, PyObject *args)
@@ -152,7 +152,7 @@
 "getpwall() -> list_of_entries\n\
 Return a list of all available password database entries, \
 in arbitrary order.\n\
-See pwd.__doc__ for more on password database entries.");
+See help(pwd) for more on password database entries.");
 
 static PyObject *
 pwd_getpwall(PyObject *self)

Modified: python/branches/pep-0384/Modules/pyexpat.c
==============================================================================
--- python/branches/pep-0384/Modules/pyexpat.c	(original)
+++ python/branches/pep-0384/Modules/pyexpat.c	Fri Aug 27 21:11:11 2010
@@ -855,18 +855,15 @@
 xmlparse_ParseFile(xmlparseobject *self, PyObject *f)
 {
     int rv = 1;
-    FILE *fp;
     PyObject *readmethod = NULL;
 
-    {
-        fp = NULL;
-        readmethod = PyObject_GetAttrString(f, "read");
-        if (readmethod == NULL) {
-            PyErr_Clear();
-            PyErr_SetString(PyExc_TypeError,
-                            "argument must have 'read' attribute");
-            return NULL;
-        }
+
+    readmethod = PyObject_GetAttrString(f, "read");
+    if (readmethod == NULL) {
+        PyErr_Clear();
+        PyErr_SetString(PyExc_TypeError,
+                        "argument must have 'read' attribute");
+        return NULL;
     }
     for (;;) {
         int bytes_read;
@@ -876,19 +873,10 @@
             return PyErr_NoMemory();
         }
 
-        if (fp) {
-            bytes_read = fread(buf, sizeof(char), BUF_SIZE, fp);
-            if (bytes_read < 0) {
-                PyErr_SetFromErrno(PyExc_IOError);
-                return NULL;
-            }
-        }
-        else {
-            bytes_read = readinst(buf, BUF_SIZE, readmethod);
-            if (bytes_read < 0) {
-                Py_DECREF(readmethod);
-                return NULL;
-            }
+        bytes_read = readinst(buf, BUF_SIZE, readmethod);
+        if (bytes_read < 0) {
+            Py_DECREF(readmethod);
+            return NULL;
         }
         rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0);
         if (PyErr_Occurred()) {

Modified: python/branches/pep-0384/Modules/readline.c
==============================================================================
--- python/branches/pep-0384/Modules/readline.c	(original)
+++ python/branches/pep-0384/Modules/readline.c	Fri Aug 27 21:11:11 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,
@@ -1044,30 +1080,23 @@
     /* we have a valid line */
     n = strlen(p);
     if (n > 0) {
-        char *line;
-        HISTORY_STATE *state = history_get_history_state();
-        if (state->length > 0)
+        const char *line;
+        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 = (const char *)history_get(length - 1)->line;
             } else
 #endif /* __APPLE__ */
-            line = history_get(state->length)->line;
+            line = (const char *)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/pep-0384/Modules/selectmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/selectmodule.c	(original)
+++ python/branches/pep-0384/Modules/selectmodule.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/sha1module.c
==============================================================================
--- python/branches/pep-0384/Modules/sha1module.c	(original)
+++ python/branches/pep-0384/Modules/sha1module.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/signalmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/signalmodule.c	(original)
+++ python/branches/pep-0384/Modules/signalmodule.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/socketmodule.c
==============================================================================
--- python/branches/pep-0384/Modules/socketmodule.c	(original)
+++ python/branches/pep-0384/Modules/socketmodule.c	Fri Aug 27 21:11:11 2010
@@ -678,9 +678,11 @@
 
         /* See if the socket is ready */
         if (writing)
-            n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
+            n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
+                       NULL, &fds, NULL, &tv);
         else
-            n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
+            n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
+                       &fds, NULL, NULL, &tv);
     }
 #endif
 
@@ -937,7 +939,7 @@
 
 /*ARGSUSED*/
 static PyObject *
-makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
+makesockaddr(SOCKET_T sockfd, struct sockaddr *addr, size_t addrlen, int proto)
 {
     if (addrlen == 0) {
         /* No address -- may be recvfrom() from known socket */
@@ -1869,6 +1871,21 @@
 \n\
 Close the socket.  It cannot be used after this call.");
 
+static PyObject *
+sock_detach(PySocketSockObject *s)
+{
+    SOCKET_T fd = s->sock_fd;
+    s->sock_fd = -1;
+    return PyLong_FromSocket_t(fd);
+}
+
+PyDoc_STRVAR(detach_doc,
+"detach()\n\
+\n\
+Close the socket object without closing the underlying file descriptor.\
+The object cannot be used after this call, but the file descriptor\
+can be reused for other purposes.  The file descriptor is returned.");
+
 static int
 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
                  int *timeoutp)
@@ -1893,7 +1910,8 @@
             FD_SET(s->sock_fd, &fds);
             FD_ZERO(&fds_exc);
             FD_SET(s->sock_fd, &fds_exc);
-            res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
+            res = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
+                         NULL, &fds, &fds_exc, &tv);
             if (res == 0) {
                 res = WSAEWOULDBLOCK;
                 timeout = 1;
@@ -2136,10 +2154,10 @@
  * also possible that we return a number of bytes smaller than the request
  * bytes.
  */
-static ssize_t
-sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
+static Py_ssize_t
+sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
 {
-    ssize_t outlen = -1;
+    Py_ssize_t outlen = -1;
     int timeout;
 #ifdef __VMS
     int remaining;
@@ -2221,11 +2239,11 @@
 static PyObject *
 sock_recv(PySocketSockObject *s, PyObject *args)
 {
-    int recvlen, flags = 0;
-    ssize_t outlen;
+    Py_ssize_t recvlen, outlen;
+    int flags = 0;
     PyObject *buf;
 
-    if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
+    if (!PyArg_ParseTuple(args, "n|i:recv", &recvlen, &flags))
         return NULL;
 
     if (recvlen < 0) {
@@ -2272,14 +2290,13 @@
 {
     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
 
-    int recvlen = 0, flags = 0;
-    ssize_t readlen;
+    int flags = 0;
     Py_buffer pbuf;
     char *buf;
-    int buflen;
+    Py_ssize_t buflen, readlen, recvlen = 0;
 
     /* Get the buffer's memory */
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recv_into", kwlist,
                                      &pbuf, &recvlen, &flags))
         return NULL;
     buf = pbuf.buf;
@@ -2339,13 +2356,13 @@
  * 'addr' is a return value for the address object.  Note that you must decref
  * it yourself.
  */
-static ssize_t
-sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
+static Py_ssize_t
+sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
                    PyObject** addr)
 {
     sock_addr_t addrbuf;
     int timeout;
-    ssize_t n = -1;
+    Py_ssize_t n = -1;
     socklen_t addrlen;
 
     *addr = NULL;
@@ -2401,10 +2418,10 @@
     PyObject *buf = NULL;
     PyObject *addr = NULL;
     PyObject *ret = NULL;
-    int recvlen, flags = 0;
-    ssize_t outlen;
+    int flags = 0;
+    Py_ssize_t recvlen, outlen;
 
-    if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
+    if (!PyArg_ParseTuple(args, "n|i:recvfrom", &recvlen, &flags))
         return NULL;
 
     if (recvlen < 0) {
@@ -2452,15 +2469,14 @@
 {
     static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
 
-    int recvlen = 0, flags = 0;
-    ssize_t readlen;
+    int flags = 0;
     Py_buffer pbuf;
     char *buf;
-    int buflen;
+    Py_ssize_t readlen, buflen, recvlen = 0;
 
     PyObject *addr = NULL;
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recvfrom_into",
                                      kwlist, &pbuf,
                                      &recvlen, &flags))
         return NULL;
@@ -2490,7 +2506,7 @@
     PyBuffer_Release(&pbuf);
     /* Return the number of bytes read and the address.  Note that we do
        not do anything special here in the case that readlen < recvlen. */
-    return Py_BuildValue("lN", readlen, addr);
+    return Py_BuildValue("nN", readlen, addr);
 }
 
 PyDoc_STRVAR(recvfrom_into_doc,
@@ -2505,7 +2521,8 @@
 sock_send(PySocketSockObject *s, PyObject *args)
 {
     char *buf;
-    int len, n = -1, flags = 0, timeout;
+    Py_ssize_t len, n = -1;
+    int flags = 0, timeout;
     Py_buffer pbuf;
 
     if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
@@ -2536,7 +2553,7 @@
     }
     if (n < 0)
         return s->errorhandler();
-    return PyLong_FromLong((long)n);
+    return PyLong_FromSsize_t(n);
 }
 
 PyDoc_STRVAR(send_doc,
@@ -2553,7 +2570,8 @@
 sock_sendall(PySocketSockObject *s, PyObject *args)
 {
     char *buf;
-    int len, n = -1, flags = 0, timeout;
+    Py_ssize_t len, n = -1;
+    int flags = 0, timeout;
     Py_buffer pbuf;
 
     if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
@@ -2663,7 +2681,7 @@
     }
     if (n < 0)
         return s->errorhandler();
-    return PyLong_FromLong((long)n);
+    return PyLong_FromSsize_t(n);
 }
 
 PyDoc_STRVAR(sendto_doc,
@@ -2757,6 +2775,8 @@
                       connect_doc},
     {"connect_ex",        (PyCFunction)sock_connect_ex, METH_O,
                       connect_ex_doc},
+    {"detach",            (PyCFunction)sock_detach, METH_NOARGS,
+                      detach_doc},
     {"fileno",            (PyCFunction)sock_fileno, METH_NOARGS,
                       fileno_doc},
 #ifdef HAVE_GETPEERNAME
@@ -2980,12 +3000,16 @@
 {
     char *name;
     sock_addr_t addrbuf;
+    PyObject *ret = NULL;
 
-    if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
+    if (!PyArg_ParseTuple(args, "et:gethostbyname", "idna", &name))
         return NULL;
     if (setipaddr(name, SAS2SA(&addrbuf),  sizeof(addrbuf), AF_INET) < 0)
-        return NULL;
-    return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
+        goto finally;
+    ret = makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
+finally:
+    PyMem_Free(name);
+    return ret;
 }
 
 PyDoc_STRVAR(gethostbyname_doc,
@@ -3136,7 +3160,7 @@
     struct sockaddr_in addr;
 #endif
     struct sockaddr *sa;
-    PyObject *ret;
+    PyObject *ret = NULL;
 #ifdef HAVE_GETHOSTBYNAME_R
     struct hostent hp_allocated;
 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
@@ -3151,10 +3175,10 @@
 #endif
 #endif /* HAVE_GETHOSTBYNAME_R */
 
-    if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
+    if (!PyArg_ParseTuple(args, "et:gethostbyname_ex", "idna", &name))
         return NULL;
     if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
-        return NULL;
+        goto finally;
     Py_BEGIN_ALLOW_THREADS
 #ifdef HAVE_GETHOSTBYNAME_R
 #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
@@ -3184,6 +3208,8 @@
 #ifdef USE_GETHOSTBYNAME_LOCK
     PyThread_release_lock(netdb_lock);
 #endif
+finally:
+    PyMem_Free(name);
     return ret;
 }
 
@@ -3208,7 +3234,7 @@
     struct sockaddr *sa = (struct sockaddr *)&addr;
     char *ip_num;
     struct hostent *h;
-    PyObject *ret;
+    PyObject *ret = NULL;
 #ifdef HAVE_GETHOSTBYNAME_R
     struct hostent hp_allocated;
 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
@@ -3230,11 +3256,11 @@
     int al;
     int af;
 
-    if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
+    if (!PyArg_ParseTuple(args, "et:gethostbyaddr", "idna", &ip_num))
         return NULL;
     af = AF_UNSPEC;
     if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
-        return NULL;
+        goto finally;
     af = sa->sa_family;
     ap = NULL;
     al = 0;
@@ -3251,7 +3277,7 @@
 #endif
     default:
         PyErr_SetString(socket_error, "unsupported address family");
-        return NULL;
+        goto finally;
     }
     Py_BEGIN_ALLOW_THREADS
 #ifdef HAVE_GETHOSTBYNAME_R
@@ -3278,6 +3304,8 @@
 #ifdef USE_GETHOSTBYNAME_LOCK
     PyThread_release_lock(netdb_lock);
 #endif
+finally:
+    PyMem_Free(ip_num);
     return ret;
 }
 
@@ -3805,8 +3833,10 @@
 
 /*ARGSUSED*/
 static PyObject *
-socket_getaddrinfo(PyObject *self, PyObject *args)
+socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
 {
+    static char* kwnames[] = {"host", "port", "family", "type", "proto", 
+                              "flags", 0};
     struct addrinfo hints, *res;
     struct addrinfo *res0 = NULL;
     PyObject *hobj = NULL;
@@ -3820,8 +3850,8 @@
 
     family = socktype = protocol = flags = 0;
     family = AF_UNSPEC;
-    if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
-                          &hobj, &pobj, &family, &socktype,
+    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo", 
+                          kwnames, &hobj, &pobj, &family, &socktype,
                           &protocol, &flags)) {
         return NULL;
     }
@@ -3939,6 +3969,7 @@
     memset(&hints, 0, sizeof(hints));
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_DGRAM;     /* make numeric port happy */
+    hints.ai_flags = AI_NUMERICHOST;    /* don't do any name resolution */
     Py_BEGIN_ALLOW_THREADS
     ACQUIRE_GETADDRINFO_LOCK
     error = getaddrinfo(hostp, pbuf, &hints, &res);
@@ -3974,7 +4005,7 @@
         }
 #endif
     }
-    error = getnameinfo(res->ai_addr, res->ai_addrlen,
+    error = getnameinfo(res->ai_addr, (socklen_t) res->ai_addrlen,
                     hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
     if (error) {
         set_gaierror(error);
@@ -4088,8 +4119,8 @@
     {"inet_ntop",               socket_inet_ntop,
      METH_VARARGS, inet_ntop_doc},
 #endif
-    {"getaddrinfo",             socket_getaddrinfo,
-     METH_VARARGS, getaddrinfo_doc},
+    {"getaddrinfo",             (PyCFunction)socket_getaddrinfo,
+     METH_VARARGS | METH_KEYWORDS, getaddrinfo_doc},
     {"getnameinfo",             socket_getnameinfo,
      METH_VARARGS, getnameinfo_doc},
     {"getdefaulttimeout",       (PyCFunction)socket_getdefaulttimeout,

Modified: python/branches/pep-0384/Modules/timemodule.c
==============================================================================
--- python/branches/pep-0384/Modules/timemodule.c	(original)
+++ python/branches/pep-0384/Modules/timemodule.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zipimport.c
==============================================================================
--- python/branches/pep-0384/Modules/zipimport.c	(original)
+++ python/branches/pep-0384/Modules/zipimport.c	Fri Aug 27 21:11:11 2010
@@ -44,8 +44,8 @@
 static PyObject *zip_directory_cache = NULL;
 
 /* forward decls */
-static PyObject *read_directory(char *archive);
-static PyObject *get_data(char *archive, PyObject *toc_entry);
+static PyObject *read_directory(PyObject *archive);
+static PyObject *get_data(PyObject *archive, PyObject *toc_entry);
 static PyObject *get_module_code(ZipImporter *self, char *fullname,
                                  int *p_ispackage, char **p_modpath);
 
@@ -60,26 +60,29 @@
 static int
 zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)
 {
-    char *path, *p, *prefix, buf[MAXPATHLEN+2];
-    size_t len;
+    PyObject *pathobj, *files;
+    Py_UNICODE *path, *p, *prefix, buf[MAXPATHLEN+2];
+    Py_ssize_t len;
 
     if (!_PyArg_NoKeywords("zipimporter()", kwds))
         return -1;
 
-    if (!PyArg_ParseTuple(args, "s:zipimporter", &path))
+    if (!PyArg_ParseTuple(args, "O&:zipimporter",
+        PyUnicode_FSDecoder, &pathobj))
         return -1;
 
-    len = strlen(path);
+    /* copy path to buf */
+    len = PyUnicode_GET_SIZE(pathobj);
     if (len == 0) {
         PyErr_SetString(ZipImportError, "archive path is empty");
-        return -1;
+        goto error;
     }
     if (len >= MAXPATHLEN) {
         PyErr_SetString(ZipImportError,
                         "archive path too long");
-        return -1;
+        goto error;
     }
-    strcpy(buf, path);
+    Py_UNICODE_strcpy(buf, PyUnicode_AS_UNICODE(pathobj));
 
 #ifdef ALTSEP
     for (p = buf; *p; p++) {
@@ -94,7 +97,12 @@
         struct stat statbuf;
         int rv;
 
-        rv = stat(buf, &statbuf);
+        if (pathobj == NULL) {
+            pathobj = PyUnicode_FromUnicode(buf, len);
+            if (pathobj == NULL)
+                goto error;
+        }
+        rv = _Py_stat(pathobj, &statbuf);
         if (rv == 0) {
             /* it exists */
             if (S_ISREG(statbuf.st_mode))
@@ -102,56 +110,60 @@
                 path = buf;
             break;
         }
+        else if (PyErr_Occurred())
+            goto error;
         /* back up one path element */
-        p = strrchr(buf, SEP);
+        p = Py_UNICODE_strrchr(buf, SEP);
         if (prefix != NULL)
             *prefix = SEP;
         if (p == NULL)
             break;
         *p = '\0';
+        len = p - buf;
         prefix = p;
+        Py_CLEAR(pathobj);
     }
-    if (path != NULL) {
-        PyObject *files;
-        files = PyDict_GetItemString(zip_directory_cache, path);
-        if (files == NULL) {
-            files = read_directory(buf);
-            if (files == NULL)
-                return -1;
-            if (PyDict_SetItemString(zip_directory_cache, path,
-                                     files) != 0)
-                return -1;
-        }
-        else
-            Py_INCREF(files);
-        self->files = files;
-    }
-    else {
+    if (path == NULL) {
         PyErr_SetString(ZipImportError, "not a Zip file");
-        return -1;
+        goto error;
     }
 
-    if (prefix == NULL)
-        prefix = "";
-    else {
+    files = PyDict_GetItem(zip_directory_cache, pathobj);
+    if (files == NULL) {
+        files = read_directory(pathobj);
+        if (files == NULL)
+            goto error;
+        if (PyDict_SetItem(zip_directory_cache, pathobj, files) != 0)
+            goto error;
+    }
+    else
+        Py_INCREF(files);
+    self->files = files;
+
+    self->archive = pathobj;
+    pathobj = NULL;
+
+    if (prefix != NULL) {
         prefix++;
-        len = strlen(prefix);
+        len = Py_UNICODE_strlen(prefix);
         if (prefix[len-1] != SEP) {
             /* add trailing SEP */
             prefix[len] = SEP;
             prefix[len + 1] = '\0';
+            len++;
         }
     }
-
-    self->archive = PyUnicode_FromString(buf);
-    if (self->archive == NULL)
-        return -1;
-
-    self->prefix = PyUnicode_FromString(prefix);
+    else
+        len = 0;
+    self->prefix = PyUnicode_FromUnicode(prefix, len);
     if (self->prefix == NULL)
-        return -1;
+        goto error;
 
     return 0;
+
+error:
+    Py_XDECREF(pathobj);
+    return -1;
 }
 
 /* GC support. */
@@ -176,19 +188,14 @@
 static PyObject *
 zipimporter_repr(ZipImporter *self)
 {
-    char *archive = "???";
-    char *prefix = "";
-
-    if (self->archive != NULL && PyUnicode_Check(self->archive))
-        archive = _PyUnicode_AsString(self->archive);
-    if (self->prefix != NULL && PyUnicode_Check(self->prefix))
-        prefix = _PyUnicode_AsString(self->prefix);
-    if (prefix != NULL && *prefix)
-        return PyUnicode_FromFormat("<zipimporter object \"%.300s%c%.150s\">",
-                                    archive, SEP, prefix);
+    if (self->archive == NULL)
+        return PyUnicode_FromString("<zipimporter object \"???\">");
+    else if (self->prefix != NULL && PyUnicode_GET_SIZE(self->prefix) != 0)
+        return PyUnicode_FromFormat("<zipimporter object \"%.300U%c%.150U\">",
+                                    self->archive, SEP, self->prefix);
     else
-        return PyUnicode_FromFormat("<zipimporter object \"%.300s\">",
-                                    archive);
+        return PyUnicode_FromFormat("<zipimporter object \"%.300U\">",
+                                    self->archive);
 }
 
 /* return fullname.split(".")[-1] */
@@ -401,42 +408,52 @@
 zipimporter_get_data(PyObject *obj, PyObject *args)
 {
     ZipImporter *self = (ZipImporter *)obj;
-    char *path;
+    PyObject *pathobj, *key;
+    const Py_UNICODE *path;
 #ifdef ALTSEP
-    char *p, buf[MAXPATHLEN + 1];
+    Py_UNICODE *p, buf[MAXPATHLEN + 1];
 #endif
+    Py_UNICODE *archive;
     PyObject *toc_entry;
-    Py_ssize_t len;
-    char *archive_str;
+    Py_ssize_t path_len, len;
 
-    if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path))
+    if (!PyArg_ParseTuple(args, "U:zipimporter.get_data", &pathobj))
         return NULL;
 
+    path_len = PyUnicode_GET_SIZE(pathobj);
+    path = PyUnicode_AS_UNICODE(pathobj);
 #ifdef ALTSEP
-    if (strlen(path) >= MAXPATHLEN) {
+    if (path_len >= MAXPATHLEN) {
         PyErr_SetString(ZipImportError, "path too long");
         return NULL;
     }
-    strcpy(buf, path);
+    Py_UNICODE_strcpy(buf, path);
     for (p = buf; *p; p++) {
         if (*p == ALTSEP)
             *p = SEP;
     }
     path = buf;
 #endif
-    archive_str = _PyUnicode_AsStringAndSize(self->archive, &len);
-    if ((size_t)len < strlen(path) &&
-        strncmp(path, archive_str, len) == 0 &&
+    archive = PyUnicode_AS_UNICODE(self->archive);
+    len = PyUnicode_GET_SIZE(self->archive);
+    if ((size_t)len < Py_UNICODE_strlen(path) &&
+        Py_UNICODE_strncmp(path, archive, len) == 0 &&
         path[len] == SEP) {
-        path = path + len + 1;
+        path += len + 1;
+        path_len -= len + 1;
     }
 
-    toc_entry = PyDict_GetItemString(self->files, path);
+    key = PyUnicode_FromUnicode(path, path_len);
+    if (key == NULL)
+        return NULL;
+    toc_entry = PyDict_GetItem(self->files, key);
     if (toc_entry == NULL) {
-        PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
+        PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, key);
+        Py_DECREF(key);
         return NULL;
     }
-    return get_data(archive_str, toc_entry);
+    Py_DECREF(key);
+    return get_data(self->archive, toc_entry);
 }
 
 static PyObject *
@@ -486,9 +503,13 @@
 
     toc_entry = PyDict_GetItemString(self->files, path);
     if (toc_entry != NULL) {
-        PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry);
-        PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes));
-        Py_XDECREF(bytes);
+        PyObject *res, *bytes;
+        bytes = get_data(self->archive, toc_entry);
+        if (bytes == NULL)
+            return NULL;
+        res = PyUnicode_FromStringAndSize(PyBytes_AS_STRING(bytes),
+                                          PyBytes_GET_SIZE(bytes));
+        Py_DECREF(bytes);
         return res;
     }
 
@@ -670,30 +691,33 @@
    data_size and file_offset are 0.
 */
 static PyObject *
-read_directory(char *archive)
+read_directory(PyObject *archive_obj)
 {
+    /* FIXME: work on Py_UNICODE* instead of char* */
     PyObject *files = NULL;
     FILE *fp;
     long compress, crc, data_size, file_size, file_offset, date, time;
     long header_offset, name_size, header_size, header_position;
     long i, l, count;
     size_t length;
-    char path[MAXPATHLEN + 5];
+    Py_UNICODE path[MAXPATHLEN + 5];
     char name[MAXPATHLEN + 5];
+    PyObject *nameobj = NULL;
     char *p, endof_central_dir[22];
     long arc_offset; /* offset from beginning of file to start of zip-archive */
+    PyObject *pathobj;
 
-    if (strlen(archive) > MAXPATHLEN) {
+    if (PyUnicode_GET_SIZE(archive_obj) > MAXPATHLEN) {
         PyErr_SetString(PyExc_OverflowError,
                         "Zip path name is too long");
         return NULL;
     }
-    strcpy(path, archive);
+    Py_UNICODE_strcpy(path, PyUnicode_AS_UNICODE(archive_obj));
 
-    fp = fopen(archive, "rb");
+    fp = _Py_fopen(archive_obj, "rb");
     if (fp == NULL) {
         PyErr_Format(ZipImportError, "can't open Zip file: "
-                     "'%.200s'", archive);
+                     "'%.200U'", archive_obj);
         return NULL;
     }
     fseek(fp, -22, SEEK_END);
@@ -701,14 +725,14 @@
     if (fread(endof_central_dir, 1, 22, fp) != 22) {
         fclose(fp);
         PyErr_Format(ZipImportError, "can't read Zip file: "
-                     "'%.200s'", archive);
+                     "'%.200U'", archive_obj);
         return NULL;
     }
     if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
         /* Bad: End of Central Dir signature */
         fclose(fp);
         PyErr_Format(ZipImportError, "not a Zip file: "
-                     "'%.200s'", archive);
+                     "'%.200U'", archive_obj);
         return NULL;
     }
 
@@ -721,7 +745,7 @@
     if (files == NULL)
         goto error;
 
-    length = (long)strlen(path);
+    length = Py_UNICODE_strlen(path);
     path[length] = SEP;
 
     /* Start of Central Directory */
@@ -760,13 +784,20 @@
         *p = 0;         /* Add terminating null byte */
         header_offset += header_size;
 
-        strncpy(path + length + 1, name, MAXPATHLEN - length - 1);
+        nameobj = PyUnicode_DecodeFSDefaultAndSize(name, name_size);
+        if (nameobj == NULL)
+            goto error;
+        Py_UNICODE_strncpy(path + length + 1, PyUnicode_AS_UNICODE(nameobj), MAXPATHLEN - length - 1);
 
-        t = Py_BuildValue("siiiiiii", path, compress, data_size,
+        pathobj = PyUnicode_FromUnicode(path, Py_UNICODE_strlen(path));
+        if (pathobj == NULL)
+            goto error;
+        t = Py_BuildValue("Niiiiiii", pathobj, compress, data_size,
                           file_size, file_offset, time, date, crc);
         if (t == NULL)
             goto error;
-        err = PyDict_SetItemString(files, name, t);
+        err = PyDict_SetItem(files, nameobj, t);
+        Py_CLEAR(nameobj);
         Py_DECREF(t);
         if (err != 0)
             goto error;
@@ -774,12 +805,13 @@
     }
     fclose(fp);
     if (Py_VerboseFlag)
-        PySys_WriteStderr("# zipimport: found %ld names in %s\n",
-            count, archive);
+        PySys_FormatStderr("# zipimport: found %ld names in %U\n",
+            count, archive_obj);
     return files;
 error:
     fclose(fp);
     Py_XDECREF(files);
+    Py_XDECREF(nameobj);
     return NULL;
 }
 
@@ -820,7 +852,7 @@
 /* Given a path to a Zip file and a toc_entry, return the (uncompressed)
    data as a new reference. */
 static PyObject *
-get_data(char *archive, PyObject *toc_entry)
+get_data(PyObject *archive, PyObject *toc_entry)
 {
     PyObject *raw_data, *data = NULL, *decompress;
     char *buf;
@@ -828,20 +860,20 @@
     int err;
     Py_ssize_t bytes_read = 0;
     long l;
-    char *datapath;
+    PyObject *datapath;
     long compress, data_size, file_size, file_offset, bytes_size;
     long time, date, crc;
 
-    if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,
+    if (!PyArg_ParseTuple(toc_entry, "Olllllll", &datapath, &compress,
                           &data_size, &file_size, &file_offset, &time,
                           &date, &crc)) {
         return NULL;
     }
 
-    fp = fopen(archive, "rb");
+    fp = _Py_fopen(archive, "rb");
     if (!fp) {
         PyErr_Format(PyExc_IOError,
-           "zipimport: can not open file %s", archive);
+           "zipimport: can not open file %U", archive);
         return NULL;
     }
 
@@ -851,7 +883,7 @@
     if (l != 0x04034B50) {
         /* Bad: Local File Header */
         PyErr_Format(ZipImportError,
-                     "bad local file header in %s",
+                     "bad local file header in %U",
                      archive);
         fclose(fp);
         return NULL;
@@ -1081,12 +1113,8 @@
 {
     PyObject *data, *code;
     char *modpath;
-    char *archive = _PyUnicode_AsString(self->archive);
-
-    if (archive == NULL)
-        return NULL;
 
-    data = get_data(archive, toc_entry);
+    data = get_data(self->archive, toc_entry);
     if (data == NULL)
         return NULL;
 

Modified: python/branches/pep-0384/Modules/zlib/ChangeLog
==============================================================================
--- python/branches/pep-0384/Modules/zlib/ChangeLog	(original)
+++ python/branches/pep-0384/Modules/zlib/ChangeLog	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/FAQ
==============================================================================
--- python/branches/pep-0384/Modules/zlib/FAQ	(original)
+++ python/branches/pep-0384/Modules/zlib/FAQ	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/INDEX
==============================================================================
--- python/branches/pep-0384/Modules/zlib/INDEX	(original)
+++ python/branches/pep-0384/Modules/zlib/INDEX	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/Makefile
==============================================================================
--- python/branches/pep-0384/Modules/zlib/Makefile	(original)
+++ python/branches/pep-0384/Modules/zlib/Makefile	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/Makefile.in
==============================================================================
--- python/branches/pep-0384/Modules/zlib/Makefile.in	(original)
+++ python/branches/pep-0384/Modules/zlib/Makefile.in	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/README
==============================================================================
--- python/branches/pep-0384/Modules/zlib/README	(original)
+++ python/branches/pep-0384/Modules/zlib/README	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/adler32.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/adler32.c	(original)
+++ python/branches/pep-0384/Modules/zlib/adler32.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/compress.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/compress.c	(original)
+++ python/branches/pep-0384/Modules/zlib/compress.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/configure
==============================================================================
--- python/branches/pep-0384/Modules/zlib/configure	(original)
+++ python/branches/pep-0384/Modules/zlib/configure	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/crc32.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/crc32.c	(original)
+++ python/branches/pep-0384/Modules/zlib/crc32.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/deflate.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/deflate.c	(original)
+++ python/branches/pep-0384/Modules/zlib/deflate.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/deflate.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/deflate.h	(original)
+++ python/branches/pep-0384/Modules/zlib/deflate.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/example.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/example.c	(original)
+++ python/branches/pep-0384/Modules/zlib/example.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/infback.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/infback.c	(original)
+++ python/branches/pep-0384/Modules/zlib/infback.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/inffast.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/inffast.c	(original)
+++ python/branches/pep-0384/Modules/zlib/inffast.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/inffast.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/inffast.h	(original)
+++ python/branches/pep-0384/Modules/zlib/inffast.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/inflate.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/inflate.c	(original)
+++ python/branches/pep-0384/Modules/zlib/inflate.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/inflate.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/inflate.h	(original)
+++ python/branches/pep-0384/Modules/zlib/inflate.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/inftrees.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/inftrees.c	(original)
+++ python/branches/pep-0384/Modules/zlib/inftrees.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/inftrees.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/inftrees.h	(original)
+++ python/branches/pep-0384/Modules/zlib/inftrees.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/make_vms.com
==============================================================================
--- python/branches/pep-0384/Modules/zlib/make_vms.com	(original)
+++ python/branches/pep-0384/Modules/zlib/make_vms.com	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/minigzip.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/minigzip.c	(original)
+++ python/branches/pep-0384/Modules/zlib/minigzip.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/trees.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/trees.c	(original)
+++ python/branches/pep-0384/Modules/zlib/trees.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/trees.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/trees.h	(original)
+++ python/branches/pep-0384/Modules/zlib/trees.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/uncompr.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/uncompr.c	(original)
+++ python/branches/pep-0384/Modules/zlib/uncompr.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/zconf.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/zconf.h	(original)
+++ python/branches/pep-0384/Modules/zlib/zconf.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/zlib.3
==============================================================================
--- python/branches/pep-0384/Modules/zlib/zlib.3	(original)
+++ python/branches/pep-0384/Modules/zlib/zlib.3	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/zlib.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/zlib.h	(original)
+++ python/branches/pep-0384/Modules/zlib/zlib.h	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/zutil.c
==============================================================================
--- python/branches/pep-0384/Modules/zlib/zutil.c	(original)
+++ python/branches/pep-0384/Modules/zlib/zutil.c	Fri Aug 27 21:11:11 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/pep-0384/Modules/zlib/zutil.h
==============================================================================
--- python/branches/pep-0384/Modules/zlib/zutil.h	(original)
+++ python/branches/pep-0384/Modules/zlib/zutil.h	Fri Aug 27 21:11:11 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/pep-0384/Objects/abstract.c
==============================================================================
--- python/branches/pep-0384/Objects/abstract.c	(original)
+++ python/branches/pep-0384/Objects/abstract.c	Fri Aug 27 21:11:11 2010
@@ -2311,15 +2311,7 @@
     va_list countva;
     PyObject *result, *tmp;
 
-#ifdef VA_LIST_IS_ARRAY
-    memcpy(countva, va, sizeof(va_list));
-#else
-#ifdef __va_copy
-    __va_copy(countva, va);
-#else
-    countva = va;
-#endif
-#endif
+        Py_VA_COPY(countva, va);
 
     while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
         ++n;

Modified: python/branches/pep-0384/Objects/bytearrayobject.c
==============================================================================
--- python/branches/pep-0384/Objects/bytearrayobject.c	(original)
+++ python/branches/pep-0384/Objects/bytearrayobject.c	Fri Aug 27 21:11:11 2010
@@ -310,9 +310,9 @@
     if (count < 0)
         count = 0;
     mysize = Py_SIZE(self);
-    size = mysize * count;
-    if (count != 0 && size / count != mysize)
+    if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
         return PyErr_NoMemory();
+    size = mysize * count;
     result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
     if (result != NULL && size != 0) {
         if (mysize == 1)
@@ -335,9 +335,9 @@
     if (count < 0)
         count = 0;
     mysize = Py_SIZE(self);
-    size = mysize * count;
-    if (count != 0 && size / count != mysize)
+    if (count > 0 && mysize > PY_SSIZE_T_MAX / count)
         return PyErr_NoMemory();
+    size = mysize * count;
     if (size < self->ob_alloc) {
         Py_SIZE(self) = size;
         self->ob_bytes[Py_SIZE(self)] = '\0'; /* Trailing null byte */
@@ -649,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;
@@ -665,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,
@@ -679,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,
@@ -930,12 +936,12 @@
 static PyObject *
 bytearray_str(PyObject *op)
 {
-	if (Py_BytesWarningFlag) {
-		if (PyErr_WarnEx(PyExc_BytesWarning,
-				 "str() on a bytearray instance", 1))
-			return NULL;
-	}
-	return bytearray_repr((PyByteArrayObject*)op);
+        if (Py_BytesWarningFlag) {
+                if (PyErr_WarnEx(PyExc_BytesWarning,
+                                 "str() on a bytearray instance", 1))
+                        return NULL;
+        }
+        return bytearray_repr((PyByteArrayObject*)op);
 }
 
 static PyObject *
@@ -1208,7 +1214,7 @@
     Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
     if (ival == -1 && PyErr_Occurred()) {
         Py_buffer varg;
-        int pos;
+        Py_ssize_t pos;
         PyErr_Clear();
         if (_getbuffer(arg, &varg) < 0)
             return -1;
@@ -1222,7 +1228,7 @@
         return -1;
     }
 
-    return memchr(PyByteArray_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
+    return memchr(PyByteArray_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
 }
 
 
@@ -1452,7 +1458,7 @@
 static PyObject *
 bytearray_maketrans(PyObject *null, PyObject *args)
 {
-	return _Py_bytes_maketrans(args);
+        return _Py_bytes_maketrans(args);
 }
 
 
@@ -1499,30 +1505,28 @@
 {
     char *self_s, *result_s;
     Py_ssize_t self_len, result_len;
-    Py_ssize_t count, i, product;
+    Py_ssize_t count, i;
     PyByteArrayObject *result;
 
     self_len = PyByteArray_GET_SIZE(self);
 
-    /* 1 at the end plus 1 after every character */
-    count = self_len+1;
-    if (maxcount < count)
+    /* 1 at the end plus 1 after every character;
+       count = min(maxcount, self_len + 1) */
+    if (maxcount <= self_len)
         count = maxcount;
+    else
+        /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
+        count = self_len + 1;
 
     /* Check for overflow */
     /*   result_len = count * to_len + self_len; */
-    product = count * to_len;
-    if (product / to_len != count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replace string is too long");
-        return NULL;
-    }
-    result_len = product + self_len;
-    if (result_len < 0) {
+    assert(count > 0);
+    if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
         PyErr_SetString(PyExc_OverflowError,
                         "replace string is too long");
         return NULL;
     }
+    result_len = count * to_len + self_len;
 
     if (! (result = (PyByteArrayObject *)
                      PyByteArray_FromStringAndSize(NULL, result_len)) )
@@ -1752,7 +1756,7 @@
     char *self_s, *result_s;
     char *start, *next, *end;
     Py_ssize_t self_len, result_len;
-    Py_ssize_t count, product;
+    Py_ssize_t count;
     PyByteArrayObject *result;
 
     self_s = PyByteArray_AS_STRING(self);
@@ -1766,16 +1770,12 @@
 
     /* use the difference between current and new, hence the "-1" */
     /*   result_len = self_len + count * (to_len-1)  */
-    product = count * (to_len-1);
-    if (product / (to_len-1) != count) {
+    assert(count > 0);
+    if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
         PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
         return NULL;
     }
-    result_len = self_len + product;
-    if (result_len < 0) {
-            PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
-            return NULL;
-    }
+    result_len = self_len + count * (to_len - 1);
 
     if ( (result = (PyByteArrayObject *)
           PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)
@@ -1819,7 +1819,7 @@
     char *self_s, *result_s;
     char *start, *next, *end;
     Py_ssize_t self_len, result_len;
-    Py_ssize_t count, offset, product;
+    Py_ssize_t count, offset;
     PyByteArrayObject *result;
 
     self_s = PyByteArray_AS_STRING(self);
@@ -1836,16 +1836,12 @@
 
     /* Check for overflow */
     /*    result_len = self_len + count * (to_len-from_len) */
-    product = count * (to_len-from_len);
-    if (product / (to_len-from_len) != count) {
-        PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
-        return NULL;
-    }
-    result_len = self_len + product;
-    if (result_len < 0) {
+    assert(count > 0);
+    if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
         PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
         return NULL;
     }
+    result_len = self_len + count * (to_len - from_len);
 
     if ( (result = (PyByteArrayObject *)
           PyByteArray_FromStringAndSize(NULL, result_len)) == NULL)

Modified: python/branches/pep-0384/Objects/bytes_methods.c
==============================================================================
--- python/branches/pep-0384/Objects/bytes_methods.c	(original)
+++ python/branches/pep-0384/Objects/bytes_methods.c	Fri Aug 27 21:11:11 2010
@@ -246,23 +246,15 @@
 void
 _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len)
 {
-        Py_ssize_t i;
+    Py_ssize_t i;
 
-        /*
-        newobj = PyBytes_FromStringAndSize(NULL, len);
-        if (!newobj)
-                return NULL;
-
-        s = PyBytes_AS_STRING(newobj);
-        */
-
-        Py_MEMCPY(result, cptr, len);
-
-        for (i = 0; i < len; i++) {
-                int c = Py_CHARMASK(result[i]);
-                if (Py_ISUPPER(c))
-                        result[i] = Py_TOLOWER(c);
-        }
+    Py_MEMCPY(result, cptr, len);
+
+    for (i = 0; i < len; i++) {
+        int c = Py_CHARMASK(result[i]);
+        if (Py_ISUPPER(c))
+            result[i] = Py_TOLOWER(c);
+    }
 }
 
 
@@ -274,23 +266,15 @@
 void
 _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len)
 {
-        Py_ssize_t i;
+    Py_ssize_t i;
 
-        /*
-        newobj = PyBytes_FromStringAndSize(NULL, len);
-        if (!newobj)
-                return NULL;
-
-        s = PyBytes_AS_STRING(newobj);
-        */
-
-        Py_MEMCPY(result, cptr, len);
-
-        for (i = 0; i < len; i++) {
-                int c = Py_CHARMASK(result[i]);
-                if (Py_ISLOWER(c))
-                        result[i] = Py_TOUPPER(c);
-        }
+    Py_MEMCPY(result, cptr, len);
+
+    for (i = 0; i < len; i++) {
+        int c = Py_CHARMASK(result[i]);
+        if (Py_ISLOWER(c))
+            result[i] = Py_TOUPPER(c);
+    }
 }
 
 
@@ -303,29 +287,23 @@
 void
 _Py_bytes_title(char *result, char *s, Py_ssize_t len)
 {
-        Py_ssize_t i;
-        int previous_is_cased = 0;
+    Py_ssize_t i;
+    int previous_is_cased = 0;
 
-        /*
-        newobj = PyBytes_FromStringAndSize(NULL, len);
-        if (newobj == NULL)
-                return NULL;
-        s_new = PyBytes_AsString(newobj);
-        */
-        for (i = 0; i < len; i++) {
-                int c = Py_CHARMASK(*s++);
-                if (Py_ISLOWER(c)) {
-                        if (!previous_is_cased)
-                            c = Py_TOUPPER(c);
-                        previous_is_cased = 1;
-                } else if (Py_ISUPPER(c)) {
-                        if (previous_is_cased)
-                            c = Py_TOLOWER(c);
-                        previous_is_cased = 1;
-                } else
-                        previous_is_cased = 0;
-                *result++ = c;
-        }
+    for (i = 0; i < len; i++) {
+        int c = Py_CHARMASK(*s++);
+        if (Py_ISLOWER(c)) {
+            if (!previous_is_cased)
+                c = Py_TOUPPER(c);
+            previous_is_cased = 1;
+        } else if (Py_ISUPPER(c)) {
+            if (previous_is_cased)
+                c = Py_TOLOWER(c);
+            previous_is_cased = 1;
+        } else
+            previous_is_cased = 0;
+        *result++ = c;
+    }
 }
 
 
@@ -338,30 +316,24 @@
 void
 _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len)
 {
-        Py_ssize_t i;
+    Py_ssize_t i;
 
-        /*
-        newobj = PyBytes_FromStringAndSize(NULL, len);
-        if (newobj == NULL)
-                return NULL;
-        s_new = PyBytes_AsString(newobj);
-        */
-        if (0 < len) {
-                int c = Py_CHARMASK(*s++);
-                if (Py_ISLOWER(c))
-                        *result = Py_TOUPPER(c);
-                else
-                        *result = c;
-                result++;
-        }
-        for (i = 1; i < len; i++) {
-                int c = Py_CHARMASK(*s++);
-                if (Py_ISUPPER(c))
-                        *result = Py_TOLOWER(c);
-                else
-                        *result = c;
-                result++;
-        }
+    if (0 < len) {
+        int c = Py_CHARMASK(*s++);
+        if (Py_ISLOWER(c))
+            *result = Py_TOUPPER(c);
+        else
+            *result = c;
+        result++;
+    }
+    for (i = 1; i < len; i++) {
+        int c = Py_CHARMASK(*s++);
+        if (Py_ISUPPER(c))
+            *result = Py_TOLOWER(c);
+        else
+            *result = c;
+        result++;
+    }
 }
 
 
@@ -374,26 +346,20 @@
 void
 _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len)
 {
-        Py_ssize_t i;
+    Py_ssize_t i;
 
-        /*
-        newobj = PyBytes_FromStringAndSize(NULL, len);
-        if (newobj == NULL)
-                return NULL;
-        s_new = PyBytes_AsString(newobj);
-        */
-        for (i = 0; i < len; i++) {
-                int c = Py_CHARMASK(*s++);
-                if (Py_ISLOWER(c)) {
-                        *result = Py_TOUPPER(c);
-                }
-                else if (Py_ISUPPER(c)) {
-                        *result = Py_TOLOWER(c);
-                }
-                else
-                        *result = c;
-                result++;
-        }
+    for (i = 0; i < len; i++) {
+        int c = Py_CHARMASK(*s++);
+        if (Py_ISLOWER(c)) {
+            *result = Py_TOUPPER(c);
+        }
+        else if (Py_ISUPPER(c)) {
+            *result = Py_TOLOWER(c);
+        }
+        else
+            *result = c;
+        result++;
+    }
 }
 
 
@@ -419,47 +385,47 @@
     }
 
     if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0)
-            return -1;
+        return -1;
     return view->len;
 }
 
 PyObject *
 _Py_bytes_maketrans(PyObject *args)
 {
-        PyObject *frm, *to, *res = NULL;
-        Py_buffer bfrm, bto;
-        Py_ssize_t i;
-        char *p;
-
-        bfrm.len = -1;
-        bto.len = -1;
-
-        if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to))
-                return NULL;
-        if (_getbuffer(frm, &bfrm) < 0)
-                return NULL;
-        if (_getbuffer(to, &bto) < 0)
-                goto done;
-        if (bfrm.len != bto.len) {
-                PyErr_Format(PyExc_ValueError,
-                             "maketrans arguments must have same length");
-                goto done;
-        }
-        res = PyBytes_FromStringAndSize(NULL, 256);
-        if (!res) {
-                goto done;
-        }
-        p = PyBytes_AS_STRING(res);
-        for (i = 0; i < 256; i++)
-                p[i] = i;
-        for (i = 0; i < bfrm.len; i++) {
-                p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i];
-        }
+    PyObject *frm, *to, *res = NULL;
+    Py_buffer bfrm, bto;
+    Py_ssize_t i;
+    char *p;
+
+    bfrm.len = -1;
+    bto.len = -1;
+
+    if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to))
+        return NULL;
+    if (_getbuffer(frm, &bfrm) < 0)
+        return NULL;
+    if (_getbuffer(to, &bto) < 0)
+        goto done;
+    if (bfrm.len != bto.len) {
+        PyErr_Format(PyExc_ValueError,
+                     "maketrans arguments must have same length");
+        goto done;
+    }
+    res = PyBytes_FromStringAndSize(NULL, 256);
+    if (!res) {
+        goto done;
+    }
+    p = PyBytes_AS_STRING(res);
+    for (i = 0; i < 256; i++)
+        p[i] = (char) i;
+    for (i = 0; i < bfrm.len; i++) {
+        p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i];
+    }
 
-  done:
-        if (bfrm.len != -1)
-                PyBuffer_Release(&bfrm);
-        if (bto.len != -1)
-                PyBuffer_Release(&bto);
-        return res;
+done:
+    if (bfrm.len != -1)
+        PyBuffer_Release(&bfrm);
+    if (bto.len != -1)
+        PyBuffer_Release(&bto);
+    return res;
 }

Modified: python/branches/pep-0384/Objects/bytesobject.c
==============================================================================
--- python/branches/pep-0384/Objects/bytesobject.c	(original)
+++ python/branches/pep-0384/Objects/bytesobject.c	Fri Aug 27 21:11:11 2010
@@ -173,15 +173,7 @@
     char *s;
     PyObject* string;
 
-#ifdef VA_LIST_IS_ARRAY
-    Py_MEMCPY(count, vargs, sizeof(va_list));
-#else
-#ifdef  __va_copy
-    __va_copy(count, vargs);
-#else
-    count = vargs;
-#endif
-#endif
+    Py_VA_COPY(count, vargs);
     /* step 1: figure out how large a buffer we need */
     for (f = format; *f; f++) {
         if (*f == '%') {
@@ -579,13 +571,14 @@
     static const char *hexdigits = "0123456789abcdef";
     register PyBytesObject* op = (PyBytesObject*) obj;
     Py_ssize_t length = Py_SIZE(op);
-    size_t newsize = 3 + 4 * length;
+    size_t newsize;
     PyObject *v;
-    if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) {
+    if (length > (PY_SSIZE_T_MAX - 3) / 4) {
         PyErr_SetString(PyExc_OverflowError,
             "bytes object is too large to make repr");
         return NULL;
     }
+    newsize = 3 + 4 * length;
     v = PyUnicode_FromUnicode(NULL, newsize);
     if (v == NULL) {
         return NULL;
@@ -732,12 +725,12 @@
     /* watch out for overflows:  the size can overflow int,
      * and the # of bytes needed can overflow size_t
      */
-    size = Py_SIZE(a) * n;
-    if (n && size / n != Py_SIZE(a)) {
+    if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) {
         PyErr_SetString(PyExc_OverflowError,
             "repeated bytes are too long");
         return NULL;
     }
+    size = Py_SIZE(a) * n;
     if (size == Py_SIZE(a) && PyBytes_CheckExact(a)) {
         Py_INCREF(a);
         return (PyObject *)a;
@@ -777,7 +770,7 @@
     Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError);
     if (ival == -1 && PyErr_Occurred()) {
         Py_buffer varg;
-        int pos;
+        Py_ssize_t pos;
         PyErr_Clear();
         if (_getbuffer(arg, &varg) < 0)
             return -1;
@@ -791,7 +784,7 @@
         return -1;
     }
 
-    return memchr(PyBytes_AS_STRING(self), ival, Py_SIZE(self)) != NULL;
+    return memchr(PyBytes_AS_STRING(self), (int) ival, Py_SIZE(self)) != NULL;
 }
 
 static PyObject *
@@ -1661,7 +1654,7 @@
 }
 
 Py_LOCAL_INLINE(Py_ssize_t)
-countchar(const char *target, int target_len, char c, Py_ssize_t maxcount)
+countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
 {
     Py_ssize_t count=0;
     const char *start=target;
@@ -1687,30 +1680,28 @@
 {
     char *self_s, *result_s;
     Py_ssize_t self_len, result_len;
-    Py_ssize_t count, i, product;
+    Py_ssize_t count, i;
     PyBytesObject *result;
 
     self_len = PyBytes_GET_SIZE(self);
 
-    /* 1 at the end plus 1 after every character */
-    count = self_len+1;
-    if (maxcount < count)
+    /* 1 at the end plus 1 after every character;
+       count = min(maxcount, self_len + 1) */
+    if (maxcount <= self_len)
         count = maxcount;
+    else
+        /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */
+        count = self_len + 1;
 
     /* Check for overflow */
     /*   result_len = count * to_len + self_len; */
-    product = count * to_len;
-    if (product / to_len != count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replacement bytes are too long");
-        return NULL;
-    }
-    result_len = product + self_len;
-    if (result_len < 0) {
+    assert(count > 0);
+    if (to_len > (PY_SSIZE_T_MAX - self_len) / count) {
         PyErr_SetString(PyExc_OverflowError,
                         "replacement bytes are too long");
         return NULL;
     }
+    result_len = count * to_len + self_len;
 
     if (! (result = (PyBytesObject *)
                      PyBytes_FromStringAndSize(NULL, result_len)) )
@@ -1939,7 +1930,7 @@
     char *self_s, *result_s;
     char *start, *next, *end;
     Py_ssize_t self_len, result_len;
-    Py_ssize_t count, product;
+    Py_ssize_t count;
     PyBytesObject *result;
 
     self_s = PyBytes_AS_STRING(self);
@@ -1953,18 +1944,13 @@
 
     /* use the difference between current and new, hence the "-1" */
     /*   result_len = self_len + count * (to_len-1)  */
-    product = count * (to_len-1);
-    if (product / (to_len-1) != count) {
+    assert(count > 0);
+    if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) {
         PyErr_SetString(PyExc_OverflowError,
                         "replacement bytes are too long");
         return NULL;
     }
-    result_len = self_len + product;
-    if (result_len < 0) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replacment bytes are too long");
-        return NULL;
-    }
+    result_len = self_len + count * (to_len - 1);
 
     if ( (result = (PyBytesObject *)
           PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
@@ -2007,7 +1993,7 @@
     char *self_s, *result_s;
     char *start, *next, *end;
     Py_ssize_t self_len, result_len;
-    Py_ssize_t count, offset, product;
+    Py_ssize_t count, offset;
     PyBytesObject *result;
 
     self_s = PyBytes_AS_STRING(self);
@@ -2024,18 +2010,13 @@
 
     /* Check for overflow */
     /*    result_len = self_len + count * (to_len-from_len) */
-    product = count * (to_len-from_len);
-    if (product / (to_len-from_len) != count) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "replacement bytes are too long");
-        return NULL;
-    }
-    result_len = self_len + product;
-    if (result_len < 0) {
+    assert(count > 0);
+    if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) {
         PyErr_SetString(PyExc_OverflowError,
                         "replacement bytes are too long");
         return NULL;
     }
+    result_len = self_len + count * (to_len-from_len);
 
     if ( (result = (PyBytesObject *)
           PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
@@ -2150,7 +2131,8 @@
 \n\
 Return a copy of B with all occurrences of subsection\n\
 old replaced by new.  If the optional argument count is\n\
-given, only the first count occurrences are replaced.");
+positive, only the first count occurrences are replaced. A\n\
+negative value of count replaces all occurrences");
 
 static PyObject *
 bytes_replace(PyBytesObject *self, PyObject *args)
@@ -2627,7 +2609,7 @@
                 Py_DECREF(new);
                 return NULL;
             }
-            ((PyBytesObject *)new)->ob_sval[i] = value;
+            ((PyBytesObject *)new)->ob_sval[i] = (char) value;
         }
         return new;
     }
@@ -2648,7 +2630,7 @@
                 Py_DECREF(new);
                 return NULL;
             }
-            ((PyBytesObject *)new)->ob_sval[i] = value;
+            ((PyBytesObject *)new)->ob_sval[i] = (char) value;
         }
         return new;
     }
@@ -2703,7 +2685,7 @@
             if (_PyBytes_Resize(&new, size) < 0)
                 goto error;
         }
-        ((PyBytesObject *)new)->ob_sval[i] = value;
+        ((PyBytesObject *)new)->ob_sval[i] = (char) value;
     }
     _PyBytes_Resize(&new, i);
 

Modified: python/branches/pep-0384/Objects/capsule.c
==============================================================================
--- python/branches/pep-0384/Objects/capsule.c	(original)
+++ python/branches/pep-0384/Objects/capsule.c	Fri Aug 27 21:11:11 2010
@@ -298,27 +298,27 @@
 
 PyTypeObject PyCapsule_Type = {
     PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "PyCapsule",		/*tp_name*/
-    sizeof(PyCapsule),		/*tp_basicsize*/
-    0,				/*tp_itemsize*/
+    "PyCapsule",                /*tp_name*/
+    sizeof(PyCapsule),          /*tp_basicsize*/
+    0,                          /*tp_itemsize*/
     /* methods */
     capsule_dealloc, /*tp_dealloc*/
-    0,				/*tp_print*/
-    0,				/*tp_getattr*/
-    0,				/*tp_setattr*/
-    0,				/*tp_reserved*/
+    0,                          /*tp_print*/
+    0,                          /*tp_getattr*/
+    0,                          /*tp_setattr*/
+    0,                          /*tp_reserved*/
     capsule_repr, /*tp_repr*/
-    0,				/*tp_as_number*/
-    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*/
-    0,				/*tp_flags*/
-    PyCapsule_Type__doc__	/*tp_doc*/
+    0,                          /*tp_as_number*/
+    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*/
+    0,                          /*tp_flags*/
+    PyCapsule_Type__doc__       /*tp_doc*/
 };
 
 

Modified: python/branches/pep-0384/Objects/complexobject.c
==============================================================================
--- python/branches/pep-0384/Objects/complexobject.c	(original)
+++ python/branches/pep-0384/Objects/complexobject.c	Fri Aug 27 21:11:11 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/pep-0384/Objects/fileobject.c
==============================================================================
--- python/branches/pep-0384/Objects/fileobject.c	(original)
+++ python/branches/pep-0384/Objects/fileobject.c	Fri Aug 27 21:11:11 2010
@@ -29,7 +29,7 @@
 PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding,
               char *errors, char *newline, int closefd)
 {
-    PyObject *io, *stream, *nameobj = NULL;
+    PyObject *io, *stream;
 
     io = PyImport_ImportModule("io");
     if (io == NULL)
@@ -40,16 +40,8 @@
     Py_DECREF(io);
     if (stream == NULL)
         return NULL;
-    if (name != NULL) {
-        nameobj = PyUnicode_DecodeFSDefault(name);
-        if (nameobj == NULL)
-            PyErr_Clear();
-        else {
-            if (PyObject_SetAttrString(stream, "name", nameobj) < 0)
-                PyErr_Clear();
-            Py_DECREF(nameobj);
-        }
-    }
+    /* ignore name attribute because the name attribute of _BufferedIOMixin
+       and TextIOWrapper is read only */
     return stream;
 }
 

Modified: python/branches/pep-0384/Objects/floatobject.c
==============================================================================
--- python/branches/pep-0384/Objects/floatobject.c	(original)
+++ python/branches/pep-0384/Objects/floatobject.c	Fri Aug 27 21:11:11 2010
@@ -305,32 +305,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
@@ -1169,7 +1157,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)
@@ -1873,7 +1861,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/pep-0384/Objects/iterobject.c
==============================================================================
--- python/branches/pep-0384/Objects/iterobject.c	(original)
+++ python/branches/pep-0384/Objects/iterobject.c	Fri Aug 27 21:11:11 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/pep-0384/Objects/listobject.c
==============================================================================
--- python/branches/pep-0384/Objects/listobject.c	(original)
+++ python/branches/pep-0384/Objects/listobject.c	Fri Aug 27 21:11:11 2010
@@ -1934,17 +1934,17 @@
         }
     }
 
-    /* Reverse sort stability achieved by initially reversing the list,
-    applying a stable forward sort, then reversing the final result. */
-    if (reverse && saved_ob_size > 1)
-        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
-
     merge_init(&ms);
 
     nremaining = saved_ob_size;
     if (nremaining < 2)
         goto succeed;
 
+    /* Reverse sort stability achieved by initially reversing the list,
+    applying a stable forward sort, then reversing the final result. */
+    if (reverse)
+        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
+
     /* March over the array once, left to right, finding natural runs,
      * and extending short natural runs to minrun elements.
      */

Modified: python/branches/pep-0384/Objects/memoryobject.c
==============================================================================
--- python/branches/pep-0384/Objects/memoryobject.c	(original)
+++ python/branches/pep-0384/Objects/memoryobject.c	Fri Aug 27 21:11:11 2010
@@ -775,10 +775,10 @@
 };
 
 static PySequenceMethods memory_as_sequence = {
-	0,                                  /* sq_length */
-	0,                                  /* sq_concat */
-	0,                                  /* sq_repeat */
-	(ssizeargfunc)memory_item,          /* sq_item */
+        0,                                  /* sq_length */
+        0,                                  /* sq_concat */
+        0,                                  /* sq_repeat */
+        (ssizeargfunc)memory_item,          /* sq_item */
 };
 
 /* Buffer methods */

Modified: python/branches/pep-0384/Objects/moduleobject.c
==============================================================================
--- python/branches/pep-0384/Objects/moduleobject.c	(original)
+++ python/branches/pep-0384/Objects/moduleobject.c	Fri Aug 27 21:11:11 2010
@@ -56,10 +56,6 @@
     return NULL;
 }
 
-static char api_version_warning[] =
-"Python C API version mismatch for module %.100s:\
- This Python has API version %d, module %.100s has version %d.";
-
 PyObject *
 PyModule_Create2(struct PyModuleDef* module, int module_api_version)
 {
@@ -79,12 +75,13 @@
     }
     name = module->m_name;
     if (module_api_version != PYTHON_API_VERSION) {
-        char message[512];
-        PyOS_snprintf(message, sizeof(message),
-                      api_version_warning, name,
-                      PYTHON_API_VERSION, name,
-                      module_api_version);
-        if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1))
+        int err;
+        err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
+            "Python C API version mismatch for module %.100s: "
+            "This Python has API version %d, module %.100s has version %d.",
+             name,
+             PYTHON_API_VERSION, name, module_api_version);
+        if (err)
             return NULL;
     }
     /* Make sure name is fully qualified.
@@ -191,8 +188,8 @@
     return _PyUnicode_AsString(nameobj);
 }
 
-static PyObject*
-module_getfilename(PyObject *m)
+PyObject*
+PyModule_GetFilenameObject(PyObject *m)
 {
     PyObject *d;
     PyObject *fileobj;
@@ -208,6 +205,7 @@
         PyErr_SetString(PyExc_SystemError, "module filename missing");
         return NULL;
     }
+    Py_INCREF(fileobj);
     return fileobj;
 }
 
@@ -215,10 +213,13 @@
 PyModule_GetFilename(PyObject *m)
 {
     PyObject *fileobj;
-    fileobj = module_getfilename(m);
+    char *utf8;
+    fileobj = PyModule_GetFilenameObject(m);
     if (fileobj == NULL)
         return NULL;
-    return _PyUnicode_AsString(fileobj);
+    utf8 = _PyUnicode_AsString(fileobj);
+    Py_DECREF(fileobj);
+    return utf8;
 }
 
 PyModuleDef*
@@ -349,19 +350,21 @@
 module_repr(PyModuleObject *m)
 {
     const char *name;
-    PyObject *filename;
+    PyObject *filename, *repr;
 
     name = PyModule_GetName((PyObject *)m);
     if (name == NULL) {
         PyErr_Clear();
         name = "?";
     }
-    filename = module_getfilename((PyObject *)m);
+    filename = PyModule_GetFilenameObject((PyObject *)m);
     if (filename == NULL) {
         PyErr_Clear();
         return PyUnicode_FromFormat("<module '%s' (built-in)>", name);
     }
-    return PyUnicode_FromFormat("<module '%s' from '%U'>", name, filename);
+    repr = PyUnicode_FromFormat("<module '%s' from '%U'>", name, filename);
+    Py_DECREF(filename);
+    return repr;
 }
 
 static int

Modified: python/branches/pep-0384/Objects/object.c
==============================================================================
--- python/branches/pep-0384/Objects/object.c	(original)
+++ python/branches/pep-0384/Objects/object.c	Fri Aug 27 21:11:11 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/pep-0384/Objects/setobject.c
==============================================================================
--- python/branches/pep-0384/Objects/setobject.c	(original)
+++ python/branches/pep-0384/Objects/setobject.c	Fri Aug 27 21:11:11 2010
@@ -349,7 +349,7 @@
         } else {
             /* ACTIVE */
             --i;
-            set_insert_clean(so, entry->key, entry->hash);
+            set_insert_clean(so, entry->key, (long) entry->hash);
         }
     }
 
@@ -368,7 +368,7 @@
     assert(so->fill <= so->mask);  /* at least one empty slot */
     n_used = so->used;
     Py_INCREF(entry->key);
-    if (set_insert_key(so, entry->key, entry->hash) == -1) {
+    if (set_insert_key(so, entry->key, (long) entry->hash) == -1) {
         Py_DECREF(entry->key);
         return -1;
     }
@@ -409,7 +409,7 @@
 {       register setentry *entry;
     PyObject *old_key;
 
-    entry = (so->lookup)(so, oldentry->key, oldentry->hash);
+    entry = (so->lookup)(so, oldentry->key, (long) oldentry->hash);
     if (entry == NULL)
         return -1;
     if (entry->key == NULL  ||  entry->key == dummy)
@@ -660,7 +660,7 @@
         if (entry->key != NULL &&
             entry->key != dummy) {
             Py_INCREF(entry->key);
-            if (set_insert_key(so, entry->key, entry->hash) == -1) {
+            if (set_insert_key(so, entry->key, (long) entry->hash) == -1) {
                 Py_DECREF(entry->key);
                 return -1;
             }
@@ -694,7 +694,7 @@
     PyObject *key;
     setentry *lu_entry;
 
-    lu_entry = (so->lookup)(so, entry->key, entry->hash);
+    lu_entry = (so->lookup)(so, entry->key, (long) entry->hash);
     if (lu_entry == NULL)
         return -1;
     key = lu_entry->key;
@@ -769,14 +769,14 @@
     if (so->hash != -1)
         return so->hash;
 
-    hash *= PySet_GET_SIZE(self) + 1;
+    hash *= (long) PySet_GET_SIZE(self) + 1;
     while (set_next(so, &pos, &entry)) {
         /* Work to increase the bit dispersion for closely spaced hash
            values.  The is important because some use cases have many
            combinations of a small number of elements with nearby
            hashes so that many distinct combinations collapse to only
            a handful of distinct hash values. */
-        h = entry->hash;
+        h = (long) entry->hash;
         hash ^= (h ^ (h << 16) ^ 89869747L)  * 3644798167u;
     }
     hash = hash * 69069L + 907133923L;
@@ -816,7 +816,7 @@
     Py_ssize_t len = 0;
     if (si->si_set != NULL && si->si_used == si->si_set->used)
         len = si->len;
-    return PyLong_FromLong(len);
+    return PyLong_FromSsize_t(len);
 }
 
 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
@@ -1547,7 +1547,7 @@
             setentry entrycopy;
             entrycopy.hash = entry->hash;
             entrycopy.key = entry->key;
-            if (!_PyDict_Contains(other, entry->key, entry->hash)) {
+            if (!_PyDict_Contains(other, entry->key, (long) entry->hash)) {
                 if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
                     Py_DECREF(result);
                     return NULL;
@@ -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;
     }
@@ -2315,7 +2309,7 @@
     if (set_next((PySetObject *)set, pos, &entry) == 0)
         return 0;
     *key = entry->key;
-    *hash = entry->hash;
+    *hash = (long) entry->hash;
     return 1;
 }
 

Modified: python/branches/pep-0384/Objects/sliceobject.c
==============================================================================
--- python/branches/pep-0384/Objects/sliceobject.c	(original)
+++ python/branches/pep-0384/Objects/sliceobject.c	Fri Aug 27 21:11:11 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/pep-0384/Objects/stringlib/fastsearch.h
==============================================================================
--- python/branches/pep-0384/Objects/stringlib/fastsearch.h	(original)
+++ python/branches/pep-0384/Objects/stringlib/fastsearch.h	Fri Aug 27 21:11:11 2010
@@ -140,13 +140,13 @@
                     /* got a match! */
                     return i;
                 /* miss: check if previous character is part of pattern */
-                if (!STRINGLIB_BLOOM(mask, s[i-1]))
+                if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1]))
                     i = i - m;
                 else
                     i = i - skip;
             } else {
                 /* skip: check if previous character is part of pattern */
-                if (!STRINGLIB_BLOOM(mask, s[i-1]))
+                if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1]))
                     i = i - m;
             }
         }

Modified: python/branches/pep-0384/Objects/stringlib/formatter.h
==============================================================================
--- python/branches/pep-0384/Objects/stringlib/formatter.h	(original)
+++ python/branches/pep-0384/Objects/stringlib/formatter.h	Fri Aug 27 21:11:11 2010
@@ -950,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')
@@ -974,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"
@@ -1134,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')
@@ -1148,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"
@@ -1223,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/pep-0384/Objects/typeobject.c
==============================================================================
--- python/branches/pep-0384/Objects/typeobject.c	(original)
+++ python/branches/pep-0384/Objects/typeobject.c	Fri Aug 27 21:11:11 2010
@@ -189,8 +189,8 @@
 
 
 static PyMemberDef type_members[] = {
-    {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
-    {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
+    {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
+    {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
     {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
     {"__weakrefoffset__", T_LONG,
      offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
@@ -2553,7 +2553,7 @@
     {"__instancecheck__", type___instancecheck__, METH_O,
      PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
     {"__subclasscheck__", type___subclasscheck__, METH_O,
-     PyDoc_STR("__subclasschck__ -> check if an class is a subclass")},
+     PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
     {0}
 };
 
@@ -3930,13 +3930,10 @@
        tp_reserved) but not tp_richcompare. */
     if (type->tp_reserved && !type->tp_richcompare) {
         int error;
-        char msg[240];
-        PyOS_snprintf(msg, sizeof(msg),
-                      "Type %.100s defines tp_reserved (formerly "
-                      "tp_compare) but not tp_richcompare. "
-                      "Comparisons may not behave as intended.",
-                      type->tp_name);
-        error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1);
+        error = PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
+            "Type %.100s defines tp_reserved (formerly tp_compare) "
+            "but not tp_richcompare. Comparisons may not behave as intended.",
+            type->tp_name);
         if (error == -1)
             goto error;
     }
@@ -5562,7 +5559,7 @@
            wrap_descr_delete, "descr.__delete__(obj)"),
     FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
            "x.__init__(...) initializes x; "
-           "see x.__class__.__doc__ for signature",
+           "see help(type(x)) for signature",
            PyWrapperFlag_KEYWORDS),
     TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
     TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),

Modified: python/branches/pep-0384/Objects/unicodectype.c
==============================================================================
--- python/branches/pep-0384/Objects/unicodectype.c	(original)
+++ python/branches/pep-0384/Objects/unicodectype.c	Fri Aug 27 21:11:11 2010
@@ -26,9 +26,9 @@
 #define NUMERIC_MASK 0x1000
 
 typedef struct {
-    const Py_UNICODE upper;
-    const Py_UNICODE lower;
-    const Py_UNICODE title;
+    const Py_UCS4 upper;
+    const Py_UCS4 lower;
+    const Py_UCS4 title;
     const unsigned char decimal;
     const unsigned char digit;
     const unsigned short flags;
@@ -37,15 +37,13 @@
 #include "unicodetype_db.h"
 
 static const _PyUnicode_TypeRecord *
-gettyperecord(Py_UNICODE code)
+gettyperecord(Py_UCS4 code)
 {
     int index;
 
-#ifdef Py_UNICODE_WIDE
     if (code >= 0x110000)
         index = 0;
     else
-#endif
     {
         index = index1[(code>>SHIFT)];
         index = index2[(index<<SHIFT)+(code&((1<<SHIFT)-1))];
@@ -57,16 +55,16 @@
 /* Returns the titlecase Unicode characters corresponding to ch or just
    ch if no titlecase mapping is known. */
 
-Py_UNICODE _PyUnicode_ToTitlecase(register Py_UNICODE ch)
+Py_UCS4 _PyUnicode_ToTitlecase(register Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
     int delta = ctype->title;
 
     if (ctype->flags & NODELTA_MASK)
-	return delta;
+        return delta;
 
     if (delta >= 32768)
-	    delta -= 65536;
+            delta -= 65536;
 
     return ch + delta;
 }
@@ -74,7 +72,7 @@
 /* Returns 1 for Unicode characters having the category 'Lt', 0
    otherwise. */
 
-int _PyUnicode_IsTitlecase(Py_UNICODE ch)
+int _PyUnicode_IsTitlecase(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -84,7 +82,7 @@
 /* Returns 1 for Unicode characters having the XID_Start property, 0
    otherwise. */
 
-int _PyUnicode_IsXidStart(Py_UNICODE ch)
+int _PyUnicode_IsXidStart(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -94,7 +92,7 @@
 /* Returns 1 for Unicode characters having the XID_Continue property,
    0 otherwise. */
 
-int _PyUnicode_IsXidContinue(Py_UNICODE ch)
+int _PyUnicode_IsXidContinue(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -104,41 +102,41 @@
 /* Returns the integer decimal (0-9) for Unicode characters having
    this property, -1 otherwise. */
 
-int _PyUnicode_ToDecimalDigit(Py_UNICODE ch)
+int _PyUnicode_ToDecimalDigit(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
     return (ctype->flags & DECIMAL_MASK) ? ctype->decimal : -1;
 }
 
-int _PyUnicode_IsDecimalDigit(Py_UNICODE ch)
+int _PyUnicode_IsDecimalDigit(Py_UCS4 ch)
 {
     if (_PyUnicode_ToDecimalDigit(ch) < 0)
-	return 0;
+        return 0;
     return 1;
 }
 
 /* Returns the integer digit (0-9) for Unicode characters having
    this property, -1 otherwise. */
 
-int _PyUnicode_ToDigit(Py_UNICODE ch)
+int _PyUnicode_ToDigit(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
     return (ctype->flags & DIGIT_MASK) ? ctype->digit : -1;
 }
 
-int _PyUnicode_IsDigit(Py_UNICODE ch)
+int _PyUnicode_IsDigit(Py_UCS4 ch)
 {
     if (_PyUnicode_ToDigit(ch) < 0)
-	return 0;
+        return 0;
     return 1;
 }
 
 /* Returns the numeric value as double for Unicode characters having
    this property, -1.0 otherwise. */
 
-int _PyUnicode_IsNumeric(Py_UNICODE ch)
+int _PyUnicode_IsNumeric(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -158,7 +156,7 @@
       * Zp Separator, Paragraph ('\u2029', PARAGRAPH SEPARATOR)
       * Zs (Separator, Space) other than ASCII space('\x20').
 */
-int _PyUnicode_IsPrintable(Py_UNICODE ch)
+int _PyUnicode_IsPrintable(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -170,7 +168,7 @@
 /* Returns 1 for Unicode characters having the category 'Ll', 0
    otherwise. */
 
-int _PyUnicode_IsLowercase(Py_UNICODE ch)
+int _PyUnicode_IsLowercase(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -180,7 +178,7 @@
 /* Returns 1 for Unicode characters having the category 'Lu', 0
    otherwise. */
 
-int _PyUnicode_IsUppercase(Py_UNICODE ch)
+int _PyUnicode_IsUppercase(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -190,35 +188,35 @@
 /* Returns the uppercase Unicode characters corresponding to ch or just
    ch if no uppercase mapping is known. */
 
-Py_UNICODE _PyUnicode_ToUppercase(Py_UNICODE ch)
+Py_UCS4 _PyUnicode_ToUppercase(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
     int delta = ctype->upper;
     if (ctype->flags & NODELTA_MASK)
-	return delta;
+        return delta;
     if (delta >= 32768)
-	    delta -= 65536;
+            delta -= 65536;
     return ch + delta;
 }
 
 /* Returns the lowercase Unicode characters corresponding to ch or just
    ch if no lowercase mapping is known. */
 
-Py_UNICODE _PyUnicode_ToLowercase(Py_UNICODE ch)
+Py_UCS4 _PyUnicode_ToLowercase(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
     int delta = ctype->lower;
     if (ctype->flags & NODELTA_MASK)
-	return delta;
+        return delta;
     if (delta >= 32768)
-	    delta -= 65536;
+            delta -= 65536;
     return ch + delta;
 }
 
 /* Returns 1 for Unicode characters having the category 'Ll', 'Lu', 'Lt',
    'Lo' or 'Lm',  0 otherwise. */
 
-int _PyUnicode_IsAlpha(Py_UNICODE ch)
+int _PyUnicode_IsAlpha(Py_UCS4 ch)
 {
     const _PyUnicode_TypeRecord *ctype = gettyperecord(ch);
 
@@ -230,27 +228,27 @@
 /* Export the interfaces using the wchar_t type for portability
    reasons:  */
 
-int _PyUnicode_IsLowercase(Py_UNICODE ch)
+int _PyUnicode_IsLowercase(Py_UCS4 ch)
 {
     return iswlower(ch);
 }
 
-int _PyUnicode_IsUppercase(Py_UNICODE ch)
+int _PyUnicode_IsUppercase(Py_UCS4 ch)
 {
     return iswupper(ch);
 }
 
-Py_UNICODE _PyUnicode_ToLowercase(Py_UNICODE ch)
+Py_UCS4 _PyUnicode_ToLowercase(Py_UCS4 ch)
 {
     return towlower(ch);
 }
 
-Py_UNICODE _PyUnicode_ToUppercase(Py_UNICODE ch)
+Py_UCS4 _PyUnicode_ToUppercase(Py_UCS4 ch)
 {
     return towupper(ch);
 }
 
-int _PyUnicode_IsAlpha(Py_UNICODE ch)
+int _PyUnicode_IsAlpha(Py_UCS4 ch)
 {
     return iswalpha(ch);
 }

Modified: python/branches/pep-0384/Objects/unicodeobject.c
==============================================================================
--- python/branches/pep-0384/Objects/unicodeobject.c	(original)
+++ python/branches/pep-0384/Objects/unicodeobject.c	Fri Aug 27 21:11:11 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;
@@ -666,7 +664,7 @@
         return NULL;
 
     /* Copy the wchar_t data into the new object */
-#ifdef HAVE_USABLE_WCHAR_T
+#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
     memcpy(unicode->str, w, size * sizeof(wchar_t));
 #else
     {
@@ -757,15 +755,7 @@
     char fmt[61]; /* should be enough for %0width.precisionlld */
     const char *copy;
 
-#ifdef VA_LIST_IS_ARRAY
-    Py_MEMCPY(count, vargs, sizeof(va_list));
-#else
-#ifdef  __va_copy
-    __va_copy(count, vargs);
-#else
-    count = vargs;
-#endif
-#endif
+    Py_VA_COPY(count, vargs);
     /* step 1: count the number of %S/%R/%A/%s format specifications
      * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
      * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
@@ -1177,7 +1167,7 @@
     if (size > PyUnicode_GET_SIZE(unicode))
         size = PyUnicode_GET_SIZE(unicode) + 1;
 
-#ifdef HAVE_USABLE_WCHAR_T
+#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
     memcpy(w, unicode->str, size * sizeof(wchar_t));
 #else
     {
@@ -1490,8 +1480,8 @@
                                          "surrogateescape");
     } else
         return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
-                                     PyUnicode_GET_SIZE(unicode),
-                                     "surrogateescape");
+                                    PyUnicode_GET_SIZE(unicode),
+                                    "surrogateescape");
 }
 
 PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
@@ -1558,12 +1548,13 @@
 
     /* If the codec returns a buffer, raise a warning and convert to bytes */
     if (PyByteArray_Check(v)) {
-        char msg[100];
+        int error;
         PyObject *b;
-        PyOS_snprintf(msg, sizeof(msg),
-                      "encoder %s returned buffer instead of bytes",
-                      encoding);
-        if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) {
+
+        error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
+            "encoder %s returned bytearray instead of bytes",
+            encoding);
+        if (error) {
             Py_DECREF(v);
             return NULL;
         }
@@ -1661,9 +1652,6 @@
     }
 }
 
-/* Convert the argument to a bytes object, according to the file
-   system encoding.  The addr param must be a PyObject**.
-   This is designed to be used with "O&" in PyArg_Parse APIs. */
 
 int
 PyUnicode_FSConverter(PyObject* arg, void* addr)
@@ -1705,6 +1693,47 @@
 }
 
 
+int
+PyUnicode_FSDecoder(PyObject* arg, void* addr)
+{
+    PyObject *output = NULL;
+    Py_ssize_t size;
+    void *data;
+    if (arg == NULL) {
+        Py_DECREF(*(PyObject**)addr);
+        return 1;
+    }
+    if (PyUnicode_Check(arg)) {
+        output = arg;
+        Py_INCREF(output);
+    }
+    else {
+        arg = PyBytes_FromObject(arg);
+        if (!arg)
+            return 0;
+        output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
+                                                  PyBytes_GET_SIZE(arg));
+        Py_DECREF(arg);
+        if (!output)
+            return 0;
+        if (!PyUnicode_Check(output)) {
+            Py_DECREF(output);
+            PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
+            return 0;
+        }
+    }
+    size = PyUnicode_GET_SIZE(output);
+    data = PyUnicode_AS_UNICODE(output);
+    if (size != Py_UNICODE_strlen(data)) {
+        PyErr_SetString(PyExc_TypeError, "embedded NUL character");
+        Py_DECREF(output);
+        return 0;
+    }
+    *(PyObject**)addr = output;
+    return Py_CLEANUP_SUPPORTED;
+}
+
+
 char*
 _PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
 {
@@ -2289,7 +2318,7 @@
        illegal prefix.  See RFC 3629 for details */
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -9957,6 +9986,23 @@
     return 0;
 }
 
+int
+Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
+{
+    register Py_UNICODE u1, u2;
+    for (; n != 0; n--) {
+        u1 = *s1;
+        u2 = *s2;
+        if (u1 != u2)
+            return (u1 < u2) ? -1 : +1;
+        if (u1 == '\0')
+            return 0;
+        s1++;
+        s2++;
+    }
+    return 0;
+}
+
 Py_UNICODE*
 Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
 {
@@ -9967,6 +10013,19 @@
     return NULL;
 }
 
+Py_UNICODE*
+Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
+{
+    const Py_UNICODE *p;
+    p = s + Py_UNICODE_strlen(s);
+    while (p != s) {
+        p--;
+        if (*p == c)
+            return (Py_UNICODE*)p;
+    }
+    return NULL;
+}
+
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-0384/Objects/unicodetype_db.h
==============================================================================
--- python/branches/pep-0384/Objects/unicodetype_db.h	(original)
+++ python/branches/pep-0384/Objects/unicodetype_db.h	Fri Aug 27 21:11:11 2010
@@ -1980,7 +1980,7 @@
 /* Returns the numeric value as double for Unicode characters
  * having this property, -1.0 otherwise.
  */
-double _PyUnicode_ToNumeric(Py_UNICODE ch)
+double _PyUnicode_ToNumeric(Py_UCS4 ch)
 {
     switch (ch) {
     case 0x0F33:
@@ -2031,7 +2031,6 @@
     case 0xABF0:
     case 0xF9B2:
     case 0xFF10:
-#ifdef Py_UNICODE_WIDE
     case 0x1018A:
     case 0x104A0:
     case 0x1D7CE:
@@ -2041,7 +2040,6 @@
     case 0x1D7F6:
     case 0x1F100:
     case 0x1F101:
-#endif
         return (double) 0.0;
     case 0x0031:
     case 0x00B9:
@@ -2105,7 +2103,6 @@
     case 0xAA51:
     case 0xABF1:
     case 0xFF11:
-#ifdef Py_UNICODE_WIDE
     case 0x10107:
     case 0x10142:
     case 0x10158:
@@ -2135,7 +2132,6 @@
     case 0x1D7F7:
     case 0x1F102:
     case 0x2092A:
-#endif
         return (double) 1.0;
     case 0x2152:
         return (double) 1.0/10.0;
@@ -2147,46 +2143,36 @@
     case 0x0F2A:
     case 0x2CFD:
     case 0xA831:
-#ifdef Py_UNICODE_WIDE
     case 0x10141:
     case 0x10175:
     case 0x10176:
     case 0x10E7B:
-#endif
         return (double) 1.0/2.0;
     case 0x2153:
-#ifdef Py_UNICODE_WIDE
     case 0x10E7D:
     case 0x1245A:
     case 0x1245D:
-#endif
         return (double) 1.0/3.0;
     case 0x00BC:
     case 0x09F7:
     case 0x0D73:
     case 0xA830:
-#ifdef Py_UNICODE_WIDE
     case 0x10140:
     case 0x10E7C:
     case 0x12460:
     case 0x12462:
-#endif
         return (double) 1.0/4.0;
     case 0x2155:
         return (double) 1.0/5.0;
     case 0x2159:
-#ifdef Py_UNICODE_WIDE
     case 0x12461:
-#endif
         return (double) 1.0/6.0;
     case 0x2150:
         return (double) 1.0/7.0;
     case 0x09F5:
     case 0x215B:
     case 0xA834:
-#ifdef Py_UNICODE_WIDE
     case 0x1245F:
-#endif
         return (double) 1.0/8.0;
     case 0x2151:
         return (double) 1.0/9.0;
@@ -2210,7 +2196,6 @@
     case 0x62FE:
     case 0xF973:
     case 0xF9FD:
-#ifdef Py_UNICODE_WIDE
     case 0x10110:
     case 0x10149:
     case 0x10150:
@@ -2229,7 +2214,6 @@
     case 0x10B7C:
     case 0x10E69:
     case 0x1D369:
-#endif
         return (double) 10.0;
     case 0x0BF1:
     case 0x0D71:
@@ -2239,7 +2223,6 @@
     case 0x4F70:
     case 0x767E:
     case 0x964C:
-#ifdef Py_UNICODE_WIDE
     case 0x10119:
     case 0x1014B:
     case 0x10152:
@@ -2251,7 +2234,6 @@
     case 0x10B5E:
     case 0x10B7E:
     case 0x10E72:
-#endif
         return (double) 100.0;
     case 0x0BF2:
     case 0x0D72:
@@ -2261,7 +2243,6 @@
     case 0x4EDF:
     case 0x5343:
     case 0x9621:
-#ifdef Py_UNICODE_WIDE
     case 0x10122:
     case 0x1014D:
     case 0x10154:
@@ -2270,17 +2251,14 @@
     case 0x10A47:
     case 0x10B5F:
     case 0x10B7F:
-#endif
         return (double) 1000.0;
     case 0x137C:
     case 0x2182:
     case 0x4E07:
     case 0x842C:
-#ifdef Py_UNICODE_WIDE
     case 0x1012B:
     case 0x10155:
     case 0x1085F:
-#endif
         return (double) 10000.0;
     case 0x2188:
         return (double) 100000.0;
@@ -2414,7 +2392,6 @@
     case 0xABF2:
     case 0xF978:
     case 0xFF12:
-#ifdef Py_UNICODE_WIDE
     case 0x10108:
     case 0x1015B:
     case 0x1015C:
@@ -2445,15 +2422,12 @@
     case 0x1D7F8:
     case 0x1F103:
     case 0x22390:
-#endif
         return (double) 2.0;
     case 0x2154:
-#ifdef Py_UNICODE_WIDE
     case 0x10177:
     case 0x10E7E:
     case 0x1245B:
     case 0x1245E:
-#endif
         return (double) 2.0/3.0;
     case 0x2156:
         return (double) 2.0/5.0;
@@ -2465,7 +2439,6 @@
     case 0x3039:
     case 0x5344:
     case 0x5EFF:
-#ifdef Py_UNICODE_WIDE
     case 0x10111:
     case 0x103D4:
     case 0x1085C:
@@ -2475,21 +2448,14 @@
     case 0x10B7D:
     case 0x10E6A:
     case 0x1D36A:
-#endif
         return (double) 20.0;
-#ifdef Py_UNICODE_WIDE
     case 0x1011A:
     case 0x10E73:
         return (double) 200.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10123:
         return (double) 2000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x1012C:
         return (double) 20000.0;
-#endif
     case 0x3251:
         return (double) 21.0;
     case 0x3252:
@@ -2571,7 +2537,6 @@
     case 0xABF3:
     case 0xF96B:
     case 0xFF13:
-#ifdef Py_UNICODE_WIDE
     case 0x10109:
     case 0x104A3:
     case 0x1085A:
@@ -2605,7 +2570,6 @@
     case 0x20B19:
     case 0x22998:
     case 0x23B1B:
-#endif
         return (double) 3.0;
     case 0x09F6:
     case 0xA835:
@@ -2616,9 +2580,7 @@
     case 0x09F8:
     case 0x0D75:
     case 0xA832:
-#ifdef Py_UNICODE_WIDE
     case 0x10178:
-#endif
         return (double) 3.0/4.0;
     case 0x2157:
         return (double) 3.0/5.0;
@@ -2628,28 +2590,20 @@
     case 0x303A:
     case 0x325A:
     case 0x5345:
-#ifdef Py_UNICODE_WIDE
     case 0x10112:
     case 0x10165:
     case 0x10E6B:
     case 0x1D36B:
     case 0x20983:
-#endif
         return (double) 30.0;
-#ifdef Py_UNICODE_WIDE
     case 0x1011B:
     case 0x1016B:
     case 0x10E74:
         return (double) 300.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10124:
         return (double) 3000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x1012D:
         return (double) 30000.0;
-#endif
     case 0x325B:
         return (double) 31.0;
     case 0x325C:
@@ -2724,7 +2678,6 @@
     case 0xAA54:
     case 0xABF4:
     case 0xFF14:
-#ifdef Py_UNICODE_WIDE
     case 0x1010A:
     case 0x104A4:
     case 0x10A43:
@@ -2756,34 +2709,25 @@
     case 0x20064:
     case 0x200E2:
     case 0x2626D:
-#endif
         return (double) 4.0;
     case 0x2158:
         return (double) 4.0/5.0;
     case 0x1375:
     case 0x32B5:
     case 0x534C:
-#ifdef Py_UNICODE_WIDE
     case 0x10113:
     case 0x10E6C:
     case 0x1D36C:
     case 0x2098C:
     case 0x2099C:
-#endif
         return (double) 40.0;
-#ifdef Py_UNICODE_WIDE
     case 0x1011C:
     case 0x10E75:
         return (double) 400.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10125:
         return (double) 4000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x1012E:
         return (double) 40000.0;
-#endif
     case 0x32B6:
         return (double) 41.0;
     case 0x32B7:
@@ -2858,7 +2802,6 @@
     case 0xAA55:
     case 0xABF5:
     case 0xFF15:
-#ifdef Py_UNICODE_WIDE
     case 0x1010B:
     case 0x10143:
     case 0x10148:
@@ -2887,14 +2830,11 @@
     case 0x1D7FB:
     case 0x1F106:
     case 0x20121:
-#endif
         return (double) 5.0;
     case 0x0F2C:
         return (double) 5.0/2.0;
     case 0x215A:
-#ifdef Py_UNICODE_WIDE
     case 0x1245C:
-#endif
         return (double) 5.0/6.0;
     case 0x215D:
         return (double) 5.0/8.0;
@@ -2903,7 +2843,6 @@
     case 0x217C:
     case 0x2186:
     case 0x32BF:
-#ifdef Py_UNICODE_WIDE
     case 0x10114:
     case 0x10144:
     case 0x1014A:
@@ -2917,11 +2856,9 @@
     case 0x10A7E:
     case 0x10E6D:
     case 0x1D36D:
-#endif
         return (double) 50.0;
     case 0x216E:
     case 0x217E:
-#ifdef Py_UNICODE_WIDE
     case 0x1011D:
     case 0x10145:
     case 0x1014C:
@@ -2932,22 +2869,17 @@
     case 0x1016F:
     case 0x10170:
     case 0x10E76:
-#endif
         return (double) 500.0;
     case 0x2181:
-#ifdef Py_UNICODE_WIDE
     case 0x10126:
     case 0x10146:
     case 0x1014E:
     case 0x10172:
-#endif
         return (double) 5000.0;
     case 0x2187:
-#ifdef Py_UNICODE_WIDE
     case 0x1012F:
     case 0x10147:
     case 0x10156:
-#endif
         return (double) 50000.0;
     case 0x0036:
     case 0x0666:
@@ -3007,7 +2939,6 @@
     case 0xF9D1:
     case 0xF9D3:
     case 0xFF16:
-#ifdef Py_UNICODE_WIDE
     case 0x1010C:
     case 0x104A6:
     case 0x10E65:
@@ -3026,28 +2957,19 @@
     case 0x1D7FC:
     case 0x1F107:
     case 0x20AEA:
-#endif
         return (double) 6.0;
     case 0x1377:
-#ifdef Py_UNICODE_WIDE
     case 0x10115:
     case 0x10E6E:
     case 0x1D36E:
-#endif
         return (double) 60.0;
-#ifdef Py_UNICODE_WIDE
     case 0x1011E:
     case 0x10E77:
         return (double) 600.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10127:
         return (double) 6000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10130:
         return (double) 60000.0;
-#endif
     case 0x0037:
     case 0x0667:
     case 0x06F7:
@@ -3104,7 +3026,6 @@
     case 0xAA57:
     case 0xABF7:
     case 0xFF17:
-#ifdef Py_UNICODE_WIDE
     case 0x1010D:
     case 0x104A7:
     case 0x10E66:
@@ -3124,32 +3045,23 @@
     case 0x1D7FD:
     case 0x1F108:
     case 0x20001:
-#endif
         return (double) 7.0;
     case 0x0F2D:
         return (double) 7.0/2.0;
     case 0x215E:
         return (double) 7.0/8.0;
     case 0x1378:
-#ifdef Py_UNICODE_WIDE
     case 0x10116:
     case 0x10E6F:
     case 0x1D36F:
-#endif
         return (double) 70.0;
-#ifdef Py_UNICODE_WIDE
     case 0x1011F:
     case 0x10E78:
         return (double) 700.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10128:
         return (double) 7000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10131:
         return (double) 70000.0;
-#endif
     case 0x0038:
     case 0x0668:
     case 0x06F8:
@@ -3204,7 +3116,6 @@
     case 0xAA58:
     case 0xABF8:
     case 0xFF18:
-#ifdef Py_UNICODE_WIDE
     case 0x1010E:
     case 0x104A8:
     case 0x10E67:
@@ -3222,28 +3133,19 @@
     case 0x1D7F4:
     case 0x1D7FE:
     case 0x1F109:
-#endif
         return (double) 8.0;
     case 0x1379:
-#ifdef Py_UNICODE_WIDE
     case 0x10117:
     case 0x10E70:
     case 0x1D370:
-#endif
         return (double) 80.0;
-#ifdef Py_UNICODE_WIDE
     case 0x10120:
     case 0x10E79:
         return (double) 800.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10129:
         return (double) 8000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10132:
         return (double) 80000.0;
-#endif
     case 0x0039:
     case 0x0669:
     case 0x06F9:
@@ -3299,7 +3201,6 @@
     case 0xAA59:
     case 0xABF9:
     case 0xFF19:
-#ifdef Py_UNICODE_WIDE
     case 0x1010F:
     case 0x104A9:
     case 0x10E68:
@@ -3320,32 +3221,23 @@
     case 0x1D7FF:
     case 0x1F10A:
     case 0x2F890:
-#endif
         return (double) 9.0;
     case 0x0F2E:
         return (double) 9.0/2.0;
     case 0x137A:
-#ifdef Py_UNICODE_WIDE
     case 0x10118:
     case 0x10341:
     case 0x10E71:
     case 0x1D371:
-#endif
         return (double) 90.0;
-#ifdef Py_UNICODE_WIDE
     case 0x10121:
     case 0x1034A:
     case 0x10E7A:
         return (double) 900.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x1012A:
         return (double) 9000.0;
-#endif
-#ifdef Py_UNICODE_WIDE
     case 0x10133:
         return (double) 90000.0;
-#endif
     }
     return -1.0;
 }
@@ -3353,7 +3245,7 @@
 /* Returns 1 for Unicode characters having the bidirectional
  * type 'WS', 'B' or 'S' or the category 'Zs', 0 otherwise.
  */
-int _PyUnicode_IsWhitespace(register const Py_UNICODE ch)
+int _PyUnicode_IsWhitespace(register const Py_UCS4 ch)
 {
 #ifdef WANT_WCTYPE_FUNCTIONS
     return iswspace(ch);
@@ -3399,7 +3291,7 @@
  * property 'BK', 'CR', 'LF' or 'NL' or having bidirectional
  * type 'B', 0 otherwise.
  */
-int _PyUnicode_IsLinebreak(register const Py_UNICODE ch)
+int _PyUnicode_IsLinebreak(register const Py_UCS4 ch)
 {
     switch (ch) {
     case 0x000A:

Modified: python/branches/pep-0384/PC/VS8.0/pythoncore.vcproj
==============================================================================
--- python/branches/pep-0384/PC/VS8.0/pythoncore.vcproj	(original)
+++ python/branches/pep-0384/PC/VS8.0/pythoncore.vcproj	Fri Aug 27 21:11:11 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/pep-0384/PC/_subprocess.c
==============================================================================
--- python/branches/pep-0384/PC/_subprocess.c	(original)
+++ python/branches/pep-0384/PC/_subprocess.c	Fri Aug 27 21:11:11 2010
@@ -329,7 +329,8 @@
 static PyObject*
 getenvironment(PyObject* environment)
 {
-    int i, envsize;
+    int i;
+    Py_ssize_t envsize;
     PyObject* out = NULL;
     PyObject* keys;
     PyObject* values;
@@ -356,7 +357,7 @@
     p = PyUnicode_AS_UNICODE(out);
 
     for (i = 0; i < envsize; i++) {
-        int ksize, vsize, totalsize;
+        Py_ssize_t ksize, vsize, totalsize;
         PyObject* key = PyList_GET_ITEM(keys, i);
         PyObject* value = PyList_GET_ITEM(values, i);
 
@@ -370,7 +371,7 @@
         totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 +
                                                      vsize + 1 + 1;
         if (totalsize > PyUnicode_GET_SIZE(out)) {
-            int offset = p - PyUnicode_AS_UNICODE(out);
+            Py_ssize_t offset = p - PyUnicode_AS_UNICODE(out);
             PyUnicode_Resize(&out, totalsize + 1024);
             p = PyUnicode_AS_UNICODE(out) + offset;
         }

Modified: python/branches/pep-0384/PC/config.c
==============================================================================
--- python/branches/pep-0384/PC/config.c	(original)
+++ python/branches/pep-0384/PC/config.c	Fri Aug 27 21:11:11 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/pep-0384/PC/msvcrtmodule.c
==============================================================================
--- python/branches/pep-0384/PC/msvcrtmodule.c	(original)
+++ python/branches/pep-0384/PC/msvcrtmodule.c	Fri Aug 27 21:11:11 2010
@@ -197,12 +197,12 @@
 PyDoc_STRVAR(getch_doc,
 "getch() -> key character\n\
 \n\
-Read a keypress and return the resulting character. Nothing is echoed to\n\
-the console. This call will block if a keypress is not already\n\
-available, but will not wait for Enter to be pressed. If the pressed key\n\
-was a special function key, this will return '\\000' or '\\xe0'; the next\n\
-call will return the keycode. The Control-C keypress cannot be read with\n\
-this function.");
+Read a keypress and return the resulting character as a byte string.\n\
+Nothing is echoed to the console. This call will block if a keypress is\n\
+not already available, but will not wait for Enter to be pressed. If the\n\
+pressed key was a special function key, this will return '\\000' or\n\
+'\\xe0'; the next call will return the keycode. The Control-C keypress\n\
+cannot be read with this function.");
 
 #ifdef _WCONIO_DEFINED
 static PyObject *
@@ -288,7 +288,7 @@
 PyDoc_STRVAR(putch_doc,
 "putch(char) -> None\n\
 \n\
-Print the character char to the console without buffering.");
+Print the byte string char to the console without buffering.");
 
 #ifdef _WCONIO_DEFINED
 static PyObject *
@@ -327,8 +327,9 @@
 PyDoc_STRVAR(ungetch_doc,
 "ungetch(char) -> None\n\
 \n\
-Cause the character char to be \"pushed back\" into the console buffer;\n\
-it will be the next character read by getch() or getche().");
+Cause the byte string char to be \"pushed back\" into the\n\
+console buffer; it will be the next character read by\n\
+getch() or getche().");
 
 #ifdef _WCONIO_DEFINED
 static PyObject *

Modified: python/branches/pep-0384/PC/pyconfig.h
==============================================================================
--- python/branches/pep-0384/PC/pyconfig.h	(original)
+++ python/branches/pep-0384/PC/pyconfig.h	Fri Aug 27 21:11:11 2010
@@ -80,7 +80,7 @@
 #define MS_WIN32 /* only support win32 and greater. */
 #define MS_WINDOWS
 #ifndef PYTHONPATH
-#	define PYTHONPATH L".\\DLLs;.\\lib;.\\lib\\plat-win"
+#	define PYTHONPATH L".\\DLLs;.\\lib"
 #endif
 #define NT_THREADS
 #define WITH_THREAD
@@ -721,6 +721,9 @@
 /* Define if the compiler provides a wchar.h header file. */
 #define HAVE_WCHAR_H 1
 
+/* The size of `wchar_t', as computed by sizeof. */
+#define SIZEOF_WCHAR_T 2
+
 /* Define if you have the dl library (-ldl).  */
 /* #undef HAVE_LIBDL */
 

Modified: python/branches/pep-0384/PC/python_nt.rc
==============================================================================
--- python/branches/pep-0384/PC/python_nt.rc	(original)
+++ python/branches/pep-0384/PC/python_nt.rc	Fri Aug 27 21:11:11 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/pep-0384/PC/winreg.c
==============================================================================
--- python/branches/pep-0384/PC/winreg.c	(original)
+++ python/branches/pep-0384/PC/winreg.c	Fri Aug 27 21:11:11 2010
@@ -765,8 +765,9 @@
             else {
                 if (!PyUnicode_Check(value))
                     return FALSE;
-
-                *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value);
+                *retDataSize = Py_SAFE_DOWNCAST(
+                                   2 + PyUnicode_GET_DATA_SIZE(value),
+                                   size_t, DWORD);
             }
             *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
             if (*retDataBuf==NULL){
@@ -798,7 +799,8 @@
                     t = PyList_GET_ITEM(value, j);
                     if (!PyUnicode_Check(t))
                         return FALSE;
-                    size += 2 + PyUnicode_GET_DATA_SIZE(t);
+                    size += Py_SAFE_DOWNCAST(2 + PyUnicode_GET_DATA_SIZE(t),
+                                             size_t, DWORD);
                 }
 
                 *retDataSize = size + 2;
@@ -848,7 +850,7 @@
                     PyErr_NoMemory();
                     return FALSE;
                 }
-                *retDataSize = view.len;
+                *retDataSize = Py_SAFE_DOWNCAST(view.len, Py_ssize_t, DWORD);
                 memcpy(*retDataBuf, view.buf, view.len);
                 PyBuffer_Release(&view);
             }
@@ -1129,7 +1131,7 @@
     int index;
     long rc;
     wchar_t *retValueBuf;
-    wchar_t *tmpBuf;
+    BYTE *tmpBuf;
     BYTE *retDataBuf;
     DWORD retValueSize, bufValueSize;
     DWORD retDataSize, bufDataSize;
@@ -1177,7 +1179,7 @@
             break;
 
         bufDataSize *= 2;
-        tmpBuf = (wchar_t *)PyMem_Realloc(retDataBuf, bufDataSize);
+        tmpBuf = (BYTE *)PyMem_Realloc(retDataBuf, bufDataSize);
         if (tmpBuf == NULL) {
             PyErr_NoMemory();
             retVal = NULL;

Modified: python/branches/pep-0384/PCbuild/build_ssl.py
==============================================================================
--- python/branches/pep-0384/PCbuild/build_ssl.py	(original)
+++ python/branches/pep-0384/PCbuild/build_ssl.py	Fri Aug 27 21:11:11 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/pep-0384/PCbuild/pyproject.vsprops
==============================================================================
--- python/branches/pep-0384/PCbuild/pyproject.vsprops	(original)
+++ python/branches/pep-0384/PCbuild/pyproject.vsprops	Fri Aug 27 21:11:11 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/pep-0384/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/pep-0384/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/pep-0384/PCbuild/pythoncore.vcproj	Fri Aug 27 21:11:11 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/pep-0384/PCbuild/readme.txt
==============================================================================
--- python/branches/pep-0384/PCbuild/readme.txt	(original)
+++ python/branches/pep-0384/PCbuild/readme.txt	Fri Aug 27 21:11:11 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/pep-0384/Python/_warnings.c
==============================================================================
--- python/branches/pep-0384/Python/_warnings.c	(original)
+++ python/branches/pep-0384/Python/_warnings.c	Fri Aug 27 21:11:11 2010
@@ -498,23 +498,21 @@
     *filename = PyDict_GetItemString(globals, "__file__");
     if (*filename != NULL) {
         Py_ssize_t len = PyUnicode_GetSize(*filename);
-        const char *file_str = _PyUnicode_AsString(*filename);
-            if (file_str == NULL || (len < 0 && PyErr_Occurred()))
-            goto handle_error;
+        Py_UNICODE *unicode = PyUnicode_AS_UNICODE(*filename);
 
         /* if filename.lower().endswith((".pyc", ".pyo")): */
         if (len >= 4 &&
-            file_str[len-4] == '.' &&
-            tolower(file_str[len-3]) == 'p' &&
-            tolower(file_str[len-2]) == 'y' &&
-            (tolower(file_str[len-1]) == 'c' ||
-                tolower(file_str[len-1]) == 'o'))
+            unicode[len-4] == '.' &&
+            Py_UNICODE_TOLOWER(unicode[len-3]) == 'p' &&
+            Py_UNICODE_TOLOWER(unicode[len-2]) == 'y' &&
+            (Py_UNICODE_TOLOWER(unicode[len-1]) == 'c' ||
+                Py_UNICODE_TOLOWER(unicode[len-1]) == 'o'))
         {
-            *filename = PyUnicode_FromStringAndSize(file_str, len-1);
-                if (*filename == NULL)
-                        goto handle_error;
-            }
-            else
+            *filename = PyUnicode_FromUnicode(unicode, len-1);
+            if (*filename == NULL)
+                goto handle_error;
+        }
+        else
             Py_INCREF(*filename);
     }
     else {
@@ -712,19 +710,17 @@
 
 
 /* Function to issue a warning message; may raise an exception. */
-int
-PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
+
+static int
+warn_unicode(PyObject *category, PyObject *message,
+             Py_ssize_t stack_level)
 {
     PyObject *res;
-    PyObject *message = PyUnicode_FromString(text);
-    if (message == NULL)
-        return -1;
 
     if (category == NULL)
         category = PyExc_RuntimeWarning;
 
     res = do_warn(message, category, stack_level);
-    Py_DECREF(message);
     if (res == NULL)
         return -1;
     Py_DECREF(res);
@@ -732,6 +728,42 @@
     return 0;
 }
 
+int
+PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
+                 const char *format, ...)
+{
+    int ret;
+    PyObject *message;
+    va_list vargs;
+
+#ifdef HAVE_STDARG_PROTOTYPES
+    va_start(vargs, format);
+#else
+    va_start(vargs);
+#endif
+    message = PyUnicode_FromFormatV(format, vargs);
+    if (message != NULL) {
+        ret = warn_unicode(category, message, stack_level);
+        Py_DECREF(message);
+    }
+    else
+        ret = -1;
+    va_end(vargs);
+    return ret;
+}
+
+int
+PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
+{
+    int ret;
+    PyObject *message = PyUnicode_FromString(text);
+    if (message == NULL)
+        return -1;
+    ret = warn_unicode(category, message, stack_level);
+    Py_DECREF(message);
+    return ret;
+}
+
 /* PyErr_Warn is only for backwards compatability and will be removed.
    Use PyErr_WarnEx instead. */
 

Modified: python/branches/pep-0384/Python/ast.c
==============================================================================
--- python/branches/pep-0384/Python/ast.c	(original)
+++ python/branches/pep-0384/Python/ast.c	Fri Aug 27 21:11:11 2010
@@ -688,6 +688,8 @@
             case tfpdef:
                 if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
                     expression = ast_for_expr(c, CHILD(n, i + 2));
+                    if (!expression)
+                        goto error;
                     asdl_seq_SET(kwdefaults, j, expression);
                     i += 2; /* '=' and test */
                 }
@@ -697,10 +699,8 @@
                 if (NCH(ch) == 3) {
                     /* ch is NAME ':' test */
                     annotation = ast_for_expr(c, CHILD(ch, 2));
-                    if (!annotation) {
-                        ast_error(ch, "expected expression");
+                    if (!annotation)
                         goto error;
-                    }
                 }
                 else {
                     annotation = NULL;
@@ -794,22 +794,22 @@
     }
     posargs = (nposargs ? asdl_seq_new(nposargs, c->c_arena) : NULL);
     if (!posargs && nposargs)
-        goto error;
+        return NULL;
     kwonlyargs = (nkwonlyargs ?
                    asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
     if (!kwonlyargs && nkwonlyargs)
-        goto error;
+        return NULL;
     posdefaults = (nposdefaults ?
                     asdl_seq_new(nposdefaults, c->c_arena) : NULL);
     if (!posdefaults && nposdefaults)
-        goto error;
+        return NULL;
     /* The length of kwonlyargs and kwdefaults are same
        since we set NULL as default for keyword only argument w/o default
        - we have sequence data structure, but no dictionary */
     kwdefaults = (nkwonlyargs ?
                    asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
     if (!kwdefaults && nkwonlyargs)
-        goto error;
+        return NULL;
 
     if (nposargs + nkwonlyargs > 255) {
         ast_error(n, "more than 255 arguments");
@@ -833,7 +833,7 @@
                 if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
                     expr_ty expression = ast_for_expr(c, CHILD(n, i + 2));
                     if (!expression)
-                        goto error;
+                        return NULL;
                     assert(posdefaults != NULL);
                     asdl_seq_SET(posdefaults, j++, expression);
                     i += 2;
@@ -842,11 +842,11 @@
                 else if (found_default) {
                     ast_error(n,
                              "non-default argument follows default argument");
-                    goto error;
+                    return NULL;
                 }
                 arg = compiler_arg(c, ch);
                 if (!arg)
-                    goto error;
+                    return NULL;
                 asdl_seq_SET(posargs, k++, arg);
                 i += 2; /* the name and the comma */
                 break;
@@ -854,7 +854,7 @@
                 if (i+1 >= NCH(n)) {
                     ast_error(CHILD(n, i),
                         "named arguments must follow bare *");
-                    goto error;
+                    return NULL;
                 }
                 ch = CHILD(n, i+1);  /* tfpdef or COMMA */
                 if (TYPE(ch) == COMMA) {
@@ -862,7 +862,7 @@
                     i += 2; /* now follows keyword only arguments */
                     res = handle_keywordonly_args(c, n, i,
                                                   kwonlyargs, kwdefaults);
-                    if (res == -1) goto error;
+                    if (res == -1) return NULL;
                     i = res; /* res has new position to process */
                 }
                 else {
@@ -874,6 +874,8 @@
                     if (NCH(ch) > 1) {
                         /* there is an annotation on the vararg */
                         varargannotation = ast_for_expr(c, CHILD(ch, 2));
+                        if (!varargannotation)
+                            return NULL;
                     }
                     i += 3;
                     if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef
@@ -881,7 +883,7 @@
                         int res = 0;
                         res = handle_keywordonly_args(c, n, i,
                                                       kwonlyargs, kwdefaults);
-                        if (res == -1) goto error;
+                        if (res == -1) return NULL;
                         i = res; /* res has new position to process */
                     }
                 }
@@ -890,29 +892,27 @@
                 ch = CHILD(n, i+1);  /* tfpdef */
                 assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef);
                 kwarg = NEW_IDENTIFIER(CHILD(ch, 0));
+                if (!kwarg)
+                    return NULL;
                 if (NCH(ch) > 1) {
                     /* there is an annotation on the kwarg */
                     kwargannotation = ast_for_expr(c, CHILD(ch, 2));
+                    if (!kwargannotation)
+                        return NULL;
                 }
-                if (!kwarg)
-                    goto error;
                 if (forbidden_name(kwarg, CHILD(ch, 0), 0))
-                    goto error;
+                    return NULL;
                 i += 3;
                 break;
             default:
                 PyErr_Format(PyExc_SystemError,
                              "unexpected node in varargslist: %d @ %d",
                              TYPE(ch), i);
-                goto error;
+                return NULL;
         }
     }
     return arguments(posargs, vararg, varargannotation, kwonlyargs, kwarg,
                     kwargannotation, posdefaults, kwdefaults, c->c_arena);
- error:
-    Py_XDECREF(vararg);
-    Py_XDECREF(kwarg);
-    return NULL;
 }
 
 static expr_ty
@@ -997,9 +997,9 @@
 
     for (i = 0; i < NCH(n); i++) {
         d = ast_for_decorator(c, CHILD(n, i));
-            if (!d)
-                return NULL;
-            asdl_seq_SET(decorator_seq, i, d);
+        if (!d)
+            return NULL;
+        asdl_seq_SET(decorator_seq, i, d);
     }
     return decorator_seq;
 }
@@ -1027,7 +1027,7 @@
     if (TYPE(CHILD(n, name_i+2)) == RARROW) {
         returns = ast_for_expr(c, CHILD(n, name_i + 3));
         if (!returns)
-                return NULL;
+            return NULL;
         name_i += 2;
     }
     body = ast_for_suite(c, CHILD(n, name_i + 3));
@@ -2136,11 +2136,10 @@
                 return NULL;
             }
             e = ast_for_testlist(c, ch);
-
-            /* set context to assign */
             if (!e)
               return NULL;
 
+            /* set context to assign */
             if (!set_context(c, e, Store, CHILD(n, i)))
               return NULL;
 
@@ -2960,6 +2959,8 @@
 
     REQ(n, with_item);
     context_expr = ast_for_expr(c, CHILD(n, 0));
+    if (!context_expr)
+        return NULL;
     if (NCH(n) == 3) {
         optional_vars = ast_for_expr(c, CHILD(n, 2));
 

Modified: python/branches/pep-0384/Python/bltinmodule.c
==============================================================================
--- python/branches/pep-0384/Python/bltinmodule.c	(original)
+++ python/branches/pep-0384/Python/bltinmodule.c	Fri Aug 27 21:11:11 2010
@@ -893,24 +893,21 @@
     }
     v = PyObject_GetAttr(v, name);
     if (v == NULL) {
-        if (!PyErr_ExceptionMatches(PyExc_Exception))
-            return NULL;
-        else {
+        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
             PyErr_Clear();
-            Py_INCREF(Py_False);
-            return Py_False;
+            Py_RETURN_FALSE;
         }
+        return NULL;
     }
     Py_DECREF(v);
-    Py_INCREF(Py_True);
-    return Py_True;
+    Py_RETURN_TRUE;
 }
 
 PyDoc_STRVAR(hasattr_doc,
 "hasattr(object, name) -> bool\n\
 \n\
 Return whether the object has an attribute with the given name.\n\
-(This is done by calling getattr(object, name) and catching exceptions.)");
+(This is done by calling getattr(object, name) and catching AttributeError.)");
 
 
 static PyObject *

Modified: python/branches/pep-0384/Python/ceval.c
==============================================================================
--- python/branches/pep-0384/Python/ceval.c	(original)
+++ python/branches/pep-0384/Python/ceval.c	Fri Aug 27 21:11:11 2010
@@ -840,11 +840,24 @@
    -fno-crossjumping).
 */
 
-#if defined(USE_COMPUTED_GOTOS) && defined(DYNAMIC_EXECUTION_PROFILE)
+#ifdef DYNAMIC_EXECUTION_PROFILE
 #undef USE_COMPUTED_GOTOS
+#define USE_COMPUTED_GOTOS 0
+#endif
+
+#ifdef HAVE_COMPUTED_GOTOS
+    #ifndef USE_COMPUTED_GOTOS
+    #define USE_COMPUTED_GOTOS 1
+    #endif
+#else
+    #if defined(USE_COMPUTED_GOTOS) && USE_COMPUTED_GOTOS
+    #error "Computed gotos are not supported on this compiler."
+    #endif
+    #undef USE_COMPUTED_GOTOS
+    #define USE_COMPUTED_GOTOS 0
 #endif
 
-#ifdef USE_COMPUTED_GOTOS
+#if USE_COMPUTED_GOTOS
 /* Import the static jump table */
 #include "opcode_targets.h"
 
@@ -990,7 +1003,7 @@
 
 */
 
-#if defined(DYNAMIC_EXECUTION_PROFILE) || defined(USE_COMPUTED_GOTOS)
+#if defined(DYNAMIC_EXECUTION_PROFILE) || USE_COMPUTED_GOTOS
 #define PREDICT(op)             if (0) goto PRED_##op
 #define PREDICTED(op)           PRED_##op:
 #define PREDICTED_WITH_ARG(op)  PRED_##op:
@@ -1200,7 +1213,12 @@
     lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
 #endif
 #if defined(Py_DEBUG) || defined(LLTRACE)
-    filename = _PyUnicode_AsString(co->co_filename);
+    {
+        PyObject *error_type, *error_value, *error_traceback;
+        PyErr_Fetch(&error_type, &error_value, &error_traceback);
+        filename = _PyUnicode_AsString(co->co_filename);
+        PyErr_Restore(error_type, error_value, error_traceback);
+    }
 #endif
 
     why = WHY_NOT;
@@ -2838,7 +2856,7 @@
             oparg = oparg<<16 | NEXTARG();
             goto dispatch_opcode;
 
-#ifdef USE_COMPUTED_GOTOS
+#if USE_COMPUTED_GOTOS
         _unknown_opcode:
 #endif
         default:

Modified: python/branches/pep-0384/Python/ceval_gil.h
==============================================================================
--- python/branches/pep-0384/Python/ceval_gil.h	(original)
+++ python/branches/pep-0384/Python/ceval_gil.h	Fri Aug 27 21:11:11 2010
@@ -106,7 +106,6 @@
 #define COND_INIT(cond) \
     if (pthread_cond_init(&cond, NULL)) { \
         Py_FatalError("pthread_cond_init(" #cond ") failed"); };
-#define COND_RESET(cond)
 #define COND_SIGNAL(cond) \
     if (pthread_cond_signal(&cond)) { \
         Py_FatalError("pthread_cond_signal(" #cond ") failed"); };
@@ -141,64 +140,120 @@
 
 #include <windows.h>
 
-#define MUTEX_T HANDLE
-#define MUTEX_INIT(mut) \
-    if (!(mut = CreateMutex(NULL, FALSE, NULL))) { \
-        Py_FatalError("CreateMutex(" #mut ") failed"); };
+#define MUTEX_T CRITICAL_SECTION
+#define MUTEX_INIT(mut) do { \
+    if (!(InitializeCriticalSectionAndSpinCount(&(mut), 4000))) \
+        Py_FatalError("CreateMutex(" #mut ") failed"); \
+} while (0)
+#define MUTEX_FINI(mut) \
+    DeleteCriticalSection(&(mut))
 #define MUTEX_LOCK(mut) \
-    if (WaitForSingleObject(mut, INFINITE) != WAIT_OBJECT_0) { \
-        Py_FatalError("WaitForSingleObject(" #mut ") failed"); };
+    EnterCriticalSection(&(mut))
 #define MUTEX_UNLOCK(mut) \
-    if (!ReleaseMutex(mut)) { \
-        Py_FatalError("ReleaseMutex(" #mut ") failed"); };
+    LeaveCriticalSection(&(mut))
 
-/* We emulate condition variables with events. It is sufficient here.
-   WaitForMultipleObjects() allows the event to be caught and the mutex
-   to be taken atomically.
-   As for SignalObjectAndWait(), its semantics are unfortunately a bit
-   more foggy. Many sources on the Web define it as atomically releasing
-   the first object while starting to wait on the second, but MSDN states
-   it is *not* atomic...
-
-   In any case, the emulation here is tailored for our particular use case.
-   For example, we don't care how many threads are woken up when a condition
-   gets signalled. Generic emulations of the pthread_cond_* API using
+/* We emulate condition variables with a semaphore.
+   We use a Semaphore rather than an auto-reset event, because although
+   an auto-resent event might appear to solve the lost-wakeup bug (race
+   condition between releasing the outer lock and waiting) because it
+   maintains state even though a wait hasn't happened, there is still
+   a lost wakeup problem if more than one thread are interrupted in the
+   critical place.  A semaphore solves that.
+   Because it is ok to signal a condition variable with no one
+   waiting, we need to keep track of the number of
+   waiting threads.  Otherwise, the semaphore's state could rise
+   without bound.
+
+   Generic emulations of the pthread_cond_* API using
    Win32 functions can be found on the Web.
    The following read can be edificating (or not):
    http://www.cse.wustl.edu/~schmidt/win32-cv-1.html
 */
-#define COND_T HANDLE
+typedef struct COND_T
+{
+    HANDLE sem;    /* the semaphore */
+    int n_waiting; /* how many are unreleased */
+} COND_T;
+
+__inline static void _cond_init(COND_T *cond)
+{
+    /* A semaphore with a large max value,  The positive value
+     * is only needed to catch those "lost wakeup" events and
+     * race conditions when a timed wait elapses.
+     */
+    if (!(cond->sem = CreateSemaphore(NULL, 0, 1000, NULL)))
+        Py_FatalError("CreateSemaphore() failed");
+    cond->n_waiting = 0;
+}
+
+__inline static void _cond_fini(COND_T *cond)
+{
+    BOOL ok = CloseHandle(cond->sem);
+    if (!ok)
+        Py_FatalError("CloseHandle() failed");
+}
+
+__inline static void _cond_wait(COND_T *cond, MUTEX_T *mut)
+{
+    ++cond->n_waiting;
+    MUTEX_UNLOCK(*mut);
+    /* "lost wakeup bug" would occur if the caller were interrupted here,
+     * but we are safe because we are using a semaphore wich has an internal
+     * count.
+     */
+    if (WaitForSingleObject(cond->sem, INFINITE) == WAIT_FAILED)
+        Py_FatalError("WaitForSingleObject() failed");
+    MUTEX_LOCK(*mut);
+}
+
+__inline static int _cond_timed_wait(COND_T *cond, MUTEX_T *mut,
+                              int us)
+{
+    DWORD r;
+    ++cond->n_waiting;
+    MUTEX_UNLOCK(*mut);
+    r = WaitForSingleObject(cond->sem, us / 1000);
+    if (r == WAIT_FAILED)
+        Py_FatalError("WaitForSingleObject() failed");
+    MUTEX_LOCK(*mut);
+    if (r == WAIT_TIMEOUT)
+        --cond->n_waiting;
+        /* Here we have a benign race condition with _cond_signal.  If the
+         * wait operation has timed out, but before we can acquire the
+         * mutex again to decrement n_waiting, a thread holding the mutex
+         * still sees a positive n_waiting value and may call
+         * ReleaseSemaphore and decrement n_waiting.
+         * This will cause n_waiting to be decremented twice.
+         * This is benign, though, because ReleaseSemaphore will also have
+         * been called, leaving the semaphore state positive.  We may
+         * thus end up with semaphore in state 1, and n_waiting == -1, and
+         * the next time someone calls _cond_wait(), that thread will
+         * pass right through, decrementing the semaphore state and
+         * incrementing n_waiting, thus correcting the extra _cond_signal.
+         */
+    return r == WAIT_TIMEOUT;
+}
+
+__inline static void _cond_signal(COND_T  *cond) {
+    /* NOTE: This must be called with the mutex held */
+    if (cond->n_waiting > 0) {
+        if (!ReleaseSemaphore(cond->sem, 1, NULL))
+            Py_FatalError("ReleaseSemaphore() failed");
+        --cond->n_waiting;
+    }
+}
+
 #define COND_INIT(cond) \
-    /* auto-reset, non-signalled */ \
-    if (!(cond = CreateEvent(NULL, FALSE, FALSE, NULL))) { \
-        Py_FatalError("CreateMutex(" #cond ") failed"); };
-#define COND_RESET(cond) \
-    if (!ResetEvent(cond)) { \
-        Py_FatalError("ResetEvent(" #cond ") failed"); };
+    _cond_init(&(cond))
+#define COND_FINI(cond) \
+    _cond_fini(&(cond))
 #define COND_SIGNAL(cond) \
-    if (!SetEvent(cond)) { \
-        Py_FatalError("SetEvent(" #cond ") failed"); };
+    _cond_signal(&(cond))
 #define COND_WAIT(cond, mut) \
-    { \
-        if (SignalObjectAndWait(mut, cond, INFINITE, FALSE) != WAIT_OBJECT_0) \
-            Py_FatalError("SignalObjectAndWait(" #mut ", " #cond") failed"); \
-        MUTEX_LOCK(mut); \
-    }
-#define COND_TIMED_WAIT(cond, mut, microseconds, timeout_result) \
-    { \
-        DWORD r; \
-        HANDLE objects[2] = { cond, mut }; \
-        MUTEX_UNLOCK(mut); \
-        r = WaitForMultipleObjects(2, objects, TRUE, microseconds / 1000); \
-        if (r == WAIT_TIMEOUT) { \
-            MUTEX_LOCK(mut); \
-            timeout_result = 1; \
-        } \
-        else if (r != WAIT_OBJECT_0) \
-            Py_FatalError("WaitForSingleObject(" #cond ") failed"); \
-        else \
-            timeout_result = 0; \
-    }
+    _cond_wait(&(cond), &(mut))
+#define COND_TIMED_WAIT(cond, mut, us, timeout_result) do { \
+    (timeout_result) = _cond_timed_wait(&(cond), &(mut), us); \
+} while (0)
 
 #else
 
@@ -282,7 +337,6 @@
                the GIL and drop it again, and reset the condition
                before we even had a chance to wait for it. */
             COND_WAIT(switch_cond, switch_mutex);
-            COND_RESET(switch_cond);
 	}
         MUTEX_UNLOCK(switch_mutex);
     }
@@ -301,7 +355,6 @@
     if (!_Py_atomic_load_relaxed(&gil_locked))
         goto _ready;
     
-    COND_RESET(gil_cond);
     while (_Py_atomic_load_relaxed(&gil_locked)) {
         int timed_out = 0;
         unsigned long saved_switchnum;

Modified: python/branches/pep-0384/Python/getargs.c
==============================================================================
--- python/branches/pep-0384/Python/getargs.c	(original)
+++ python/branches/pep-0384/Python/getargs.c	Fri Aug 27 21:11:11 2010
@@ -105,15 +105,7 @@
 {
     va_list lva;
 
-#ifdef VA_LIST_IS_ARRAY
-    memcpy(lva, va, sizeof(va_list));
-#else
-#ifdef __va_copy
-    __va_copy(lva, va);
-#else
-    lva = va;
-#endif
-#endif
+        Py_VA_COPY(lva, va);
 
     return vgetargs1(args, format, &lva, 0);
 }
@@ -123,15 +115,7 @@
 {
     va_list lva;
 
-#ifdef VA_LIST_IS_ARRAY
-    memcpy(lva, va, sizeof(va_list));
-#else
-#ifdef __va_copy
-    __va_copy(lva, va);
-#else
-    lva = va;
-#endif
-#endif
+        Py_VA_COPY(lva, va);
 
     return vgetargs1(args, format, &lva, FLAG_SIZE_T);
 }
@@ -1246,13 +1230,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 +1260,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";
@@ -1389,15 +1360,7 @@
         return 0;
     }
 
-#ifdef VA_LIST_IS_ARRAY
-    memcpy(lva, va, sizeof(va_list));
-#else
-#ifdef __va_copy
-    __va_copy(lva, va);
-#else
-    lva = va;
-#endif
-#endif
+        Py_VA_COPY(lva, va);
 
     retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0);
     return retval;
@@ -1421,15 +1384,7 @@
         return 0;
     }
 
-#ifdef VA_LIST_IS_ARRAY
-    memcpy(lva, va, sizeof(va_list));
-#else
-#ifdef __va_copy
-    __va_copy(lva, va);
-#else
-    lva = va;
-#endif
-#endif
+        Py_VA_COPY(lva, va);
 
     retval = vgetargskeywords(args, keywords, format,
                               kwlist, &lva, FLAG_SIZE_T);

Modified: python/branches/pep-0384/Python/getcopyright.c
==============================================================================
--- python/branches/pep-0384/Python/getcopyright.c	(original)
+++ python/branches/pep-0384/Python/getcopyright.c	Fri Aug 27 21:11:11 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/pep-0384/Python/getversion.c
==============================================================================
--- python/branches/pep-0384/Python/getversion.c	(original)
+++ python/branches/pep-0384/Python/getversion.c	Fri Aug 27 21:11:11 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/pep-0384/Python/import.c
==============================================================================
--- python/branches/pep-0384/Python/import.c	(original)
+++ python/branches/pep-0384/Python/import.c	Fri Aug 27 21:11:11 2010
@@ -1790,22 +1790,6 @@
     return fdp;
 }
 
-/* Helpers for main.c
- *  Find the source file corresponding to a named module
- */
-struct filedescr *
-_PyImport_FindModule(const char *name, PyObject *path, char *buf,
-            size_t buflen, FILE **p_fp, PyObject **p_loader)
-{
-    return find_module((char *) name, (char *) name, path,
-                       buf, buflen, p_fp, p_loader);
-}
-
-PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
-{
-    return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
-}
-
 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
  * The arguments here are tricky, best shown by example:
  *    /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
@@ -1960,8 +1944,75 @@
 #endif
 }
 
+/* Call _wfopen() on Windows, or fopen() otherwise. Return the new file
+   object on success, or NULL if the file cannot be open or (if
+   PyErr_Occurred()) on unicode error */
+
+FILE*
+_Py_fopen(PyObject *unicode, const char *mode)
+{
+#ifdef MS_WINDOWS
+    wchar_t path[MAXPATHLEN+1];
+    wchar_t wmode[10];
+    Py_ssize_t len;
+    int usize;
+
+    len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
+    if (len == -1)
+        return NULL;
+    path[len] = L'\0';
+
+    usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
+    if (usize == 0)
+        return NULL;
+
+    return _wfopen(path, wmode);
+#else
+    FILE *f;
+    PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
+    if (bytes == NULL)
+        return NULL;
+    f = fopen(PyBytes_AS_STRING(bytes), mode);
+    Py_DECREF(bytes);
+    return f;
+#endif
+}
 
 #ifdef HAVE_STAT
+
+/* Call _wstat() on Windows, or stat() otherwise. Only fill st_mode
+   attribute on Windows. Return 0 on success, -1 on stat error or (if
+   PyErr_Occurred()) unicode error. */
+
+int
+_Py_stat(PyObject *unicode, struct stat *statbuf)
+{
+#ifdef MS_WINDOWS
+    wchar_t path[MAXPATHLEN+1];
+    Py_ssize_t len;
+    int err;
+    struct _stat wstatbuf;
+
+    len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
+    if (len == -1)
+        return -1;
+    path[len] = L'\0';
+
+    err = _wstat(path, &wstatbuf);
+    if (!err)
+        statbuf->st_mode = wstatbuf.st_mode;
+    return err;
+#else
+    int ret;
+    PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
+    if (bytes == NULL)
+        return -1;
+    ret = stat(PyBytes_AS_STRING(bytes), statbuf);
+    Py_DECREF(bytes);
+    return ret;
+#endif
+}
+
 /* Helper to look for __init__.py or __init__.py[co] in potential package */
 static int
 find_init_module(char *buf)
@@ -2013,15 +2064,52 @@
 
 static int init_builtin(char *); /* Forward */
 
+static PyObject*
+load_builtin(char *name, char *pathname, int type)
+{
+    PyObject *m, *modules;
+    int err;
+
+    if (pathname != NULL && pathname[0] != '\0')
+        name = pathname;
+
+    if (type == C_BUILTIN)
+        err = init_builtin(name);
+    else
+        err = PyImport_ImportFrozenModule(name);
+    if (err < 0)
+        return NULL;
+    if (err == 0) {
+        PyErr_Format(PyExc_ImportError,
+                "Purported %s module %.200s not found",
+                type == C_BUILTIN ?
+                "builtin" : "frozen",
+                name);
+        return NULL;
+    }
+
+    modules = PyImport_GetModuleDict();
+    m = PyDict_GetItemString(modules, name);
+    if (m == NULL) {
+        PyErr_Format(
+                PyExc_ImportError,
+                "%s module %.200s not properly initialized",
+                type == C_BUILTIN ?
+                "builtin" : "frozen",
+                name);
+        return NULL;
+    }
+    Py_INCREF(m);
+    return m;
+}
+
 /* Load an external module using the default search path and return
    its module object WITH INCREMENTED REFERENCE COUNT */
 
 static PyObject *
 load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
 {
-    PyObject *modules;
     PyObject *m;
-    int err;
 
     /* First check that there's an open file (if we need one)  */
     switch (type) {
@@ -2057,34 +2145,7 @@
 
     case C_BUILTIN:
     case PY_FROZEN:
-        if (pathname != NULL && pathname[0] != '\0')
-            name = pathname;
-        if (type == C_BUILTIN)
-            err = init_builtin(name);
-        else
-            err = PyImport_ImportFrozenModule(name);
-        if (err < 0)
-            return NULL;
-        if (err == 0) {
-            PyErr_Format(PyExc_ImportError,
-                         "Purported %s module %.200s not found",
-                         type == C_BUILTIN ?
-                                    "builtin" : "frozen",
-                         name);
-            return NULL;
-        }
-        modules = PyImport_GetModuleDict();
-        m = PyDict_GetItemString(modules, name);
-        if (m == NULL) {
-            PyErr_Format(
-                PyExc_ImportError,
-                "%s module %.200s not properly initialized",
-                type == C_BUILTIN ?
-                    "builtin" : "frozen",
-                name);
-            return NULL;
-        }
-        Py_INCREF(m);
+        m = load_builtin(name, pathname, type);
         break;
 
     case IMP_HOOK: {
@@ -3613,56 +3674,70 @@
 static int
 NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
 {
-    char *path;
-    Py_ssize_t pathlen;
+#ifndef MS_WINDOWS
+    PyObject *path;
+    struct stat statbuf;
+    int rv;
 
     if (!_PyArg_NoKeywords("NullImporter()", kwds))
         return -1;
 
-    if (!PyArg_ParseTuple(args, "es:NullImporter",
-                          Py_FileSystemDefaultEncoding, &path))
+    if (!PyArg_ParseTuple(args, "O&:NullImporter",
+                          PyUnicode_FSConverter, &path))
         return -1;
 
-    pathlen = strlen(path);
-    if (pathlen == 0) {
-        PyMem_Free(path);
+    if (PyBytes_GET_SIZE(path) == 0) {
+        Py_DECREF(path);
         PyErr_SetString(PyExc_ImportError, "empty pathname");
         return -1;
-    } else {
-#ifndef MS_WINDOWS
-        struct stat statbuf;
-        int rv;
+    }
 
-        rv = stat(path, &statbuf);
-        PyMem_Free(path);
-        if (rv == 0) {
-            /* it exists */
-            if (S_ISDIR(statbuf.st_mode)) {
-                /* it's a directory */
-                PyErr_SetString(PyExc_ImportError,
-                                "existing directory");
-                return -1;
-            }
+    rv = stat(PyBytes_AS_STRING(path), &statbuf);
+    Py_DECREF(path);
+    if (rv == 0) {
+        /* it exists */
+        if (S_ISDIR(statbuf.st_mode)) {
+            /* it's a directory */
+            PyErr_SetString(PyExc_ImportError, "existing directory");
+            return -1;
         }
+    }
 #else /* MS_WINDOWS */
-        DWORD rv;
-        /* see issue1293 and issue3677:
-         * stat() on Windows doesn't recognise paths like
-         * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
-         */
-        rv = GetFileAttributesA(path);
-        PyMem_Free(path);
-        if (rv != INVALID_FILE_ATTRIBUTES) {
-            /* it exists */
-            if (rv & FILE_ATTRIBUTE_DIRECTORY) {
-                /* it's a directory */
-                PyErr_SetString(PyExc_ImportError,
-                                "existing directory");
-                return -1;
-            }
+    PyObject *pathobj;
+    DWORD rv;
+    wchar_t path[MAXPATHLEN+1];
+    Py_ssize_t len;
+
+    if (!_PyArg_NoKeywords("NullImporter()", kwds))
+        return -1;
+
+    if (!PyArg_ParseTuple(args, "U:NullImporter",
+                          &pathobj))
+        return -1;
+
+    if (PyUnicode_GET_SIZE(pathobj) == 0) {
+        PyErr_SetString(PyExc_ImportError, "empty pathname");
+        return -1;
+    }
+
+    len = PyUnicode_AsWideChar((PyUnicodeObject*)pathobj,
+                               path, sizeof(path) / sizeof(path[0]));
+    if (len == -1)
+        return -1;
+    /* see issue1293 and issue3677:
+     * stat() on Windows doesn't recognise paths like
+     * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
+     */
+    rv = GetFileAttributesW(path);
+    if (rv != INVALID_FILE_ATTRIBUTES) {
+        /* it exists */
+        if (rv & FILE_ATTRIBUTE_DIRECTORY) {
+            /* it's a directory */
+            PyErr_SetString(PyExc_ImportError, "existing directory");
+            return -1;
         }
-#endif
     }
+#endif
     return 0;
 }
 

Modified: python/branches/pep-0384/Python/modsupport.c
==============================================================================
--- python/branches/pep-0384/Python/modsupport.c	(original)
+++ python/branches/pep-0384/Python/modsupport.c	Fri Aug 27 21:11:11 2010
@@ -456,15 +456,7 @@
     int n = countformat(f, '\0');
     va_list lva;
 
-#ifdef VA_LIST_IS_ARRAY
-    memcpy(lva, va, sizeof(va_list));
-#else
-#ifdef __va_copy
-    __va_copy(lva, va);
-#else
-    lva = va;
-#endif
-#endif
+        Py_VA_COPY(lva, va);
 
     if (n < 0)
         return NULL;

Modified: python/branches/pep-0384/Python/peephole.c
==============================================================================
--- python/branches/pep-0384/Python/peephole.c	(original)
+++ python/branches/pep-0384/Python/peephole.c	Fri Aug 27 21:11:11 2010
@@ -159,13 +159,16 @@
             return 0;
     }
     if (newconst == NULL) {
-        PyErr_Clear();
+        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
+            PyErr_Clear();
         return 0;
     }
     size = PyObject_Size(newconst);
-    if (size == -1)
+    if (size == -1) {
+        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
+            return 0;
         PyErr_Clear();
-    else if (size > 20) {
+    } else if (size > 20) {
         Py_DECREF(newconst);
         return 0;
     }
@@ -219,7 +222,8 @@
             return 0;
     }
     if (newconst == NULL) {
-        PyErr_Clear();
+        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
+            PyErr_Clear();
         return 0;
     }
 

Modified: python/branches/pep-0384/Python/pythonrun.c
==============================================================================
--- python/branches/pep-0384/Python/pythonrun.c	(original)
+++ python/branches/pep-0384/Python/pythonrun.c	Fri Aug 27 21:11:11 2010
@@ -134,18 +134,13 @@
     return flag;
 }
 
-#if defined(HAVE_LANGINFO_H) && defined(CODESET)
 static char*
-get_codeset(void)
+get_codec_name(const char *encoding)
 {
-    char* codeset, *name_str;
+    char *name_utf8, *name_str;
     PyObject *codec, *name = NULL;
 
-    codeset = nl_langinfo(CODESET);
-    if (!codeset || codeset[0] == '\0')
-        return NULL;
-
-    codec = _PyCodec_Lookup(codeset);
+    codec = _PyCodec_Lookup(encoding);
     if (!codec)
         goto error;
 
@@ -154,18 +149,34 @@
     if (!name)
         goto error;
 
-    name_str = _PyUnicode_AsString(name);
+    name_utf8 = _PyUnicode_AsString(name);
     if (name == NULL)
         goto error;
-    codeset = strdup(name_str);
+    name_str = strdup(name_utf8);
     Py_DECREF(name);
-    return codeset;
+    if (name_str == NULL) {
+        PyErr_NoMemory();
+        return NULL;
+    }
+    return name_str;
 
 error:
     Py_XDECREF(codec);
     Py_XDECREF(name);
     return NULL;
 }
+
+#if defined(HAVE_LANGINFO_H) && defined(CODESET)
+static char*
+get_codeset(void)
+{
+    char* codeset = nl_langinfo(CODESET);
+    if (!codeset || codeset[0] == '\0') {
+        PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
+        return NULL;
+    }
+    return get_codec_name(codeset);
+}
 #endif
 
 void
@@ -206,6 +217,11 @@
         Py_FatalError("Py_Initialize: can't make first thread");
     (void) PyThreadState_Swap(tstate);
 
+    /* auto-thread-state API, if available */
+#ifdef WITH_THREAD
+    _PyGILState_Init(interp, tstate);
+#endif /* WITH_THREAD */
+
     _Py_ReadyTypes();
 
     if (!_PyFrame_Init())
@@ -268,6 +284,8 @@
     /* Initialize _warnings. */
     _PyWarnings_Init();
 
+    _PyTime_Init();
+
     initfsencoding();
 
     if (install_sigs)
@@ -286,11 +304,6 @@
         Py_FatalError(
             "Py_Initialize: can't initialize sys standard streams");
 
-    /* auto-thread-state API, if available */
-#ifdef WITH_THREAD
-    _PyGILState_Init(interp, tstate);
-#endif /* WITH_THREAD */
-
     if (!Py_NoSiteFlag)
         initsite(); /* Module site */
 }
@@ -318,7 +331,7 @@
     if (fout != NULL && fout != Py_None) {
         tmp = PyObject_CallMethod(fout, "flush", "");
         if (tmp == NULL)
-            PyErr_Clear();
+            PyErr_WriteUnraisable(fout);
         else
             Py_DECREF(tmp);
     }
@@ -402,6 +415,9 @@
     while (PyGC_Collect() > 0)
         /* nothing */;
 #endif
+    /* We run this while most interpreter state is still alive, so that
+       debug information can be printed out */
+    _PyGC_Fini();
 
     /* Destroy all modules */
     PyImport_Cleanup();
@@ -701,25 +717,35 @@
 {
     PyObject *codec;
 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
-    char *codeset;
+    char *codeset = NULL;
 
     if (Py_FileSystemDefaultEncoding == NULL) {
-        /* On Unix, set the file system encoding according to the
-           user's preference, if the CODESET names a well-known
-           Python codec, and Py_FileSystemDefaultEncoding isn't
-           initialized by other means. Also set the encoding of
-           stdin and stdout if these are terminals.  */
-        codeset = get_codeset();
+        const char *env_encoding = Py_GETENV("PYTHONFSENCODING");
+        if (env_encoding != NULL) {
+            codeset = get_codec_name(env_encoding);
+            if (!codeset) {
+                fprintf(stderr, "PYTHONFSENCODING is not a valid encoding:\n");
+                PyErr_Print();
+            }
+        }
+        if (!codeset) {
+            /* On Unix, set the file system encoding according to the
+               user's preference, if the CODESET names a well-known
+               Python codec, and Py_FileSystemDefaultEncoding isn't
+               initialized by other means. Also set the encoding of
+               stdin and stdout if these are terminals.  */
+            codeset = get_codeset();
+        }
         if (codeset != NULL) {
             Py_FileSystemDefaultEncoding = codeset;
             Py_HasFileSystemDefaultEncoding = 0;
             return;
+        } else {
+            fprintf(stderr, "Unable to get the locale encoding:\n");
+            PyErr_Print();
         }
 
-        PyErr_Clear();
-        fprintf(stderr,
-                "Unable to get the locale encoding: "
-                "fallback to utf-8\n");
+        fprintf(stderr, "Unable to get the filesystem encoding: fallback to utf-8\n");
         Py_FileSystemDefaultEncoding = "utf-8";
         Py_HasFileSystemDefaultEncoding = 1;
     }

Modified: python/branches/pep-0384/Python/sysmodule.c
==============================================================================
--- python/branches/pep-0384/Python/sysmodule.c	(original)
+++ python/branches/pep-0384/Python/sysmodule.c	Fri Aug 27 21:11:11 2010
@@ -1723,6 +1723,10 @@
 }
 #endif
 
+#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
+  (argc > 0 && argv0 != NULL && \
+   wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
+  
 void
 PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
 {
@@ -1747,7 +1751,7 @@
         wchar_t link[MAXPATHLEN+1];
         wchar_t argv0copy[2*MAXPATHLEN+1];
         int nr = 0;
-        if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0)
+        if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
             nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
         if (nr > 0) {
             /* It's a symlink */
@@ -1772,7 +1776,7 @@
         }
 #endif /* HAVE_READLINK */
 #if SEP == '\\' /* Special case for MS filename syntax */
-        if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) {
+        if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
             wchar_t *q;
 #if defined(MS_WINDOWS) && !defined(MS_WINCE)
             /* This code here replaces the first element in argv with the full
@@ -1798,7 +1802,7 @@
             }
         }
 #else /* All other filename syntaxes */
-        if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) {
+        if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
 #if defined(HAVE_REALPATH)
             if (_wrealpath(argv0, fullpath)) {
                 argv0 = fullpath;
@@ -1834,18 +1838,14 @@
    PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
 
 static int
-sys_pyfile_write(const char *text, PyObject *file)
+sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
 {
-    PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL;
+    PyObject *writer = NULL, *args = NULL, *result = NULL;
     int err;
 
     if (file == NULL)
         return -1;
 
-    unicode = PyUnicode_FromString(text);
-    if (unicode == NULL)
-        goto error;
-
     writer = PyObject_GetAttrString(file, "write");
     if (writer == NULL)
         goto error;
@@ -1865,13 +1865,29 @@
 error:
     err = -1;
 finally:
-    Py_XDECREF(unicode);
     Py_XDECREF(writer);
     Py_XDECREF(args);
     Py_XDECREF(result);
     return err;
 }
 
+static int
+sys_pyfile_write(const char *text, PyObject *file)
+{
+    PyObject *unicode = NULL;
+    int err;
+
+    if (file == NULL)
+        return -1;
+
+    unicode = PyUnicode_FromString(text);
+    if (unicode == NULL)
+        return -1;
+
+    err = sys_pyfile_write_unicode(unicode, file);
+    Py_DECREF(unicode);
+    return err;
+}
 
 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
    Adapted from code submitted by Just van Rossum.
@@ -1884,8 +1900,8 @@
       no exceptions are raised.
 
       PyErr_CheckSignals() is not called to avoid the execution of the Python
-      signal handlers: they may raise a new exception whereas mywrite() ignores
-      all exceptions.
+      signal handlers: they may raise a new exception whereas sys_write()
+      ignores all exceptions.
 
       Both take a printf-style format string as their first argument followed
       by a variable length argument list determined by the format string.
@@ -1902,7 +1918,7 @@
  */
 
 static void
-mywrite(char *name, FILE *fp, const char *format, va_list va)
+sys_write(char *name, FILE *fp, const char *format, va_list va)
 {
     PyObject *file;
     PyObject *error_type, *error_value, *error_traceback;
@@ -1918,10 +1934,8 @@
     }
     if (written < 0 || (size_t)written >= sizeof(buffer)) {
         const char *truncated = "... truncated";
-        if (sys_pyfile_write(truncated, file) != 0) {
-            PyErr_Clear();
+        if (sys_pyfile_write(truncated, file) != 0)
             fputs(truncated, fp);
-        }
     }
     PyErr_Restore(error_type, error_value, error_traceback);
 }
@@ -1932,7 +1946,7 @@
     va_list va;
 
     va_start(va, format);
-    mywrite("stdout", stdout, format, va);
+    sys_write("stdout", stdout, format, va);
     va_end(va);
 }
 
@@ -1942,6 +1956,48 @@
     va_list va;
 
     va_start(va, format);
-    mywrite("stderr", stderr, format, va);
+    sys_write("stderr", stderr, format, va);
+    va_end(va);
+}
+
+static void
+sys_format(char *name, FILE *fp, const char *format, va_list va)
+{
+    PyObject *file, *message;
+    PyObject *error_type, *error_value, *error_traceback;
+    char *utf8;
+
+    PyErr_Fetch(&error_type, &error_value, &error_traceback);
+    file = PySys_GetObject(name);
+    message = PyUnicode_FromFormatV(format, va);
+    if (message != NULL) {
+        if (sys_pyfile_write_unicode(message, file) != 0) {
+            PyErr_Clear();
+            utf8 = _PyUnicode_AsString(message);
+            if (utf8 != NULL)
+                fputs(utf8, fp);
+        }
+        Py_DECREF(message);
+    }
+    PyErr_Restore(error_type, error_value, error_traceback);
+}
+
+void
+PySys_FormatStdout(const char *format, ...)
+{
+    va_list va;
+
+    va_start(va, format);
+    sys_format("stdout", stdout, format, va);
+    va_end(va);
+}
+
+void
+PySys_FormatStderr(const char *format, ...)
+{
+    va_list va;
+
+    va_start(va, format);
+    sys_format("stderr", stderr, format, va);
     va_end(va);
 }

Modified: python/branches/pep-0384/README
==============================================================================
--- python/branches/pep-0384/README	(original)
+++ python/branches/pep-0384/README	Fri Aug 27 21:11:11 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/pep-0384/Tools/README
==============================================================================
--- python/branches/pep-0384/Tools/README	(original)
+++ python/branches/pep-0384/Tools/README	Fri Aug 27 21:11:11 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/pep-0384/Tools/buildbot/external-common.bat
==============================================================================
--- python/branches/pep-0384/Tools/buildbot/external-common.bat	(original)
+++ python/branches/pep-0384/Tools/buildbot/external-common.bat	Fri Aug 27 21:11:11 2010
@@ -14,7 +14,7 @@
 @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
+ at rem 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 +27,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/pep-0384/Tools/framer/framer/bases.py
==============================================================================
--- python/branches/pep-0384/Tools/framer/framer/bases.py	(original)
+++ python/branches/pep-0384/Tools/framer/framer/bases.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/framer/framer/template.py
==============================================================================
--- python/branches/pep-0384/Tools/framer/framer/template.py	(original)
+++ python/branches/pep-0384/Tools/framer/framer/template.py	Fri Aug 27 21:11:11 2010
@@ -76,7 +76,7 @@
 
 module_init_start = """\
 PyMODINIT_FUNC
-init%(ModuleName)s(void)
+PyInit_%(ModuleName)s(void)
 {
         PyObject *mod;
 

Modified: python/branches/pep-0384/Tools/freeze/freeze.py
==============================================================================
--- python/branches/pep-0384/Tools/freeze/freeze.py	(original)
+++ python/branches/pep-0384/Tools/freeze/freeze.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/freeze/makeconfig.py
==============================================================================
--- python/branches/pep-0384/Tools/freeze/makeconfig.py	(original)
+++ python/branches/pep-0384/Tools/freeze/makeconfig.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/gdb/libpython.py
==============================================================================
--- python/branches/pep-0384/Tools/gdb/libpython.py	(original)
+++ python/branches/pep-0384/Tools/gdb/libpython.py	Fri Aug 27 21:11:11 2010
@@ -88,6 +88,13 @@
     # threshold in case the data was corrupted
     return xrange(safety_limit(val))
 
+def write_unicode(file, text):
+    # Write a byte or unicode string to file. Unicode strings are encoded to
+    # ENCODING encoding with 'backslashreplace' error handler to avoid
+    # UnicodeEncodeError.
+    if isinstance(text, unicode):
+        text = text.encode(ENCODING, 'backslashreplace')
+    file.write(text)
 
 class StringTruncated(RuntimeError):
     pass
@@ -1360,7 +1367,8 @@
         if self.is_evalframeex():
             pyop = self.get_pyop()
             if pyop:
-                sys.stdout.write('#%i %s\n' % (self.get_index(), pyop.get_truncated_repr(MAX_OUTPUT_LEN)))
+                line = pyop.get_truncated_repr(MAX_OUTPUT_LEN)
+                write_unicode(sys.stdout, '#%i %s\n' % (self.get_index(), line))
                 sys.stdout.write(pyop.current_line())
             else:
                 sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())

Modified: python/branches/pep-0384/Tools/msi/msi.py
==============================================================================
--- python/branches/pep-0384/Tools/msi/msi.py	(original)
+++ python/branches/pep-0384/Tools/msi/msi.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/msi/msilib.py
==============================================================================
--- python/branches/pep-0384/Tools/msi/msilib.py	(original)
+++ python/branches/pep-0384/Tools/msi/msilib.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/msi/uuids.py
==============================================================================
--- python/branches/pep-0384/Tools/msi/uuids.py	(original)
+++ python/branches/pep-0384/Tools/msi/uuids.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/pynche/ChipViewer.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/ChipViewer.py	(original)
+++ python/branches/pep-0384/Tools/pynche/ChipViewer.py	Fri Aug 27 21:11:11 2010
@@ -13,7 +13,7 @@
 selected and nearest ChipWidgets.
 """
 
-from Tkinter import *
+from tkinter import *
 import ColorDB
 
 

Modified: python/branches/pep-0384/Tools/pynche/DetailsViewer.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/DetailsViewer.py	(original)
+++ python/branches/pep-0384/Tools/pynche/DetailsViewer.py	Fri Aug 27 21:11:11 2010
@@ -52,7 +52,7 @@
 Shift + Right == +25
 """
 
-from Tkinter import *
+from tkinter import *
 
 STOP = 'Stop'
 WRAP = 'Wrap Around'

Modified: python/branches/pep-0384/Tools/pynche/ListViewer.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/ListViewer.py	(original)
+++ python/branches/pep-0384/Tools/pynche/ListViewer.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/pynche/PyncheWidget.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/PyncheWidget.py	(original)
+++ python/branches/pep-0384/Tools/pynche/PyncheWidget.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/pynche/StripViewer.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/StripViewer.py	(original)
+++ python/branches/pep-0384/Tools/pynche/StripViewer.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/pynche/Switchboard.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/Switchboard.py	(original)
+++ python/branches/pep-0384/Tools/pynche/Switchboard.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/pynche/TextViewer.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/TextViewer.py	(original)
+++ python/branches/pep-0384/Tools/pynche/TextViewer.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/pynche/TypeinViewer.py
==============================================================================
--- python/branches/pep-0384/Tools/pynche/TypeinViewer.py	(original)
+++ python/branches/pep-0384/Tools/pynche/TypeinViewer.py	Fri Aug 27 21:11:11 2010
@@ -12,7 +12,7 @@
 you must hit Return or Tab to select the color.
 """
 
-from Tkinter import *
+from tkinter import *
 
 
 

Modified: python/branches/pep-0384/Tools/scripts/2to3
==============================================================================
--- python/branches/pep-0384/Tools/scripts/2to3	(original)
+++ python/branches/pep-0384/Tools/scripts/2to3	Fri Aug 27 21:11:11 2010
@@ -1,6 +1,5 @@
 #!/usr/bin/env python
-from lib2to3.main import main
 import sys
-import os
+from lib2to3.main import main
 
 sys.exit(main("lib2to3.fixes"))

Modified: python/branches/pep-0384/Tools/scripts/README
==============================================================================
--- python/branches/pep-0384/Tools/scripts/README	(original)
+++ python/branches/pep-0384/Tools/scripts/README	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/byext.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/byext.py	(original)
+++ python/branches/pep-0384/Tools/scripts/byext.py	Fri Aug 27 21:11:11 2010
@@ -1,10 +1,11 @@
-#! /usr/bin/env python3.0
+#! /usr/bin/env python3
 
 """Show file statistics by extension."""
 
 import os
 import sys
 
+
 class Stats:
 
     def __init__(self):
@@ -28,12 +29,11 @@
             sys.stderr.write("Can't list %s: %s\n" % (dir, err))
             self.addstats("<dir>", "unlistable", 1)
             return
-        names.sort()
-        for name in names:
+        for name in sorted(names):
             if name.startswith(".#"):
-                continue # Skip CVS temp files
+                continue  # Skip CVS temp files
             if name.endswith("~"):
-                continue# Skip Emacs backup files
+                continue  # Skip Emacs backup files
             full = os.path.join(dir, name)
             if os.path.islink(full):
                 self.addstats("<lnk>", "links", 1)
@@ -46,26 +46,25 @@
         head, ext = os.path.splitext(filename)
         head, base = os.path.split(filename)
         if ext == base:
-            ext = "" # E.g. .cvsignore is deemed not to have an extension
+            ext = ""  # E.g. .cvsignore is deemed not to have an extension
         ext = os.path.normcase(ext)
         if not ext:
             ext = "<none>"
         self.addstats(ext, "files", 1)
         try:
-            f = open(filename, "rb")
+            with open(filename, "rb") as f:
+                data = f.read()
         except IOError as err:
             sys.stderr.write("Can't open %s: %s\n" % (filename, err))
             self.addstats(ext, "unopenable", 1)
             return
-        data = f.read()
-        f.close()
         self.addstats(ext, "bytes", len(data))
         if b'\0' in data:
             self.addstats(ext, "binary", 1)
             return
         if not data:
             self.addstats(ext, "empty", 1)
-        #self.addstats(ext, "chars", len(data))
+        # self.addstats(ext, "chars", len(data))
         lines = str(data, "latin-1").splitlines()
         self.addstats(ext, "lines", len(lines))
         del lines
@@ -105,17 +104,20 @@
         for ext in exts:
             self.stats[ext]["ext"] = ext
         cols.insert(0, "ext")
+
         def printheader():
             for col in cols:
                 print("%*s" % (colwidth[col], col), end=' ')
             print()
+
         printheader()
         for ext in exts:
             for col in cols:
                 value = self.stats[ext].get(col, "")
                 print("%*s" % (colwidth[col], value), end=' ')
             print()
-        printheader() # Another header at the bottom
+        printheader()  # Another header at the bottom
+
 
 def main():
     args = sys.argv[1:]
@@ -125,5 +127,6 @@
     s.statargs(args)
     s.report()
 
+
 if __name__ == "__main__":
     main()

Deleted: python/branches/pep-0384/Tools/scripts/checkappend.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/checkappend.py	Fri Aug 27 21:11:11 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()

Modified: python/branches/pep-0384/Tools/scripts/checkpyc.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/checkpyc.py	(original)
+++ python/branches/pep-0384/Tools/scripts/checkpyc.py	Fri Aug 27 21:11:11 2010
@@ -7,14 +7,17 @@
 from stat import ST_MTIME
 import imp
 
+# PEP 3147 compatibility (PYC Repository Directories)
+cache_from_source = (imp.cache_from_source if hasattr(imp, 'get_tag') else
+                     lambda path: path + 'c')
+
+
 def main():
-    silent = 0
-    verbose = 0
-    if sys.argv[1:]:
-        if sys.argv[1] == '-v':
-            verbose = 1
-        elif sys.argv[1] == '-s':
-            silent = 1
+    if len(sys.argv) > 1:
+        verbose = (sys.argv[1] == '-v')
+        silent = (sys.argv[1] == '-s')
+    else:
+        verbose = silent = False
     MAGIC = imp.get_magic()
     if not silent:
         print('Using MAGIC word', repr(MAGIC))
@@ -26,9 +29,8 @@
             continue
         if not silent:
             print('Checking ', repr(dirname), '...')
-        names.sort()
-        for name in names:
-            if name[-3:] == '.py':
+        for name in sorted(names):
+            if name.endswith('.py'):
                 name = os.path.join(dirname, name)
                 try:
                     st = os.stat(name)
@@ -37,30 +39,31 @@
                     continue
                 if verbose:
                     print('Check', repr(name), '...')
-                name_c = name + 'c'
+                name_c = cache_from_source(name)
                 try:
-                    f = open(name_c, 'r')
+                    with open(name_c, 'rb') as f:
+                        magic_str = f.read(4)
+                        mtime_str = f.read(4)
                 except IOError:
                     print('Cannot open', repr(name_c))
                     continue
-                magic_str = f.read(4)
-                mtime_str = f.read(4)
-                f.close()
                 if magic_str != MAGIC:
                     print('Bad MAGIC word in ".pyc" file', end=' ')
                     print(repr(name_c))
                     continue
                 mtime = get_long(mtime_str)
-                if mtime == 0 or mtime == -1:
+                if mtime in {0, -1}:
                     print('Bad ".pyc" file', repr(name_c))
                 elif mtime != st[ST_MTIME]:
                     print('Out-of-date ".pyc" file', end=' ')
                     print(repr(name_c))
 
+
 def get_long(s):
     if len(s) != 4:
         return -1
-    return ord(s[0]) + (ord(s[1])<<8) + (ord(s[2])<<16) + (ord(s[3])<<24)
+    return s[0] + (s[1] << 8) + (s[2] << 16) + (s[3] << 24)
+
 
 if __name__ == '__main__':
     main()

Deleted: python/branches/pep-0384/Tools/scripts/classfix.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/classfix.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/cvsfiles.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/cvsfiles.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/logmerge.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/logmerge.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/methfix.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/methfix.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/patchcheck.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/patchcheck.py	(original)
+++ python/branches/pep-0384/Tools/scripts/patchcheck.py	Fri Aug 27 21:11:11 2010
@@ -9,6 +9,7 @@
     """Return 'N file(s)' with the proper plurality on 'file'."""
     return "{} file{}".format(count, "s" if count != 1 else "")
 
+
 def status(message, modal=False, info=None):
     """Decorator to output status info to stdout."""
     def decorated_fxn(fxn):
@@ -21,32 +22,25 @@
             elif info:
                 print(info(result))
             else:
-                if result:
-                    print("yes")
-                else:
-                    print("NO")
+                print("yes" if result else "NO")
             return result
         return call_fxn
     return decorated_fxn
 
+
 @status("Getting the list of files that have been added/changed",
             info=lambda x: n_files_str(len(x)))
 def changed_files():
     """Run ``svn status`` and return a set of files that have been
-    changed/added."""
+    changed/added.
+    """
     cmd = 'svn status --quiet --non-interactive --ignore-externals'
     svn_st = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
     svn_st.wait()
-    output = [x.decode().rstrip() for x in svn_st.stdout.readlines()]
-    files = set()
-    for line in output:
-        if not line[0] in ('A', 'M'):
-            continue
-        line_parts = line.split()
-        path = line_parts[-1]
-        if os.path.isfile(path):
-            files.add(path)
-    return files
+    output = (x.decode().rstrip().rsplit(None, 1)[-1]
+              for x in svn_st.stdout if x[0] in b'AM')
+    return set(path for path in output if os.path.isfile(path))
+
 
 def report_modified_files(file_paths):
     count = len(file_paths)
@@ -58,6 +52,7 @@
             lines.append("  {}".format(path))
         return "\n".join(lines)
 
+
 @status("Fixing whitespace", info=report_modified_files)
 def normalize_whitespace(file_paths):
     """Make sure that the whitespace for .py files have been normalized."""
@@ -68,16 +63,19 @@
             fixed.append(path)
     return fixed
 
+
 @status("Docs modified", modal=True)
 def docs_modified(file_paths):
     """Report if any file in the Doc directory has been changed."""
     return bool(file_paths)
 
+
 @status("Misc/ACKS updated", modal=True)
 def credit_given(file_paths):
     """Check if Misc/ACKS has been changed."""
     return 'Misc/ACKS' in file_paths
 
+
 @status("Misc/NEWS updated", modal=True)
 def reported_news(file_paths):
     """Check if Misc/NEWS has been changed."""

Modified: python/branches/pep-0384/Tools/scripts/reindent-rst.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/reindent-rst.py	(original)
+++ python/branches/pep-0384/Tools/scripts/reindent-rst.py	Fri Aug 27 21:11:11 2010
@@ -6,7 +6,7 @@
 
 import sys, re, shutil
 
-ws_re = re.compile(r'\s+(\r?\n)$')
+ws_re = re.compile(br'\s+(\r?\n)$')
 
 def main(argv=sys.argv):
     rv = 0
@@ -14,7 +14,7 @@
         try:
             with open(filename, 'rb') as f:
                 lines = f.readlines()
-            new_lines = [ws_re.sub(r'\1', line) for line in lines]
+            new_lines = [ws_re.sub(br'\1', line) for line in lines]
             if new_lines != lines:
                 print('Fixing %s...' % filename)
             shutil.copyfile(filename, filename + '.bak')

Modified: python/branches/pep-0384/Tools/scripts/reindent.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/reindent.py	(original)
+++ python/branches/pep-0384/Tools/scripts/reindent.py	Fri Aug 27 21:11:11 2010
@@ -42,26 +42,27 @@
 __version__ = "1"
 
 import tokenize
-import os, shutil
+import os
+import shutil
 import sys
 
-verbose    = 0
-recurse    = 0
-dryrun     = 0
+verbose = False
+recurse = False
+dryrun = False
 makebackup = True
 
+
 def usage(msg=None):
-    if msg is not None:
-        print(msg, file=sys.stderr)
-    print(__doc__, file=sys.stderr)
+    if msg is None:
+        msg = __doc__
+    print(msg, file=sys.stderr)
+
 
 def errprint(*args):
-    sep = ""
-    for arg in args:
-        sys.stderr.write(sep + str(arg))
-        sep = " "
+    sys.stderr.write(" ".join(str(arg) for arg in args))
     sys.stderr.write("\n")
 
+
 def main():
     import getopt
     global verbose, recurse, dryrun, makebackup
@@ -73,13 +74,13 @@
         return
     for o, a in opts:
         if o in ('-d', '--dryrun'):
-            dryrun += 1
+            dryrun = True
         elif o in ('-r', '--recurse'):
-            recurse += 1
+            recurse = True
         elif o in ('-n', '--nobackup'):
             makebackup = False
         elif o in ('-v', '--verbose'):
-            verbose += 1
+            verbose = True
         elif o in ('-h', '--help'):
             usage()
             return
@@ -91,6 +92,7 @@
     for arg in args:
         check(arg)
 
+
 def check(file):
     if os.path.isdir(file) and not os.path.islink(file):
         if verbose:
@@ -108,13 +110,12 @@
     if verbose:
         print("checking", file, "...", end=' ')
     try:
-        f = open(file)
+        with open(file) as f:
+            r = Reindenter(f)
     except IOError as msg:
         errprint("%s: I/O Error: %s" % (file, str(msg)))
         return
 
-    r = Reindenter(f)
-    f.close()
     if r.run():
         if verbose:
             print("changed.")
@@ -126,9 +127,8 @@
                 shutil.copyfile(file, bak)
                 if verbose:
                     print("backed up", file, "to", bak)
-            f = open(file, "w")
-            r.write(f)
-            f.close()
+            with open(file, "w") as f:
+                r.write(f)
             if verbose:
                 print("wrote new", file)
         return True
@@ -137,6 +137,7 @@
             print("unchanged.")
         return False
 
+
 def _rstrip(line, JUNK='\n \t'):
     """Return line stripped of trailing spaces, tabs, newlines.
 
@@ -146,10 +147,11 @@
     """
 
     i = len(line)
-    while i > 0 and line[i-1] in JUNK:
+    while i > 0 and line[i - 1] in JUNK:
         i -= 1
     return line[:i]
 
+
 class Reindenter:
 
     def __init__(self, f):
@@ -192,9 +194,9 @@
         # we see a line with *something* on it.
         i = stats[0][0]
         after.extend(lines[1:i])
-        for i in range(len(stats)-1):
+        for i in range(len(stats) - 1):
             thisstmt, thislevel = stats[i]
-            nextstmt = stats[i+1][0]
+            nextstmt = stats[i + 1][0]
             have = getlspace(lines[thisstmt])
             want = thislevel * 4
             if want < 0:
@@ -206,7 +208,7 @@
                     want = have2want.get(have, -1)
                     if want < 0:
                         # Then it probably belongs to the next real stmt.
-                        for j in range(i+1, len(stats)-1):
+                        for j in range(i + 1, len(stats) - 1):
                             jline, jlevel = stats[j]
                             if jlevel >= 0:
                                 if have == getlspace(lines[jline]):
@@ -216,11 +218,11 @@
                                            # comment like this one,
                         # in which case we should shift it like its base
                         # line got shifted.
-                        for j in range(i-1, -1, -1):
+                        for j in range(i - 1, -1, -1):
                             jline, jlevel = stats[j]
                             if jlevel >= 0:
-                                want = have + getlspace(after[jline-1]) - \
-                                       getlspace(lines[jline])
+                                want = have + (getlspace(after[jline - 1]) -
+                                               getlspace(lines[jline]))
                                 break
                     if want < 0:
                         # Still no luck -- leave it alone.
@@ -295,6 +297,7 @@
             if line:   # not endmarker
                 self.stats.append((slinecol[0], self.level))
 
+
 # Count number of leading blanks.
 def getlspace(line):
     i, n = 0, len(line)
@@ -302,5 +305,6 @@
         i += 1
     return i
 
+
 if __name__ == '__main__':
     main()

Modified: python/branches/pep-0384/Tools/scripts/rgrep.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/rgrep.py	(original)
+++ python/branches/pep-0384/Tools/scripts/rgrep.py	Fri Aug 27 21:11:11 2010
@@ -9,8 +9,9 @@
 import re
 import getopt
 
+
 def main():
-    bufsize = 64*1024
+    bufsize = 64 * 1024
     reflags = 0
     opts, args = getopt.getopt(sys.argv[1:], "i")
     for o, a in opts:
@@ -24,11 +25,11 @@
     try:
         prog = re.compile(pattern, reflags)
     except re.error as msg:
-        usage("error in regular expression: %s" % str(msg))
+        usage("error in regular expression: %s" % msg)
     try:
         f = open(filename)
     except IOError as msg:
-        usage("can't open %s: %s" % (repr(filename), str(msg)), 1)
+        usage("can't open %r: %s" % (filename, msg), 1)
     f.seek(0, 2)
     pos = f.tell()
     leftover = None
@@ -49,16 +50,17 @@
             del lines[0]
         else:
             leftover = None
-        lines.reverse()
-        for line in lines:
+        for line in reversed(lines):
             if prog.search(line):
                 print(line)
 
+
 def usage(msg, code=2):
     sys.stdout = sys.stderr
     print(msg)
     print(__doc__)
     sys.exit(code)
 
+
 if __name__ == '__main__':
     main()

Modified: python/branches/pep-0384/Tools/scripts/serve.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/serve.py	(original)
+++ python/branches/pep-0384/Tools/scripts/serve.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/setup.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/setup.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/suff.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/suff.py	(original)
+++ python/branches/pep-0384/Tools/scripts/suff.py	Fri Aug 27 21:11:11 2010
@@ -6,24 +6,21 @@
 
 import sys
 
+
 def main():
     files = sys.argv[1:]
     suffixes = {}
     for filename in files:
         suff = getsuffix(filename)
-        if suff not in suffixes:
-            suffixes[suff] = []
-        suffixes[suff].append(filename)
-    keys = sorted(suffixes.keys())
-    for suff in keys:
-        print(repr(suff), len(suffixes[suff]))
+        suffixes.setdefault(suff, []).append(filename)
+    for suff, filenames in sorted(suffixes.items()):
+        print(repr(suff), len(filenames))
+
 
 def getsuffix(filename):
-    suff = ''
-    for i in range(len(filename)):
-        if filename[i] == '.':
-            suff = filename[i:]
-    return suff
+    name, sep, suff = filename.rpartition('.')
+    return sep + suff if sep else ''
+
 
 if __name__ == '__main__':
     main()

Modified: python/branches/pep-0384/Tools/scripts/svneol.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/svneol.py	(original)
+++ python/branches/pep-0384/Tools/scripts/svneol.py	Fri Aug 27 21:11:11 2010
@@ -32,9 +32,12 @@
 
 import re
 import os
+import sys
+import subprocess
+
 
 def propfiles(root, fn):
-    default = os.path.join(root, ".svn", "props", fn+".svn-work")
+    default = os.path.join(root, ".svn", "props", fn + ".svn-work")
     try:
         format = int(open(os.path.join(root, ".svn", "format")).read().strip())
     except IOError:
@@ -42,12 +45,13 @@
     if format in (8, 9):
         # In version 8 and 9, committed props are stored in prop-base, local
         # modifications in props
-        return [os.path.join(root, ".svn", "prop-base", fn+".svn-base"),
-                os.path.join(root, ".svn", "props", fn+".svn-work")]
-    raise ValueError, "Unknown repository format"
+        return [os.path.join(root, ".svn", "prop-base", fn + ".svn-base"),
+                os.path.join(root, ".svn", "props", fn + ".svn-work")]
+    raise ValueError("Unknown repository format")
+
 
 def proplist(root, fn):
-    "Return a list of property names for file fn in directory root"
+    """Return a list of property names for file fn in directory root."""
     result = []
     for path in propfiles(root, fn):
         try:
@@ -56,7 +60,7 @@
             # no properties file: not under version control,
             # or no properties set
             continue
-        while 1:
+        while True:
             # key-value pairs, of the form
             # K <length>
             # <keyname>NL
@@ -79,13 +83,32 @@
         f.close()
     return result
 
+
+def set_eol_native(path):
+    cmd = 'svn propset svn:eol-style native "{}"'.format(path)
+    propset = subprocess.Popen(cmd, shell=True)
+    propset.wait()
+
+
 possible_text_file = re.compile(r"\.([hc]|py|txt|sln|vcproj)$").search
 
-for root, dirs, files in os.walk('.'):
-    if '.svn' in dirs:
-        dirs.remove('.svn')
-    for fn in files:
-        if possible_text_file(fn):
+
+def main():
+    for arg in sys.argv[1:] or [os.curdir]:
+        if os.path.isfile(arg):
+            root, fn = os.path.split(arg)
             if 'svn:eol-style' not in proplist(root, fn):
-                path = os.path.join(root, fn)
-                os.system('svn propset svn:eol-style native "%s"' % path)
+                set_eol_native(arg)
+        elif os.path.isdir(arg):
+            for root, dirs, files in os.walk(arg):
+                if '.svn' in dirs:
+                    dirs.remove('.svn')
+                for fn in files:
+                    if possible_text_file(fn):
+                        if 'svn:eol-style' not in proplist(root, fn):
+                            path = os.path.join(root, fn)
+                            set_eol_native(path)
+
+
+if __name__ == '__main__':
+    main()

Modified: python/branches/pep-0384/Tools/scripts/untabify.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/untabify.py	(original)
+++ python/branches/pep-0384/Tools/scripts/untabify.py	Fri Aug 27 21:11:11 2010
@@ -6,6 +6,7 @@
 import sys
 import getopt
 
+
 def main():
     tabsize = 8
     try:
@@ -23,11 +24,11 @@
     for filename in args:
         process(filename, tabsize)
 
+
 def process(filename, tabsize):
     try:
-        f = open(filename)
-        text = f.read()
-        f.close()
+        with open(filename) as f:
+            text = f.read()
     except IOError as msg:
         print("%r: I/O error: %s" % (filename, msg))
         return
@@ -43,10 +44,10 @@
         os.rename(filename, backup)
     except os.error:
         pass
-    f = open(filename, "w")
-    f.write(newtext)
-    f.close()
+    with open(filename, "w") as f:
+        f.write(newtext)
     print(filename)
 
+
 if __name__ == '__main__':
     main()

Modified: python/branches/pep-0384/Tools/scripts/win_add2path.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/win_add2path.py	(original)
+++ python/branches/pep-0384/Tools/scripts/win_add2path.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/scripts/xxci.py
==============================================================================
--- python/branches/pep-0384/Tools/scripts/xxci.py	Fri Aug 27 21:11:11 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/pep-0384/Tools/unicode/makeunicodedata.py
==============================================================================
--- python/branches/pep-0384/Tools/unicode/makeunicodedata.py	(original)
+++ python/branches/pep-0384/Tools/unicode/makeunicodedata.py	Fri Aug 27 21:11:11 2010
@@ -28,7 +28,7 @@
 import sys
 
 SCRIPT = sys.argv[0]
-VERSION = "2.6"
+VERSION = "3.2"
 
 # The Unicode Database
 UNIDATA_VERSION = "5.2.0"
@@ -479,7 +479,7 @@
     print('/* Returns the numeric value as double for Unicode characters', file=fp)
     print(' * having this property, -1.0 otherwise.', file=fp)
     print(' */', file=fp)
-    print('double _PyUnicode_ToNumeric(Py_UNICODE ch)', file=fp)
+    print('double _PyUnicode_ToNumeric(Py_UCS4 ch)', file=fp)
     print('{', file=fp)
     print('    switch (ch) {', file=fp)
     for value, codepoints in numeric_items:
@@ -488,21 +488,10 @@
         parts = [repr(float(part)) for part in parts]
         value = '/'.join(parts)
 
-        haswide = False
-        hasnonewide = False
         codepoints.sort()
         for codepoint in codepoints:
-            if codepoint < 0x10000:
-                hasnonewide = True
-            if codepoint >= 0x10000 and not haswide:
-                print('#ifdef Py_UNICODE_WIDE', file=fp)
-                haswide = True
             print('    case 0x%04X:' % (codepoint,), file=fp)
-        if haswide and hasnonewide:
-            print('#endif', file=fp)
         print('        return (double) %s;' % (value,), file=fp)
-        if haswide and not hasnonewide:
-            print('#endif', file=fp)
     print('    }', file=fp)
     print('    return -1.0;', file=fp)
     print('}', file=fp)
@@ -512,27 +501,16 @@
     print("/* Returns 1 for Unicode characters having the bidirectional", file=fp)
     print(" * type 'WS', 'B' or 'S' or the category 'Zs', 0 otherwise.", file=fp)
     print(" */", file=fp)
-    print('int _PyUnicode_IsWhitespace(register const Py_UNICODE ch)', file=fp)
+    print('int _PyUnicode_IsWhitespace(register const Py_UCS4 ch)', file=fp)
     print('{', file=fp)
     print('#ifdef WANT_WCTYPE_FUNCTIONS', file=fp)
     print('    return iswspace(ch);', file=fp)
     print('#else', file=fp)
     print('    switch (ch) {', file=fp)
 
-    haswide = False
-    hasnonewide = False
     for codepoint in sorted(spaces):
-        if codepoint < 0x10000:
-            hasnonewide = True
-        if codepoint >= 0x10000 and not haswide:
-            print('#ifdef Py_UNICODE_WIDE', file=fp)
-            haswide = True
         print('    case 0x%04X:' % (codepoint,), file=fp)
-    if haswide and hasnonewide:
-        print('#endif', file=fp)
     print('        return 1;', file=fp)
-    if haswide and not hasnonewide:
-        print('#endif', file=fp)
 
     print('    }', file=fp)
     print('    return 0;', file=fp)
@@ -545,23 +523,12 @@
     print(" * property 'BK', 'CR', 'LF' or 'NL' or having bidirectional", file=fp)
     print(" * type 'B', 0 otherwise.", file=fp)
     print(" */", file=fp)
-    print('int _PyUnicode_IsLinebreak(register const Py_UNICODE ch)', file=fp)
+    print('int _PyUnicode_IsLinebreak(register const Py_UCS4 ch)', file=fp)
     print('{', file=fp)
     print('    switch (ch) {', file=fp)
-    haswide = False
-    hasnonewide = False
     for codepoint in sorted(linebreaks):
-        if codepoint < 0x10000:
-            hasnonewide = True
-        if codepoint >= 0x10000 and not haswide:
-            print('#ifdef Py_UNICODE_WIDE', file=fp)
-            haswide = True
         print('    case 0x%04X:' % (codepoint,), file=fp)
-    if haswide and hasnonewide:
-        print('#endif', file=fp)
     print('        return 1;', file=fp)
-    if haswide and not hasnonewide:
-        print('#endif', file=fp)
 
     print('    }', file=fp)
     print('    return 0;', file=fp)

Modified: python/branches/pep-0384/configure
==============================================================================
--- python/branches/pep-0384/configure	(original)
+++ python/branches/pep-0384/configure	Fri Aug 27 21:11:11 2010
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.in Revision: 82090 .
+# From configure.in Revision: 83580 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.65 for python 3.2.
 #
@@ -1421,8 +1421,9 @@
   --with-libm=STRING      math library
   --with-libc=STRING      C library
   --with-wide-unicode     Use 4-byte Unicode characters (default is 2 bytes)
-  --with-computed-gotos   Use computed gotos / threaded dispatch in evaluation
-                          loop (not available on all compilers)
+  --with(out)-computed-gotos
+                          Use computed gotos in evaluation loop (enabled by
+                          default on supported compilers)
 
 Some influential environment variables:
   CC          C compiler command
@@ -1929,11 +1930,11 @@
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
-	     enum { N = $2 / 2 - 1 };
 int
 main ()
 {
-static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))];
+static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 };
+	     0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))];
 test_array [0] = 0
 
   ;
@@ -1944,11 +1945,11 @@
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
-	        enum { N = $2 / 2 - 1 };
 int
 main ()
 {
-static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1)
+static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 };
+		($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1)
 		 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))];
 test_array [0] = 0
 
@@ -9121,7 +9122,7 @@
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_doc_strings" >&5
 $as_echo "$with_doc_strings" >&6; }
 
-# Check for Python-specific malloc support
+# Check if eval loop should use timestamp counter profiling
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-tsc" >&5
 $as_echo_n "checking for --with-tsc... " >&6; }
 
@@ -13502,6 +13503,49 @@
 
 fi
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports computed gotos" >&5
+$as_echo_n "checking whether $CC supports computed gotos... " >&6; }
+if test "${ac_cv_computed_gotos+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "$cross_compiling" = yes; then :
+  ac_cv_computed_gotos=no
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int main(int argc, char **argv)
+{
+    static void *targets[1] = { &&LABEL1 };
+    goto LABEL2;
+LABEL1:
+    return 0;
+LABEL2:
+    goto *targets[0];
+    return 1;
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  ac_cv_computed_gotos=yes
+else
+  ac_cv_computed_gotos=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_computed_gotos" >&5
+$as_echo "$ac_cv_computed_gotos" >&6; }
+if test "$ac_cv_computed_gotos" = yes
+then
+
+$as_echo "#define HAVE_COMPUTED_GOTOS 1" >>confdefs.h
+
+fi
+
 # Check for --with-computed-gotos
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-computed-gotos" >&5
 $as_echo_n "checking for --with-computed-gotos... " >&6; }
@@ -13509,21 +13553,28 @@
 # Check whether --with-computed-gotos was given.
 if test "${with_computed_gotos+set}" = set; then :
   withval=$with_computed_gotos;
-if test "$withval" != no
+if test "$withval" = yes
 then
 
 $as_echo "#define USE_COMPUTED_GOTOS 1" >>confdefs.h
 
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 $as_echo "yes" >&6; }
-else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
 fi
-else
+if test "$withval" = no
+then
+
+$as_echo "#define USE_COMPUTED_GOTOS 0" >>confdefs.h
+
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no value specified" >&5
+$as_echo "no value specified" >&6; }
+fi
+
 
 
 
@@ -14086,8 +14137,8 @@
 
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 # Files that config.status was made for.
-config_files="$ac_config_files"
-config_headers="$ac_config_headers"
+config_files="`echo $ac_config_files`"
+config_headers="`echo $ac_config_headers`"
 
 _ACEOF
 

Modified: python/branches/pep-0384/configure.in
==============================================================================
--- python/branches/pep-0384/configure.in	(original)
+++ python/branches/pep-0384/configure.in	Fri Aug 27 21:11:11 2010
@@ -2458,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]),[
@@ -4124,20 +4124,50 @@
    wide chars that would be converted.])
 fi
 
+AC_MSG_CHECKING(whether $CC supports computed gotos)
+AC_CACHE_VAL(ac_cv_computed_gotos,
+AC_RUN_IFELSE([AC_LANG_SOURCE([[[
+int main(int argc, char **argv)
+{
+    static void *targets[1] = { &&LABEL1 };
+    goto LABEL2;
+LABEL1:
+    return 0;
+LABEL2:
+    goto *targets[0];
+    return 1;
+}
+]]])],
+[ac_cv_computed_gotos=yes],
+[ac_cv_computed_gotos=no],
+[ac_cv_computed_gotos=no]))
+AC_MSG_RESULT($ac_cv_computed_gotos)
+if test "$ac_cv_computed_gotos" = yes
+then
+  AC_DEFINE(HAVE_COMPUTED_GOTOS, 1,
+  [Define if the C compiler supports computed gotos.])
+fi
+
 # Check for --with-computed-gotos
 AC_MSG_CHECKING(for --with-computed-gotos)
 AC_ARG_WITH(computed-gotos,
-            AS_HELP_STRING([--with-computed-gotos],
-                           [Use computed gotos / threaded dispatch in evaluation loop (not available on all compilers)]),
+            AS_HELP_STRING([--with(out)-computed-gotos],
+                           [Use computed gotos in evaluation loop (enabled by default on supported compilers)]),
 [
-if test "$withval" != no
+if test "$withval" = yes
 then 
   AC_DEFINE(USE_COMPUTED_GOTOS, 1,
   [Define if you want to use computed gotos in ceval.c.]) 
   AC_MSG_RESULT(yes)
-else AC_MSG_RESULT(no)
-fi],
-[AC_MSG_RESULT(no)])
+fi
+if test "$withval" = no
+then 
+  AC_DEFINE(USE_COMPUTED_GOTOS, 0,
+  [Define if you want to use computed gotos in ceval.c.]) 
+  AC_MSG_RESULT(no)
+fi
+],
+[AC_MSG_RESULT(no value specified)])
 
 
 

Modified: python/branches/pep-0384/pyconfig.h.in
==============================================================================
--- python/branches/pep-0384/pyconfig.h.in	(original)
+++ python/branches/pep-0384/pyconfig.h.in	Fri Aug 27 21:11:11 2010
@@ -104,6 +104,9 @@
 /* Define to 1 if you have the `clock' function. */
 #undef HAVE_CLOCK
 
+/* Define if the C compiler supports computed gotos. */
+#undef HAVE_COMPUTED_GOTOS
+
 /* Define to 1 if you have the `confstr' function. */
 #undef HAVE_CONFSTR
 
@@ -1037,7 +1040,7 @@
 /* Define to 1 if your <sys/time.h> declares `struct tm'. */
 #undef TM_IN_SYS_TIME
 
-/* Define if you want to use computed gotos in ceval.c. */
+/* Define to 0 if you don't want to use computed gotos in ceval.c. */
 #undef USE_COMPUTED_GOTOS
 
 /* Enable extensions on AIX 3, Interix.  */

Modified: python/branches/pep-0384/setup.py
==============================================================================
--- python/branches/pep-0384/setup.py	(original)
+++ python/branches/pep-0384/setup.py	Fri Aug 27 21:11:11 2010
@@ -22,6 +22,10 @@
 # This global variable is used to hold the list of modules to be disabled.
 disabled_module_list = []
 
+# File which contains the directory for shared mods (for sys.path fixup
+# when running from the build dir, see Modules/getpath.c)
+_BUILDDIR_COOKIE = "pybuilddir.txt"
+
 def add_dir_to_list(dirlist, dir):
     """Add the directory 'dir' to the list 'dirlist' (at the front) if
     1) 'dir' is not already in 'dirlist'
@@ -224,6 +228,16 @@
             args['compiler_so'] = compiler + ' ' + ccshared + ' ' + cflags
         self.compiler.set_executables(**args)
 
+        # Not only do we write the builddir cookie, but we manually install
+        # the shared modules directory if it isn't already in sys.path.
+        # Otherwise trying to import the extensions after building them
+        # will fail.
+        with open(_BUILDDIR_COOKIE, "wb") as f:
+            f.write(self.build_lib.encode('utf-8', 'surrogateescape'))
+        abs_build_lib = os.path.join(os.getcwd(), self.build_lib)
+        if abs_build_lib not in sys.path:
+            sys.path.append(abs_build_lib)
+
         build_ext.build_extensions(self)
 
         longest = max([len(e.name) for e in self.extensions])
@@ -452,20 +466,14 @@
         # 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"]) )
         # random number generator implemented in C
         exts.append( Extension("_random", ["_randommodule.c"]) )
-        # high-performance collections
-        exts.append( Extension("_collections", ["_collectionsmodule.c"]) )
         # bisect
         exts.append( Extension("_bisect", ["_bisectmodule.c"]) )
         # heapq
         exts.append( Extension("_heapq", ["_heapqmodule.c"]) )
-        # operator.add() and similar goodies
-        exts.append( Extension('operator', ['operator.c']) )
         # C-optimized pickle replacement
         exts.append( Extension("_pickle", ["_pickle.c"]) )
         # atexit
@@ -1639,8 +1647,7 @@
                    '_ctypes/callbacks.c',
                    '_ctypes/callproc.c',
                    '_ctypes/stgdict.c',
-                   '_ctypes/cfield.c',
-                   '_ctypes/malloc_closure.c']
+                   '_ctypes/cfield.c']
         depends = ['_ctypes/ctypes.h']
 
         if sys.platform == 'darwin':


More information about the Python-checkins mailing list