[Python-checkins] r82926 - in python/branches/py3k-cdecimal: Demo/classes/Complex.py Demo/classes/Dates.py Demo/classes/Dbm.py Demo/classes/README Demo/classes/Range.py Demo/classes/Rev.py Demo/classes/Vec.py Demo/embed/Makefile Demo/embed/demo.c Demo/md5test/md5driver.py Demo/parser/test_parser.py Demo/parser/test_unparse.py Demo/parser/unparse.py Doc/Makefile Doc/README.txt Doc/c-api/arg.rst Doc/c-api/datetime.rst Doc/c-api/file.rst Doc/c-api/init.rst Doc/c-api/intro.rst Doc/c-api/number.rst Doc/c-api/unicode.rst Doc/data/refcounts.dat Doc/distutils/apiref.rst Doc/distutils/builtdist.rst Doc/distutils/extending.rst Doc/distutils/setupscript.rst Doc/distutils/sourcedist.rst Doc/documenting/building.rst Doc/documenting/index.rst Doc/documenting/markup.rst Doc/documenting/style.rst Doc/faq/extending.rst Doc/faq/gui.rst Doc/glossary.rst Doc/howto/functional.rst Doc/howto/unicode.rst Doc/library/2to3.rst Doc/library/ast.rst Doc/library/calendar.rst Doc/library/cmath.rst Doc/library/codecs.rst Doc/library/contextlib.rst Doc/library/datetime.rst Doc/library/dis.rst Doc/library/doctest.rst Doc/library/fnmatch.rst Doc/library/functions.rst Doc/library/http.cookiejar.rst Doc/library/http.server.rst Doc/library/importlib.rst Doc/library/logging.rst Doc/library/math.rst Doc/library/multiprocessing.rst Doc/library/os.path.rst Doc/library/os.rst Doc/library/pdb.rst Doc/library/re.rst Doc/library/select.rst Doc/library/socket.rst Doc/library/sqlite3.rst Doc/library/ssl.rst Doc/library/stdtypes.rst Doc/library/string.rst Doc/library/struct.rst Doc/library/subprocess.rst Doc/library/sys.rst Doc/library/sysconfig.rst Doc/library/unittest.rst Doc/library/urllib.parse.rst Doc/library/urllib.request.rst Doc/library/warnings.rst Doc/reference/compound_stmts.rst Doc/reference/datamodel.rst Doc/reference/expressions.rst Doc/reference/introduction.rst Doc/reference/lexical_analysis.rst Doc/tools/sphinxext/indexsidebar.html Doc/tools/sphinxext/pyspecific.py Doc/tutorial/classes.rst Doc/tutorial/controlflow.rst Doc/tutorial/introduction.rst Doc/using/cmdline.rst Doc/using/mac.rst Doc/whatsnew/2.7.rst Doc/whatsnew/3.0.rst Doc/whatsnew/3.2.rst Grammar/Grammar Include/longobject.h Include/pyctype.h Include/structseq.h Include/traceback.h Include/unicodeobject.h Lib/_abcoll.py Lib/_strptime.py Lib/ast.py Lib/contextlib.py Lib/ctypes/__init__.py Lib/ctypes/test/test_callbacks.py Lib/ctypes/test/test_win32.py Lib/decimal.py Lib/dis.py Lib/distutils/command/install.py Lib/distutils/msvc9compiler.py Lib/distutils/tests/test_sdist.py Lib/distutils/unixccompiler.py Lib/email/feedparser.py Lib/email/test/test_email.py Lib/encodings/aliases.py Lib/encodings/cp858.py Lib/fnmatch.py Lib/heapq.py Lib/http/cookiejar.py Lib/idlelib/textView.py Lib/importlib/__init__.py Lib/importlib/_bootstrap.py Lib/importlib/abc.py Lib/importlib/test/benchmark.py Lib/importlib/test/extension/test_case_sensitivity.py Lib/importlib/test/extension/test_finder.py Lib/importlib/test/extension/test_loader.py Lib/importlib/test/extension/test_path_hook.py Lib/importlib/test/import_/test_path.py Lib/importlib/test/regrtest.py Lib/importlib/test/source/test_abc_loader.py Lib/importlib/test/source/test_case_sensitivity.py Lib/importlib/test/source/test_file_loader.py Lib/importlib/test/source/test_finder.py Lib/importlib/test/source/test_path_hook.py Lib/importlib/test/source/test_source_encoding.py Lib/importlib/test/test_abc.py Lib/importlib/test/test_api.py Lib/importlib/test/test_util.py Lib/inspect.py Lib/lib2to3 Lib/lib2to3/fixes/fix_itertools_imports.py Lib/lib2to3/tests/test_fixers.py Lib/logging/config.py Lib/macpath.py Lib/ntpath.py Lib/os2emxpath.py Lib/pdb.doc Lib/pdb.py Lib/pickletools.py Lib/posixpath.py Lib/pydoc.py Lib/site.py Lib/smtpd.py Lib/sndhdr.py Lib/socket.py Lib/subprocess.py Lib/sysconfig.py Lib/tarfile.py Lib/test/decimaltestdata/extra.decTest Lib/test/math_testcases.txt Lib/test/regrtest.py Lib/test/sndhdrdata Lib/test/support.py Lib/test/symlink_support.py Lib/test/test_ast.py Lib/test/test_audioop.py Lib/test/test_calendar.py Lib/test/test_cmath.py Lib/test/test_codeccallbacks.py Lib/test/test_codecs.py Lib/test/test_collections.py Lib/test/test_complex.py Lib/test/test_contextlib.py Lib/test/test_datetime.py Lib/test/test_decimal.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_dis.py Lib/test/test_enumerate.py Lib/test/test_exceptions.py Lib/test/test_extcall.py Lib/test/test_float.py Lib/test/test_fnmatch.py Lib/test/test_gdb.py Lib/test/test_genericpath.py Lib/test/test_getargs2.py Lib/test/test_glob.py Lib/test/test_http_cookiejar.py Lib/test/test_httpservers.py Lib/test/test_imp.py Lib/test/test_import.py Lib/test/test_inspect.py Lib/test/test_iter.py Lib/test/test_keywordonlyarg.py Lib/test/test_logging.py Lib/test/test_math.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_parser.py Lib/test/test_platform.py Lib/test/test_posixpath.py Lib/test/test_property.py Lib/test/test_pyexpat.py Lib/test/test_runpy.py Lib/test/test_shutil.py Lib/test/test_sndhdr.py Lib/test/test_strtod.py Lib/test/test_struct.py Lib/test/test_structseq.py Lib/test/test_subprocess.py Lib/test/test_syntax.py Lib/test/test_sysconfig.py Lib/test/test_tarfile.py Lib/test/test_threaded_import.py Lib/test/test_tokenize.py Lib/test/test_tuple.py Lib/test/test_unicode.py Lib/test/test_unpack.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urlparse.py Lib/test/test_xmlrpc_net.py Lib/unittest/case.py Lib/unittest/test/test_case.py Lib/urllib/parse.py Lib/urllib/request.py Lib/uuid.py Lib/warnings.py Lib/xml/dom/expatbuilder.py Makefile.pre.in Misc/ACKS Misc/NEWS Misc/Vim/vimrc Misc/maintainers.rst Modules/_ctypes/callproc.c Modules/_ctypes/libffi/fficonfig.py.in Modules/_ctypes/libffi_msvc/LICENSE Modules/_ctypes/libffi_msvc/README Modules/_ctypes/libffi_msvc/README.ctypes Modules/_ctypes/libffi_msvc/ffi.c Modules/_ctypes/libffi_msvc/ffi.h Modules/_ctypes/libffi_msvc/ffi_common.h Modules/_ctypes/libffi_msvc/fficonfig.h Modules/_ctypes/libffi_msvc/ffitarget.h Modules/_ctypes/libffi_msvc/prep_cif.c Modules/_ctypes/libffi_msvc/types.c Modules/_ctypes/libffi_msvc/win32.c Modules/_ctypes/libffi_msvc/win64.asm Modules/_io/_iomodule.c Modules/_math.c Modules/_scproxy.c Modules/_ssl.c Modules/_struct.c Modules/_testcapimodule.c Modules/_time.c Modules/_time.h Modules/audioop.c Modules/cmathmodule.c Modules/datetimemodule.c Modules/makesetup Modules/mathmodule.c Modules/parsermodule.c Modules/posixmodule.c Modules/selectmodule.c Modules/timemodule.c Modules/xxmodule.c Objects/abstract.c Objects/bytearrayobject.c Objects/bytes_methods.c Objects/descrobject.c Objects/enumobject.c Objects/exceptions.c Objects/floatobject.c Objects/frameobject.c Objects/memoryobject.c Objects/stringlib/formatter.h Objects/structseq.c Objects/typeobject.c Objects/unicodeobject.c PC/VS8.0/pythoncore.vcproj PCbuild/_ctypes.vcproj PCbuild/pythoncore.vcproj Parser/Python.asdl Parser/asdl_c.py Python/Python-ast.c Python/_warnings.c Python/ast.c Python/ceval.c Python/compile.c Python/getargs.c Python/graminit.c Python/import.c Python/pythonrun.c Python/sysmodule.c Python/traceback.c README Tools/README Tools/gdb/libpython.py Tools/i18n/msgfmt.py Tools/scripts Tools/scripts/patchcheck.py Tools/webchecker configure configure.in setup.py

stefan.krah python-checkins at python.org
Sat Jul 17 12:36:12 CEST 2010


Author: stefan.krah
Date: Sat Jul 17 12:36:09 2010
New Revision: 82926

Log:
Merged revisions 81981,81988-81990,81994,81999-82001,82003-82005,82008,82011,82014-82015,82022,82028,82034-82035,82037-82038,82041,82043,82045,82049,82051,82053,82055,82057,82059,82061,82068,82070-82071,82073,82076,82084,82089-82090,82113-82115,82119,82125,82128,82131,82138,82146,82148,82152,82156,82159,82162-82163,82166,82168,82171,82180-82181,82184-82186,82190,82193-82194,82200,82202,82204,82206,82208,82211,82214,82220,82223,82226,82228,82230-82232,82234,82238,82244,82247,82252,82255,82259,82262-82263,82269-82270,82273,82278,82281,82283,82286,82288-82302,82304-82316,82318,82320-82321,82326,82328,82331,82333,82336,82342-82343,82346-82347,82349,82351,82354,82357-82360,82365,82370-82371,82373,82375-82377,82381,82383-82384,82386-82387,82391-82394,82402,82405,82407,82410,82413,82416-82417,82422,82430,82434,82437-82438,82440,82442-82443,82448,82452,82456,82462,82464-82465,82467-82468,82471-82472,82478,82480-82481,82484-82485,82487-82488,82495,82507,82510,82514-82524,82526-82527,82533,82535,82537-82538,82540-82542,82547,82550-82553,82555,82557-82561,82567,82570,82573,82576-82578,82585,82587,82589,82591,82593-82595,82597,82599-82601,82604,82607,82609-82610,82615,82617,82624-82626,82628-82630,82632-82633,82636-82637,82642,82644,82646-82647,82649-82650,82654,82659,82661-82663,82723-82724,82730-82731,82735,82737,82739,82741,82743-82746,82748-82750,82753,82757-82764,82766-82767,82771,82777,82780,82784-82785,82789-82790,82796,82798-82799,82801,82804-82806,82814,82817-82822,82825,82828,82830-82832,82834-82835,82837-82839,82842-82843,82848-82850,82856-82857,82871-82874,82879,82881,82885,82887,82890,82895,82899,82910,82915,82918-82919,82921-82922 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/branches/py3k

................
  r81981 | alexander.belopolsky | 2010-06-14 16:15:50 +0200 (Mon, 14 Jun 2010) | 3 lines
  
  Issue #5094: The ``datetime`` module now has a simple concrete class
  implementing ``datetime.tzinfo`` interface.
................
  r81988 | alexander.belopolsky | 2010-06-14 19:32:03 +0200 (Mon, 14 Jun 2010) | 1 line
  
  Issue 6280: Tests and simpler implementation for calendar.timegm
................
  r81989 | alexander.belopolsky | 2010-06-14 20:33:19 +0200 (Mon, 14 Jun 2010) | 1 line
  
  Undo r81988 code change leaving added test.
................
  r81990 | brett.cannon | 2010-06-15 00:22:54 +0200 (Tue, 15 Jun 2010) | 5 lines
  
  Switch the __import__ state check from using __builtins__ to builtins to be
  nicer to other VMs.
  
  Thanks to Philip Jenvey for the pointer.
................
  r81994 | mark.dickinson | 2010-06-15 10:42:37 +0200 (Tue, 15 Jun 2010) | 10 lines
  
  Merged revisions 81992 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81992 | mark.dickinson | 2010-06-15 09:33:03 +0100 (Tue, 15 Jun 2010) | 3 lines
    
    Issue #8469:  Further clarifications and improvements to struct module
    documentation.  Thanks Mads Kiilerich.
  ........
................
  r81999 | ronald.oussoren | 2010-06-15 18:05:20 +0200 (Tue, 15 Jun 2010) | 5 lines
  
  Fix for issue #8577: without this patch test_distutils
  will fail when builddir != srcdir (that is, when you
  run configure in a directory that is not the top of
  the source tree).
................
  r82000 | antoine.pitrou | 2010-06-15 19:00:21 +0200 (Tue, 15 Jun 2010) | 3 lines
  
  Fixes to the PyFile_FromFd() doc, by Renato Cunha.
................
  r82001 | antoine.pitrou | 2010-06-15 19:30:16 +0200 (Tue, 15 Jun 2010) | 3 lines
  
  Further refinements to the C file API.
................
  r82003 | alexander.belopolsky | 2010-06-15 20:40:23 +0200 (Tue, 15 Jun 2010) | 1 line
  
  Minor changes to the choice of assert methods
................
  r82004 | alexander.belopolsky | 2010-06-15 21:24:52 +0200 (Tue, 15 Jun 2010) | 1 line
  
  Issue 5094: minor documentation fixes
................
  r82005 | ronald.oussoren | 2010-06-15 23:19:50 +0200 (Tue, 15 Jun 2010) | 3 lines
  
  Fix for buildbot failure in  r81999.
................
  r82008 | r.david.murray | 2010-06-16 01:46:40 +0200 (Wed, 16 Jun 2010) | 9 lines
  
  Merged revisions 81634 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81634 | r.david.murray | 2010-05-31 21:42:41 -0400 (Mon, 31 May 2010) | 2 lines
    
    #7583: clarify discussion of hard tab expansion in doctests.
  ........
................
  r82011 | r.david.murray | 2010-06-16 04:19:40 +0200 (Wed, 16 Jun 2010) | 17 lines
  
  Merged revisions 81675 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81675 | r.david.murray | 2010-06-03 11:43:20 -0400 (Thu, 03 Jun 2010) | 10 lines
    
    #5610: use \Z not $ so we don't eat extra chars when body part ends with \r\n.
    
    If a body part ended with \r\n, feedparser, using '$' to terminate its
    search for the newline, would match on the \r\n, and think that it needed
    to strip two characters in order to account for the line end before the
    boundary.  That made it chop one too many characters off the end of
    the body part.  Using \Z makes the match correct.
    
    Patch and test by Tony Nelson.
  ........
................
  r82014 | r.david.murray | 2010-06-16 14:53:07 +0200 (Wed, 16 Jun 2010) | 20 lines
  
  Blocked revisions 81571,81678 via svnmerge
  
  I'm going to merge 81678 by hand.
  
  ........
    r81571 | victor.stinner | 2010-05-27 18:29:48 -0400 (Thu, 27 May 2010) | 3 lines
    
    Issue #8835: test_support.transient_internet() catchs gaierror(EAI_NONAME) and
    gaierror(EAI_NODATA)
  ........
    r81678 | r.david.murray | 2010-06-03 16:19:25 -0400 (Thu, 03 Jun 2010) | 7 lines
    
    #8889: rewrite transient_internet so we don't use EAI_NODATA on FreeBSD.
    
    FreeBSD doesn't have socket.EAI_NODATA.  I rewrote the routine because
    there's no easy way to conditionally include a context manager in a
    with statement.  As a side benefit, instead of a stack of context
    managers there's now only one.
  ........
................
  r82015 | r.david.murray | 2010-06-16 14:56:31 +0200 (Wed, 16 Jun 2010) | 2 lines
  
  Remove versionadded accidentally introduced by r82008.
................
  r82022 | senthil.kumaran | 2010-06-16 18:41:11 +0200 (Wed, 16 Jun 2010) | 9 lines
  
  Merged revisions 82018 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82018 | senthil.kumaran | 2010-06-16 20:25:31 +0530 (Wed, 16 Jun 2010) | 3 lines
    
    Fix Issue8937 - SimpleHTTPServer should contain usage example
  ........
................
  r82028 | senthil.kumaran | 2010-06-16 19:44:57 +0200 (Wed, 16 Jun 2010) | 9 lines
  
  Merged revisions 82026 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82026 | senthil.kumaran | 2010-06-16 23:07:32 +0530 (Wed, 16 Jun 2010) | 3 lines
    
    Addressing RDM's review comments on the doc change.
  ........
................
  r82034 | alexander.belopolsky | 2010-06-17 00:38:15 +0200 (Thu, 17 Jun 2010) | 6 lines
  
  Issue #9012: "Separate compilation of time and datetime modules."
  Segregated code shared between time and datetime modules into
  Modules/_time.c.  Added a new header file, Modules/_time.h, which
  will be used instead of Include/timefuncs.h for declarations shared
  between time and datetime modules.
................
  r82035 | victor.stinner | 2010-06-17 01:05:06 +0200 (Thu, 17 Jun 2010) | 4 lines
  
  Issue #9012: Add _time.c and _time.h to the Visual Studio project file
  
  Add these new files, added by r82034, to the pythoncore project.
................
  r82037 | victor.stinner | 2010-06-17 01:33:54 +0200 (Thu, 17 Jun 2010) | 4 lines
  
  Issue #850997: mbcs encoding (Windows only) handles errors argument: strict
  mode raises unicode errors. The encoder only supports "strict" and "replace"
  error handlers, the decoder only supports "strict" and "ignore" error handlers.
................
  r82038 | victor.stinner | 2010-06-17 01:48:49 +0200 (Thu, 17 Jun 2010) | 2 lines
  
  Issue #850997: Oops, I forgot the author of the patch: Mark Hammond
................
  r82041 | r.david.murray | 2010-06-17 04:04:29 +0200 (Thu, 17 Jun 2010) | 16 lines
  
  Merged revisions 82039 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82039 | r.david.murray | 2010-06-16 21:36:52 -0400 (Wed, 16 Jun 2010) | 10 lines
    
    #8720: fix inspect regression by teaching getsourcefile about linecache.
    
    The fix for issue 4050 caused a regression:  before that fix, source
    lines in the linecache would eventually be found by inspect.  After the
    fix inspect reports an error earlier, and the source isn't found.
    The fix for the fix is to have getsourcefile look in the linecache for
    the file and return the psuedo-filename if the source is there, just as
    it already returns it if there is a PEP 302 loader.
  ........
................
  r82043 | mark.dickinson | 2010-06-17 14:33:22 +0200 (Thu, 17 Jun 2010) | 6 lines
  
  Issue #9011: Remove buggy and unnecessary 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.  (The peephole
  optimizer already takes care of optimizing this case, so there's no
  lost optimization opportunity here.)
................
  r82045 | r.david.murray | 2010-06-17 15:23:18 +0200 (Thu, 17 Jun 2010) | 5 lines
  
  Don't use os.normcase when the result we are expecting is None.
  
  This worked fine on linux but fails on Windows.  That may or may
  not be a but in normcase.
................
  r82049 | senthil.kumaran | 2010-06-17 18:48:06 +0200 (Thu, 17 Jun 2010) | 9 lines
  
  Merged revisions 82047 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82047 | senthil.kumaran | 2010-06-17 22:08:34 +0530 (Thu, 17 Jun 2010) | 3 lines
    
    Fix Issue4452 - Incorrect docstring of os.setpgrp
  ........
................
  r82051 | mark.dickinson | 2010-06-17 20:24:52 +0200 (Thu, 17 Jun 2010) | 2 lines
  
  Add note about changes to the `round` function between 2.x and 3.x.
................
  r82053 | alexander.belopolsky | 2010-06-17 20:30:34 +0200 (Thu, 17 Jun 2010) | 2 lines
  
  Issue #6641: The datetime.strptime method now supports the %z directive.
................
  r82055 | barry.warsaw | 2010-06-17 20:38:20 +0200 (Thu, 17 Jun 2010) | 2 lines
  
  Typo repair.
................
  r82057 | victor.stinner | 2010-06-17 23:43:33 +0200 (Thu, 17 Jun 2010) | 2 lines
  
  Issue #8203: Fix IDLE Credits dialog: view_file() uses its encoding argument.
................
  r82059 | victor.stinner | 2010-06-18 01:08:50 +0200 (Fri, 18 Jun 2010) | 5 lines
  
  Issue #6543: Write the traceback in the terminal encoding instead of utf-8.
  Fix the encoding of the modules filename.
  
  Reindent also traceback.h, just because I hate tabs :-)
................
  r82061 | victor.stinner | 2010-06-18 01:17:37 +0200 (Fri, 18 Jun 2010) | 2 lines
  
  Issue #6543: Mention the author of the patch, Amaury Forgeot d'Arc
................
  r82068 | senthil.kumaran | 2010-06-18 17:08:18 +0200 (Fri, 18 Jun 2010) | 3 lines
  
  Fix Issue1368368 - prompt_user_passwd() in FancyURLopener masks 401 Unauthorized error page
................
  r82070 | alexander.belopolsky | 2010-06-18 18:22:00 +0200 (Fri, 18 Jun 2010) | 1 line
  
  Fixed a typo in a comment.
................
  r82071 | alexander.belopolsky | 2010-06-18 18:57:49 +0200 (Fri, 18 Jun 2010) | 1 line
  
  Added a new line at the end of the file.
................
  r82073 | alexander.belopolsky | 2010-06-18 20:44:37 +0200 (Fri, 18 Jun 2010) | 4 lines
  
  Issue #6641: Original commit for this issue, r82053, introduced a
  regression making datetime subclass' strptime return datetime rather
  than subclass instances.  Fixed this bug and a few typos.
................
  r82076 | jean-paul.calderone | 2010-06-18 22:03:54 +0200 (Fri, 18 Jun 2010) | 19 lines
  
  Merged revisions 82075 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82075 | jean-paul.calderone | 2010-06-18 16:00:17 -0400 (Fri, 18 Jun 2010) | 12 lines
    
    Revert r60115
    
    This revision introduced quoting for strings containing | based
    on a misunderstanding of the commonly used quoting rules used
    on Windows.
    
    | is interpreted by cmd.exe, not by the MS C runtime argv initializer.
    It only needs to be quoted if it is part of an argument passed through
    cmd.exe.
    
    See issue1300, issue7839, and issue8972.
  ........
................
  r82084 | victor.stinner | 2010-06-19 01:59:45 +0200 (Sat, 19 Jun 2010) | 6 lines
  
  Issue #8939: Improve arg.rst
  
   * Add :ctype: to Py_BEGIN_ALLOW_THREADS and int
   * "s" and "s#" formats of Py_BuildValue(): specify that the Python object type
     is str in the description
................
  r82089 | jean-paul.calderone | 2010-06-19 21:54:48 +0200 (Sat, 19 Jun 2010) | 1 line
  
  merge forward from the python 2.x branch
................
  r82090 | jean-paul.calderone | 2010-06-19 21:58:37 +0200 (Sat, 19 Jun 2010) | 1 line
  
  Revert r82089.  Commit was intended for a branch.
................
  r82113 | benjamin.peterson | 2010-06-20 17:25:14 +0200 (Sun, 20 Jun 2010) | 8 lines
  
  Blocked revisions 82112 via svnmerge
  
  ........
    r82112 | benjamin.peterson | 2010-06-20 10:12:04 -0500 (Sun, 20 Jun 2010) | 1 line
    
    update emacs section
  ........
................
  r82114 | benjamin.peterson | 2010-06-20 17:27:07 +0200 (Sun, 20 Jun 2010) | 1 line
  
  update release schedule url
................
  r82115 | benjamin.peterson | 2010-06-20 17:27:42 +0200 (Sun, 20 Jun 2010) | 1 line
  
  add copyright years
................
  r82119 | mark.dickinson | 2010-06-20 22:01:04 +0200 (Sun, 20 Jun 2010) | 9 lines
  
  Merged revisions 82117 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82117 | mark.dickinson | 2010-06-20 19:50:19 +0100 (Sun, 20 Jun 2010) | 1 line
    
    Merge test_strtod and test_float string-to-float conversion tests.
  ........
................
  r82125 | brett.cannon | 2010-06-21 04:49:35 +0200 (Mon, 21 Jun 2010) | 2 lines
  
  Move over to assertIs.
................
  r82128 | alexander.belopolsky | 2010-06-21 17:21:14 +0200 (Mon, 21 Jun 2010) | 2 lines
  
  Issue #9005: Prevent utctimetuple() from producing year 0 or year 10,000.
................
  r82131 | benjamin.peterson | 2010-06-21 17:37:16 +0200 (Mon, 21 Jun 2010) | 9 lines
  
  Merged revisions 82130 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82130 | benjamin.peterson | 2010-06-21 10:27:46 -0500 (Mon, 21 Jun 2010) | 1 line
    
    fix finding visual studio 2008 on 64 bit #8854
  ........
................
  r82138 | thomas.heller | 2010-06-21 18:00:31 +0200 (Mon, 21 Jun 2010) | 13 lines
  
  Merged revisions 82126-82127 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82126 | thomas.heller | 2010-06-21 16:00:24 +0200 (Mo, 21 Jun 2010) | 1 line
    
    Fix #8959 by reverting revision 80761.
  ........
    r82127 | thomas.heller | 2010-06-21 17:01:18 +0200 (Mo, 21 Jun 2010) | 2 lines
    
    Add tests for problems reported in issue 8959.
  ........
................
  r82146 | senthil.kumaran | 2010-06-22 04:42:52 +0200 (Tue, 22 Jun 2010) | 3 lines
  
  Minor docs issue.
................
  r82148 | senthil.kumaran | 2010-06-22 04:57:23 +0200 (Tue, 22 Jun 2010) | 3 lines
  
  Minor comment formatting.
................
  r82152 | alexander.belopolsky | 2010-06-22 16:07:33 +0200 (Tue, 22 Jun 2010) | 1 line
  
  Added more test cases
................
  r82156 | benjamin.peterson | 2010-06-22 20:11:34 +0200 (Tue, 22 Jun 2010) | 10 lines
  
  Blocked revisions 82155 via svnmerge
  
  ........
    r82155 | benjamin.peterson | 2010-06-22 13:09:02 -0500 (Tue, 22 Jun 2010) | 4 lines
    
    keep UserDict an old-style class
    
    Be generous in abc.py to allow this.
  ........
................
  r82159 | benjamin.peterson | 2010-06-22 21:21:52 +0200 (Tue, 22 Jun 2010) | 9 lines
  
  Merged revisions 82157 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82157 | benjamin.peterson | 2010-06-22 14:16:37 -0500 (Tue, 22 Jun 2010) | 1 line
    
    remove INT_MAX assertions; they can fail with large Py_ssize_t #9058
  ........
................
  r82162 | benjamin.peterson | 2010-06-22 21:52:02 +0200 (Tue, 22 Jun 2010) | 8 lines
  
  Blocked revisions 82161 via svnmerge
  
  ........
    r82161 | benjamin.peterson | 2010-06-22 14:49:47 -0500 (Tue, 22 Jun 2010) | 1 line
    
    bump revision
  ........
................
  r82163 | benjamin.peterson | 2010-06-22 22:02:39 +0200 (Tue, 22 Jun 2010) | 9 lines
  
  Merged revisions 82160 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82160 | benjamin.peterson | 2010-06-22 14:45:51 -0500 (Tue, 22 Jun 2010) | 1 line
    
    spacing nit; this isn't C
  ........
................
  r82166 | benjamin.peterson | 2010-06-22 22:29:32 +0200 (Tue, 22 Jun 2010) | 9 lines
  
  Merged revisions 82165 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82165 | benjamin.peterson | 2010-06-22 15:26:20 -0500 (Tue, 22 Jun 2010) | 1 line
    
    must force gc here
  ........
................
  r82168 | benjamin.peterson | 2010-06-22 22:34:34 +0200 (Tue, 22 Jun 2010) | 9 lines
  
  Merged revisions 82167 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82167 | benjamin.peterson | 2010-06-22 15:32:02 -0500 (Tue, 22 Jun 2010) | 1 line
    
    mark ref counting as impl detail
  ........
................
  r82171 | antoine.pitrou | 2010-06-22 23:49:39 +0200 (Tue, 22 Jun 2010) | 10 lines
  
  Merged revisions 82169 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82169 | antoine.pitrou | 2010-06-22 23:42:05 +0200 (mar., 22 juin 2010) | 4 lines
    
    Fix misindents in compile.c (for Benjamin).
    Of course, whoever used the wrong indentation rules needs to be spanked.
  ........
................
  r82180 | stefan.krah | 2010-06-23 20:35:33 +0200 (Wed, 23 Jun 2010) | 8 lines
  
  Blocked revisions 82177 via svnmerge
  
  ........
    r82177 | stefan.krah | 2010-06-23 20:12:09 +0200 (Wed, 23 Jun 2010) | 3 lines
    
    Issue #8930: Remaining indentation fixes after the Grand Unified Indenting.
  ........
................
  r82181 | stefan.krah | 2010-06-23 20:42:39 +0200 (Wed, 23 Jun 2010) | 3 lines
  
  Issue #8930: Remaining indentation fixes after the Grand Unified Indenting.
................
  r82184 | alexander.belopolsky | 2010-06-23 23:40:15 +0200 (Wed, 23 Jun 2010) | 1 line
  
  Issue #9051: Instances of timezone class can now be pickled.
................
  r82185 | alexander.belopolsky | 2010-06-24 00:29:48 +0200 (Thu, 24 Jun 2010) | 1 line
  
  Test future pickle protocols.  Thanks Antoine Pitrou for suggestion.
................
  r82186 | alexander.belopolsky | 2010-06-24 00:58:49 +0200 (Thu, 24 Jun 2010) | 1 line
  
  Added more test cases
................
  r82190 | benjamin.peterson | 2010-06-24 02:17:03 +0200 (Thu, 24 Jun 2010) | 9 lines
  
  Merged revisions 82189 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82189 | benjamin.peterson | 2010-06-23 19:12:40 -0500 (Wed, 23 Jun 2010) | 1 line
    
    prevent assignment to set literals
  ........
................
  r82193 | stefan.krah | 2010-06-24 12:22:10 +0200 (Thu, 24 Jun 2010) | 10 lines
  
  Blocked revisions 82191 via svnmerge
  
  ........
    r82191 | stefan.krah | 2010-06-24 11:33:05 +0200 (Thu, 24 Jun 2010) | 5 lines
    
    Issue #9020: The Py_IS* macros from pyctype.h should generally only be
    used with signed/unsigned char arguments. For integer arguments, EOF
    has to be handled separately.
  ........
................
  r82194 | stefan.krah | 2010-06-24 12:25:08 +0200 (Thu, 24 Jun 2010) | 3 lines
  
  Add specification for the Py_IS* macros in pyctype.h.
................
  r82200 | victor.stinner | 2010-06-25 00:08:25 +0200 (Fri, 25 Jun 2010) | 3 lines
  
  Issue #8949: "z" format of PyArg_Parse*() functions doesn't accept bytes
  objects, as described in the documentation.
................
  r82202 | victor.stinner | 2010-06-25 00:31:12 +0200 (Fri, 25 Jun 2010) | 2 lines
  
  PyArg_Parse*() functions: factorize code for s/z and u/Z formats
................
  r82204 | antoine.pitrou | 2010-06-25 00:34:04 +0200 (Fri, 25 Jun 2010) | 5 lines
  
  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.
................
  r82206 | victor.stinner | 2010-06-25 00:57:10 +0200 (Fri, 25 Jun 2010) | 2 lines
  
  getbuffer(): release the buffer on error (if the buffer is not contiguous)
................
  r82208 | victor.stinner | 2010-06-25 02:02:38 +0200 (Fri, 25 Jun 2010) | 3 lines
  
  Issue #8850: Remove "w" and "w#" formats from PyArg_Parse*() functions, use
  "w*" format instead. Add tests for "w*" format.
................
  r82211 | antoine.pitrou | 2010-06-25 02:07:34 +0200 (Fri, 25 Jun 2010) | 10 lines
  
  Merged revisions 82210 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82210 | antoine.pitrou | 2010-06-25 02:03:21 +0200 (ven., 25 juin 2010) | 4 lines
    
    Issue #9075: In the ssl module, remove the setting of a `debug` flag
    on an OpenSSL structure.
  ........
................
  r82214 | ezio.melotti | 2010-06-25 12:56:11 +0200 (Fri, 25 Jun 2010) | 1 line
  
  #9018: os.path.normcase() now raises a TypeError if the argument is not str or bytes.
................
  r82220 | benjamin.peterson | 2010-06-25 21:30:21 +0200 (Fri, 25 Jun 2010) | 1 line
  
  only take into account positional arguments count in related error messages
................
  r82223 | mark.dickinson | 2010-06-25 22:22:24 +0200 (Fri, 25 Jun 2010) | 9 lines
  
  Merged revisions 82221 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82221 | mark.dickinson | 2010-06-25 21:19:48 +0100 (Fri, 25 Jun 2010) | 1 line
    
    Fix indentation of Python code example in C comment.
  ........
................
  r82226 | benjamin.peterson | 2010-06-25 22:37:22 +0200 (Fri, 25 Jun 2010) | 9 lines
  
  Merged revisions 82225 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82225 | benjamin.peterson | 2010-06-25 15:34:01 -0500 (Fri, 25 Jun 2010) | 1 line
    
    mark implementation detail as such
  ........
................
  r82228 | benjamin.peterson | 2010-06-25 23:24:10 +0200 (Fri, 25 Jun 2010) | 8 lines
  
  Blocked revisions 82227 via svnmerge
  
  ........
    r82227 | benjamin.peterson | 2010-06-25 16:19:04 -0500 (Fri, 25 Jun 2010) | 1 line
    
    this must be a typo
  ........
................
  r82230 | benjamin.peterson | 2010-06-26 01:02:11 +0200 (Sat, 26 Jun 2010) | 9 lines
  
  Merged revisions 82229 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82229 | benjamin.peterson | 2010-06-25 17:58:47 -0500 (Fri, 25 Jun 2010) | 1 line
    
    mark implementation detail as such
  ........
................
  r82231 | benjamin.peterson | 2010-06-26 01:24:35 +0200 (Sat, 26 Jun 2010) | 1 line
  
  fix typos
................
  r82232 | benjamin.peterson | 2010-06-26 01:37:15 +0200 (Sat, 26 Jun 2010) | 1 line
  
  remove old, outdated tool
................
  r82234 | r.david.murray | 2010-06-26 02:17:12 +0200 (Sat, 26 Jun 2010) | 9 lines
  
  Merged revisions 82233 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82233 | r.david.murray | 2010-06-25 20:06:44 -0400 (Fri, 25 Jun 2010) | 2 lines
    
    #4640: add a test to optparse that proves issue is invalid.
  ........
................
  r82238 | alexander.belopolsky | 2010-06-26 04:15:07 +0200 (Sat, 26 Jun 2010) | 11 lines
  
  Merged revisions 82236 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82236 | alexander.belopolsky | 2010-06-25 22:05:19 -0400 (Fri, 25 Jun 2010) | 4 lines
    
    Issue #9024: Fixed mark-up for PyDateTime_IMPORT macro and added that
    it is typically used in module initialization function. Thanks Tim
    Golden for the patch.
  ........
................
  r82244 | r.david.murray | 2010-06-26 05:34:33 +0200 (Sat, 26 Jun 2010) | 9 lines
  
  Merged revisions 82242 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82242 | r.david.murray | 2010-06-25 23:27:32 -0400 (Fri, 25 Jun 2010) | 2 lines
    
    Fix indentation in recently added test.
  ........
................
  r82247 | r.david.murray | 2010-06-26 20:44:14 +0200 (Sat, 26 Jun 2010) | 14 lines
  
  Blocked revisions 82246 via svnmerge
  
  ........
    r82246 | r.david.murray | 2010-06-26 14:39:50 -0400 (Sat, 26 Jun 2010) | 8 lines
    
    #9085: email versions have gotten out of sync, 2.7 is actually 4.0.3.
    
    In 2.5 the email version was bumped to 4.0.2 just before release but
    after the maintenance branch was set up.  The bump was not backported
    to trunk, and 2.6 went out the door with a version number of 4.0.1.
    I bumped this to 4.0.2 because of a behavior change, but that makes
    it look the same as 2.5.  So bump it again to 4.0.3.
  ........
................
  r82252 | ezio.melotti | 2010-06-26 20:50:39 +0200 (Sat, 26 Jun 2010) | 9 lines
  
  Merged revisions 82248 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82248 | ezio.melotti | 2010-06-26 21:44:42 +0300 (Sat, 26 Jun 2010) | 1 line
    
    Fix extra space.
  ........
................
  r82255 | alexander.belopolsky | 2010-06-26 20:57:02 +0200 (Sat, 26 Jun 2010) | 9 lines
  
  Merged revisions 82251 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82251 | alexander.belopolsky | 2010-06-26 14:49:10 -0400 (Sat, 26 Jun 2010) | 1 line
    
    Issue 9024: Added :cdata: tag to PyDateTimeAPI
  ........
................
  r82259 | brett.cannon | 2010-06-27 00:29:06 +0200 (Sun, 27 Jun 2010) | 6 lines
  
  Having CFLAGS come before OPT prevents silencing certain classes of warnings
  from the fact that OPT contains -Wall be default. This is annoying when
  compilers like clang have thorough debugging information about things that
  Python does extensively (e.g. -Wunused-value for unused return values caused by
  a macro use).
................
  r82262 | georg.brandl | 2010-06-27 12:17:12 +0200 (Sun, 27 Jun 2010) | 1 line
  
  #9078: fix some Unicode C API descriptions, in comments and docs.
................
  r82263 | georg.brandl | 2010-06-27 12:37:48 +0200 (Sun, 27 Jun 2010) | 1 line
  
  #9064: accept number of frames for "up" and "down" commands in pdb.
................
  r82269 | georg.brandl | 2010-06-27 12:59:19 +0200 (Sun, 27 Jun 2010) | 1 line
  
  Wording fix.
................
  r82270 | georg.brandl | 2010-06-27 13:24:03 +0200 (Sun, 27 Jun 2010) | 1 line
  
  Untabify.
................
  r82273 | ronald.oussoren | 2010-06-27 14:37:46 +0200 (Sun, 27 Jun 2010) | 15 lines
  
  Merged revisions 82272 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82272 | ronald.oussoren | 2010-06-27 14:36:16 +0200 (Sun, 27 Jun 2010) | 8 lines
    
    Two small fixes for the support for SDKs on MacOSX:
    
    1) The code that checks if an path should be located in the SDK
       explicitly excludes /usr/local. This fixes issue9046
    
    2) The SDK variant for filtering "db_dirs_to_check" in setup.py
       was not doing anything because of a missing assignment.
  ........
................
  r82278 | ronald.oussoren | 2010-06-27 14:45:47 +0200 (Sun, 27 Jun 2010) | 12 lines
  
  Merged revisions 82276 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82276 | ronald.oussoren | 2010-06-27 14:43:47 +0200 (Sun, 27 Jun 2010) | 5 lines
    
    The uuid library on OSX 10.5 seems to contain the same bug as the one
    on OSX 10.6, therefore don't use it there either.
    
    This fixes issue8621.
  ........
................
  r82281 | ronald.oussoren | 2010-06-27 14:51:31 +0200 (Sun, 27 Jun 2010) | 19 lines
  
  Merged revisions 82150 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82150 | ronald.oussoren | 2010-06-22 11:32:22 +0200 (Tue, 22 Jun 2010) | 12 lines
    
    The code in _scproxy (a mac specific helper module to 
    detect proxy settings) had the wrong logic for detecting
    if the checkbox 'Exclude simple hostnames' is checked. This
    checkin fixes that.
    
    As a result the test failure 'Issue8455' goes away on systems
    where the checkbox is not checked.
    
    I'm carefully avoiding saying that is fixes that issue,
    test_urllib2_localnet assumes that system proxy settings are
    empty (not just on OSX, see Issue8455 for details).
  ........
................
  r82283 | georg.brandl | 2010-06-27 15:28:06 +0200 (Sun, 27 Jun 2010) | 8 lines
  
  Blocked revisions 82271 via svnmerge
  
  ........
    r82271 | georg.brandl | 2010-06-27 13:24:15 +0200 (So, 27 Jun 2010) | 1 line
    
    Untabify.
  ........
................
  r82286 | ronald.oussoren | 2010-06-27 16:26:30 +0200 (Sun, 27 Jun 2010) | 11 lines
  
  Merged revisions 82284 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82284 | ronald.oussoren | 2010-06-27 15:59:39 +0200 (Sun, 27 Jun 2010) | 4 lines
    
    Fix for Issue8883: without this patch test_urllib will fail
    when there is a bare IP address in the "Bypass proxy settings
    for these Hosts & Domains" list on MacOSX.
  ........
................
  r82288 | mark.dickinson | 2010-06-27 19:36:54 +0200 (Sun, 27 Jun 2010) | 1 line
  
  Issue #9089: PyNumber_Int is no more.  Remove it from the docs.
................
  r82289 | mark.dickinson | 2010-06-27 20:18:01 +0200 (Sun, 27 Jun 2010) | 1 line
  
  Issue #9089: Remove intobject.h from MSVC project files.
................
  r82290 | mark.dickinson | 2010-06-27 20:19:09 +0200 (Sun, 27 Jun 2010) | 1 line
  
  Issue #9089: Remove references to intobject.c and intobject.h from comments.
................
  r82291 | brett.cannon | 2010-06-27 22:40:18 +0200 (Sun, 27 Jun 2010) | 1 line
  
  Revert r82259; still no good way to override instead of replace OPT, but changing order alters pydebug optimization flags.
................
  r82292 | benjamin.peterson | 2010-06-27 22:50:37 +0200 (Sun, 27 Jun 2010) | 451 lines
  
  Blocked revisions 79620,79624-79625,79633-79637,79639-79640,79650-79651,79654,79673,79693,79695,79697-79698,79704,79706-79707,79710,79712-79714,79718-79719,79722,79730,79744,79750,79755,79760,79769,79808,79811,79890,80062,80065,80082,80086,80171,80189,80242-80243,80374,80411-80412,80445,80579-80581,80700,80737,80745,80752,80794,80813-80814,80823,80963,80982,81012-81013,81030,81035,81088,81140-81141,81149-81151,81275,81484,81502,81517,81561,81705,81847,81919,81964,82056,82136-82137,82142,82149 via svnmerge
  
  ........
    r79620 | brian.curtin | 2010-04-02 16:18:14 -0500 (Fri, 02 Apr 2010) | 9 lines
    
    Implement #7347. Add CreateKeyEx, DeleteKeyEx, and update _winreg tests.
    
    *ReflectionKey functions used to not be documented or tested, but they are
    now sufficiently documented and tested on platforms where they apply. 
    Additionally, fixed a bug in QueryReflectionKey which was returning an
    incorrect value.
    
    All tests pass from XP through Windows 7, on 32 and 64-bit platforms.
  ........
    r79624 | ezio.melotti | 2010-04-02 16:43:10 -0500 (Fri, 02 Apr 2010) | 1 line
    
    Fix test_compiler.py that was using unittest.__file__ to find Lib/ (unittest is now a package).
  ........
    r79625 | brian.curtin | 2010-04-02 16:51:37 -0500 (Fri, 02 Apr 2010) | 2 lines
    
    Add a line about #7347 to Misc\News
  ........
    r79633 | brian.curtin | 2010-04-02 18:26:06 -0500 (Fri, 02 Apr 2010) | 14 lines
    
    Implement #1220212. Add os.kill support for Windows.
    
    os.kill takes one of two newly added signals, CTRL_C_EVENT and 
    CTRL_BREAK_EVENT, or any integer value. The events are a special case
    which work with subprocess console applications which implement a 
    special console control handler. Any other value but those two will 
    cause os.kill to use TerminateProcess, outright killing the process.
    
    This change adds win_console_handler.py, which is a script to implement 
    SetConsoleCtrlHandler and applicable handler function, using ctypes.
    
    subprocess also gets another attribute which is a necessary flag to 
    creationflags in Popen in order to send the CTRL events.
  ........
    r79634 | brian.curtin | 2010-04-02 18:31:28 -0500 (Fri, 02 Apr 2010) | 2 lines
    
    Add note about #1220212 (os.kill on Windows)
  ........
    r79635 | benjamin.peterson | 2010-04-02 18:31:40 -0500 (Fri, 02 Apr 2010) | 1 line
    
    set svn:eol-style on new file
  ........
    r79636 | benjamin.peterson | 2010-04-02 18:59:41 -0500 (Fri, 02 Apr 2010) | 4 lines
    
    always check _PyString_Resize for error
    
    also normalize how this error is checked
  ........
    r79637 | raymond.hettinger | 2010-04-02 19:39:26 -0500 (Fri, 02 Apr 2010) | 1 line
    
    Clear cyclical references in list based OrderedDict.
  ........
    r79639 | benjamin.peterson | 2010-04-02 19:57:33 -0500 (Fri, 02 Apr 2010) | 1 line
    
    more _PyString_Resize error checking
  ........
    r79640 | brian.curtin | 2010-04-02 19:59:32 -0500 (Fri, 02 Apr 2010) | 3 lines
    
    Fix assertRaises usage on reflection functions which should raise
    NotImplementedError on Windows XP and below.
  ........
    r79650 | raymond.hettinger | 2010-04-02 22:14:28 -0500 (Fri, 02 Apr 2010) | 1 line
    
    Improve clear() method.  Keeps key/value refcnts >= 1 until final dict.clear() so that decrefs to zero won't trigger arbitrary code .  Also runs a bit faster.
  ........
    r79651 | raymond.hettinger | 2010-04-03 02:57:09 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Factor-out constant expressions
  ........
    r79654 | victor.stinner | 2010-04-03 03:40:16 -0500 (Sat, 03 Apr 2010) | 5 lines
    
    Issue #8227: Fix C API documentation, argument parsing
    
     * 'z', 'z#', 'z*' does also accept Unicode
     * unify types name: replace "string or Unicode objet" by "string or Unicode"
  ........
    r79673 | brian.curtin | 2010-04-03 08:58:39 -0500 (Sat, 03 Apr 2010) | 2 lines
    
    Add missing return statement in an error condition.
  ........
    r79693 | benjamin.peterson | 2010-04-03 10:38:38 -0500 (Sat, 03 Apr 2010) | 1 line
    
    wrap
  ........
    r79695 | benjamin.peterson | 2010-04-03 10:40:29 -0500 (Sat, 03 Apr 2010) | 1 line
    
    remove unneeded argument
  ........
    r79697 | benjamin.peterson | 2010-04-03 10:44:56 -0500 (Sat, 03 Apr 2010) | 1 line
    
    silence PyCObject warnings in bsddb
  ........
    r79698 | benjamin.peterson | 2010-04-03 10:45:59 -0500 (Sat, 03 Apr 2010) | 1 line
    
    spelling
  ........
    r79704 | benjamin.peterson | 2010-04-03 10:58:15 -0500 (Sat, 03 Apr 2010) | 1 line
    
    remove deprecation warnings silence attempting
  ........
    r79706 | benjamin.peterson | 2010-04-03 11:06:42 -0500 (Sat, 03 Apr 2010) | 1 line
    
    stop CObject deprecation warnings in test___all__
  ........
    r79707 | mark.dickinson | 2010-04-03 11:41:20 -0500 (Sat, 03 Apr 2010) | 5 lines
    
    Ensure 'module removed' warning messages contain the word 'module' or 'package'.
    
    This should fix the test_py3kwarn failure on OS X.  test_support.import_module
    also requires this.
  ........
    r79710 | mark.dickinson | 2010-04-03 11:54:02 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Replace backquotes with repr(), to silence a SyntaxWarning.
  ........
    r79712 | raymond.hettinger | 2010-04-03 12:10:05 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Silence a compiler warning.
  ........
    r79713 | raymond.hettinger | 2010-04-03 13:10:37 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Add count() method to collections.deque().
  ........
    r79714 | mark.dickinson | 2010-04-03 13:17:54 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Silence DeprecationWarnings from uses of has_key and <> in plat-mac.
  ........
    r79718 | antoine.pitrou | 2010-04-03 16:42:18 -0500 (Sat, 03 Apr 2010) | 3 lines
    
    Remove useless (?) import from r79706
  ........
    r79719 | benjamin.peterson | 2010-04-03 16:50:40 -0500 (Sat, 03 Apr 2010) | 1 line
    
    import bsddb more robustly
  ........
    r79722 | raymond.hettinger | 2010-04-03 17:34:15 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Expand test coverage for deque.count().
  ........
    r79730 | raymond.hettinger | 2010-04-03 20:24:59 -0500 (Sat, 03 Apr 2010) | 1 line
    
    Issue 5479:  Add functools.total_ordering class decorator.
  ........
    r79744 | raymond.hettinger | 2010-04-04 02:33:46 -0500 (Sun, 04 Apr 2010) | 1 line
    
    Documentation nit
  ........
    r79750 | raymond.hettinger | 2010-04-04 13:34:45 -0500 (Sun, 04 Apr 2010) | 1 line
    
    Add functools.CmpToKey()
  ........
    r79755 | raymond.hettinger | 2010-04-04 16:45:01 -0500 (Sun, 04 Apr 2010) | 6 lines
    
    Add tests for cmp_to_key.
    Adopt PEP 8 compliant function name.
    Factor-out existing uses cmp_to_key.
    Update documentation to use internal pointers instead of external resource.
  ........
    r79760 | raymond.hettinger | 2010-04-04 17:24:03 -0500 (Sun, 04 Apr 2010) | 1 line
    
    Add tests for functools.total_ordering.
  ........
    r79769 | benjamin.peterson | 2010-04-04 18:23:22 -0500 (Sun, 04 Apr 2010) | 1 line
    
    fix dis on new style classes #8310
  ........
    r79808 | raymond.hettinger | 2010-04-05 13:53:43 -0500 (Mon, 05 Apr 2010) | 1 line
    
    Classes that override __eq__ also need to define __hash__.
  ........
    r79811 | brian.curtin | 2010-04-05 14:04:23 -0500 (Mon, 05 Apr 2010) | 7 lines
    
    Fix a failing test on an apparently slow Windows buildbot.
    
    On slower Windows machines, waiting 0.1 seconds can sometimes not be 
    enough for a subprocess to start and be ready to accept signals, causing 
    the test to fail. One buildbot is also choking on input()/EOFError so 
    that was changed to not depend on input.
  ........
    r79890 | mark.dickinson | 2010-04-07 05:18:27 -0500 (Wed, 07 Apr 2010) | 4 lines
    
    Use some more interesting test values for (unsigned) long long ctypes tests,
    in the hope of getting more information about the test_ctypes failures
    on Sparc (see issue #8314).
  ........
    r80062 | r.david.murray | 2010-04-13 15:57:40 -0500 (Tue, 13 Apr 2010) | 2 lines
    
    Issue #5277: Fix quote counting when parsing RFC 2231 encoded parameters.
  ........
    r80065 | brian.curtin | 2010-04-13 21:24:24 -0500 (Tue, 13 Apr 2010) | 6 lines
    
    Add a small sleep to let a subprocess start before terminating it.
    
    David Bolen's buildbot isn't know for it's speed, and it seems that we
    may have been trying to kill the subprocess before it was fully 
    initialized. I ran with this change on the bot itself and it seemed to work.
  ........
    r80082 | georg.brandl | 2010-04-14 16:36:49 -0500 (Wed, 14 Apr 2010) | 1 line
    
    #8370: fix module name in backported doc addition.
  ........
    r80086 | brian.curtin | 2010-04-14 19:40:40 -0500 (Wed, 14 Apr 2010) | 9 lines
    
    Fix os.kill tests to be more robust and work with slower machines.
    
    Rather than depending on some sleep value, start up an interpreter
    as a subprocess and communicate with it. Because subprocess pipes 
    can't be read from until EOF and I want to read from them before that,
    use ctypes to peek by using PeekNamedPipe. Once the subprocess has 
    written the message, then it is ready to roll and accept signals.
    After that, kill it.
  ........
    r80171 | antoine.pitrou | 2010-04-18 06:16:24 -0500 (Sun, 18 Apr 2010) | 3 lines
    
    Fix bootstrap after r80166
  ........
    r80189 | victor.stinner | 2010-04-18 13:22:25 -0500 (Sun, 18 Apr 2010) | 1 line
    
    Revert r80166 (and r80171), restore Lib/platform.py. subprocess cannot be used in platform.py
  ........
    r80242 | ronald.oussoren | 2010-04-20 03:53:12 -0500 (Tue, 20 Apr 2010) | 8 lines
    
    The PythonLauncher change is needed due
    to changes in how the BASECFLAGS and CFLAGS
    variables get filled by configure.
    
    The Mac/Makefile.in change ensures that 
    pythonw gets build with the rigth deployment
    targets.
  ........
    r80243 | ronald.oussoren | 2010-04-20 03:54:48 -0500 (Tue, 20 Apr 2010) | 3 lines
    
    This patch fixes the handling of a weak-linked
    variable and should fix issue #8095.
  ........
    r80374 | antoine.pitrou | 2010-04-22 12:44:41 -0500 (Thu, 22 Apr 2010) | 3 lines
    
    Temporarily display OpenSSL version in verbose run -- trying to diagnose failure on Neal's buildbot.
  ........
    r80411 | florent.xicluna | 2010-04-23 12:59:10 -0500 (Fri, 23 Apr 2010) | 2 lines
    
    Remove ImportWarnings filters.  They become obsolete after r79310, issue #8205.
  ........
    r80412 | florent.xicluna | 2010-04-23 13:10:12 -0500 (Fri, 23 Apr 2010) | 2 lines
    
    Fix the "regrtest -s" switch.
  ........
    r80445 | brian.curtin | 2010-04-24 12:10:22 -0500 (Sat, 24 Apr 2010) | 2 lines
    
    Fix #5774. Some _winreg functions are documented as taking kwargs but don't.
  ........
    r80579 | nick.coghlan | 2010-04-28 09:34:30 -0500 (Wed, 28 Apr 2010) | 1 line
    
    Also mention patch submitter's name in NEWS, not just in the commit message
  ........
    r80580 | nick.coghlan | 2010-04-28 09:51:08 -0500 (Wed, 28 Apr 2010) | 1 line
    
    Issue 8202: when using the -m command line switch, sys.argv[0] is now '-m' instead of '-c' while searching for the module to be executed
  ........
    r80581 | nick.coghlan | 2010-04-28 09:53:59 -0500 (Wed, 28 Apr 2010) | 1 line
    
    Add version changed note for -m tinkering with sys.argv[0] during the search process
  ........
    r80700 | ronald.oussoren | 2010-05-02 04:55:57 -0500 (Sun, 02 May 2010) | 3 lines
    
    Small update to r80698 to ensure that webbrowser.open
    uses the default browser.
  ........
    r80737 | brett.cannon | 2010-05-03 18:57:15 -0500 (Mon, 03 May 2010) | 4 lines
    
    Fix two potential uninitialization errors and an unneeded assignment.
    
    Found using Clang's static analyzer.
  ........
    r80745 | brett.cannon | 2010-05-03 20:04:53 -0500 (Mon, 03 May 2010) | 5 lines
    
    Mention the code clean-up thanks to Clang's static analyzer in Modules.
    
    Was not applied to modules that will not compile under OS X, dbmmodule.c,
    getaddrinfo.c, and getnameinfo.c.
  ........
    r80752 | victor.stinner | 2010-05-04 06:35:36 -0500 (Tue, 04 May 2010) | 4 lines
    
    _pyio: Fix TextIOWrapper constructor: os has no device_encoding() function
    
    _io module doesn't call this function which was introduced in Python3.
  ........
    r80794 | barry.warsaw | 2010-05-05 11:17:22 -0500 (Wed, 05 May 2010) | 1 line
    
    NEWS
  ........
    r80813 | brett.cannon | 2010-05-05 15:20:19 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove three unneeded variable assignments.
    
    Found using Clang's static analyzer.
  ........
    r80814 | brett.cannon | 2010-05-05 15:24:30 -0500 (Wed, 05 May 2010) | 1 line
    
    Partially revert the over-reaching r80813.
  ........
    r80823 | brett.cannon | 2010-05-05 15:54:53 -0500 (Wed, 05 May 2010) | 1 line
    
    Mention how Clang's static anaylzer was run over Objects/ and Python/.
  ........
    r80963 | ronald.oussoren | 2010-05-08 03:44:37 -0500 (Sat, 08 May 2010) | 4 lines
    
    Fix for issue #7724: make it possible to build using
    the OSX 10.4u SDK on MacOSX 10.6 by honoring the specified
    SDK when looking for files.
  ........
    r80982 | antoine.pitrou | 2010-05-08 10:23:57 -0500 (Sat, 08 May 2010) | 3 lines
    
    Revert r80963 - it broke compilation everywhere
  ........
    r81012 | gregory.p.smith | 2010-05-08 18:38:49 -0500 (Sat, 08 May 2010) | 2 lines
    
    Fixes [issue7245] Better Ctrl-C support in pdb.
  ........
    r81013 | gregory.p.smith | 2010-05-08 20:20:20 -0500 (Sat, 08 May 2010) | 5 lines
    
    Revert r81012.  buildbot problems and its questionable of me to even
    add this to trunk while we're on the way to 2.7rc1.
    
    When fixed this can go into py3k first.  Sorry.
  ........
    r81030 | antoine.pitrou | 2010-05-09 10:15:11 -0500 (Sun, 09 May 2010) | 3 lines
    
    Fixup indentation of PC/_msi.c
  ........
    r81035 | antoine.pitrou | 2010-05-09 13:32:48 -0500 (Sun, 09 May 2010) | 3 lines
    
    Remove spurious newlines, and add version number.
  ........
    r81088 | brian.curtin | 2010-05-11 14:13:13 -0500 (Tue, 11 May 2010) | 13 lines
    
    #8575 - Update and reorganize some _winreg contents.
    
    I've removed the hopeful note about a future higher-level module since
    it's been in there for quite a long time and nothing of the sort has 
    come up. There are a few places where markup was added to cross-reference
    other sections, and many of the external links have been removed and now
    point to newly created sections containing previously undocumented
    information.
    
    The Value Types section was created and it's contents were taken from
    a function-specific area, since it applies to more than just that
    function. It fits in better with the other newly documented constants.
  ........
    r81140 | florent.xicluna | 2010-05-13 12:05:29 -0500 (Thu, 13 May 2010) | 3 lines
    
    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 13:16:06 -0500 (Thu, 13 May 2010) | 2 lines
    
    Revert the additional OS X information (r81140).  Keep the endianness information.
  ........
    r81149 | florent.xicluna | 2010-05-13 16:40:01 -0500 (Thu, 13 May 2010) | 2 lines
    
    Better test skipping, with message in the log.
  ........
    r81150 | florent.xicluna | 2010-05-13 16:41:05 -0500 (Thu, 13 May 2010) | 2 lines
    
    Improve test feedback to troubleshoot issue #8423 on OS X.
  ........
    r81151 | florent.xicluna | 2010-05-13 18:46:48 -0500 (Thu, 13 May 2010) | 2 lines
    
    Revert changeset r81150 which helped diagnose issue #8423 on some OS X buildbot.
  ........
    r81275 | antoine.pitrou | 2010-05-17 14:56:59 -0500 (Mon, 17 May 2010) | 4 lines
    
    Issue #7079: Fix a possible crash when closing a file object while using
    it from another thread.  Patch by Daniel Stutzbach.
  ........
    r81484 | georg.brandl | 2010-05-22 16:26:21 -0500 (Sat, 22 May 2010) | 1 line
    
    NEWS rewrap and punctuation consistency.
  ........
    r81502 | georg.brandl | 2010-05-24 16:37:54 -0500 (Mon, 24 May 2010) | 1 line
    
    #8616: update module name
  ........
    r81517 | brian.curtin | 2010-05-25 10:06:15 -0500 (Tue, 25 May 2010) | 5 lines
    
    Fix #2810 - handle the case where some registry calls return
    ERROR_MORE_DATA, requiring another call to get the remaining data.
    
    Patch by Daniel Stutzbach
  ........
    r81561 | alexander.belopolsky | 2010-05-26 15:57:04 -0500 (Wed, 26 May 2010) | 1 line
    
    Added Andrej Krpic. (Thanks for issue #7879 patch.)
  ........
    r81705 | r.david.murray | 2010-06-04 14:51:06 -0500 (Fri, 04 Jun 2010) | 9 lines
    
    #4487: have Charset check with codecs for possible aliases.
    
    Previously, unexpected results occurred when email was passed, for example,
    'utf8' as a charset name, since email would accept it but would *not* use
    the 'utf-8' codec for it, even though Python itself recognises that as
    an alias for utf-8.  Now Charset checks with codecs for aliases as well
    as its own internal table.  Issue 8898 has been opened to change this
    further in py3k so that all aliasing is routed through the codecs module.
  ........
    r81847 | brian.curtin | 2010-06-08 16:15:06 -0500 (Tue, 08 Jun 2010) | 3 lines
    
    Move a variable declration outside of a loop to match what was
    done in r81843 for py3k.
  ........
    r81919 | vinay.sajip | 2010-06-11 17:56:50 -0500 (Fri, 11 Jun 2010) | 1 line
    
    Issue #8924: logging: Improved error handling for Unicode in exception text.
  ........
    r81964 | nick.coghlan | 2010-06-13 01:50:39 -0500 (Sun, 13 Jun 2010) | 1 line
    
    Revert r80580 due to some unintended side effects. See issue #8202 for details.
  ........
    r82056 | florent.xicluna | 2010-06-17 15:30:56 -0500 (Thu, 17 Jun 2010) | 2 lines
    
    Add few words about test.test_genericpath.CommonTest
  ........
    r82136 | benjamin.peterson | 2010-06-21 10:56:45 -0500 (Mon, 21 Jun 2010) | 1 line
    
    update pydoc-topics
  ........
    r82137 | benjamin.peterson | 2010-06-21 10:57:57 -0500 (Mon, 21 Jun 2010) | 1 line
    
    bump verson to 2.7rc2
  ........
    r82142 | benjamin.peterson | 2010-06-21 12:28:30 -0500 (Mon, 21 Jun 2010) | 1 line
    
    towards final release
  ........
    r82149 | ronald.oussoren | 2010-06-22 04:18:28 -0500 (Tue, 22 Jun 2010) | 11 lines
    
    Fix for issue8446:
    
    * Don't import 'ic' in webbrowser, that module is no longer used
    * Remove 'MacOS' from the list of modules that should emit a Py3kWarning on import.
      This is needed because one of the earlier tests triggers and import of this
      extension, and that causes a failure in test_py3kwarn (running test_py3kwarn 
      separately worked fine)
    
    With these changes 'make tests' no longer says that test_py3kwarn fails.
  ........
................
  r82293 | benjamin.peterson | 2010-06-27 22:54:28 +0200 (Sun, 27 Jun 2010) | 13 lines
  
  Merged revisions 80712,81651 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r80712 | vinay.sajip | 2010-05-03 10:11:53 -0500 (Mon, 03 May 2010) | 1 line
    
    Issue #8576: logging updated to remove usage of find_unused_port().
  ........
    r81651 | vinay.sajip | 2010-06-02 05:05:31 -0500 (Wed, 02 Jun 2010) | 1 line
    
    Logging: improved error reporting for BaseConfigurator.resolve().
  ........
................
  r82294 | benjamin.peterson | 2010-06-27 23:05:30 +0200 (Sun, 27 Jun 2010) | 174 lines
  
  Blocked revisions 80731-80736,80739,80741-80744,80746-80747,80807-80812,80815-80822,80843,80874 via svnmerge
  
  ........
    r80731 | brett.cannon | 2010-05-03 18:41:23 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove unneeded variable initialization.
    
    Found using Clang's static analyzer.
  ........
    r80732 | brett.cannon | 2010-05-03 18:41:51 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove an unused variable.
    
    Found using Clang's static analyzer.
  ........
    r80733 | brett.cannon | 2010-05-03 18:42:40 -0500 (Mon, 03 May 2010) | 3 lines
    
    Clean up whitespace and remove unneeded variable initialization as found by
    Clang.
  ........
    r80734 | brett.cannon | 2010-05-03 18:43:49 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove unneeded variable mutation and initializations.
    
    Found using Clang's static analyzer.
  ........
    r80735 | brett.cannon | 2010-05-03 18:44:54 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove unneeded variable assignment.
    
    Found using Clang's static analyzer.
  ........
    r80736 | brett.cannon | 2010-05-03 18:51:28 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove unused variables and a variable initialization.
    
    Found using Clang's static analyzer.
  ........
    r80739 | brett.cannon | 2010-05-03 19:36:00 -0500 (Mon, 03 May 2010) | 4 lines
    
    Prevent a possible NULL de-reference and an unneeded variable assignment.
    
    Found using Clang's static analyzer.
  ........
    r80741 | brett.cannon | 2010-05-03 19:48:11 -0500 (Mon, 03 May 2010) | 4 lines
    
    Fix a Py_DECREF to a Py_XDECREF.
    
    Found using Clang's static analyzer.
  ........
    r80742 | brett.cannon | 2010-05-03 19:52:41 -0500 (Mon, 03 May 2010) | 4 lines
    
    Strip out extraneous whitespace, cast a some `const char *` to `void *` when
    passed to free() and make a `char *` to a `const char *` as found by Clang's
    static analyzer.
  ........
    r80743 | brett.cannon | 2010-05-03 19:57:44 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove an unneeded variable assignment.
    
    Found using Clang's static analyzer.
  ........
    r80744 | brett.cannon | 2010-05-03 20:01:00 -0500 (Mon, 03 May 2010) | 2 lines
    
    Fix some whitespace.
  ........
    r80746 | brett.cannon | 2010-05-03 20:16:51 -0500 (Mon, 03 May 2010) | 4 lines
    
    Remove an unneeded variable and assignment.
    
    Found using Clang's static analyzer.
  ........
    r80747 | brett.cannon | 2010-05-03 20:23:36 -0500 (Mon, 03 May 2010) | 4 lines
    
    Pull a NULL pointer check up to cover more cases in the function.
    
    Found using Clang's static analyzer.
  ........
    r80807 | brett.cannon | 2010-05-05 15:14:27 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unnecessary variable.
    
    Found using Clang's static analyzer.
  ........
    r80808 | brett.cannon | 2010-05-05 15:15:14 -0500 (Wed, 05 May 2010) | 2 lines
    
    Remove extraneous whitespace.
  ........
    r80809 | brett.cannon | 2010-05-05 15:16:09 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded variable increment.
    
    Found using Clang's static analyzer.
  ........
    r80810 | brett.cannon | 2010-05-05 15:16:50 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded variable.
    
    Found using Clang's static analyzer.
  ........
    r80811 | brett.cannon | 2010-05-05 15:18:23 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded variable assignment.
    
    Found using Clang's static analyzer.
  ........
    r80812 | brett.cannon | 2010-05-05 15:19:26 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded assignment.
    
    Found using Clang's static analyzer.
  ........
    r80815 | brett.cannon | 2010-05-05 15:25:47 -0500 (Wed, 05 May 2010) | 1 line
    
    Fix whitespace.
  ........
    r80816 | brett.cannon | 2010-05-05 15:26:58 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded variable and fix a little whitespace.
    
    Found using Clang's static analyzer.
  ........
    r80817 | brett.cannon | 2010-05-05 15:27:49 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded variable increment.
    
    Found using Clang's static analyzer.
  ........
    r80818 | brett.cannon | 2010-05-05 15:30:30 -0500 (Wed, 05 May 2010) | 8 lines
    
    Remove two unneeded branches to an 'if' statement by applying De Morgan's Law
    and creating a single 'if' statement along with a NULL default value for a
    variable.
    
    Also clean up a bunch of whitespace.
    
    Found using Clang's static analyzer.
  ........
    r80819 | brett.cannon | 2010-05-05 15:35:24 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unnecessary variable assignment.
    
    Found using Clang's static analyzer.
  ........
    r80820 | brett.cannon | 2010-05-05 15:38:52 -0500 (Wed, 05 May 2010) | 4 lines
    
    Change to a Py_XDECREF and fix some whitespace.
    
    Found using Clang's static analyzer.
  ........
    r80821 | brett.cannon | 2010-05-05 15:50:03 -0500 (Wed, 05 May 2010) | 4 lines
    
    Explicitly add stdio.h and string.h to make strtod.c work standalone.
    
    Found using Clang's static analyzer.
  ........
    r80822 | brett.cannon | 2010-05-05 15:53:20 -0500 (Wed, 05 May 2010) | 4 lines
    
    Remove an unneeded variable assignment.
    
    Found using Clang's static analyzer.
  ........
    r80843 | brett.cannon | 2010-05-05 18:11:08 -0500 (Wed, 05 May 2010) | 1 line
    
    Revert a change where an expression is not needed now, but could be in the future.
  ........
    r80874 | brett.cannon | 2010-05-06 12:56:36 -0500 (Thu, 06 May 2010) | 5 lines
    
    Add back in a line that was unneeded which advanced a pointer, but commented
    out as it is currently unneeded.
    
    This effectively adds back in the line removed in r80809 as a comment.
  ........
................
  r82295 | benjamin.peterson | 2010-06-27 23:15:09 +0200 (Sun, 27 Jun 2010) | 16 lines
  
  Blocked revisions 79925-79926,80397 via svnmerge
  
  ........
    r79925 | nick.coghlan | 2010-04-10 09:24:36 -0500 (Sat, 10 Apr 2010) | 1 line
    
    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)
  ........
    r79926 | nick.coghlan | 2010-04-10 10:01:54 -0500 (Sat, 10 Apr 2010) | 1 line
    
    Fix typo in comment
  ........
    r80397 | sean.reifschneider | 2010-04-23 03:38:24 -0500 (Fri, 23 Apr 2010) | 2 lines
    
    Small comment documentation change to clarify "ident" selection.
  ........
................
  r82296 | benjamin.peterson | 2010-06-27 23:22:34 +0200 (Sun, 27 Jun 2010) | 12 lines
  
  Blocked revisions 80649,80710 via svnmerge
  
  ........
    r80649 | tarek.ziade | 2010-04-30 07:15:12 -0500 (Fri, 30 Apr 2010) | 1 line
    
    Fixed #8577. distutils.sysconfig.get_python_inc() now differenciates buildir and srcdir
  ........
    r80710 | brett.cannon | 2010-05-02 16:51:23 -0500 (Sun, 02 May 2010) | 1 line
    
    Update the Vim syntax highlight file.
  ........
................
  r82297 | benjamin.peterson | 2010-06-27 23:27:49 +0200 (Sun, 27 Jun 2010) | 16 lines
  
  Blocked revisions 80787,80793 via svnmerge
  
  ........
    r80787 | ronald.oussoren | 2010-05-05 10:32:39 -0500 (Wed, 05 May 2010) | 5 lines
    
    Force exit using os._exit instead of sys.exit,
    this makes sure that the child does not continue
    testing.
  ........
    r80793 | barry.warsaw | 2010-05-05 11:15:09 -0500 (Wed, 05 May 2010) | 5 lines
    
    Bug 7755: audiotest.au is arguably copyrighted material, but definitely makes
    Debian unhappy.  The actual contents of the audio clip are unimportant, so
    replace it with something that we know is okay.  Guido likes woodpeckers.
  ........
................
  r82298 | benjamin.peterson | 2010-06-27 23:45:24 +0200 (Sun, 27 Jun 2010) | 37 lines
  
  Merged revisions 81465-81466,81468,81679,81735,81760,81868,82183 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81465 | georg.brandl | 2010-05-22 06:29:19 -0500 (Sat, 22 May 2010) | 2 lines
    
    Issue #3924: Ignore cookies with invalid "version" field in cookielib.
  ........
    r81466 | georg.brandl | 2010-05-22 06:31:16 -0500 (Sat, 22 May 2010) | 1 line
    
    Underscore the name of an internal utility function.
  ........
    r81468 | georg.brandl | 2010-05-22 06:43:25 -0500 (Sat, 22 May 2010) | 1 line
    
    #8635: document enumerate() start parameter in docstring.
  ........
    r81679 | benjamin.peterson | 2010-06-03 16:21:03 -0500 (Thu, 03 Jun 2010) | 1 line
    
    use a set for membership testing
  ........
    r81735 | michael.foord | 2010-06-05 06:46:59 -0500 (Sat, 05 Jun 2010) | 1 line
    
    Extract error message truncating into a method (unittest.TestCase._truncateMessage).
  ........
    r81760 | michael.foord | 2010-06-05 14:38:42 -0500 (Sat, 05 Jun 2010) | 1 line
    
    Issue 8302. SkipTest exception is setUpClass or setUpModule is now reported as a skip rather than an error.
  ........
    r81868 | benjamin.peterson | 2010-06-09 14:45:04 -0500 (Wed, 09 Jun 2010) | 1 line
    
    fix code formatting
  ........
    r82183 | benjamin.peterson | 2010-06-23 15:29:26 -0500 (Wed, 23 Jun 2010) | 1 line
    
    cpython only gc tests
  ........
................
  r82299 | benjamin.peterson | 2010-06-27 23:48:35 +0200 (Sun, 27 Jun 2010) | 13 lines
  
  Merged revisions 81881-81882 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81881 | andrew.kuchling | 2010-06-10 19:16:08 -0500 (Thu, 10 Jun 2010) | 1 line
    
    #5753: update demo.c to use PySys_SetArgvEx(), and add a comment
  ........
    r81882 | andrew.kuchling | 2010-06-10 19:23:01 -0500 (Thu, 10 Jun 2010) | 1 line
    
    #5753: Suggest PySys_SetArgvEx() instead of PySys_SetArgv()
  ........
................
  r82300 | brett.cannon | 2010-06-27 23:49:22 +0200 (Sun, 27 Jun 2010) | 4 lines
  
  Add a link to PEP 3147 from the importlib docs.
  
  Closes issue 8667. Thanks Ashley Sands for the patch.
................
  r82301 | benjamin.peterson | 2010-06-28 00:32:30 +0200 (Mon, 28 Jun 2010) | 303 lines
  
  Merged revisions 80605-80609,80642-80646,80651-80652,80674,80684-80686,80748,80852,80854,80870,80872-80873,80907,80915-80916,80951-80952,80976-80977,80985,81038-81040,81042,81053,81070,81104-81105,81114,81125,81245,81285,81402,81463,81516,81562-81563,81567,81593,81635,81680-81681,81684,81801,81888,81931-81933,81939-81942,81963,81984,81991,82120,82188,82264-82267 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r80605 | andrew.kuchling | 2010-04-28 19:22:16 -0500 (Wed, 28 Apr 2010) | 1 line
    
    Add various items
  ........
    r80606 | andrew.kuchling | 2010-04-28 20:44:30 -0500 (Wed, 28 Apr 2010) | 6 lines
    
    Fix doubled 'the'.
    Markup fixes to use :exc:, :option: in a few places.
      (Glitch: unittest.main's -c ends up a link to the Python
      interpreter's -c option.  Should we skip using :option: for that
      switch, or disable the auto-linking somehow?)
  ........
    r80607 | andrew.kuchling | 2010-04-28 20:45:41 -0500 (Wed, 28 Apr 2010) | 1 line
    
    Add various unittest items
  ........
    r80608 | benjamin.peterson | 2010-04-28 22:18:05 -0500 (Wed, 28 Apr 2010) | 1 line
    
    update pypy description
  ........
    r80609 | benjamin.peterson | 2010-04-28 22:30:59 -0500 (Wed, 28 Apr 2010) | 1 line
    
    update pypy url
  ........
    r80642 | andrew.kuchling | 2010-04-29 19:49:09 -0500 (Thu, 29 Apr 2010) | 1 line
    
    Always add space after RFC; reword paragraph
  ........
    r80643 | andrew.kuchling | 2010-04-29 19:52:31 -0500 (Thu, 29 Apr 2010) | 6 lines
    
    Reword paragraph to make its meaning clearer.
    
    Antoine Pitrou: is my version of the paragraph still correct?
    
    R. David Murray: is this more understandable than the previous version?
  ........
    r80644 | andrew.kuchling | 2010-04-29 20:02:15 -0500 (Thu, 29 Apr 2010) | 1 line
    
    Fix typos
  ........
    r80645 | andrew.kuchling | 2010-04-29 20:32:47 -0500 (Thu, 29 Apr 2010) | 1 line
    
    Markup fix; clarify by adding 'in that order'
  ........
    r80646 | andrew.kuchling | 2010-04-29 20:33:40 -0500 (Thu, 29 Apr 2010) | 1 line
    
    Add various items; rearrange unittest section a bit
  ........
    r80651 | andrew.kuchling | 2010-04-30 08:46:55 -0500 (Fri, 30 Apr 2010) | 1 line
    
    Minor grammar re-wording
  ........
    r80652 | andrew.kuchling | 2010-04-30 08:47:34 -0500 (Fri, 30 Apr 2010) | 1 line
    
    Add item
  ........
    r80674 | andrew.kuchling | 2010-04-30 20:19:16 -0500 (Fri, 30 Apr 2010) | 1 line
    
    Add various items
  ........
    r80684 | andrew.kuchling | 2010-05-01 07:05:52 -0500 (Sat, 01 May 2010) | 1 line
    
    Minor grammar fix
  ........
    r80685 | andrew.kuchling | 2010-05-01 07:06:51 -0500 (Sat, 01 May 2010) | 1 line
    
    Describe memoryview
  ........
    r80686 | antoine.pitrou | 2010-05-01 07:16:39 -0500 (Sat, 01 May 2010) | 4 lines
    
    Fix attribution. Travis didn't do much and he did a bad work.
    (yes, this is a sensitive subject, sorry)
  ........
    r80748 | andrew.kuchling | 2010-05-03 20:24:22 -0500 (Mon, 03 May 2010) | 1 line
    
    Add some more items; the urlparse change is added twice
  ........
    r80852 | andrew.kuchling | 2010-05-05 20:09:47 -0500 (Wed, 05 May 2010) | 1 line
    
    Reword paragraph; fix filename, which should be pyconfig.h
  ........
    r80854 | andrew.kuchling | 2010-05-05 20:10:56 -0500 (Wed, 05 May 2010) | 1 line
    
    Add various items
  ........
    r80870 | andrew.kuchling | 2010-05-06 09:14:09 -0500 (Thu, 06 May 2010) | 1 line
    
    Describe ElementTree 1.3; rearrange new-module sections; describe dict views as sets; small edits and items
  ........
    r80872 | andrew.kuchling | 2010-05-06 12:21:59 -0500 (Thu, 06 May 2010) | 1 line
    
    Add 2 items; record ideas for two initial sections; clarify wording
  ........
    r80873 | andrew.kuchling | 2010-05-06 12:27:57 -0500 (Thu, 06 May 2010) | 1 line
    
    Change section title; point to unittest2
  ........
    r80907 | andrew.kuchling | 2010-05-06 20:45:14 -0500 (Thu, 06 May 2010) | 1 line
    
    Add a new section on the development plan; add an item
  ........
    r80915 | antoine.pitrou | 2010-05-07 05:15:51 -0500 (Fri, 07 May 2010) | 3 lines
    
    Fix some markup and a class name. Also, wrap a long line.
  ........
    r80916 | andrew.kuchling | 2010-05-07 06:30:47 -0500 (Fri, 07 May 2010) | 1 line
    
    Re-word text
  ........
    r80951 | andrew.kuchling | 2010-05-07 20:15:26 -0500 (Fri, 07 May 2010) | 1 line
    
    Add two items
  ........
    r80952 | andrew.kuchling | 2010-05-07 20:35:55 -0500 (Fri, 07 May 2010) | 1 line
    
    Get accents correct
  ........
    r80976 | andrew.kuchling | 2010-05-08 08:28:03 -0500 (Sat, 08 May 2010) | 1 line
    
    Add logging.dictConfig example; give up on writing a Ttk example
  ........
    r80977 | andrew.kuchling | 2010-05-08 08:29:46 -0500 (Sat, 08 May 2010) | 1 line
    
    Markup fixes
  ........
    r80985 | andrew.kuchling | 2010-05-08 10:39:46 -0500 (Sat, 08 May 2010) | 7 lines
    
    Write summary of the 2.7 release; rewrite the future section some more;
    mention PYTHONWARNINGS env. var; tweak some examples for readability.
    
    And with this commit, the "What's New" is done... except for a
    complete read-through to polish the text, and fixing any reported errors,
    but those tasks can easily wait until after beta2.
  ........
    r81038 | benjamin.peterson | 2010-05-09 16:09:40 -0500 (Sun, 09 May 2010) | 1 line
    
    finish clause
  ........
    r81039 | andrew.kuchling | 2010-05-10 09:18:27 -0500 (Mon, 10 May 2010) | 1 line
    
    Markup fix; re-word a sentence
  ........
    r81040 | andrew.kuchling | 2010-05-10 09:20:12 -0500 (Mon, 10 May 2010) | 1 line
    
    Use title case
  ........
    r81042 | andrew.kuchling | 2010-05-10 10:03:35 -0500 (Mon, 10 May 2010) | 1 line
    
    Link to unittest2 article
  ........
    r81053 | florent.xicluna | 2010-05-10 14:59:22 -0500 (Mon, 10 May 2010) | 2 lines
    
    Add a link on maketrans().
  ........
    r81070 | andrew.kuchling | 2010-05-10 18:13:41 -0500 (Mon, 10 May 2010) | 1 line
    
    Fix typo
  ........
    r81104 | andrew.kuchling | 2010-05-11 19:38:44 -0500 (Tue, 11 May 2010) | 1 line
    
    Revision pass: lots of edits, typo fixes, rearrangements
  ........
    r81105 | andrew.kuchling | 2010-05-11 19:40:47 -0500 (Tue, 11 May 2010) | 1 line
    
    Let's call this done
  ........
    r81114 | andrew.kuchling | 2010-05-12 08:56:07 -0500 (Wed, 12 May 2010) | 1 line
    
    Grammar fix
  ........
    r81125 | andrew.kuchling | 2010-05-12 13:56:48 -0500 (Wed, 12 May 2010) | 1 line
    
    #8696: add documentation for logging.config.dictConfig (PEP 391)
  ........
    r81245 | andrew.kuchling | 2010-05-16 18:31:16 -0500 (Sun, 16 May 2010) | 1 line
    
    Add cross-reference to later section
  ........
    r81285 | vinay.sajip | 2010-05-18 03:16:27 -0500 (Tue, 18 May 2010) | 1 line
    
    Fixed minor typo in ReST markup.
  ........
    r81402 | vinay.sajip | 2010-05-21 12:41:34 -0500 (Fri, 21 May 2010) | 1 line
    
    Updated logging documentation with more dictConfig information.
  ........
    r81463 | georg.brandl | 2010-05-22 03:17:23 -0500 (Sat, 22 May 2010) | 1 line
    
    #8785: less confusing description of regex.find*.
  ........
    r81516 | andrew.kuchling | 2010-05-25 08:34:08 -0500 (Tue, 25 May 2010) | 1 line
    
    Add three items
  ........
    r81562 | andrew.kuchling | 2010-05-27 08:22:53 -0500 (Thu, 27 May 2010) | 1 line
    
    Rewrite wxWidgets section
  ........
    r81563 | andrew.kuchling | 2010-05-27 08:30:09 -0500 (Thu, 27 May 2010) | 1 line
    
    Remove top-level 'General Questions' section, pushing up the questions it contains
  ........
    r81567 | andrew.kuchling | 2010-05-27 16:29:59 -0500 (Thu, 27 May 2010) | 1 line
    
    Add item
  ........
    r81593 | georg.brandl | 2010-05-29 03:46:18 -0500 (Sat, 29 May 2010) | 1 line
    
    #8616: add new turtle demo "nim".
  ........
    r81635 | georg.brandl | 2010-06-01 02:25:23 -0500 (Tue, 01 Jun 2010) | 1 line
    
    Put docs for RegexObject.search() before RegexObject.match() to mirror re.search() and re.match() order.
  ........
    r81680 | vinay.sajip | 2010-06-03 17:34:42 -0500 (Thu, 03 Jun 2010) | 1 line
    
    Issue #8890: Documentation changed to avoid reference to temporary files.
  ........
    r81681 | sean.reifschneider | 2010-06-03 20:51:26 -0500 (Thu, 03 Jun 2010) | 2 lines
    
    Issue8810: Clearing up docstring for tzinfo.utcoffset.
  ........
    r81684 | vinay.sajip | 2010-06-04 08:41:02 -0500 (Fri, 04 Jun 2010) | 1 line
    
    Issue #8890: Documentation changed to avoid reference to temporary files - other cases covered.
  ........
    r81801 | andrew.kuchling | 2010-06-07 08:38:40 -0500 (Mon, 07 Jun 2010) | 1 line
    
    #8875: Remove duplicated paragraph
  ........
    r81888 | andrew.kuchling | 2010-06-10 20:54:58 -0500 (Thu, 10 Jun 2010) | 1 line
    
    Add a few more items
  ........
    r81931 | georg.brandl | 2010-06-12 01:26:54 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Fix punctuation.
  ........
    r81932 | georg.brandl | 2010-06-12 01:28:58 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Document that an existing directory raises in mkdir().
  ........
    r81933 | georg.brandl | 2010-06-12 01:45:33 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Update version in README.
  ........
    r81939 | georg.brandl | 2010-06-12 04:45:01 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Use newer toctree syntax.
  ........
    r81940 | georg.brandl | 2010-06-12 04:45:28 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Add document on how to build.
  ........
    r81941 | georg.brandl | 2010-06-12 04:45:58 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Fix gratuitous indentation.
  ........
    r81942 | georg.brandl | 2010-06-12 04:46:03 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Update README.
  ........
    r81963 | andrew.kuchling | 2010-06-12 15:00:55 -0500 (Sat, 12 Jun 2010) | 1 line
    
    Grammar fix
  ........
    r81984 | georg.brandl | 2010-06-14 10:58:39 -0500 (Mon, 14 Jun 2010) | 1 line
    
    #8993: fix reference.
  ........
    r81991 | andrew.kuchling | 2010-06-14 19:38:58 -0500 (Mon, 14 Jun 2010) | 1 line
    
    Add another bunch of items
  ........
    r82120 | andrew.kuchling | 2010-06-20 16:45:45 -0500 (Sun, 20 Jun 2010) | 1 line
    
    Note that Python 3.x isn't covered; add forward ref. for UTF-8; note error in 2.5 and up
  ........
    r82188 | benjamin.peterson | 2010-06-23 19:02:46 -0500 (Wed, 23 Jun 2010) | 1 line
    
    remove reverted changed
  ........
    r82264 | georg.brandl | 2010-06-27 05:47:47 -0500 (Sun, 27 Jun 2010) | 1 line
    
    Confusing punctuation.
  ........
    r82265 | georg.brandl | 2010-06-27 05:49:23 -0500 (Sun, 27 Jun 2010) | 1 line
    
    Use designated syntax for optional grammar element.
  ........
    r82266 | georg.brandl | 2010-06-27 05:51:44 -0500 (Sun, 27 Jun 2010) | 1 line
    
    Fix URL.
  ........
    r82267 | georg.brandl | 2010-06-27 05:55:38 -0500 (Sun, 27 Jun 2010) | 1 line
    
    Two typos.
  ........
................
  r82302 | benjamin.peterson | 2010-06-28 00:37:28 +0200 (Mon, 28 Jun 2010) | 15 lines
  
  Merged revisions 81380 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81380 | brett.cannon | 2010-05-20 13:37:55 -0500 (Thu, 20 May 2010) | 8 lines
    
    Turned out that if you used explicit relative import syntax
    (e.g. from .os import sep) and it failed, import would still try the implicit
    relative import semantics of an absolute import (from os import sep). That's
    not right, so when level is negative, only do explicit relative import
    semantics.
    
    Fixes issue #7902. Thanks to Meador Inge for the patch.
  ........
................
  r82304 | benjamin.peterson | 2010-06-28 00:41:29 +0200 (Mon, 28 Jun 2010) | 13 lines
  
  Merged revisions 81499,81506 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81499 | georg.brandl | 2010-05-24 16:29:07 -0500 (Mon, 24 May 2010) | 1 line
    
    #8016: add the CP858 codec (approved by Benjamin).  (Also add CP720 to the tests, it was missing there.)
  ........
    r81506 | benjamin.peterson | 2010-05-24 17:04:53 -0500 (Mon, 24 May 2010) | 1 line
    
    set svn:eol-style
  ........
................
  r82305 | benjamin.peterson | 2010-06-28 00:44:51 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82303 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82303 | benjamin.peterson | 2010-06-27 17:40:26 -0500 (Sun, 27 Jun 2010) | 1 line
    
    mark tracking tests as implementation details
  ........
................
  r82306 | benjamin.peterson | 2010-06-28 01:16:51 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Blocked revisions 81700 via svnmerge
  
  ........
    r81700 | martin.v.loewis | 2010-06-04 14:15:32 -0500 (Fri, 04 Jun 2010) | 2 lines
    
    Display installer warning that Windows 2000 won't 
    be supported in future releases.
  ........
................
  r82307 | benjamin.peterson | 2010-06-28 01:21:13 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 81880 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81880 | andrew.kuchling | 2010-06-10 19:14:34 -0500 (Thu, 10 Jun 2010) | 1 line
    
    Edit comments for current Python; bump version number of Python
  ........
................
  r82308 | benjamin.peterson | 2010-06-28 01:26:04 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Recorded merge of revisions 80866 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r80866 | andrew.kuchling | 2010-05-06 08:03:39 -0500 (Thu, 06 May 2010) | 1 line
    
    Use anonymous hyperlinks
  ........
................
  r82309 | benjamin.peterson | 2010-06-28 01:31:03 +0200 (Mon, 28 Jun 2010) | 8 lines
  
  Blocked revisions 80396 via svnmerge
  
  ........
    r80396 | sean.reifschneider | 2010-04-23 03:31:55 -0500 (Fri, 23 Apr 2010) | 2 lines
    
    issue8451: Making syslog module use sys.argv[0] for "ident".
  ........
................
  r82310 | benjamin.peterson | 2010-06-28 01:34:03 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 81004 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r81004 | mark.dickinson | 2010-05-08 14:13:21 -0500 (Sat, 08 May 2010) | 1 line
    
    Fix configure bug that was misreporting availability of MacOS X 10.5 SDK as available on Linux but not on OS X.
  ........
................
  r82311 | benjamin.peterson | 2010-06-28 01:49:45 +0200 (Mon, 28 Jun 2010) | 24 lines
  
  Merged revisions 79894-79895,80098,80120 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r79894 | jeroen.ruigrok | 2010-04-07 09:33:37 -0500 (Wed, 07 Apr 2010) | 5 lines
    
    FreeBSD is not a sysv platform, so use freebsd.S instead of sysv.S (as is
    also the case in FreeBSD's port of libffi).
    
    Reviewed by: dickinsm
  ........
    r79895 | jeroen.ruigrok | 2010-04-07 11:34:08 -0500 (Wed, 07 Apr 2010) | 2 lines
    
    Document the libffi FreeBSD fix.
  ........
    r80098 | benjamin.peterson | 2010-04-15 16:42:16 -0500 (Thu, 15 Apr 2010) | 1 line
    
    add space
  ........
    r80120 | antoine.pitrou | 2010-04-16 16:34:02 -0500 (Fri, 16 Apr 2010) | 3 lines
    
    Ignore jinja2
  ........
................
  r82312 | benjamin.peterson | 2010-06-28 01:53:17 +0200 (Mon, 28 Jun 2010) | 8 lines
  
  Blocked revisions 79596 via svnmerge
  
  ........
    r79596 | eric.smith | 2010-04-02 07:30:56 -0500 (Fri, 02 Apr 2010) | 1 line
    
    Issue 7994: Make object.__format__ with a non-empty format string a PendingDecprecationWarning. Still need to remove uses of this from various tests.
  ........
................
  r82313 | brett.cannon | 2010-06-28 01:57:46 +0200 (Mon, 28 Jun 2010) | 29 lines
  
  Implement importlib.abc.SourceLoader and deprecate PyLoader and PyPycLoader.
  
  SourceLoader is a simplification of both PyLoader and PyPycLoader. If one only
  wants to use source, then they need to only implement get_data and
  get_filename. To also use bytecode -- sourceless loading is not supported --
  then two abstract methods -- path_mtime and set_data -- need to be implemented.
  Compared to PyLoader and PyPycLoader, there are less abstract methods
  introduced and bytecode files become an optimization controlled by the ABC and
  hidden from the user (this need came about as PEP 3147 showed that not treating
  bytecode as an optimization can cause problems for compatibility).
  
  PyLoader is deprecated in favor of SourceLoader. To be compatible from Python
  3.1 onwards, a subclass need only use simple methods for source_path and
  is_package. Otherwise conditional subclassing based on whether Python 3.1 or
  Python 3.2 is being is the only change. The documentation and docstring for
  PyLoader explain what is exactly needed.
  
  PyPycLoader is deprecated also in favor of SourceLoader. Because PEP 3147
  shifted bytecode path details so much, there is no foolproof way to provide
  backwards-compatibility with SourceLoader. Because of this the class is simply
  deprecated and users should move to SourceLoader (and optionally PyLoader for
  Python 3.1). This does lead to a loss of support for sourceless loading
  unfortunately.
  
  At some point before Python 3.2 is released, SourceLoader will be moved over to
  importlib._bootstrap so that the core code of importlib relies on the new code
  instead of the old PyPycLoader code. This commit is being done now so that
  there is no issue in having the API in Python 3.1a1.
................
  r82314 | benjamin.peterson | 2010-06-28 02:01:59 +0200 (Mon, 28 Jun 2010) | 32 lines
  
  Merged revisions 77402,77505,77510 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r77402 | brett.cannon | 2010-01-09 20:56:19 -0600 (Sat, 09 Jan 2010) | 12 lines
    
    DeprecationWarning is now silent by default.
    
    This was originally suggested by Guido, discussed on the stdlib-sig mailing
    list, and given the OK by Guido directly to me. What this change essentially
    means is that Python has taken a policy of silencing warnings that are only
    of interest to developers by default. This should prevent users from seeing
    warnings which are triggered by an application being run against a new
    interpreter before the app developer has a chance to update their code.
    
    Closes issue #7319. Thanks to Antoine Pitrou, Ezio Melotti, and Brian Curtin
    for helping with the issue.
  ........
    r77505 | brett.cannon | 2010-01-14 14:00:28 -0600 (Thu, 14 Jan 2010) | 7 lines
    
    The silencing of DeprecationWarning was not taking -3 into consideration. Since
    Py3K warnings are DeprecationWarning by default this was causing -3 to
    essentially be a no-op. Now DeprecationWarning is only silenced if -3 is not
    used.
    
    Closes issue #7700. Thanks Ezio Melotti and Florent Xicluna for patch help.
  ........
    r77510 | brett.cannon | 2010-01-14 19:31:45 -0600 (Thu, 14 Jan 2010) | 1 line
    
    Remove C++/C99-style comments.
  ........
................
  r82315 | benjamin.peterson | 2010-06-28 02:16:12 +0200 (Mon, 28 Jun 2010) | 1 line
  
  fix versionchanged
................
  r82316 | benjamin.peterson | 2010-06-28 02:24:13 +0200 (Mon, 28 Jun 2010) | 1 line
  
  fix test with more obviously incorrect bytecode
................
  r82318 | benjamin.peterson | 2010-06-28 05:07:10 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82317 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82317 | benjamin.peterson | 2010-06-27 21:58:25 -0500 (Sun, 27 Jun 2010) | 1 line
    
    remove unused last argument to property_copy
  ........
................
  r82320 | brett.cannon | 2010-06-28 06:57:24 +0200 (Mon, 28 Jun 2010) | 11 lines
  
  Move importlib.abc.SourceLoader to _bootstrap.
  
  Required updating code relying on other modules to switch to _bootstrap's
  unique module requirements. This led to the realization that
  get_code was being too liberal in its exception catching when calling set_data
  by blindly grabbing IOError. Shifted the responsibility of safely ignoring
  writes to a read-only path to set_data.
  
  Importlib is still not relying on SourceLoader yet; requires creating a
  SourcelessLoader and updating the source finder.
................
  r82321 | brett.cannon | 2010-06-28 07:46:25 +0200 (Mon, 28 Jun 2010) | 2 lines
  
  Add an inheritance test for importlib.abc.SourceLoader.
................
  r82326 | senthil.kumaran | 2010-06-28 16:08:00 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82324 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82324 | senthil.kumaran | 2010-06-28 19:26:46 +0530 (Mon, 28 Jun 2010) | 3 lines
    
    Fix Issue8653 - Docstring for urlunsplit function.
  ........
................
  r82328 | alexander.belopolsky | 2010-06-28 16:36:55 +0200 (Mon, 28 Jun 2010) | 1 line
  
  Added missing white space
................
  r82331 | benjamin.peterson | 2010-06-28 17:39:55 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82330 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82330 | benjamin.peterson | 2010-06-28 10:36:40 -0500 (Mon, 28 Jun 2010) | 1 line
    
    testcapi tests are definitely cpython only
  ........
................
  r82333 | benjamin.peterson | 2010-06-28 17:43:25 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82332 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82332 | benjamin.peterson | 2010-06-28 10:41:06 -0500 (Mon, 28 Jun 2010) | 1 line
    
    fix skipping condition
  ........
................
  r82336 | senthil.kumaran | 2010-06-28 19:31:40 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82334 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82334 | senthil.kumaran | 2010-06-28 22:37:40 +0530 (Mon, 28 Jun 2010) | 3 lines
    
    Documentation correction. urllib2.urlopen.info returns a mimetools.Message instance not HTTPMessage object.
  ........
................
  r82342 | benjamin.peterson | 2010-06-28 21:43:42 +0200 (Mon, 28 Jun 2010) | 1 line
  
  update error message
................
  r82343 | mark.dickinson | 2010-06-28 21:44:20 +0200 (Mon, 28 Jun 2010) | 23 lines
  
  Merged revisions 82338,82340-82341 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82338 | mark.dickinson | 2010-06-28 20:31:41 +0100 (Mon, 28 Jun 2010) | 9 lines
    
    Fix some shallow bugs in Demo/parser/unparse.py, and add tests:
    
      - insert commas between entries in del statement
      - left and right shifts were represented as >> and << (respectively); reverse
      - unindent properly after for: else:  or while: else:
      - add parens around the result of an unary operation
      - add parens around negative numbers, to avoid turning (-1)**2 into -1**2.
  ........
    r82340 | mark.dickinson | 2010-06-28 20:34:15 +0100 (Mon, 28 Jun 2010) | 1 line
    
    Fix typo in test_unparse.py.
  ........
    r82341 | mark.dickinson | 2010-06-28 20:38:19 +0100 (Mon, 28 Jun 2010) | 1 line
    
    Set svn:eol-style on test_unparse.py.
  ........
................
  r82346 | mark.dickinson | 2010-06-28 22:09:18 +0200 (Mon, 28 Jun 2010) | 9 lines
  
  Merged revisions 82345 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82345 | mark.dickinson | 2010-06-28 20:54:19 +0100 (Mon, 28 Jun 2010) | 1 line
    
    unparse.py:  fix mispaced parentheses in chained comparisons
  ........
................
  r82347 | mark.dickinson | 2010-06-28 23:14:17 +0200 (Mon, 28 Jun 2010) | 18 lines
  
  Update Demo/parser/unparse.py to current Python 3.x syntax.  Additions:
   - relative imports
   - keyword-only arguments
   - function annotations
   - class decorators
   - raise ... from ...
   - except ... as ...
   - nonlocal
   - bytes literals
   - set literals
   - set comprehensions
   - dict comprehensions
  Removals:
   - print statement.
  
  Some of this should be backported to 2.x.
................
  r82349 | mark.dickinson | 2010-06-28 23:39:51 +0200 (Mon, 28 Jun 2010) | 1 line
  
  unparse.py: Typo fix.
................
  r82351 | brian.curtin | 2010-06-29 02:14:28 +0200 (Tue, 29 Jun 2010) | 3 lines
  
  Update md5driver.py for 3.x.
  Changed an import, replaced md5.new() with md5(), and added an encode where needed.
................
  r82354 | benjamin.peterson | 2010-06-29 03:27:35 +0200 (Tue, 29 Jun 2010) | 1 line
  
  rephrase and remove uneeded statement
................
  r82357 | mark.dickinson | 2010-06-29 09:38:37 +0200 (Tue, 29 Jun 2010) | 9 lines
  
  Merged revisions 82356 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82356 | mark.dickinson | 2010-06-29 08:37:25 +0100 (Tue, 29 Jun 2010) | 1 line
    
    Spelling.
  ........
................
  r82358 | mark.dickinson | 2010-06-29 09:48:23 +0200 (Tue, 29 Jun 2010) | 1 line
  
  unparse.py: respect coding cookie in input files
................
  r82359 | mark.dickinson | 2010-06-29 10:52:36 +0200 (Tue, 29 Jun 2010) | 1 line
  
  Add parentheses around numeric literals, to avoid turning 3 .bit_length() into 3.bit_length().
................
  r82360 | mark.dickinson | 2010-06-29 12:01:48 +0200 (Tue, 29 Jun 2010) | 8 lines
  
  More unparse.py fixes:
  
   - parenthesize lambdas, to avoid turning (lambda : int)() into lambda: int()
   - unparse an infinite float literals in the AST as an overflowing finite value
  
  unparse.py now successfully round-trips on all valid Lib/*.py and Lib/test/*.py files.
................
  r82365 | mark.dickinson | 2010-06-29 16:08:23 +0200 (Tue, 29 Jun 2010) | 1 line
  
  test_unparse.py: Do roundtrip testing for all Python files in Lib and Lib/test.
................
  r82370 | vinay.sajip | 2010-06-29 17:31:15 +0200 (Tue, 29 Jun 2010) | 1 line
  
  Added information about pickle security and SocketHandler, and some cross-reference targets.
................
  r82371 | benjamin.peterson | 2010-06-29 17:32:34 +0200 (Tue, 29 Jun 2010) | 8 lines
  
  Blocked revisions 82368 via svnmerge
  
  ........
    r82368 | benjamin.peterson | 2010-06-29 10:18:02 -0500 (Tue, 29 Jun 2010) | 1 line
    
    group cStringIO docs under its factory function
  ........
................
  r82373 | benjamin.peterson | 2010-06-29 17:57:57 +0200 (Tue, 29 Jun 2010) | 1 line
  
  note that byte strings can be raw, too #9114
................
  r82375 | brett.cannon | 2010-06-29 20:26:11 +0200 (Tue, 29 Jun 2010) | 1 line
  
  Make a sentence a little less awkward.
................
  r82376 | benjamin.peterson | 2010-06-29 20:36:39 +0200 (Tue, 29 Jun 2010) | 1 line
  
  update for nonlocal keyword
................
  r82377 | mark.dickinson | 2010-06-29 20:38:59 +0200 (Tue, 29 Jun 2010) | 1 line
  
  Fix typo in unparsing of a class definition.
................
  r82381 | mark.dickinson | 2010-06-29 22:10:42 +0200 (Tue, 29 Jun 2010) | 9 lines
  
  Merged revisions 82379 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82379 | mark.dickinson | 2010-06-29 21:09:12 +0100 (Tue, 29 Jun 2010) | 1 line
    
    Issue #1789:  clarify that the 'size' column in struct docs refers to standard size.
  ........
................
  r82383 | mark.dickinson | 2010-06-30 10:32:11 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Collapse else: if: ... into elif: 
................
  r82384 | mark.dickinson | 2010-06-30 10:46:53 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Output try-except-finally statements where appropriate.
................
  r82386 | mark.dickinson | 2010-06-30 11:05:47 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Better solution for attribute access on integer literals.
................
  r82387 | mark.dickinson | 2010-06-30 11:14:43 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Remove backtick syntax for repr.
................
  r82391 | mark.dickinson | 2010-06-30 13:13:36 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Issue #9011:  Tests for Python 3.2's treatment of negated imaginary literals.
................
  r82392 | mark.dickinson | 2010-06-30 13:14:30 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Revert accidental extra changes included in r82391.
................
  r82393 | mark.dickinson | 2010-06-30 13:45:53 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Unparse infinite imaginary literals correctly.  Add some more numeric tests.
................
  r82394 | michael.foord | 2010-06-30 14:17:50 +0200 (Wed, 30 Jun 2010) | 1 line
  
  Issue 9110. Adding ContextDecorator to contextlib. This enables the creation of APIs that act as decorators as well as context managers. contextlib.contextmanager changed to use ContextDecorator.
................
  r82402 | mark.dickinson | 2010-06-30 18:36:12 +0200 (Wed, 30 Jun 2010) | 12 lines
  
  Blocked revisions 82399-82400 via svnmerge
  
  ........
    r82399 | mark.dickinson | 2010-06-30 15:19:56 +0100 (Wed, 30 Jun 2010) | 1 line
    
    Update Demo/parser directory; backport unparse fixes from py3k.
  ........
    r82400 | mark.dickinson | 2010-06-30 17:27:57 +0100 (Wed, 30 Jun 2010) | 2 lines
    
    Issue #9125:  Update parser module for "except ... as ..." syntax.
  ........
................
  r82405 | benjamin.peterson | 2010-06-30 19:39:45 +0200 (Wed, 30 Jun 2010) | 9 lines
  
  Merged revisions 82403 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82403 | benjamin.peterson | 2010-06-30 12:11:08 -0500 (Wed, 30 Jun 2010) | 1 line
    
    mark test depending on ref counting
  ........
................
  r82407 | giampaolo.rodola | 2010-06-30 19:47:39 +0200 (Wed, 30 Jun 2010) | 9 lines
  
  Merged revisions 82404 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82404 | giampaolo.rodola | 2010-06-30 19:38:28 +0200 (mer, 30 giu 2010) | 1 line
    
    fix issue #6589: cleanup asyncore.socket_map if smtpd.SMTPServer constructor raises an exception
  ........
................
  r82410 | benjamin.peterson | 2010-06-30 20:44:04 +0200 (Wed, 30 Jun 2010) | 9 lines
  
  Merged revisions 82409 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82409 | benjamin.peterson | 2010-06-30 13:41:08 -0500 (Wed, 30 Jun 2010) | 1 line
    
    an AttributeError is perfectly acceptable here
  ........
................
  r82413 | ezio.melotti | 2010-07-01 09:32:02 +0200 (Thu, 01 Jul 2010) | 13 lines
  
  Update PyUnicode_DecodeUTF8 from RFC 2279 to RFC 3629.
  
  1) #8271: when a byte sequence is invalid, only the start byte and all the
     valid continuation bytes are now replaced by U+FFFD, instead of replacing
     the number of bytes specified by the start byte.
     See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (pages 94-95);
  2) 5- and 6-bytes-long UTF-8 sequences are now considered invalid (no changes
     in behavior);
  3) Change the error messages "unexpected code byte" to "invalid start byte"
     and "invalid data" to "invalid continuation byte";
  4) Add an extensive set of tests in test_unicode;
  5) Fix test_codeccallbacks because it was failing after this change.
................
  r82416 | benjamin.peterson | 2010-07-01 17:09:14 +0200 (Thu, 01 Jul 2010) | 8 lines
  
  Blocked revisions 82415 via svnmerge
  
  ........
    r82415 | benjamin.peterson | 2010-07-01 10:07:15 -0500 (Thu, 01 Jul 2010) | 1 line
    
    remove docs about delegating to special methods; it does no such thing
  ........
................
  r82417 | benjamin.peterson | 2010-07-01 17:16:55 +0200 (Thu, 01 Jul 2010) | 1 line
  
  correctly lookup __trunc__ and __floor__
................
  r82422 | benjamin.peterson | 2010-07-01 19:49:01 +0200 (Thu, 01 Jul 2010) | 9 lines
  
  Merged revisions 82420 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82420 | benjamin.peterson | 2010-07-01 12:45:52 -0500 (Thu, 01 Jul 2010) | 1 line
    
    fix fixer name
  ........
................
  r82430 | benjamin.peterson | 2010-07-02 01:39:26 +0200 (Fri, 02 Jul 2010) | 8 lines
  
  Blocked revisions 82429 via svnmerge
  
  ........
    r82429 | benjamin.peterson | 2010-07-01 18:35:37 -0500 (Thu, 01 Jul 2010) | 1 line
    
    trunc does use the special method, though
  ........
................
  r82434 | georg.brandl | 2010-07-02 09:41:51 +0200 (Fri, 02 Jul 2010) | 9 lines
  
  Merged revisions 82433 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82433 | georg.brandl | 2010-07-02 09:33:50 +0200 (Fr, 02 Jul 2010) | 1 line
    
    Grammar and markup fixes.
  ........
................
  r82437 | benjamin.peterson | 2010-07-02 15:35:17 +0200 (Fri, 02 Jul 2010) | 1 line
  
  account for different ref counting semantics of _PyObject_LookupSpecial
................
  r82438 | benjamin.peterson | 2010-07-02 15:46:42 +0200 (Fri, 02 Jul 2010) | 1 line
  
  fix lookup of __ceil__
................
  r82440 | nick.coghlan | 2010-07-02 17:57:50 +0200 (Fri, 02 Jul 2010) | 9 lines
  
  Merged revisions 82439 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82439 | nick.coghlan | 2010-07-03 01:50:14 +1000 (Sat, 03 Jul 2010) | 1 line
    
    Fix a couple of minor nits in What's New before the release goes out
  ........
................
  r82442 | mark.dickinson | 2010-07-02 18:05:15 +0200 (Fri, 02 Jul 2010) | 1 line
  
  Style/consistency nit: make math_floor and math_ceil code look the same.
................
  r82443 | nick.coghlan | 2010-07-02 18:14:05 +0200 (Fri, 02 Jul 2010) | 9 lines
  
  Merged revisions 82441 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82441 | nick.coghlan | 2010-07-03 02:01:53 +1000 (Sat, 03 Jul 2010) | 1 line
    
    Issue 8202 actually caused an unintended behavioural change and was reverted in 2.7 - remove reference from What's New
  ........
................
  r82448 | benjamin.peterson | 2010-07-02 21:45:07 +0200 (Fri, 02 Jul 2010) | 9 lines
  
  Merged revisions 82447 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82447 | benjamin.peterson | 2010-07-02 14:41:39 -0500 (Fri, 02 Jul 2010) | 1 line
    
    add space
  ........
................
  r82452 | mark.dickinson | 2010-07-02 22:26:07 +0200 (Fri, 02 Jul 2010) | 9 lines
  
  Merged revisions 82446 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82446 | mark.dickinson | 2010-07-02 19:06:52 +0100 (Fri, 02 Jul 2010) | 1 line
    
    Clarify sys.float_info documentation.
  ........
................
  r82456 | brett.cannon | 2010-07-03 00:03:00 +0200 (Sat, 03 Jul 2010) | 7 lines
  
  Some people have mistaken Python bytecode as being stable and unchanging. In
  reality it's simply an implementation detail for CPython. This point is now
  clearly documented in both the docs for dis and the glossary.
  
  Closes issue #7829. Thanks to Terry Reedy for some initial suggestions on
  wording.
................
  r82462 | ezio.melotti | 2010-07-03 01:18:51 +0200 (Sat, 03 Jul 2010) | 17 lines
  
  Merged revisions 82455,82457,82459 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82455 | eric.smith | 2010-07-03 00:44:16 +0300 (Sat, 03 Jul 2010) | 1 line
    
    Moved period outside paren, where it belongs.
  ........
    r82457 | ezio.melotti | 2010-07-03 01:17:29 +0300 (Sat, 03 Jul 2010) | 1 line
    
    #9139: Add examples for str.format().
  ........
    r82459 | ezio.melotti | 2010-07-03 01:50:39 +0300 (Sat, 03 Jul 2010) | 1 line
    
    #9139: the thousands separator is new in 2.7.  Also add a missing variable in the example.
  ........
................
  r82464 | benjamin.peterson | 2010-07-03 01:25:44 +0200 (Sat, 03 Jul 2010) | 9 lines
  
  Merged revisions 82461 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82461 | benjamin.peterson | 2010-07-02 18:05:27 -0500 (Fri, 02 Jul 2010) | 1 line
    
    don't require the presence of __getformat__ or __setformat__; use requires_IEEE_754 globally
  ........
................
  r82465 | brett.cannon | 2010-07-03 03:32:48 +0200 (Sat, 03 Jul 2010) | 3 lines
  
  Make test_import a little bit more robust for cleaning up after itself in the
  face of a failure.
................
  r82467 | alexander.belopolsky | 2010-07-03 05:35:27 +0200 (Sat, 03 Jul 2010) | 9 lines
  
  Merged revisions 82466 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82466 | alexander.belopolsky | 2010-07-02 23:27:12 -0400 (Fri, 02 Jul 2010) | 1 line
    
    Revert r81681 (issue 8810).
  ........
................
  r82468 | ezio.melotti | 2010-07-03 06:52:19 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Update comment about surrogates.
................
  r82471 | nick.coghlan | 2010-07-03 09:36:51 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Issue 6507: accept source strings directly in dis.dis(). Original patch by Daniel Urban
................
  r82472 | nick.coghlan | 2010-07-03 09:38:28 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Issue 6507: missing patch submitter from NEWS entry in previous checkin
................
  r82478 | mark.dickinson | 2010-07-03 11:17:16 +0200 (Sat, 03 Jul 2010) | 9 lines
  
  Merged revisions 82476 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82476 | mark.dickinson | 2010-07-03 10:15:09 +0100 (Sat, 03 Jul 2010) | 1 line
    
    Fix typo in sys.float_info docs.
  ........
................
  r82480 | georg.brandl | 2010-07-03 12:21:50 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Wrap and use the correct directive.
................
  r82481 | georg.brandl | 2010-07-03 12:22:10 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Use the right role.
................
  r82484 | georg.brandl | 2010-07-03 12:26:17 +0200 (Sat, 03 Jul 2010) | 9 lines
  
  Recorded merge of revisions 82474 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82474 | georg.brandl | 2010-07-03 10:40:13 +0200 (Sa, 03 Jul 2010) | 1 line
    
    Fix role name.
  ........
................
  r82485 | georg.brandl | 2010-07-03 12:26:54 +0200 (Sat, 03 Jul 2010) | 9 lines
  
  Merged revisions 82483 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82483 | georg.brandl | 2010-07-03 12:25:54 +0200 (Sa, 03 Jul 2010) | 1 line
    
    Add link to bytecode docs.
  ........
................
  r82487 | georg.brandl | 2010-07-03 12:33:26 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Fix markup.
................
  r82488 | georg.brandl | 2010-07-03 12:41:33 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Remove the need for a "()" empty argument list after opcodes.
................
  r82495 | victor.stinner | 2010-07-03 15:44:22 +0200 (Sat, 03 Jul 2010) | 10 lines
  
  Merged revisions 82492 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r82492 | victor.stinner | 2010-07-03 15:36:19 +0200 (sam., 03 juil. 2010) | 3 lines
    
    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
  ........
................
  r82507 | benjamin.peterson | 2010-07-03 17:09:20 +0200 (Sat, 03 Jul 2010) | 3 lines
  
  Removed merge tracking for "svnmerge" for 
  svn+ssh://pythondev@svn.python.org/python/branches/py3k/python/trunk
................
  r82510 | senthil.kumaran | 2010-07-03 19:48:22 +0200 (Sat, 03 Jul 2010) | 4 lines
  
  Fix Issue5468 - urlencode to handle bytes and other alternate encodings.
  (Extensive tests provided). Patch by Dan Mahn.
................
  r82514 | alexander.belopolsky | 2010-07-03 22:35:53 +0200 (Sat, 03 Jul 2010) | 3 lines
  
  Issue #9094: Make python -m pickletools disassemble pickles given in
  the command line.
................
  r82515 | mark.dickinson | 2010-07-03 23:00:51 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Remove nonexistent tools from Tools README.
................
  r82516 | brett.cannon | 2010-07-03 23:37:28 +0200 (Sat, 03 Jul 2010) | 2 lines
  
  Ignore __pycache__.
................
  r82517 | alexander.belopolsky | 2010-07-03 23:42:47 +0200 (Sat, 03 Jul 2010) | 3 lines
  
  Issue #9151: Demo/classes/Dates.py does not work in 3.x
  Made minimal changes to make included test pass.
................
  r82518 | brett.cannon | 2010-07-03 23:48:25 +0200 (Sat, 03 Jul 2010) | 34 lines
  
  Make importlib.abc.SourceLoader the primary mechanism for importlib.
  
  This required moving the class from importlib/abc.py into
  importlib/_bootstrap.py and jiggering some code to work better with the class.
  This included changing how the file finder worked to better meet import
  semantics. This also led to fixing importlib to handle the empty string from
  sys.path as import currently does (and making me wish we didn't support that
  instead just required people to insert '.' instead to represent cwd).
  
  It also required making the new set_data abstractmethod create
  any needed subdirectories implicitly thanks to __pycache__ (it was either this
  or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir
  method or have set_data with no data arg mean to create a directory).
  
  Lastly, as an optimization the file loaders cache the file path where the
  finder found something to use for loading (this is thanks to having a
  sourceless loader separate from the source loader to simplify the code and
  cut out stat calls).
  Unfortunately test_runpy assumed a loader would always work for a module, even
  if you changed from underneath it what it was expected to work with. By simply
  dropping the previous loader in test_runpy so the proper loader can be returned
  by the finder fixed the failure.
  
  At this point importlib deviates from import on two points:
  
  1. The exception raised when trying to import a file is different (import does
  an explicit file check to print a special message, importlib just says the path
  cannot be imported as if it was just some module name).
  
  2. the co_filename on a code object is not being set to where bytecode was
  actually loaded from instead of where the marshalled code object originally
  came from (a solution for this has already been agreed upon on python-dev but has
  not been implemented yet; issue8611).
................
  r82519 | brett.cannon | 2010-07-03 23:50:52 +0200 (Sat, 03 Jul 2010) | 1 line
  
  Trailing whitespace is bad for .rst files.
................
  r82520 | brett.cannon | 2010-07-04 00:03:16 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Fix a spelling mistake in a comment.
................
  r82521 | alexander.belopolsky | 2010-07-04 00:05:41 +0200 (Sun, 04 Jul 2010) | 5 lines
  
  Issue #9151: Demo/classes/Dates.py does not work in 3.x Converted
  descriptive comment into a docstring.  Cast attributes to int in
  __init__.  Use __new__ instead of deleting attributes to
  "uninitialize".
................
  r82522 | brett.cannon | 2010-07-04 00:18:47 +0200 (Sun, 04 Jul 2010) | 34 lines
  
  Make importlib.abc.SourceLoader the primary mechanism for importlib.
  
  This required moving the class from importlib/abc.py into
  importlib/_bootstrap.py and jiggering some code to work better with the class.
  This included changing how the file finder worked to better meet import
  semantics. This also led to fixing importlib to handle the empty string from
  sys.path as import currently does (and making me wish we didn't support that
  instead just required people to insert '.' instead to represent cwd).
  
  It also required making the new set_data abstractmethod create
  any needed subdirectories implicitly thanks to __pycache__ (it was either this
  or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir
  method or have set_data with no data arg mean to create a directory).
  
  Lastly, as an optimization the file loaders cache the file path where the
  finder found something to use for loading (this is thanks to having a
  sourceless loader separate from the source loader to simplify the code and
  cut out stat calls).
  Unfortunately test_runpy assumed a loader would always work for a module, even
  if you changed from underneath it what it was expected to work with. By simply
  dropping the previous loader in test_runpy so the proper loader can be returned
  by the finder fixed the failure.
  
  At this point importlib deviates from import on two points:
  
  1. The exception raised when trying to import a file is different (import does
  an explicit file check to print a special message, importlib just says the path
  cannot be imported as if it was just some module name).
  
  2. the co_filename on a code object is not being set to where bytecode was
  actually loaded from instead of where the marshalled code object originally
  came from (a solution for this has already been agreed upon on python-dev but has
  not been implemented yet; issue8611).
................
  r82523 | brett.cannon | 2010-07-04 00:32:41 +0200 (Sun, 04 Jul 2010) | 34 lines
  
  Make importlib.abc.SourceLoader the primary mechanism for importlib.
  
  This required moving the class from importlib/abc.py into
  importlib/_bootstrap.py and jiggering some code to work better with the class.
  This included changing how the file finder worked to better meet import
  semantics. This also led to fixing importlib to handle the empty string from
  sys.path as import currently does (and making me wish we didn't support that
  instead just required people to insert '.' instead to represent cwd).
  
  It also required making the new set_data abstractmethod create
  any needed subdirectories implicitly thanks to __pycache__ (it was either this
  or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir
  method or have set_data with no data arg mean to create a directory).
  
  Lastly, as an optimization the file loaders cache the file path where the
  finder found something to use for loading (this is thanks to having a
  sourceless loader separate from the source loader to simplify the code and
  cut out stat calls).
  Unfortunately test_runpy assumed a loader would always work for a module, even
  if you changed from underneath it what it was expected to work with. By simply
  dropping the previous loader in test_runpy so the proper loader can be returned
  by the finder fixed the failure.
  
  At this point importlib deviates from import on two points:
  
  1. The exception raised when trying to import a file is different (import does
  an explicit file check to print a special message, importlib just says the path
  cannot be imported as if it was just some module name).
  
  2. the co_filename on a code object is not being set to where bytecode was
  actually loaded from instead of where the marshalled code object originally
  came from (a solution for this has already been agreed upon on python-dev but has
  not been implemented yet; issue8611).
................
  r82524 | alexander.belopolsky | 2010-07-04 00:36:06 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Made minimal modifications to pass included tests
................
  r82526 | georg.brandl | 2010-07-04 09:25:18 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Remove old and unsafe Dbm demo class.
................
  r82527 | mark.dickinson | 2010-07-04 12:15:11 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Fix refleak in Modules/audioop.c.
................
  r82533 | alexander.belopolsky | 2010-07-04 18:28:08 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Issue #9152: Removed dead code in datetime module
................
  r82535 | benjamin.peterson | 2010-07-04 18:33:07 +0200 (Sun, 04 Jul 2010) | 3 lines
  
  Removed merge tracking for "svnmerge" for 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
................
  r82537 | mark.dickinson | 2010-07-04 18:37:31 +0200 (Sun, 04 Jul 2010) | 2 lines
  
  Issue #9128: Fix validation of class decorators in parser module.
................
  r82538 | benjamin.peterson | 2010-07-04 18:37:39 +0200 (Sun, 04 Jul 2010) | 3 lines
  
  Initialized merge tracking via "svnmerge" with revisions "0-80937" from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3
................
  r82540 | benjamin.peterson | 2010-07-04 18:40:27 +0200 (Sun, 04 Jul 2010) | 3 lines
  
  Removed merge tracking for "svnmerge" for 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3
................
  r82541 | benjamin.peterson | 2010-07-04 18:41:33 +0200 (Sun, 04 Jul 2010) | 3 lines
  
  Initialized merge tracking via "svnmerge" with revisions "0-80937" from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
................
  r82542 | benjamin.peterson | 2010-07-04 18:44:15 +0200 (Sun, 04 Jul 2010) | 17 lines
  
  Merged revisions 81478,82530-82531 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r81478 | benjamin.peterson | 2010-05-22 13:47:39 -0500 (Sat, 22 May 2010) | 1 line
    
    ensure doctests have some future_features
  ........
    r82530 | benjamin.peterson | 2010-07-04 11:11:41 -0500 (Sun, 04 Jul 2010) | 1 line
    
    simplify ignore star imports from itertools #8892
  ........
    r82531 | benjamin.peterson | 2010-07-04 11:13:20 -0500 (Sun, 04 Jul 2010) | 1 line
    
    wrap with parenthesis not \
  ........
................
  r82547 | alexander.belopolsky | 2010-07-04 19:00:20 +0200 (Sun, 04 Jul 2010) | 3 lines
  
  Issue #9118: help(None) will now return NoneType doc instead of
  starting interactive help.
................
  r82550 | alexander.belopolsky | 2010-07-04 19:38:32 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Fixed doctests
................
  r82551 | alexander.belopolsky | 2010-07-04 19:47:30 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Fixed the test
................
  r82552 | mark.dickinson | 2010-07-04 20:11:51 +0200 (Sun, 04 Jul 2010) | 2 lines
  
  Issue #9130: Fix validation of relative imports in parser module.
................
  r82553 | mark.dickinson | 2010-07-04 20:15:26 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Fix symbol numbers in test_parser test.
................
  r82555 | mark.dickinson | 2010-07-04 20:38:57 +0200 (Sun, 04 Jul 2010) | 2 lines
  
  Issue #9130: Validate ellipsis tokens in relative imports.
................
  r82557 | mark.dickinson | 2010-07-04 20:49:18 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Make Demo/parser/test_parser.py run.
................
  r82558 | mark.dickinson | 2010-07-04 21:23:49 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Remove coding cookie from heapq.py.
................
  r82559 | mark.dickinson | 2010-07-04 21:27:12 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Re-encode shlex.py in UTF-8, and remove coding cookie.
................
  r82560 | mark.dickinson | 2010-07-04 22:07:09 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Revert -r82559;  it's not clear that this is the right thing to do, and the change obscures the original intentions.
................
  r82561 | andrew.kuchling | 2010-07-04 22:47:00 +0200 (Sun, 04 Jul 2010) | 1 line
  
  Add brief explanation; remove no-longer-working link
................
  r82567 | brett.cannon | 2010-07-05 00:05:34 +0200 (Mon, 05 Jul 2010) | 5 lines
  
  Do some basic refactoring. Along the way also list what files had their
  whitespace cleaned up and do the proper plurality for "N file(s)" based on N.
  
  Refactoring closes issue8912. Thanks to Éric Araujo for the patch.
................
  r82570 | senthil.kumaran | 2010-07-05 13:41:42 +0200 (Mon, 05 Jul 2010) | 3 lines
  
  Fix: Issue9091 Minor documentation clarification.
................
  r82573 | senthil.kumaran | 2010-07-05 14:00:56 +0200 (Mon, 05 Jul 2010) | 3 lines
  
  Fix the docstrings of the capitalize method.
................
  r82576 | benjamin.peterson | 2010-07-05 16:59:40 +0200 (Mon, 05 Jul 2010) | 1 line
  
  pydoc still has a silly encoding
................
  r82577 | benjamin.peterson | 2010-07-05 17:01:22 +0200 (Mon, 05 Jul 2010) | 1 line
  
  cleanup basicsize logic #3268
................
  r82578 | alexander.belopolsky | 2010-07-05 17:05:33 +0200 (Mon, 05 Jul 2010) | 1 line
  
  Added more tests for utctimetuple()
................
  r82585 | benjamin.peterson | 2010-07-05 19:11:05 +0200 (Mon, 05 Jul 2010) | 1 line
  
  looking up on the type is correct, so this isn't an XXX
................
  r82587 | georg.brandl | 2010-07-05 19:48:38 +0200 (Mon, 05 Jul 2010) | 1 line
  
  #9166: NotImplemented is not an exception.
................
  r82589 | alexander.belopolsky | 2010-07-05 19:57:31 +0200 (Mon, 05 Jul 2010) | 1 line
  
  Added two more test cases for datetime
................
  r82591 | benjamin.peterson | 2010-07-05 22:04:54 +0200 (Mon, 05 Jul 2010) | 1 line
  
  untabify
................
  r82593 | georg.brandl | 2010-07-05 22:13:06 +0200 (Mon, 05 Jul 2010) | 1 line
  
  Remove Dbm.
................
  r82594 | georg.brandl | 2010-07-05 22:13:41 +0200 (Mon, 05 Jul 2010) | 1 line
  
  Update Vec class constructor, remove indirection via function, use operator module.
................
  r82595 | mark.dickinson | 2010-07-05 22:14:26 +0200 (Mon, 05 Jul 2010) | 1 line
  
  Post-detabification cleanup.
................
  r82597 | victor.stinner | 2010-07-05 23:36:21 +0200 (Mon, 05 Jul 2010) | 2 lines
  
  #9158: Fix y* format of PyArg_Parse*() functions documentation
................
  r82599 | alexander.belopolsky | 2010-07-05 23:44:05 +0200 (Mon, 05 Jul 2010) | 1 line
  
  "Modernized" the demo a little.
................
  r82600 | brett.cannon | 2010-07-06 00:11:16 +0200 (Tue, 06 Jul 2010) | 1 line
  
  Fix test_xmlrpc_net to no longer fail since there are no more buildbots for trunk.
................
  r82601 | senthil.kumaran | 2010-07-06 04:08:36 +0200 (Tue, 06 Jul 2010) | 3 lines
  
  Change 'lowered' to 'lowercased'
................
  r82604 | matthias.klose | 2010-07-06 12:53:30 +0200 (Tue, 06 Jul 2010) | 2 lines
  
  - sysmodule.c (get_hash_info): Define as static function.
................
  r82607 | mark.dickinson | 2010-07-06 17:00:40 +0200 (Tue, 06 Jul 2010) | 1 line
  
  Indentation and PEP 7 fixes.
................
  r82609 | vinay.sajip | 2010-07-06 17:08:55 +0200 (Tue, 06 Jul 2010) | 1 line
  
  Minor improvements to logging documentation.
................
  r82610 | mark.dickinson | 2010-07-06 17:11:44 +0200 (Tue, 06 Jul 2010) | 1 line
  
  Style nit.
................
  r82615 | georg.brandl | 2010-07-07 00:58:50 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Fix typo.
................
  r82617 | alexander.belopolsky | 2010-07-07 01:19:45 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Issue #9000: datetime.timezone objects now have eval-friendly repr.
................
  r82624 | mark.dickinson | 2010-07-07 18:10:44 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Kill gratuitous space.
................
  r82625 | mark.dickinson | 2010-07-07 18:17:31 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Minor refactoring in lgamma code, for clarity.
................
  r82626 | mark.dickinson | 2010-07-07 18:21:29 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Issue #9186:  log1p(-1.0) should raise ValueError, not OverflowError.
................
  r82628 | benjamin.peterson | 2010-07-07 20:44:05 +0200 (Wed, 07 Jul 2010) | 1 line
  
  this needn't be in the loop
................
  r82629 | georg.brandl | 2010-07-07 20:51:43 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Make comment out of an awkward note.
................
  r82630 | benjamin.peterson | 2010-07-07 20:54:59 +0200 (Wed, 07 Jul 2010) | 1 line
  
  don't ignore exceptions from PyObject_IsTrue
................
  r82632 | georg.brandl | 2010-07-07 21:04:36 +0200 (Wed, 07 Jul 2010) | 1 line
  
  Turn more notes into comments.
................
  r82633 | benjamin.peterson | 2010-07-07 21:04:48 +0200 (Wed, 07 Jul 2010) | 1 line
  
  add NEWS
................
  r82636 | benjamin.peterson | 2010-07-07 22:54:01 +0200 (Wed, 07 Jul 2010) | 4 lines
  
  make struct sequences subclass tuple; kill lots of code
  
  This fixes #8413.
................
  r82637 | benjamin.peterson | 2010-07-08 00:45:06 +0200 (Thu, 08 Jul 2010) | 1 line
  
  ValueError in this case is also acceptable
................
  r82642 | alexander.belopolsky | 2010-07-08 01:56:38 +0200 (Thu, 08 Jul 2010) | 1 line
  
  Issue #5288: Eliminated round-trips between timdelta and int offsets
................
  r82644 | ezio.melotti | 2010-07-08 17:03:02 +0200 (Thu, 08 Jul 2010) | 1 line
  
  Fix typo in a comment in mathmodule.c.
................
  r82646 | mark.dickinson | 2010-07-08 19:23:40 +0200 (Thu, 08 Jul 2010) | 1 line
  
  In test_decimal, convert heuristic for skipping tests into an explicit skiplist.
................
  r82647 | antoine.pitrou | 2010-07-08 20:51:30 +0200 (Thu, 08 Jul 2010) | 3 lines
  
  Issue #8605: Skip test_gdb if Python is compiled with optimizations.
................
  r82649 | mark.dickinson | 2010-07-08 21:03:34 +0200 (Thu, 08 Jul 2010) | 1 line
  
  Fix a performance issue in Decimal.pow.  Thanks Stefan Krah for finding this.
................
  r82650 | mark.dickinson | 2010-07-08 21:09:16 +0200 (Thu, 08 Jul 2010) | 1 line
  
  Fix misplaced exactness check that was causing unnecessary work in Decimal.__pow__.
................
  r82654 | mark.dickinson | 2010-07-08 23:15:36 +0200 (Thu, 08 Jul 2010) | 3 lines
  
  Issue #9136: Profiling Decimal gave 'dictionary changed size during iteration'.
  Remove the use of locals() that caused this error.
................
  r82659 | brian.curtin | 2010-07-08 23:39:08 +0200 (Thu, 08 Jul 2010) | 17 lines
  
  Implement #1578269. Patch by Jason R. Coombs.
  
  Added Windows support for os.symlink when run on Windows 6.0 or greater,
  aka Vista. Previous Windows versions will raise NotImplementedError
  when trying to symlink.
  
  Includes numerous test updates and additions to test_os, including
  a symlink_support module because of the fact that privilege escalation
  is required in order to run the tests to ensure that the user is able
  to create symlinks. By default, accounts do not have the required
  privilege, so the escalation code will have to be exposed later (or
  documented on how to do so). I'll be following up with that work next.
  
  Note that the tests use ctypes, which was agreed on during the PyCon
  language summit.
................
  r82661 | brian.curtin | 2010-07-09 00:13:25 +0200 (Fri, 09 Jul 2010) | 2 lines
  
  Undo inadvertant checkin.
................
  r82662 | benjamin.peterson | 2010-07-09 00:16:05 +0200 (Fri, 09 Jul 2010) | 1 line
  
  assert tuple inheritance
................
  r82663 | benjamin.peterson | 2010-07-09 00:33:03 +0200 (Fri, 09 Jul 2010) | 1 line
  
  fix repr of complicated structseqs #9206
................
  r82723 | benjamin.peterson | 2010-07-09 03:58:26 +0200 (Fri, 09 Jul 2010) | 1 line
  
  use assert method
................
  r82724 | georg.brandl | 2010-07-09 09:33:15 +0200 (Fri, 09 Jul 2010) | 1 line
  
  2.7 is now stable.
................
  r82730 | r.david.murray | 2010-07-09 14:23:21 +0200 (Fri, 09 Jul 2010) | 4 lines
  
  7846: limit fnmatch pattern cache to _MAXCACHE=100 entries.
  
  Patch by Andrew Clegg.
................
  r82731 | r.david.murray | 2010-07-09 15:14:03 +0200 (Fri, 09 Jul 2010) | 2 lines
  
  Fix sort order mistake in Misc/ACKS.
................
  r82735 | benjamin.peterson | 2010-07-09 15:20:40 +0200 (Fri, 09 Jul 2010) | 1 line
  
  OverflowError is fine
................
  r82737 | brian.curtin | 2010-07-09 15:22:07 +0200 (Fri, 09 Jul 2010) | 2 lines
  
  Reorder Jason "two O's" Coombs
................
  r82739 | benjamin.peterson | 2010-07-09 15:28:42 +0200 (Fri, 09 Jul 2010) | 1 line
  
  allow more exceptions
................
  r82741 | benjamin.peterson | 2010-07-09 15:31:11 +0200 (Fri, 09 Jul 2010) | 1 line
  
  wrap
................
  r82743 | brian.curtin | 2010-07-09 15:54:27 +0200 (Fri, 09 Jul 2010) | 8 lines
  
  Fix the breakage of Lib/tarfile.py on non-Windows platforms due to 
  using WindowsError in a try/except. Only add WindowsError to the list of
  exceptions to catch when we are actually running on Windows.
  
  Additionally, add a call that was left out in test_posixpath.
  
  Thanks Amaury, Antoine, and Jason.
................
  r82744 | brian.curtin | 2010-07-09 17:15:09 +0200 (Fri, 09 Jul 2010) | 3 lines
  
  Adding versionchanged to the various Windows os.symlink additions, along
  with a few minor touchups.
................
  r82745 | brian.curtin | 2010-07-09 17:58:59 +0200 (Fri, 09 Jul 2010) | 2 lines
  
  Re-flow several long lines from #1578269.
................
  r82746 | jeffrey.yasskin | 2010-07-09 18:30:58 +0200 (Fri, 09 Jul 2010) | 12 lines
  
  Issue #9189: Allow users to set $CFLAGS, $CPPFLAGS, and $LDFLAGS when running
  configure to append to Python's default values for those variables, and
  similarly allow users to set $XXFLAGS on the make command line to append to the
  values set by configure.
  
  In the makefile, this renames the variables that used to be $XXFLAGS to
  $PY_XXFLAGS, and renames the old $PY_CFLAGS to $PY_CORE_CFLAGS.  To compensate,
  sysconfig now aliases $XXFLAGS=$PY_XXFLAGS so that scripts using it keep
  working.  I see that as the right interface, not a backward-compatibility hack,
  since these are logically the $XXFLAGS variables; we just use a different name
  in the makefile to deal with make's semantics.
................
  r82748 | benjamin.peterson | 2010-07-09 20:28:25 +0200 (Fri, 09 Jul 2010) | 1 line
  
  remove SocketIO.__del__; close() can handle it
................
  r82749 | mark.dickinson | 2010-07-09 21:25:48 +0200 (Fri, 09 Jul 2010) | 1 line
  
  Silence gcc warning. (In function 'bytearray_init': warning: 'value' may be used uninitialized in this function).
................
  r82750 | benjamin.peterson | 2010-07-09 21:37:00 +0200 (Fri, 09 Jul 2010) | 1 line
  
  be more robust across platforms
................
  r82753 | jeffrey.yasskin | 2010-07-09 21:55:05 +0200 (Fri, 09 Jul 2010) | 2 lines
  
  Oops. Fix distutils tests that r82746 broke.
................
  r82757 | georg.brandl | 2010-07-10 10:58:37 +0200 (Sat, 10 Jul 2010) | 1 line
  
  Fix markup.
................
  r82758 | georg.brandl | 2010-07-10 12:23:40 +0200 (Sat, 10 Jul 2010) | 1 line
  
  Emphasize role of count for Pascal string.
................
  r82759 | georg.brandl | 2010-07-10 12:32:36 +0200 (Sat, 10 Jul 2010) | 1 line
  
  #3071: tell how many values were expected when unpacking too many.
................
  r82760 | georg.brandl | 2010-07-10 12:39:57 +0200 (Sat, 10 Jul 2010) | 1 line
  
  #3214: improve description of duck-typing in glossary.
................
  r82761 | georg.brandl | 2010-07-10 13:40:13 +0200 (Sat, 10 Jul 2010) | 1 line
  
  #1434090: properly append child in expatbuilder doctype handler.
................
  r82762 | georg.brandl | 2010-07-10 13:51:06 +0200 (Sat, 10 Jul 2010) | 1 line
  
  #8338: fix outdated class name.
................
  r82763 | georg.brandl | 2010-07-10 14:01:34 +0200 (Sat, 10 Jul 2010) | 1 line
  
  #8456: fix signature of sqlite3.connect().
................
  r82764 | georg.brandl | 2010-07-10 14:20:38 +0200 (Sat, 10 Jul 2010) | 1 line
  
  #8564: update docs on integrating doctest/unittest with unittest(2) test discovery.
................
  r82766 | r.david.murray | 2010-07-10 15:52:13 +0200 (Sat, 10 Jul 2010) | 5 lines
  
  Fix 'refleak' introduced by fnmatch cache purge tests.
  
  This introduces a 'purge' function for the fnmatch module analogous
  to the 'purge' function in the re module.
................
  r82767 | michael.foord | 2010-07-10 15:52:22 +0200 (Sat, 10 Jul 2010) | 2 lines
  
  Fix error message for comparing single line strings in unittest.TestCase.assertEqual.
  Issue 9174.
................
  r82771 | r.david.murray | 2010-07-10 16:23:36 +0200 (Sat, 10 Jul 2010) | 2 lines
  
  Add missing docs for re module 'purge' function.
................
  r82777 | benjamin.peterson | 2010-07-10 17:14:45 +0200 (Sat, 10 Jul 2010) | 1 line
  
  ValueError is eventually what we want to move to, I suppose
................
  r82780 | senthil.kumaran | 2010-07-11 05:12:43 +0200 (Sun, 11 Jul 2010) | 3 lines
  
  Stricter verification for file based url scheme and reliance on ftp protocol.
................
  r82784 | benjamin.peterson | 2010-07-11 05:36:35 +0200 (Sun, 11 Jul 2010) | 1 line
  
  remove unneeded error check
................
  r82785 | senthil.kumaran | 2010-07-11 07:01:52 +0200 (Sun, 11 Jul 2010) | 3 lines
  
  Issue2007: Removing reference to MSIE Cookie handling by mechanize. Suggested by John J Lee.
................
  r82789 | georg.brandl | 2010-07-11 10:33:16 +0200 (Sun, 11 Jul 2010) | 1 line
  
  Silence makeindex.
................
  r82790 | georg.brandl | 2010-07-11 10:36:20 +0200 (Sun, 11 Jul 2010) | 1 line
  
  #3214 followup: add link to ABC entry.
................
  r82796 | ronald.oussoren | 2010-07-11 11:05:07 +0200 (Sun, 11 Jul 2010) | 2 lines
  
  Fix for issue 9164
................
  r82798 | georg.brandl | 2010-07-11 11:23:11 +0200 (Sun, 11 Jul 2010) | 1 line
  
  #6774: explain shutdown() behavior varying with platform.
................
  r82799 | georg.brandl | 2010-07-11 11:26:57 +0200 (Sun, 11 Jul 2010) | 1 line
  
  Fix typo.
................
  r82801 | georg.brandl | 2010-07-11 11:33:39 +0200 (Sun, 11 Jul 2010) | 1 line
  
  #9184: fix default value for "buffering" param of open().
................
  r82804 | georg.brandl | 2010-07-11 11:41:21 +0200 (Sun, 11 Jul 2010) | 1 line
  
  Allow set literals in literal_eval().
................
  r82805 | georg.brandl | 2010-07-11 11:42:10 +0200 (Sun, 11 Jul 2010) | 1 line
  
  #7935: cross-reference to ast.literal_eval() from eval() docs.
................
  r82806 | georg.brandl | 2010-07-11 12:22:44 +0200 (Sun, 11 Jul 2010) | 1 line
  
  #9223: link to Command class reference, and move Command interface docs nearer to class docs.
................
  r82814 | antoine.pitrou | 2010-07-11 14:12:00 +0200 (Sun, 11 Jul 2010) | 4 lines
  
  Issue #7616: Fix copying of overlapping memoryview slices with the Intel
  compiler.
................
  r82817 | benjamin.peterson | 2010-07-11 14:59:24 +0200 (Sun, 11 Jul 2010) | 1 line
  
  test for set literals
................
  r82818 | mark.dickinson | 2010-07-11 19:38:24 +0200 (Sun, 11 Jul 2010) | 2 lines
  
  Issue #9165: Add math.isfinite and cmath.isfinite.
................
  r82819 | martin.v.loewis | 2010-07-11 19:39:46 +0200 (Sun, 11 Jul 2010) | 2 lines
  
  Issue #8974: fix print calls in msgfmt.py.
................
  r82820 | mark.dickinson | 2010-07-11 20:13:41 +0200 (Sun, 11 Jul 2010) | 1 line
  
  Improve docstrings for isnan, isinf and isfinite.
................
  r82821 | mark.dickinson | 2010-07-11 20:53:06 +0200 (Sun, 11 Jul 2010) | 3 lines
  
  Issue #9137: Fix issue in MutableMapping.update, which incorrectly
  treated keyword arguments called 'self' or 'other' specially.
................
  r82822 | mark.dickinson | 2010-07-11 21:12:10 +0200 (Sun, 11 Jul 2010) | 1 line
  
  assertEquals -> assertEqual
................
  r82825 | mark.dickinson | 2010-07-11 21:47:37 +0200 (Sun, 11 Jul 2010) | 1 line
  
  Include versionadded in (c)math.isfinite docs (thanks Ezio Melotti).  Other minor doc cleanups.
................
  r82828 | benjamin.peterson | 2010-07-12 01:06:06 +0200 (Mon, 12 Jul 2010) | 1 line
  
  allow byte literals
................
  r82830 | brian.curtin | 2010-07-12 01:32:11 +0200 (Mon, 12 Jul 2010) | 2 lines
  
  Put my name down for winreg.
................
  r82831 | martin.v.loewis | 2010-07-12 08:03:18 +0200 (Mon, 12 Jul 2010) | 2 lines
  
  Remove myself.
................
  r82832 | georg.brandl | 2010-07-12 11:00:29 +0200 (Mon, 12 Jul 2010) | 1 line
  
  Take care of duplicate target name warnings.
................
  r82834 | georg.brandl | 2010-07-12 11:06:13 +0200 (Mon, 12 Jul 2010) | 1 line
  
  Use raw string literals for regexes containing backlash.
................
  r82835 | mark.dickinson | 2010-07-12 11:37:40 +0200 (Mon, 12 Jul 2010) | 1 line
  
  Remove mention of execfile from the tutorial.
................
  r82837 | mark.dickinson | 2010-07-12 16:14:18 +0200 (Mon, 12 Jul 2010) | 1 line
  
  Issue #2009: refactor varargslist and typedargslist productions to make them more friendly for third-party parsers.
................
  r82838 | mark.dickinson | 2010-07-12 16:18:21 +0200 (Mon, 12 Jul 2010) | 1 line
  
  Regenerate Python/graminit.c.
................
  r82839 | ezio.melotti | 2010-07-12 21:49:41 +0200 (Mon, 12 Jul 2010) | 1 line
  
  #6026: skip test_get_file_list when zlib is not available.
................
  r82842 | antoine.pitrou | 2010-07-12 22:01:52 +0200 (Mon, 12 Jul 2010) | 3 lines
  
  Fix definition of len() and indexing for memoryview objects (part of #7696).
................
  r82843 | mark.dickinson | 2010-07-12 22:03:24 +0200 (Mon, 12 Jul 2010) | 1 line
  
  Yield more information on failure in test_struct boolean test.
................
  r82848 | georg.brandl | 2010-07-13 08:38:10 +0200 (Tue, 13 Jul 2010) | 1 line
  
  Add bytes in literal_eval doc.
................
  r82849 | jeroen.ruigrok | 2010-07-13 16:47:01 +0200 (Tue, 13 Jul 2010) | 2 lines
  
  Fix documentation typo: wprite() -> write().
................
  r82850 | alexander.belopolsky | 2010-07-13 16:50:16 +0200 (Tue, 13 Jul 2010) | 1 line
  
  Set sys.modules[name] to None instead of 0 to block module import.
................
  r82856 | victor.stinner | 2010-07-14 01:04:56 +0200 (Wed, 14 Jul 2010) | 2 lines
  
  Issue #9243: Fix sndhdr module and add unit tests, contributed by James Lee.
................
  r82857 | victor.stinner | 2010-07-14 01:08:01 +0200 (Wed, 14 Jul 2010) | 2 lines
  
  Woops, test_sndhdr.py contains the same code twice: fix it
................
  r82871 | georg.brandl | 2010-07-14 10:00:22 +0200 (Wed, 14 Jul 2010) | 1 line
  
  #9258: fix copy-paste errors.
................
  r82872 | georg.brandl | 2010-07-14 10:53:18 +0200 (Wed, 14 Jul 2010) | 1 line
  
  Remove XXX from text.
................
  r82873 | georg.brandl | 2010-07-14 10:53:36 +0200 (Wed, 14 Jul 2010) | 1 line
  
  Remove unused code that would raise a NameError.
................
  r82874 | georg.brandl | 2010-07-14 10:54:40 +0200 (Wed, 14 Jul 2010) | 1 line
  
  #9235: fix missing import of sys.
................
  r82879 | stefan.krah | 2010-07-14 12:16:11 +0200 (Wed, 14 Jul 2010) | 3 lines
  
  High byte is the exit status.
................
  r82881 | senthil.kumaran | 2010-07-14 12:21:22 +0200 (Wed, 14 Jul 2010) | 3 lines
  
  Fix Issue5842 - Moving the tests out of urllib.parse module
................
  r82885 | antoine.pitrou | 2010-07-14 13:52:38 +0200 (Wed, 14 Jul 2010) | 4 lines
  
  Issue #9251: test_threaded_import didn't fail when run through regrtest
  if the import lock was disabled.
................
  r82887 | alexander.belopolsky | 2010-07-14 15:46:57 +0200 (Wed, 14 Jul 2010) | 1 line
  
  PEP 8 conformance: class_ -> cls
................
  r82890 | senthil.kumaran | 2010-07-14 21:15:23 +0200 (Wed, 14 Jul 2010) | 3 lines
  
  Fix: Issue6853 - Get HTTPS system proxy in Windows.
................
  r82895 | senthil.kumaran | 2010-07-14 22:10:52 +0200 (Wed, 14 Jul 2010) | 3 lines
  
  Fix a mistake, https proxy shoud be https://
................
  r82899 | senthil.kumaran | 2010-07-14 22:30:02 +0200 (Wed, 14 Jul 2010) | 2 lines
  
  Fix issue9132 - Documentation for comparing dictionaries is out of date
................
  r82910 | brett.cannon | 2010-07-15 08:24:04 +0200 (Thu, 15 Jul 2010) | 2 lines
  
  Touch up comments and code along with outputting what the unit of measure is.
................
  r82915 | alexander.belopolsky | 2010-07-16 16:39:45 +0200 (Fri, 16 Jul 2010) | 1 line
  
  Corrected TUPLE<N> opcodes' docs.
................
  r82918 | brett.cannon | 2010-07-16 21:04:29 +0200 (Fri, 16 Jul 2010) | 4 lines
  
  Add benchmarks for importing just source w/o writing bytecode, importing source
  while writing bytecode, and importing bytecode with source existing (don't care
  about sourceless imports).
................
  r82919 | antoine.pitrou | 2010-07-16 21:10:38 +0200 (Fri, 16 Jul 2010) | 4 lines
  
  Fix possible failure in pickling tests due to different instantiations
  of the random module being around.
................
  r82921 | brett.cannon | 2010-07-16 21:26:23 +0200 (Fri, 16 Jul 2010) | 1 line
  
  Add comma grouping to max result so it's easier to read.
................
  r82922 | r.david.murray | 2010-07-17 03:19:57 +0200 (Sat, 17 Jul 2010) | 4 lines
  
  #1555570: correctly handle a \r\n that is split by the read buffer.
  
  Patch and test by Tony Nelson.
................


Added:
   python/branches/py3k-cdecimal/Demo/parser/test_unparse.py
      - copied unchanged from r82922, /python/branches/py3k/Demo/parser/test_unparse.py
   python/branches/py3k-cdecimal/Doc/documenting/building.rst
      - copied unchanged from r82922, /python/branches/py3k/Doc/documenting/building.rst
   python/branches/py3k-cdecimal/Lib/encodings/cp858.py
      - copied unchanged from r82922, /python/branches/py3k/Lib/encodings/cp858.py
   python/branches/py3k-cdecimal/Lib/test/sndhdrdata/
      - copied from r82922, /python/branches/py3k/Lib/test/sndhdrdata/
   python/branches/py3k-cdecimal/Lib/test/symlink_support.py
      - copied unchanged from r82922, /python/branches/py3k/Lib/test/symlink_support.py
   python/branches/py3k-cdecimal/Lib/test/test_sndhdr.py
      - copied unchanged from r82922, /python/branches/py3k/Lib/test/test_sndhdr.py
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/LICENSE
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/LICENSE
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/README
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/README
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/README.ctypes
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/README.ctypes
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffi.c
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.c
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffi_common.h
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi_common.h
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffitarget.h
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/ffitarget.h
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/prep_cif.c
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/prep_cif.c
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/types.c
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/types.c
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/win32.c
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/win32.c
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/win64.asm
      - copied unchanged from r82922, /python/branches/py3k/Modules/_ctypes/libffi_msvc/win64.asm
   python/branches/py3k-cdecimal/Modules/_time.c
      - copied unchanged from r82922, /python/branches/py3k/Modules/_time.c
   python/branches/py3k-cdecimal/Modules/_time.h
      - copied unchanged from r82922, /python/branches/py3k/Modules/_time.h
Removed:
   python/branches/py3k-cdecimal/Demo/classes/Dbm.py
   python/branches/py3k-cdecimal/Tools/webchecker/
Modified:
   python/branches/py3k-cdecimal/   (props changed)
   python/branches/py3k-cdecimal/Demo/classes/Complex.py
   python/branches/py3k-cdecimal/Demo/classes/Dates.py
   python/branches/py3k-cdecimal/Demo/classes/README
   python/branches/py3k-cdecimal/Demo/classes/Range.py
   python/branches/py3k-cdecimal/Demo/classes/Rev.py
   python/branches/py3k-cdecimal/Demo/classes/Vec.py
   python/branches/py3k-cdecimal/Demo/embed/Makefile
   python/branches/py3k-cdecimal/Demo/embed/demo.c
   python/branches/py3k-cdecimal/Demo/md5test/md5driver.py
   python/branches/py3k-cdecimal/Demo/parser/test_parser.py
   python/branches/py3k-cdecimal/Demo/parser/unparse.py
   python/branches/py3k-cdecimal/Doc/Makefile
   python/branches/py3k-cdecimal/Doc/README.txt
   python/branches/py3k-cdecimal/Doc/c-api/arg.rst
   python/branches/py3k-cdecimal/Doc/c-api/datetime.rst
   python/branches/py3k-cdecimal/Doc/c-api/file.rst
   python/branches/py3k-cdecimal/Doc/c-api/init.rst
   python/branches/py3k-cdecimal/Doc/c-api/intro.rst
   python/branches/py3k-cdecimal/Doc/c-api/number.rst
   python/branches/py3k-cdecimal/Doc/c-api/unicode.rst
   python/branches/py3k-cdecimal/Doc/data/refcounts.dat
   python/branches/py3k-cdecimal/Doc/distutils/apiref.rst
   python/branches/py3k-cdecimal/Doc/distutils/builtdist.rst
   python/branches/py3k-cdecimal/Doc/distutils/extending.rst
   python/branches/py3k-cdecimal/Doc/distutils/setupscript.rst
   python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst
   python/branches/py3k-cdecimal/Doc/documenting/index.rst
   python/branches/py3k-cdecimal/Doc/documenting/markup.rst
   python/branches/py3k-cdecimal/Doc/documenting/style.rst
   python/branches/py3k-cdecimal/Doc/faq/extending.rst
   python/branches/py3k-cdecimal/Doc/faq/gui.rst
   python/branches/py3k-cdecimal/Doc/glossary.rst
   python/branches/py3k-cdecimal/Doc/howto/functional.rst
   python/branches/py3k-cdecimal/Doc/howto/unicode.rst
   python/branches/py3k-cdecimal/Doc/library/2to3.rst
   python/branches/py3k-cdecimal/Doc/library/ast.rst
   python/branches/py3k-cdecimal/Doc/library/calendar.rst
   python/branches/py3k-cdecimal/Doc/library/cmath.rst
   python/branches/py3k-cdecimal/Doc/library/codecs.rst
   python/branches/py3k-cdecimal/Doc/library/contextlib.rst
   python/branches/py3k-cdecimal/Doc/library/datetime.rst
   python/branches/py3k-cdecimal/Doc/library/dis.rst
   python/branches/py3k-cdecimal/Doc/library/doctest.rst
   python/branches/py3k-cdecimal/Doc/library/fnmatch.rst
   python/branches/py3k-cdecimal/Doc/library/functions.rst
   python/branches/py3k-cdecimal/Doc/library/http.cookiejar.rst
   python/branches/py3k-cdecimal/Doc/library/http.server.rst
   python/branches/py3k-cdecimal/Doc/library/importlib.rst
   python/branches/py3k-cdecimal/Doc/library/logging.rst
   python/branches/py3k-cdecimal/Doc/library/math.rst
   python/branches/py3k-cdecimal/Doc/library/multiprocessing.rst
   python/branches/py3k-cdecimal/Doc/library/os.path.rst
   python/branches/py3k-cdecimal/Doc/library/os.rst
   python/branches/py3k-cdecimal/Doc/library/pdb.rst
   python/branches/py3k-cdecimal/Doc/library/re.rst
   python/branches/py3k-cdecimal/Doc/library/select.rst
   python/branches/py3k-cdecimal/Doc/library/socket.rst
   python/branches/py3k-cdecimal/Doc/library/sqlite3.rst
   python/branches/py3k-cdecimal/Doc/library/ssl.rst
   python/branches/py3k-cdecimal/Doc/library/stdtypes.rst
   python/branches/py3k-cdecimal/Doc/library/string.rst
   python/branches/py3k-cdecimal/Doc/library/struct.rst
   python/branches/py3k-cdecimal/Doc/library/subprocess.rst
   python/branches/py3k-cdecimal/Doc/library/sys.rst
   python/branches/py3k-cdecimal/Doc/library/sysconfig.rst
   python/branches/py3k-cdecimal/Doc/library/unittest.rst
   python/branches/py3k-cdecimal/Doc/library/urllib.parse.rst
   python/branches/py3k-cdecimal/Doc/library/urllib.request.rst
   python/branches/py3k-cdecimal/Doc/library/warnings.rst
   python/branches/py3k-cdecimal/Doc/reference/compound_stmts.rst
   python/branches/py3k-cdecimal/Doc/reference/datamodel.rst
   python/branches/py3k-cdecimal/Doc/reference/expressions.rst
   python/branches/py3k-cdecimal/Doc/reference/introduction.rst
   python/branches/py3k-cdecimal/Doc/reference/lexical_analysis.rst
   python/branches/py3k-cdecimal/Doc/tools/sphinxext/indexsidebar.html
   python/branches/py3k-cdecimal/Doc/tools/sphinxext/pyspecific.py
   python/branches/py3k-cdecimal/Doc/tutorial/classes.rst
   python/branches/py3k-cdecimal/Doc/tutorial/controlflow.rst
   python/branches/py3k-cdecimal/Doc/tutorial/introduction.rst
   python/branches/py3k-cdecimal/Doc/using/cmdline.rst
   python/branches/py3k-cdecimal/Doc/using/mac.rst
   python/branches/py3k-cdecimal/Doc/whatsnew/2.7.rst
   python/branches/py3k-cdecimal/Doc/whatsnew/3.0.rst
   python/branches/py3k-cdecimal/Doc/whatsnew/3.2.rst
   python/branches/py3k-cdecimal/Grammar/Grammar
   python/branches/py3k-cdecimal/Include/longobject.h
   python/branches/py3k-cdecimal/Include/pyctype.h
   python/branches/py3k-cdecimal/Include/structseq.h
   python/branches/py3k-cdecimal/Include/traceback.h
   python/branches/py3k-cdecimal/Include/unicodeobject.h
   python/branches/py3k-cdecimal/Lib/_abcoll.py
   python/branches/py3k-cdecimal/Lib/_strptime.py
   python/branches/py3k-cdecimal/Lib/ast.py
   python/branches/py3k-cdecimal/Lib/contextlib.py
   python/branches/py3k-cdecimal/Lib/ctypes/__init__.py
   python/branches/py3k-cdecimal/Lib/ctypes/test/test_callbacks.py
   python/branches/py3k-cdecimal/Lib/ctypes/test/test_win32.py
   python/branches/py3k-cdecimal/Lib/decimal.py
   python/branches/py3k-cdecimal/Lib/dis.py
   python/branches/py3k-cdecimal/Lib/distutils/command/install.py
   python/branches/py3k-cdecimal/Lib/distutils/msvc9compiler.py
   python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py
   python/branches/py3k-cdecimal/Lib/distutils/unixccompiler.py
   python/branches/py3k-cdecimal/Lib/email/feedparser.py
   python/branches/py3k-cdecimal/Lib/email/test/test_email.py
   python/branches/py3k-cdecimal/Lib/encodings/aliases.py
   python/branches/py3k-cdecimal/Lib/fnmatch.py
   python/branches/py3k-cdecimal/Lib/heapq.py
   python/branches/py3k-cdecimal/Lib/http/cookiejar.py
   python/branches/py3k-cdecimal/Lib/idlelib/textView.py
   python/branches/py3k-cdecimal/Lib/importlib/__init__.py
   python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py
   python/branches/py3k-cdecimal/Lib/importlib/abc.py
   python/branches/py3k-cdecimal/Lib/importlib/test/benchmark.py
   python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_case_sensitivity.py
   python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_finder.py
   python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_loader.py
   python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_path_hook.py
   python/branches/py3k-cdecimal/Lib/importlib/test/import_/test_path.py
   python/branches/py3k-cdecimal/Lib/importlib/test/regrtest.py
   python/branches/py3k-cdecimal/Lib/importlib/test/source/test_abc_loader.py
   python/branches/py3k-cdecimal/Lib/importlib/test/source/test_case_sensitivity.py
   python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py
   python/branches/py3k-cdecimal/Lib/importlib/test/source/test_finder.py
   python/branches/py3k-cdecimal/Lib/importlib/test/source/test_path_hook.py
   python/branches/py3k-cdecimal/Lib/importlib/test/source/test_source_encoding.py
   python/branches/py3k-cdecimal/Lib/importlib/test/test_abc.py
   python/branches/py3k-cdecimal/Lib/importlib/test/test_api.py
   python/branches/py3k-cdecimal/Lib/importlib/test/test_util.py
   python/branches/py3k-cdecimal/Lib/inspect.py
   python/branches/py3k-cdecimal/Lib/lib2to3/   (props changed)
   python/branches/py3k-cdecimal/Lib/lib2to3/fixes/fix_itertools_imports.py
   python/branches/py3k-cdecimal/Lib/lib2to3/tests/test_fixers.py
   python/branches/py3k-cdecimal/Lib/logging/config.py
   python/branches/py3k-cdecimal/Lib/macpath.py
   python/branches/py3k-cdecimal/Lib/ntpath.py
   python/branches/py3k-cdecimal/Lib/os2emxpath.py
   python/branches/py3k-cdecimal/Lib/pdb.doc
   python/branches/py3k-cdecimal/Lib/pdb.py
   python/branches/py3k-cdecimal/Lib/pickletools.py
   python/branches/py3k-cdecimal/Lib/posixpath.py
   python/branches/py3k-cdecimal/Lib/pydoc.py
   python/branches/py3k-cdecimal/Lib/site.py
   python/branches/py3k-cdecimal/Lib/smtpd.py
   python/branches/py3k-cdecimal/Lib/sndhdr.py
   python/branches/py3k-cdecimal/Lib/socket.py
   python/branches/py3k-cdecimal/Lib/subprocess.py
   python/branches/py3k-cdecimal/Lib/sysconfig.py
   python/branches/py3k-cdecimal/Lib/tarfile.py
   python/branches/py3k-cdecimal/Lib/test/decimaltestdata/extra.decTest
   python/branches/py3k-cdecimal/Lib/test/math_testcases.txt
   python/branches/py3k-cdecimal/Lib/test/regrtest.py
   python/branches/py3k-cdecimal/Lib/test/support.py
   python/branches/py3k-cdecimal/Lib/test/test_ast.py
   python/branches/py3k-cdecimal/Lib/test/test_audioop.py
   python/branches/py3k-cdecimal/Lib/test/test_calendar.py
   python/branches/py3k-cdecimal/Lib/test/test_cmath.py
   python/branches/py3k-cdecimal/Lib/test/test_codeccallbacks.py
   python/branches/py3k-cdecimal/Lib/test/test_codecs.py
   python/branches/py3k-cdecimal/Lib/test/test_collections.py
   python/branches/py3k-cdecimal/Lib/test/test_complex.py
   python/branches/py3k-cdecimal/Lib/test/test_contextlib.py
   python/branches/py3k-cdecimal/Lib/test/test_datetime.py
   python/branches/py3k-cdecimal/Lib/test/test_decimal.py
   python/branches/py3k-cdecimal/Lib/test/test_descr.py
   python/branches/py3k-cdecimal/Lib/test/test_dict.py
   python/branches/py3k-cdecimal/Lib/test/test_dis.py
   python/branches/py3k-cdecimal/Lib/test/test_enumerate.py
   python/branches/py3k-cdecimal/Lib/test/test_exceptions.py
   python/branches/py3k-cdecimal/Lib/test/test_extcall.py
   python/branches/py3k-cdecimal/Lib/test/test_float.py
   python/branches/py3k-cdecimal/Lib/test/test_fnmatch.py
   python/branches/py3k-cdecimal/Lib/test/test_gdb.py
   python/branches/py3k-cdecimal/Lib/test/test_genericpath.py
   python/branches/py3k-cdecimal/Lib/test/test_getargs2.py
   python/branches/py3k-cdecimal/Lib/test/test_glob.py
   python/branches/py3k-cdecimal/Lib/test/test_http_cookiejar.py
   python/branches/py3k-cdecimal/Lib/test/test_httpservers.py
   python/branches/py3k-cdecimal/Lib/test/test_imp.py
   python/branches/py3k-cdecimal/Lib/test/test_import.py
   python/branches/py3k-cdecimal/Lib/test/test_inspect.py
   python/branches/py3k-cdecimal/Lib/test/test_iter.py
   python/branches/py3k-cdecimal/Lib/test/test_keywordonlyarg.py
   python/branches/py3k-cdecimal/Lib/test/test_logging.py
   python/branches/py3k-cdecimal/Lib/test/test_math.py
   python/branches/py3k-cdecimal/Lib/test/test_optparse.py
   python/branches/py3k-cdecimal/Lib/test/test_os.py
   python/branches/py3k-cdecimal/Lib/test/test_parser.py
   python/branches/py3k-cdecimal/Lib/test/test_platform.py
   python/branches/py3k-cdecimal/Lib/test/test_posixpath.py
   python/branches/py3k-cdecimal/Lib/test/test_property.py
   python/branches/py3k-cdecimal/Lib/test/test_pyexpat.py
   python/branches/py3k-cdecimal/Lib/test/test_runpy.py
   python/branches/py3k-cdecimal/Lib/test/test_shutil.py
   python/branches/py3k-cdecimal/Lib/test/test_strtod.py
   python/branches/py3k-cdecimal/Lib/test/test_struct.py
   python/branches/py3k-cdecimal/Lib/test/test_structseq.py
   python/branches/py3k-cdecimal/Lib/test/test_subprocess.py
   python/branches/py3k-cdecimal/Lib/test/test_syntax.py
   python/branches/py3k-cdecimal/Lib/test/test_sysconfig.py
   python/branches/py3k-cdecimal/Lib/test/test_tarfile.py
   python/branches/py3k-cdecimal/Lib/test/test_threaded_import.py
   python/branches/py3k-cdecimal/Lib/test/test_tokenize.py
   python/branches/py3k-cdecimal/Lib/test/test_tuple.py
   python/branches/py3k-cdecimal/Lib/test/test_unicode.py
   python/branches/py3k-cdecimal/Lib/test/test_unpack.py
   python/branches/py3k-cdecimal/Lib/test/test_urllib.py
   python/branches/py3k-cdecimal/Lib/test/test_urllib2.py
   python/branches/py3k-cdecimal/Lib/test/test_urlparse.py
   python/branches/py3k-cdecimal/Lib/test/test_xmlrpc_net.py
   python/branches/py3k-cdecimal/Lib/unittest/case.py
   python/branches/py3k-cdecimal/Lib/unittest/test/test_case.py
   python/branches/py3k-cdecimal/Lib/urllib/parse.py
   python/branches/py3k-cdecimal/Lib/urllib/request.py
   python/branches/py3k-cdecimal/Lib/uuid.py
   python/branches/py3k-cdecimal/Lib/warnings.py
   python/branches/py3k-cdecimal/Lib/xml/dom/expatbuilder.py
   python/branches/py3k-cdecimal/Makefile.pre.in
   python/branches/py3k-cdecimal/Misc/ACKS
   python/branches/py3k-cdecimal/Misc/NEWS
   python/branches/py3k-cdecimal/Misc/Vim/vimrc
   python/branches/py3k-cdecimal/Misc/maintainers.rst
   python/branches/py3k-cdecimal/Modules/_ctypes/callproc.c
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi/fficonfig.py.in
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffi.h
   python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/fficonfig.h
   python/branches/py3k-cdecimal/Modules/_io/_iomodule.c
   python/branches/py3k-cdecimal/Modules/_math.c
   python/branches/py3k-cdecimal/Modules/_scproxy.c
   python/branches/py3k-cdecimal/Modules/_ssl.c
   python/branches/py3k-cdecimal/Modules/_struct.c
   python/branches/py3k-cdecimal/Modules/_testcapimodule.c
   python/branches/py3k-cdecimal/Modules/audioop.c
   python/branches/py3k-cdecimal/Modules/cmathmodule.c
   python/branches/py3k-cdecimal/Modules/datetimemodule.c
   python/branches/py3k-cdecimal/Modules/makesetup
   python/branches/py3k-cdecimal/Modules/mathmodule.c
   python/branches/py3k-cdecimal/Modules/parsermodule.c
   python/branches/py3k-cdecimal/Modules/posixmodule.c
   python/branches/py3k-cdecimal/Modules/selectmodule.c
   python/branches/py3k-cdecimal/Modules/timemodule.c
   python/branches/py3k-cdecimal/Modules/xxmodule.c
   python/branches/py3k-cdecimal/Objects/abstract.c
   python/branches/py3k-cdecimal/Objects/bytearrayobject.c
   python/branches/py3k-cdecimal/Objects/bytes_methods.c
   python/branches/py3k-cdecimal/Objects/descrobject.c
   python/branches/py3k-cdecimal/Objects/enumobject.c
   python/branches/py3k-cdecimal/Objects/exceptions.c
   python/branches/py3k-cdecimal/Objects/floatobject.c
   python/branches/py3k-cdecimal/Objects/frameobject.c
   python/branches/py3k-cdecimal/Objects/memoryobject.c
   python/branches/py3k-cdecimal/Objects/stringlib/formatter.h
   python/branches/py3k-cdecimal/Objects/structseq.c
   python/branches/py3k-cdecimal/Objects/typeobject.c
   python/branches/py3k-cdecimal/Objects/unicodeobject.c
   python/branches/py3k-cdecimal/PC/VS8.0/pythoncore.vcproj
   python/branches/py3k-cdecimal/PCbuild/_ctypes.vcproj
   python/branches/py3k-cdecimal/PCbuild/pythoncore.vcproj
   python/branches/py3k-cdecimal/Parser/Python.asdl
   python/branches/py3k-cdecimal/Parser/asdl_c.py
   python/branches/py3k-cdecimal/Python/Python-ast.c
   python/branches/py3k-cdecimal/Python/_warnings.c
   python/branches/py3k-cdecimal/Python/ast.c
   python/branches/py3k-cdecimal/Python/ceval.c
   python/branches/py3k-cdecimal/Python/compile.c
   python/branches/py3k-cdecimal/Python/getargs.c
   python/branches/py3k-cdecimal/Python/graminit.c
   python/branches/py3k-cdecimal/Python/import.c
   python/branches/py3k-cdecimal/Python/pythonrun.c
   python/branches/py3k-cdecimal/Python/sysmodule.c
   python/branches/py3k-cdecimal/Python/traceback.c
   python/branches/py3k-cdecimal/README
   python/branches/py3k-cdecimal/Tools/README
   python/branches/py3k-cdecimal/Tools/gdb/libpython.py
   python/branches/py3k-cdecimal/Tools/i18n/msgfmt.py
   python/branches/py3k-cdecimal/Tools/scripts/   (props changed)
   python/branches/py3k-cdecimal/Tools/scripts/patchcheck.py
   python/branches/py3k-cdecimal/configure
   python/branches/py3k-cdecimal/configure.in
   python/branches/py3k-cdecimal/setup.py

Modified: python/branches/py3k-cdecimal/Demo/classes/Complex.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/Complex.py	(original)
+++ python/branches/py3k-cdecimal/Demo/classes/Complex.py	Sat Jul 17 12:36:09 2010
@@ -151,13 +151,9 @@
             raise ValueError("can't convert Complex with nonzero im to float")
         return float(self.re)
 
-    def __cmp__(self, other):
+    def __eq__(self, other):
         other = ToComplex(other)
-        return cmp((self.re, self.im), (other.re, other.im))
-
-    def __rcmp__(self, other):
-        other = ToComplex(other)
-        return cmp(other, self)
+        return (self.re, self.im) == (other.re, other.im)
 
     def __bool__(self):
         return not (self.re == self.im == 0)
@@ -190,14 +186,14 @@
 
     __rmul__ = __mul__
 
-    def __div__(self, other):
+    def __truediv__(self, other):
         other = ToComplex(other)
         d = float(other.re*other.re + other.im*other.im)
         if not d: raise ZeroDivisionError('Complex division')
         return Complex((self.re*other.re + self.im*other.im) / d,
                        (self.im*other.re - self.re*other.im) / d)
 
-    def __rdiv__(self, other):
+    def __rtruediv__(self, other):
         other = ToComplex(other)
         return other / self
 
@@ -226,8 +222,9 @@
     print('       ', a, 'and', b, end=' ')
     try:
         result = eval(expr)
-    except:
-        result = sys.exc_info()[0]
+    except Exception as e:
+        print('!!\t!!\t!! error: {}'.format(e))
+        return
     print('->', result)
     if isinstance(result, str) or isinstance(value, str):
         ok = (result == value)
@@ -295,13 +292,6 @@
                     (Complex(1), Complex(0,10), 1),
                     (2, Complex(4,0), 16),
             ],
-            'cmp(a,b)': [
-                    (1, 10, -1),
-                    (1, Complex(0,10), 1),
-                    (Complex(0,10), 1, -1),
-                    (Complex(0,10), Complex(1), -1),
-                    (Complex(1), Complex(0,10), 1),
-            ],
     }
     for expr in sorted(testsuite):
         print(expr + ':')

Modified: python/branches/py3k-cdecimal/Demo/classes/Dates.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/Dates.py	(original)
+++ python/branches/py3k-cdecimal/Demo/classes/Dates.py	Sat Jul 17 12:36:09 2010
@@ -1,45 +1,47 @@
-# Class Date supplies date objects that support date arithmetic.
-#
-# Date(month,day,year) returns a Date object.  An instance prints as,
-# e.g., 'Mon 16 Aug 1993'.
-#
-# Addition, subtraction, comparison operators, min, max, and sorting
-# all work as expected for date objects:  int+date or date+int returns
-# the date `int' days from `date'; date+date raises an exception;
-# date-int returns the date `int' days before `date'; date2-date1 returns
-# an integer, the number of days from date1 to date2; int-date raises an
-# exception; date1 < date2 is true iff date1 occurs before date2 (&
-# similarly for other comparisons); min(date1,date2) is the earlier of
-# the two dates and max(date1,date2) the later; and date objects can be
-# used as dictionary keys.
-#
-# Date objects support one visible method, date.weekday().  This returns
-# the day of the week the date falls on, as a string.
-#
-# Date objects also have 4 read-only data attributes:
-#   .month  in 1..12
-#   .day    in 1..31
-#   .year   int or long int
-#   .ord    the ordinal of the date relative to an arbitrary staring point
-#
-# The Dates module also supplies function today(), which returns the
-# current date as a date object.
-#
-# Those entranced by calendar trivia will be disappointed, as no attempt
-# has been made to accommodate the Julian (etc) system.  On the other
-# hand, at least this package knows that 2000 is a leap year but 2100
-# isn't, and works fine for years with a hundred decimal digits <wink>.
-
-# Tim Peters   tim at ksr.com
-# not speaking for Kendall Square Research Corp
+"""
+Class Date supplies date objects that support date arithmetic.
 
-# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
-# by Guido van Rossum
+Date(month,day,year) returns a Date object.  An instance prints as,
+e.g., 'Mon 16 Aug 1993'.
 
-# Note that as of Python 2.3, a datetime module is included in the stardard
-# library.
+Addition, subtraction, comparison operators, min, max, and sorting
+all work as expected for date objects:  int+date or date+int returns
+the date `int' days from `date'; date+date raises an exception;
+date-int returns the date `int' days before `date'; date2-date1 returns
+an integer, the number of days from date1 to date2; int-date raises an
+exception; date1 < date2 is true iff date1 occurs before date2 (&
+similarly for other comparisons); min(date1,date2) is the earlier of
+the two dates and max(date1,date2) the later; and date objects can be
+used as dictionary keys.
+
+Date objects support one visible method, date.weekday().  This returns
+the day of the week the date falls on, as a string.
+
+Date objects also have 4 read-only data attributes:
+  .month  in 1..12
+  .day    in 1..31
+  .year   int or long int
+  .ord    the ordinal of the date relative to an arbitrary staring point
+
+The Dates module also supplies function today(), which returns the
+current date as a date object.
+
+Those entranced by calendar trivia will be disappointed, as no attempt
+has been made to accommodate the Julian (etc) system.  On the other
+hand, at least this package knows that 2000 is a leap year but 2100
+isn't, and works fine for years with a hundred decimal digits <wink>.
+
+Tim Peters   tim at ksr.com
+not speaking for Kendall Square Research Corp
+
+Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
+by Guido van Rossum
+
+Note that as of Python 2.3, a datetime module is included in the stardard
+library.
+"""
 
-# vi:set tabsize=8:
+import functools
 
 _MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
                  'June', 'July', 'August', 'September', 'October',
@@ -57,8 +59,6 @@
     dbm = dbm + dim
 del dbm, dim
 
-_INT_TYPES = type(1), type(1)
-
 def _is_leap(year):           # 1 if leap year, else 0
     if year % 4 != 0: return 0
     if year % 400 == 0: return 1
@@ -85,11 +85,12 @@
 _DI400Y = _days_before_year(400)      # number of days in 400 years
 
 def _num2date(n):             # return date with ordinal n
-    if type(n) not in _INT_TYPES:
+    if not isinstance(n, int):
         raise TypeError('argument must be integer: %r' % type(n))
 
-    ans = Date(1,1,1)   # arguments irrelevant; just getting a Date obj
-    del ans.ord, ans.month, ans.day, ans.year # un-initialize it
+    # Get uninitialized Date object.  This is necesary because once
+    # attributes are set, they cannot be changed.
+    ans = Date.__new__(Date)
     ans.ord = n
 
     n400 = (n-1)//_DI400Y                # # of 400-year blocks preceding
@@ -99,11 +100,7 @@
     if dby >= n:
         more = more - 1
         dby = dby - _days_in_year(more)
-    year, n = year + more, int(n - dby)
-
-    try: year = int(year)               # chop to int, if it fits
-    except (ValueError, OverflowError): pass
-
+    year, n = year + more, n - dby
     month = min(n//29 + 1, 12)
     dbm = _days_before_month(month, year)
     if dbm >= n:
@@ -114,9 +111,9 @@
     return ans
 
 def _num2day(n):      # return weekday name of day with ordinal n
-    return _DAY_NAMES[ int(n % 7) ]
-
+    return _DAY_NAMES[n % 7]
 
+ at functools.total_ordering
 class Date:
     def __init__(self, month, day, year):
         if not 1 <= month <= 12:
@@ -124,7 +121,7 @@
         dim = _days_in_month(month, year)
         if not 1 <= day <= dim:
             raise ValueError('day must be in 1..%r: %r' % (dim, day))
-        self.month, self.day, self.year = month, day, year
+        self.month, self.day, self.year = map(int, (month, day, year))
         self.ord = _date2num(self)
 
     # don't allow setting existing attributes
@@ -133,8 +130,11 @@
             raise AttributeError('read-only attribute ' + name)
         self.__dict__[name] = value
 
-    def __cmp__(self, other):
-        return cmp(self.ord, other.ord)
+    def __eq__(self, other):
+        return self.ord == other.ord
+
+    def __lt__(self, other):
+        return self.ord < other.ord
 
     # define a hash function so dates can be used as dictionary keys
     def __hash__(self):
@@ -150,14 +150,14 @@
 
     # Python 1.1 coerces neither int+date nor date+int
     def __add__(self, n):
-        if type(n) not in _INT_TYPES:
+        if not isinstance(n, int):
             raise TypeError('can\'t add %r to date' % type(n))
         return _num2date(self.ord + n)
     __radd__ = __add__ # handle int+date
 
     # Python 1.1 coerces neither date-int nor date-date
     def __sub__(self, other):
-        if type(other) in _INT_TYPES:           # date-int
+        if isinstance(other, int):           # date-int
             return _num2date(self.ord - other)
         else:
             return self.ord - other.ord         # date-date

Deleted: python/branches/py3k-cdecimal/Demo/classes/Dbm.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/Dbm.py	Sat Jul 17 12:36:09 2010
+++ (empty file)
@@ -1,66 +0,0 @@
-# A wrapper around the (optional) built-in class dbm, supporting keys
-# and values of almost any type instead of just string.
-# (Actually, this works only for keys and values that can be read back
-# correctly after being converted to a string.)
-
-
-class Dbm:
-
-    def __init__(self, filename, mode, perm):
-        import dbm.ndbm
-        self.db = dbm.ndbm.open(filename, mode, perm)
-
-    def __repr__(self):
-        s = ''
-        for key in self.keys():
-            t = repr(key) + ': ' + repr(self[key])
-            if s: t = ', ' + t
-            s = s + t
-        return '{' + s + '}'
-
-    def __len__(self):
-        return len(self.db)
-
-    def __getitem__(self, key):
-        return eval(self.db[repr(key)])
-
-    def __setitem__(self, key, value):
-        self.db[repr(key)] = repr(value)
-
-    def __delitem__(self, key):
-        del self.db[repr(key)]
-
-    def keys(self):
-        res = []
-        for key in self.db.keys():
-            res.append(eval(key))
-        return res
-
-    def has_key(self, key):
-        return repr(key) in self.db
-
-
-def test():
-    d = Dbm('@dbm', 'rw', 0o600)
-    print(d)
-    while 1:
-        try:
-            key = eval(input('key: '))
-            if key in d:
-                value = d[key]
-                print('currently:', value)
-            value = eval(input('value: '))
-            if value is None:
-                del d[key]
-            else:
-                d[key] = value
-        except KeyboardInterrupt:
-            print('')
-            print(d)
-        except EOFError:
-            print('[eof]')
-            break
-    print(d)
-
-
-test()

Modified: python/branches/py3k-cdecimal/Demo/classes/README
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/README	(original)
+++ python/branches/py3k-cdecimal/Demo/classes/README	Sat Jul 17 12:36:09 2010
@@ -2,7 +2,6 @@
 
 Complex.py	Complex numbers
 Dates.py	Date manipulation package by Tim Peters
-Dbm.py		Wrapper around built-in dbm, supporting	arbitrary values
 Range.py	Example of a generator: re-implement built-in range()
 Rev.py		Yield the reverse of a sequence
 Vec.py		A simple vector class

Modified: python/branches/py3k-cdecimal/Demo/classes/Range.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/Range.py	(original)
+++ python/branches/py3k-cdecimal/Demo/classes/Range.py	Sat Jul 17 12:36:09 2010
@@ -66,7 +66,7 @@
 def test():
     import time, builtins
     #Just a quick sanity check
-    correct_result = builtins.range(5, 100, 3)
+    correct_result = list(builtins.range(5, 100, 3))
     oldrange_result = list(oldrange(5, 100, 3))
     genrange_result = list(genrange(5, 100, 3))
     if genrange_result != correct_result or oldrange_result != correct_result:

Modified: python/branches/py3k-cdecimal/Demo/classes/Rev.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/Rev.py	(original)
+++ python/branches/py3k-cdecimal/Demo/classes/Rev.py	Sat Jul 17 12:36:09 2010
@@ -4,8 +4,7 @@
 
 It works on mutable or inmutable sequences.
 
->>> chars = list(Rev('Hello World!'))
->>> print ''.join(chars)
+>>> Rev('Hello World!')
 !dlroW olleH
 
 The .forw is so you can use anonymous sequences in __init__, and still
@@ -16,16 +15,16 @@
 confusion. Maybe it should be change to copy input sequence to break
 the connection completely ? )
 
->>> nnn = range(3)
+>>> nnn = list(range(3))
 >>> rnn = Rev(nnn)
->>> for n in rnn: print n
+>>> for n in rnn: n
 ...
 2
 1
 0
 >>> for n in range(4, 6): nnn.append(n)   # update nnn
 ...
->>> for n in rnn: print n     # prints reversed updated values
+>>> for n in rnn: n     # prints reversed updated values
 ...
 5
 4
@@ -35,7 +34,7 @@
 >>> nnn = nnn[1:-1]
 >>> nnn
 [1, 2, 4]
->>> for n in rnn: print n     # prints reversed values of old nnn
+>>> for n in rnn: n     # prints reversed values of old nnn
 ...
 5
 4
@@ -45,16 +44,15 @@
 
 #
 >>> WH = Rev('Hello World!')
->>> print WH.forw, WH.back
+>>> print(WH.forw, WH.back)
 Hello World! !dlroW olleH
->>> nnn = Rev(range(1, 10))
->>> print nnn.forw
+>>> nnn = Rev(list(range(1, 10)))
+>>> print(nnn.forw)
 [1, 2, 3, 4, 5, 6, 7, 8, 9]
->>> print nnn.back
+>>> print(nnn.back)
 [9, 8, 7, 6, 5, 4, 3, 2, 1]
 
->>> rrr = Rev(nnn)
->>> rrr
+>>> Rev(nnn)
 <1, 2, 3, 4, 5, 6, 7, 8, 9>
 
 '''

Modified: python/branches/py3k-cdecimal/Demo/classes/Vec.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/classes/Vec.py	(original)
+++ python/branches/py3k-cdecimal/Demo/classes/Vec.py	Sat Jul 17 12:36:09 2010
@@ -1,23 +1,41 @@
-# A simple vector class
+class Vec:
+    """ A simple vector class
 
+    Instances of the Vec class  can be constructed from numbers
 
-def vec(*v):
-    return Vec(*v)
+    >>> a = Vec(1, 2, 3)
+    >>> b = Vec(3, 2, 1)
 
+    added
+    >>> a + b
+    Vec(4, 4, 4)
 
-class Vec:
+    subtracted
+    >>> a - b
+    Vec(-2, 0, 2)
+
+    and multiplied by a scalar on the left
+    >>> 3.0 * a
+    Vec(3.0, 6.0, 9.0)
 
+    or on the right
+    >>> a * 3.0
+    Vec(3.0, 6.0, 9.0)
+    """
     def __init__(self, *v):
         self.v = list(v)
 
-    def fromlist(self, v):
+    @classmethod
+    def fromlist(cls, v):
         if not isinstance(v, list):
             raise TypeError
-        self.v = v[:]
-        return self
+        inst = cls()
+        inst.v = v
+        return inst
 
     def __repr__(self):
-        return 'vec(' + repr(self.v)[1:-1] + ')'
+        args = ', '.join(repr(x) for x in self.v)
+        return 'Vec({})'.format(args)
 
     def __len__(self):
         return len(self.v)
@@ -27,28 +45,24 @@
 
     def __add__(self, other):
         # Element-wise addition
-        v = list(map(lambda x, y: x+y, self, other))
-        return Vec().fromlist(v)
+        v = [x + y for x, y in zip(self.v, other.v)]
+        return Vec.fromlist(v)
 
     def __sub__(self, other):
         # Element-wise subtraction
-        v = list(map(lambda x, y: x-y, self, other))
-        return Vec().fromlist(v)
+        v = [x - y for x, y in zip(self.v, other.v)]
+        return Vec.fromlist(v)
 
     def __mul__(self, scalar):
         # Multiply by scalar
-        v = [x*scalar for x in self.v]
-        return Vec().fromlist(v)
+        v = [x * scalar for x in self.v]
+        return Vec.fromlist(v)
 
+    __rmul__ = __mul__
 
 
 def test():
-    a = vec(1, 2, 3)
-    b = vec(3, 2, 1)
-    print(a)
-    print(b)
-    print(a+b)
-    print(a-b)
-    print(a*3.0)
+    import doctest
+    doctest.testmod()
 
 test()

Modified: python/branches/py3k-cdecimal/Demo/embed/Makefile
==============================================================================
--- python/branches/py3k-cdecimal/Demo/embed/Makefile	(original)
+++ python/branches/py3k-cdecimal/Demo/embed/Makefile	Sat Jul 17 12:36:09 2010
@@ -1,5 +1,5 @@
 # Makefile for embedded Python use demo.
-# (This version tailored for my Red Hat Linux 6.1 setup;
+# (This version originally written on Red Hat Linux 6.1;
 # edit lines marked with XXX.)
 
 # XXX The compiler you are using
@@ -10,7 +10,7 @@
 srcdir=		../..
 
 # Python version
-VERSION=	3.0
+VERSION=	3.2
 
 # Compiler flags
 OPT=		-g
@@ -21,7 +21,7 @@
 # The Python library
 LIBPYTHON=	$(blddir)/libpython$(VERSION).a
 
-# XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile
+# XXX edit LIBS (in particular) to match $(blddir)/Makefile
 LIBS=		-lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil
 LDFLAGS=	-Xlinker -export-dynamic
 SYSLIBS=	-lm

Modified: python/branches/py3k-cdecimal/Demo/embed/demo.c
==============================================================================
--- python/branches/py3k-cdecimal/Demo/embed/demo.c	(original)
+++ python/branches/py3k-cdecimal/Demo/embed/demo.c	Sat Jul 17 12:36:09 2010
@@ -20,10 +20,19 @@
     Py_Initialize();
 
     /* Define sys.argv.  It is up to the application if you
-       want this; you can also let it undefined (since the Python
+       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...) */
-    PySys_SetArgv(2, args);
+       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
+       the current working directory.  This can be risky; if you run
+       an application embedding Python in a directory controlled by
+       someone else, attackers could put a Trojan-horse module in the
+       directory (say, a file named os.py) that your application would
+       then import and run.
+    */
+    PySys_SetArgvEx(argc, argv, 0);
 
     /* Do some application specific code */
     printf("Hello, brave new world\n\n");

Modified: python/branches/py3k-cdecimal/Demo/md5test/md5driver.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/md5test/md5driver.py	(original)
+++ python/branches/py3k-cdecimal/Demo/md5test/md5driver.py	Sat Jul 17 12:36:09 2010
@@ -1,11 +1,10 @@
+from hashlib import md5
 import string
-import md5
 from sys import argv
 
 def MDPrint(str):
     outstr = ''
-    for i in str:
-        o = ord(i)
+    for o in str:
         outstr = (outstr
                   + string.hexdigits[(o >> 4) & 0xF]
                   + string.hexdigits[o & 0xF])
@@ -42,7 +41,7 @@
     print('MD5 time trial. Processing', TEST_BYTES, 'characters...')
     t1 = time()
 
-    mdContext = md5.new()
+    mdContext = md5()
 
     for i in range(TEST_BLOCKS):
         mdContext.update(data)
@@ -57,13 +56,13 @@
 
 
 def MDString(str):
-    MDPrint(md5.new(str).digest())
+    MDPrint(md5(str.encode("utf-8")).digest())
     print('"' + str + '"')
 
 
 def MDFile(filename):
     f = open(filename, 'rb')
-    mdContext = md5.new()
+    mdContext = md5()
 
     while 1:
         data = f.read(1024)
@@ -78,7 +77,7 @@
 import sys
 
 def MDFilter():
-    mdContext = md5.new()
+    mdContext = md5()
 
     while 1:
         data = sys.stdin.read(16)

Modified: python/branches/py3k-cdecimal/Demo/parser/test_parser.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/parser/test_parser.py	(original)
+++ python/branches/py3k-cdecimal/Demo/parser/test_parser.py	Sat Jul 17 12:36:09 2010
@@ -11,19 +11,19 @@
     global _numFailed
     print('----', fileName, end=' ')
     try:
-        ast = parser.suite(t)
-        tup = parser.ast2tuple(ast)
-        # this discards the first AST; a huge memory savings when running
+        st = parser.suite(t)
+        tup = parser.st2tuple(st)
+        # this discards the first ST; a huge memory savings when running
         # against a large source file like Tkinter.py.
-        ast = None
-        new = parser.tuple2ast(tup)
+        st = None
+        new = parser.tuple2st(tup)
     except parser.ParserError as err:
         print()
         print('parser module raised exception on input file', fileName + ':')
         traceback.print_exc()
         _numFailed = _numFailed + 1
     else:
-        if tup != parser.ast2tuple(new):
+        if tup != parser.st2tuple(new):
             print()
             print('parser module failed on input file', fileName)
             _numFailed = _numFailed + 1

Modified: python/branches/py3k-cdecimal/Demo/parser/unparse.py
==============================================================================
--- python/branches/py3k-cdecimal/Demo/parser/unparse.py	(original)
+++ python/branches/py3k-cdecimal/Demo/parser/unparse.py	Sat Jul 17 12:36:09 2010
@@ -1,9 +1,15 @@
 "Usage: unparse.py <path to source file>"
 import sys
-import _ast
+import math
+import ast
+import tokenize
 import io
 import os
 
+# Large float and imaginary literals get turned into infinities in the AST.
+# We unparse those infinities to INFSTR.
+INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
+
 def interleave(inter, f, seq):
     """Call f on each item in seq, calling inter() in between.
     """
@@ -20,7 +26,7 @@
 class Unparser:
     """Methods in this class recursively traverse an AST and
     output source code for the abstract syntax; original formatting
-    is disregarged. """
+    is disregarded. """
 
     def __init__(self, tree, file = sys.stdout):
         """Unparser(tree, file=sys.stdout) -> None.
@@ -80,10 +86,11 @@
 
     def _ImportFrom(self, t):
         self.fill("from ")
-        self.write(t.module)
+        self.write("." * t.level)
+        if t.module:
+            self.write(t.module)
         self.write(" import ")
         interleave(lambda: self.write(", "), self.dispatch, t.names)
-        # XXX(jpe) what is level for?
 
     def _Assign(self, t):
         self.fill()
@@ -115,7 +122,7 @@
 
     def _Delete(self, t):
         self.fill("del ")
-        self.dispatch(t.targets)
+        interleave(lambda: self.write(", "), self.dispatch, t.targets)
 
     def _Assert(self, t):
         self.fill("assert ")
@@ -124,24 +131,14 @@
             self.write(", ")
             self.dispatch(t.msg)
 
-    def _Print(self, t):
-        self.fill("print ")
-        do_comma = False
-        if t.dest:
-            self.write(">>")
-            self.dispatch(t.dest)
-            do_comma = True
-        for e in t.values:
-            if do_comma:self.write(", ")
-            else:do_comma=True
-            self.dispatch(e)
-        if not t.nl:
-            self.write(",")
-
     def _Global(self, t):
         self.fill("global ")
         interleave(lambda: self.write(", "), self.write, t.names)
 
+    def _Nonlocal(self, t):
+        self.fill("nonlocal ")
+        interleave(lambda: self.write(", "), self.write, t.names)
+
     def _Yield(self, t):
         self.write("(")
         self.write("yield")
@@ -151,15 +148,15 @@
         self.write(")")
 
     def _Raise(self, t):
-        self.fill('raise ')
-        if t.type:
-            self.dispatch(t.type)
-        if t.inst:
-            self.write(", ")
-            self.dispatch(t.inst)
-        if t.tback:
-            self.write(", ")
-            self.dispatch(t.tback)
+        self.fill("raise")
+        if not t.exc:
+            assert not t.cause
+            return
+        self.write(" ")
+        self.dispatch(t.exc)
+        if t.cause:
+            self.write(" from ")
+            self.dispatch(t.cause)
 
     def _TryExcept(self, t):
         self.fill("try")
@@ -176,10 +173,14 @@
             self.leave()
 
     def _TryFinally(self, t):
-        self.fill("try")
-        self.enter()
-        self.dispatch(t.body)
-        self.leave()
+        if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept):
+            # try-except-finally
+            self.dispatch(t.body)
+        else:
+            self.fill("try")
+            self.enter()
+            self.dispatch(t.body)
+            self.leave()
 
         self.fill("finally")
         self.enter()
@@ -192,21 +193,40 @@
             self.write(" ")
             self.dispatch(t.type)
         if t.name:
-            self.write(", ")
-            self.dispatch(t.name)
+            self.write(" as ")
+            self.write(t.name)
         self.enter()
         self.dispatch(t.body)
         self.leave()
 
     def _ClassDef(self, t):
         self.write("\n")
+        for deco in t.decorator_list:
+            self.fill("@")
+            self.dispatch(deco)
         self.fill("class "+t.name)
-        if t.bases:
-            self.write("(")
-            for a in t.bases:
-                self.dispatch(a)
-                self.write(", ")
-            self.write(")")
+        self.write("(")
+        comma = False
+        for e in t.bases:
+            if comma: self.write(", ")
+            else: comma = True
+            self.dispatch(e)
+        for e in t.keywords:
+            if comma: self.write(", ")
+            else: comma = True
+            self.dispatch(e)
+        if t.starargs:
+            if comma: self.write(", ")
+            else: comma = True
+            self.write("*")
+            self.dispatch(t.starargs)
+        if t.kwargs:
+            if comma: self.write(", ")
+            else: comma = True
+            self.write("**")
+            self.dispatch(t.kwargs)
+        self.write(")")
+
         self.enter()
         self.dispatch(t.body)
         self.leave()
@@ -219,6 +239,9 @@
         self.fill("def "+t.name + "(")
         self.dispatch(t.args)
         self.write(")")
+        if t.returns:
+            self.write(" -> ")
+            self.dispatch(t.returns)
         self.enter()
         self.dispatch(t.body)
         self.leave()
@@ -235,15 +258,24 @@
             self.fill("else")
             self.enter()
             self.dispatch(t.orelse)
-            self.leave
+            self.leave()
 
     def _If(self, t):
         self.fill("if ")
         self.dispatch(t.test)
         self.enter()
-        # XXX elif?
         self.dispatch(t.body)
         self.leave()
+        # collapse nested ifs into equivalent elifs.
+        while (t.orelse and len(t.orelse) == 1 and
+               isinstance(t.orelse[0], ast.If)):
+            t = t.orelse[0]
+            self.fill("elif ")
+            self.dispatch(t.test)
+            self.enter()
+            self.dispatch(t.body)
+            self.leave()
+        # final else
         if t.orelse:
             self.fill("else")
             self.enter()
@@ -260,7 +292,7 @@
             self.fill("else")
             self.enter()
             self.dispatch(t.orelse)
-            self.leave
+            self.leave()
 
     def _With(self, t):
         self.fill("with ")
@@ -273,19 +305,18 @@
         self.leave()
 
     # expr
+    def _Bytes(self, t):
+        self.write(repr(t.s))
+
     def _Str(self, tree):
         self.write(repr(tree.s))
 
     def _Name(self, t):
         self.write(t.id)
 
-    def _Repr(self, t):
-        self.write("`")
-        self.dispatch(t.value)
-        self.write("`")
-
     def _Num(self, t):
-        self.write(repr(t.n))
+        # Substitute overflowing decimal literal for AST infinities.
+        self.write(repr(t.n).replace("inf", INFSTR))
 
     def _List(self, t):
         self.write("[")
@@ -306,6 +337,22 @@
             self.dispatch(gen)
         self.write(")")
 
+    def _SetComp(self, t):
+        self.write("{")
+        self.dispatch(t.elt)
+        for gen in t.generators:
+            self.dispatch(gen)
+        self.write("}")
+
+    def _DictComp(self, t):
+        self.write("{")
+        self.dispatch(t.key)
+        self.write(": ")
+        self.dispatch(t.value)
+        for gen in t.generators:
+            self.dispatch(gen)
+        self.write("}")
+
     def _comprehension(self, t):
         self.write(" for ")
         self.dispatch(t.target)
@@ -324,14 +371,20 @@
         self.dispatch(t.orelse)
         self.write(")")
 
+    def _Set(self, t):
+        assert(t.elts) # should be at least one element
+        self.write("{")
+        interleave(lambda: self.write(", "), self.dispatch, t.elts)
+        self.write("}")
+
     def _Dict(self, t):
         self.write("{")
-        def writem(xxx_todo_changeme):
-            (k, v) = xxx_todo_changeme
+        def write_pair(pair):
+            (k, v) = pair
             self.dispatch(k)
             self.write(": ")
             self.dispatch(v)
-        interleave(lambda: self.write(", "), writem, zip(t.keys, t.values))
+        interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values))
         self.write("}")
 
     def _Tuple(self, t):
@@ -346,13 +399,14 @@
 
     unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
     def _UnaryOp(self, t):
-        self.write(self.unop[t.op.__class__.__name__])
         self.write("(")
+        self.write(self.unop[t.op.__class__.__name__])
+        self.write(" ")
         self.dispatch(t.operand)
         self.write(")")
 
     binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",
-                    "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
+                    "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
                     "FloorDiv":"//", "Pow": "**"}
     def _BinOp(self, t):
         self.write("(")
@@ -369,9 +423,9 @@
         for o, e in zip(t.ops, t.comparators):
             self.write(" " + self.cmpops[o.__class__.__name__] + " ")
             self.dispatch(e)
-            self.write(")")
+        self.write(")")
 
-    boolops = {_ast.And: 'and', _ast.Or: 'or'}
+    boolops = {ast.And: 'and', ast.Or: 'or'}
     def _BoolOp(self, t):
         self.write("(")
         s = " %s " % self.boolops[t.op.__class__]
@@ -380,6 +434,11 @@
 
     def _Attribute(self,t):
         self.dispatch(t.value)
+        # Special case: 3.__abs__() is a syntax error, so if t.value
+        # is an integer literal then we need to either parenthesize
+        # it or add an extra space to get 3 .__abs__().
+        if isinstance(t.value, ast.Num) and isinstance(t.value.n, int):
+            self.write(" ")
         self.write(".")
         self.write(t.attr)
 
@@ -433,28 +492,55 @@
     def _ExtSlice(self, t):
         interleave(lambda: self.write(', '), self.dispatch, t.dims)
 
+    # argument
+    def _arg(self, t):
+        self.write(t.arg)
+        if t.annotation:
+            self.write(": ")
+            self.dispatch(t.annotation)
+
     # others
     def _arguments(self, t):
         first = True
-        nonDef = len(t.args)-len(t.defaults)
-        for a in t.args[0:nonDef]:
+        # normal arguments
+        defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults
+        for a, d in zip(t.args, defaults):
             if first:first = False
             else: self.write(", ")
             self.dispatch(a)
-        for a,d in zip(t.args[nonDef:], t.defaults):
-            if first:first = False
-            else: self.write(", ")
-            self.dispatch(a),
-            self.write("=")
-            self.dispatch(d)
-        if t.vararg:
+            if d:
+                self.write("=")
+                self.dispatch(d)
+
+        # varargs, or bare '*' if no varargs but keyword-only arguments present
+        if t.vararg or t.kwonlyargs:
             if first:first = False
             else: self.write(", ")
-            self.write("*"+t.vararg)
+            self.write("*")
+            if t.vararg:
+                self.write(t.vararg)
+                if t.varargannotation:
+                    self.write(": ")
+                    self.dispatch(t.varargannotation)
+
+        # keyword-only arguments
+        if t.kwonlyargs:
+            for a, d in zip(t.kwonlyargs, t.kw_defaults):
+                if first:first = False
+                else: self.write(", ")
+                self.dispatch(a),
+                if d:
+                    self.write("=")
+                    self.dispatch(d)
+
+        # kwargs
         if t.kwarg:
             if first:first = False
             else: self.write(", ")
             self.write("**"+t.kwarg)
+            if t.kwargannotation:
+                self.write(": ")
+                self.dispatch(t.kwargannotation)
 
     def _keyword(self, t):
         self.write(t.arg)
@@ -462,10 +548,12 @@
         self.dispatch(t.value)
 
     def _Lambda(self, t):
+        self.write("(")
         self.write("lambda ")
         self.dispatch(t.args)
         self.write(": ")
         self.dispatch(t.body)
+        self.write(")")
 
     def _alias(self, t):
         self.write(t.name)
@@ -473,8 +561,11 @@
             self.write(" as "+t.asname)
 
 def roundtrip(filename, output=sys.stdout):
-    source = open(filename).read()
-    tree = compile(source, filename, "exec", _ast.PyCF_ONLY_AST)
+    with open(filename, "rb") as pyfile:
+        encoding = tokenize.detect_encoding(pyfile.readline)[0]
+    with open(filename, "r", encoding=encoding) as pyfile:
+        source = pyfile.read()
+    tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)
     Unparser(tree, output)
 
 

Modified: python/branches/py3k-cdecimal/Doc/Makefile
==============================================================================
--- python/branches/py3k-cdecimal/Doc/Makefile	(original)
+++ python/branches/py3k-cdecimal/Doc/Makefile	Sat Jul 17 12:36:09 2010
@@ -144,6 +144,7 @@
 	# archive the A4 latex
 	-rm -r build/latex
 	make latex PAPER=a4
+	-sed -i 's/makeindex/makeindex -q/' build/latex/Makefile
 	(cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2)
 	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-a4.zip
 	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-a4.tar.bz2
@@ -151,6 +152,7 @@
 	# archive the letter latex
 	rm -r build/latex
 	make latex PAPER=letter
+	-sed -i 's/makeindex/makeindex -q/' build/latex/Makefile
 	(cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2)
 	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-letter.zip
 	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-letter.tar.bz2

Modified: python/branches/py3k-cdecimal/Doc/README.txt
==============================================================================
--- python/branches/py3k-cdecimal/Doc/README.txt	(original)
+++ python/branches/py3k-cdecimal/Doc/README.txt	Sat Jul 17 12:36:09 2010
@@ -14,12 +14,11 @@
 Building the docs
 =================
 
-You need to install Python 2.4 or higher (but Python 3.0 is not supported yet);
-the toolset used to build the docs are written in Python.  The toolset used
-to build the documentation is called *Sphinx*, it is not included in this
-tree, but maintained separately in the Python Subversion repository.  Also
-needed are Jinja, a templating engine (included in Sphinx as a Subversion
-external), and optionally Pygments, a code highlighter.
+You need to have Python 2.4 or higher installed; the toolset used to build the
+docs is written in Python.  It is called *Sphinx*, it is not included in this
+tree, but maintained separately.  Also needed are the docutils, supplying the
+base markup that Sphinx uses, Jinja, a templating engine, and optionally
+Pygments, a code highlighter.
 
 
 Using make
@@ -47,29 +46,29 @@
    convert them into a single Compiled HTML (.chm) file -- these are popular
    under Microsoft Windows, but very handy on every platform.
 
-   To create the CHM file, you need to run the Microsoft HTML Help Workshop
-   over the generated project (.hhp) file.
+   To create the CHM file, you need to run the Microsoft HTML Help Workshop over
+   the generated project (.hhp) file.
 
- * "latex", which builds LaTeX source files that can be run with "pdflatex"
-   to produce PDF documents.
+ * "latex", which builds LaTeX source files as input to "pdflatex" to produce
+   PDF documents.
 
  * "text", which builds a plain text file for each source file.
 
  * "linkcheck", which checks all external references to see whether they are
-   broken, redirected or malformed, and outputs this information to stdout
-   as well as a plain-text (.txt) file.
+   broken, redirected or malformed, and outputs this information to stdout as
+   well as a plain-text (.txt) file.
 
  * "changes", which builds an overview over all versionadded/versionchanged/
    deprecated items in the current version. This is meant as a help for the
    writer of the "What's New" document.
 
- * "coverage", which builds a coverage overview for standard library modules
-   and C API.
+ * "coverage", which builds a coverage overview for standard library modules and
+   C API.
 
- * "pydoc-topics", which builds a Python module containing a dictionary
-   with plain text documentation for the labels defined in
-   `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic
-   and keyword help.
+ * "pydoc-topics", which builds a Python module containing a dictionary with
+   plain text documentation for the labels defined in
+   `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and
+   keyword help.
 
 A "make update" updates the Subversion checkouts in `tools/`.
 
@@ -95,7 +94,7 @@
 
 or by installing it from PyPI.
 
-You can optionally also install Pygments, either as a checkout via :: 
+You can optionally also install Pygments, either as a checkout via ::
 
    svn co http://svn.python.org/projects/external/Pygments-1.3.1/pygments tools/pygments
 

Modified: python/branches/py3k-cdecimal/Doc/c-api/arg.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/arg.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/arg.rst	Sat Jul 17 12:36:09 2010
@@ -36,7 +36,7 @@
 
 However, when a :ctype:`Py_buffer` structure gets filled, the underlying
 buffer is locked so that the caller can subsequently use the buffer even
-inside a ``Py_BEGIN_ALLOW_THREADS`` block without the risk of mutable data
+inside a :ctype:`Py_BEGIN_ALLOW_THREADS` block without the risk of mutable data
 being resized or destroyed.  As a result, **you have to call**
 :cfunc:`PyBuffer_Release` after you have finished processing the data (or
 in any early abort case).
@@ -48,9 +48,9 @@
    the length argument (int or :ctype:`Py_ssize_t`) is controlled by
    defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including
    :file:`Python.h`.  If the macro was defined, length is a
-   :ctype:`Py_ssize_t` rather than an int.  This behavior will change
+   :ctype:`Py_ssize_t` rather than an :ctype:`int`. This behavior will change
    in a future Python version to only support :ctype:`Py_ssize_t` and
-   drop int support.  It is best to always define :cmacro:`PY_SSIZE_T_CLEAN`.
+   drop :ctype:`int` support. It is best to always define :cmacro:`PY_SSIZE_T_CLEAN`.
 
 
 ``s`` (:class:`str`) [const char \*]
@@ -100,7 +100,7 @@
    contain embedded NUL bytes; if it does, a :exc:`TypeError`
    exception is raised.
 
-``y*`` (:class:`bytes`, :class:`bytearray` or buffer compatible object) [Py_buffer \*]
+``y*`` (:class:`bytes`, :class:`bytearray` or buffer compatible object) [Py_buffer]
    This variant on ``s*`` doesn't accept Unicode objects, only objects
    supporting the buffer protocol.  **This is the recommended way to accept
    binary data.**
@@ -150,21 +150,11 @@
    any conversion.  Raises :exc:`TypeError` if the object is not a Unicode
    object.  The C variable may also be declared as :ctype:`PyObject\*`.
 
-``w`` (:class:`bytearray` or read-write character buffer) [char \*]
-   Similar to ``y``, but accepts any object which implements the read-write buffer
-   interface.  The caller must determine the length of the buffer by other means,
-   or use ``w#`` instead.  Only single-segment buffer objects are accepted;
-   :exc:`TypeError` is raised for all others.
-
 ``w*`` (:class:`bytearray` or read-write byte-oriented buffer) [Py_buffer]
-   This is to ``w`` what ``y*`` is to ``y``.
-
-``w#`` (:class:`bytearray` or read-write character buffer) [char \*, int]
-   Like ``y#``, but accepts any object which implements the read-write buffer
-   interface.  The :ctype:`char \*` variable is set to point to the first byte
-   of the buffer, and the :ctype:`int` is set to the length of the buffer.
-   Only single-segment buffer objects are accepted; :exc:`TypeError` is raised
-   for all others.
+   This format accepts any object which implements the read-write buffer
+   interface. It fills a :ctype:`Py_buffer` structure provided by the caller.
+   The buffer may contain embedded null bytes. The caller have to call
+   :cfunc:`PyBuffer_Release` when it is done with the buffer.
 
 ``es`` (:class:`str`) [const char \*encoding, char \*\*buffer]
    This variant on ``s`` is used for encoding Unicode into a character buffer.
@@ -492,11 +482,11 @@
    strings a tad more readable.
 
    ``s`` (:class:`str` or ``None``) [char \*]
-      Convert a null-terminated C string to a Python object using ``'utf-8'``
+      Convert a null-terminated C string to a Python :class:`str` object using ``'utf-8'``
       encoding. If the C string pointer is *NULL*, ``None`` is used.
 
    ``s#`` (:class:`str` or ``None``) [char \*, int]
-      Convert a C string and its length to a Python object using ``'utf-8'``
+      Convert a C string and its length to a Python :class:`str` object using ``'utf-8'``
       encoding. If the C string pointer is *NULL*, the length is ignored and
       ``None`` is returned.
 

Modified: python/branches/py3k-cdecimal/Doc/c-api/datetime.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/datetime.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/datetime.rst	Sat Jul 17 12:36:09 2010
@@ -8,9 +8,10 @@
 Various date and time objects are supplied by the :mod:`datetime` module.
 Before using any of these functions, the header file :file:`datetime.h` must be
 included in your source (note that this is not included by :file:`Python.h`),
-and the macro :cfunc:`PyDateTime_IMPORT` must be invoked.  The macro puts a
-pointer to a C structure into a static variable,  ``PyDateTimeAPI``, that is
-used by the following macros.
+and the macro :cmacro:`PyDateTime_IMPORT` must be invoked, usually as part of
+the module initialisation function.  The macro puts a pointer to a C structure
+into a static variable, :cdata:`PyDateTimeAPI`, that is used by the following
+macros.
 
 Type-check macros:
 

Modified: python/branches/py3k-cdecimal/Doc/c-api/file.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/file.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/file.rst	Sat Jul 17 12:36:09 2010
@@ -7,24 +7,29 @@
 
 .. index:: object: file
 
-Python's built-in file objects are implemented entirely on the :ctype:`FILE\*`
-support from the C standard library.  This is an implementation detail and may
-change in future releases of Python.  The ``PyFile_`` APIs are a wrapper over
-the :mod:`io` module.
-
-
-.. cfunction:: PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd)
-
-   Create a new :ctype:`PyFileObject` from the file descriptor of an already
-   opened file *fd*. The arguments *name*, *encoding* and *newline* can be
-   *NULL* to use the defaults; *buffering* can be *-1* to use the default.
-   Return *NULL* on failure.
+These APIs are a minimal emulation of the Python 2 C API for built-in file
+objects, which used to rely on the buffered I/O (:ctype:`FILE\*`) support
+from the C standard library.  In Python 3, files and streams use the new
+:mod:`io` module, which defines several layers over the low-level unbuffered
+I/O of the operating system.  The functions described below are
+convenience C wrappers over these new APIs, and meant mostly for internal
+error reporting in the interpreter; third-party code is advised to access
+the :mod:`io` APIs instead.
+
+
+.. cfunction:: PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *errors, char *newline, int closefd)
+
+   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.
 
    .. warning::
 
-     Take care when you are mixing streams and descriptors! For more
-     information, see `the GNU C Library docs
-     <http://www.gnu.org/software/libc/manual/html_node/Stream_002fDescriptor-Precautions.html#Stream_002fDescriptor-Precautions>`_.
+     Since Python streams have their own buffering layer, mixing them with
+     OS-level file descriptors can produce various issues (such as unexpected
+     ordering of data).
 
 
 .. cfunction:: int PyObject_AsFileDescriptor(PyObject *p)

Modified: python/branches/py3k-cdecimal/Doc/c-api/init.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/init.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/init.rst	Sat Jul 17 12:36:09 2010
@@ -385,7 +385,7 @@
 
 .. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv)
 
-   This function works like :cfunc:`PySys_SetArgv` with *updatepath* set to 1.
+   This function works like :cfunc:`PySys_SetArgvEx` with *updatepath* set to 1.
 
 
 .. cfunction:: void Py_SetPythonHome(wchar_t *home)

Modified: python/branches/py3k-cdecimal/Doc/c-api/intro.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/intro.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/intro.rst	Sat Jul 17 12:36:09 2010
@@ -519,12 +519,12 @@
 :mod:`builtins`, :mod:`__main__`, :mod:`sys`, and :mod:`exceptions`.  It also
 initializes the module search path (``sys.path``).
 
-.. index:: single: PySys_SetArgv()
+.. index:: single: PySys_SetArgvEx()
 
 :cfunc:`Py_Initialize` does not set the "script argument list"  (``sys.argv``).
-If this variable is needed by Python code that  will be executed later, it must
-be set explicitly with a call to  ``PySys_SetArgv(argc, argv)`` subsequent to
-the call to :cfunc:`Py_Initialize`.
+If this variable is needed by Python code that will be executed later, it must
+be set explicitly with a call to  ``PySys_SetArgvEx(argc, argv, updatepath)``
+after the call to :cfunc:`Py_Initialize`.
 
 On most systems (in particular, on Unix and Windows, although the details are
 slightly different), :cfunc:`Py_Initialize` calculates the module search path

Modified: python/branches/py3k-cdecimal/Doc/c-api/number.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/number.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/number.rst	Sat Jul 17 12:36:09 2010
@@ -215,18 +215,6 @@
    the Python statement ``o1 |= o2``.
 
 
-.. cfunction:: PyObject* PyNumber_Int(PyObject *o)
-
-   Returns the *o* converted to an integer object on success, or *NULL* on
-   failure.  This is the equivalent of the Python expression ``int(o)``.
-
-   .. note::
-
-     This function is defined in the transitional :file:`intobject.h`
-     header file.  It will be removed completely in Python 3.1.  Use
-     the :cfunc:`PyNumber_Long` function instead.
-
-
 .. cfunction:: PyObject* PyNumber_Long(PyObject *o)
 
    .. index:: builtin: int

Modified: python/branches/py3k-cdecimal/Doc/c-api/unicode.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/c-api/unicode.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/c-api/unicode.rst	Sat Jul 17 12:36:09 2010
@@ -346,10 +346,10 @@
    Coerce an encoded object *obj* to an Unicode object and return a reference with
    incremented refcount.
 
-   String and other char buffer compatible objects are decoded according to the
-   given encoding and using the error handling defined by errors.  Both can be
-   *NULL* to have the interface use the default values (see the next section for
-   details).
+   :class:`bytes`, :class:`bytearray` and other char buffer compatible objects
+   are decoded according to the given encoding and using the error handling
+   defined by errors. Both can be *NULL* to have the interface use the default
+   values (see the next section for details).
 
    All other objects, including Unicode objects, cause a :exc:`TypeError` to be
    set.

Modified: python/branches/py3k-cdecimal/Doc/data/refcounts.dat
==============================================================================
--- python/branches/py3k-cdecimal/Doc/data/refcounts.dat	(original)
+++ python/branches/py3k-cdecimal/Doc/data/refcounts.dat	Sat Jul 17 12:36:09 2010
@@ -846,9 +846,6 @@
 PyNumber_InPlaceXor:PyObject*:v:0:
 PyNumber_InPlaceXor:PyObject*:w:0:
 
-PyNumber_Int:PyObject*::+1:
-PyNumber_Int:PyObject*:o:0:
-
 PyNumber_Invert:PyObject*::+1:
 PyNumber_Invert:PyObject*:o:0:
 

Modified: python/branches/py3k-cdecimal/Doc/distutils/apiref.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/distutils/apiref.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/distutils/apiref.rst	Sat Jul 17 12:36:09 2010
@@ -21,7 +21,9 @@
 .. 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.
@@ -147,11 +149,11 @@
 In addition, the :mod:`distutils.core` module exposed a number of  classes that
 live elsewhere.
 
-* :class:`Extension` from :mod:`distutils.extension`
+* :class:`~distutils.extension.Extension` from :mod:`distutils.extension`
 
-* :class:`Command` from :mod:`distutils.cmd`
+* :class:`~distutils.cmd.Command` from :mod:`distutils.cmd`
 
-* :class:`Distribution` from :mod:`distutils.dist`
+* :class:`~distutils.dist.Distribution` from :mod:`distutils.dist`
 
 A short description of each of these follows, but see the relevant module for
 the full reference.
@@ -995,7 +997,7 @@
    errors are ignored (apart from being reported to ``sys.stdout`` if *verbose* is
    true).
 
-**\*\*** Some of this could be replaced with the shutil module? **\*\***
+.. XXX Some of this could be replaced with the shutil module?
 
 
 :mod:`distutils.file_util` --- Single file operations
@@ -1311,8 +1313,7 @@
   the "negative alias" of :option:`--verbose`, then :option:`--quiet` on the
   command line sets *verbose* to false.
 
-**\*\*** Should be replaced with :mod:`optik` (which is also now known as
-:mod:`optparse` in Python 2.3 and later). **\*\***
+.. XXX Should be replaced with :mod:`optparse`.
 
 
 .. function:: fancy_getopt(options, negative_opt, object, args)
@@ -1680,8 +1681,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`.
@@ -1691,20 +1692,84 @@
 
    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
 ==========================================================
 
@@ -1943,63 +2008,3 @@
 This is described in more detail in :pep:`301`.
 
 .. % 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/py3k-cdecimal/Doc/distutils/builtdist.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/distutils/builtdist.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/distutils/builtdist.rst	Sat Jul 17 12:36:09 2010
@@ -146,8 +146,8 @@
 Creating dumb built distributions
 =================================
 
-**\*\*** Need to document absolute vs. prefix-relative packages here, but first
-I have to implement it! **\*\***
+.. XXX Need to document absolute vs. prefix-relative packages here, but first
+       I have to implement it!
 
 
 .. _creating-rpms:
@@ -322,7 +322,7 @@
 option.
 
 By default the installer will display the cool "Python Powered" logo when it is
-run, but you can also supply your own 152x161 bitmap which must be a Windows
+run, but you can also supply your own 152x261 bitmap which must be a Windows
 :file:`.bmp` file with the :option:`--bitmap` option.
 
 The installer will also display a large title on the desktop background window
@@ -375,7 +375,7 @@
 The Postinstallation script
 ---------------------------
 
-Starting with Python 2.3, a postinstallation script can be specified which the
+Starting with Python 2.3, a postinstallation script can be specified with the
 :option:`--install-script` option.  The basename of the script must be
 specified, and the script filename must also be listed in the scripts argument
 to the setup function.

Modified: python/branches/py3k-cdecimal/Doc/distutils/extending.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/distutils/extending.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/distutils/extending.rst	Sat Jul 17 12:36:09 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:`Command`
-class from :mod:`distutils.cmd`.  New commands may directly inherit from
+Most distutils command implementations are subclasses of the
+:class:`distutils.cmd.Command` class.  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/py3k-cdecimal/Doc/distutils/setupscript.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/distutils/setupscript.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/distutils/setupscript.rst	Sat Jul 17 12:36:09 2010
@@ -207,7 +207,7 @@
 SWIG on the interface file and compile the resulting C/C++ file into your
 extension.
 
-**\*\*** SWIG support is rough around the edges and largely untested! **\*\***
+.. XXX SWIG support is rough around the edges and largely untested!
 
 This warning notwithstanding, options to SWIG can be currently passed like
 this::
@@ -326,7 +326,7 @@
 (Again, this sort of non-portable construct should be avoided if you intend to
 distribute your code.)
 
-**\*\*** Should mention clib libraries here or somewhere else! **\*\***
+.. XXX Should mention clib libraries here or somewhere else!
 
 
 Other options

Modified: python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst	Sat Jul 17 12:36:09 2010
@@ -76,10 +76,10 @@
   :option:`packages` options
 
 * all C source files mentioned in the :option:`ext_modules` or
-  :option:`libraries` options (
+  :option:`libraries` options
 
-  **\*\*** getting C library sources currently broken---no
-  :meth:`get_source_files` method in :file:`build_clib.py`! **\*\***)
+  .. XXX Getting C library sources is 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`.

Modified: python/branches/py3k-cdecimal/Doc/documenting/index.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/documenting/index.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/documenting/index.rst	Sat Jul 17 12:36:09 2010
@@ -10,9 +10,9 @@
 `reStructuredText`_, developed by the `docutils`_ project, amended by custom
 directives and using a toolset named `Sphinx`_ to postprocess the HTML output.
 
-This document describes the style guide for our documentation, the custom
-reStructuredText markup introduced to support Python documentation and how it
-should be used, as well as the Sphinx build system.
+This document describes the style guide for our documentation as well as the
+custom reStructuredText markup introduced by Sphinx to support Python
+documentation and how it should be used.
 
 .. _reStructuredText: http://docutils.sf.net/rst.html
 .. _docutils: http://docutils.sf.net/
@@ -35,3 +35,4 @@
    rest.rst
    markup.rst
    fromlatex.rst
+   building.rst

Modified: python/branches/py3k-cdecimal/Doc/documenting/markup.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/documenting/markup.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/documenting/markup.rst	Sat Jul 17 12:36:09 2010
@@ -698,10 +698,10 @@
       .. toctree::
          :maxdepth: 2
 
-         intro.rst
-         strings.rst
-         datatypes.rst
-         numeric.rst
+         intro
+         strings
+         datatypes
+         numeric
          (many more files listed here)
 
    This accomplishes two things:
@@ -709,8 +709,8 @@
    * Tables of contents from all those files are inserted, with a maximum depth
      of two, that means one nested heading.  ``toctree`` directives in those
      files are also taken into account.
-   * Sphinx knows that the relative order of the files ``intro.rst``,
-     ``strings.rst`` and so forth, and it knows that they are children of the
+   * Sphinx knows that the relative order of the files ``intro``,
+     ``strings`` and so forth, and it knows that they are children of the
      shown file, the library index.  From this information it generates "next
      chapter", "previous chapter" and "parent chapter" links.
 

Modified: python/branches/py3k-cdecimal/Doc/documenting/style.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/documenting/style.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/documenting/style.rst	Sat Jul 17 12:36:09 2010
@@ -7,7 +7,7 @@
 wherever possible. This particular style guide was selected mostly because it
 seems reasonable and is easy to get online.
 
-Topics which are not covered in the Apple's style guide will be discussed in
+Topics which are not covered in Apple's style guide will be discussed in
 this document.
 
 All reST files use an indentation of 3 spaces.  The maximum line length is 80

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

Modified: python/branches/py3k-cdecimal/Doc/faq/gui.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/faq/gui.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/faq/gui.rst	Sat Jul 17 12:36:09 2010
@@ -13,14 +13,14 @@
 =====================
 
 What platform-independent GUI toolkits exist for Python?
---------------------------------------------------------
+========================================================
 
 Depending on what platform(s) you are aiming at, there are several.
 
 .. XXX check links
 
 Tkinter
-'''''''
+-------
 
 Standard builds of Python include an object-oriented interface to the Tcl/Tk
 widget set, called Tkinter.  This is probably the easiest to install and use.
@@ -29,22 +29,27 @@
 Unix platforms.
 
 wxWidgets
-'''''''''
+---------
 
-wxWidgets is a GUI class library written in C++ that's a portable
-interface to various platform-specific libraries, and that has a
-Python interface called `wxPython <http://www.wxpython.org>`__.
-
-wxWidgets preserves the look and feel of the
-underlying graphics toolkit, and has a large set of widgets and
-collection of GDI classes.  See `the wxWidgets page
-<http://www.wxwidgets.org>`_ for more details.
+wxWidgets (http://www.wxwidgets.org) is a free, portable GUI class
+library written in C++ that provides a native look and feel on a
+number of platforms, with Windows, MacOS X, GTK, X11, all listed as
+current stable targets.  Language bindings are available for a number
+of languages including Python, Perl, Ruby, etc.
+
+wxPython (http://www.wxpython.org) is the Python binding for
+wxwidgets.  While it often lags slightly behind the official wxWidgets
+releases, it also offers a number of features via pure Python
+extensions that are not available in other language bindings.  There
+is an active wxPython user and developer community.
+
+Both wxWidgets and wxPython are free, open source, software with
+permissive licences that allow their use in commercial products as
+well as in freeware or shareware.
 
-wxWidgets supports Windows and MacOS; on Unix variants,
-it supports both GTk+ and Motif toolkits.
 
 Qt
-'''
+---
 
 There are bindings available for the Qt toolkit (`PyQt
 <http://www.riverbankcomputing.co.uk/software/pyqt/>`_) and for KDE (`PyKDE <http://www.riverbankcomputing.co.uk/software/pykde/intro>`__).  If
@@ -55,13 +60,13 @@
 <http://www.trolltech.com>`_.
 
 Gtk+
-''''
+----
 
 PyGtk bindings for the `Gtk+ toolkit <http://www.gtk.org>`_ have been
 implemented by James Henstridge; see <http://www.pygtk.org>.
 
 FLTK
-''''
+----
 
 Python bindings for `the FLTK toolkit <http://www.fltk.org>`_, a simple yet
 powerful and mature cross-platform windowing system, are available from `the
@@ -69,7 +74,7 @@
 
 
 FOX
-'''
+----
 
 A wrapper for `the FOX toolkit <http://www.fox-toolkit.org/>`_ called `FXpy
 <http://fxpy.sourceforge.net/>`_ is available.  FOX supports both Unix variants
@@ -77,13 +82,13 @@
 
 
 OpenGL
-''''''
+------
 
 For OpenGL bindings, see `PyOpenGL <http://pyopengl.sourceforge.net>`_.
 
 
 What platform-specific GUI toolkits exist for Python?
------------------------------------------------------
+========================================================
 
 `The Mac port <http://python.org/download/mac>`_ by Jack Jansen has a rich and
 ever-growing set of modules that support the native Mac toolbox calls.  The port

Modified: python/branches/py3k-cdecimal/Doc/glossary.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/glossary.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/glossary.rst	Sat Jul 17 12:36:09 2010
@@ -57,11 +57,17 @@
 
    bytecode
       Python source code is compiled into bytecode, the internal representation
-      of a Python program in the interpreter.  The bytecode is also cached in
-      ``.pyc`` and ``.pyo`` files so that executing the same file is faster the
-      second time (recompilation from source to bytecode can be avoided).  This
-      "intermediate language" is said to run on a :term:`virtual machine`
-      that executes the machine code corresponding to each bytecode.
+      of a Python program in the CPython interpreter.  The bytecode is also
+      cached in ``.pyc`` and ``.pyo`` files so that executing the same file is
+      faster the second time (recompilation from source to bytecode can be
+      avoided).  This "intermediate language" is said to run on a
+      :term:`virtual machine` that executes the machine code corresponding to
+      each bytecode. Do note that bytecodes are not expected to work between
+      different Python virtual machines, nor to be stable between Python
+      releases.
+
+      A list of bytecode instructions can be found in the documentation for
+      :ref:`the dis module <bytecodes>`.
 
    class
       A template for creating user-defined objects. Class definitions
@@ -148,15 +154,15 @@
       object.
 
    duck-typing
-      A pythonic programming style which determines an object's type by inspection
-      of its method or attribute signature rather than by explicit relationship
-      to some type object ("If it looks like a duck and quacks like a duck, it
+      A programming style which does not look at an object's type to determine
+      if it has the right interface; instead, the method or attribute is simply
+      called or used ("If it looks like a duck and quacks like a duck, it
       must be a duck.")  By emphasizing interfaces rather than specific types,
       well-designed code improves its flexibility by allowing polymorphic
       substitution.  Duck-typing avoids tests using :func:`type` or
-      :func:`isinstance`. (Note, however, that duck-typing can be complemented
-      with abstract base classes.) Instead, it typically employs :func:`hasattr`
-      tests or :term:`EAFP` programming.
+      :func:`isinstance`.  (Note, however, that duck-typing can be complemented
+      with :term:`abstract base class`\ es.)  Instead, it typically employs
+      :func:`hasattr` tests or :term:`EAFP` programming.
 
    EAFP
       Easier to ask for forgiveness than permission.  This common Python coding
@@ -424,10 +430,11 @@
    nested scope
       The ability to refer to a variable in an enclosing definition.  For
       instance, a function defined inside another function can refer to
-      variables in the outer function.  Note that nested scopes work only for
-      reference and not for assignment which will always write to the innermost
-      scope.  In contrast, local variables both read and write in the innermost
-      scope.  Likewise, global variables read and write to the global namespace.
+      variables in the outer function.  Note that nested scopes by default work
+      only for reference and not for assignment.  Local variables both read and
+      write in the innermost scope.  Likewise, global variables read and write
+      to the global namespace.  The :keyword:`nonlocal` allows writing to outer
+      scopes.
 
    new-style class
       Old name for the flavor of classes now used for all class objects.  In

Modified: python/branches/py3k-cdecimal/Doc/howto/functional.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/howto/functional.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/howto/functional.rst	Sat Jul 17 12:36:09 2010
@@ -5,9 +5,6 @@
 :Author: A. M. Kuchling
 :Release: 0.31
 
-(This is a first draft.  Please send comments/error reports/suggestions to
-amk at amk.ca.)
-
 In this document, we'll take a tour of Python's features suitable for
 implementing programs in a functional style.  After an introduction to the
 concepts of functional programming, we'll look at language features such as

Modified: python/branches/py3k-cdecimal/Doc/howto/unicode.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/howto/unicode.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/howto/unicode.rst	Sat Jul 17 12:36:09 2010
@@ -4,10 +4,12 @@
   Unicode HOWTO
 *****************
 
-:Release: 1.1
+:Release: 1.11
 
-This HOWTO discusses Python's support for Unicode, and explains various problems
-that people commonly encounter when trying to work with Unicode.
+This HOWTO discusses Python 2.x's support for Unicode, and explains
+various problems that people commonly encounter when trying to work
+with Unicode.  (This HOWTO has not yet been updated to cover the 3.x
+versions of Python.)
 
 
 Introduction to Unicode
@@ -146,8 +148,9 @@
 4. Many Internet standards are defined in terms of textual data, and can't
    handle content with embedded zero bytes.
 
-Generally people don't use this encoding, instead choosing other encodings that
-are more efficient and convenient.
+Generally people don't use this encoding, instead choosing other
+encodings that are more efficient and convenient.  UTF-8 is probably
+the most commonly supported encoding; it will be discussed below.
 
 Encodings don't have to handle every possible Unicode character, and most
 encodings don't.  The rules for converting a Unicode string into the ASCII
@@ -223,8 +226,8 @@
 <http://en.wikipedia.org/wiki/UTF-8>, for example.
 
 
-Python's Unicode Support
-========================
+Python 2.x's Unicode Support
+============================
 
 Now that you've learned the rudiments of Unicode, we can look at Python's
 Unicode features.
@@ -266,8 +269,8 @@
     >>> b'\x80abc'.decode("utf-8", "ignore")
     'abc'
 
-Encodings are specified as strings containing the encoding's name.  Python comes
-with roughly 100 different encodings; see the Python Library Reference at
+Encodings are specified as strings containing the encoding's name.  Python 3.2
+comes with roughly 100 different encodings; see the Python Library Reference at
 :ref:`standard-encodings` for a list.  Some encodings have multiple names; for
 example, 'latin-1', 'iso_8859_1' and '8859' are all synonyms for the same
 encoding.
@@ -626,7 +629,10 @@
 
 Version 1.1: Feb-Nov 2008.  Updates the document with respect to Python 3 changes.
 
+Version 1.11: posted June 20 2010.  Notes that Python 3.x is not covered,
+and that the HOWTO only covers 2.x.
 
+.. comment Describe Python 3.x support (new section? new document?)
 .. comment Additional topic: building Python w/ UCS2 or UCS4 support
 .. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
 

Modified: python/branches/py3k-cdecimal/Doc/library/2to3.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/2to3.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/2to3.rst	Sat Jul 17 12:36:09 2010
@@ -276,7 +276,7 @@
 
    Converts the :keyword:`print` statement to the :func:`print` function.
 
-.. 2to3fixer:: raises
+.. 2to3fixer:: raise
 
    Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise
    E(V).with_traceback(T)``.  If ``E`` is a tuple, the translation will be

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

Modified: python/branches/py3k-cdecimal/Doc/library/calendar.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/calendar.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/calendar.rst	Sat Jul 17 12:36:09 2010
@@ -15,7 +15,7 @@
 are given as integers. For related
 functionality, see also the :mod:`datetime` and :mod:`time` modules.
 
-Most of these functions and classses rely on the :mod:`datetime` module which
+Most of these functions and classes rely on the :mod:`datetime` module which
 uses an idealized calendar, the current Gregorian calendar indefinitely extended
 in both directions.  This matches the definition of the "proleptic Gregorian"
 calendar in Dershowitz and Reingold's book "Calendrical Calculations", where

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

Modified: python/branches/py3k-cdecimal/Doc/library/codecs.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/codecs.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/codecs.rst	Sat Jul 17 12:36:09 2010
@@ -953,6 +953,8 @@
 +-----------------+--------------------------------+--------------------------------+
 | cp857           | 857, IBM857                    | Turkish                        |
 +-----------------+--------------------------------+--------------------------------+
+| cp858           | 858, IBM858                    | Western Europe                 |
++-----------------+--------------------------------+--------------------------------+
 | cp860           | 860, IBM860                    | Portuguese                     |
 +-----------------+--------------------------------+--------------------------------+
 | cp861           | 861, CP-IS, IBM861             | Icelandic                      |
@@ -1223,6 +1225,23 @@
    Convert a label to Unicode, as specified in :rfc:`3490`.
 
 
+:mod:`encodings.mbcs` --- Windows ANSI codepage
+-----------------------------------------------
+
+.. module:: encodings.mbcs
+   :synopsis: Windows ANSI codepage
+
+Encode operand according to the ANSI codepage (CP_ACP). This codec only
+supports ``'strict'`` and ``'replace'`` error handlers to encode, and
+``'strict'`` and ``'ignore'`` error handlers to decode.
+
+Availability: Windows only.
+
+.. versionchanged:: 3.2
+   Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
+   to encode, and ``'ignore'`` to decode.
+
+
 :mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
 -------------------------------------------------------------
 

Modified: python/branches/py3k-cdecimal/Doc/library/contextlib.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/contextlib.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/contextlib.rst	Sat Jul 17 12:36:09 2010
@@ -51,6 +51,11 @@
    the exception has been handled, and execution will resume with the statement
    immediately following the :keyword:`with` statement.
 
+   contextmanager uses :class:`ContextDecorator` so the context managers it
+   creates can be used as decorators as well as in :keyword:`with` statements.
+
+   .. versionchanged:: 3.2
+      Use of :class:`ContextDecorator`.
 
 .. function:: closing(thing)
 
@@ -79,6 +84,58 @@
    ``page.close()`` will be called when the :keyword:`with` block is exited.
 
 
+.. class:: ContextDecorator()
+
+   A base class that enables a context manager to also be used as a decorator.
+
+   Context managers inheriting from ``ContextDecorator`` have to implement
+   ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional
+   exception handling even when used as a decorator.
+
+   Example::
+
+      from contextlib import ContextDecorator
+
+      class mycontext(ContextDecorator):
+         def __enter__(self):
+            print('Starting')
+            return self
+
+         def __exit__(self, *exc):
+            print('Finishing')
+            return False
+
+      >>> @mycontext()
+      ... def function():
+      ...    print('The bit in the middle')
+      ...
+      >>> function()
+      Starting
+      The bit in the middle
+      Finishing
+
+      >>> with mycontext():
+      ...    print('The bit in the middle')
+      ...
+      Starting
+      The bit in the middle
+      Finishing
+
+   Existing context managers that already have a base class can be extended by
+   using ``ContextDecorator`` as a mixin class::
+
+      from contextlib import ContextDecorator
+
+      class mycontext(ContextBaseClass, ContextDecorator):
+         def __enter__(self):
+            return self
+
+         def __exit__(self, *exc):
+            return False
+
+   .. versionadded:: 3.2
+
+
 .. seealso::
 
    :pep:`0343` - The "with" statement

Modified: python/branches/py3k-cdecimal/Doc/library/datetime.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/datetime.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/datetime.rst	Sat Jul 17 12:36:09 2010
@@ -28,11 +28,14 @@
 have an optional time zone information member, :attr:`tzinfo`, that can contain
 an instance of a subclass of the abstract :class:`tzinfo` class.  These
 :class:`tzinfo` objects capture information about the offset from UTC time, the
-time zone name, and whether Daylight Saving Time is in effect.  Note that no
-concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
-Supporting timezones at whatever level of detail is required is up to the
-application.  The rules for time adjustment across the world are more political
-than rational, and there is no standard suitable for every application.
+time zone name, and whether Daylight Saving Time is in effect.  Note that only
+one concrete :class:`tzinfo` class, the :class:`timezone` class, is supplied by the
+:mod:`datetime` module.  The :class:`timezone` class can reprsent simple
+timezones with fixed offset from UTC such as UTC itself or North American EST and
+EDT timezones.  Supporting timezones at whatever level of detail is
+required is up to the application.  The rules for time adjustment across the
+world are more political than rational, change frequently, and there is no
+standard suitable for every application aside from UTC.
 
 The :mod:`datetime` module exports the following constants:
 
@@ -99,6 +102,14 @@
    time adjustment (for example, to account for time zone and/or daylight saving
    time).
 
+.. class:: timezone
+
+   A class that implements the :class:`tzinfo` abstract base class as a
+   fixed offset from the UTC.
+
+   .. versionadded:: 3.2
+
+
 Objects of these types are immutable.
 
 Objects of the :class:`date` type are always naive.
@@ -116,6 +127,7 @@
    object
        timedelta
        tzinfo
+           timezone
        time
        date
            datetime
@@ -660,8 +672,8 @@
 
    Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like
    :meth:`now`, but returns the current UTC date and time, as a naive
-   :class:`datetime` object. See also :meth:`now`.
-
+   :class:`datetime` object.  An aware current UTC datetime can be obtained by
+   calling ``datetime.now(timezone.utc)``.  See also :meth:`now`.
 
 .. classmethod:: datetime.fromtimestamp(timestamp, tz=None)
 
@@ -962,10 +974,10 @@
    ``d.dst()`` returns.  DST is never in effect for a UTC time.
 
    If *d* is aware, *d* is normalized to UTC time, by subtracting
-   ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
-   returned.  :attr:`tm_isdst` is forced to 0. Note that the result's
-   :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
-   *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
+   ``d.utcoffset()``, and a :class:`time.struct_time` for the
+   normalized time is returned.  :attr:`tm_isdst` is forced to 0. Note
+   that an :exc:`OverflowError` may be raised if *d*.year was
+   ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
    boundary.
 
 
@@ -1318,8 +1330,10 @@
 :class:`tzinfo` is an abstract base class, meaning that this class should not be
 instantiated directly.  You need to derive a concrete subclass, and (at least)
 supply implementations of the standard :class:`tzinfo` methods needed by the
-:class:`datetime` methods you use.  The :mod:`datetime` module does not supply
-any concrete subclasses of :class:`tzinfo`.
+:class:`datetime` methods you use.  The :mod:`datetime` module supplies
+a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent
+timezones with fixed offset from UTC such as UTC itself or North American EST and
+EDT.
 
 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
 constructors for :class:`datetime` and :class:`time` objects. The latter objects
@@ -1337,7 +1351,7 @@
 :mod:`datetime` objects.  If in doubt, simply implement all of them.
 
 
-.. method:: tzinfo.utcoffset(self, dt)
+.. method:: tzinfo.utcoffset(dt)
 
    Return offset of local time from UTC, in minutes east of UTC.  If local time is
    west of UTC, this should be negative.  Note that this is intended to be the
@@ -1359,7 +1373,7 @@
    :exc:`NotImplementedError`.
 
 
-.. method:: tzinfo.dst(self, dt)
+.. method:: tzinfo.dst(dt)
 
    Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
    ``None`` if DST information isn't known.  Return ``timedelta(0)`` if DST is not
@@ -1407,7 +1421,7 @@
    The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.
 
 
-.. method:: tzinfo.tzname(self, dt)
+.. method:: tzinfo.tzname(dt)
 
    Return the time zone name corresponding to the :class:`datetime` object *dt*, as
    a string. Nothing about string names is defined by the :mod:`datetime` module,
@@ -1443,7 +1457,7 @@
 There is one more :class:`tzinfo` method that a subclass may wish to override:
 
 
-.. method:: tzinfo.fromutc(self, dt)
+.. method:: tzinfo.fromutc(dt)
 
    This is called from the default :class:`datetime.astimezone()` implementation.
    When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
@@ -1520,9 +1534,65 @@
 standard local time.
 
 Applications that can't bear such ambiguities should avoid using hybrid
-:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
-other fixed-offset :class:`tzinfo` subclass (such as a class representing only
-EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
+:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`,
+or any other fixed-offset :class:`tzinfo` subclass (such as a class representing
+only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
+
+
+.. _datetime-timezone:
+
+:class:`timezone` Objects
+--------------------------
+
+A :class:`timezone` object represents a timezone that is defined by a
+fixed offset from UTC.  Note that objects of this class cannot be used
+to represent timezone information in the locations where different
+offsets are used in different days of the year or where historical
+changes have been made to civil time.
+
+
+.. class:: timezone(offset[, name])
+
+  The *offset* argument must be specified as a :class:`timedelta`
+  object representing the difference between the local time and UTC.  It must
+  be strictly between ``-timedelta(hours=24)`` and
+  ``timedelta(hours=24)`` and represent a whole number of minutes,
+  otherwise :exc:`ValueError` is raised.
+
+  The *name* argument is optional.  If specified it must be a string that
+  is used as the value returned by the ``tzname(dt)`` method.  Otherwise,
+  ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
+  *offset*, HH and MM are two digits of ``offset.hours`` and
+  ``offset.minutes`` respectively.
+
+.. method:: timezone.utcoffset(dt)
+
+  Return the fixed value specified when the :class:`timezone` instance is
+  constructed.  The *dt* argument is ignored.  The return value is a
+  :class:`timedelta` instance equal to the difference between the
+  local time and UTC.
+
+.. method:: timezone.tzname(dt)
+
+  Return the fixed value specified when the :class:`timezone` instance is
+  constructed or a string 'UTCsHH:MM', where s is the sign of
+  *offset*, HH and MM are two digits of ``offset.hours`` and
+  ``offset.minutes`` respectively.
+
+.. method:: timezone.dst(dt)
+
+  Always returns ``None``.
+
+.. method:: timezone.fromutc(dt)
+
+  Return ``dt + offset``.  The *dt* argument must be an aware
+  :class:`datetime` instance, with ``tzinfo`` set to ``self``.
+
+Class attributes:
+
+.. attribute:: timezone.utc
+
+   The UTC timezone, ``timezone(timedelta(0))``.
 
 
 .. _strftime-strptime-behavior:
@@ -1690,3 +1760,10 @@
 (5)
    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.

Modified: python/branches/py3k-cdecimal/Doc/library/dis.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/dis.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/dis.rst	Sat Jul 17 12:36:09 2010
@@ -5,12 +5,19 @@
    :synopsis: Disassembler for Python bytecode.
 
 
-The :mod:`dis` module supports the analysis of Python :term:`bytecode` by
-disassembling it.  Since there is no Python assembler, this module defines the
-Python assembly language.  The Python bytecode which this module takes as an
+The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
+disassembling it. The CPython bytecode which this module takes as an
 input is defined in the file :file:`Include/opcode.h` and used by the compiler
 and the interpreter.
 
+.. impl-detail::
+
+   Bytecode is an implementation detail of the CPython interpreter!  No
+   guarantees are made that bytecode will not be added, removed, or changed
+   between versions of Python.  Use of this module should not be considered to
+   work across Python VMs or Python releases.
+
+
 Example: Given the function :func:`myfunc`::
 
    def myfunc(alist):
@@ -31,23 +38,27 @@
 
 .. function:: dis(x=None)
 
-   Disassemble the *x* object. *x* can denote either a module, a
-   class, a method, a function, or a code object.   For a module, it disassembles
-   all functions.  For a class, it disassembles all methods.  For a single code
-   sequence, it prints one line per bytecode instruction.  If no object is
-   provided, it 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)
 
-   Disassembles the top-of-stack function of a traceback, using the last traceback
-   if none was passed.  The instruction causing the exception is indicated.
+   Disassemble the top-of-stack function of a traceback, using the last
+   traceback if none was passed.  The instruction causing the exception is
+   indicated.
 
 
 .. function:: disassemble(code, lasti=-1)
               disco(code, lasti=-1)
 
-   Disassembles a code object, indicating the last instruction if *lasti* was
+   Disassemble a code object, indicating the last instruction if *lasti* was
    provided.  The output is divided in the following columns:
 
    #. the line number, for the first instruction of each line
@@ -133,225 +144,233 @@
 The Python compiler currently generates the following bytecode instructions.
 
 
-.. opcode:: STOP_CODE ()
+**General instructions**
+
+.. opcode:: STOP_CODE
 
    Indicates end-of-code to the compiler, not used by the interpreter.
 
 
-.. opcode:: NOP ()
+.. opcode:: NOP
 
    Do nothing code.  Used as a placeholder by the bytecode optimizer.
 
 
-.. opcode:: POP_TOP ()
+.. opcode:: POP_TOP
 
    Removes the top-of-stack (TOS) item.
 
 
-.. opcode:: ROT_TWO ()
+.. opcode:: ROT_TWO
 
    Swaps the two top-most stack items.
 
 
-.. opcode:: ROT_THREE ()
+.. opcode:: ROT_THREE
 
    Lifts second and third stack item one position up, moves top down to position
    three.
 
 
-.. opcode:: ROT_FOUR ()
+.. opcode:: ROT_FOUR
 
    Lifts second, third and forth stack item one position up, moves top down to
    position four.
 
 
-.. opcode:: DUP_TOP ()
+.. opcode:: DUP_TOP
 
    Duplicates the reference on top of the stack.
 
-Unary Operations take the top of the stack, apply the operation, and push the
-result back on the stack.
 
+**Unary operations**
+
+Unary operations take the top of the stack, apply the operation, and push the
+result back on the stack.
 
-.. opcode:: UNARY_POSITIVE ()
+.. opcode:: UNARY_POSITIVE
 
    Implements ``TOS = +TOS``.
 
 
-.. opcode:: UNARY_NEGATIVE ()
+.. opcode:: UNARY_NEGATIVE
 
    Implements ``TOS = -TOS``.
 
 
-.. opcode:: UNARY_NOT ()
+.. opcode:: UNARY_NOT
 
    Implements ``TOS = not TOS``.
 
 
-.. opcode:: UNARY_INVERT ()
+.. opcode:: UNARY_INVERT
 
    Implements ``TOS = ~TOS``.
 
 
-.. opcode:: GET_ITER ()
+.. opcode:: GET_ITER
 
    Implements ``TOS = iter(TOS)``.
 
+
+**Binary operations**
+
 Binary operations remove the top of the stack (TOS) and the second top-most
 stack item (TOS1) from the stack.  They perform the operation, and put the
 result back on the stack.
 
-
-.. opcode:: BINARY_POWER ()
+.. opcode:: BINARY_POWER
 
    Implements ``TOS = TOS1 ** TOS``.
 
 
-.. opcode:: BINARY_MULTIPLY ()
+.. opcode:: BINARY_MULTIPLY
 
    Implements ``TOS = TOS1 * TOS``.
 
 
-.. opcode:: BINARY_FLOOR_DIVIDE ()
+.. opcode:: BINARY_FLOOR_DIVIDE
 
    Implements ``TOS = TOS1 // TOS``.
 
 
-.. opcode:: BINARY_TRUE_DIVIDE ()
+.. opcode:: BINARY_TRUE_DIVIDE
 
    Implements ``TOS = TOS1 / TOS``.
 
 
-.. opcode:: BINARY_MODULO ()
+.. opcode:: BINARY_MODULO
 
    Implements ``TOS = TOS1 % TOS``.
 
 
-.. opcode:: BINARY_ADD ()
+.. opcode:: BINARY_ADD
 
    Implements ``TOS = TOS1 + TOS``.
 
 
-.. opcode:: BINARY_SUBTRACT ()
+.. opcode:: BINARY_SUBTRACT
 
    Implements ``TOS = TOS1 - TOS``.
 
 
-.. opcode:: BINARY_SUBSCR ()
+.. opcode:: BINARY_SUBSCR
 
    Implements ``TOS = TOS1[TOS]``.
 
 
-.. opcode:: BINARY_LSHIFT ()
+.. opcode:: BINARY_LSHIFT
 
    Implements ``TOS = TOS1 << TOS``.
 
 
-.. opcode:: BINARY_RSHIFT ()
+.. opcode:: BINARY_RSHIFT
 
    Implements ``TOS = TOS1 >> TOS``.
 
 
-.. opcode:: BINARY_AND ()
+.. opcode:: BINARY_AND
 
    Implements ``TOS = TOS1 & TOS``.
 
 
-.. opcode:: BINARY_XOR ()
+.. opcode:: BINARY_XOR
 
    Implements ``TOS = TOS1 ^ TOS``.
 
 
-.. opcode:: BINARY_OR ()
+.. opcode:: BINARY_OR
 
    Implements ``TOS = TOS1 | TOS``.
 
+
+**In-place operations**
+
 In-place operations are like binary operations, in that they remove TOS and
 TOS1, and push the result back on the stack, but the operation is done in-place
 when TOS1 supports it, and the resulting TOS may be (but does not have to be)
 the original TOS1.
 
-
-.. opcode:: INPLACE_POWER ()
+.. opcode:: INPLACE_POWER
 
    Implements in-place ``TOS = TOS1 ** TOS``.
 
 
-.. opcode:: INPLACE_MULTIPLY ()
+.. opcode:: INPLACE_MULTIPLY
 
    Implements in-place ``TOS = TOS1 * TOS``.
 
 
-.. opcode:: INPLACE_FLOOR_DIVIDE ()
+.. opcode:: INPLACE_FLOOR_DIVIDE
 
    Implements in-place ``TOS = TOS1 // TOS``.
 
 
-.. opcode:: INPLACE_TRUE_DIVIDE ()
+.. opcode:: INPLACE_TRUE_DIVIDE
 
    Implements in-place ``TOS = TOS1 / TOS``.
 
 
-.. opcode:: INPLACE_MODULO ()
+.. opcode:: INPLACE_MODULO
 
    Implements in-place ``TOS = TOS1 % TOS``.
 
 
-.. opcode:: INPLACE_ADD ()
+.. opcode:: INPLACE_ADD
 
    Implements in-place ``TOS = TOS1 + TOS``.
 
 
-.. opcode:: INPLACE_SUBTRACT ()
+.. opcode:: INPLACE_SUBTRACT
 
    Implements in-place ``TOS = TOS1 - TOS``.
 
 
-.. opcode:: INPLACE_LSHIFT ()
+.. opcode:: INPLACE_LSHIFT
 
    Implements in-place ``TOS = TOS1 << TOS``.
 
 
-.. opcode:: INPLACE_RSHIFT ()
+.. opcode:: INPLACE_RSHIFT
 
    Implements in-place ``TOS = TOS1 >> TOS``.
 
 
-.. opcode:: INPLACE_AND ()
+.. opcode:: INPLACE_AND
 
    Implements in-place ``TOS = TOS1 & TOS``.
 
 
-.. opcode:: INPLACE_XOR ()
+.. opcode:: INPLACE_XOR
 
    Implements in-place ``TOS = TOS1 ^ TOS``.
 
 
-.. opcode:: INPLACE_OR ()
+.. opcode:: INPLACE_OR
 
    Implements in-place ``TOS = TOS1 | TOS``.
 
 
-.. opcode:: STORE_SUBSCR ()
+.. opcode:: STORE_SUBSCR
 
    Implements ``TOS1[TOS] = TOS2``.
 
 
-.. opcode:: DELETE_SUBSCR ()
+.. opcode:: DELETE_SUBSCR
 
    Implements ``del TOS1[TOS]``.
 
-Miscellaneous opcodes.
 
+**Miscellaneous opcodes**
 
-.. opcode:: PRINT_EXPR ()
+.. opcode:: PRINT_EXPR
 
    Implements the expression statement for the interactive mode.  TOS is removed
    from the stack and printed.  In non-interactive mode, an expression statement is
    terminated with ``POP_STACK``.
 
 
-.. opcode:: BREAK_LOOP ()
+.. opcode:: BREAK_LOOP
 
    Terminates a loop due to a :keyword:`break` statement.
 
@@ -377,36 +396,35 @@
    Calls ``dict.setitem(TOS1[-i], TOS, TOS1)``.  Used to implement dict
    comprehensions.
 
-
 For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while the
 added value or key/value pair is popped off, the container object remains on
 the stack so that it is available for further iterations of the loop.
 
 
-.. opcode:: RETURN_VALUE ()
+.. opcode:: RETURN_VALUE
 
    Returns with TOS to the caller of the function.
 
 
-.. opcode:: YIELD_VALUE ()
+.. opcode:: YIELD_VALUE
 
    Pops ``TOS`` and yields it from a :term:`generator`.
 
 
-.. opcode:: IMPORT_STAR ()
+.. opcode:: IMPORT_STAR
 
    Loads all symbols not starting with ``'_'`` directly from the module TOS to the
    local namespace. The module is popped after loading all names. This opcode
    implements ``from module import *``.
 
 
-.. opcode:: POP_BLOCK ()
+.. opcode:: POP_BLOCK
 
    Removes one block from the block stack.  Per frame, there is a  stack of blocks,
    denoting nested loops, try statements, and such.
 
 
-.. opcode:: POP_EXCEPT ()
+.. opcode:: POP_EXCEPT
 
    Removes one block from the block stack. The popped block must be an exception
    handler block, as implicitly created when entering an except handler.
@@ -414,14 +432,14 @@
    last three popped values are used to restore the exception state.
 
 
-.. opcode:: END_FINALLY ()
+.. opcode:: END_FINALLY
 
    Terminates a :keyword:`finally` clause.  The interpreter recalls whether the
    exception has to be re-raised, or whether the function returns, and continues
    with the outer-next block.
 
 
-.. opcode:: LOAD_BUILD_CLASS ()
+.. opcode:: LOAD_BUILD_CLASS
 
    Pushes :func:`builtins.__build_class__` onto the stack.  It is later called
    by ``CALL_FUNCTION`` to construct a class.
@@ -439,7 +457,7 @@
    :opcode:`UNPACK_SEQUENCE`).
 
 
-.. opcode:: WITH_CLEANUP ()
+.. opcode:: WITH_CLEANUP
 
    Cleans up the stack when a :keyword:`with` statement block exits.  TOS is
    the context manager's :meth:`__exit__` bound method. Below TOS are 1--3
@@ -649,7 +667,7 @@
    Pushes a try block from a try-except clause onto the block stack. *delta* points
    to the finally block.
 
-.. opcode:: STORE_MAP ()
+.. opcode:: STORE_MAP
 
    Store a key and value pair in a dictionary.  Pops the key and value while leaving
    the dictionary on the stack.
@@ -765,7 +783,7 @@
    variable-arguments tuple, followed by explicit keyword and positional arguments.
 
 
-.. opcode:: HAVE_ARGUMENT ()
+.. opcode:: HAVE_ARGUMENT
 
    This is not really an opcode.  It identifies the dividing line between opcodes
    which don't take arguments ``< HAVE_ARGUMENT`` and those which do ``>=

Modified: python/branches/py3k-cdecimal/Doc/library/doctest.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/doctest.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/doctest.rst	Sat Jul 17 12:36:09 2010
@@ -282,11 +282,8 @@
 How are Docstring Examples Recognized?
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-In most cases a copy-and-paste of an interactive console session works fine, but
-doctest isn't trying to do an exact emulation of any specific Python shell.  All
-hard tab characters are expanded to spaces, using 8-column tab stops.  If you
-don't believe tabs should mean that, too bad:  don't use hard tabs, or write
-your own :class:`DocTestParser` class.
+In most cases a copy-and-paste of an interactive console session works fine,
+but doctest isn't trying to do an exact emulation of any specific Python shell.
 
 ::
 
@@ -317,6 +314,17 @@
   blank line, put ``<BLANKLINE>`` in your doctest example each place a blank line
   is expected.
 
+* All hard tab characters are expanded to spaces, using 8-column tab stops.
+  Tabs in output generated by the tested code are not modified.  Because any
+  hard tabs in the sample output *are* expanded, this means that if the code
+  output includes hard tabs, the only way the doctest can pass is if the
+  :const:`NORMALIZE_WHITESPACE` option or directive is in effect.
+  Alternatively, the test can be rewritten to capture the output and compare it
+  to an expected value as part of the test.  This handling of tabs in the
+  source was arrived at through trial and error, and has proven to be the least
+  error prone way of handling them.  It is possible to use a different
+  algorithm for handling tabs by writing a custom :class:`DocTestParser` class.
+
 * Output to stdout is captured, but not output to stderr (exception tracebacks
   are captured via a different means).
 
@@ -905,18 +913,16 @@
 As your collection of doctest'ed modules grows, you'll want a way to run all
 their doctests systematically.  :mod:`doctest` provides two functions that can
 be used to create :mod:`unittest` test suites from modules and text files
-containing doctests.  These test suites can then be run using :mod:`unittest`
-test runners::
+containing doctests.  To integrate with :mod:`unittest` test discovery, include
+a :func:`load_tests` function in your test module::
 
    import unittest
    import doctest
-   import my_module_with_doctests, and_another
+   import my_module_with_doctests
 
-   suite = unittest.TestSuite()
-   for mod in my_module_with_doctests, and_another:
-       suite.addTest(doctest.DocTestSuite(mod))
-   runner = unittest.TextTestRunner()
-   runner.run(suite)
+   def load_tests(loader, tests, ignore):
+       tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
+       return test
 
 There are two main functions for creating :class:`unittest.TestSuite` instances
 from text files and modules with doctests:
@@ -1778,4 +1784,3 @@
 .. [#] Examples containing both expected output and an exception are not supported.
    Trying to guess where one ends and the other begins is too error-prone, and that
    also makes for a confusing test.
-

Modified: python/branches/py3k-cdecimal/Doc/library/fnmatch.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/fnmatch.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/fnmatch.rst	Sat Jul 17 12:36:09 2010
@@ -82,6 +82,13 @@
       <_sre.SRE_Match object at 0x...>
 
 
+.. function:: purge()
+
+   Clear the internal pattern cache.
+
+   .. versionadded:: 3.2
+
+
 .. seealso::
 
    Module :mod:`glob`

Modified: python/branches/py3k-cdecimal/Doc/library/functions.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/functions.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/functions.rst	Sat Jul 17 12:36:09 2010
@@ -335,6 +335,9 @@
    returns the current global and local dictionary, respectively, which may be
    useful to pass around for use by :func:`eval` or :func:`exec`.
 
+   See :func:`ast.literal_eval` for a function that can safely evaluate strings
+   with expressions containing only literals.
+
 
 .. function:: exec(object[, globals[, locals]])
 
@@ -676,7 +679,7 @@
    :meth:`__index__` method that returns an integer.
 
 
-.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
+.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
 
    Open *file* and return a corresponding stream.  If the file cannot be opened,
    an :exc:`IOError` is raised.

Modified: python/branches/py3k-cdecimal/Doc/library/http.cookiejar.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/http.cookiejar.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/http.cookiejar.rst	Sat Jul 17 12:36:09 2010
@@ -108,10 +108,6 @@
       :mod:`http.cookiejar` and :mod:`http.cookies` modules do not depend on each
       other.
 
-   http://wwwsearch.sourceforge.net/mechanize/
-      Extensions to this module, including a class for reading Microsoft Internet
-      Explorer cookies on Windows.
-
    http://wp.netscape.com/newsref/std/cookie_spec.html
       The specification of the original Netscape cookie protocol.  Though this is
       still the dominant protocol, the 'Netscape cookie protocol' implemented by all
@@ -292,11 +288,8 @@
 FileCookieJar subclasses and co-operation with web browsers
 -----------------------------------------------------------
 
-The following :class:`CookieJar` subclasses are provided for reading and writing
-.  Further :class:`CookieJar` subclasses, including one that reads Microsoft
-Internet Explorer cookies, are available at
-http://wwwsearch.sourceforge.net/mechanize/.
-
+The following :class:`CookieJar` subclasses are provided for reading and
+writing .
 
 .. class:: MozillaCookieJar(filename, delayload=None, policy=None)
 

Modified: python/branches/py3k-cdecimal/Doc/library/http.server.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/http.server.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/http.server.rst	Sat Jul 17 12:36:09 2010
@@ -281,7 +281,31 @@
       contents of the file are output. If the file's MIME type starts with
       ``text/`` the file is opened in text mode; otherwise binary mode is used.
 
-      For example usage, see the implementation of the :func:`test` function.
+      For example usage, see the implementation of the :func:`test` function
+      invocation in the :mod:`http.server` module.
+
+
+The :class:`SimpleHTTPRequestHandler` class can be used in the following
+manner in order to create a very basic webserver serving files relative to
+the current directory. ::
+
+   import http.server
+   import socketserver
+
+   PORT = 8000
+
+   Handler = http.server.SimpleHTTPRequestHandler
+
+   httpd = socketserver.TCPServer(("", PORT), Handler)
+
+   print("serving at port", PORT)
+   httpd.serve_forever()
+
+:mod:`http.server` can also be invoked directly using the :option:`-m`
+switch of the interpreter a with ``port number`` argument.  Similar to
+the previous example, this serves files relative to the current directory. ::
+
+        python -m http.server 8000
 
 
 .. class:: CGIHTTPRequestHandler(request, client_address, server)

Modified: python/branches/py3k-cdecimal/Doc/library/importlib.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/importlib.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/importlib.rst	Sat Jul 17 12:36:09 2010
@@ -18,12 +18,12 @@
 :func:`__import__` function) in Python source code. This provides an
 implementation of :keyword:`import` which is portable to any Python
 interpreter. This also provides a reference implementation which is easier to
-comprehend than one in a programming language other than Python.
+comprehend than one implemented in a programming language other than Python.
 
-Two, the components to implement :keyword:`import` can be exposed in this
+Two, the components to implement :keyword:`import` are exposed in this
 package, making it easier for users to create their own custom objects (known
 generically as an :term:`importer`) to participate in the import process.
-Details on providing custom importers can be found in :pep:`302`.
+Details on custom importers can be found in :pep:`302`.
 
 .. seealso::
 
@@ -36,8 +36,7 @@
         in :data:`sys.modules`).
 
     The :func:`.__import__` function
-        The built-in function for which the :keyword:`import` statement is
-        syntactic sugar.
+        The :keyword:`import` statement is syntactic sugar for this function.
 
     :pep:`235`
         Import on Case-Insensitive Platforms
@@ -46,7 +45,7 @@
         Defining Python Source Code Encodings
 
     :pep:`302`
-        New Import Hooks.
+        New Import Hooks
 
     :pep:`328`
         Imports: Multi-Line and Absolute/Relative
@@ -57,14 +56,16 @@
     :pep:`3120`
         Using UTF-8 as the Default Source Encoding
 
+    :pep:`3147`
+        PYC Repository Directories
+
 
 Functions
 ---------
 
 .. function:: __import__(name, globals={}, locals={}, fromlist=list(), level=0)
 
-    An implementation of the built-in :func:`__import__` function. See the
-    built-in function's documentation for usage instructions.
+    An implementation of the built-in :func:`__import__` function.
 
 .. function:: import_module(name, package=None)
 
@@ -210,22 +211,112 @@
 
     .. method:: get_filename(fullname)
 
-        An abstract method that is to return the value for :attr:`__file__` for
+        An abstract method that is to return the value of :attr:`__file__` for
         the specified module. If no path is available, :exc:`ImportError` is
         raised.
 
+        If source code is available, then the method should return the path to
+        the source file, regardless of whether a bytecode was used to load the
+        module.
+
+
+.. class:: SourceLoader
+
+    An abstract base class for implementing source (and optionally bytecode)
+    file loading. The class inherits from both :class:`ResourceLoader` and
+    :class:`ExecutionLoader`, requiring the implementation of:
+
+    * :meth:`ResourceLoader.get_data`
+    * :meth:`ExecutionLoader.get_filename`
+          Implement to only return the path to the source file; sourceless
+          loading is not supported.
+
+    The abstract methods defined by this class are to add optional bytecode
+    file support. Not implementing these optional methods causes the loader to
+    only work with source code. Implementing the methods allows the loader to
+    work with source *and* bytecode files; it does not allow for *sourceless*
+    loading where only bytecode is provided.  Bytecode files are an
+    optimization to speed up loading by removing the parsing step of Python's
+    compiler, and so no bytecode-specific API is exposed.
+
+    .. method:: path_mtime(self, path)
+
+        Optional abstract method which returns the modification time for the
+        specified path.
+
+    .. method:: set_data(self, path, data)
+
+        Optional abstract method which writes the specified bytes to a file
+        path. Any intermediate directories which do not exist are to be created
+        automatically.
+
+        When writing to the path fails because the path is read-only
+        (:attr:`errno.EACCES`), do not propagate the exception.
+
+    .. method:: get_code(self, fullname)
+
+        Concrete implementation of :meth:`InspectLoader.get_code`.
+
+    .. method:: load_module(self, fullname)
+
+        Concrete implementation of :meth:`Loader.load_module`.
+
+    .. method:: get_source(self, fullname)
+
+        Concrete implementation of :meth:`InspectLoader.get_source`.
+
+    .. method:: is_package(self, fullname)
+
+        Concrete implementation of :meth:`InspectLoader.is_package`. A module
+        is determined to be a package if its file path is a file named
+        ``__init__`` when the file extension is removed.
+
 
 .. class:: PyLoader
 
     An abstract base class inheriting from
-    :class:`importlib.abc.ExecutionLoader` and
-    :class:`importlib.abc.ResourceLoader` designed to ease the loading of
+    :class:`ExecutionLoader` and
+    :class:`ResourceLoader` designed to ease the loading of
     Python source modules (bytecode is not handled; see
-    :class:`importlib.abc.PyPycLoader` for a source/bytecode ABC). A subclass
+    :class:`SourceLoader` for a source/bytecode ABC). A subclass
     implementing this ABC will only need to worry about exposing how the source
     code is stored; all other details for loading Python source code will be
     handled by the concrete implementations of key methods.
 
+    .. deprecated:: 3.2
+        This class has been deprecated in favor of :class:`SourceLoader` and is
+        slated for removal in Python 3.4. See below for how to create a
+        subclass that is compatbile with Python 3.1 onwards.
+
+    If compatibility with Python 3.1 is required, then use the following idiom
+    to implement a subclass that will work with Python 3.1 onwards (make sure
+    to implement :meth:`ExecutionLoader.get_filename`)::
+
+        try:
+            from importlib.abc import SourceLoader
+        except ImportError:
+            from importlib.abc import PyLoader as SourceLoader
+
+
+        class CustomLoader(SourceLoader):
+            def get_filename(self, fullname):
+                """Return the path to the source file."""
+                # Implement ...
+
+            def source_path(self, fullname):
+                """Implement source_path in terms of get_filename."""
+                try:
+                    return self.get_filename(fullname)
+                except ImportError:
+                    return None
+
+            def is_package(self, fullname):
+                """Implement is_package by looking for an __init__ file
+                name as returned by get_filename."""
+                filename = os.path.basename(self.get_filename(fullname))
+                return os.path.splitext(filename)[0] == '__init__'
+
+
     .. method:: source_path(fullname)
 
         An abstract method that returns the path to the source code for a
@@ -267,10 +358,18 @@
 
 .. class:: PyPycLoader
 
-    An abstract base class inheriting from :class:`importlib.abc.PyLoader`.
+    An abstract base class inheriting from :class:`PyLoader`.
     This ABC is meant to help in creating loaders that support both Python
     source and bytecode.
 
+    .. deprecated:: 3.2
+        This class has been deprecated in favor of :class:`SourceLoader` and to
+        properly support :pep:`3147`. If compatibility is required with
+        Python 3.1, implement both :class:`SourceLoader` and :class:`PyLoader`;
+        instructions on how to do so are included in the documentation for
+        :class:`PyLoader`. Do note that this solution will not support
+        sourceless/bytecode-only loading; only source *and* bytecode loading.
+
     .. method:: source_mtime(fullname)
 
         An abstract method which returns the modification time for the source
@@ -289,8 +388,8 @@
     .. method:: get_filename(fullname)
 
         A concrete implementation of
-        :meth:`importlib.abc.ExecutionLoader.get_filename` that relies on
-        :meth:`importlib.abc.PyLoader.source_path` and :meth:`bytecode_path`.
+        :meth:`ExecutionLoader.get_filename` that relies on
+        :meth:`PyLoader.source_path` and :meth:`bytecode_path`.
         If :meth:`source_path` returns a path, then that value is returned.
         Else if :meth:`bytecode_path` returns a path, that path will be
         returned. If a path is not available from both methods,
@@ -417,100 +516,3 @@
     attribute to be used at the global level of the module during
     initialization.
 
-
-Example
--------
-
-Below is an example meta path importer that uses a dict for back-end storage
-for source code. While not an optimal solution -- manipulations of
-:attr:`__path__` on packages does not influence import -- it does illustrate
-what little is required to implement an importer.
-
-.. testcode::
-
-    """An importer where source is stored in a dict."""
-    from importlib import abc
-
-
-    class DictImporter(abc.Finder, abc.PyLoader):
-
-        """A meta path importer that stores source code in a dict.
-
-        The keys are the module names -- packages must end in ``.__init__``.
-        The values must be something that can be passed to 'bytes'.
-
-        """
-
-        def __init__(self, memory):
-            """Store the dict."""
-            self.memory = memory
-
-        def contains(self, name):
-            """See if a module or package is in the dict."""
-            if name in self.memory:
-                return name
-            package_name = '{}.__init__'.format(name)
-            if  package_name in self.memory:
-                return package_name
-            return False
-
-        __contains__ = contains  # Convenience.
-
-        def find_module(self, fullname, path=None):
-            """Find the module in the dict."""
-            if fullname in self:
-                return self
-            return None
-
-        def source_path(self, fullname):
-            """Return the module name if the module is in the dict."""
-            if not fullname in self:
-                raise ImportError
-            return fullname
-
-        def get_data(self, path):
-            """Return the bytes for the source.
-
-            The value found in the dict is passed through 'bytes' before being
-            returned.
-
-            """
-            name = self.contains(path)
-            if not name:
-                raise IOError
-            return bytes(self.memory[name])
-
-        def is_package(self, fullname):
-            """Tell if module is a package based on whether the dict contains the
-            name with ``.__init__`` appended to it."""
-            if fullname not in self:
-                raise ImportError
-            if fullname in self.memory:
-                return False
-            # If name is in this importer but not as it is then it must end in
-            # ``__init__``.
-            else:
-                return True
-
-.. testcode::
-    :hide:
-
-    import importlib
-    import sys
-
-
-    # Build the dict; keys of name, value of __package__.
-    names = {'_top_level': '', '_pkg.__init__': '_pkg', '_pkg.mod': '_pkg'}
-    source = {name: "name = {!r}".format(name).encode() for name in names}
-
-    # Register the meta path importer.
-    importer = DictImporter(source)
-    sys.meta_path.append(importer)
-
-    # Sanity check.
-    for name in names:
-        module = importlib.import_module(name)
-        assert module.__name__ == name
-        assert getattr(module, 'name') == name
-        assert module.__loader__ is importer
-        assert module.__package__ == names[name]

Modified: python/branches/py3k-cdecimal/Doc/library/logging.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/logging.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/logging.rst	Sat Jul 17 12:36:09 2010
@@ -53,10 +53,12 @@
 
 Most applications are probably going to want to log to a file, so let's start
 with that case. Using the :func:`basicConfig` function, we can set up the
-default handler so that debug messages are written to a file::
+default handler so that debug messages are written to a file (in the example,
+we assume that you have the appropriate permissions to create a file called
+*example.log* in the current directory)::
 
    import logging
-   LOG_FILENAME = '/tmp/logging_example.out'
+   LOG_FILENAME = 'example.log'
    logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
 
    logging.debug('This message should go to the log file')
@@ -75,7 +77,7 @@
    import logging
    import logging.handlers
 
-   LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
+   LOG_FILENAME = 'logging_rotatingfile_example.out'
 
    # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('MyLogger')
@@ -100,14 +102,14 @@
 The result should be 6 separate files, each with part of the log history for the
 application::
 
-   /tmp/logging_rotatingfile_example.out
-   /tmp/logging_rotatingfile_example.out.1
-   /tmp/logging_rotatingfile_example.out.2
-   /tmp/logging_rotatingfile_example.out.3
-   /tmp/logging_rotatingfile_example.out.4
-   /tmp/logging_rotatingfile_example.out.5
+   logging_rotatingfile_example.out
+   logging_rotatingfile_example.out.1
+   logging_rotatingfile_example.out.2
+   logging_rotatingfile_example.out.3
+   logging_rotatingfile_example.out.4
+   logging_rotatingfile_example.out.5
 
-The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
+The most current file is always :file:`logging_rotatingfile_example.out`,
 and each time it reaches the size limit it is renamed with the suffix
 ``.1``. Each of the existing backup files is renamed to increment the suffix
 (``.1`` becomes ``.2``, etc.)  and the ``.6`` file is erased.
@@ -244,7 +246,7 @@
   methods listed above, but this is how to log at custom log levels.
 
 :func:`getLogger` returns a reference to a logger instance with the specified
-if it is provided, or ``root`` if not.  The names are period-separated
+name if it is provided, or ``root`` if not.  The names are period-separated
 hierarchical structures.  Multiple calls to :func:`getLogger` with the same name
 will return a reference to the same logger object.  Loggers that are further
 down in the hierarchical list are children of loggers higher up in the list.
@@ -321,24 +323,34 @@
 Configuring Logging
 ^^^^^^^^^^^^^^^^^^^
 
-Programmers can configure logging either by creating loggers, handlers, and
-formatters explicitly in a main module with the configuration methods listed
-above (using Python code), or by creating a logging config file.  The following
-code is an example of configuring a very simple logger, a console handler, and a
-simple formatter in a Python module::
+Programmers can configure logging in three ways:
+
+1. Creating loggers, handlers, and formatters explicitly using Python
+   code that calls the configuration methods listed above.
+2. Creating a logging config file and reading it using the :func:`fileConfig`
+   function.
+3. Creating a dictionary of configuration information and passing it
+   to the :func:`dictConfig` function.
+
+The following example configures a very simple logger, a console
+handler, and a simple formatter using Python code::
 
     import logging
 
     # create logger
     logger = logging.getLogger("simple_example")
     logger.setLevel(logging.DEBUG)
+
     # create console handler and set level to debug
     ch = logging.StreamHandler()
     ch.setLevel(logging.DEBUG)
+
     # create formatter
     formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
+
     # add formatter to ch
     ch.setFormatter(formatter)
+
     # add ch to logger
     logger.addHandler(ch)
 
@@ -428,6 +440,45 @@
 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
+recommended configuration method for new applications and deployments. Because
+a Python dictionary is used to hold configuration information, and since you
+can populate that dictionary using different means, you have more options for
+configuration. For example, you can use a configuration file in JSON format,
+or, if you have access to YAML processing functionality, a file in YAML
+format, to populate the configuration dictionary. Or, of course, you can
+construct the dictionary in Python code, receive it in pickled form over a
+socket, or use whatever approach makes sense for your application.
+
+Here's an example of the same configuration as above, in YAML format for
+the new dictionary-based approach::
+
+    version: 1
+    formatters:
+      simple:
+        format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
+    handlers:
+      console:
+        class: logging.StreamHandler
+        level: DEBUG
+        formatter: simple
+        stream: ext://sys.stdout
+    loggers:
+      simpleExample:
+        level: DEBUG
+        handlers: [console]
+        propagate: no
+    root:
+        level: DEBUG
+        handlers: [console]
+
+For more information about logging using a dictionary, see
+:ref:`logging-config-api`.
+
 .. _library-config:
 
 Configuring Logging for a Library
@@ -1065,14 +1116,14 @@
 
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s %(message)s',
-                       filename='/tmp/myapp.log',
+                       filename='myapp.log',
                        filemode='w')
    logging.debug('A debug message')
    logging.info('Some information')
    logging.warning('A shot across the bows')
 
 The :meth:`basicConfig` method is used to change the configuration defaults,
-which results in output (written to ``/tmp/myapp.log``) which should look
+which results in output (written to ``myapp.log``) which should look
 something like the following::
 
    2004-07-02 13:00:08,743 DEBUG A debug message
@@ -1364,6 +1415,8 @@
    2008-01-18 14:49:54,033 d.e.f WARNING  IP: 127.0.0.1       User: jim      A message at WARNING level with 2 parameters
 
 
+.. _multiple-processes:
+
 Logging to a single file from multiple processes
 ------------------------------------------------
 
@@ -1519,6 +1572,11 @@
       69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
       69 myapp.area2     ERROR    The five boxing wizards jump quickly.
 
+Note that there are some security issues with pickle in some scenarios. If
+these affect you, you can use an alternative serialization scheme by overriding
+the :meth:`makePickle` method and implementing your alternative there, as
+well as adapting the above script to use your alternative serialization.
+
 Using arbitrary objects as messages
 -----------------------------------
 
@@ -1674,6 +1732,8 @@
    :exc:`NotImplementedError`.
 
 
+.. _stream-handler:
+
 StreamHandler
 ^^^^^^^^^^^^^
 
@@ -1707,6 +1767,8 @@
       no output, so an explicit :meth:`flush` call may be needed at times.
 
 
+.. _file-handler:
+
 FileHandler
 ^^^^^^^^^^^
 
@@ -1715,7 +1777,7 @@
 :class:`StreamHandler`.
 
 
-.. class:: FileHandler(filename, mode='a', encoding=None, delay=0)
+.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
 
    Returns a new instance of the :class:`FileHandler` class. The specified file is
    opened and used as the stream for logging. If *mode* is not specified,
@@ -1733,6 +1795,7 @@
 
       Outputs the record to the file.
 
+.. _null-handler:
 
 NullHandler
 ^^^^^^^^^^^
@@ -1756,6 +1819,8 @@
 See :ref:`library-config` for more information on how to use
 :class:`NullHandler`.
 
+.. _watched-file-handler:
+
 WatchedFileHandler
 ^^^^^^^^^^^^^^^^^^
 
@@ -1794,6 +1859,7 @@
       changed.  If it has, the existing stream is flushed and closed and the
       file opened again, before outputting the record to the file.
 
+.. _rotating-file-handler:
 
 RotatingFileHandler
 ^^^^^^^^^^^^^^^^^^^
@@ -1834,6 +1900,7 @@
       Outputs the record to the file, catering for rollover as described
       previously.
 
+.. _timed-rotating-file-handler:
 
 TimedRotatingFileHandler
 ^^^^^^^^^^^^^^^^^^^^^^^^
@@ -1843,7 +1910,7 @@
 timed intervals.
 
 
-.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=False)
+.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
 
    Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
    specified file is opened and used as the stream for logging. On rotating it also
@@ -1886,6 +1953,9 @@
    one is deleted. The deletion logic uses the interval to determine which
    files to delete, so changing the interval may leave old files lying around.
 
+   If *delay* is true, then file opening is deferred until the first call to
+   :meth:`emit`.
+
 
    .. method:: doRollover()
 
@@ -1897,6 +1967,8 @@
       Outputs the record to the file, catering for rollover as described above.
 
 
+.. _socket-handler:
+
 SocketHandler
 ^^^^^^^^^^^^^
 
@@ -1943,6 +2015,11 @@
       Pickles the record's attribute dictionary in binary format with a length
       prefix, and returns it ready for transmission across the socket.
 
+      Note that pickles aren't completely secure. If you are concerned about
+      security, you may want to override this method to implement a more secure
+      mechanism. For example, you can sign pickles using HMAC and then verify
+      them on the receiving end, or alternatively you can disable unpickling of
+      global objects on the receiving end.
 
    .. method:: send(packet)
 
@@ -1950,6 +2027,8 @@
       partial sends which can happen when the network is busy.
 
 
+.. _datagram-handler:
+
 DatagramHandler
 ^^^^^^^^^^^^^^^
 
@@ -1983,6 +2062,8 @@
       Send a pickled string to a socket.
 
 
+.. _syslog-handler:
+
 SysLogHandler
 ^^^^^^^^^^^^^
 
@@ -2172,6 +2253,7 @@
       lookup to get the message ID. This version returns 1, which is the base
       message ID in :file:`win32service.pyd`.
 
+.. _smtp-handler:
 
 SMTPHandler
 ^^^^^^^^^^^
@@ -2200,6 +2282,7 @@
       If you want to specify a subject line which is record-dependent, override
       this method.
 
+.. _memory-handler:
 
 MemoryHandler
 ^^^^^^^^^^^^^
@@ -2270,6 +2353,8 @@
       Checks for buffer full or a record at the *flushLevel* or higher.
 
 
+.. _http-handler:
+
 HTTPHandler
 ^^^^^^^^^^^
 
@@ -2412,6 +2497,7 @@
       just uses :func:`traceback.print_exception`. The resulting string is
       returned.
 
+.. _filter:
 
 Filter Objects
 --------------
@@ -2437,6 +2523,7 @@
       yes. If deemed appropriate, the record may be modified in-place by this
       method.
 
+.. _log-record:
 
 LogRecord Objects
 -----------------
@@ -2468,6 +2555,7 @@
       Returns the message for this :class:`LogRecord` instance after merging any
       user-supplied arguments with the message.
 
+.. _logger-adapter:
 
 LoggerAdapter Objects
 ---------------------
@@ -2553,19 +2641,57 @@
 in :mod:`logging` itself) and defining handlers which are declared either in
 :mod:`logging` or :mod:`logging.handlers`.
 
+.. function:: dictConfig(config)
+
+    Takes the logging configuration from a dictionary.  The contents of
+    this dictionary are described in :ref:`logging-config-dictschema`
+    below.
+
+    If an error is encountered during configuration, this function will
+    raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
+    or :exc:`ImportError` with a suitably descriptive message.  The
+    following is a (possibly incomplete) list of conditions which will
+    raise an error:
+
+    * A ``level`` which is not a string or which is a string not
+      corresponding to an actual logging level.
+    * A ``propagate`` value which is not a boolean.
+    * An id which does not have a corresponding destination.
+    * A non-existent handler id found during an incremental call.
+    * An invalid logger name.
+    * Inability to resolve to an internal or external object.
+
+    Parsing is performed by the :class:`DictConfigurator` class, whose
+    constructor is passed the dictionary used for configuration, and
+    has a :meth:`configure` method.  The :mod:`logging.config` module
+    has a callable attribute :attr:`dictConfigClass`
+    which is initially set to :class:`DictConfigurator`.
+    You can replace the value of :attr:`dictConfigClass` with a
+    suitable implementation of your own.
+
+    :func:`dictConfig` calls :attr:`dictConfigClass` passing
+    the specified dictionary, and then calls the :meth:`configure` method on
+    the returned object to put the configuration into effect::
+
+          def dictConfig(config):
+              dictConfigClass(config).configure()
+
+    For example, a subclass of :class:`DictConfigurator` could call
+    ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
+    set up custom prefixes which would be usable in the subsequent
+    :meth:`configure` call. :attr:`dictConfigClass` would be bound to
+    this new subclass, and then :func:`dictConfig` could be called exactly as
+    in the default, uncustomized state.
 
-.. function:: fileConfig(fname, defaults=None, disable_existing_loggers=True)
+.. function:: fileConfig(fname[, defaults])
 
    Reads the logging configuration from a :mod:`configparser`\-format file named
    *fname*. This function can be called several times from an application,
-   allowing an end user the ability to select from various pre-canned
+   allowing an end user to select from various pre-canned
    configurations (if the developer provides a mechanism to present the choices
    and load the chosen configuration). Defaults to be passed to the ConfigParser
    can be specified in the *defaults* argument.
 
-   If *disable_existing_loggers* is true, any existing loggers that are not
-   children of named loggers will be disabled.
-
 
 .. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
 
@@ -2589,6 +2715,402 @@
    :func:`listen`.
 
 
+.. _logging-config-dictschema:
+
+Configuration dictionary schema
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Describing a logging configuration requires listing the various
+objects to create and the connections between them; for example, you
+may create a handler named "console" and then say that the logger
+named "startup" will send its messages to the "console" handler.
+These objects aren't limited to those provided by the :mod:`logging`
+module because you might write your own formatter or handler class.
+The parameters to these classes may also need to include external
+objects such as ``sys.stderr``.  The syntax for describing these
+objects and connections is defined in :ref:`logging-config-dict-connections`
+below.
+
+Dictionary Schema Details
+"""""""""""""""""""""""""
+
+The dictionary passed to :func:`dictConfig` must contain the following
+keys:
+
+* `version` - to be set to an integer value representing the schema
+  version.  The only valid value at present is 1, but having this key
+  allows the schema to evolve while still preserving backwards
+  compatibility.
+
+All other keys are optional, but if present they will be interpreted
+as described below.  In all cases below where a 'configuring dict' is
+mentioned, it will be checked for the special ``'()'`` key to see if a
+custom instantiation is required.  If so, the mechanism described in
+:ref:`logging-config-dict-userdef` below is used to create an instance;
+otherwise, the context is used to determine what to instantiate.
+
+* `formatters` - the corresponding value will be a dict in which each
+  key is a formatter id and each value is a dict describing how to
+  configure the corresponding Formatter instance.
+
+  The configuring dict is searched for keys ``format`` and ``datefmt``
+  (with defaults of ``None``) and these are used to construct a
+  :class:`logging.Formatter` instance.
+
+* `filters` - the corresponding value will be a dict in which each key
+  is a filter id and each value is a dict describing how to configure
+  the corresponding Filter instance.
+
+  The configuring dict is searched for the key ``name`` (defaulting to the
+  empty string) and this is used to construct a :class:`logging.Filter`
+  instance.
+
+* `handlers` - the corresponding value will be a dict in which each
+  key is a handler id and each value is a dict describing how to
+  configure the corresponding Handler instance.
+
+  The configuring dict is searched for the following keys:
+
+  * ``class`` (mandatory).  This is the fully qualified name of the
+    handler class.
+
+  * ``level`` (optional).  The level of the handler.
+
+  * ``formatter`` (optional).  The id of the formatter for this
+    handler.
+
+  * ``filters`` (optional).  A list of ids of the filters for this
+    handler.
+
+  All *other* keys are passed through as keyword arguments to the
+  handler's constructor.  For example, given the snippet::
+
+      handlers:
+        console:
+          class : logging.StreamHandler
+          formatter: brief
+          level   : INFO
+          filters: [allow_foo]
+          stream  : ext://sys.stdout
+        file:
+          class : logging.handlers.RotatingFileHandler
+          formatter: precise
+          filename: logconfig.log
+          maxBytes: 1024
+          backupCount: 3
+
+  the handler with id ``console`` is instantiated as a
+  :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
+  stream.  The handler with id ``file`` is instantiated as a
+  :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
+  ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
+
+* `loggers` - the corresponding value will be a dict in which each key
+  is a logger name and each value is a dict describing how to
+  configure the corresponding Logger instance.
+
+  The configuring dict is searched for the following keys:
+
+  * ``level`` (optional).  The level of the logger.
+
+  * ``propagate`` (optional).  The propagation setting of the logger.
+
+  * ``filters`` (optional).  A list of ids of the filters for this
+    logger.
+
+  * ``handlers`` (optional).  A list of ids of the handlers for this
+    logger.
+
+  The specified loggers will be configured according to the level,
+  propagation, filters and handlers specified.
+
+* `root` - this will be the configuration for the root logger.
+  Processing of the configuration will be as for any logger, except
+  that the ``propagate`` setting will not be applicable.
+
+* `incremental` - whether the configuration is to be interpreted as
+  incremental to the existing configuration.  This value defaults to
+  ``False``, which means that the specified configuration replaces the
+  existing configuration with the same semantics as used by the
+  existing :func:`fileConfig` API.
+
+  If the specified value is ``True``, the configuration is processed
+  as described in the section on :ref:`logging-config-dict-incremental`.
+
+* `disable_existing_loggers` - whether any existing loggers are to be
+  disabled. This setting mirrors the parameter of the same name in
+  :func:`fileConfig`. If absent, this parameter defaults to ``True``.
+  This value is ignored if `incremental` is ``True``.
+
+.. _logging-config-dict-incremental:
+
+Incremental Configuration
+"""""""""""""""""""""""""
+
+It is difficult to provide complete flexibility for incremental
+configuration.  For example, because objects such as filters
+and formatters are anonymous, once a configuration is set up, it is
+not possible to refer to such anonymous objects when augmenting a
+configuration.
+
+Furthermore, there is not a compelling case for arbitrarily altering
+the object graph of loggers, handlers, filters, formatters at
+run-time, once a configuration is set up; the verbosity of loggers and
+handlers can be controlled just by setting levels (and, in the case of
+loggers, propagation flags).  Changing the object graph arbitrarily in
+a safe way is problematic in a multi-threaded environment; while not
+impossible, the benefits are not worth the complexity it adds to the
+implementation.
+
+Thus, when the ``incremental`` key of a configuration dict is present
+and is ``True``, the system will completely ignore any ``formatters`` and
+``filters`` entries, and process only the ``level``
+settings in the ``handlers`` entries, and the ``level`` and
+``propagate`` settings in the ``loggers`` and ``root`` entries.
+
+Using a value in the configuration dict lets configurations to be sent
+over the wire as pickled dicts to a socket listener. Thus, the logging
+verbosity of a long-running application can be altered over time with
+no need to stop and restart the application.
+
+.. _logging-config-dict-connections:
+
+Object connections
+""""""""""""""""""
+
+The schema describes a set of logging objects - loggers,
+handlers, formatters, filters - which are connected to each other in
+an object graph.  Thus, the schema needs to represent connections
+between the objects.  For example, say that, once configured, a
+particular logger has attached to it a particular handler.  For the
+purposes of this discussion, we can say that the logger represents the
+source, and the handler the destination, of a connection between the
+two.  Of course in the configured objects this is represented by the
+logger holding a reference to the handler.  In the configuration dict,
+this is done by giving each destination object an id which identifies
+it unambiguously, and then using the id in the source object's
+configuration to indicate that a connection exists between the source
+and the destination object with that id.
+
+So, for example, consider the following YAML snippet::
+
+    formatters:
+      brief:
+        # configuration for formatter with id 'brief' goes here
+      precise:
+        # configuration for formatter with id 'precise' goes here
+    handlers:
+      h1: #This is an id
+       # configuration of handler with id 'h1' goes here
+       formatter: brief
+      h2: #This is another id
+       # configuration of handler with id 'h2' goes here
+       formatter: precise
+    loggers:
+      foo.bar.baz:
+        # other configuration for logger 'foo.bar.baz'
+        handlers: [h1, h2]
+
+(Note: YAML used here because it's a little more readable than the
+equivalent Python source form for the dictionary.)
+
+The ids for loggers are the logger names which would be used
+programmatically to obtain a reference to those loggers, e.g.
+``foo.bar.baz``.  The ids for Formatters and Filters can be any string
+value (such as ``brief``, ``precise`` above) and they are transient,
+in that they are only meaningful for processing the configuration
+dictionary and used to determine connections between objects, and are
+not persisted anywhere when the configuration call is complete.
+
+The above snippet indicates that logger named ``foo.bar.baz`` should
+have two handlers attached to it, which are described by the handler
+ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
+``brief``, and the formatter for ``h2`` is that described by id
+``precise``.
+
+
+.. _logging-config-dict-userdef:
+
+User-defined objects
+""""""""""""""""""""
+
+The schema supports user-defined objects for handlers, filters and
+formatters.  (Loggers do not need to have different types for
+different instances, so there is no support in this configuration
+schema for user-defined logger classes.)
+
+Objects to be configured are described by dictionaries
+which detail their configuration.  In some places, the logging system
+will be able to infer from the context how an object is to be
+instantiated, but when a user-defined object is to be instantiated,
+the system will not know how to do this.  In order to provide complete
+flexibility for user-defined object instantiation, the user needs
+to provide a 'factory' - a callable which is called with a
+configuration dictionary and which returns the instantiated object.
+This is signalled by an absolute import path to the factory being
+made available under the special key ``'()'``.  Here's a concrete
+example::
+
+    formatters:
+      brief:
+        format: '%(message)s'
+      default:
+        format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
+        datefmt: '%Y-%m-%d %H:%M:%S'
+      custom:
+          (): my.package.customFormatterFactory
+          bar: baz
+          spam: 99.9
+          answer: 42
+
+The above YAML snippet defines three formatters.  The first, with id
+``brief``, is a standard :class:`logging.Formatter` instance with the
+specified format string.  The second, with id ``default``, has a
+longer format and also defines the time format explicitly, and will
+result in a :class:`logging.Formatter` initialized with those two format
+strings.  Shown in Python source form, the ``brief`` and ``default``
+formatters have configuration sub-dictionaries::
+
+    {
+      'format' : '%(message)s'
+    }
+
+and::
+
+    {
+      'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
+      'datefmt' : '%Y-%m-%d %H:%M:%S'
+    }
+
+respectively, and as these dictionaries do not contain the special key
+``'()'``, the instantiation is inferred from the context: as a result,
+standard :class:`logging.Formatter` instances are created.  The
+configuration sub-dictionary for the third formatter, with id
+``custom``, is::
+
+  {
+    '()' : 'my.package.customFormatterFactory',
+    'bar' : 'baz',
+    'spam' : 99.9,
+    'answer' : 42
+  }
+
+and this contains the special key ``'()'``, which means that
+user-defined instantiation is wanted.  In this case, the specified
+factory callable will be used. If it is an actual callable it will be
+used directly - otherwise, if you specify a string (as in the example)
+the actual callable will be located using normal import mechanisms.
+The callable will be called with the **remaining** items in the
+configuration sub-dictionary as keyword arguments.  In the above
+example, the formatter with id ``custom`` will be assumed to be
+returned by the call::
+
+    my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
+
+The key ``'()'`` has been used as the special key because it is not a
+valid keyword parameter name, and so will not clash with the names of
+the keyword arguments used in the call.  The ``'()'`` also serves as a
+mnemonic that the corresponding value is a callable.
+
+
+.. _logging-config-dict-externalobj:
+
+Access to external objects
+""""""""""""""""""""""""""
+
+There are times where a configuration needs to refer to objects
+external to the configuration, for example ``sys.stderr``.  If the
+configuration dict is constructed using Python code, this is
+straightforward, but a problem arises when the configuration is
+provided via a text file (e.g. JSON, YAML).  In a text file, there is
+no standard way to distinguish ``sys.stderr`` from the literal string
+``'sys.stderr'``.  To facilitate this distinction, the configuration
+system looks for certain special prefixes in string values and
+treat them specially.  For example, if the literal string
+``'ext://sys.stderr'`` is provided as a value in the configuration,
+then the ``ext://`` will be stripped off and the remainder of the
+value processed using normal import mechanisms.
+
+The handling of such prefixes is done in a way analogous to protocol
+handling: there is a generic mechanism to look for prefixes which
+match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
+whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
+in a prefix-dependent manner and the result of the processing replaces
+the string value.  If the prefix is not recognised, then the string
+value will be left as-is.
+
+
+.. _logging-config-dict-internalobj:
+
+Access to internal objects
+""""""""""""""""""""""""""
+
+As well as external objects, there is sometimes also a need to refer
+to objects in the configuration.  This will be done implicitly by the
+configuration system for things that it knows about.  For example, the
+string value ``'DEBUG'`` for a ``level`` in a logger or handler will
+automatically be converted to the value ``logging.DEBUG``, and the
+``handlers``, ``filters`` and ``formatter`` entries will take an
+object id and resolve to the appropriate destination object.
+
+However, a more generic mechanism is needed for user-defined
+objects which are not known to the :mod:`logging` module.  For
+example, consider :class:`logging.handlers.MemoryHandler`, which takes
+a ``target`` argument which is another handler to delegate to. Since
+the system already knows about this class, then in the configuration,
+the given ``target`` just needs to be the object id of the relevant
+target handler, and the system will resolve to the handler from the
+id.  If, however, a user defines a ``my.package.MyHandler`` which has
+an ``alternate`` handler, the configuration system would not know that
+the ``alternate`` referred to a handler.  To cater for this, a generic
+resolution system allows the user to specify::
+
+    handlers:
+      file:
+        # configuration of file handler goes here
+
+      custom:
+        (): my.package.MyHandler
+        alternate: cfg://handlers.file
+
+The literal string ``'cfg://handlers.file'`` will be resolved in an
+analogous way to strings with the ``ext://`` prefix, but looking
+in the configuration itself rather than the import namespace.  The
+mechanism allows access by dot or by index, in a similar way to
+that provided by ``str.format``.  Thus, given the following snippet::
+
+    handlers:
+      email:
+        class: logging.handlers.SMTPHandler
+        mailhost: localhost
+        fromaddr: my_app at domain.tld
+        toaddrs:
+          - support_team at domain.tld
+          - dev_team at domain.tld
+        subject: Houston, we have a problem.
+
+in the configuration, the string ``'cfg://handlers'`` would resolve to
+the dict with key ``handlers``, the string ``'cfg://handlers.email``
+would resolve to the dict with key ``email`` in the ``handlers`` dict,
+and so on.  The string ``'cfg://handlers.email.toaddrs[1]`` would
+resolve to ``'dev_team.domain.tld'`` and the string
+``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
+``'support_team at domain.tld'``. The ``subject`` value could be accessed
+using either ``'cfg://handlers.email.subject'`` or, equivalently,
+``'cfg://handlers.email[subject]'``.  The latter form only needs to be
+used if the key contains spaces or non-alphanumeric characters.  If an
+index value consists only of decimal digits, access will be attempted
+using the corresponding integer value, falling back to the string
+value if needed.
+
+Given a string ``cfg://handlers.myhandler.mykey.123``, this will
+resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
+If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
+the system will attempt to retrieve the value from
+``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
+to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
+fails.
+
 .. _logging-config-fileformat:
 
 Configuration file format

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

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

Modified: python/branches/py3k-cdecimal/Doc/library/os.path.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/os.path.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/os.path.rst	Sat Jul 17 12:36:09 2010
@@ -201,6 +201,7 @@
    Normalize the case of a pathname.  On Unix and Mac OS X, this returns the
    path unchanged; on case-insensitive filesystems, it converts the path to
    lowercase.  On Windows, it also converts forward slashes to backward slashes.
+   Raise a TypeError if the type of *path* is not ``str`` or ``bytes``.
 
 
 .. function:: normpath(path)
@@ -230,11 +231,18 @@
 
 .. function:: samefile(path1, path2)
 
-   Return ``True`` if both pathname arguments refer to the same file or directory
-   (as indicated by device number and i-node number). Raise an exception if a
-   :func:`os.stat` call on either pathname fails.
+   Return ``True`` if both pathname arguments refer to the same file or directory.
+   On Unix, this is determined by the device number and i-node number and raises an
+   exception if a :func:`os.stat` call on either pathname fails.
+
+   On Windows, two files are the same if they resolve to the same final path
+   name using the Windows API call GetFinalPathNameByHandle. This function
+   raises an exception if handles cannot be obtained to either file.
 
-   Availability: Unix.
+   Availability: Windows, Unix.
+
+   .. versionchanged:: 3.2
+      Added Windows support.
 
 
 .. function:: sameopenfile(fp1, fp2)

Modified: python/branches/py3k-cdecimal/Doc/library/os.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/os.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/os.rst	Sat Jul 17 12:36:09 2010
@@ -723,7 +723,7 @@
 
       This function is intended for low-level I/O.  For normal usage, use the
       built-in function :func:`open`, which returns a "file object" with
-      :meth:`~file.read` and :meth:`~file.wprite` methods (and many more).  To
+      :meth:`~file.read` and :meth:`~file.write` methods (and many more).  To
       wrap a file descriptor in a "file object", use :func:`fdopen`.
 
 
@@ -1064,8 +1064,10 @@
 .. function:: lstat(path)
 
    Like :func:`stat`, but do not follow symbolic links.  This is an alias for
-   :func:`stat` on platforms that do not support symbolic links, such as
-   Windows.
+   :func:`stat` on platforms that do not support symbolic links.
+
+   .. versionchanged:: 3.2
+      Added support for Windows 6.0 (Vista) symbolic links.
 
 
 .. function:: mkfifo(path[, mode])
@@ -1115,7 +1117,8 @@
 
    Create a directory named *path* with numeric mode *mode*. The default *mode*
    is ``0o777`` (octal).  On some systems, *mode* is ignored.  Where it is used,
-   the current umask value is first masked out.
+   the current umask value is first masked out.  If the directory already
+   exists, :exc:`OSError` is raised.
 
    It is also possible to create temporary directories; see the
    :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
@@ -1180,7 +1183,10 @@
    and the call may raise an UnicodeDecodeError. If the *path* is a bytes
    object, the result will be a bytes object.
 
-   Availability: Unix.
+   Availability: Unix, Windows
+
+   .. versionchanged:: 3.2
+      Added support for Windows 6.0 (Vista) symbolic links.
 
 
 .. function:: remove(path)
@@ -1342,7 +1348,27 @@
 
    Create a symbolic link pointing to *source* named *link_name*.
 
-   Availability: Unix.
+   On Windows, symlink version takes an additional, optional parameter,
+   *target_is_directory*, which defaults to False.
+
+   symlink(source, link_name, target_is_directory=False)
+
+   On Windows, a symlink represents a file or a directory, and does not
+   morph to the target dynamically.  For this reason, when creating a
+   symlink on Windows, if the target is not already present, the symlink
+   will default to being a file symlink.  If *target_is_directory* is set to
+   True, the symlink will be created as a directory symlink.  This
+   parameter is ignored if the target exists (and the symlink is created
+   with the same type as the target).
+
+   Symbolic link support was introduced in Windows 6.0 (Vista). *symlink*
+   will raise a NotImplementedError on Windows versions earlier than 6.0. The
+   SeCreateSymbolicLinkPrivilege is required in order to create symlinks.
+
+   Availability:  Unix, Windows
+
+   .. versionchanged:: 3.2
+      Added support for Windows 6.0 (Vista) symbolic links.
 
 
 .. function:: unlink(path)

Modified: python/branches/py3k-cdecimal/Doc/library/pdb.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/pdb.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/pdb.rst	Sat Jul 17 12:36:09 2010
@@ -210,11 +210,13 @@
    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)
-   Move the current frame one level down in the stack trace (to a newer frame).
-
-u(p)
-   Move the current frame one level up in the stack trace (to an older frame).
+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 *lineno* argument, set a break there in the current file.  With a

Modified: python/branches/py3k-cdecimal/Doc/library/re.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/re.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/re.rst	Sat Jul 17 12:36:09 2010
@@ -692,6 +692,11 @@
    metacharacters in it.
 
 
+.. function:: purge()
+
+   Clear the regular expression cache.
+
+
 .. exception:: error
 
    Exception raised when a string passed to one of the functions here is not a
@@ -709,18 +714,12 @@
 
    The :class:`RegexObject` class supports the following methods and attributes:
 
+   .. method:: RegexObject.search(string[, pos[, endpos]])
 
-   .. method:: RegexObject.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.
-
-      .. note::
-
-         If you want to locate a match anywhere in *string*, use
-         :meth:`~RegexObject.search` instead.
+      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.
 
       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
@@ -732,24 +731,34 @@
       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.match(string, 0, 50)`` is equivalent to
-      ``rx.match(string[:50], 0)``.
+      expression object, ``rx.search(string, 0, 50)`` is equivalent to
+      ``rx.search(string[:50], 0)``.
 
-         >>> 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("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.search(string[, pos[, endpos]])
+   .. method:: RegexObject.match(string[, pos[, endpos]])
 
-      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.
+      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.
 
       The optional *pos* and *endpos* parameters have the same meaning as for the
-      :meth:`~RegexObject.match` method.
+      :meth:`~RegexObject.search` method.
+
+      .. note::
+
+         If you want to locate a match anywhere in *string*, use
+         :meth:`~RegexObject.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 ...>
 
 
    .. method:: RegexObject.split(string[, maxsplit=0])
@@ -759,12 +768,16 @@
 
    .. method:: RegexObject.findall(string[, pos[, endpos]])
 
-      Identical to the :func:`findall` function, using the compiled pattern.
+      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]])
 
-      Identical to the :func:`finditer` function, using the compiled pattern.
+      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])
@@ -1217,9 +1230,9 @@
    ...   random.shuffle(inner_word)
    ...   return m.group(1) + "".join(inner_word) + m.group(3)
    >>> text = "Professor Abdolmalek, please report your absences promptly."
-   >>> re.sub("(\w)(\w+)(\w)", repl, text)
+   >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
    'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
-   >>> re.sub("(\w)(\w+)(\w)", repl, text)
+   >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
    'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
 
 

Modified: python/branches/py3k-cdecimal/Doc/library/select.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/select.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/select.rst	Sat Jul 17 12:36:09 2010
@@ -41,14 +41,14 @@
 
 .. function:: kqueue()
 
-   (Only supported on BSD.)  Returns a kernel queue object object; see section
+   (Only supported on BSD.)  Returns a kernel queue object; see section
    :ref:`kqueue-objects` below for the methods supported by kqueue objects.
 
 
 .. function:: kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)
 
-   (Only supported on BSD.)  Returns a kernel event object object; see section
-   :ref:`kevent-objects` below for the methods supported by kqueue objects.
+   (Only supported on BSD.)  Returns a kernel event object; see section
+   :ref:`kevent-objects` below for the methods supported by kevent objects.
 
 
 .. function:: select(rlist, wlist, xlist[, timeout])

Modified: python/branches/py3k-cdecimal/Doc/library/socket.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/socket.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/socket.rst	Sat Jul 17 12:36:09 2010
@@ -71,18 +71,21 @@
 tuple, and the fields depend on the address type. The general tuple form is
 ``(addr_type, v1, v2, v3 [, scope])``, where:
 
-   - *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
-     TIPC_ADDR_ID.
-   - *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
-     TIPC_NODE_SCOPE.
-   - If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
-     the port identifier, and *v3* should be 0.
+- *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
+  TIPC_ADDR_ID.
+- *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
+  TIPC_NODE_SCOPE.
+- If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
+  the port identifier, and *v3* should be 0.
 
-     If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
-     is the lower port number, and *v3* is the upper port number.
+  If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
+  is the lower port number, and *v3* is the upper port number.
 
-     If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
-     reference, and *v3* should be set to 0.
+  If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
+  reference, and *v3* should be set to 0.
+
+  If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
+  reference, and *v3* should be set to 0.
 
 
 All errors raise exceptions.  The normal exceptions for invalid argument types
@@ -690,7 +693,7 @@
 
    Set a timeout on blocking socket operations.  The *value* argument can be a
    nonnegative float expressing seconds, or ``None``. If a float is given,
-   subsequent socket operations will raise an :exc:`timeout` exception if the
+   subsequent socket operations will raise a :exc:`timeout` exception if the
    timeout period *value* has elapsed before the operation has completed.  Setting
    a timeout of ``None`` disables timeouts on socket operations.
    ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``;
@@ -745,7 +748,9 @@
    Shut down one or both halves of the connection.  If *how* is :const:`SHUT_RD`,
    further receives are disallowed.  If *how* is :const:`SHUT_WR`, further sends
    are disallowed.  If *how* is :const:`SHUT_RDWR`, further sends and receives are
-   disallowed.
+   disallowed.  Depending on the platform, shutting down one half of the connection
+   can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` does
+   not allow further reads on the other end of the connection).
 
 Note that there are no methods :meth:`read` or :meth:`write`; use
 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.

Modified: python/branches/py3k-cdecimal/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/sqlite3.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/sqlite3.rst	Sat Jul 17 12:36:09 2010
@@ -136,7 +136,7 @@
    first blank for the column name: the column name would simply be "x".
 
 
-.. function:: connect(database[, timeout, isolation_level, detect_types, factory])
+.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
 
    Opens a connection to the SQLite database file *database*. You can use
    ``":memory:"`` to open a database connection to a database that resides in RAM

Modified: python/branches/py3k-cdecimal/Doc/library/ssl.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/ssl.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/ssl.rst	Sat Jul 17 12:36:09 2010
@@ -110,13 +110,16 @@
 
    .. note::
 
-      This information varies depending on the version of OpenSSL.
-      For instance, in some older versions of OpenSSL (such as 0.9.7l on
-      OS X 10.4), an SSLv2 client could not connect to an SSLv23 server.
-      Conversely, starting from 1.0.0, an SSLv23 client will actually
-      try the SSLv3 protocol unless you explicitly enable SSLv2 ciphers.
+      Which connections succeed will vary depending on the version of
+      OpenSSL.  For instance, in some older versions of OpenSSL (such
+      as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
+      SSLv23 server.  Another example: beginning with OpenSSL 1.0.0,
+      an SSLv23 client will not actually attempt SSLv2 connections
+      unless you explicitly enable SSLv2 ciphers; for example, you
+      might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
+      to enable them.
 
-   The parameter ``ciphers`` sets the available ciphers for this SSL object.
+   The *ciphers* parameter sets the available ciphers for this SSL object.
    It should be a string in the `OpenSSL cipher list format
    <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
 

Modified: python/branches/py3k-cdecimal/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/stdtypes.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/stdtypes.rst	Sat Jul 17 12:36:09 2010
@@ -452,7 +452,7 @@
     Equivalent to::
 
         def bit_length(self):
-            s = bin(x)          # binary representation:  bin(-37) --> '-0b100101'
+            s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
             s = s.lstrip('-0b') # remove leading zeros and minus sign
             return len(s)       # len('100101') --> 6
 
@@ -966,7 +966,8 @@
 
 .. method:: str.capitalize()
 
-   Return a copy of the string with only its first character capitalized.
+   Return a copy of the string with its first character capitalized and the
+   rest lowercased.
 
 
 .. method:: str.center(width[, fillchar])
@@ -1329,6 +1330,10 @@
    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
@@ -2259,10 +2264,19 @@
    buffer protocol.  Builtin objects that support the buffer protocol include
    :class:`bytes` and :class:`bytearray`.
 
-   ``len(view)`` returns the total number of bytes in the memoryview, *view*.
+   A :class:`memoryview` has the notion of an *element*, which is the
+   atomic memory unit handled by the originating object *obj*.  For many
+   simple types such as :class:`bytes` and :class:`bytearray`, an element
+   is a single byte, but other types such as :class:`array.array` may have
+   bigger elements.
+
+   ``len(view)`` returns the total number of elements in the memoryview,
+   *view*.  The :class:`~memoryview.itemsize` attribute will give you the
+   number of bytes in a single element.
 
    A :class:`memoryview` supports slicing to expose its data.  Taking a single
-   index will return a single byte.  Full slicing will result in a subview::
+   index will return a single element as a :class:`bytes` object.  Full
+   slicing will result in a subview::
 
       >>> v = memoryview(b'abcefg')
       >>> v[1]
@@ -2273,11 +2287,8 @@
       <memory at 0x77ab28>
       >>> bytes(v[1:4])
       b'bce'
-      >>> v[3:-1]
-      <memory at 0x744f18>
-      >>> bytes(v[4:-1])
 
-   If the object the memory view is over supports changing its data, the
+   If the object the memoryview is over supports changing its data, the
    memoryview supports slice assignment::
 
       >>> data = bytearray(b'abcefg')
@@ -2295,14 +2306,20 @@
       File "<stdin>", line 1, in <module>
       ValueError: cannot modify size of memoryview object
 
-   Notice how the size of the memoryview object can not be changed.
-
+   Notice how the size of the memoryview object cannot be changed.
 
    :class:`memoryview` has two methods:
 
    .. method:: tobytes()
 
-      Return the data in the buffer as a bytestring.
+      Return the data in the buffer as a bytestring.  This is equivalent to
+      calling the :class:`bytes` constructor on the memoryview. ::
+
+         >>> m = memoryview(b"abc")
+         >>> m.tobytes()
+         b'abc'
+         >>> bytes(m)
+         b'abc'
 
    .. method:: tolist()
 
@@ -2320,7 +2337,15 @@
 
    .. attribute:: itemsize
 
-      The size in bytes of each element of the memoryview.
+      The size in bytes of each element of the memoryview::
+
+         >>> m = memoryview(array.array('H', [1,2,3]))
+         >>> m.itemsize
+         2
+         >>> m[0]
+         b'\x01\x00'
+         >>> len(m[0]) == m.itemsize
+         True
 
    .. attribute:: shape
 

Modified: python/branches/py3k-cdecimal/Doc/library/string.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/string.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/string.rst	Sat Jul 17 12:36:09 2010
@@ -174,7 +174,7 @@
    .. method:: convert_field(value, conversion)
 
       Converts the value (returned by :meth:`get_field`) given a conversion type
-      (as in the tuple returned by the :meth:`parse` method.)  The default
+      (as in the tuple returned by the :meth:`parse` method).  The default
       version understands 'r' (repr) and 's' (str) conversion types.
 
 
@@ -185,7 +185,7 @@
 
 The :meth:`str.format` method and the :class:`Formatter` class share the same
 syntax for format strings (although in the case of :class:`Formatter`,
-subclasses can define their own format string syntax.)
+subclasses can define their own format string syntax).
 
 Format strings contain "replacement fields" surrounded by curly braces ``{}``.
 Anything that is not contained in braces is considered literal text, which is
@@ -197,7 +197,7 @@
    .. productionlist:: sf
       replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
       field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
-      arg_name: (`identifier` | `integer`)?
+      arg_name: [`identifier` | `integer`]
       attribute_name: `identifier`
       element_index: `integer` | `index_string`
       index_string: <any source character except "]"> +
@@ -211,6 +211,8 @@
 preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
 by a colon ``':'``.  These specify a non-default format for the replacement value.
 
+See also the :ref:`formatspec` section.
+
 The *field_name* itself begins with an *arg_name* that is either either a number or a
 keyword.  If it's a number, it refers to a positional argument, and if it's a keyword,
 it refers to a named keyword argument.  If the numerical arg_names in a format string
@@ -221,6 +223,10 @@
 attribute using :func:`getattr`, while an expression of the form ``'[index]'``
 does an index lookup using :func:`__getitem__`.
 
+.. versionchanged:: 3.1
+   The positional argument specifiers can be omitted, so ``'{} {}'`` is
+   equivalent to ``'{0} {1}'``.
+
 Some simple format string examples::
 
    "First, thou shalt count to {0}" # References first positional argument
@@ -261,26 +267,7 @@
 format_spec are substituted before the *format_spec* string is interpreted.
 This allows the formatting of a value to be dynamically specified.
 
-For example, suppose you wanted to have a replacement field whose field width is
-determined by another variable::
-
-   "A man with two {0:{1}}".format("noses", 10)
-
-This would first evaluate the inner replacement field, making the format string
-effectively::
-
-   "A man with two {0:10}"
-
-Then the outer replacement field would be evaluated, producing::
-
-   "noses     "
-
-Which is substituted into the string, yielding::
-
-   "A man with two noses     "
-
-(The extra space is because we specified a field width of 10, and because left
-alignment is the default for strings.)
+See the :ref:`formatexamples` section for some examples.
 
 
 .. _formatspec:
@@ -290,7 +277,7 @@
 
 "Format specifications" are used within replacement fields contained within a
 format string to define how individual values are presented (see
-:ref:`formatstrings`.)  They can also be passed directly to the built-in
+:ref:`formatstrings`).  They can also be passed directly to the built-in
 :func:`format` function.  Each formattable type may define how the format
 specification is to be interpreted.
 
@@ -324,7 +311,7 @@
    | Option  | Meaning                                                  |
    +=========+==========================================================+
    | ``'<'`` | Forces the field to be left-aligned within the available |
-   |         | space (This is the default.)                             |
+   |         | space (this is the default).                             |
    +---------+----------------------------------------------------------+
    | ``'>'`` | Forces the field to be right-aligned within the          |
    |         | available space.                                         |
@@ -366,6 +353,9 @@
 For a locale aware separator, use the ``'n'`` integer presentation type
 instead.
 
+.. versionchanged:: 3.1
+   Added the ``','`` option (see also :pep:`378`).
+
 *width* is a decimal integer defining the minimum field width.  If not
 specified, then the field width will be determined by the content.
 
@@ -484,6 +474,147 @@
    +---------+----------------------------------------------------------+
 
 
+.. _formatexamples:
+
+Format examples
+^^^^^^^^^^^^^^^
+
+This section contains examples of the new format syntax and comparison with
+the old ``%``-formatting.
+
+In most of the cases the syntax is similar to the old ``%``-formatting, with the
+addition of the ``{}`` and with ``:`` used instead of ``%``.
+For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
+
+The new format syntax also supports new and different options, shown in the
+follow examples.
+
+Accessing arguments by position::
+
+   >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
+   'a, b, c'
+   >>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
+   'a, b, c'
+   >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
+   'c, b, a'
+   >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
+   'c, b, a'
+   >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
+   'abracadabra'
+
+Accessing arguments by name::
+
+   >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
+   'Coordinates: 37.24N, -115.81W'
+   >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
+   >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
+   'Coordinates: 37.24N, -115.81W'
+
+Accessing arguments' attributes::
+
+   >>> c = 3-5j
+   >>> ('The complex number {0} is formed from the real part {0.real} '
+   ...  'and the imaginary part {0.imag}.').format(c)
+   'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
+   >>> class Point:
+   ...     def __init__(self, x, y):
+   ...         self.x, self.y = x, y
+   ...     def __str__(self):
+   ...         return 'Point({self.x}, {self.y})'.format(self=self)
+   ...
+   >>> str(Point(4, 2))
+   'Point(4, 2)'
+
+Accessing arguments' items::
+
+   >>> coord = (3, 5)
+   >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
+   'X: 3;  Y: 5'
+
+Replacing ``%s`` and ``%r``::
+
+   >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
+   "repr() shows quotes: 'test1'; str() doesn't: test2"
+
+Aligning the text and specifying a width::
+
+   >>> '{:<30}'.format('left aligned')
+   'left aligned                  '
+   >>> '{:>30}'.format('right aligned')
+   '                 right aligned'
+   >>> '{:^30}'.format('centered')
+   '           centered           '
+   >>> '{:*^30}'.format('centered')  # use '*' as a fill char
+   '***********centered***********'
+
+Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
+
+   >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
+   '+3.140000; -3.140000'
+   >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
+   ' 3.140000; -3.140000'
+   >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
+   '3.140000; -3.140000'
+
+Replacing ``%x`` and ``%o`` and converting the value to different bases::
+
+   >>> # format also supports binary numbers
+   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
+   'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
+   >>> # with 0x, 0o, or 0b as prefix:
+   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
+   'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
+
+Using the comma as a thousands separator::
+
+   >>> '{:,}'.format(1234567890)
+   '1,234,567,890'
+
+Expressing a percentage::
+
+   >>> points = 19
+   >>> total = 22
+   >>> 'Correct answers: {:.2%}.'.format(points/total)
+   'Correct answers: 86.36%'
+
+Using type-specific formatting::
+
+   >>> import datetime
+   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
+   >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
+   '2010-07-04 12:15:58'
+
+Nesting arguments and more complex examples::
+
+   >>> for align, text in zip('<^>', ['left', 'center', 'right']):
+   ...     '{0:{align}{fill}16}'.format(text, fill=align, align=align)
+   ...
+   'left<<<<<<<<<<<<'
+   '^^^^^center^^^^^'
+   '>>>>>>>>>>>right'
+   >>>
+   >>> octets = [192, 168, 0, 1]
+   >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
+   'C0A80001'
+   >>> int(_, 16)
+   3232235521
+   >>>
+   >>> width = 5
+   >>> for num in range(5,12):
+   ...     for base in 'dXob':
+   ...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
+   ...     print()
+   ...
+       5     5     5   101
+       6     6     6   110
+       7     7     7   111
+       8     8    10  1000
+       9     9    11  1001
+      10     A    12  1010
+      11     B    13  1011
+
+
+
 .. _template-strings:
 
 Template strings

Modified: python/branches/py3k-cdecimal/Doc/library/struct.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/struct.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/struct.rst	Sat Jul 17 12:36:09 2010
@@ -20,9 +20,9 @@
    order to maintain proper alignment for the C types involved; similarly,
    alignment is taken into account when unpacking.  This behavior is chosen so
    that the bytes of a packed struct correspond exactly to the layout in memory
-   of the corresponding C struct.  To omit pad bytes, use `standard` size and
-   alignment instead of `native` size and alignment: see :ref:`struct-alignment`
-   for details.
+   of the corresponding C struct.  To handle platform-independent data formats
+   or omit implicit pad bytes, use `standard` size and alignment instead of
+   `native` size and alignment: see :ref:`struct-alignment` for details.
 
 Functions and Exceptions
 ------------------------
@@ -95,19 +95,19 @@
 the byte order, size and alignment of the packed data, according to the
 following table:
 
-+-----------+------------------------+--------------------+
-| Character | Byte order             | Size and alignment |
-+===========+========================+====================+
-| ``@``     | native                 | native             |
-+-----------+------------------------+--------------------+
-| ``=``     | native                 | standard           |
-+-----------+------------------------+--------------------+
-| ``<``     | little-endian          | standard           |
-+-----------+------------------------+--------------------+
-| ``>``     | big-endian             | standard           |
-+-----------+------------------------+--------------------+
-| ``!``     | network (= big-endian) | standard           |
-+-----------+------------------------+--------------------+
++-----------+------------------------+----------+-----------+
+| Character | Byte order             | Size     | Alignment |
++===========+========================+==========+===========+
+| ``@``     | native                 | native   | native    |
++-----------+------------------------+----------+-----------+
+| ``=``     | native                 | standard | none      |
++-----------+------------------------+----------+-----------+
+| ``<``     | little-endian          | standard | none      |
++-----------+------------------------+----------+-----------+
+| ``>``     | big-endian             | standard | none      |
++-----------+------------------------+----------+-----------+
+| ``!``     | network (= big-endian) | standard | none      |
++-----------+------------------------+----------+-----------+
 
 If the first character is not one of these, ``'@'`` is assumed.
 
@@ -120,11 +120,8 @@
 Native size and alignment are determined using the C compiler's
 ``sizeof`` expression.  This is always combined with native byte order.
 
-Standard size and alignment are as follows: no alignment is required for any
-type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
-:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
-bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
-point numbers, respectively. :ctype:`_Bool` is 1 byte.
+Standard size depends only on the format character;  see the table in
+the :ref:`format-characters` section.
 
 Note the difference between ``'@'`` and ``'='``: both use native byte order, but
 the size and alignment of the latter is standardized.
@@ -135,12 +132,6 @@
 There is no way to indicate non-native byte order (force byte-swapping); use the
 appropriate choice of ``'<'`` or ``'>'``.
 
-The ``'P'`` format character is only available for the native byte ordering
-(selected as the default or with the ``'@'`` byte order character). The byte
-order character ``'='`` chooses to use little- or big-endian ordering based on
-the host system. The struct module does not interpret this as native ordering,
-so the ``'P'`` format is not available.
-
 Notes:
 
 (1) Padding is only automatically added between successive structure members.
@@ -160,7 +151,11 @@
 ^^^^^^^^^^^^^^^^^
 
 Format characters have the following meaning; the conversion between C and
-Python values should be obvious given their types:
+Python values should be obvious given their types.  The 'Standard size' column
+refers to the size of the packed value in bytes when using standard size; that
+is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or
+``'='``.  When using native size, the size of the packed value is
+platform-dependent.
 
 +--------+-------------------------+--------------------+----------------+------------+
 | Format | C Type                  | Python type        | Standard size  | Notes      |
@@ -192,15 +187,15 @@
 | ``Q``  | :ctype:`unsigned long   | integer            | 8              | \(3), \(4) |
 |        | long`                   |                    |                |            |
 +--------+-------------------------+--------------------+----------------+------------+
-| ``f``  | :ctype:`float`          | float              | 4              |            |
+| ``f``  | :ctype:`float`          | float              | 4              | \(5)       |
 +--------+-------------------------+--------------------+----------------+------------+
-| ``d``  | :ctype:`double`         | float              | 8              |            |
+| ``d``  | :ctype:`double`         | float              | 8              | \(5)       |
 +--------+-------------------------+--------------------+----------------+------------+
 | ``s``  | :ctype:`char[]`         | bytes              |                | \(1)       |
 +--------+-------------------------+--------------------+----------------+------------+
 | ``p``  | :ctype:`char[]`         | bytes              |                | \(1)       |
 +--------+-------------------------+--------------------+----------------+------------+
-| ``P``  | :ctype:`void \*`        | integer            |                |            |
+| ``P``  | :ctype:`void \*`        | integer            |                | \(6)       |
 +--------+-------------------------+--------------------+----------------+------------+
 
 Notes:
@@ -228,6 +223,18 @@
    .. versionchanged:: 3.2
       Use of the :meth:`__index__` method for non-integers is new in 3.2.
 
+(5)
+   For the ``'f'`` and ``'d'`` conversion codes, the packed representation uses
+   the IEEE 754 binary32 (for ``'f'``) or binary64 (for ``'d'``) format,
+   regardless of the floating-point format used by the platform.
+
+(6)
+   The ``'P'`` format character is only available for the native byte ordering
+   (selected as the default or with the ``'@'`` byte order character). The byte
+   order character ``'='`` chooses to use little- or big-endian ordering based
+   on the host system. The struct module does not interpret this as native
+   ordering, so the ``'P'`` format is not available.
+
 
 A format character may be preceded by an integral repeat count.  For example,
 the format string ``'4h'`` means exactly the same as ``'hhhh'``.
@@ -252,18 +259,16 @@
    In 3.0, some of the integer formats wrapped out-of-range values and
    raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
 
-
 The ``'p'`` format character encodes a "Pascal string", meaning a short
-variable-length string stored in a fixed number of bytes. The count is the total
-number of bytes stored.  The first byte stored is the length of the string, or
-255, whichever is smaller.  The bytes of the string follow.  If the string
-passed in to :func:`pack` is too long (longer than the count minus 1), only the
-leading count-1 bytes of the string are stored.  If the string is shorter than
-count-1, it is padded with null bytes so that exactly count bytes in all are
-used.  Note that for :func:`unpack`, the ``'p'`` format character consumes count
-bytes, but that the string returned can never contain more than 255 bytes.
-
-
+variable-length string stored in a *fixed number of bytes*, given by the count.
+The first byte stored is the length of the string, or 255, whichever is
+smaller.  The bytes of the string follow.  If the string passed in to
+:func:`pack` is too long (longer than the count minus 1), only the leading
+``count-1`` bytes of the string are stored.  If the string is shorter than
+``count-1``, it is padded with null bytes so that exactly count bytes in all
+are used.  Note that for :func:`unpack`, the ``'p'`` format character consumes
+``count`` bytes, but that the string returned can never contain more than 255
+bytes.
 
 For the ``'?'`` format character, the return value is either :const:`True` or
 :const:`False`. When packing, the truth value of the argument object is used.

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

Modified: python/branches/py3k-cdecimal/Doc/library/sys.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/sys.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/sys.rst	Sat Jul 17 12:36:09 2010
@@ -223,44 +223,65 @@
 .. data:: float_info
 
    A structseq holding information about the float type. It contains low level
-   information about the precision and internal representation. Please study
-   your system's :file:`float.h` for more information.
-
-   +---------------------+--------------------------------------------------+
-   | attribute           |  explanation                                     |
-   +=====================+==================================================+
-   | :const:`epsilon`    | Difference between 1 and the next representable  |
-   |                     | floating point number                            |
-   +---------------------+--------------------------------------------------+
-   | :const:`dig`        | digits (see :file:`float.h`)                     |
-   +---------------------+--------------------------------------------------+
-   | :const:`mant_dig`   | mantissa digits (see :file:`float.h`)            |
-   +---------------------+--------------------------------------------------+
-   | :const:`max`        | maximum representable finite float               |
-   +---------------------+--------------------------------------------------+
-   | :const:`max_exp`    | maximum int e such that radix**(e-1) is in the   |
-   |                     | range of finite representable floats             |
-   +---------------------+--------------------------------------------------+
-   | :const:`max_10_exp` | maximum int e such that 10**e is in the          |
-   |                     | range of finite representable floats             |
-   +---------------------+--------------------------------------------------+
-   | :const:`min`        | Minimum positive normalizer float                |
-   +---------------------+--------------------------------------------------+
-   | :const:`min_exp`    | minimum int e such that radix**(e-1) is a        |
-   |                     | normalized float                                 |
-   +---------------------+--------------------------------------------------+
-   | :const:`min_10_exp` | minimum int e such that 10**e is a normalized    |
-   |                     | float                                            |
-   +---------------------+--------------------------------------------------+
-   | :const:`radix`      | radix of exponent                                |
-   +---------------------+--------------------------------------------------+
-   | :const:`rounds`     | addition rounds (see :file:`float.h`)            |
-   +---------------------+--------------------------------------------------+
-
-   .. note::
-
-      The information in the table is simplified.
+   information about the precision and internal representation.  The values
+   correspond to the various floating-point constants defined in the standard
+   header file :file:`float.h` for the 'C' programming language; see section
+   5.2.4.2.2 of the 1999 ISO/IEC C standard [C99]_, 'Characteristics of
+   floating types', for details.
+
+   +---------------------+----------------+--------------------------------------------------+
+   | attribute           | float.h macro  | explanation                                      |
+   +=====================+================+==================================================+
+   | :const:`epsilon`    | DBL_EPSILON    | difference between 1 and the least value greater |
+   |                     |                | than 1 that is representable as a float          |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`dig`        | DBL_DIG        | maximum number of decimal digits that can be     |
+   |                     |                | faithfully represented in a float;  see below    |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`mant_dig`   | DBL_MANT_DIG   | float precision: the number of base-``radix``    |
+   |                     |                | digits in the significand of a float             |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`max`        | DBL_MAX        | maximum representable finite float               |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`max_exp`    | DBL_MAX_EXP    | maximum integer e such that ``radix**(e-1)`` is  |
+   |                     |                | a representable finite float                     |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`max_10_exp` | DBL_MAX_10_EXP | maximum integer e such that ``10**e`` is in the  |
+   |                     |                | range of representable finite floats             |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`min`        | DBL_MIN        | minimum positive normalized float                |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`min_exp`    | DBL_MIN_EXP    | minimum integer e such that ``radix**(e-1)`` is  |
+   |                     |                | a normalized float                               |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`min_10_exp` | DBL_MIN_10_EXP | minimum integer e such that ``10**e`` is a       |
+   |                     |                | normalized float                                 |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`radix`      | FLT_RADIX      | radix of exponent representation                 |
+   +---------------------+----------------+--------------------------------------------------+
+   | :const:`rounds`     | FLT_ROUNDS     | constant representing rounding mode              |
+   |                     |                | used for arithmetic operations                   |
+   +---------------------+----------------+--------------------------------------------------+
+
+   The attribute :attr:`sys.float_info.dig` needs further explanation.  If
+   ``s`` is any string representing a decimal number with at most
+   :attr:`sys.float_info.dig` significant digits, then converting ``s`` to a
+   float and back again will recover a string representing the same decimal
+   value::
 
+      >>> import sys
+      >>> sys.float_info.dig
+      15
+      >>> s = '3.14159265358979'    # decimal string with 15 significant digits
+      >>> format(float(s), '.15g')  # convert to float and back -> same value
+      '3.14159265358979'
+
+   But for strings with more than :attr:`sys.float_info.dig` significant digits,
+   this isn't always true::
+
+      >>> s = '9876543211234567'    # 16 significant digits is too many!
+      >>> format(float(s), '.16g')  # conversion changes value
+      '9876543211234568'
 
 .. data:: float_repr_style
 
@@ -957,3 +978,8 @@
    first three characters of :const:`version`.  It is provided in the :mod:`sys`
    module for informational purposes; modifying this value has no effect on the
    registry keys used by Python. Availability: Windows.
+
+.. rubric:: Citations
+
+.. [C99] ISO/IEC 9899:1999.  "Programming languages -- C."  A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf .
+

Modified: python/branches/py3k-cdecimal/Doc/library/sysconfig.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/sysconfig.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/sysconfig.rst	Sat Jul 17 12:36:09 2010
@@ -16,9 +16,9 @@
 Configuration variables
 -----------------------
 
-A Python distribution contains a :file:`Makefile` file and a :file:`python.h`
-that are necessary to build the Python binary itself, but also any C extension
-created in a third party project and compiled using :mod:`distutils`.
+A Python distribution contains a :file:`Makefile` and a :file:`pyconfig.h`
+header file that are necessary to build both the Python binary itself and
+third-party C extensions compiled using :mod:`distutils`.
 
 :mod:`sysconfig` puts all variables found in these files in a dictionary that
 can be accessed using :func:`get_config_vars` or :func:`get_config_var`.

Modified: python/branches/py3k-cdecimal/Doc/library/unittest.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/unittest.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/unittest.rst	Sat Jul 17 12:36:09 2010
@@ -220,26 +220,26 @@
 
 unittest supports three command options.
 
-* -f / --failfast
+* :option:`-b` / :option:`--buffer`
 
-  Stop the test run on the first error or failure.
+  The standard output and standard error streams are buffered during the test
+  run. Output during a passing test is discarded. Output is echoed normally
+  on test fail or error and is added to the failure messages.
 
-* -c / --catch
+* :option:`-c` / :option:`--catch`
 
-  Control-c during the test run waits for the current test to end and then
-  reports all the results so far. A second control-c raises the normal
-  ``KeyboardInterrupt`` exception.
+  Control-C during the test run waits for the current test to end and then
+  reports all the results so far. A second control-C raises the normal
+  :exc:`KeyboardInterrupt` exception.
 
   See `Signal Handling`_ for the functions that provide this functionality.
 
-* -b / --buffer
+* :option:`-f` / :option:`--failfast`
 
-  The standard out and standard error streams are buffered during the test
-  run. Output during a passing test is discarded. Output is echoed normally
-  on test fail or error and is added to the failure messages.
+  Stop the test run on the first error or failure.
 
 .. versionadded:: 3.2
-   The command line options ``-c``, ``-b`` and ``-f`` where added.
+   The command line options ``-c``, ``-b`` and ``-f`` were added.
 
 The command line can also be used for test discovery, for running all of the
 tests in a project or just a subset.
@@ -270,8 +270,9 @@
    -t directory     Top level directory of project (default to
                     start directory)
 
-The -s, -p, & -t options can be passsed in as positional arguments. The
-following two command lines are equivalent::
+The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
+as positional arguments in that order. The following two command lines
+are equivalent::
 
    python -m unittest discover -s project_directory -p '*_test.py'
    python -m unittest discover project_directory '*_test.py'
@@ -829,6 +830,11 @@
       compare equal, the test will fail with the explanation given by *msg*, or
       :const:`None`.
 
+      If *delta* is supplied instead of *places* then the difference
+      between *first* and *second* must be less than *delta*.
+
+      Supplying both *delta* and *places* raises a ``TypeError``.
+
       .. versionchanged:: 3.2
          Objects that compare equal are automatically almost equal.
          Added the ``delta`` keyword argument.
@@ -849,7 +855,7 @@
       compare equal, the test will fail with the explanation given by *msg*, or
       :const:`None`.
 
-      If *delta* is supplied instead of *places* then the the difference
+      If *delta* is supplied instead of *places* then the difference
       between *first* and *second* must be more than *delta*.
 
       Supplying both *delta* and *places* raises a ``TypeError``.
@@ -1902,12 +1908,12 @@
 Signal Handling
 ---------------
 
-The -c / --catch command line option to unittest, along with the ``catchbreak``
+The :option:`-c`/:option:`--catch` command line option to unittest, along with the ``catchbreak``
 parameter to :func:`unittest.main()`, provide more friendly handling of
-control-c during a test run. With catch break behavior enabled control-c will
+control-C during a test run. With catch break behavior enabled control-C will
 allow the currently running test to complete, and the test run will then end
 and report all the results so far. A second control-c will raise a
-``KeyboardInterrupt`` in the usual way.
+:exc:`KeyboardInterrupt` in the usual way.
 
 The control-c handling signal handler attempts to remain compatible with code or
 tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``

Modified: python/branches/py3k-cdecimal/Doc/library/urllib.parse.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/urllib.parse.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/urllib.parse.rst	Sat Jul 17 12:36:09 2010
@@ -310,23 +310,29 @@
    ``b'a&\xef'``.
 
 
-.. function:: urlencode(query, doseq=False)
+.. function:: urlencode(query, doseq=False, safe='', encoding=None, errors=None)
 
-   Convert a mapping object or a sequence of two-element tuples to a
-   "url-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 ``'&'`` characters, where both *key* and
-   *value* are quoted using :func:`quote_plus` above. When a sequence of
-   two-element tuples is used as the *query* argument, the first element of
-   each tuple is a key and the second is a value. The value element in itself
-   can be a sequence and in that case, if the optional parameter *doseq* is
-   evaluates to *True*, individual ``key=value`` pairs separated by ``'&'`` are
-   generated for each element of the value sequence for the key.  The order of
-   parameters in the encoded string will match the order of parameter tuples in
-   the sequence. This module provides the functions :func:`parse_qs` and
-   :func:`parse_qsl` which are used to parse query strings into Python data
-   structures.
+   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,
+   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 ``'&'``
+   characters, where both *key* and *value* are quoted using :func:`quote_plus`
+   above. When a sequence of two-element tuples is used as the *query*
+   argument, the first element of each tuple is a key and the second is a
+   value. The value element in itself can be a sequence and in that case, if
+   the optional parameter *doseq* is evaluates to *True*, individual
+   ``key=value`` pairs separated by ``'&'`` are generated for each element of
+   the value sequence for the key.  The order of parameters in the encoded
+   string will match the order of parameter tuples in the sequence. This module
+   provides the functions :func:`parse_qs` and :func:`parse_qsl` which are used
+   to parse query strings into Python data structures.
+
+   When *query* parameter is a :class:`str`, the *safe*, *encoding* and *error*
+   parameters are sent the :func:`quote_plus` for encoding.
+
+   .. versionchanged:: 3.2
+      query paramater supports bytes and string.
 
 
 .. seealso::

Modified: python/branches/py3k-cdecimal/Doc/library/urllib.request.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/urllib.request.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/urllib.request.rst	Sat Jul 17 12:36:09 2010
@@ -40,8 +40,8 @@
      commonly used to determine if a redirect was followed
 
    * :meth:`info` --- return the meta-information of the page, such as headers,
-     in the form of an :class:`http.client.HTTPMessage` instance (see `Quick
-     Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
+     in the form of an :func:`email.message_from_string` instance (see
+     `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
 
    Raises :exc:`URLError` on errors.
 

Modified: python/branches/py3k-cdecimal/Doc/library/warnings.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/library/warnings.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/library/warnings.rst	Sat Jul 17 12:36:09 2010
@@ -57,7 +57,7 @@
 | :exc:`UserWarning`               | The default category for :func:`warn`.        |
 +----------------------------------+-----------------------------------------------+
 | :exc:`DeprecationWarning`        | Base category for warnings about deprecated   |
-|                                  | features.                                     |
+|                                  | features (ignored by default).                |
 +----------------------------------+-----------------------------------------------+
 | :exc:`SyntaxWarning`             | Base category for warnings about dubious      |
 |                                  | syntactic features.                           |
@@ -91,6 +91,9 @@
 standard warning categories.  A warning category must always be a subclass of
 the :exc:`Warning` class.
 
+.. versionchanged:: 3.2
+   :exc:`DeprecationWarning` is ignored by default.
+
 
 .. _warning-filter:
 
@@ -150,14 +153,6 @@
 :mod:`warnings` module parses these when it is first imported (invalid options
 are ignored, after printing a message to ``sys.stderr``).
 
-The warnings that are ignored by default may be enabled by passing :option:`-Wd`
-to the interpreter. This enables default handling for all warnings, including
-those that are normally ignored by default. This is particular useful for
-enabling ImportWarning when debugging problems importing a developed package.
-ImportWarning can also be enabled explicitly in Python code using::
-
-   warnings.simplefilter('default', ImportWarning)
-
 
 .. _warning-suppress:
 
@@ -233,6 +228,37 @@
 entries from the warnings list before each new operation).
 
 
+Updating Code For New Versions of Python
+----------------------------------------
+
+Warnings that are only of interest to the developer are ignored by default. As
+such you should make sure to test your code with typically ignored warnings
+made visible. You can do this from the command-line by passing :option:`-Wd`
+to the interpreter (this is shorthand for :option:`-W default`).  This enables
+default handling for all warnings, including those that are ignored by default.
+To change what action is taken for encountered warnings you simply change what
+argument is passed to :option:`-W`, e.g. :option:`-W error`. See the
+:option:`-W` flag for more details on what is possible.
+
+To programmatically do the same as :option:`-Wd`, use::
+
+  warnings.simplefilter('default')
+
+Make sure to execute this code as soon as possible. This prevents the
+registering of what warnings have been raised from unexpectedly influencing how
+future warnings are treated.
+
+Having certain warnings ignored by default is done to prevent a user from
+seeing warnings that are only of interest to the developer. As you do not
+necessarily have control over what interpreter a user uses to run their code,
+it is possible that a new version of Python will be released between your
+release cycles.  The new interpreter release could trigger new warnings in your
+code that were not there in an older interpreter, e.g.
+:exc:`DeprecationWarning` for a module that you are using. While you as a
+developer want to be notified that your code is using a deprecated module, to a
+user this information is essentially noise and provides no benefit to them.
+
+
 .. _warning-functions:
 
 Available Functions

Modified: python/branches/py3k-cdecimal/Doc/reference/compound_stmts.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/reference/compound_stmts.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/reference/compound_stmts.rst	Sat Jul 17 12:36:09 2010
@@ -272,14 +272,12 @@
        try:
            foo
        finally:
-           N = None
            del N
 
-That means that you have to assign the exception to a different name if you want
-to be able to refer to it after the except clause.  The reason for this is that
-with the traceback attached to them, exceptions will form a reference cycle with
-the stack frame, keeping all locals in that frame alive until the next garbage
-collection occurs.
+This means the exception must be assigned to a different name to be able to
+refer to it after the except clause.  Exceptions are cleared because with the
+traceback attached to them, they form a reference cycle with the stack frame,
+keeping all locals in that frame alive until the next garbage collection occurs.
 
 .. index::
    module: sys

Modified: python/branches/py3k-cdecimal/Doc/reference/datamodel.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/reference/datamodel.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/reference/datamodel.rst	Sat Jul 17 12:36:09 2010
@@ -1595,7 +1595,7 @@
 
 In particular, the metaclass :class:`abc.ABCMeta` implements these methods in
 order to allow the addition of Abstract Base Classes (ABCs) as "virtual base
-classes" to any class or type (including built-in types), and including to other
+classes" to any class or type (including built-in types), including other
 ABCs.
 
 .. method:: class.__instancecheck__(self, instance)
@@ -1614,7 +1614,7 @@
 
 Note that these methods are looked up on the type (metaclass) of a class.  They
 cannot be defined as class methods in the actual class.  This is consistent with
-the lookup of special methods that are called on instances, only that in this
+the lookup of special methods that are called on instances, only in this
 case the instance is itself a class.
 
 .. seealso::

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

Modified: python/branches/py3k-cdecimal/Doc/reference/introduction.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/reference/introduction.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/reference/introduction.rst	Sat Jul 17 12:36:09 2010
@@ -69,12 +69,12 @@
    more information, see `the IronPython website <http://www.ironpython.com/>`_.
 
 PyPy
-   An implementation of Python written in Python; even the bytecode interpreter is
-   written in Python.  This is executed using CPython as the underlying
-   interpreter.  One of the goals of the project is to encourage experimentation
-   with the language itself by making it easier to modify the interpreter (since it
-   is written in Python).  Additional information is available on `the PyPy
-   project's home page <http://codespeak.net/pypy/>`_.
+   An implementation of Python written completely in Python. It supports several
+   advanced features not found in other implementations like stackless support
+   and a Just in Time compiler. One of the goals of the project is to encourage
+   experimentation with the language itself by making it easier to modify the
+   interpreter (since it is written in Python).  Additional information is
+   available on `the PyPy project's home page <http://pypy.org/>`_.
 
 Each of these implementations varies in some way from the language as documented
 in this manual, or introduces specific information beyond what's covered in the

Modified: python/branches/py3k-cdecimal/Doc/reference/lexical_analysis.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/reference/lexical_analysis.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/reference/lexical_analysis.rst	Sat Jul 17 12:36:09 2010
@@ -407,7 +407,7 @@
 
 .. productionlist::
    bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`)
-   bytesprefix: "b" | "B"
+   bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR"
    shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"'
    longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""'
    shortbytesitem: `shortbyteschar` | `bytesescapeseq`
@@ -431,16 +431,16 @@
 characters that otherwise have a special meaning, such as newline, backslash
 itself, or the quote character.
 
-String literals may optionally be prefixed with a letter ``'r'`` or ``'R'``;
-such strings are called :dfn:`raw strings` and treat backslashes as literal
-characters.  As a result, ``'\U'`` and ``'\u'`` escapes in raw strings are not
-treated specially.
-
 Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an
 instance of the :class:`bytes` type instead of the :class:`str` type.  They
 may only contain ASCII characters; bytes with a numeric value of 128 or greater
 must be expressed with escapes.
 
+Both string and bytes literals may optionally be prefixed with a letter ``'r'``
+or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as
+literal characters.  As a result, in string literals, ``'\U'`` and ``'\u'``
+escapes in raw strings are not treated specially.
+
 In triple-quoted strings, unescaped newlines and quotes are allowed (and are
 retained), except that three unescaped quotes in a row terminate the string.  (A
 "quote" is the character used to open the string, i.e. either ``'`` or ``"``.)
@@ -545,9 +545,9 @@
 String literal concatenation
 ----------------------------
 
-Multiple adjacent string literals (delimited by whitespace), possibly using
-different quoting conventions, are allowed, and their meaning is the same as
-their concatenation.  Thus, ``"hello" 'world'`` is equivalent to
+Multiple adjacent string or bytes literals (delimited by whitespace), possibly
+using different quoting conventions, are allowed, and their meaning is the same
+as their concatenation.  Thus, ``"hello" 'world'`` is equivalent to
 ``"helloworld"``.  This feature can be used to reduce the number of backslashes
 needed, to split long strings conveniently across long lines, or even to add
 comments to parts of strings, for example::

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

Modified: python/branches/py3k-cdecimal/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/py3k-cdecimal/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/py3k-cdecimal/Doc/tools/sphinxext/pyspecific.py	Sat Jul 17 12:36:09 2010
@@ -5,7 +5,7 @@
 
     Sphinx extension with Python doc-specific markup.
 
-    :copyright: 2008, 2009 by Georg Brandl.
+    :copyright: 2008, 2009, 2010 by Georg Brandl.
     :license: Python license.
 """
 
@@ -149,7 +149,7 @@
 import re
 from sphinx import addnodes
 
-opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)\s*\((.*)\)')
+opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
 
 def parse_opcode_signature(env, sig, signode):
     """Transform an opcode signature into RST nodes."""
@@ -158,9 +158,10 @@
         raise ValueError
     opname, arglist = m.groups()
     signode += addnodes.desc_name(opname, opname)
-    paramlist = addnodes.desc_parameterlist()
-    signode += paramlist
-    paramlist += addnodes.desc_parameter(arglist, arglist)
+    if arglist is not None:
+        paramlist = addnodes.desc_parameterlist()
+        signode += paramlist
+        paramlist += addnodes.desc_parameter(arglist, arglist)
     return opname.strip()
 
 

Modified: python/branches/py3k-cdecimal/Doc/tutorial/classes.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/tutorial/classes.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/tutorial/classes.rst	Sat Jul 17 12:36:09 2010
@@ -580,7 +580,7 @@
 =================
 
 "Private" instance variables that cannot be accessed except from inside an
-object, don't exist in Python.  However, there is a convention that is followed
+object don't exist in Python.  However, there is a convention that is followed
 by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
 be treated as a non-public part of the API (whether it is a function, a method
 or a data member).  It should be considered an implementation detail and subject
@@ -599,12 +599,12 @@
 possible to access or modify a variable that is considered private.  This can
 even be useful in special circumstances, such as in the debugger.
 
-Notice that code passed to ``exec()``, ``eval()`` or ``execfile()`` does not
-consider the classname of the invoking  class to be the current class; this is
-similar to the effect of the  ``global`` statement, the effect of which is
-likewise restricted to  code that is byte-compiled together.  The same
-restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well
-as when referencing ``__dict__`` directly.
+Notice that code passed to ``exec()`` or ``eval()`` does not consider the
+classname of the invoking class to be the current class; this is similar to the
+effect of the ``global`` statement, the effect of which is likewise restricted
+to code that is byte-compiled together.  The same restriction applies to
+``getattr()``, ``setattr()`` and ``delattr()``, as well as when referencing
+``__dict__`` directly.
 
 
 .. _tut-odds:

Modified: python/branches/py3k-cdecimal/Doc/tutorial/controlflow.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/tutorial/controlflow.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/tutorial/controlflow.rst	Sat Jul 17 12:36:09 2010
@@ -87,7 +87,6 @@
 If you do need to iterate over a sequence of numbers, the built-in function
 :func:`range` comes in handy.  It generates arithmetic progressions::
 
-
     >>> for i in range(5):
     ...     print(i)
     ...
@@ -97,9 +96,7 @@
     3
     4
 
-
-
-The given end point is never part of the generated list; ``range(10)`` generates
+The given end point is never part of the generated sequence; ``range(10)`` generates
 10 values, the legal indices for items of a sequence of length 10.  It
 is possible to let the range start at another number, or to specify a different
 increment (even negative; sometimes this is called the 'step')::

Modified: python/branches/py3k-cdecimal/Doc/tutorial/introduction.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/tutorial/introduction.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/tutorial/introduction.rst	Sat Jul 17 12:36:09 2010
@@ -208,7 +208,7 @@
 
    print(hello)
 
-Note that newlines still need to be embedded in the string using ``\n``; the
+Note that newlines still need to be embedded in the string using ``\n`` -- the
 newline following the trailing backslash is discarded.  This example would print
 the following:
 

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

Modified: python/branches/py3k-cdecimal/Doc/using/mac.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/using/mac.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/using/mac.rst	Sat Jul 17 12:36:09 2010
@@ -114,8 +114,8 @@
 =======
 
 MacPython ships with the standard IDLE development environment. A good
-introduction to using IDLE can be found at http://hkn.eecs.berkeley.edu/
-dyoo/python/idle_intro/index.html.
+introduction to using IDLE can be found at
+http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html.
 
 
 .. _mac-package-manager:

Modified: python/branches/py3k-cdecimal/Doc/whatsnew/2.7.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/whatsnew/2.7.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/whatsnew/2.7.rst	Sat Jul 17 12:36:09 2010
@@ -6,12 +6,11 @@
 :Release: |release|
 :Date: |today|
 
-.. Fix accents on Kristjan Valur Jonsson, Fuerstenau
-
-.. Big jobs: ElementTree 1.3, pep 391, sysconfig
-..  unittest test discovery
 ..  hyperlink all the methods & functions.
 
+.. T_STRING_INPLACE not described in main docs
+.. "Format String Syntax" in string.rst could use many more examples.
+
 .. $Id$
    Rules for maintenance:
 
@@ -54,20 +53,77 @@
    when researching a change.
 
 This article explains the new features in Python 2.7.  The final
-release of 2.7 is currently scheduled for June 2010; the detailed
+release of 2.7 is currently scheduled for July 2010; the detailed
 schedule is described in :pep:`373`.
 
-Python 2.7 is planned to be the last major release in the 2.x series.
-Though more major releases have not been absolutely ruled out, the
-Python maintainers are planning to focus more on Python 3.x.  Despite
-that, it's likely that the 2.7 release will have a longer period of
-maintenance compared to earlier 2.x versions.
-
-.. Compare with previous release in 2 - 3 sentences here.
-   add hyperlink when the documentation becomes available online.
+Numeric handling has been improved in many ways, for both
+floating-point numbers and for the :class:`Decimal` class.  There are
+some useful additions to the standard library, such as a greatly
+enhanced :mod:`unittest` module, the :mod:`argparse` module for
+parsing command-line options, convenient ordered-dictionary and
+:class:`Counter` classes in the :mod:`collections` module, and many
+other improvements.
+
+Python 2.7 is planned to be the last of the 2.x releases, so we worked
+on making it a good release for the long term.  To help with porting
+to Python 3, several new features from the Python 3.x series have been
+included in 2.7.
+
+This article doesn't attempt to provide a complete specification of
+the new features, but instead provides a convenient overview.  For
+full details, you should refer to the documentation for Python 2.7 at
+http://docs.python.org. If you want to understand the rationale for
+the design and implementation, refer to the PEP for a particular new
+feature or the issue on http://bugs.python.org in which a change was
+discussed.  Whenever possible, "What's New in Python" links to the
+bug/patch item for each change.
 
 .. _whatsnew27-python31:
 
+The Future for Python 2.x
+=========================
+
+Python 2.7 is intended to be the last major release in the 2.x series.
+The Python maintainers are planning to focus their future efforts on
+the Python 3.x series.
+
+This means that 2.7 will remain in place for a long time, running
+production systems that have not been ported to Python 3.x.
+Two consequences of the long-term significance of 2.7 are:
+
+* It's very likely the 2.7 release will have a longer period of
+  maintenance compared to earlier 2.x versions.  Python 2.7 will
+  continue to be maintained while the transition to 3.x continues, and
+  the developers are planning to support Python 2.7 with bug-fix
+  releases beyond the typical two years.
+
+* A policy decision was made to silence warnings only of interest to
+  developers.  :exc:`DeprecationWarning` and its
+  descendants are now ignored unless otherwise requested, preventing
+  users from seeing warnings triggered by an application.  This change
+  was also made in the branch that will become Python 3.2. (Discussed
+  on stdlib-sig and carried out in :issue:`7319`.)
+
+  In previous releases, :exc:`DeprecationWarning` messages were
+  enabled by default, providing Python developers with a clear
+  indication of where their code may break in a future major version
+  of Python.
+
+  However, there are increasingly many users of Python-based
+  applications who are not directly involved in the development of
+  those applications.  :exc:`DeprecationWarning` messages are
+  irrelevant to such users, making them worry about an application
+  that's actually working correctly and burdening application developers
+  with responding to these concerns.
+
+  You can re-enable display of :exc:`DeprecationWarning` messages by
+  running Python with the :option:`-Wdefault` (short form:
+  :option:`-Wd`) switch, or by setting the :envvar:`PYTHONWARNINGS`
+  environment variable to ``"default"`` (or ``"d"``) before running
+  Python.  Python code can also re-enable them
+  by calling ``warnings.simplefilter('default')``.
+
+
 Python 3.1 Features
 =======================
 
@@ -78,25 +134,31 @@
 
 A partial list of 3.1 features that were backported to 2.7:
 
-* A version of the :mod:`io` library, rewritten in C for performance.
+* The syntax for set literals (``{1,2,3}`` is a mutable set).
+* Dictionary and set comprehensions (``{ i: i*2 for i in range(3)}``).
+* Multiple context managers in a single :keyword:`with` statement.
+* A new version of the :mod:`io` library, rewritten in C for performance.
 * The ordered-dictionary type described in :ref:`pep-0372`.
-* The new format specifier described in :ref:`pep-0378`.
+* The new ``","`` format specifier described in :ref:`pep-0378`.
 * The :class:`memoryview` object.
-* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
+* 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
+  results more correctly, and :func:`repr` of a floating-point
   number *x* returns a result that's guaranteed to round back to the
-  same number when converted back to a string.
+  same number when converted back to a float.
+* The :ctype:`PyCapsule` type, used to provide a C API for extension modules.
 * The :cfunc:`PyLong_AsLongAndOverflow` C API function.
 
-One porting change: the :option:`-3` switch now automatically
-enables the :option:`-Qwarn` switch that causes warnings
-about using classic division with integers and long integers.
-
 Other new Python3-mode warnings include:
 
 * :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
-  which are not supported in 3.x.
+  which are not supported in 3.x, now trigger warnings.
+* The :option:`-3` switch now automatically
+  enables the :option:`-Qwarn` switch that causes warnings
+  about using classic division with integers and long integers.
+
+
 
 .. ========================================================================
 .. Large, PEP-level features and changes should be described here.
@@ -104,22 +166,22 @@
 
 .. _pep-0372:
 
-PEP 372: Adding an ordered dictionary to collections
+PEP 372: Adding an Ordered Dictionary to collections
 ====================================================
 
 Regular Python dictionaries iterate over key/value pairs in arbitrary order.
 Over the years, a number of authors have written alternative implementations
 that remember the order that the keys were originally inserted.  Based on
-the experiences from those implementations, a new
-:class:`~collections.OrderedDict` class has been introduced in the
-:mod:`collections` module.
+the experiences from those implementations, 2.7 introduces a new
+:class:`~collections.OrderedDict` class in the :mod:`collections` module.
 
-The :class:`~collections.OrderedDict` API is substantially the same as regular
-dictionaries but will iterate over keys and values in a guaranteed order
+The :class:`~collections.OrderedDict` API provides the same interface as regular
+dictionaries but iterates over keys and values in a guaranteed order
 depending on when a key was first inserted::
 
     >>> from collections import OrderedDict
-    >>> d = OrderedDict([('first', 1), ('second', 2),
+    >>> d = OrderedDict([('first', 1),
+    ...                  ('second', 2),
     ...                  ('third', 3)])
     >>> d.items()
     [('first', 1), ('second', 2), ('third', 3)]
@@ -156,9 +218,11 @@
 Comparing two ordered dictionaries checks both the keys and values,
 and requires that the insertion order was the same::
 
-    >>> od1 = OrderedDict([('first', 1), ('second', 2),
+    >>> od1 = OrderedDict([('first', 1),
+    ...                    ('second', 2),
     ...                    ('third', 3)])
-    >>> od2 = OrderedDict([('third', 3), ('first', 1),
+    >>> od2 = OrderedDict([('third', 3),
+    ...                    ('first', 1),
     ...                    ('second', 2)])
     >>> od1 == od2
     False
@@ -176,17 +240,12 @@
 deletion doesn't have to traverse the entire linked list and therefore
 remains O(1).
 
-.. XXX check O(1)-ness with Raymond
-..     Also check if the 'somenamedtuple' in the collection module should
-..     be replaced/removed in order to use
-..     :meth:`~collections.namedtuple._asdict()` (see below)
-
 The standard library now supports use of ordered dictionaries in several
 modules.
 
-* The :mod:`ConfigParser` module uses them by default, letting
-  configuration files be read, modified, and then written back in their original
-  order.
+* The :mod:`ConfigParser` module uses them by default, meaning that
+  configuration files can now read, modified, and then written back
+  in their original order.
 
 * The :meth:`~collections.somenamedtuple._asdict()` method for
   :func:`collections.namedtuple` now returns an ordered dictionary with the
@@ -210,7 +269,7 @@
 =================================================
 
 To make program output more readable, it can be useful to add
-separators to large numbers and render them as
+separators to large numbers, rendering them as
 18,446,744,073,709,551,616 instead of 18446744073709551616.
 
 The fully general solution for doing this is the :mod:`locale` module,
@@ -237,8 +296,6 @@
 comma-formatting mechanism isn't as general as the :mod:`locale`
 module, but it's easier to use.
 
-.. XXX "Format String Syntax" in string.rst could use many more examples.
-
 .. seealso::
 
    :pep:`378` - Format Specifier for Thousands Separator
@@ -248,13 +305,13 @@
 ======================================================
 
 The :mod:`argparse` module for parsing command-line arguments was
-added, intended as a more powerful replacement for the
+added as a more powerful replacement for the
 :mod:`optparse` module.
 
 This means Python now supports three different modules for parsing
 command-line arguments: :mod:`getopt`, :mod:`optparse`, and
 :mod:`argparse`.  The :mod:`getopt` module closely resembles the C
-:cfunc:`getopt` function, so it remains useful if you're writing a
+library's :cfunc:`getopt` function, so it remains useful if you're writing a
 Python prototype that will eventually be rewritten in C.
 :mod:`optparse` becomes redundant, but there are no plans to remove it
 because there are many scripts still using it, and there's no
@@ -306,23 +363,28 @@
       -o FILE     direct output to FILE instead of stdout
       -C NUM      display NUM lines of added context
 
-Similarly to :mod:`optparse`, the command-line switches and arguments
+As with :mod:`optparse`, the command-line switches and arguments
 are returned as an object with attributes named by the *dest* parameters::
 
     -> ./python.exe argparse-example.py -v
-    {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []}
+    {'output': None,
+     'is_verbose': True,
+     'context': 0,
+     'inputs': []}
 
     -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
-    {'output': '/tmp/output', 'is_verbose': True, 'context': 4,
+    {'output': '/tmp/output',
+     'is_verbose': True,
+     'context': 4,
      'inputs': ['file1', 'file2']}
 
 :mod:`argparse` has much fancier validation than :mod:`optparse`; you
 can specify an exact number of arguments as an integer, 0 or more
 arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
 optional argument with ``'?'``.  A top-level parser can contain
-sub-parsers, so you can define subcommands that have different sets of
+sub-parsers to define subcommands that have different sets of
 switches, as in ``svn commit``, ``svn checkout``, etc.  You can
-specify an argument type as :class:`~argparse.FileType`, which will
+specify an argument's type as :class:`~argparse.FileType`, which will
 automatically open files for you and understands that ``'-'`` means
 standard input or output.
 
@@ -331,6 +393,8 @@
    `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
 
    `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
+     Part of the Python documentation, describing how to convert
+     code that uses :mod:`optparse`.
 
    :pep:`389` - argparse - New Command Line Parsing Module
      PEP written and implemented by Steven Bethard.
@@ -338,34 +402,88 @@
 PEP 391: Dictionary-Based Configuration For Logging
 ====================================================
 
-.. not documented in library reference yet.
+.. XXX not documented in library reference yet; add link here once it's added.
 
-The :mod:`logging` module is very flexible; an application can define
+The :mod:`logging` module is very flexible; applications can define
 a tree of logging subsystems, and each logger in this tree can filter
 out certain messages, format them differently, and direct messages to
 a varying number of handlers.
 
 All this flexibility can require a lot of configuration.  You can
 write Python statements to create objects and set their properties,
-but a complex set-up would require verbose but boring code.
+but a complex set-up requires verbose but boring code.
 :mod:`logging` also supports a :func:`~logging.config.fileConfig`
 function that parses a file, but the file format doesn't support
 configuring filters, and it's messier to generate programmatically.
 
 Python 2.7 adds a :func:`~logging.config.dictConfig` function that
-uses a dictionary, and there are many ways to produce a dictionary
-from different sources.  You can construct one with code, of course.
-Python's standard library now includes a JSON parser, so you could
-parse a file containing JSON, or you could use a YAML parsing library
-if one is installed.
+uses a dictionary to configure logging.  There are many ways to
+produce a dictionary from different sources: construct one with code;
+parse a file containing JSON; or use a YAML parsing library if one is
+installed.
+
+The following example configures two loggers, the root logger and a
+logger named "network".   Messages sent to the root logger will be
+sent to the system log using the syslog protocol, and messages
+to the "network" logger will be written to a :file:`network.log` file
+that will be rotated once the log reaches 1Mb.
+
+::
+
+    import logging
+    import logging.config
 
-XXX describe an example.
+    configdict = {
+     'version': 1,    # Configuration schema in use; must be 1 for now
+     'formatters': {
+         'standard': {
+             'format': ('%(asctime)s %(name)-15s '
+                        '%(levelname)-8s %(message)s')}},
+
+     'handlers': {'netlog': {'backupCount': 10,
+                         'class': 'logging.handlers.RotatingFileHandler',
+                         'filename': '/logs/network.log',
+                         'formatter': 'standard',
+                         'level': 'INFO',
+                         'maxBytes': 1024*1024},
+                  'syslog': {'class': 'logging.handlers.SysLogHandler',
+                             'formatter': 'standard',
+                             'level': 'ERROR'}},
+
+     # Specify all the subordinate loggers
+     'loggers': {
+                 'network': {
+                             'handlers': ['netlog']
+                 }
+     },
+     # Specify properties of the root logger
+     'root': {
+              'handlers': ['syslog']
+     },
+    }
+
+    # Set up configuration
+    logging.config.dictConfig(configdict)
+
+    # As an example, log two error messages
+    logger = logging.getLogger('/')
+    logger.error('Database not found')
 
-Two smaller enhancements to the logging module are:
+    netlogger = logging.getLogger('network')
+    netlogger.error('Connection failed')
+
+Three smaller enhancements to the :mod:`logging` module, all
+implemented by Vinay Sajip, are:
 
 .. rev79293
 
-* :class:`Logger` instances gained a :meth:`getChild` that retrieves a
+* The :class:`~logging.handlers.SysLogHandler` class now supports
+  syslogging over TCP.  The constructor has a *socktype* parameter
+  giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
+  for UDP or :const:`socket.SOCK_STREAM` for TCP.  The default
+  protocol remains UDP.
+
+* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
   descendant logger using a relative path.  For example,
   once you retrieve a logger by doing ``log = getLogger('app')``,
   calling ``log.getChild('network.listen')`` is equivalent to
@@ -387,12 +505,10 @@
 are different in Python 3.x.  They return an object called a :dfn:`view`
 instead of a fully materialized list.
 
-.. Views can be iterated over, but they also behave like sets.  XXX not working.
-
 It's not possible to change the return values of :meth:`keys`,
 :meth:`values`, and :meth:`items` in Python 2.7 because too much code
 would break.  Instead the 3.x versions were added under the new names
-of :meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
+:meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
 
 ::
 
@@ -402,6 +518,17 @@
     >>> d.viewkeys()
     dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
 
+Views can be iterated over, but the key and item views also behave
+like sets.  The ``&`` operator performs intersection, and ``|``
+performs a union::
+
+    >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
+    >>> d2 = dict((i**.5, i) for i in range(1000))
+    >>> d1.viewkeys() & d2.viewkeys()
+    set([0.0, 10.0, 20.0, 30.0])
+    >>> d1.viewkeys() | range(0, 30)
+    set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
+
 The view keeps track of the dictionary and its contents change as the
 dictionary is modified::
 
@@ -433,6 +560,58 @@
      Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
 
 
+PEP 3137: The memoryview Object
+====================================================
+
+The :class:`memoryview` object provides a view of another object's
+memory content that matches the :class:`bytes` type's interface.
+
+    >>> import string
+    >>> m = memoryview(string.letters)
+    >>> m
+    <memory at 0x37f850>
+    >>> len(m)           # Returns length of underlying object
+    52
+    >>> m[0], m[25], m[26]   # Indexing returns one byte
+    ('a', 'z', 'A')
+    >>> m2 = m[0:26]         # Slicing returns another memoryview
+    >>> m2
+    <memory at 0x37f080>
+
+The content of the view can be converted to a string of bytes or
+a list of integers:
+
+    >>> m2.tobytes()
+    'abcdefghijklmnopqrstuvwxyz'
+    >>> m2.tolist()
+    [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
+    >>>
+
+:class:`memoryview` objects allow modifying the underlying object if
+it's a mutable object.
+
+    >>> m2[0] = 75
+    Traceback (most recent call last):
+      File "<stdin>", line 1, in <module>
+    TypeError: cannot modify read-only memory
+    >>> b = bytearray(string.letters)  # Creating a mutable object
+    >>> b
+    bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
+    >>> mb = memoryview(b)
+    >>> mb[0] = '*'         # Assign to view, changing the bytearray.
+    >>> b[0:5]              # The bytearray has been changed.
+    bytearray(b'*bcde')
+    >>>
+
+.. seealso::
+
+   :pep:`3137` - Immutable Bytes and Mutable Buffer
+     PEP written by Guido van Rossum.
+     Implemented by Travis Oliphant, Antoine Pitrou and others.
+     Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
+
+
+
 Other Language Changes
 ======================
 
@@ -458,9 +637,9 @@
   3.x, generalizing list/generator comprehensions to use
   the literal syntax for sets and dictionaries.
 
-    >>> {x:x*x for x in range(6)}
+    >>> {x: x*x for x in range(6)}
     {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
-    >>> {'a'*x for x in range(6)}
+    >>> {('a'*x) for x in range(6)}
     set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
 
   Backported by Alexandre Vassalotti; :issue:`2333`.
@@ -490,8 +669,8 @@
   in many different places: :func:`str` on
   floats and complex numbers; the :class:`float` and :class:`complex`
   constructors;
-  numeric formatting; serialization and
-  deserialization of floats and complex numbers using the
+  numeric formatting; serializing and
+  deserializing floats and complex numbers using the
   :mod:`marshal`, :mod:`pickle`
   and :mod:`json` modules;
   parsing of float and imaginary literals in Python code;
@@ -506,7 +685,7 @@
   .. maybe add an example?
 
   The rounding library responsible for this improvement works on
-  Windows, and on Unix platforms using the gcc, icc, or suncc
+  Windows and on Unix platforms using the gcc, icc, or suncc
   compilers.  There may be a small number of platforms where correct
   operation of this code cannot be guaranteed, so the code is not
   used on such systems.  You can find out which code is being used
@@ -516,6 +695,37 @@
   Implemented by Eric Smith and Mark Dickinson, using David Gay's
   :file:`dtoa.c` library; :issue:`7117`.
 
+* Conversions from long integers and regular integers to floating
+  point now round differently, returning the floating-point number
+  closest to the number.  This doesn't matter for small integers that
+  can be converted exactly, but for large numbers that will
+  unavoidably lose precision, Python 2.7 now approximates more
+  closely.  For example, Python 2.6 computed the following::
+
+    >>> n = 295147905179352891391
+    >>> float(n)
+    2.9514790517935283e+20
+    >>> n - long(float(n))
+    65535L
+
+  Python 2.7's floating-point result is larger, but much closer to the
+  true value::
+
+    >>> n = 295147905179352891391
+    >>> float(n)
+    2.9514790517935289e+20
+    >>> n - long(float(n))
+    -1L
+
+  (Implemented by Mark Dickinson; :issue:`3166`.)
+
+  Integer division is also more accurate in its rounding behaviours.  (Also
+  implemented by Mark Dickinson; :issue:`1811`.)
+
+* Implicit coercion for complex numbers has been removed; the interpreter
+  will no longer ever attempt to call a :meth:`__coerce__` method on complex
+  objects.  (Removed by Meador Inge and Mark Dickinson; :issue:`5211`.)
+
 * The :meth:`str.format` method now supports automatic numbering of the replacement
   fields.  This makes using :meth:`str.format` more closely resemble using
   ``%s`` formatting::
@@ -543,6 +753,16 @@
   so it will now produce 'INF' and 'NAN'.
   (Contributed by Eric Smith; :issue:`3382`.)
 
+  A low-level change: the :meth:`object.__format__` method now triggers
+  a :exc:`PendingDeprecationWarning` if it's passed a format string,
+  because the :meth:`__format__` method for :class:`object` converts
+  the object to a string representation and formats that.  Previously
+  the method silently applied the format string to the string
+  representation, but that could hide mistakes in Python code.  If
+  you're supplying formatting information such as an alignment or
+  precision, presumably you're expecting the formatting to be applied
+  in some object-specific way.  (Fixed by Eric Smith; :issue:`7994`.)
+
 * The :func:`int` and :func:`long` types gained a ``bit_length``
   method that returns the number of bits necessary to represent
   its argument in binary::
@@ -560,32 +780,11 @@
 
   (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
 
-* Conversions from long integers and regular integers to floating
-  point now round differently, returning the floating-point number
-  closest to the number.  This doesn't matter for small integers that
-  can be converted exactly, but for large numbers that will
-  unavoidably lose precision, Python 2.7 now approximates more
-  closely.  For example, Python 2.6 computed the following::
-
-    >>> n = 295147905179352891391
-    >>> float(n)
-    2.9514790517935283e+20
-    >>> n - long(float(n))
-    65535L
-
-  Python 2.7's floating-point result is larger, but much closer to the
-  true value::
-
-    >>> n = 295147905179352891391
-    >>> float(n)
-    2.9514790517935289e+20
-    >>> n - long(float(n))
-    -1L
-
-  (Implemented by Mark Dickinson; :issue:`3166`.)
-
-  Integer division is also more accurate in its rounding behaviours.  (Also
-  implemented by Mark Dickinson; :issue:`1811`.)
+* The :keyword:`import` statement will no longer try a relative import
+  if an absolute import (e.g. ``from .os import sep``) fails.  This
+  fixes a bug, but could possibly break certain :keyword:`import`
+  statements that were only working by accident.  (Fixed by Meador Inge;
+  :issue:`7902`.)
 
 * It's now possible for a subclass of the built-in :class:`unicode` type
   to override the :meth:`__unicode__` method.  (Implemented by
@@ -603,9 +802,15 @@
   (Contributed by Amaury Forgeot d'Arc, after a suggestion by
   George Sakkis; :issue:`5982`.)
 
-* A new encoding named "cp720", used primarily for Arabic text, is now
-  supported.  (Contributed by Alexander Belchenko and Amaury Forgeot
-  d'Arc; :issue:`1616979`.)
+* When a restricted set of attributes were set using ``__slots__``,
+  deleting an unset attribute would not raise :exc:`AttributeError`
+  as you would expect.  Fixed by Benjamin Peterson; :issue:`7604`.)
+
+* Two new encodings are now supported: "cp720", used primarily for
+  Arabic text; and "cp858", a variant of CP 850 that adds the euro
+  symbol.  (CP720 contributed by Alexander Belchenko and Amaury
+  Forgeot d'Arc in :issue:`1616979`; CP858 contributed by Tim Hatch in
+  :issue:`8016`.)
 
 * The :class:`file` object will now set the :attr:`filename` attribute
   on the :exc:`IOError` exception when trying to open a directory
@@ -615,7 +820,7 @@
   (fixed by Stefan Krah; :issue:`5677`).
 
 * The Python tokenizer now translates line endings itself, so the
-  :func:`compile` built-in function can now accept code using any
+  :func:`compile` built-in function now accepts code using any
   line-ending convention.  Additionally, it no longer requires that the
   code end in a newline.
 
@@ -648,13 +853,12 @@
 For example, the following setting will print warnings every time
 they occur, but turn warnings from the :mod:`Cookie` module into an
 error.  (The exact syntax for setting an environment variable varies
-across operating systems and shells, so it may be different for you.)
+across operating systems and shells.)
 
 ::
 
   export PYTHONWARNINGS=all,error:::Cookie:0
 
-
 .. ======================================================================
 
 
@@ -678,7 +882,7 @@
   any of them.  This would previously take quadratic
   time for garbage collection, but now the number of full garbage collections
   is reduced as the number of objects on the heap grows.
-  The new logic is to only perform a full garbage collection pass when
+  The new logic only performs a full garbage collection pass when
   the middle generation has been collected 10 times and when the
   number of survivor objects from the middle generation exceeds 10% of
   the number of objects in the oldest generation.  (Suggested by Martin
@@ -788,11 +992,11 @@
   The new version features better Python 3.x compatibility, various bug fixes,
   and adds several new BerkeleyDB flags and methods.
   (Updated by Jesús Cea Avión; :issue:`8156`.  The pybsddb
-  changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
+  changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
 
 * The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
-  management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
-  (Contributed by Hagen Fuerstenau; :issue:`3860`.)
+  management protocol, so you can write ``with bz2.BZ2File(...) as f:``.
+  (Contributed by Hagen Fürstenau; :issue:`3860`.)
 
 * New class: the :class:`~collections.Counter` class in the :mod:`collections`
   module is useful for tallying data.  :class:`~collections.Counter` instances
@@ -816,7 +1020,7 @@
      >>> c['z']
      0
 
-  There are three additional :class:`~collections.Counter` methods:
+  There are three additional :class:`~collections.Counter` methods.
   :meth:`~collections.Counter.most_common` returns the N most common
   elements and their counts.  :meth:`~collections.Counter.elements`
   returns an iterator over the contained elements, repeating each
@@ -843,12 +1047,20 @@
 
   .. revision 79660
 
-  The new :class:`~collections.OrderedDict` class is described in the earlier
+  New class: :class:`~collections.OrderedDict` is described in the earlier
   section :ref:`pep-0372`.
 
+  New method: The :class:`~collections.deque` data type now has a
+  :meth:`~collections.deque.count` method that returns the number of
+  contained elements equal to the supplied argument *x*, and a
+  :meth:`~collections.deque.reverse` method that reverses the elements
+  of the deque in-place.  :class:`deque` also exposes its maximum
+  length as the read-only :attr:`~collections.deque.maxlen` attribute.
+  (Both features added by Raymond Hettinger.)
+
   The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
   If *rename* is true, field names that are invalid because they've
-  been repeated or that aren't legal Python identifiers will be
+  been repeated or aren't legal Python identifiers will be
   renamed to legal names that are derived from the field's
   position within the list of fields:
 
@@ -859,13 +1071,43 @@
 
   (Added by Raymond Hettinger; :issue:`1818`.)
 
-  The :class:`~collections.deque` data type now has a
-  :meth:`~collections.deque.count` method that returns the number of
-  contained elements equal to the supplied argument *x*, and a
-  :meth:`~collections.deque.reverse` method that reverses the elements
-  of the deque in-place.  :class:`deque` also exposes its maximum
-  length as the read-only :attr:`~collections.deque.maxlen` attribute.
-  (Both features added by Raymond Hettinger.)
+  Finally, the :class:`~collections.Mapping` abstract base class now
+  returns :const:`NotImplemented` if a mapping is compared to
+  another type that isn't a :class:`Mapping`.
+  (Fixed by Daniel Stutzbach; :issue:`8729`.)
+
+* Constructors for the parsing classes in the :mod:`ConfigParser` module now
+  take a *allow_no_value* parameter, defaulting to false; if true,
+  options without values will be allowed.  For example::
+
+    >>> import ConfigParser, StringIO
+    >>> sample_config = """
+    ... [mysqld]
+    ... user = mysql
+    ... pid-file = /var/run/mysqld/mysqld.pid
+    ... skip-bdb
+    ... """
+    >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
+    >>> config.readfp(StringIO.StringIO(sample_config))
+    >>> config.get('mysqld', 'user')
+    'mysql'
+    >>> print config.get('mysqld', 'skip-bdb')
+    None
+    >>> print config.get('mysqld', 'unknown')
+    Traceback (most recent call last):
+      ...
+    NoOptionError: No option 'unknown' in section: 'mysqld'
+
+  (Contributed by Mats Kindahl; :issue:`7005`.)
+
+* Deprecated function: :func:`contextlib.nested`, which allows
+  handling more than one context manager with a single :keyword:`with`
+  statement, has been deprecated, because the :keyword:`with` statement
+  now supports multiple context managers.
+
+* The :mod:`cookielib` module now ignores cookies that have an invalid
+  version field, one that doesn't contain an integer value.  (Fixed by
+  John J. Lee; :issue:`3924`.)
 
 * The :mod:`copy` module's :func:`~copy.deepcopy` function will now
   correctly copy bound instance methods.  (Implemented by
@@ -885,7 +1127,7 @@
 * New method: the :class:`~decimal.Decimal` class gained a
   :meth:`~decimal.Decimal.from_float` class method that performs an exact
   conversion of a floating-point number to a :class:`~decimal.Decimal`.
-  Note that this is an **exact** conversion that strives for the
+  This exact conversion strives for the
   closest decimal approximation to the floating-point representation's value;
   the resulting decimal value will therefore still include the inaccuracy,
   if any.
@@ -893,27 +1135,57 @@
   ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
   (Implemented by Raymond Hettinger; :issue:`4796`.)
 
-  Most of the methods of the :class:`~decimal.Context` class now accept integers
-  as well as :class:`~decimal.Decimal` instances; the only exceptions are the
-  :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
-  methods.  (Patch by Juan José Conti; :issue:`7633`.)
+  Comparing instances of :class:`Decimal` with floating-point
+  numbers now produces sensible results based on the numeric values
+  of the operands.  Previously such comparisons would fall back to
+  Python's default rules for comparing objects, which produced arbitrary
+  results based on their type.  Note that you still cannot combine
+  :class:`Decimal` and floating-point in other operations such as addition,
+  since you should be explicitly choosing how to convert between float and
+  :class:`Decimal`.
+  (Fixed by Mark Dickinson; :issue:`2531`.)
 
   The constructor for :class:`~decimal.Decimal` now accepts
   floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
   and non-European Unicode characters such as Arabic-Indic digits
   (contributed by Mark Dickinson; :issue:`6595`).
 
+  Most of the methods of the :class:`~decimal.Context` class now accept integers
+  as well as :class:`~decimal.Decimal` instances; the only exceptions are the
+  :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
+  methods.  (Patch by Juan José Conti; :issue:`7633`.)
+
   When using :class:`~decimal.Decimal` instances with a string's
   :meth:`~str.format` method, the default alignment was previously
-  left-alignment.  This has been changed to right-alignment, which seems
+  left-alignment.  This has been changed to right-alignment, which is
   more sensible for numeric types.  (Changed by Mark Dickinson; :issue:`6857`.)
 
+  Comparisons involving a signaling NaN value (or ``sNAN``) now signal
+  :const:`InvalidOperation` instead of silently returning a true or
+  false value depending on the comparison operator.  Quiet NaN values
+  (or ``NaN``) are now hashable.  (Fixed by Mark Dickinson;
+  :issue:`7279`.)
+
 * The :mod:`difflib` module now produces output that is more
-  compatible with modern :command:`diff`/:command:`patch` tools thanks
-  to two changes: 1) the header giving the filename now uses a tab
-  character instead of spaces as a separator, and 2) the date format
-  used is now ISO-8601 style, ``2005-01-26 23:30:50``.  (Fixed by
-  Anatoly Techtonik; :issue:`7585`.)
+  compatible with modern :command:`diff`/:command:`patch` tools
+  through one small change, using a tab character instead of spaces as
+  a separator in the header giving the filename.  (Fixed by Anatoly
+  Techtonik; :issue:`7585`.)
+
+* The Distutils ``sdist`` command now always regenerates the
+  :file:`MANIFEST` file, since even if the :file:`MANIFEST.in` or
+  :file:`setup.py` files haven't been modified, the user might have
+  created some new files that should be included.
+  (Fixed by Tarek Ziadé; :issue:`8688`.)
+
+* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
+  will now ignore the name of the module containing the exception
+  being tested.  (Patch by Lennart Regebro; :issue:`7490`.)
+
+* The :mod:`email` module's :class:`~email.message.Message` class will
+  now accept a Unicode-valued payload, automatically converting the
+  payload to the encoding specified by :attr:`output_charset`.
+  (Added by R. David Murray; :issue:`1368247`.)
 
 * The :class:`~fractions.Fraction` class now accepts a single float or
   :class:`~decimal.Decimal` instance, or two rational numbers, as
@@ -921,17 +1193,18 @@
   rationals added in :issue:`5812`, and float/decimal in
   :issue:`8294`.)
 
-  An oversight was fixed, making the :class:`Fraction` match the other
-  numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
+  Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
   fractions and complex numbers now raise a :exc:`TypeError`.
+  This fixes an oversight, making the :class:`Fraction` match the other
+  numeric types.
 
   .. revision 79455
 
-* New class: a new :class:`~ftplib.FTP_TLS` class in
+* New class: :class:`~ftplib.FTP_TLS` in
   the :mod:`ftplib` module provides secure FTP
   connections using TLS encapsulation of authentication as well as
   subsequent control and data transfers.
-  (Contributed by Giampaolo Rodola', :issue:`2054`.)
+  (Contributed by Giampaolo Rodola; :issue:`2054`.)
 
   The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
   uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
@@ -957,8 +1230,8 @@
   otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
 
 * The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
-  management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
-  (contributed by Hagen Fuerstenau; :issue:`3860`), and it now implements
+  management protocol, so you can write ``with gzip.GzipFile(...) as f:``
+  (contributed by Hagen Fürstenau; :issue:`3860`), and it now implements
   the :class:`io.BufferedIOBase` ABC, so you can wrap it with
   :class:`io.BufferedReader` for faster processing
   (contributed by Nir Aides; :issue:`7471`).
@@ -973,18 +1246,25 @@
 * New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
   attribute containing a tuple naming the supported algorithms.
   In Python 2.7, ``hashlib.algorithms`` contains
-  ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
+  ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``.
   (Contributed by Carl Chenet; :issue:`7418`.)
 
 * The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
   supports buffering, resulting in much faster reading of HTTP responses.
-  (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
+  (Contributed by Kristján Valur Jónsson; :issue:`4879`.)
 
   The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
   now support a *source_address* parameter, a ``(host, port)`` 2-tuple
   giving the source address that will be used for the connection.
   (Contributed by Eldon Ziegler; :issue:`3972`.)
 
+* The :mod:`ihooks` module now supports relative imports.  Note that
+  :mod:`ihooks` is an older module for customizing imports,
+  superseded by the :mod:`imputil` module added in Python 2.0.
+  (Relative import support added by Neil Schemenauer.)
+
+  .. revision 75423
+
 * The :mod:`imaplib` module now supports IPv6 addresses.
   (Contributed by Derek Morr; :issue:`1655`.)
 
@@ -997,9 +1277,9 @@
     >>> def f(a, b=1, *pos, **named):
     ...     pass
     >>> getcallargs(f, 1, 2, 3)
-    {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
+    {'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
     >>> getcallargs(f, a=2, x=4)
-    {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
+    {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
     >>> getcallargs(f)
     Traceback (most recent call last):
     ...
@@ -1050,8 +1330,8 @@
   floats or :class:`~decimal.Decimal` instances.  (Implemented by Raymond
   Hettinger; :issue:`5032`.)
 
-  :func:`itertools.combinations` and :func:`itertools.product` were
-  previously raising :exc:`ValueError` for values of *r* larger than
+  :func:`itertools.combinations` and :func:`itertools.product`
+  previously raised :exc:`ValueError` for values of *r* larger than
   the input iterable.  This was deemed a specification error, so they
   now return an empty iterator.  (Fixed by Raymond Hettinger; :issue:`4816`.)
 
@@ -1065,6 +1345,12 @@
   with any object literal that decodes to a list of pairs.
   (Contributed by Raymond Hettinger; :issue:`5381`.)
 
+* The :mod:`mailbox` module's :class:`Maildir` class now records the
+  timestamp on the directories it reads, and only re-reads them if the
+  modification time has subsequently changed.  This improves
+  performance by avoiding unneeded directory scans.  (Fixed by
+  A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
+
 * New functions: the :mod:`math` module gained
   :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
   :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
@@ -1095,7 +1381,8 @@
   real, effective, and saved GIDs and UIDs;
   :func:`~os.setresgid` and :func:`~os.setresuid`, which set
   real, effective, and saved GIDs and UIDs to new values;
-  :func:`~os.initgroups`.  (GID/UID functions
+  :func:`~os.initgroups`, which initialize the group access list
+  for the current process.  (GID/UID functions
   contributed by Travis H.; :issue:`6508`.  Support for initgroups added
   by Jean-Paul Calderone; :issue:`7333`.)
 
@@ -1117,6 +1404,20 @@
   now accept an optional *flags* argument, for consistency with the
   other functions in the module.  (Added by Gregory P. Smith.)
 
+* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
+  will execute the code at a provided *path* argument.  *path* can be
+  the path of a Python source file (:file:`example.py`), a compiled
+  bytecode file (:file:`example.pyc`), a directory
+  (:file:`./package/`), or a zip archive (:file:`example.zip`).  If a
+  directory or zip path is provided, it will be added to the front of
+  ``sys.path`` and the module :mod:`__main__` will be imported.  It's
+  expected that the directory or zip contains a :file:`__main__.py`;
+  if it doesn't, some other :file:`__main__.py` might be imported from
+  a location later in ``sys.path``.  This makes more of the machinery
+  of :mod:`runpy` available to scripts that want to mimic the way
+  Python's command line processes an explicit path name.
+  (Added by Nick Coghlan; :issue:`6816`.)
+
 * New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
   takes a filename, archive type (zip or tar-format), and a directory
   path, and creates an archive containing the directory's contents.
@@ -1128,12 +1429,17 @@
   named pipes like a regular file by opening them for reading, and
   this would block indefinitely.  (Fixed by Antoine Pitrou; :issue:`3002`.)
 
+* The :mod:`signal` module no longer re-installs the signal handler
+  unless this is truly necessary, which fixes a bug that could make it
+  impossible to catch the EINTR signal robustly.  (Fixed by
+  Charles-Francois Natali; :issue:`8354`.)
+
 * New functions: in the :mod:`site` module, three new functions
   return various site- and user-specific paths.
   :func:`~site.getsitepackages` returns a list containing all
-  global site-packages directories, and
+  global site-packages directories,
   :func:`~site.getusersitepackages` returns the path of the user's
-  site-packages directory.
+  site-packages directory, and
   :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
   environment variable, giving the path to a directory that can be used
   to store data.
@@ -1144,20 +1450,7 @@
   catch and swallow the :exc:`KeyboardInterrupt` exception.  (Fixed by
   Victor Stinner; :issue:`3137`.)
 
-* The :mod:`socket` module's :class:`~ssl.SSL` objects now support the
-  buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
-  :issue:`7133`).  :class:`SSL` objects also now automatically set
-  OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
-  code being returned from :meth:`recv` operations that trigger an SSL
-  renegotiation (fix by Antoine Pitrou; :issue:`8222`).
-
-  The version of OpenSSL being used is now available as the module
-  attributes :attr:`OPENSSL_VERSION` (a string),
-  :attr:`OPENSSL_VERSION_INFO` (a 5-tuple), and
-  :attr:`OPENSSL_VERSION_NUMBER` (an integer).  (Added by Antoine
-  Pitrou; :issue:`8321`.)
-
-  The :func:`~socket.create_connection` function
+* The :func:`~socket.create_connection` function
   gained a *source_address* parameter, a ``(host, port)`` 2-tuple
   giving the source address that will be used for the connection.
   (Contributed by Eldon Ziegler; :issue:`3972`.)
@@ -1168,11 +1461,16 @@
   Antoine Pitrou; :issue:`8104`.)
 
 * The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
-  has a :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute.
-  The default value is False; if overridden to be True,
+  supports socket timeouts and disabling the Nagle algorithm.
+  The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
+  defaults to False; if overridden to be True,
   new request connections will have the TCP_NODELAY option set to
   prevent buffering many small sends into a single TCP packet.
-  (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
+  The :attr:`~SocketServer.TCPServer.timeout` class attribute can hold
+  a timeout in seconds that will be applied to the request socket; if
+  no request is received within that time, :meth:`handle_timeout`
+  will be called and :meth:`handle_request` will return.
+  (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
 
 * Updated module: the :mod:`sqlite3` module has been updated to
   version 2.6.0 of the `pysqlite package <http://code.google.com/p/pysqlite/>`__. Version 2.6.0 includes a number of bugfixes, and adds
@@ -1181,6 +1479,32 @@
   and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
   (Updated by Gerhard Häring.)
 
+* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the
+  buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
+  :issue:`7133`) and automatically set
+  OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
+  code being returned from :meth:`recv` operations that trigger an SSL
+  renegotiation (fix by Antoine Pitrou; :issue:`8222`).
+
+  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`.)
+
+  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 :mod:`struct` module will no longer silently ignore overflow
   errors when a value is too large for a particular integer format
   code (one of ``bBhHiIlLqQ``); it now always raises a
@@ -1216,6 +1540,10 @@
   false for ones that are implicitly global.
   (Contributed by Jeremy Hylton.)
 
+* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
+  identifier instead of the previous default value of ``'python'``.
+  (Changed by Sean Reifschneider; :issue:`8451`.)
+
 * The ``sys.version_info`` value is now a named tuple, with attributes
   named :attr:`major`, :attr:`minor`, :attr:`micro`,
   :attr:`releaselevel`, and :attr:`serial`.  (Contributed by Ross
@@ -1237,7 +1565,7 @@
 
   :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
   objects being added to a tar file.  When you call :meth:`~tarfile.TarFile.add`,
-  instance, you may supply an optional *filter* argument
+  you may supply an optional *filter* argument
   that's a callable.  The *filter* callable will be passed the
   :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
   If the callable returns ``None``, the file will be excluded from the
@@ -1262,8 +1590,39 @@
   and has been updated to version 5.2.0 (updated by
   Florent Xicluna; :issue:`8024`).
 
-* The :class:`~UserDict.UserDict` class is now a new-style class.  (Changed by
-  Benjamin Peterson.)
+* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
+  unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
+  URL is of the form ``"<something>://..."``, the text before the
+  ``://`` is treated as the scheme, even if it's a made-up scheme that
+  the module doesn't know about.  This change may break code that
+  worked around the old behaviour.  For example, Python 2.6.4 or 2.5
+  will return the following:
+
+    >>> import urlparse
+    >>> urlparse.urlsplit('invented://host/filename?query')
+    ('invented', '', '//host/filename?query', '', '')
+
+  Python 2.7 (and Python 2.6.5) will return:
+
+    >>> import urlparse
+    >>> urlparse.urlsplit('invented://host/filename?query')
+    ('invented', 'host', '/filename?query', '', '')
+
+  (Python 2.7 actually produces slightly different output, since it
+  returns a named tuple instead of a standard tuple.)
+
+  The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
+  :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
+
+    >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
+    ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
+                path='/foo', params='', query='', fragment='')
+
+* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
+  module is a set that only holds weak references to its elements; elements
+  will be removed once there are no references pointing to them.
+  (Originally implemented in Python 3.x by Raymond Hettinger, and backported
+  to 2.7 by Michael Foord.)
 
 * The ElementTree library, :mod:`xml.etree`, no longer escapes
   ampersands and angle brackets when outputting an XML processing
@@ -1271,13 +1630,22 @@
   or comment (which looks like ``<!-- comment -->``).
   (Patch by Neil Muller; :issue:`2746`.)
 
+* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
+  :mod:`SimpleXMLRPCServer` modules, have improved performance by
+  supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
+  to compress the XML being exchanged.  The gzip compression is
+  controlled by the :attr:`encode_threshold` attribute of
+  :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
+  responses larger than this will be compressed.
+  (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
+
 * The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
-  management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
+  management protocol, so you can write ``with zipfile.ZipFile(...) as f:``.
   (Contributed by Brian Curtin; :issue:`5511`.)
 
-  :mod:`zipfile` now supports archiving empty directories and
+  :mod:`zipfile` now also supports archiving empty directories and
   extracts them correctly.  (Fixed by Kuba Wieczorek; :issue:`4710`.)
-  Reading files out of an archive is now faster, and interleaving
+  Reading files out of an archive is faster, and interleaving
   :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
   (Contributed by Nir Aides; :issue:`7610`.)
 
@@ -1291,36 +1659,157 @@
   :issue:`6003`.)
 
 
+.. ======================================================================
+.. whole new modules get described in subsections here
+
+
+.. _importlib-section:
+
+New module: importlib
+------------------------------
+
+Python 3.1 includes the :mod:`importlib` package, a re-implementation
+of the logic underlying Python's :keyword:`import` statement.
+:mod:`importlib` is useful for implementors of Python interpreters and
+to users who wish to write new importers that can participate in the
+import process.  Python 2.7 doesn't contain the complete
+:mod:`importlib` package, but instead has a tiny subset that contains
+a single function, :func:`~importlib.import_module`.
+
+``import_module(name, package=None)`` imports a module.  *name* is
+a string containing the module or package's name.  It's possible to do
+relative imports by providing a string that begins with a ``.``
+character, such as ``..utils.errors``.  For relative imports, the
+*package* argument must be provided and is the name of the package that
+will be used as the anchor for
+the relative import.  :func:`~importlib.import_module` both inserts the imported
+module into ``sys.modules`` and returns the module object.
+
+Here are some examples::
+
+    >>> from importlib import import_module
+    >>> anydbm = import_module('anydbm')  # Standard absolute import
+    >>> anydbm
+    <module 'anydbm' from '/p/python/Lib/anydbm.py'>
+    >>> # Relative import
+    >>> file_util = import_module('..file_util', 'distutils.command')
+    >>> file_util
+    <module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
+
+:mod:`importlib` was implemented by Brett Cannon and introduced in
+Python 3.1.
+
+
 New module: sysconfig
 ---------------------------------
 
-XXX A new :mod:`sysconfig` module has been extracted from
-:mod:`distutils` and put in the standard library.
+The :mod:`sysconfig` module has been pulled out of the Distutils
+package, becoming a new top-level module in its own right.
+:mod:`sysconfig` provides functions for getting information about
+Python's build process: compiler switches, installation paths, the
+platform name, and whether Python is running from its source
+directory.
+
+Some of the functions in the module are:
+
+* :func:`~sysconfig.get_config_var` returns variables from Python's
+  Makefile and the :file:`pyconfig.h` file.
+* :func:`~sysconfig.get_config_vars` returns a dictionary containing
+  all of the configuration variables.
+* :func:`~sysconfig.getpath` returns the configured path for
+  a particular type of module: the standard library,
+  site-specific modules, platform-specific modules, etc.
+* :func:`~sysconfig.is_python_build` returns true if you're running a
+  binary from a Python source tree, and false otherwise.
+
+Consult the :mod:`sysconfig` documentation for more details and for
+a complete list of functions.
+
+The Distutils package and :mod:`sysconfig` are now maintained by Tarek
+Ziadé, who has also started a Distutils2 package (source repository at
+http://hg.python.org/distutils2/) for developing a next-generation
+version of Distutils.
 
-The :mod:`sysconfig` module provides access to Python's configuration
-information like the list of installation paths and the configuration
-variables relevant for the current platform. (contributed by Tarek)
 
-Updated module: ElementTree 1.3
----------------------------------
+ttk: Themed Widgets for Tk
+--------------------------
+
+Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
+widgets but have a more customizable appearance and can therefore more
+closely resemble the native platform's widgets.  This widget
+set was originally called Tile, but was renamed to Ttk (for "themed Tk")
+on being added to Tcl/Tck release 8.5.
 
-XXX write this.
+To learn more, read the :mod:`ttk` module documentation.  You may also
+wish to read the Tcl/Tk manual page describing the
+Ttk theme engine, available at
+http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
+screenshots of the Python/Ttk code in use are at
+http://code.google.com/p/python-ttk/wiki/Screenshots.
 
-.. ======================================================================
-.. whole new modules get described in subsections here
+The :mod:`ttk` module was written by Guilherme Polo and added in
+:issue:`2983`.  An alternate version called ``Tile.py``, written by
+Martin Franklin and maintained by Kevin Walzer, was proposed for
+inclusion in :issue:`2618`, but the authors argued that Guilherme
+Polo's work was more comprehensive.
 
 
-Unit Testing Enhancements
+.. _unittest-section:
+
+Updated module: unittest
 ---------------------------------
 
-The :mod:`unittest` module was enhanced in several ways.
-The progress messages now shows 'x' for expected failures
+The :mod:`unittest` module was greatly enhanced; many
+new features were added.  Most of these features were implemented
+by Michael Foord, unless otherwise noted.  The enhanced version of
+the module is downloadable separately for use with Python versions 2.4 to 2.6,
+packaged as the :mod:`unittest2` package, from
+http://pypi.python.org/pypi/unittest2.
+
+When used from the command line, the module can automatically discover
+tests.  It's not as fancy as `py.test <http://pytest.org>`__ or
+`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
+to run tests kept within a set of package directories.  For example,
+the following command will search the :file:`test/` subdirectory for
+any importable test files named ``test*.py``::
+
+   python -m unittest discover -s test
+
+Consult the :mod:`unittest` module documentation for more details.
+(Developed in :issue:`6001`.)
+
+The :func:`main` function supports some other new options:
+
+* :option:`-b` or :option:`--buffer` will buffer the standard output
+  and standard error streams during each test.  If the test passes,
+  any resulting output will be discarded; on failure, the buffered
+  output will be displayed.
+
+* :option:`-c` or :option:`--catch` will cause the control-C interrupt
+  to be handled more gracefully.  Instead of interrupting the test
+  process immediately, the currently running test will be completed
+  and then the partial results up to the interruption will be reported.
+  If you're impatient, a second press of control-C will cause an immediate
+  interruption.
+
+  This control-C handler tries to avoid causing problems when the code
+  being tested or the tests being run have defined a signal handler of
+  their own, by noticing that a signal handler was already set and
+  calling it.  If this doesn't work for you, there's a
+  :func:`removeHandler` decorator that can be used to mark tests that
+  should have the control-C handling disabled.
+
+* :option:`-f` or :option:`--failfast` makes
+  test execution stop immediately when a test fails instead of
+  continuing to execute further tests.  (Suggested by Cliff Dyer and
+  implemented by Michael Foord; :issue:`8074`.)
+
+The progress messages now show 'x' for expected failures
 and 'u' for unexpected successes when run in verbose mode.
 (Contributed by Benjamin Peterson.)
-Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a test.
-(:issue:`1034053`.)
 
-.. XXX describe test discovery (Contributed by Michael Foord; :issue:`6001`.)
+Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
+test (:issue:`1034053`).
 
 The error messages for :meth:`~unittest.TestCase.assertEqual`,
 :meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
@@ -1330,7 +1819,7 @@
 provide will be printed for failures.  (Added by Michael Foord; :issue:`5663`.)
 
 The :meth:`~unittest.TestCase.assertRaises` method now
-return a context handler when called without providing a callable
+returns a context handler when called without providing a callable
 object to run.  For example, you can write this::
 
   with self.assertRaises(KeyError):
@@ -1350,7 +1839,7 @@
 
 The methods :meth:`~unittest.TestCase.addCleanup` and
 :meth:`~unittest.TestCase.doCleanups` were added.
-:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that
+:meth:`~unittest.TestCase.addCleanup` lets you add cleanup functions that
 will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
 :meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
 for much simpler resource allocation and deallocation during tests
@@ -1382,10 +1871,10 @@
   differences in the two strings.  This comparison is now used by
   default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
 
-* :meth:`~unittest.TestCase.assertRegexpMatches` checks whether its first argument is a
-  string matching a regular expression provided as its second argument.
-
-  .. XXX add assertNotRegexpMatches see issue 8038
+* :meth:`~unittest.TestCase.assertRegexpMatches` and
+  :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
+  first argument is a string matching or not matching the regular
+  expression provided as the second argument (:issue:`8038`).
 
 * :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
   is raised, and then also checks that the string representation of
@@ -1414,9 +1903,10 @@
   all of the key/value pairs in *first* are found in *second*.
 
 * :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
-  whether *first* and *second* are approximately equal by computing
-  their difference, rounding the result to an optionally-specified number
-  of *places* (the default is 7), and comparing to zero.
+  whether *first* and *second* are approximately equal.  This method
+  can either round their difference to an optionally-specified number
+  of *places* (the default is 7) and compare it to zero, or require
+  the difference to be smaller than a supplied *delta* value.
 
 * :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
   :attr:`~unittest.TestLoader.suiteClass` attribute of
@@ -1428,20 +1918,13 @@
   objects being compared are of the specified type.  This function
   should compare the two objects and raise an exception if they don't
   match; it's a good idea for the function to provide additional
-  information about why the two objects are matching, much as the new
+  information about why the two objects aren't matching, much as the new
   sequence comparison methods do.
 
 :func:`unittest.main` now takes an optional ``exit`` argument.  If
-False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be
-used from the interactive interpreter. (Contributed by J. Pablo
-Fernández; :issue:`3379`.)
-
-A new command-line switch, :option:`-f` or :option:`--failfast`, makes
-test execution stop immediately when a test fails instead of
-continuing to execute further tests.  (Suggested by Cliff Dyer and
-implemented by Michael Foord; :issue:`8074`.)
-
-.. XXX document the other new switches
+False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
+:func:`main` to be used from the interactive interpreter.
+(Contributed by J. Pablo Fernández; :issue:`3379`.)
 
 :class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
 :meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
@@ -1450,70 +1933,98 @@
 With all these changes, the :file:`unittest.py` was becoming awkwardly
 large, so the module was turned into a package and the code split into
 several files (by Benjamin Peterson).  This doesn't affect how the
-module is imported.
-
-
-.. _importlib-section:
-
-importlib: Importing Modules
-------------------------------
+module is imported or used.
 
-Python 3.1 includes the :mod:`importlib` package, a re-implementation
-of the logic underlying Python's :keyword:`import` statement.
-:mod:`importlib` is useful for implementors of Python interpreters and
-to users who wish to write new importers that can participate in the
-import process.  Python 2.7 doesn't contain the complete
-:mod:`importlib` package, but instead has a tiny subset that contains
-a single function, :func:`~importlib.import_module`.
-
-``import_module(name, package=None)`` imports a module.  *name* is
-a string containing the module or package's name.  It's possible to do
-relative imports by providing a string that begins with a ``.``
-character, such as ``..utils.errors``.  For relative imports, the
-*package* argument must be provided and is the name of the package that
-will be used as the anchor for
-the relative import.  :func:`~importlib.import_module` both inserts the imported
-module into ``sys.modules`` and returns the module object.
-
-Here are some examples::
-
-    >>> from importlib import import_module
-    >>> anydbm = import_module('anydbm')  # Standard absolute import
-    >>> anydbm
-    <module 'anydbm' from '/p/python/Lib/anydbm.py'>
-    >>> # Relative import
-    >>> sysconfig = import_module('..sysconfig', 'distutils.command')
-    >>> sysconfig
-    <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
-
-:mod:`importlib` was implemented by Brett Cannon and introduced in
-Python 3.1.
-
-
-ttk: Themed Widgets for Tk
---------------------------
-
-Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
-widgets but have a more customizable appearance and can therefore more
-closely resemble the native platform's widgets.  This widget
-set was originally called Tile, but was renamed to Ttk (for "themed Tk")
-on being added to Tcl/Tck release 8.5.
+.. seealso::
 
-XXX write a brief discussion and an example here.
+  http://www.voidspace.org.uk/python/articles/unittest2.shtml
+    Describes the new features, how to use them, and the
+    rationale for various design decisions.  (By Michael Foord.)
 
-The :mod:`ttk` module was written by Guilherme Polo and added in
-:issue:`2983`.  An alternate version called ``Tile.py``, written by
-Martin Franklin and maintained by Kevin Walzer, was proposed for
-inclusion in :issue:`2618`, but the authors argued that Guilherme
-Polo's work was more comprehensive.
+.. _elementtree-section:
 
+Updated module: ElementTree 1.3
+---------------------------------
 
-Deprecations and Removals
-=========================
+The version of the ElementTree library included with Python was updated to
+version 1.3.  Some of the new features are:
 
-* :func:`contextlib.nested`, which allows handling more than one context manager
-  with one :keyword:`with` statement, has been deprecated; :keyword:`with`
-  supports multiple context managers syntactically now.
+* The various parsing functions now take a *parser* keyword argument
+  giving an :class:`XMLParser` instance that will
+  be used.  This makes it possible to override the file's internal encoding::
+
+    p = ET.XMLParser(encoding='utf-8')
+    t = ET.XML("""<root/>""", parser=p)
+
+  Errors in parsing XML now raise a :exc:`ParseError` exception, whose
+  instances have a :attr:`position` attribute
+  containing a (*line*, *column*) tuple giving the location of the problem.
+
+* ElementTree's code for converting trees to a string has been
+  significantly reworked, making it roughly twice as fast in many
+  cases.  The :class:`ElementTree` :meth:`write` and :class:`Element`
+  :meth:`write` methods now have a *method* parameter that can be
+  "xml" (the default), "html", or "text".  HTML mode will output empty
+  elements as ``<empty></empty>`` instead of ``<empty/>``, and text
+  mode will skip over elements and only output the text chunks.  If
+  you set the :attr:`tag` attribute of an element to ``None`` but
+  leave its children in place, the element will be omitted when the
+  tree is written out, so you don't need to do more extensive rearrangement
+  to remove a single element.
+
+  Namespace handling has also been improved.  All ``xmlns:<whatever>``
+  declarations are now output on the root element, not scattered throughout
+  the resulting XML.  You can set the default namespace for a tree
+  by setting the :attr:`default_namespace` attribute and can
+  register new prefixes with :meth:`register_namespace`.  In XML mode,
+  you can use the true/false *xml_declaration* parameter to suppress the
+  XML declaration.
+
+* New :class:`Element` method: :meth:`extend` appends the items from a
+  sequence to the element's children.  Elements themselves behave like
+  sequences, so it's easy to move children from one element to
+  another::
+
+    from xml.etree import ElementTree as ET
+
+    t = ET.XML("""<list>
+      <item>1</item> <item>2</item>  <item>3</item>
+    </list>""")
+    new = ET.XML('<root/>')
+    new.extend(t)
+
+    # Outputs <root><item>1</item>...</root>
+    print ET.tostring(new)
+
+* New :class:`Element` method: :meth:`iter` yields the children of the
+  element as a generator.  It's also possible to write ``for child in
+  elem:`` to loop over an element's children.  The existing method
+  :meth:`getiterator` is now deprecated, as is :meth:`getchildren`
+  which constructs and returns a list of children.
+
+* New :class:`Element` method: :meth:`itertext` yields all chunks of
+  text that are descendants of the element.  For example::
+
+    t = ET.XML("""<list>
+      <item>1</item> <item>2</item>  <item>3</item>
+    </list>""")
+
+    # Outputs ['\n  ', '1', ' ', '2', '  ', '3', '\n']
+    print list(t.itertext())
+
+* Deprecated: using an element as a Boolean (i.e., ``if elem:``) would
+  return true if the element had any children, or false if there were
+  no children.  This behaviour is confusing -- ``None`` is false, but
+  so is a childless element? -- so it will now trigger a
+  :exc:`FutureWarning`.  In your code, you should be explicit: write
+  ``len(elem) != 0`` if you're interested in the number of children,
+  or ``elem is not None``.
+
+Fredrik Lundh develops ElementTree and produced the 1.3 version;
+you can read his article describing 1.3 at
+http://effbot.org/zone/elementtree-13-intro.htm.
+Florent Xicluna updated the version included with
+Python, after discussions on python-dev and in :issue:`6472`.)
 
 .. ======================================================================
 
@@ -1528,9 +2039,9 @@
   <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
   When you begin debugging an executable program P, GDB will look for
   a file named ``P-gdb.py`` and automatically read it.  Dave Malcolm
-  contributed a :file:`python-gdb.py` that adds a number of useful
-  commands when debugging Python itself.  For example, there are
-  ``py-up`` and ``py-down`` that go up or down one Python stack frame,
+  contributed a :file:`python-gdb.py` that adds a number of
+  commands useful when debugging Python itself.  For example,
+  ``py-up`` and ``py-down`` go up or down one Python stack frame,
   which usually corresponds to several C stack frames.  ``py-print``
   prints the value of a Python variable, and ``py-bt`` prints the
   Python stack trace.  (Added as a result of :issue:`8032`.)
@@ -1543,11 +2054,11 @@
 * :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
   worker thread submit notifications to the main Python thread.  This
   is particularly useful for asynchronous IO operations.
-  (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
+  (Contributed by Kristján Valur Jónsson; :issue:`4293`.)
 
 * New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
   only the filename, function name, and first line number are required.
-  This is useful to extension modules that are attempting to
+  This is useful for extension modules that are attempting to
   construct a more useful traceback stack.  Previously such
   extensions needed to call :cfunc:`PyCode_New`, which had many
   more arguments.  (Added by Jeffrey Yasskin.)
@@ -1555,7 +2066,7 @@
 * New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
   exception class, just as the existing :cfunc:`PyErr_NewException` does,
   but takes an extra ``char *`` argument containing the docstring for the
-  new exception class.  (Added by the 'lekma' user on the Python bug tracker;
+  new exception class.  (Added by 'lekma' on the Python bug tracker;
   :issue:`7033`.)
 
 * New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
@@ -1576,6 +2087,28 @@
   :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
   are now deprecated.
 
+* New function: :cfunc:`PySys_SetArgvEx` sets the value of
+  ``sys.argv`` and can optionally update ``sys.path`` to include the
+  directory containing the script named by ``sys.argv[0]`` depending
+  on the value of an *updatepath* parameter.
+
+  This function was added to close a security hole for applications
+  that embed Python.  The old function, :cfunc:`PySys_SetArgv`, would
+  always update ``sys.path``, and sometimes it would add the current
+  directory.  This meant that, if you ran an application embedding
+  Python in a directory controlled by someone else, attackers could
+  put a Trojan-horse module in the directory (say, a file named
+  :file:`os.py`) that your application would then import and run.
+
+  If you maintain a C/C++ application that embeds Python, check
+  whether you're calling :cfunc:`PySys_SetArgv` and carefully consider
+  whether the application should be using :cfunc:`PySys_SetArgvEx`
+  with *updatepath* set to false.
+
+  Security issue reported as `CVE-2008-5983
+  <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_;
+  discussed in :issue:`5753`, and fixed by Antoine Pitrou.
+
 * New macros: the Python header files now define the following macros:
   :cmacro:`Py_ISALNUM`,
   :cmacro:`Py_ISALPHA`,
@@ -1594,9 +2127,14 @@
 
   .. XXX these macros don't seem to be described in the c-api docs.
 
+* Removed function: :cmacro:`PyEval_CallObject` is now only available
+  as a macro.  A function version was being kept around to preserve
+  ABI linking compatibility, but that was in 1997; it can certainly be
+  deleted by now.  (Removed by Antoine Pitrou; :issue:`8276`.)
+
 * New format codes: the :cfunc:`PyFormat_FromString`,
-  :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
-  accepts ``%lld`` and ``%llu`` format codes for displaying values of
+  :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` functions now
+  accept ``%lld`` and ``%llu`` format codes for displaying
   C's :ctype:`long long` types.
   (Contributed by Mark Dickinson; :issue:`7228`.)
 
@@ -1610,7 +2148,7 @@
   ever release the lock, since the other threads weren't replicated,
   and the child process would no longer be able to perform imports.
 
-  Python 2.7 now acquires the import lock before performing an
+  Python 2.7 acquires the import lock before performing an
   :func:`os.fork`, and will also clean up any locks created using the
   :mod:`threading` module.  C extension modules that have internal
   locks, or that call :cfunc:`fork()` themselves, will not benefit
@@ -1623,6 +2161,12 @@
   being raised when an interpreter shuts down.
   (Patch by Adam Olsen; :issue:`1722344`.)
 
+* When using the :ctype:`PyMemberDef` structure to define attributes
+  of a type, Python will no longer let you try to delete or set a
+  :const:`T_STRING_INPLACE` attribute.
+
+  .. rev 79644
+
 * Global symbols defined by the :mod:`ctypes` module are now prefixed
   with ``Py``, or with ``_ctypes``.  (Implemented by Thomas
   Heller; :issue:`3102`.)
@@ -1631,15 +2175,15 @@
   building the :mod:`pyexpat` module to use the system Expat library.
   (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
 
-* New configure option: compiling Python with the
+* New configure option: the
   :option:`--with-valgrind` option will now disable the pymalloc
   allocator, which is difficult for the Valgrind memory-error detector
   to analyze correctly.
   Valgrind will therefore be better at detecting memory leaks and
   overruns. (Contributed by James Henstridge; :issue:`2422`.)
 
-* New configure option: you can now supply no arguments to
-  :option:`--with-dbmliborder=` in order to build none of the various
+* New configure option: you can now supply an empty string to
+  :option:`--with-dbmliborder=` in order to disable all of the various
   DBM modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
   :issue:`6491`.)
 
@@ -1660,6 +2204,52 @@
   Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
 
 
+.. _whatsnew27-capsules:
+
+Capsules
+-------------------
+
+Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a
+C API to an extension module.  A capsule is essentially the holder of
+a C ``void *`` pointer, and is made available as a module attribute; for
+example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
+and :mod:`unicodedata` exposes ``ucnhash_CAPI``.  Other extensions
+can import the module, access its dictionary to get the capsule
+object, and then get the ``void *`` pointer, which will usually point
+to an array of pointers to the module's various API functions.
+
+There is an existing data type already used for this,
+:ctype:`PyCObject`, but it doesn't provide type safety.  Evil code
+written in pure Python could cause a segmentation fault by taking a
+:ctype:`PyCObject` from module A and somehow substituting it for the
+:ctype:`PyCObject` in module B.   Capsules know their own name,
+and getting the pointer requires providing the name::
+
+   void *vtable;
+
+   if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
+           PyErr_SetString(PyExc_ValueError, "argument type invalid");
+           return NULL;
+   }
+
+   vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
+
+You are assured that ``vtable`` points to whatever you're expecting.
+If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would
+detect the mismatched name and return false.  Refer to
+:ref:`using-capsules` for more information on using these objects.
+
+Python 2.7 now uses capsules internally to provide various
+extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was
+modified to handle capsules, preserving compile-time compatibility
+with the :ctype:`CObject` interface.  Use of
+:cfunc:`PyCObject_AsVoidPtr` will signal a
+:exc:`PendingDeprecationWarning`, which is silent by default.
+
+Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
+discussed in :issue:`5630`.
+
+
 .. ======================================================================
 
 Port-Specific Changes: Windows
@@ -1672,16 +2262,24 @@
   and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
   (Contributed by David Cournapeau; :issue:`4365`.)
 
+* The :mod:`_winreg` module for accessing the registry now implements
+  the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
+  versions of previously-supported functions that take several extra
+  arguments.  The :func:`DisableReflectionKey`,
+  :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
+  tested and documented.
+  (Implemented by Brian Curtin: :issue:`7347`.)
+
 * The new :cfunc:`_beginthreadex` API is used to start threads, and
   the native thread-local storage functions are now used.
-  (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
+  (Contributed by Kristján Valur Jónsson; :issue:`3582`.)
 
 * The :func:`os.kill` function now works on Windows.  The signal value
   can be the constants :const:`CTRL_C_EVENT`,
-  :const:`CTRL_BREAK_EVENT`, or any integer.  The Control-C and
-  Control-Break keystroke events can be sent to subprocesses; any
-  other value will use the :cfunc:`TerminateProcess` API.
-  (Contributed by Miki Tebeka; :issue:`1220212`.)
+  :const:`CTRL_BREAK_EVENT`, or any integer.  The first two constants
+  will send Control-C and Control-Break keystroke events to
+  subprocesses; any other value will use the :cfunc:`TerminateProcess`
+  API.  (Contributed by Miki Tebeka; :issue:`1220212`.)
 
 * The :func:`os.listdir` function now correctly fails
   for an empty path.  (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
@@ -1700,18 +2298,29 @@
   installation and a user-installed copy of the same version.
   (Changed by Ronald Oussoren; :issue:`4865`.)
 
+Port-Specific Changes: FreeBSD
+-----------------------------------
+
+* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
+  :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
+  alternate routing table, is now available in the :mod:`socket`
+  module.  (Added by Kyle VanderBeek; :issue:`8235`.)
 
 Other Changes and Fixes
 =======================
 
 * Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
   added to the :file:`Tools` directory.  :file:`iobench` measures the
-  speed of built-in file I/O objects (as returned by :func:`open`)
+  speed of the built-in file I/O objects returned by :func:`open`
   while performing various operations, and :file:`ccbench` is a
   concurrency benchmark that tries to measure computing throughput,
   thread switching latency, and IO processing bandwidth when
   performing several tasks using a varying number of threads.
 
+* The :file:`Tools/i18n/msgfmt.py` script now understands plural
+  forms in :file:`.po` files.  (Fixed by Martin von Löwis;
+  :issue:`5464`.)
+
 * When importing a module from a :file:`.pyc` or :file:`.pyo` file
   with an existing :file:`.py` counterpart, the :attr:`co_filename`
   attributes of the resulting code objects are overwritten when the
@@ -1747,14 +2356,13 @@
 This section lists previously described changes and other bugfixes
 that may require changes to your code:
 
-* When using :class:`Decimal` instances with a string's
-  :meth:`format` method, the default alignment was previously
-  left-alignment.  This has been changed to right-alignment, which might
-  change the output of your programs.
-  (Changed by Mark Dickinson; :issue:`6857`.)
+* The :func:`range` function processes its arguments more
+  consistently; it will now call :meth:`__int__` on non-float,
+  non-integer arguments that are supplied to it.  (Fixed by Alexander
+  Belopolsky; :issue:`1533`.)
 
-  Another :meth:`format`-related change: the default precision used
-  for floating-point and complex numbers was changed from 6 decimal
+* The string :meth:`format` method changed the default precision used
+  for floating-point and complex numbers from 6 decimal
   places to 12, which matches the precision used by :func:`str`.
   (Changed by Eric Smith; :issue:`5920`.)
 
@@ -1764,18 +2372,79 @@
   affects new-style classes (derived from :class:`object`) and C extension
   types.  (:issue:`6101`.)
 
-* The :meth:`readline` method of :class:`StringIO` objects now does
-  nothing when a negative length is requested, as other file-like
-  objects do.  (:issue:`7348`).
+* Due to a bug in Python 2.6, the *exc_value* parameter to
+  :meth:`__exit__` methods was often the string representation of the
+  exception, not an instance.  This was fixed in 2.7, so *exc_value*
+  will be an instance as expected.  (Fixed by Florent Xicluna;
+  :issue:`7853`.)
+
+* When a restricted set of attributes were set using ``__slots__``,
+  deleting an unset attribute would not raise :exc:`AttributeError`
+  as you would expect.  Fixed by Benjamin Peterson; :issue:`7604`.)
 
 In the standard library:
 
+* Operations with :class:`datetime` instances that resulted in a year
+  falling outside the supported range didn't always raise
+  :exc:`OverflowError`.  Such errors are now checked more carefully
+  and will now raise the exception. (Reported by Mark Leander, patch
+  by Anand B. Pillai and Alexander Belopolsky; :issue:`7150`.)
+
+* When using :class:`Decimal` instances with a string's
+  :meth:`format` method, the default alignment was previously
+  left-alignment.  This has been changed to right-alignment, which might
+  change the output of your programs.
+  (Changed by Mark Dickinson; :issue:`6857`.)
+
+  Comparisons involving a signaling NaN value (or ``sNAN``) now signal
+  :const:`InvalidOperation` instead of silently returning a true or
+  false value depending on the comparison operator.  Quiet NaN values
+  (or ``NaN``) are now hashable.  (Fixed by Mark Dickinson;
+  :issue:`7279`.)
+
 * The ElementTree library, :mod:`xml.etree`, no longer escapes
   ampersands and angle brackets when outputting an XML processing
   instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
   or comment (which looks like `<!-- comment -->`).
   (Patch by Neil Muller; :issue:`2746`.)
 
+* The :meth:`readline` method of :class:`StringIO` objects now does
+  nothing when a negative length is requested, as other file-like
+  objects do.  (:issue:`7348`).
+
+* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
+  identifier instead of the previous default value of ``'python'``.
+  (Changed by Sean Reifschneider; :issue:`8451`.)
+
+* The :mod:`tarfile` module's default error handling has changed, to
+  no longer suppress fatal errors.  The default error level was previously 0,
+  which meant that errors would only result in a message being written to the
+  debug log, but because the debug log is not activated by default,
+  these errors go unnoticed.  The default error level is now 1,
+  which raises an exception if there's an error.
+  (Changed by Lars Gustäbel; :issue:`7357`.)
+
+* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
+  unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
+  URL is of the form ``"<something>://..."``, the text before the
+  ``://`` is treated as the scheme, even if it's a made-up scheme that
+  the module doesn't know about.  This change may break code that
+  worked around the old behaviour.  For example, Python 2.6.4 or 2.5
+  will return the following:
+
+    >>> import urlparse
+    >>> urlparse.urlsplit('invented://host/filename?query')
+    ('invented', '', '//host/filename?query', '', '')
+
+  Python 2.7 (and Python 2.6.5) will return:
+
+    >>> import urlparse
+    >>> urlparse.urlsplit('invented://host/filename?query')
+    ('invented', 'host', '/filename?query', '', '')
+
+  (Python 2.7 actually produces slightly different output, since it
+  returns a named tuple instead of a standard tuple.)
+
 For C extensions:
 
 * C extensions that use integer format codes with the ``PyArg_Parse*``
@@ -1786,6 +2455,14 @@
   :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
   which are now deprecated.
 
+For applications that embed Python:
+
+* The :cfunc:`PySys_SetArgvEx` function was added, letting
+  applications close a security hole when the existing
+  :cfunc:`PySys_SetArgv` function was used.  Check whether you're
+  calling :cfunc:`PySys_SetArgv` and carefully consider whether the
+  application should be using :cfunc:`PySys_SetArgvEx` with
+  *updatepath* set to false.
 
 .. ======================================================================
 
@@ -1797,5 +2474,6 @@
 
 The author would like to thank the following people for offering
 suggestions, corrections and assistance with various drafts of this
-article: Ryan Lovett, R. David Murray, Hugh Secker-Walker.
+article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
+Hugh Secker-Walker.
 

Modified: python/branches/py3k-cdecimal/Doc/whatsnew/3.0.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/whatsnew/3.0.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/whatsnew/3.0.rst	Sat Jul 17 12:36:09 2010
@@ -798,6 +798,15 @@
 * A new built-in function :func:`next` was added to call the
   :meth:`__next__` method on an object.
 
+* The :func:`round` function rounding strategy and return type have
+  changed.  Exact halfway cases are now rounded to the nearest even
+  result instead of away from zero.  (For example, ``round(2.5)`` now
+  returns ``2`` rather than ``3``.)  :func:`round(x[, n])` now
+  delegates to ``x.__round__([n])`` instead of always returning a
+  float.  It generally returns an integer when called with a single
+  argument and a value of the same type as ``x`` when called with two
+  arguments.
+
 * Moved :func:`intern` to :func:`sys.intern`.
 
 * Removed: :func:`apply`.  Instead of ``apply(f, args)`` use

Modified: python/branches/py3k-cdecimal/Doc/whatsnew/3.2.rst
==============================================================================
--- python/branches/py3k-cdecimal/Doc/whatsnew/3.2.rst	(original)
+++ python/branches/py3k-cdecimal/Doc/whatsnew/3.2.rst	Sat Jul 17 12:36:09 2010
@@ -173,7 +173,8 @@
 
 * bytearray objects cannot be used anymore as filenames: convert them to bytes
 
-* "t#" format of PyArg_Parse*() functions has been removed: use "s#" or "s*"
-  instead
+* PyArg_Parse*() functions:
+
+  * "t#" format has been removed: use "s#" or "s*" instead
+  * "w" and "w#" formats has been removed: use "w*" instead
 
-* Stub

Modified: python/branches/py3k-cdecimal/Grammar/Grammar
==============================================================================
--- python/branches/py3k-cdecimal/Grammar/Grammar	(original)
+++ python/branches/py3k-cdecimal/Grammar/Grammar	Sat Jul 17 12:36:09 2010
@@ -11,9 +11,9 @@
 # "How to Change Python's Grammar"
 
 # Start symbols for the grammar:
-#	single_input is a single interactive statement;
-#	file_input is a module or sequence of commands read from an input file;
-#	eval_input is the input for the eval() and input() functions.
+#       single_input is a single interactive statement;
+#       file_input is a module or sequence of commands read from an input file;
+#       eval_input is the input for the eval() and input() functions.
 # NB: compound_stmt in single_input is followed by extra NEWLINE!
 single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
 file_input: (NEWLINE | stmt)* ENDMARKER
@@ -24,13 +24,13 @@
 decorated: decorators (classdef | funcdef)
 funcdef: 'def' NAME parameters ['->' test] ':' suite
 parameters: '(' [typedargslist] ')'
-typedargslist: ((tfpdef ['=' test] ',')*
-                ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
-                | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
+typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
+       ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]]
+     |  '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
 tfpdef: NAME [':' test]
-varargslist: ((vfpdef ['=' test] ',')*
-              ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] | '**' vfpdef)
-              | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
+varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [','
+       ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]]
+     |  '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
 vfpdef: NAME
 
 stmt: simple_stmt | compound_stmt
@@ -71,9 +71,9 @@
 for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
 try_stmt: ('try' ':' suite
            ((except_clause ':' suite)+
-	    ['else' ':' suite]
-	    ['finally' ':' suite] |
-	   'finally' ':' suite))
+            ['else' ':' suite]
+            ['finally' ':' suite] |
+           'finally' ':' suite))
 with_stmt: 'with' with_item (',' with_item)*  ':' suite
 with_item: test ['as' expr]
 # NB compile.c makes sure that the default except clause is last

Modified: python/branches/py3k-cdecimal/Include/longobject.h
==============================================================================
--- python/branches/py3k-cdecimal/Include/longobject.h	(original)
+++ python/branches/py3k-cdecimal/Include/longobject.h	Sat Jul 17 12:36:09 2010
@@ -58,7 +58,7 @@
 #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"
 #endif /* SIZEOF_PID_T */
 
-/* For use by intobject.c only */
+/* Used by Python/mystrtoul.c. */
 PyAPI_DATA(unsigned char) _PyLong_DigitValue[256];
 
 /* _PyLong_Frexp returns a double x and an exponent e such that the

Modified: python/branches/py3k-cdecimal/Include/pyctype.h
==============================================================================
--- python/branches/py3k-cdecimal/Include/pyctype.h	(original)
+++ python/branches/py3k-cdecimal/Include/pyctype.h	Sat Jul 17 12:36:09 2010
@@ -11,6 +11,9 @@
 
 extern const unsigned int _Py_ctype_table[256];
 
+/* Unlike their C counterparts, the following macros are not meant to
+ * handle an int with any of the values [EOF, 0-UCHAR_MAX]. The argument
+ * must be a signed/unsigned char. */
 #define Py_ISLOWER(c)  (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_LOWER)
 #define Py_ISUPPER(c)  (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_UPPER)
 #define Py_ISALPHA(c)  (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALPHA)

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

Modified: python/branches/py3k-cdecimal/Include/traceback.h
==============================================================================
--- python/branches/py3k-cdecimal/Include/traceback.h	(original)
+++ python/branches/py3k-cdecimal/Include/traceback.h	Sat Jul 17 12:36:09 2010
@@ -10,16 +10,16 @@
 /* Traceback interface */
 
 typedef struct _traceback {
-	PyObject_HEAD
-	struct _traceback *tb_next;
-	struct _frame *tb_frame;
-	int tb_lasti;
-	int tb_lineno;
+    PyObject_HEAD
+    struct _traceback *tb_next;
+    struct _frame *tb_frame;
+    int tb_lasti;
+    int tb_lineno;
 } PyTracebackObject;
 
 PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *);
 PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *);
-PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, const char *, int, int);
+PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, PyObject *, int, int);
 
 /* Reveal traceback type so we can typecheck traceback objects */
 PyAPI_DATA(PyTypeObject) PyTraceBack_Type;

Modified: python/branches/py3k-cdecimal/Include/unicodeobject.h
==============================================================================
--- python/branches/py3k-cdecimal/Include/unicodeobject.h	(original)
+++ python/branches/py3k-cdecimal/Include/unicodeobject.h	Sat Jul 17 12:36:09 2010
@@ -498,14 +498,14 @@
     Py_ssize_t size             /* size of buffer */
     );
 
-/* Similar to PyUnicode_FromUnicode(), but u points to Latin-1 encoded bytes */
+/* Similar to PyUnicode_FromUnicode(), but u points to UTF-8 encoded bytes */
 PyAPI_FUNC(PyObject*) PyUnicode_FromStringAndSize(
     const char *u,        /* char buffer */
     Py_ssize_t size       /* size of buffer */
     );
 
 /* Similar to PyUnicode_FromUnicode(), but u points to null-terminated
-   Latin-1 encoded bytes */
+   UTF-8 encoded bytes */
 PyAPI_FUNC(PyObject*) PyUnicode_FromString(
     const char *u        /* string */
     );
@@ -550,7 +550,7 @@
 
    Coercion is done in the following way:
 
-   1. String and other char buffer compatible objects are decoded
+   1. bytes, bytearray and other char buffer compatible objects are decoded
       under the assumptions that they contain data using the current
       default encoding. Decoding is done in "strict" mode.
 
@@ -574,7 +574,7 @@
    Unicode objects are passed back as-is (subclasses are converted to
    true Unicode objects), all other objects are delegated to
    PyUnicode_FromEncodedObject(obj, NULL, "strict") which results in
-   using the default encoding as basis for decoding the object.
+   using UTF-8 encoding as basis for decoding the object.
 
    The API returns NULL in case of an error. The caller is responsible
    for decref'ing the returned objects.
@@ -606,7 +606,7 @@
 
 #ifdef HAVE_WCHAR_H
 
-/* Create a Unicode Object from the whcar_t buffer w of the given
+/* Create a Unicode Object from the wchar_t buffer w of the given
    size.
 
    The buffer is copied into the new object. */
@@ -665,7 +665,7 @@
    parameters encoding and errors have the same semantics as the ones
    of the builtin unicode() API.
 
-   Setting encoding to NULL causes the default encoding to be used.
+   Setting encoding to NULL causes the default encoding (UTF-8) to be used.
 
    Error handling is set by errors which may also be set to NULL
    meaning to use the default handling defined for the codec. Default

Modified: python/branches/py3k-cdecimal/Lib/_abcoll.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/_abcoll.py	(original)
+++ python/branches/py3k-cdecimal/Lib/_abcoll.py	Sat Jul 17 12:36:09 2010
@@ -480,7 +480,15 @@
         except KeyError:
             pass
 
-    def update(self, other=(), **kwds):
+    def update(*args, **kwds):
+        if len(args) > 2:
+            raise TypeError("update() takes at most 2 positional "
+                            "arguments ({} given)".format(len(args)))
+        elif not args:
+            raise TypeError("update() takes at least 1 argument (0 given)")
+        self = args[0]
+        other = args[1] if len(args) >= 2 else ()
+
         if isinstance(other, Mapping):
             for key in other:
                 self[key] = other[key]

Modified: python/branches/py3k-cdecimal/Lib/_strptime.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/_strptime.py	(original)
+++ python/branches/py3k-cdecimal/Lib/_strptime.py	Sat Jul 17 12:36:09 2010
@@ -16,7 +16,9 @@
 from re import compile as re_compile
 from re import IGNORECASE, ASCII
 from re import escape as re_escape
-from datetime import date as datetime_date
+from datetime import (date as datetime_date,
+                      timedelta as datetime_timedelta,
+                      timezone as datetime_timezone)
 try:
     from _thread import allocate_lock as _thread_allocate_lock
 except:
@@ -204,6 +206,7 @@
             #XXX: Does 'Y' need to worry about having less or more than
             #     4 digits?
             'Y': r"(?P<Y>\d\d\d\d)",
+            'z': r"(?P<z>[+-]\d\d[0-5]\d)",
             'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
             'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
             'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
@@ -293,7 +296,9 @@
 
 
 def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
-    """Return a time struct based on the input string and the format string."""
+    """Return a 2-tuple consisting of a time struct and an int containing
+    the number of microseconds based on the input string and the
+    format string."""
 
     for index, arg in enumerate([data_string, format]):
         if not isinstance(arg, str):
@@ -333,10 +338,12 @@
     if len(data_string) != found.end():
         raise ValueError("unconverted data remains: %s" %
                           data_string[found.end():])
+
     year = 1900
     month = day = 1
     hour = minute = second = fraction = 0
     tz = -1
+    tzoffset = None
     # Default to -1 to signify that values not known; not critical to have,
     # though
     week_of_year = -1
@@ -417,6 +424,11 @@
             else:
                 # W starts week on Monday.
                 week_of_year_start = 0
+        elif group_key == 'z':
+            z = found_dict['z']
+            tzoffset = int(z[1:3]) * 60 + int(z[3:5])
+            if z.startswith("-"):
+                tzoffset = -tzoffset
         elif group_key == 'Z':
             # Since -1 is default value only need to worry about setting tz if
             # it can be something other than -1.
@@ -453,9 +465,35 @@
         day = datetime_result.day
     if weekday == -1:
         weekday = datetime_date(year, month, day).weekday()
-    return (time.struct_time((year, month, day,
-                              hour, minute, second,
-                              weekday, julian, tz)), fraction)
+    # Add timezone info
+    tzname = found_dict.get("Z")
+    if tzoffset is not None:
+        gmtoff = tzoffset * 60
+    else:
+        gmtoff = None
+
+    return (year, month, day,
+            hour, minute, second,
+            weekday, julian, tz, gmtoff, tzname), fraction
 
 def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
-    return _strptime(data_string, format)[0]
+    """Return a time struct based on the input string and the
+    format string."""
+    tt = _strptime(data_string, format)[0]
+    return time.struct_time(tt[:9])
+
+def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
+    """Return a class cls instance based on the input string and the
+    format string."""
+    tt, fraction = _strptime(data_string, format)
+    gmtoff, tzname = tt[-2:]
+    args = tt[:6] + (fraction,)
+    if gmtoff is not None:
+        tzdelta = datetime_timedelta(seconds=gmtoff)
+        if tzname:
+            tz = datetime_timezone(tzdelta, tzname)
+        else:
+            tz = datetime_timezone(tzdelta)
+        args += (tz,)
+
+    return cls(*args)

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

Modified: python/branches/py3k-cdecimal/Lib/contextlib.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/contextlib.py	(original)
+++ python/branches/py3k-cdecimal/Lib/contextlib.py	Sat Jul 17 12:36:09 2010
@@ -4,9 +4,20 @@
 from functools import wraps
 from warnings import warn
 
-__all__ = ["contextmanager", "closing"]
+__all__ = ["contextmanager", "closing", "ContextDecorator"]
 
-class GeneratorContextManager(object):
+
+class ContextDecorator(object):
+    "A base class or mixin that enables context managers to work as decorators."
+    def __call__(self, func):
+        @wraps(func)
+        def inner(*args, **kwds):
+            with self:
+                return func(*args, **kwds)
+        return inner
+
+
+class GeneratorContextManager(ContextDecorator):
     """Helper for @contextmanager decorator."""
 
     def __init__(self, gen):

Modified: python/branches/py3k-cdecimal/Lib/ctypes/__init__.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/ctypes/__init__.py	(original)
+++ python/branches/py3k-cdecimal/Lib/ctypes/__init__.py	Sat Jul 17 12:36:09 2010
@@ -265,7 +265,7 @@
     pass
 else:
     if _os.name in ("nt", "ce"):
-        set_conversion_mode("mbcs", "ignore")
+        set_conversion_mode("mbcs", "strict")
     else:
         set_conversion_mode("ascii", "strict")
 

Modified: python/branches/py3k-cdecimal/Lib/ctypes/test/test_callbacks.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/ctypes/test/test_callbacks.py	(original)
+++ python/branches/py3k-cdecimal/Lib/ctypes/test/test_callbacks.py	Sat Jul 17 12:36:09 2010
@@ -166,6 +166,41 @@
 
         self.assertTrue(diff < 0.01, "%s not less than 0.01" % diff)
 
+    def test_issue_8959_a(self):
+        from ctypes.util import find_library
+        libc_path = find_library("c")
+        if not libc_path:
+            return # cannot test
+        libc = CDLL(libc_path)
+
+        @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
+        def cmp_func(a, b):
+            return a[0] - b[0]
+
+        array = (c_int * 5)(5, 1, 99, 7, 33)
+
+        libc.qsort(array, len(array), sizeof(c_int), cmp_func)
+        self.assertEqual(array[:], [1, 5, 7, 33, 99])
+
+    try:
+        WINFUNCTYPE
+    except NameError:
+        pass
+    else:
+        def test_issue_8959_b(self):
+            from ctypes.wintypes import BOOL, HWND, LPARAM
+            global windowCount
+            windowCount = 0
+
+            @WINFUNCTYPE(BOOL, HWND, LPARAM)
+            def EnumWindowsCallbackFunc(hwnd, lParam):
+                global windowCount
+                windowCount += 1
+                return True #Allow windows to keep enumerating
+
+            windll.user32.EnumWindows(EnumWindowsCallbackFunc, 0)
+            self.assertFalse(windowCount == 0)
+
 ################################################################
 
 if __name__ == '__main__':

Modified: python/branches/py3k-cdecimal/Lib/ctypes/test/test_win32.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/ctypes/test/test_win32.py	(original)
+++ python/branches/py3k-cdecimal/Lib/ctypes/test/test_win32.py	Sat Jul 17 12:36:09 2010
@@ -6,6 +6,32 @@
 
 import _ctypes_test
 
+if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int):
+    # Only windows 32-bit has different calling conventions.
+
+    class WindowsTestCase(unittest.TestCase):
+        def test_callconv_1(self):
+            # Testing stdcall function
+
+            IsWindow = windll.user32.IsWindow
+            # ValueError: Procedure probably called with not enough arguments (4 bytes missing)
+            self.assertRaises(ValueError, IsWindow)
+
+            # This one should succeeed...
+            self.assertEqual(0, IsWindow(0))
+
+            # ValueError: Procedure probably called with too many arguments (8 bytes in excess)
+            self.assertRaises(ValueError, IsWindow, 0, 0, 0)
+
+        def test_callconv_2(self):
+            # Calling stdcall function as cdecl
+
+            IsWindow = cdll.user32.IsWindow
+
+            # ValueError: Procedure called with not enough arguments (4 bytes missing)
+            # or wrong calling convention
+            self.assertRaises(ValueError, IsWindow, None)
+
 if sys.platform == "win32":
     class FunctionCallTestCase(unittest.TestCase):
 

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

Modified: python/branches/py3k-cdecimal/Lib/dis.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/dis.py	(original)
+++ python/branches/py3k-cdecimal/Lib/dis.py	Sat Jul 17 12:36:09 2010
@@ -12,6 +12,22 @@
 
 _have_code = (types.MethodType, types.FunctionType, types.CodeType, type)
 
+def _try_compile(source, name):
+    """Attempts to compile the given source, first as an expression and
+       then as a statement if the first approach fails.
+
+       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:
+        c = compile(source, name, 'exec')
+    return c
+
 def dis(x=None):
     """Disassemble classes, methods, functions, or code.
 
@@ -38,7 +54,9 @@
     elif hasattr(x, 'co_code'):
         disassemble(x)
     elif isinstance(x, (bytes, bytearray)):
-        disassemble_string(x)
+        _disassemble_bytes(x)
+    elif isinstance(x, str):
+        _disassemble_str(x)
     else:
         raise TypeError("don't know how to disassemble %s objects" %
                         type(x).__name__)
@@ -157,7 +175,7 @@
                 print('(' + free[oparg] + ')', end=' ')
         print()
 
-def disassemble_string(code, lasti=-1, varnames=None, names=None,
+def _disassemble_bytes(code, lasti=-1, varnames=None, names=None,
                        constants=None):
     labels = findlabels(code)
     n = len(code)
@@ -196,6 +214,10 @@
                 print('(' + cmp_op[oparg] + ')', end=' ')
         print()
 
+def _disassemble_str(source):
+    """Compile the source string, then disassemble the code object."""
+    disassemble(_try_compile(source, '<dis>'))
+
 disco = disassemble                     # XXX For backwards compatibility
 
 def findlabels(code):

Modified: python/branches/py3k-cdecimal/Lib/distutils/command/install.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/distutils/command/install.py	(original)
+++ python/branches/py3k-cdecimal/Lib/distutils/command/install.py	Sat Jul 17 12:36:09 2010
@@ -302,8 +302,8 @@
         # about needing recursive variable expansion (shudder).
 
         py_version = sys.version.split()[0]
-        prefix, exec_prefix, srcdir = get_config_vars('prefix', 'exec_prefix',
-                                                      'srcdir')
+        prefix, exec_prefix, srcdir, projectbase = get_config_vars('prefix', 'exec_prefix',
+                                                      'srcdir', 'projectbase')
 
         self.config_vars = {'dist_name': self.distribution.get_name(),
                             'dist_version': self.distribution.get_version(),
@@ -316,6 +316,7 @@
                             'sys_exec_prefix': exec_prefix,
                             'exec_prefix': exec_prefix,
                             'srcdir': srcdir,
+                            'projectbase': projectbase,
                            }
 
         self.config_vars['userbase'] = self.install_userbase

Modified: python/branches/py3k-cdecimal/Lib/distutils/msvc9compiler.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/distutils/msvc9compiler.py	(original)
+++ python/branches/py3k-cdecimal/Lib/distutils/msvc9compiler.py	Sat Jul 17 12:36:09 2010
@@ -37,9 +37,18 @@
          winreg.HKEY_LOCAL_MACHINE,
          winreg.HKEY_CLASSES_ROOT)
 
-VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
-WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
-NET_BASE = r"Software\Microsoft\.NETFramework"
+NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32)
+if NATIVE_WIN64:
+    # Visual C++ is a 32-bit application, so we need to look in
+    # the corresponding registry branch, if we're running a
+    # 64-bit Python on Win64
+    VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f"
+    WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows"
+    NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework"
+else:
+    VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
+    WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
+    NET_BASE = r"Software\Microsoft\.NETFramework"
 
 # A map keyed by get_platform() return values to values accepted by
 # 'vcvarsall.bat'.  Note a cross-compile may combine these (eg, 'x86_amd64' is

Modified: python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py	(original)
+++ python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py	Sat Jul 17 12:36:09 2010
@@ -346,6 +346,7 @@
         finally:
             archive.close()
 
+    @unittest.skipUnless(zlib, "requires zlib")
     def test_get_file_list(self):
         # make sure MANIFEST is recalculated
         dist, cmd = self.get_cmd()

Modified: python/branches/py3k-cdecimal/Lib/distutils/unixccompiler.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/distutils/unixccompiler.py	(original)
+++ python/branches/py3k-cdecimal/Lib/distutils/unixccompiler.py	Sat Jul 17 12:36:09 2010
@@ -340,7 +340,9 @@
             static = os.path.join(dir, static_f)
 
             if sys.platform == 'darwin' and (
-                    dir.startswith('/System/') or dir.startswith('/usr/')):
+                dir.startswith('/System/') or (
+                dir.startswith('/usr/') and not dir.startswith('/usr/local/'))):
+
                 shared = os.path.join(sysroot, dir[1:], shared_f)
                 dylib = os.path.join(sysroot, dir[1:], dylib_f)
                 static = os.path.join(sysroot, dir[1:], static_f)

Modified: python/branches/py3k-cdecimal/Lib/email/feedparser.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/email/feedparser.py	(original)
+++ python/branches/py3k-cdecimal/Lib/email/feedparser.py	Sat Jul 17 12:36:09 2010
@@ -28,7 +28,7 @@
 
 NLCRE = re.compile('\r\n|\r|\n')
 NLCRE_bol = re.compile('(\r\n|\r|\n)')
-NLCRE_eol = re.compile('(\r\n|\r|\n)$')
+NLCRE_eol = re.compile('(\r\n|\r|\n)\Z')
 NLCRE_crack = re.compile('(\r\n|\r|\n)')
 # RFC 2822 $3.6.8 Optional fields.  ftext is %d33-57 / %d59-126, Any character
 # except controls, SP, and ":".
@@ -104,6 +104,10 @@
         # data after the final RE.  In the case of a NL/CR terminated string,
         # this is the empty string.
         self._partial = parts.pop()
+        #GAN 29Mar09  bugs 1555570, 1721862  Confusion at 8K boundary ending with \r:
+        # is there a \n to follow later?
+        if not self._partial and parts and parts[-1].endswith('\r'):
+            self._partial = parts.pop(-2)+parts.pop()
         # parts is a list of strings, alternating between the line contents
         # and the eol character(s).  Gather up a list of lines after
         # re-attaching the newlines.

Modified: python/branches/py3k-cdecimal/Lib/email/test/test_email.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/email/test/test_email.py	(original)
+++ python/branches/py3k-cdecimal/Lib/email/test/test_email.py	Sat Jul 17 12:36:09 2010
@@ -2454,6 +2454,39 @@
 -Me
 """)
 
+    def test_pushCR_LF(self):
+        '''FeedParser BufferedSubFile.push() assumed it received complete
+           line endings.  A CR ending one push() followed by a LF starting
+           the next push() added an empty line.
+        '''
+        imt = [
+            ("a\r \n",  2),
+            ("b",       0),
+            ("c\n",     1),
+            ("",        0),
+            ("d\r\n",   1),
+            ("e\r",     0),
+            ("\nf",     1),
+            ("\r\n",    1),
+          ]
+        from email.feedparser import BufferedSubFile, NeedMoreData
+        bsf = BufferedSubFile()
+        om = []
+        nt = 0
+        for il, n in imt:
+            bsf.push(il)
+            nt += n
+            n1 = 0
+            while True:
+                ol = bsf.readline()
+                if ol == NeedMoreData:
+                    break
+                om.append(ol)
+                n1 += 1
+            self.assertTrue(n == n1)
+        self.assertTrue(len(om) == nt)
+        self.assertTrue(''.join([il for il, n in imt]) == ''.join(om))
+
 
 
 class TestParsers(TestEmailBase):
@@ -2588,6 +2621,24 @@
         eq(headers, ['A', 'B', 'CC'])
         eq(msg.get_payload(), 'body')
 
+    def test_CRLFLF_at_end_of_part(self):
+        # issue 5610: feedparser should not eat two chars from body part ending
+        # with "\r\n\n".
+        m = (
+            "From: foo at bar.com\n"
+            "To: baz\n"
+            "Mime-Version: 1.0\n"
+            "Content-Type: multipart/mixed; boundary=BOUNDARY\n"
+            "\n"
+            "--BOUNDARY\n"
+            "Content-Type: text/plain\n"
+            "\n"
+            "body ending with CRLF newline\r\n"
+            "\n"
+            "--BOUNDARY--\n"
+          )
+        msg = email.message_from_string(m)
+        self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n'))
 
 
 class TestBase64(unittest.TestCase):

Modified: python/branches/py3k-cdecimal/Lib/encodings/aliases.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/encodings/aliases.py	(original)
+++ python/branches/py3k-cdecimal/Lib/encodings/aliases.py	Sat Jul 17 12:36:09 2010
@@ -146,6 +146,11 @@
     'csibm857'           : 'cp857',
     'ibm857'             : 'cp857',
 
+    # cp858 codec
+    '858'                : 'cp858',
+    'csibm858'           : 'cp858',
+    'ibm858'             : 'cp858',
+
     # cp860 codec
     '860'                : 'cp860',
     'csibm860'           : 'cp860',

Modified: python/branches/py3k-cdecimal/Lib/fnmatch.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/fnmatch.py	(original)
+++ python/branches/py3k-cdecimal/Lib/fnmatch.py	Sat Jul 17 12:36:09 2010
@@ -12,10 +12,16 @@
 
 import re
 
-__all__ = ["filter", "fnmatch","fnmatchcase","translate"]
+__all__ = ["filter", "fnmatch", "fnmatchcase", "purge", "translate"]
 
 _cache = {}  # Maps text patterns to compiled regexen.
 _cacheb = {}  # Ditto for bytes patterns.
+_MAXCACHE = 100 # Maximum size of caches
+
+def purge():
+    """Clear the pattern cache"""
+    _cache.clear()
+    _cacheb.clear()
 
 def fnmatch(name, pat):
     """Test whether FILENAME matches PATTERN.
@@ -48,6 +54,8 @@
             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
 

Modified: python/branches/py3k-cdecimal/Lib/heapq.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/heapq.py	(original)
+++ python/branches/py3k-cdecimal/Lib/heapq.py	Sat Jul 17 12:36:09 2010
@@ -1,5 +1,3 @@
-# -*- coding: latin-1 -*-
-
 """Heap queue algorithm (a.k.a. priority queue).
 
 Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
@@ -34,7 +32,7 @@
 
 __about__ = """Heap queues
 
-[explanation by François Pinard]
+[explanation by François Pinard]
 
 Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
 all k, counting elements from 0.  For the sake of comparison,

Modified: python/branches/py3k-cdecimal/Lib/http/cookiejar.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/http/cookiejar.py	(original)
+++ python/branches/py3k-cdecimal/Lib/http/cookiejar.py	Sat Jul 17 12:36:09 2010
@@ -436,6 +436,13 @@
         if attr: headers.append("; ".join(attr))
     return ", ".join(headers)
 
+def strip_quotes(text):
+    if text.startswith('"'):
+        text = text[1:]
+    if text.endswith('"'):
+        text = text[:-1]
+    return text
+
 def parse_ns_headers(ns_headers):
     """Ad-hoc parser for Netscape protocol cookie-attributes.
 
@@ -453,7 +460,7 @@
     """
     known_attrs = ("expires", "domain", "path", "secure",
                    # RFC 2109 attrs (may turn up in Netscape cookies, too)
-                   "port", "max-age")
+                   "version", "port", "max-age")
 
     result = []
     for ns_header in ns_headers:
@@ -473,12 +480,11 @@
                     k = lc
                 if k == "version":
                     # This is an RFC 2109 cookie.
+                    v = strip_quotes(v)
                     version_set = True
                 if k == "expires":
                     # convert expires date to seconds since epoch
-                    if v.startswith('"'): v = v[1:]
-                    if v.endswith('"'): v = v[:-1]
-                    v = http2time(v)  # None if invalid
+                    v = http2time(strip_quotes(v))  # None if invalid
             pairs.append((k, v))
 
         if pairs:
@@ -1446,7 +1452,11 @@
 
         # set the easy defaults
         version = standard.get("version", None)
-        if version is not None: version = int(version)
+        if version is not None:
+            try:
+                version = int(version)
+            except ValueError:
+                return None  # invalid version, ignore cookie
         secure = standard.get("secure", False)
         # (discard is also set if expires is Absent)
         discard = standard.get("discard", False)

Modified: python/branches/py3k-cdecimal/Lib/idlelib/textView.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/idlelib/textView.py	(original)
+++ python/branches/py3k-cdecimal/Lib/idlelib/textView.py	Sat Jul 17 12:36:09 2010
@@ -62,11 +62,7 @@
 
 def view_file(parent, title, filename, encoding=None):
     try:
-        if encoding:
-            import codecs
-            textFile = codecs.open(filename, 'r')
-        else:
-            textFile = open(filename, 'r')
+        textFile = open(filename, 'r', encoding=encoding)
     except IOError:
         import tkinter.messagebox as tkMessageBox
         tkMessageBox.showerror(title='File Load Error',

Modified: python/branches/py3k-cdecimal/Lib/importlib/__init__.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/__init__.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/__init__.py	Sat Jul 17 12:36:09 2010
@@ -36,7 +36,7 @@
     """
     if 'PYTHONCASEOK' in os.environ:
         return True
-    elif check in os.listdir(directory):
+    elif check in os.listdir(directory if directory else os.getcwd()):
         return True
     return False
 

Modified: python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py	Sat Jul 17 12:36:09 2010
@@ -22,7 +22,7 @@
 def _path_join(*args):
     """Replacement for os.path.join."""
     return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x
-                            for x in args)
+                            for x in args if x)
 
 
 def _path_exists(path):
@@ -53,6 +53,8 @@
 # XXX Could also expose Modules/getpath.c:isdir()
 def _path_isdir(path):
     """Replacement for os.path.isdir."""
+    if not path:
+        path = _os.getcwd()
     return _path_is_mode_type(path, 0o040000)
 
 
@@ -99,6 +101,8 @@
     new.__dict__.update(old.__dict__)
 
 
+code_type = type(_wrap.__code__)
+
 # Finder/loader utility code ##################################################
 
 def set_package(fxn):
@@ -138,7 +142,7 @@
     the second argument.
 
     """
-    def decorated(self, fullname):
+    def decorated(self, fullname, *args, **kwargs):
         module = sys.modules.get(fullname)
         is_reload = bool(module)
         if not is_reload:
@@ -148,7 +152,7 @@
             module = imp.new_module(fullname)
             sys.modules[fullname] = module
         try:
-            return fxn(self, module)
+            return fxn(self, module, *args, **kwargs)
         except:
             if not is_reload:
                 del sys.modules[fullname]
@@ -301,258 +305,227 @@
         return imp.is_frozen_package(fullname)
 
 
-class PyLoader:
+class _LoaderBasics:
 
-    """Loader base class for Python source code.
+    """Base class of common code needed by both SourceLoader and
+    _SourcelessFileLoader."""
 
-    Subclasses need to implement the methods:
+    def is_package(self, fullname):
+        """Concrete implementation of InspectLoader.is_package by checking if
+        the path returned by get_filename has a filename of '__init__.py'."""
+        filename = self.get_filename(fullname).rpartition(path_sep)[2]
+        return filename.rsplit('.', 1)[0] == '__init__'
+
+    def _bytes_from_bytecode(self, fullname, data, source_mtime):
+        """Return the marshalled bytes from bytecode, verifying the magic
+        number and timestamp alon the way.
 
-    - source_path
-    - get_data
-    - is_package
+        If source_mtime is None then skip the timestamp check.
 
-    """
+        """
+        magic = data[:4]
+        raw_timestamp = data[4:8]
+        if len(magic) != 4 or magic != imp.get_magic():
+            raise ImportError("bad magic number in {}".format(fullname))
+        elif len(raw_timestamp) != 4:
+            raise EOFError("bad timestamp in {}".format(fullname))
+        elif source_mtime is not None:
+            if marshal._r_long(raw_timestamp) != source_mtime:
+                raise ImportError("bytecode is stale for {}".format(fullname))
+        # Can't return the code object as errors from marshal loading need to
+        # propagate even when source is available.
+        return data[8:]
 
     @module_for_loader
-    def load_module(self, module):
-        """Initialize the module."""
+    def _load_module(self, module, *, sourceless=False):
+        """Helper for load_module able to handle either source or sourceless
+        loading."""
         name = module.__name__
-        code_object = self.get_code(module.__name__)
+        code_object = self.get_code(name)
         module.__file__ = self.get_filename(name)
+        if not sourceless:
+            module.__cached__ = imp.cache_from_source(module.__file__)
+        else:
+            module.__cached__ = module.__file__
+        module.__package__ = name
         if self.is_package(name):
-            module.__path__  = [module.__file__.rsplit(path_sep, 1)[0]]
-        module.__package__ = module.__name__
-        if not hasattr(module, '__path__'):
+            module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
+        else:
             module.__package__ = module.__package__.rpartition('.')[0]
         module.__loader__ = self
         exec(code_object, module.__dict__)
         return module
 
-    def get_filename(self, fullname):
-        """Return the path to the source file, else raise ImportError."""
-        path = self.source_path(fullname)
-        if path is not None:
-            return path
-        else:
-            raise ImportError("no source path available for "
-                                "{0!r}".format(fullname))
 
-    def get_code(self, fullname):
-        """Get a code object from source."""
-        source_path = self.source_path(fullname)
-        if source_path is None:
-            message = "a source path must exist to load {0}".format(fullname)
-            raise ImportError(message)
-        source = self.get_data(source_path)
-        return compile(source, source_path, 'exec', dont_inherit=True)
+class SourceLoader(_LoaderBasics):
 
-    # Never use in implementing import! Imports code within the method.
-    def get_source(self, fullname):
-        """Return the source code for a module.
+    def path_mtime(self, path:str) -> int:
+        """Optional method that returns the modification time for the specified
+        path.
 
-        self.source_path() and self.get_data() are used to implement this
-        method.
+        Implementing this method allows the loader to read bytecode files.
 
         """
-        path = self.source_path(fullname)
-        if path is None:
-            return None
-        try:
-            source_bytes = self.get_data(path)
-        except IOError:
-            return ImportError("source not available through get_data()")
-        import io
-        import tokenize
-        encoding = tokenize.detect_encoding(io.BytesIO(source_bytes).readline)
-        return source_bytes.decode(encoding[0])
+        raise NotImplementedError
 
+    def set_data(self, path:str, data:bytes) -> None:
+        """Optional method which writes data to a file path.
 
-class PyPycLoader(PyLoader):
+        Implementing this method allows for the writing of bytecode files.
 
-    """Loader base class for Python source and bytecode.
+        """
+        raise NotImplementedError
 
-    Requires implementing the methods needed for PyLoader as well as
-    source_mtime, bytecode_path, and write_bytecode.
 
-    """
-
-    def get_filename(self, fullname):
-        """Return the source or bytecode file path."""
-        path = self.source_path(fullname)
-        if path is not None:
-            return path
-        path = self.bytecode_path(fullname)
-        if path is not None:
-            return path
-        raise ImportError("no source or bytecode path available for "
-                            "{0!r}".format(fullname))
+    def get_source(self, fullname):
+        """Concrete implementation of InspectLoader.get_source."""
+        import tokenize
+        path = self.get_filename(fullname)
+        try:
+            source_bytes = self.get_data(path)
+        except IOError:
+            raise ImportError("source not available through get_data()")
+        encoding = tokenize.detect_encoding(_io.BytesIO(source_bytes).readline)
+        newline_decoder = _io.IncrementalNewlineDecoder(None, True)
+        return newline_decoder.decode(source_bytes.decode(encoding[0]))
 
     def get_code(self, fullname):
-        """Get a code object from source or bytecode."""
-        # XXX Care enough to make sure this call does not happen if the magic
-        #     number is bad?
-        source_timestamp = self.source_mtime(fullname)
-        # Try to use bytecode if it is available.
-        bytecode_path = self.bytecode_path(fullname)
-        if bytecode_path:
-            data = self.get_data(bytecode_path)
+        """Concrete implementation of InspectLoader.get_code.
+
+        Reading of bytecode requires path_mtime to be implemented. To write
+        bytecode, set_data must also be implemented.
+
+        """
+        source_path = self.get_filename(fullname)
+        bytecode_path = imp.cache_from_source(source_path)
+        source_mtime = None
+        if bytecode_path is not None:
             try:
-                magic = data[:4]
-                if len(magic) < 4:
-                    raise ImportError("bad magic number in {}".format(fullname))
-                raw_timestamp = data[4:8]
-                if len(raw_timestamp) < 4:
-                    raise EOFError("bad timestamp in {}".format(fullname))
-                pyc_timestamp = marshal._r_long(raw_timestamp)
-                bytecode = data[8:]
-                # Verify that the magic number is valid.
-                if imp.get_magic() != magic:
-                    raise ImportError("bad magic number in {}".format(fullname))
-                # Verify that the bytecode is not stale (only matters when
-                # there is source to fall back on.
-                if source_timestamp:
-                    if pyc_timestamp < source_timestamp:
-                        raise ImportError("bytecode is stale")
-            except (ImportError, EOFError):
-                # If source is available give it a shot.
-                if source_timestamp is not None:
+                source_mtime = self.path_mtime(source_path)
+            except NotImplementedError:
+                pass
+            else:
+                try:
+                    data = self.get_data(bytecode_path)
+                except IOError:
                     pass
                 else:
-                    raise
-            else:
-                # Bytecode seems fine, so try to use it.
-                # XXX If the bytecode is ill-formed, would it be beneficial to
-                #     try for using source if available and issue a warning?
-                return marshal.loads(bytecode)
-        elif source_timestamp is None:
-            raise ImportError("no source or bytecode available to create code "
-                                "object for {0!r}".format(fullname))
-        # Use the source.
-        code_object = super().get_code(fullname)
-        # Generate bytecode and write it out.
-        if not sys.dont_write_bytecode:
+                    try:
+                        bytes_data = self._bytes_from_bytecode(fullname, data,
+                                                               source_mtime)
+                    except (ImportError, EOFError):
+                        pass
+                    else:
+                        found = marshal.loads(bytes_data)
+                        if isinstance(found, code_type):
+                            return found
+                        else:
+                            msg = "Non-code object in {}"
+                            raise ImportError(msg.format(bytecode_path))
+        source_bytes = self.get_data(source_path)
+        code_object = compile(source_bytes, source_path, 'exec',
+                                dont_inherit=True)
+        if (not sys.dont_write_bytecode and bytecode_path is not None and
+                source_mtime is not None):
+            # If e.g. Jython ever implements imp.cache_from_source to have
+            # their own cached file format, this block of code will most likely
+            # throw an exception.
             data = bytearray(imp.get_magic())
-            data.extend(marshal._w_long(source_timestamp))
+            data.extend(marshal._w_long(source_mtime))
             data.extend(marshal.dumps(code_object))
-            self.write_bytecode(fullname, data)
+            try:
+                self.set_data(bytecode_path, data)
+            except NotImplementedError:
+                pass
         return code_object
 
+    def load_module(self, fullname):
+        """Concrete implementation of Loader.load_module.
 
-class _PyFileLoader(PyLoader):
+        Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be
+        implemented to load source code. Use of bytecode is dictated by whether
+        get_code uses/writes bytecode.
 
-    """Load a Python source file."""
+        """
+        return self._load_module(fullname)
 
-    def __init__(self, name, path, is_pkg):
-        self._name = name
-        self._is_pkg = is_pkg
-        # Figure out the base path based on whether it was source or bytecode
-        # that was found.
-        try:
-            self._base_path = _path_without_ext(path, imp.PY_SOURCE)
-        except ValueError:
-            self._base_path = _path_without_ext(path, imp.PY_COMPILED)
-
-    def _find_path(self, ext_type):
-        """Find a path from the base path and the specified extension type that
-        exists, returning None if one is not found."""
-        for suffix in _suffix_list(ext_type):
-            path = self._base_path + suffix
-            if _path_exists(path):
-                return path
-        else:
-            return None
+
+class _FileLoader:
+
+    """Base file loader class which implements the loader protocol methods that
+    require file system usage."""
+
+    def __init__(self, fullname, path):
+        """Cache the module name and the path to the file found by the
+        finder."""
+        self._name = fullname
+        self._path = path
 
     @_check_name
-    def source_path(self, fullname):
-        """Return the path to an existing source file for the module, or None
-        if one cannot be found."""
-        # Not a property so that it is easy to override.
-        return self._find_path(imp.PY_SOURCE)
+    def get_filename(self, fullname):
+        """Return the path to the source file as found by the finder."""
+        return self._path
 
     def get_data(self, path):
         """Return the data from path as raw bytes."""
-        return _io.FileIO(path, 'r').read()  # Assuming bytes.
+        with _closing(_io.FileIO(path, 'r')) as file:
+            return file.read()
 
-    @_check_name
-    def is_package(self, fullname):
-        """Return a boolean based on whether the module is a package.
 
-        Raises ImportError (like get_source) if the loader cannot handle the
-        package.
+class _SourceFileLoader(_FileLoader, SourceLoader):
 
-        """
-        return self._is_pkg
+    """Concrete implementation of SourceLoader using the file system."""
 
+    def path_mtime(self, path):
+        """Return the modification time for the path."""
+        return int(_os.stat(path).st_mtime)
 
-class _PyPycFileLoader(PyPycLoader, _PyFileLoader):
+    def set_data(self, path, data):
+        """Write bytes data to a file."""
+        try:
+            with _closing(_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:
+                raise
 
-    """Load a module from a source or bytecode file."""
 
-    def _find_path(self, ext_type):
-        """Return PEP 3147 path if ext_type is PY_COMPILED, otherwise
-        super()._find_path() is called."""
-        if ext_type == imp.PY_COMPILED:
-            # We don't really care what the extension on self._base_path is,
-            # as long as it has exactly one dot.
-            source_path = self._base_path + '.py'
-            pycache_path = imp.cache_from_source(source_path)
-            legacy_path = self._base_path + '.pyc'
-            # The rule is: if the source file exists, then Python always uses
-            # the __pycache__/foo.<tag>.pyc file.  If the source file does not
-            # exist, then Python uses the legacy path.
-            pyc_path = (pycache_path
-                        if _path_exists(source_path)
-                        else legacy_path)
-            return (pyc_path if _path_exists(pyc_path) else None)
-        return super()._find_path(ext_type)
+class _SourcelessFileLoader(_FileLoader, _LoaderBasics):
 
-    @_check_name
-    def source_mtime(self, name):
-        """Return the modification time of the source for the specified
-        module."""
-        source_path = self.source_path(name)
-        if not source_path:
-            return None
-        return int(_os.stat(source_path).st_mtime)
+    """Loader which handles sourceless file imports."""
 
-    @_check_name
-    def bytecode_path(self, fullname):
-        """Return the path to a bytecode file, or None if one does not
-        exist."""
-        # Not a property for easy overriding.
-        return self._find_path(imp.PY_COMPILED)
-
-    @_check_name
-    def write_bytecode(self, name, data):
-        """Write out 'data' for the specified module, returning a boolean
-        signifying if the write-out actually occurred.
+    def load_module(self, fullname):
+        return self._load_module(fullname, sourceless=True)
 
-        Raises ImportError (just like get_source) if the specified module
-        cannot be handled by the loader.
+    def get_code(self, fullname):
+        path = self.get_filename(fullname)
+        data = self.get_data(path)
+        bytes_data = self._bytes_from_bytecode(fullname, data, None)
+        found = marshal.loads(bytes_data)
+        if isinstance(found, code_type):
+            return found
+        else:
+            raise ImportError("Non-code object in {}".format(path))
 
-        """
-        bytecode_path = self.bytecode_path(name)
-        if not bytecode_path:
-            source_path = self.source_path(name)
-            bytecode_path = imp.cache_from_source(source_path)
-            # Ensure that the __pycache__ directory exists.  We can't use
-            # os.path.dirname() here.
-            dirname, sep, basename = bytecode_path.rpartition(path_sep)
-            try:
-                _os.mkdir(dirname)
-            except OSError as error:
-                if error.errno != errno.EEXIST:
-                    raise
-        try:
-            # Assuming bytes.
-            with _closing(_io.FileIO(bytecode_path, 'w')) as bytecode_file:
-                bytecode_file.write(data)
-                return True
-        except IOError as exc:
-            if exc.errno == errno.EACCES:
-                return False
-            else:
-                raise
+    def get_source(self, fullname):
+        """Return None as there is no source code."""
+        return None
 
 
 class _ExtensionFileLoader:
@@ -563,7 +536,7 @@
 
     """
 
-    def __init__(self, name, path, is_pkg):
+    def __init__(self, name, path):
         """Initialize the loader.
 
         If is_pkg is True then an exception is raised as extension modules
@@ -572,8 +545,6 @@
         """
         self._name = name
         self._path = path
-        if is_pkg:
-            raise ValueError("extension modules cannot be packages")
 
     @_check_name
     @set_package
@@ -671,147 +642,88 @@
             return None
 
 
-class _ChainedFinder:
-
-    """Finder that sequentially calls other finders."""
-
-    def __init__(self, *finders):
-        self._finders = finders
-
-    def find_module(self, fullname, path=None):
-        for finder in self._finders:
-            result = finder.find_module(fullname, path)
-            if result:
-                return result
-        else:
-            return None
-
-
 class _FileFinder:
 
-    """Base class for file finders.
-
-    Subclasses are expected to define the following attributes:
-
-        * _suffixes
-            Sequence of file suffixes whose order will be followed.
+    """File-based finder.
 
-        * _possible_package
-            True if importer should check for packages.
-
-        * _loader
-            A callable that takes the module name, a file path, and whether
-            the path points to a package and returns a loader for the module
-            found at that path.
+    Constructor takes a list of objects detailing what file extensions their
+    loader supports along with whether it can be used for a package.
 
     """
 
-    def __init__(self, path_entry):
-        """Initialize an importer for the passed-in sys.path entry (which is
-        assumed to have already been verified as an existing directory).
-
-        Can be used as an entry on sys.path_hook.
+    def __init__(self, path, *details):
+        """Initialize with finder details."""
+        packages = []
+        modules = []
+        for detail in details:
+            modules.extend((suffix, detail.loader) for suffix in detail.suffixes)
+            if detail.supports_packages:
+                packages.extend((suffix, detail.loader)
+                                for suffix in detail.suffixes)
+        self.packages = packages
+        self.modules = modules
+        self.path = path
 
-        """
-        absolute_path = _path_absolute(path_entry)
-        if not _path_isdir(absolute_path):
-            raise ImportError("only directories are supported")
-        self._path_entry = absolute_path
-
-    def find_module(self, fullname, path=None):
+    def find_module(self, fullname):
+        """Try to find a loader for the specified module."""
         tail_module = fullname.rpartition('.')[2]
-        package_directory = None
-        if self._possible_package:
-            for ext in self._suffixes:
-                package_directory = _path_join(self._path_entry, tail_module)
-                init_filename = '__init__' + ext
-                package_init = _path_join(package_directory, init_filename)
-                if (_path_isfile(package_init) and
-                        _case_ok(self._path_entry, tail_module) and
-                        _case_ok(package_directory, init_filename)):
-                    return self._loader(fullname, package_init, True)
-        for ext in self._suffixes:
-            file_name = tail_module + ext
-            file_path = _path_join(self._path_entry, file_name)
-            if (_path_isfile(file_path) and
-                    _case_ok(self._path_entry, file_name)):
-                return self._loader(fullname, file_path, False)
-        else:
-            # Raise a warning if it matches a directory w/o an __init__ file.
-            if (package_directory is not None and
-                    _path_isdir(package_directory) and
-                    _case_ok(self._path_entry, tail_module)):
-                _warnings.warn("Not importing directory %s: missing __init__"
-                                % package_directory, ImportWarning)
-            return None
-
-
-class _PyFileFinder(_FileFinder):
-
-    """Importer for source/bytecode files."""
-
-    _possible_package = True
-    _loader = _PyFileLoader
-
-    def __init__(self, path_entry):
-        # Lack of imp during class creation means _suffixes is set here.
-        # Make sure that Python source files are listed first!  Needed for an
-        # optimization by the loader.
-        self._suffixes = _suffix_list(imp.PY_SOURCE)
-        super().__init__(path_entry)
-
-
-class _PyPycFileFinder(_PyFileFinder):
+        base_path = _path_join(self.path, tail_module)
+        if _path_isdir(base_path) and _case_ok(self.path, tail_module):
+            for suffix, loader in self.packages:
+                init_filename = '__init__' + suffix
+                full_path = _path_join(base_path, init_filename)
+                if (_path_isfile(full_path) and
+                        _case_ok(base_path, init_filename)):
+                    return loader(fullname, full_path)
+            else:
+                msg = "Not importing directory {}: missing __init__"
+                _warnings.warn(msg.format(base_path), ImportWarning)
+        for suffix, loader in self.modules:
+            mod_filename = tail_module + suffix
+            full_path = _path_join(self.path, mod_filename)
+            if _path_isfile(full_path) and _case_ok(self.path, mod_filename):
+                return loader(fullname, full_path)
+        return None
 
-    """Finder for source and bytecode files."""
+class _SourceFinderDetails:
 
-    _loader = _PyPycFileLoader
+    loader = _SourceFileLoader
+    supports_packages = True
 
-    def __init__(self, path_entry):
-        super().__init__(path_entry)
-        self._suffixes += _suffix_list(imp.PY_COMPILED)
+    def __init__(self):
+        self.suffixes = _suffix_list(imp.PY_SOURCE)
 
+class _SourcelessFinderDetails:
 
+    loader = _SourcelessFileLoader
+    supports_packages = True
 
+    def __init__(self):
+        self.suffixes = _suffix_list(imp.PY_COMPILED)
 
-class _ExtensionFileFinder(_FileFinder):
 
-    """Importer for extension files."""
+class _ExtensionFinderDetails:
 
-    _possible_package = False
-    _loader = _ExtensionFileLoader
+    loader = _ExtensionFileLoader
+    supports_packages = False
 
-    def __init__(self, path_entry):
-        # Assigning to _suffixes here instead of at the class level because
-        # imp is not imported at the time of class creation.
-        self._suffixes = _suffix_list(imp.C_EXTENSION)
-        super().__init__(path_entry)
+    def __init__(self):
+        self.suffixes = _suffix_list(imp.C_EXTENSION)
 
 
 # Import itself ###############################################################
 
-def _chained_path_hook(*path_hooks):
-    """Create a closure which sequentially checks path hooks to see which ones
-    (if any) can work with a path."""
-    def path_hook(entry):
-        """Check to see if 'entry' matches any of the enclosed path hooks."""
-        finders = []
-        for hook in path_hooks:
-            try:
-                finder = hook(entry)
-            except ImportError:
-                continue
-            else:
-                finders.append(finder)
-        if not finders:
-            raise ImportError("no finder found")
-        else:
-            return _ChainedFinder(*finders)
-
-    return path_hook
+def _file_path_hook(path):
+    """If the path is a directory, return a file-based finder."""
+    if _path_isdir(path):
+        return _FileFinder(path, _ExtensionFinderDetails(),
+                           _SourceFinderDetails(),
+                           _SourcelessFinderDetails())
+    else:
+        raise ImportError("only directories are supported")
 
 
-_DEFAULT_PATH_HOOK = _chained_path_hook(_ExtensionFileFinder, _PyPycFileFinder)
+_DEFAULT_PATH_HOOK = _file_path_hook
 
 class _DefaultPathFinder(PathFinder):
 

Modified: python/branches/py3k-cdecimal/Lib/importlib/abc.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/abc.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/abc.py	Sat Jul 17 12:36:09 2010
@@ -1,8 +1,16 @@
 """Abstract base classes related to import."""
 from . import _bootstrap
 from . import machinery
+from . import util
 import abc
+import imp
+import io
+import marshal
+import os.path
+import sys
+import tokenize
 import types
+import warnings
 
 
 class Loader(metaclass=abc.ABCMeta):
@@ -58,19 +66,19 @@
     def is_package(self, fullname:str) -> bool:
         """Abstract method which when implemented should return whether the
         module is a package."""
-        return NotImplementedError
+        raise NotImplementedError
 
     @abc.abstractmethod
     def get_code(self, fullname:str) -> types.CodeType:
         """Abstract method which when implemented should return the code object
         for the module"""
-        return NotImplementedError
+        raise NotImplementedError
 
     @abc.abstractmethod
     def get_source(self, fullname:str) -> str:
         """Abstract method which should return the source code for the
         module."""
-        return NotImplementedError
+        raise NotImplementedError
 
 InspectLoader.register(machinery.BuiltinImporter)
 InspectLoader.register(machinery.FrozenImporter)
@@ -92,33 +100,170 @@
         raise NotImplementedError
 
 
-class PyLoader(_bootstrap.PyLoader, ResourceLoader, ExecutionLoader):
+class SourceLoader(_bootstrap.SourceLoader, ResourceLoader, ExecutionLoader):
 
-    """Abstract base class to assist in loading source code by requiring only
-    back-end storage methods to be implemented.
+    """Abstract base class for loading source code (and optionally any
+    corresponding bytecode).
+
+    To support loading from source code, the abstractmethods inherited from
+    ResourceLoader and ExecutionLoader need to be implemented. To also support
+    loading from bytecode, the optional methods specified directly by this ABC
+    is required.
+
+    Inherited abstractmethods not implemented in this ABC:
+
+        * ResourceLoader.get_data
+        * ExecutionLoader.get_filename
+
+    """
 
-    The methods get_code, get_source, and load_module are implemented for the
-    user.
+
+class PyLoader(SourceLoader):
+
+    """Implement the deprecated PyLoader ABC in terms of SourceLoader.
+
+    This class has been deprecated! It is slated for removal in Python 3.4.
+    If compatibility with Python 3.1 is not needed then implement the
+    SourceLoader ABC instead of this class. If Python 3.1 compatibility is
+    needed, then use the following idiom to have a single class that is
+    compatible with Python 3.1 onwards::
+
+        try:
+            from importlib.abc import SourceLoader
+        except ImportError:
+            from importlib.abc import PyLoader as SourceLoader
+
+
+        class CustomLoader(SourceLoader):
+            def get_filename(self, fullname):
+                # Implement ...
+
+            def source_path(self, fullname):
+                '''Implement source_path in terms of get_filename.'''
+                try:
+                    return self.get_filename(fullname)
+                except ImportError:
+                    return None
+
+            def is_package(self, fullname):
+                filename = os.path.basename(self.get_filename(fullname))
+                return os.path.splitext(filename)[0] == '__init__'
 
     """
 
     @abc.abstractmethod
+    def is_package(self, fullname):
+        raise NotImplementedError
+
+    @abc.abstractmethod
     def source_path(self, fullname:str) -> object:
         """Abstract method which when implemented should return the path to the
-        sourced code for the module."""
+        source code for the module."""
         raise NotImplementedError
 
+    def get_filename(self, fullname):
+        """Implement get_filename in terms of source_path.
+
+        As get_filename should only return a source file path there is no
+        chance of the path not existing but loading still being possible, so
+        ImportError should propagate instead of being turned into returning
+        None.
+
+        """
+        warnings.warn("importlib.abc.PyLoader is deprecated and is "
+                            "slated for removal in Python 3.4; "
+                            "use SourceLoader instead. "
+                            "See the importlib documentation on how to be "
+                            "compatible with Python 3.1 onwards.",
+                        PendingDeprecationWarning)
+        path = self.source_path(fullname)
+        if path is None:
+            raise ImportError
+        else:
+            return path
+
 
-class PyPycLoader(_bootstrap.PyPycLoader, PyLoader):
+class PyPycLoader(PyLoader):
 
     """Abstract base class to assist in loading source and bytecode by
     requiring only back-end storage methods to be implemented.
 
+    This class has been deprecated! Removal is slated for Python 3.4. Implement
+    the SourceLoader ABC instead. If Python 3.1 compatibility is needed, see
+    PyLoader.
+
     The methods get_code, get_source, and load_module are implemented for the
     user.
 
     """
 
+    def get_filename(self, fullname):
+        """Return the source or bytecode file path."""
+        path = self.source_path(fullname)
+        if path is not None:
+            return path
+        path = self.bytecode_path(fullname)
+        if path is not None:
+            return path
+        raise ImportError("no source or bytecode path available for "
+                            "{0!r}".format(fullname))
+
+    def get_code(self, fullname):
+        """Get a code object from source or bytecode."""
+        warnings.warn("importlib.abc.PyPycLoader is deprecated and slated for "
+                            "removal in Python 3.4; use SourceLoader instead. "
+                            "If Python 3.1 compatibility is required, see the "
+                            "latest documentation for PyLoader.",
+                        PendingDeprecationWarning)
+        source_timestamp = self.source_mtime(fullname)
+        # Try to use bytecode if it is available.
+        bytecode_path = self.bytecode_path(fullname)
+        if bytecode_path:
+            data = self.get_data(bytecode_path)
+            try:
+                magic = data[:4]
+                if len(magic) < 4:
+                    raise ImportError("bad magic number in {}".format(fullname))
+                raw_timestamp = data[4:8]
+                if len(raw_timestamp) < 4:
+                    raise EOFError("bad timestamp in {}".format(fullname))
+                pyc_timestamp = marshal._r_long(raw_timestamp)
+                bytecode = data[8:]
+                # Verify that the magic number is valid.
+                if imp.get_magic() != magic:
+                    raise ImportError("bad magic number in {}".format(fullname))
+                # Verify that the bytecode is not stale (only matters when
+                # there is source to fall back on.
+                if source_timestamp:
+                    if pyc_timestamp < source_timestamp:
+                        raise ImportError("bytecode is stale")
+            except (ImportError, EOFError):
+                # If source is available give it a shot.
+                if source_timestamp is not None:
+                    pass
+                else:
+                    raise
+            else:
+                # Bytecode seems fine, so try to use it.
+                return marshal.loads(bytecode)
+        elif source_timestamp is None:
+            raise ImportError("no source or bytecode available to create code "
+                                "object for {0!r}".format(fullname))
+        # Use the source.
+        source_path = self.source_path(fullname)
+        if source_path is None:
+            message = "a source path must exist to load {0}".format(fullname)
+            raise ImportError(message)
+        source = self.get_data(source_path)
+        code_object = compile(source, source_path, 'exec', dont_inherit=True)
+        # Generate bytecode and write it out.
+        if not sys.dont_write_bytecode:
+            data = bytearray(imp.get_magic())
+            data.extend(marshal._w_long(source_timestamp))
+            data.extend(marshal.dumps(code_object))
+            self.write_bytecode(fullname, data)
+        return code_object
+
     @abc.abstractmethod
     def source_mtime(self, fullname:str) -> int:
         """Abstract method which when implemented should return the

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

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_case_sensitivity.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_case_sensitivity.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_case_sensitivity.py	Sat Jul 17 12:36:09 2010
@@ -13,7 +13,8 @@
         good_name = ext_util.NAME
         bad_name = good_name.upper()
         assert good_name != bad_name
-        finder = _bootstrap._ExtensionFileFinder(ext_util.PATH)
+        finder = _bootstrap._FileFinder(ext_util.PATH,
+                                        _bootstrap._ExtensionFinderDetails())
         return finder.find_module(bad_name)
 
     def test_case_sensitive(self):

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_finder.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_finder.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_finder.py	Sat Jul 17 12:36:09 2010
@@ -9,7 +9,8 @@
     """Test the finder for extension modules."""
 
     def find_module(self, fullname):
-        importer = _bootstrap._ExtensionFileFinder(util.PATH)
+        importer = _bootstrap._FileFinder(util.PATH,
+                                          _bootstrap._ExtensionFinderDetails())
         return importer.find_module(fullname)
 
     def test_module(self):

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_loader.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_loader.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_loader.py	Sat Jul 17 12:36:09 2010
@@ -13,7 +13,7 @@
 
     def load_module(self, fullname):
         loader = _bootstrap._ExtensionFileLoader(ext_util.NAME,
-                                                ext_util.FILEPATH, False)
+                                                ext_util.FILEPATH)
         return loader.load_module(fullname)
 
     def test_module(self):

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_path_hook.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_path_hook.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/extension/test_path_hook.py	Sat Jul 17 12:36:09 2010
@@ -14,7 +14,7 @@
     # XXX Should it only work for directories containing an extension module?
 
     def hook(self, entry):
-        return _bootstrap._ExtensionFileFinder(entry)
+        return _bootstrap._file_path_hook(entry)
 
     def test_success(self):
         # Path hook should handle a directory where a known extension module

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/import_/test_path.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/import_/test_path.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/import_/test_path.py	Sat Jul 17 12:36:09 2010
@@ -5,6 +5,7 @@
 import imp
 import os
 import sys
+import tempfile
 from test import support
 from types import MethodType
 import unittest
@@ -80,23 +81,28 @@
 
     def test_implicit_hooks(self):
         # Test that the implicit path hooks are used.
-        existing_path = os.path.dirname(support.TESTFN)
         bad_path = '<path>'
         module = '<module>'
         assert not os.path.exists(bad_path)
-        with util.import_state():
-            nothing = _bootstrap._DefaultPathFinder.find_module(module,
-                                                           path=[existing_path])
-            self.assertTrue(nothing is None)
-            self.assertTrue(existing_path in sys.path_importer_cache)
-            self.assertTrue(not isinstance(sys.path_importer_cache[existing_path],
-                                        imp.NullImporter))
-            nothing = _bootstrap._DefaultPathFinder.find_module(module,
-                                                                path=[bad_path])
-            self.assertTrue(nothing is None)
-            self.assertTrue(bad_path in sys.path_importer_cache)
-            self.assertTrue(isinstance(sys.path_importer_cache[bad_path],
-                                    imp.NullImporter))
+        existing_path = tempfile.mkdtemp()
+        try:
+            with util.import_state():
+                nothing = _bootstrap._DefaultPathFinder.find_module(module,
+                                                        path=[existing_path])
+                self.assertTrue(nothing is None)
+                self.assertTrue(existing_path in sys.path_importer_cache)
+                result = isinstance(sys.path_importer_cache[existing_path],
+                                    imp.NullImporter)
+                self.assertFalse(result)
+                nothing = _bootstrap._DefaultPathFinder.find_module(module,
+                                                            path=[bad_path])
+                self.assertTrue(nothing is None)
+                self.assertTrue(bad_path in sys.path_importer_cache)
+                self.assertTrue(isinstance(sys.path_importer_cache[bad_path],
+                                           imp.NullImporter))
+        finally:
+            os.rmdir(existing_path)
+
 
     def test_path_importer_cache_has_None(self):
         # Test that the default hook is used when sys.path_importer_cache

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/regrtest.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/regrtest.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/regrtest.py	Sat Jul 17 12:36:09 2010
@@ -6,9 +6,11 @@
 this script.
 
 XXX FAILING
-    test_import
-        execution bit
+  * test_import
+    - test_incorrect_code_name
         file name differing between __file__ and co_filename (r68360 on trunk)
+    - test_import_by_filename
+        exception for trying to import by file name does not match
 
 """
 import importlib

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_abc_loader.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_abc_loader.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_abc_loader.py	Sat Jul 17 12:36:09 2010
@@ -1,14 +1,68 @@
 import importlib
 from importlib import abc
+
 from .. import abc as testing_abc
 from .. import util
 from . import util as source_util
+
 import imp
+import inspect
+import io
 import marshal
 import os
 import sys
 import types
 import unittest
+import warnings
+
+
+class SourceOnlyLoaderMock(abc.SourceLoader):
+
+    # Globals that should be defined for all modules.
+    source = (b"_ = '::'.join([__name__, __file__, __cached__, __package__, "
+              b"repr(__loader__)])")
+
+    def __init__(self, path):
+        self.path = path
+
+    def get_data(self, path):
+        assert self.path == path
+        return self.source
+
+    def get_filename(self, fullname):
+        return self.path
+
+
+class SourceLoaderMock(SourceOnlyLoaderMock):
+
+    source_mtime = 1
+
+    def __init__(self, path, magic=imp.get_magic()):
+        super().__init__(path)
+        self.bytecode_path = imp.cache_from_source(self.path)
+        data = bytearray(magic)
+        data.extend(marshal._w_long(self.source_mtime))
+        code_object = compile(self.source, self.path, 'exec',
+                                dont_inherit=True)
+        data.extend(marshal.dumps(code_object))
+        self.bytecode = bytes(data)
+        self.written = {}
+
+    def get_data(self, path):
+        if path == self.path:
+            return super().get_data(path)
+        elif path == self.bytecode_path:
+            return self.bytecode
+        else:
+            raise IOError
+
+    def path_mtime(self, path):
+        assert path == self.path
+        return self.source_mtime
+
+    def set_data(self, path, data):
+        self.written[path] = bytes(data)
+        return path == self.bytecode_path
 
 
 class PyLoaderMock(abc.PyLoader):
@@ -33,17 +87,42 @@
         return self.source
 
     def is_package(self, name):
+        filename = os.path.basename(self.get_filename(name))
+        return os.path.splitext(filename)[0] == '__init__'
+
+    def source_path(self, name):
         try:
-            return '__init__' in self.module_paths[name]
+            return self.module_paths[name]
         except KeyError:
             raise ImportError
 
-    def source_path(self, name):
+    def get_filename(self, name):
+        """Silence deprecation warning."""
+        with warnings.catch_warnings(record=True) as w:
+            warnings.simplefilter("always")
+            path = super().get_filename(name)
+            assert len(w) == 1
+            assert issubclass(w[0].category, PendingDeprecationWarning)
+            return path
+
+
+class PyLoaderCompatMock(PyLoaderMock):
+
+    """Mock that matches what is suggested to have a loader that is compatible
+    from Python 3.1 onwards."""
+
+    def get_filename(self, fullname):
         try:
-            return self.module_paths[name]
+            return self.module_paths[fullname]
         except KeyError:
             raise ImportError
 
+    def source_path(self, fullname):
+        try:
+            return self.get_filename(fullname)
+        except ImportError:
+            return None
+
 
 class PyPycLoaderMock(abc.PyPycLoader, PyLoaderMock):
 
@@ -114,6 +193,13 @@
         except TypeError:
             return '__init__' in self.bytecode_to_path[name]
 
+    def get_code(self, name):
+        with warnings.catch_warnings(record=True) as w:
+            warnings.simplefilter("always")
+            code_object = super().get_code(name)
+            assert len(w) == 1
+            assert issubclass(w[0].category, PendingDeprecationWarning)
+            return code_object
 
 class PyLoaderTests(testing_abc.LoaderTests):
 
@@ -200,6 +286,14 @@
         return mock
 
 
+class PyLoaderCompatTests(PyLoaderTests):
+
+    """Test that the suggested code to make a loader that is compatible from
+    Python 3.1 forward works."""
+
+    mocker = PyLoaderCompatMock
+
+
 class PyLoaderInterfaceTests(unittest.TestCase):
 
     """Tests for importlib.abc.PyLoader to make sure that when source_path()
@@ -234,30 +328,6 @@
             mock.get_filename(name)
 
 
-class PyLoaderGetSourceTests(unittest.TestCase):
-
-    """Tests for importlib.abc.PyLoader.get_source()."""
-
-    def test_default_encoding(self):
-        # Should have no problems with UTF-8 text.
-        name = 'mod'
-        mock = PyLoaderMock({name: os.path.join('path', 'to', 'mod')})
-        source = 'x = "ü"'
-        mock.source = source.encode('utf-8')
-        returned_source = mock.get_source(name)
-        self.assertEqual(returned_source, source)
-
-    def test_decoded_source(self):
-        # Decoding should work.
-        name = 'mod'
-        mock = PyLoaderMock({name: os.path.join('path', 'to', 'mod')})
-        source = "# coding: Latin-1\nx='ü'"
-        assert source.encode('latin-1') != source.encode('utf-8')
-        mock.source = source.encode('latin-1')
-        returned_source = mock.get_source(name)
-        self.assertEqual(returned_source, source)
-
-
 class PyPycLoaderTests(PyLoaderTests):
 
     """Tests for importlib.abc.PyPycLoader."""
@@ -413,7 +483,7 @@
     def test_bad_bytecode(self):
         # Malformed code object bytecode should lead to a ValueError.
         name = 'mod'
-        bc = {name: {'path': os.path.join('path', 'to', 'mod'), 'bc': b'XXX'}}
+        bc = {name: {'path': os.path.join('path', 'to', 'mod'), 'bc': b'1234'}}
         mock = PyPycLoaderMock({name: None}, bc)
         with util.uncache(name), self.assertRaises(ValueError):
             mock.load_module(name)
@@ -465,12 +535,341 @@
             mock.load_module(name)
 
 
+class SourceLoaderTestHarness(unittest.TestCase):
+
+    def setUp(self, *, is_package=True, **kwargs):
+        self.package = 'pkg'
+        if is_package:
+            self.path = os.path.join(self.package, '__init__.py')
+            self.name = self.package
+        else:
+            module_name = 'mod'
+            self.path = os.path.join(self.package, '.'.join(['mod', 'py']))
+            self.name = '.'.join([self.package, module_name])
+        self.cached = imp.cache_from_source(self.path)
+        self.loader = self.loader_mock(self.path, **kwargs)
+
+    def verify_module(self, module):
+        self.assertEqual(module.__name__, self.name)
+        self.assertEqual(module.__file__, self.path)
+        self.assertEqual(module.__cached__, self.cached)
+        self.assertEqual(module.__package__, self.package)
+        self.assertEqual(module.__loader__, self.loader)
+        values = module._.split('::')
+        self.assertEqual(values[0], self.name)
+        self.assertEqual(values[1], self.path)
+        self.assertEqual(values[2], self.cached)
+        self.assertEqual(values[3], self.package)
+        self.assertEqual(values[4], repr(self.loader))
+
+    def verify_code(self, code_object):
+        module = imp.new_module(self.name)
+        module.__file__ = self.path
+        module.__cached__ = self.cached
+        module.__package__ = self.package
+        module.__loader__ = self.loader
+        module.__path__ = []
+        exec(code_object, module.__dict__)
+        self.verify_module(module)
+
+
+class SourceOnlyLoaderTests(SourceLoaderTestHarness):
+
+    """Test importlib.abc.SourceLoader for source-only loading.
+
+    Reload testing is subsumed by the tests for
+    importlib.util.module_for_loader.
+
+    """
+
+    loader_mock = SourceOnlyLoaderMock
+
+    def test_get_source(self):
+        # Verify the source code is returned as a string.
+        # If an IOError is raised by get_data then raise ImportError.
+        expected_source = self.loader.source.decode('utf-8')
+        self.assertEqual(self.loader.get_source(self.name), expected_source)
+        def raise_IOError(path):
+            raise IOError
+        self.loader.get_data = raise_IOError
+        with self.assertRaises(ImportError):
+            self.loader.get_source(self.name)
+
+    def test_is_package(self):
+        # Properly detect when loading a package.
+        self.setUp(is_package=True)
+        self.assertTrue(self.loader.is_package(self.name))
+        self.setUp(is_package=False)
+        self.assertFalse(self.loader.is_package(self.name))
+
+    def test_get_code(self):
+        # Verify the code object is created.
+        code_object = self.loader.get_code(self.name)
+        self.verify_code(code_object)
+
+    def test_load_module(self):
+        # Loading a module should set __name__, __loader__, __package__,
+        # __path__ (for packages), __file__, and __cached__.
+        # The module should also be put into sys.modules.
+        with util.uncache(self.name):
+            module = self.loader.load_module(self.name)
+            self.verify_module(module)
+            self.assertEqual(module.__path__, [os.path.dirname(self.path)])
+            self.assertTrue(self.name in sys.modules)
+
+    def test_package_settings(self):
+        # __package__ needs to be set, while __path__ is set on if the module
+        # is a package.
+        # Testing the values for a package are covered by test_load_module.
+        self.setUp(is_package=False)
+        with util.uncache(self.name):
+            module = self.loader.load_module(self.name)
+            self.verify_module(module)
+            self.assertTrue(not hasattr(module, '__path__'))
+
+    def test_get_source_encoding(self):
+        # Source is considered encoded in UTF-8 by default unless otherwise
+        # specified by an encoding line.
+        source = "_ = 'ü'"
+        self.loader.source = source.encode('utf-8')
+        returned_source = self.loader.get_source(self.name)
+        self.assertEqual(returned_source, source)
+        source = "# coding: latin-1\n_ = ü"
+        self.loader.source = source.encode('latin-1')
+        returned_source = self.loader.get_source(self.name)
+        self.assertEqual(returned_source, source)
+
+
+ at unittest.skipIf(sys.dont_write_bytecode, "sys.dont_write_bytecode is true")
+class SourceLoaderBytecodeTests(SourceLoaderTestHarness):
+
+    """Test importlib.abc.SourceLoader's use of bytecode.
+
+    Source-only testing handled by SourceOnlyLoaderTests.
+
+    """
+
+    loader_mock = SourceLoaderMock
+
+    def verify_code(self, code_object, *, bytecode_written=False):
+        super().verify_code(code_object)
+        if bytecode_written:
+            self.assertIn(self.cached, self.loader.written)
+            data = bytearray(imp.get_magic())
+            data.extend(marshal._w_long(self.loader.source_mtime))
+            data.extend(marshal.dumps(code_object))
+            self.assertEqual(self.loader.written[self.cached], bytes(data))
+
+    def test_code_with_everything(self):
+        # When everything should work.
+        code_object = self.loader.get_code(self.name)
+        self.verify_code(code_object)
+
+    def test_no_bytecode(self):
+        # If no bytecode exists then move on to the source.
+        self.loader.bytecode_path = "<does not exist>"
+        # Sanity check
+        with self.assertRaises(IOError):
+            bytecode_path = imp.cache_from_source(self.path)
+            self.loader.get_data(bytecode_path)
+        code_object = self.loader.get_code(self.name)
+        self.verify_code(code_object, bytecode_written=True)
+
+    def test_code_bad_timestamp(self):
+        # Bytecode is only used when the timestamp matches the source EXACTLY.
+        for source_mtime in (0, 2):
+            assert source_mtime != self.loader.source_mtime
+            original = self.loader.source_mtime
+            self.loader.source_mtime = source_mtime
+            # If bytecode is used then EOFError would be raised by marshal.
+            self.loader.bytecode = self.loader.bytecode[8:]
+            code_object = self.loader.get_code(self.name)
+            self.verify_code(code_object, bytecode_written=True)
+            self.loader.source_mtime = original
+
+    def test_code_bad_magic(self):
+        # Skip over bytecode with a bad magic number.
+        self.setUp(magic=b'0000')
+        # If bytecode is used then EOFError would be raised by marshal.
+        self.loader.bytecode = self.loader.bytecode[8:]
+        code_object = self.loader.get_code(self.name)
+        self.verify_code(code_object, bytecode_written=True)
+
+    def test_dont_write_bytecode(self):
+        # Bytecode is not written if sys.dont_write_bytecode is true.
+        # Can assume it is false already thanks to the skipIf class decorator.
+        try:
+            sys.dont_write_bytecode = True
+            self.loader.bytecode_path = "<does not exist>"
+            code_object = self.loader.get_code(self.name)
+            self.assertNotIn(self.cached, self.loader.written)
+        finally:
+            sys.dont_write_bytecode = False
+
+    def test_no_set_data(self):
+        # If set_data is not defined, one can still read bytecode.
+        self.setUp(magic=b'0000')
+        original_set_data = self.loader.__class__.set_data
+        try:
+            del self.loader.__class__.set_data
+            code_object = self.loader.get_code(self.name)
+            self.verify_code(code_object)
+        finally:
+            self.loader.__class__.set_data = original_set_data
+
+    def test_set_data_raises_exceptions(self):
+        # Raising NotImplementedError or IOError is okay for set_data.
+        def raise_exception(exc):
+            def closure(*args, **kwargs):
+                raise exc
+            return closure
+
+        self.setUp(magic=b'0000')
+        self.loader.set_data = raise_exception(NotImplementedError)
+        code_object = self.loader.get_code(self.name)
+        self.verify_code(code_object)
+
+
+class SourceLoaderGetSourceTests(unittest.TestCase):
+
+    """Tests for importlib.abc.SourceLoader.get_source()."""
+
+    def test_default_encoding(self):
+        # Should have no problems with UTF-8 text.
+        name = 'mod'
+        mock = SourceOnlyLoaderMock('mod.file')
+        source = 'x = "ü"'
+        mock.source = source.encode('utf-8')
+        returned_source = mock.get_source(name)
+        self.assertEqual(returned_source, source)
+
+    def test_decoded_source(self):
+        # Decoding should work.
+        name = 'mod'
+        mock = SourceOnlyLoaderMock("mod.file")
+        source = "# coding: Latin-1\nx='ü'"
+        assert source.encode('latin-1') != source.encode('utf-8')
+        mock.source = source.encode('latin-1')
+        returned_source = mock.get_source(name)
+        self.assertEqual(returned_source, source)
+
+    def test_universal_newlines(self):
+        # PEP 302 says universal newlines should be used.
+        name = 'mod'
+        mock = SourceOnlyLoaderMock('mod.file')
+        source = "x = 42\r\ny = -13\r\n"
+        mock.source = source.encode('utf-8')
+        expect = io.IncrementalNewlineDecoder(None, True).decode(source)
+        self.assertEqual(mock.get_source(name), expect)
+
+class AbstractMethodImplTests(unittest.TestCase):
+
+    """Test the concrete abstractmethod implementations."""
+
+    class Loader(abc.Loader):
+        def load_module(self, fullname):
+            super().load_module(fullname)
+
+    class Finder(abc.Finder):
+        def find_module(self, _):
+            super().find_module(_)
+
+    class ResourceLoader(Loader, abc.ResourceLoader):
+        def get_data(self, _):
+            super().get_data(_)
+
+    class InspectLoader(Loader, abc.InspectLoader):
+        def is_package(self, _):
+            super().is_package(_)
+
+        def get_code(self, _):
+            super().get_code(_)
+
+        def get_source(self, _):
+            super().get_source(_)
+
+    class ExecutionLoader(InspectLoader, abc.ExecutionLoader):
+        def get_filename(self, _):
+            super().get_filename(_)
+
+    class SourceLoader(ResourceLoader, ExecutionLoader, abc.SourceLoader):
+        pass
+
+    class PyLoader(ResourceLoader, InspectLoader, abc.PyLoader):
+        def source_path(self, _):
+            super().source_path(_)
+
+    class PyPycLoader(PyLoader, abc.PyPycLoader):
+        def bytecode_path(self, _):
+            super().bytecode_path(_)
+
+        def source_mtime(self, _):
+            super().source_mtime(_)
+
+        def write_bytecode(self, _, _2):
+            super().write_bytecode(_, _2)
+
+    def raises_NotImplementedError(self, ins, *args):
+        for method_name in args:
+            method = getattr(ins, method_name)
+            arg_count = len(inspect.getfullargspec(method)[0]) - 1
+            args = [''] * arg_count
+            try:
+                method(*args)
+            except NotImplementedError:
+                pass
+            else:
+                msg = "{}.{} did not raise NotImplementedError"
+                self.fail(msg.format(ins.__class__.__name__, method_name))
+
+    def test_Loader(self):
+        self.raises_NotImplementedError(self.Loader(), 'load_module')
+
+    # XXX misplaced; should be somewhere else
+    def test_Finder(self):
+        self.raises_NotImplementedError(self.Finder(), 'find_module')
+
+    def test_ResourceLoader(self):
+        self.raises_NotImplementedError(self.ResourceLoader(), 'load_module',
+                                        'get_data')
+
+    def test_InspectLoader(self):
+        self.raises_NotImplementedError(self.InspectLoader(), 'load_module',
+                                        'is_package', 'get_code', 'get_source')
+
+    def test_ExecutionLoader(self):
+        self.raises_NotImplementedError(self.ExecutionLoader(), 'load_module',
+                                        'is_package', 'get_code', 'get_source',
+                                        'get_filename')
+
+    def test_SourceLoader(self):
+        ins = self.SourceLoader()
+        # Required abstractmethods.
+        self.raises_NotImplementedError(ins, 'get_filename', 'get_data')
+        # Optional abstractmethods.
+        self.raises_NotImplementedError(ins,'path_mtime', 'set_data')
+
+    def test_PyLoader(self):
+        self.raises_NotImplementedError(self.PyLoader(), 'source_path',
+                                        'get_data', 'is_package')
+
+    def test_PyPycLoader(self):
+        self.raises_NotImplementedError(self.PyPycLoader(), 'source_path',
+                                        'source_mtime', 'bytecode_path',
+                                        'write_bytecode')
+
+
 def test_main():
     from test.support import run_unittest
-    run_unittest(PyLoaderTests, PyLoaderInterfaceTests, PyLoaderGetSourceTests,
+    run_unittest(PyLoaderTests, PyLoaderCompatTests,
+                    PyLoaderInterfaceTests,
                     PyPycLoaderTests, PyPycLoaderInterfaceTests,
                     SkipWritingBytecodeTests, RegeneratedBytecodeTests,
-                    BadBytecodeFailureTests, MissingPathsTests)
+                    BadBytecodeFailureTests, MissingPathsTests,
+                    SourceOnlyLoaderTests,
+                    SourceLoaderBytecodeTests,
+                    SourceLoaderGetSourceTests,
+                    AbstractMethodImplTests)
 
 
 if __name__ == '__main__':

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_case_sensitivity.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_case_sensitivity.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_case_sensitivity.py	Sat Jul 17 12:36:09 2010
@@ -19,7 +19,9 @@
     assert name != name.lower()
 
     def find(self, path):
-        finder = _bootstrap._PyPycFileFinder(path)
+        finder = _bootstrap._FileFinder(path,
+                                        _bootstrap._SourceFinderDetails(),
+                                        _bootstrap._SourcelessFinderDetails())
         return finder.find_module(self.name)
 
     def sensitivity_test(self):
@@ -27,7 +29,7 @@
         sensitive_pkg = 'sensitive.{0}'.format(self.name)
         insensitive_pkg = 'insensitive.{0}'.format(self.name.lower())
         context = source_util.create_modules(insensitive_pkg, sensitive_pkg)
-        with  context as mapping:
+        with context as mapping:
             sensitive_path = os.path.join(mapping['.root'], 'sensitive')
             insensitive_path = os.path.join(mapping['.root'], 'insensitive')
             return self.find(sensitive_path), self.find(insensitive_path)
@@ -37,7 +39,7 @@
             env.unset('PYTHONCASEOK')
             sensitive, insensitive = self.sensitivity_test()
             self.assertTrue(hasattr(sensitive, 'load_module'))
-            self.assertIn(self.name, sensitive._base_path)
+            self.assertIn(self.name, sensitive.get_filename(self.name))
             self.assertIsNone(insensitive)
 
     def test_insensitive(self):
@@ -45,9 +47,9 @@
             env.set('PYTHONCASEOK', '1')
             sensitive, insensitive = self.sensitivity_test()
             self.assertTrue(hasattr(sensitive, 'load_module'))
-            self.assertIn(self.name, sensitive._base_path)
+            self.assertIn(self.name, sensitive.get_filename(self.name))
             self.assertTrue(hasattr(insensitive, 'load_module'))
-            self.assertIn(self.name, insensitive._base_path)
+            self.assertIn(self.name, insensitive.get_filename(self.name))
 
 
 def test_main():

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py	Sat Jul 17 12:36:09 2010
@@ -1,9 +1,11 @@
 import importlib
 from importlib import _bootstrap
 from .. import abc
+from .. import util
 from . import util as source_util
 
 import imp
+import marshal
 import os
 import py_compile
 import stat
@@ -23,8 +25,7 @@
     # [basic]
     def test_module(self):
         with source_util.create_modules('_temp') as mapping:
-            loader = _bootstrap._PyPycFileLoader('_temp', mapping['_temp'],
-                                                    False)
+            loader = _bootstrap._SourceFileLoader('_temp', mapping['_temp'])
             module = loader.load_module('_temp')
             self.assertTrue('_temp' in sys.modules)
             check = {'__name__': '_temp', '__file__': mapping['_temp'],
@@ -34,9 +35,8 @@
 
     def test_package(self):
         with source_util.create_modules('_pkg.__init__') as mapping:
-            loader = _bootstrap._PyPycFileLoader('_pkg',
-                                                 mapping['_pkg.__init__'],
-                                                 True)
+            loader = _bootstrap._SourceFileLoader('_pkg',
+                                                 mapping['_pkg.__init__'])
             module = loader.load_module('_pkg')
             self.assertTrue('_pkg' in sys.modules)
             check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'],
@@ -48,8 +48,8 @@
 
     def test_lacking_parent(self):
         with source_util.create_modules('_pkg.__init__', '_pkg.mod')as mapping:
-            loader = _bootstrap._PyPycFileLoader('_pkg.mod',
-                                                    mapping['_pkg.mod'], False)
+            loader = _bootstrap._SourceFileLoader('_pkg.mod',
+                                                    mapping['_pkg.mod'])
             module = loader.load_module('_pkg.mod')
             self.assertTrue('_pkg.mod' in sys.modules)
             check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'],
@@ -63,8 +63,7 @@
 
     def test_module_reuse(self):
         with source_util.create_modules('_temp') as mapping:
-            loader = _bootstrap._PyPycFileLoader('_temp', mapping['_temp'],
-                                                    False)
+            loader = _bootstrap._SourceFileLoader('_temp', mapping['_temp'])
             module = loader.load_module('_temp')
             module_id = id(module)
             module_dict_id = id(module.__dict__)
@@ -74,7 +73,7 @@
             # everything that has happened above can be too fast;
             # force an mtime on the source that is guaranteed to be different
             # than the original mtime.
-            loader.source_mtime = self.fake_mtime(loader.source_mtime)
+            loader.path_mtime = self.fake_mtime(loader.path_mtime)
             module = loader.load_module('_temp')
             self.assertTrue('testing_var' in module.__dict__,
                          "'testing_var' not in "
@@ -94,8 +93,7 @@
                 setattr(orig_module, attr, value)
             with open(mapping[name], 'w') as file:
                 file.write('+++ bad syntax +++')
-            loader = _bootstrap._PyPycFileLoader('_temp', mapping['_temp'],
-                                                    False)
+            loader = _bootstrap._SourceFileLoader('_temp', mapping['_temp'])
             with self.assertRaises(SyntaxError):
                 loader.load_module(name)
             for attr in attributes:
@@ -106,17 +104,32 @@
         with source_util.create_modules('_temp') as mapping:
             with open(mapping['_temp'], 'w') as file:
                 file.write('=')
-            loader = _bootstrap._PyPycFileLoader('_temp', mapping['_temp'],
-                                                    False)
+            loader = _bootstrap._SourceFileLoader('_temp', mapping['_temp'])
             with self.assertRaises(SyntaxError):
                 loader.load_module('_temp')
             self.assertTrue('_temp' not in sys.modules)
 
+    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.write("# test file for importlib")
+        try:
+            with util.uncache('_temp'):
+                loader = _bootstrap._SourceFileLoader('_temp', '_temp.py')
+                mod = loader.load_module('_temp')
+                self.assertEqual('_temp.py', mod.__file__)
+                self.assertEqual(imp.cache_from_source('_temp.py'),
+                                 mod.__cached__)
+
+        finally:
+            os.unlink('_temp.py')
+
 
 class BadBytecodeTest(unittest.TestCase):
 
     def import_(self, file, module_name):
-        loader = _bootstrap._PyPycFileLoader(module_name, file, False)
+        loader = self.loader(module_name, file)
         module = loader.load_module(module_name)
         self.assertTrue(module_name in sys.modules)
 
@@ -129,101 +142,156 @@
         except KeyError:
             pass
         py_compile.compile(mapping[name])
-        bytecode_path = imp.cache_from_source(mapping[name])
-        with open(bytecode_path, 'rb') as file:
-            bc = file.read()
-        new_bc = manipulator(bc)
-        with open(bytecode_path, 'wb') as file:
-            if new_bc:
-                file.write(new_bc)
-        if del_source:
+        if not del_source:
+            bytecode_path = imp.cache_from_source(mapping[name])
+        else:
             os.unlink(mapping[name])
-            make_legacy_pyc(mapping[name])
+            bytecode_path = make_legacy_pyc(mapping[name])
+        if manipulator:
+            with open(bytecode_path, 'rb') as file:
+                bc = file.read()
+                new_bc = manipulator(bc)
+            with open(bytecode_path, 'wb') as file:
+                if new_bc is not None:
+                    file.write(new_bc)
         return bytecode_path
 
-    @source_util.writes_bytecode_files
-    def test_empty_file(self):
-        # When a .pyc is empty, regenerate it if possible, else raise
-        # ImportError.
+    def _test_empty_file(self, test, *, del_source=False):
         with source_util.create_modules('_temp') as mapping:
             bc_path = self.manipulate_bytecode('_temp', mapping,
-                                                lambda bc: None)
-            self.import_(mapping['_temp'], '_temp')
-            with open(bc_path, 'rb') as file:
-                self.assertGreater(len(file.read()), 8)
-            self.manipulate_bytecode('_temp', mapping, lambda bc: None,
-                                        del_source=True)
-            with self.assertRaises(ImportError):
-                self.import_(mapping['_temp'], '_temp')
+                                                lambda bc: b'',
+                                                del_source=del_source)
+            test('_temp', mapping, bc_path)
 
     @source_util.writes_bytecode_files
-    def test_partial_magic(self):
+    def _test_partial_magic(self, test, *, del_source=False):
         # When their are less than 4 bytes to a .pyc, regenerate it if
         # possible, else raise ImportError.
         with source_util.create_modules('_temp') as mapping:
             bc_path = self.manipulate_bytecode('_temp', mapping,
-                                                lambda bc: bc[:3])
-            self.import_(mapping['_temp'], '_temp')
-            with open(bc_path, 'rb') as file:
-                self.assertGreater(len(file.read()), 8)
-            self.manipulate_bytecode('_temp', mapping, lambda bc: bc[:3],
-                                        del_source=True)
+                                                lambda bc: bc[:3],
+                                                del_source=del_source)
+            test('_temp', mapping, bc_path)
+
+    def _test_magic_only(self, test, *, del_source=False):
+        with source_util.create_modules('_temp') as mapping:
+            bc_path = self.manipulate_bytecode('_temp', mapping,
+                                                lambda bc: bc[:4],
+                                                del_source=del_source)
+            test('_temp', mapping, bc_path)
+
+    def _test_partial_timestamp(self, test, *, del_source=False):
+        with source_util.create_modules('_temp') as mapping:
+            bc_path = self.manipulate_bytecode('_temp', mapping,
+                                                lambda bc: bc[:7],
+                                                del_source=del_source)
+            test('_temp', mapping, bc_path)
+
+    def _test_no_marshal(self, *, del_source=False):
+        with source_util.create_modules('_temp') as mapping:
+            bc_path = self.manipulate_bytecode('_temp', mapping,
+                                                lambda bc: bc[:8],
+                                                del_source=del_source)
+            file_path = mapping['_temp'] if not del_source else bc_path
+            with self.assertRaises(EOFError):
+                self.import_(file_path, '_temp')
+
+    def _test_non_code_marshal(self, *, del_source=False):
+        with source_util.create_modules('_temp') as mapping:
+            bytecode_path = self.manipulate_bytecode('_temp', mapping,
+                                    lambda bc: bc[:8] + marshal.dumps(b'abcd'),
+                                    del_source=del_source)
+            file_path = mapping['_temp'] if not del_source else bytecode_path
             with self.assertRaises(ImportError):
-                self.import_(mapping['_temp'], '_temp')
+                self.import_(file_path, '_temp')
+
+    def _test_bad_marshal(self, *, del_source=False):
+        with source_util.create_modules('_temp') as mapping:
+            bytecode_path = self.manipulate_bytecode('_temp', mapping,
+                                                lambda bc: bc[:8] + b'<test>',
+                                                del_source=del_source)
+            file_path = mapping['_temp'] if not del_source else bytecode_path
+            with self.assertRaises(ValueError):
+                self.import_(file_path, '_temp')
+
+    def _test_bad_magic(self, test, *, del_source=False):
+        with source_util.create_modules('_temp') as mapping:
+            bc_path = self.manipulate_bytecode('_temp', mapping,
+                                    lambda bc: b'\x00\x00\x00\x00' + bc[4:])
+            test('_temp', mapping, bc_path)
+
+
+class SourceLoaderBadBytecodeTest(BadBytecodeTest):
+
+    loader = _bootstrap._SourceFileLoader
+
+    @source_util.writes_bytecode_files
+    def test_empty_file(self):
+        # When a .pyc is empty, regenerate it if possible, else raise
+        # ImportError.
+        def test(name, mapping, bytecode_path):
+            self.import_(mapping[name], name)
+            with open(bytecode_path, 'rb') as file:
+                self.assertGreater(len(file.read()), 8)
+
+        self._test_empty_file(test)
+
+    def test_partial_magic(self):
+        def test(name, mapping, bytecode_path):
+            self.import_(mapping[name], name)
+            with open(bytecode_path, 'rb') as file:
+                self.assertGreater(len(file.read()), 8)
+
+        self._test_partial_magic(test)
 
     @source_util.writes_bytecode_files
     def test_magic_only(self):
         # When there is only the magic number, regenerate the .pyc if possible,
         # else raise EOFError.
-        with source_util.create_modules('_temp') as mapping:
-            bc_path = self.manipulate_bytecode('_temp', mapping,
-                                                lambda bc: bc[:4])
-            self.import_(mapping['_temp'], '_temp')
-            with open(bc_path, 'rb') as file:
+        def test(name, mapping, bytecode_path):
+            self.import_(mapping[name], name)
+            with open(bytecode_path, 'rb') as file:
                 self.assertGreater(len(file.read()), 8)
-            self.manipulate_bytecode('_temp', mapping, lambda bc: bc[:4],
-                                        del_source=True)
-            with self.assertRaises(EOFError):
-                self.import_(mapping['_temp'], '_temp')
+
+    @source_util.writes_bytecode_files
+    def test_bad_magic(self):
+        # When the magic number is different, the bytecode should be
+        # regenerated.
+        def test(name, mapping, bytecode_path):
+            self.import_(mapping[name], name)
+            with open(bytecode_path, 'rb') as bytecode_file:
+                self.assertEqual(bytecode_file.read(4), imp.get_magic())
+
+        self._test_bad_magic(test)
 
     @source_util.writes_bytecode_files
     def test_partial_timestamp(self):
         # When the timestamp is partial, regenerate the .pyc, else
         # raise EOFError.
-        with source_util.create_modules('_temp') as mapping:
-            bc_path = self.manipulate_bytecode('_temp', mapping,
-                                                lambda bc: bc[:7])
-            self.import_(mapping['_temp'], '_temp')
+        def test(name, mapping, bc_path):
+            self.import_(mapping[name], name)
             with open(bc_path, 'rb') as file:
                 self.assertGreater(len(file.read()), 8)
-            self.manipulate_bytecode('_temp', mapping, lambda bc: bc[:7],
-                                        del_source=True)
-            with self.assertRaises(EOFError):
-                self.import_(mapping['_temp'], '_temp')
 
     @source_util.writes_bytecode_files
     def test_no_marshal(self):
         # When there is only the magic number and timestamp, raise EOFError.
-        with source_util.create_modules('_temp') as mapping:
-            bc_path = self.manipulate_bytecode('_temp', mapping,
-                                                lambda bc: bc[:8])
-            with self.assertRaises(EOFError):
-                self.import_(mapping['_temp'], '_temp')
+        self._test_no_marshal()
 
     @source_util.writes_bytecode_files
-    def test_bad_magic(self):
-        # When the magic number is different, the bytecode should be
-        # regenerated.
-        with source_util.create_modules('_temp') as mapping:
-            bc_path = self.manipulate_bytecode('_temp', mapping,
-                                    lambda bc: b'\x00\x00\x00\x00' + bc[4:])
-            self.import_(mapping['_temp'], '_temp')
-            with open(bc_path, 'rb') as bytecode_file:
-                self.assertEqual(bytecode_file.read(4), imp.get_magic())
+    def test_non_code_marshal(self):
+        self._test_non_code_marshal()
+        # XXX ImportError when sourceless
+
+    # [bad marshal]
+    @source_util.writes_bytecode_files
+    def test_bad_marshal(self):
+        # Bad marshal data should raise a ValueError.
+        self._test_bad_marshal()
 
     # [bad timestamp]
     @source_util.writes_bytecode_files
-    def test_bad_bytecode(self):
+    def test_old_timestamp(self):
         # When the timestamp is older than the source, bytecode should be
         # regenerated.
         zeros = b'\x00\x00\x00\x00'
@@ -240,23 +308,6 @@
                 bytecode_file.seek(4)
                 self.assertEqual(bytecode_file.read(4), source_timestamp)
 
-    # [bad marshal]
-    @source_util.writes_bytecode_files
-    def test_bad_marshal(self):
-        # Bad marshal data should raise a ValueError.
-        with source_util.create_modules('_temp') as mapping:
-            bytecode_path = imp.cache_from_source(mapping['_temp'])
-            source_mtime = os.path.getmtime(mapping['_temp'])
-            source_timestamp = importlib._w_long(source_mtime)
-            source_util.ensure_bytecode_path(bytecode_path)
-            with open(bytecode_path, 'wb') as bytecode_file:
-                bytecode_file.write(imp.get_magic())
-                bytecode_file.write(source_timestamp)
-                bytecode_file.write(b'AAAA')
-            with self.assertRaises(ValueError):
-                self.import_(mapping['_temp'], '_temp')
-            self.assertTrue('_temp' not in sys.modules)
-
     # [bytecode read-only]
     @source_util.writes_bytecode_files
     def test_read_only_bytecode(self):
@@ -279,9 +330,57 @@
                 os.chmod(bytecode_path, stat.S_IWUSR)
 
 
+class SourcelessLoaderBadBytecodeTest(BadBytecodeTest):
+
+    loader = _bootstrap._SourcelessFileLoader
+
+    def test_empty_file(self):
+        def test(name, mapping, bytecode_path):
+            with self.assertRaises(ImportError):
+                self.import_(bytecode_path, name)
+
+        self._test_empty_file(test, del_source=True)
+
+    def test_partial_magic(self):
+        def test(name, mapping, bytecode_path):
+            with self.assertRaises(ImportError):
+                self.import_(bytecode_path, name)
+        self._test_partial_magic(test, del_source=True)
+
+    def test_magic_only(self):
+        def test(name, mapping, bytecode_path):
+            with self.assertRaises(EOFError):
+                self.import_(bytecode_path, name)
+
+        self._test_magic_only(test, del_source=True)
+
+    def test_bad_magic(self):
+        def test(name, mapping, bytecode_path):
+            with self.assertRaises(ImportError):
+                self.import_(bytecode_path, name)
+
+        self._test_bad_magic(test, del_source=True)
+
+    def test_partial_timestamp(self):
+        def test(name, mapping, bytecode_path):
+            with self.assertRaises(EOFError):
+                self.import_(bytecode_path, name)
+
+        self._test_partial_timestamp(test, del_source=True)
+
+    def test_no_marshal(self):
+        self._test_no_marshal(del_source=True)
+
+    def test_non_code_marshal(self):
+        self._test_non_code_marshal(del_source=True)
+
+
 def test_main():
     from test.support import run_unittest
-    run_unittest(SimpleTest, BadBytecodeTest)
+    run_unittest(SimpleTest,
+                 SourceLoaderBadBytecodeTest,
+                 SourcelessLoaderBadBytecodeTest
+                 )
 
 
 if __name__ == '__main__':

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_finder.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_finder.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_finder.py	Sat Jul 17 12:36:09 2010
@@ -34,7 +34,9 @@
     """
 
     def import_(self, root, module):
-        finder = _bootstrap._PyPycFileFinder(root)
+        finder = _bootstrap._FileFinder(root,
+                                        _bootstrap._SourceFinderDetails(),
+                                        _bootstrap._SourcelessFinderDetails())
         return finder.find_module(module)
 
     def run_test(self, test, create=None, *, compile_=None, unlink=None):
@@ -113,10 +115,9 @@
 
     # [package over modules]
     def test_package_over_module(self):
-        # XXX This is not a blackbox test!
         name = '_temp'
         loader = self.run_test(name, {'{0}.__init__'.format(name), name})
-        self.assertTrue('__init__' in loader._base_path)
+        self.assertTrue('__init__' in loader.get_filename(name))
 
 
     def test_failure(self):
@@ -131,6 +132,17 @@
             with self.assertRaises(ImportWarning):
                 self.run_test('pkg', {'pkg.__init__'}, unlink={'pkg.__init__'})
 
+    def test_empty_string_for_dir(self):
+        # The empty string from sys.path means to search in the cwd.
+        finder = _bootstrap._FileFinder('', _bootstrap._SourceFinderDetails())
+        with open('mod.py', 'w') as file:
+            file.write("# test file for importlib")
+        try:
+            loader = finder.find_module('mod')
+            self.assertTrue(hasattr(loader, 'load_module'))
+        finally:
+            os.unlink('mod.py')
+
 
 def test_main():
     from test.support import run_unittest

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_path_hook.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_path_hook.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_path_hook.py	Sat Jul 17 12:36:09 2010
@@ -8,11 +8,14 @@
     """Test the path hook for source."""
 
     def test_success(self):
-        # XXX Only work on existing directories?
         with source_util.create_modules('dummy') as mapping:
-            self.assertTrue(hasattr(_bootstrap._FileFinder(mapping['.root']),
+            self.assertTrue(hasattr(_bootstrap._file_path_hook(mapping['.root']),
                                  'find_module'))
 
+    def test_empty_string(self):
+        # The empty string represents the cwd.
+        self.assertTrue(hasattr(_bootstrap._file_path_hook(''), 'find_module'))
+
 
 def test_main():
     from test.support import run_unittest

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_source_encoding.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_source_encoding.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_source_encoding.py	Sat Jul 17 12:36:09 2010
@@ -35,8 +35,8 @@
         with source_util.create_modules(self.module_name) as mapping:
             with open(mapping[self.module_name], 'wb') as file:
                 file.write(source)
-            loader = _bootstrap._PyPycFileLoader(self.module_name,
-                                       mapping[self.module_name], False)
+            loader = _bootstrap._SourceFileLoader(self.module_name,
+                                       mapping[self.module_name])
             return loader.load_module(self.module_name)
 
     def create_source(self, encoding):
@@ -97,8 +97,8 @@
         with source_util.create_modules(module_name) as mapping:
             with open(mapping[module_name], 'wb') as file:
                 file.write(source)
-            loader = _bootstrap._PyPycFileLoader(module_name,
-                                                 mapping[module_name], False)
+            loader = _bootstrap._SourceFileLoader(module_name,
+                                                 mapping[module_name])
             return loader.load_module(module_name)
 
     # [cr]

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/test_abc.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/test_abc.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/test_abc.py	Sat Jul 17 12:36:09 2010
@@ -59,6 +59,11 @@
     subclasses = [abc.PyLoader]
 
 
+class SourceLoader(InheritanceTests, unittest.TestCase):
+
+    superclasses = [abc.ResourceLoader, abc.ExecutionLoader]
+
+
 class PyLoader(InheritanceTests, unittest.TestCase):
 
     superclasses = [abc.Loader, abc.ResourceLoader, abc.ExecutionLoader]

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/test_api.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/test_api.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/test_api.py	Sat Jul 17 12:36:09 2010
@@ -27,7 +27,7 @@
                 self.assertEqual(module.__name__, name)
 
     def test_shallow_relative_package_import(self):
-        # Test importing a module from a package through a relatve import.
+        # Test importing a module from a package through a relative import.
         pkg_name = 'pkg'
         pkg_long_name = '{0}.__init__'.format(pkg_name)
         module_name = 'mod'

Modified: python/branches/py3k-cdecimal/Lib/importlib/test/test_util.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/importlib/test/test_util.py	(original)
+++ python/branches/py3k-cdecimal/Lib/importlib/test/test_util.py	Sat Jul 17 12:36:09 2010
@@ -40,7 +40,7 @@
         with test_util.uncache(name):
             sys.modules[name] = module
             returned_module = self.return_module(name)
-            self.assertTrue(sys.modules[name] is returned_module)
+            self.assertIs(returned_module, sys.modules[name])
 
     def test_new_module_failure(self):
         # Test that a module is removed from sys.modules if added but an
@@ -57,7 +57,7 @@
         with test_util.uncache(name):
             sys.modules[name] = module
             self.raise_exception(name)
-            self.assertTrue(sys.modules[name] is module)
+            self.assertIs(module, sys.modules[name])
 
 
 class SetPackageTests(unittest.TestCase):

Modified: python/branches/py3k-cdecimal/Lib/inspect.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/inspect.py	(original)
+++ python/branches/py3k-cdecimal/Lib/inspect.py	Sat Jul 17 12:36:09 2010
@@ -437,7 +437,9 @@
     if info: return info[0]
 
 def getsourcefile(object):
-    """Return the Python source file an object was defined in, if it exists."""
+    """Return the filename that can be used to locate an object's source.
+    Return None if no way can be identified to get the source.
+    """
     filename = getfile(object)
     if filename[-4:].lower() in ('.pyc', '.pyo'):
         filename = filename[:-4] + '.py'
@@ -450,6 +452,9 @@
     # only return a non-existent filename if the module has a PEP 302 loader
     if hasattr(getmodule(object, filename), '__loader__'):
         return filename
+    # or it is in the linecache
+    if filename in linecache.cache:
+        return filename
 
 def getabsfile(object, _filename=None):
     """Return an absolute path to the source or compiled file for an object.
@@ -954,7 +959,7 @@
         else:
             arg2value[varargs] = ()
     elif 0 < num_args < num_pos:
-        raise TypeError('%s() takes %s %d %s (%d given)' % (
+        raise TypeError('%s() takes %s %d positional %s (%d given)' % (
             f_name, 'at most' if defaults else 'exactly', num_args,
             'arguments' if num_args > 1 else 'argument', num_total))
     elif num_args == 0 and num_total:

Modified: python/branches/py3k-cdecimal/Lib/lib2to3/fixes/fix_itertools_imports.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/lib2to3/fixes/fix_itertools_imports.py	(original)
+++ python/branches/py3k-cdecimal/Lib/lib2to3/fixes/fix_itertools_imports.py	Sat Jul 17 12:36:09 2010
@@ -20,6 +20,9 @@
             if child.type == token.NAME:
                 member = child.value
                 name_node = child
+            elif child.type == token.STAR:
+                # Just leave the import as is.
+                return
             else:
                 assert child.type == syms.import_as_name
                 name_node = child.children[0]
@@ -44,8 +47,8 @@
             children[-1].remove()
 
         # If there are no imports left, just get rid of the entire statement
-        if not (imports.children or getattr(imports, 'value', None)) or \
-                imports.parent is None:
+        if (not (imports.children or getattr(imports, 'value', None)) or
+            imports.parent is None):
             p = node.prefix
             node = BlankLine()
             node.prefix = p

Modified: python/branches/py3k-cdecimal/Lib/lib2to3/tests/test_fixers.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/lib2to3/tests/test_fixers.py	(original)
+++ python/branches/py3k-cdecimal/Lib/lib2to3/tests/test_fixers.py	Sat Jul 17 12:36:09 2010
@@ -3670,6 +3670,10 @@
         a = "from itertools import bar, filterfalse, foo"
         self.check(b, a)
 
+    def test_import_star(self):
+        s = "from itertools import *"
+        self.unchanged(s)
+
 
     def test_unchanged(self):
         s = "from itertools import foo"

Modified: python/branches/py3k-cdecimal/Lib/logging/config.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/logging/config.py	(original)
+++ python/branches/py3k-cdecimal/Lib/logging/config.py	Sat Jul 17 12:36:09 2010
@@ -386,15 +386,21 @@
         """
         name = s.split('.')
         used = name.pop(0)
-        found = self.importer(used)
-        for frag in name:
-            used += '.' + frag
-            try:
-                found = getattr(found, frag)
-            except AttributeError:
-                self.importer(used)
-                found = getattr(found, frag)
-        return found
+        try:
+            found = self.importer(used)
+            for frag in name:
+                used += '.' + frag
+                try:
+                    found = getattr(found, frag)
+                except AttributeError:
+                    self.importer(used)
+                    found = getattr(found, frag)
+            return found
+        except ImportError:
+            e, tb = sys.exc_info()[1:]
+            v = ValueError('Cannot resolve %r: %s' % (s, e))
+            v.__cause__, v.__traceback__ = e, tb
+            raise v
 
     def ext_convert(self, value):
         """Default converter for the ext:// protocol."""
@@ -873,6 +879,8 @@
         def run(self):
             server = self.rcvr(port=self.port, handler=self.hdlr,
                                ready=self.ready)
+            if self.port == 0:
+                self.port = server.server_address[1]
             self.ready.set()
             global _listener
             logging._acquireLock()

Modified: python/branches/py3k-cdecimal/Lib/macpath.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/macpath.py	(original)
+++ python/branches/py3k-cdecimal/Lib/macpath.py	Sat Jul 17 12:36:09 2010
@@ -32,6 +32,9 @@
 # Normalize the case of a pathname.  Dummy in Posix, but <s>.lower() here.
 
 def normcase(path):
+    if not isinstance(path, (bytes, str)):
+        raise TypeError("normcase() argument must be str or bytes, "
+                        "not '{}'".format(path.__class__.__name__))
     return path.lower()
 
 

Modified: python/branches/py3k-cdecimal/Lib/ntpath.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/ntpath.py	(original)
+++ python/branches/py3k-cdecimal/Lib/ntpath.py	Sat Jul 17 12:36:09 2010
@@ -16,7 +16,8 @@
            "getatime","getctime", "islink","exists","lexists","isdir","isfile",
            "ismount", "expanduser","expandvars","normpath","abspath",
            "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
-           "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
+           "extsep","devnull","realpath","supports_unicode_filenames","relpath",
+           "samefile",]
 
 # strings representing various path-related bits and pieces
 # These are primarily for export; internally, they are hardcoded.
@@ -78,6 +79,9 @@
     """Normalize case of pathname.
 
     Makes all characters lowercase and all slashes into backslashes."""
+    if not isinstance(s, (bytes, str)):
+        raise TypeError("normcase() argument must be str or bytes, "
+                        "not '{}'".format(s.__class__.__name__))
     return s.replace(_get_altsep(s), _get_sep(s)).lower()
 
 
@@ -306,16 +310,28 @@
     return split(p)[0]
 
 # Is a path a symbolic link?
-# This will always return false on systems where posix.lstat doesn't exist.
+# This will always return false on systems where os.lstat doesn't exist.
 
 def islink(path):
-    """Test for symbolic link.
-    On WindowsNT/95 and OS/2 always returns false
+    """Test whether a path is a symbolic link.
+    This will always return false for Windows prior to 6.0
+    and for OS/2.
     """
-    return False
-
-# alias exists to lexists
-lexists = exists
+    try:
+        st = os.lstat(path)
+    except (os.error, AttributeError):
+        return False
+    return stat.S_ISLNK(st.st_mode)
+
+# Being true for dangling symbolic links is also useful.
+
+def lexists(path):
+    """Test whether a path exists.  Returns True for broken symbolic links"""
+    try:
+        st = os.lstat(path)
+    except (os.error, WindowsError):
+        return False
+    return True
 
 # Is a path a mount point?  Either a root (with or without drive letter)
 # or an UNC path with at most a / or \ after the mount point.
@@ -609,3 +625,17 @@
     if not rel_list:
         return _get_dot(path)
     return join(*rel_list)
+
+
+# determine if two files are in fact the same file
+def samefile(f1, f2):
+    "Test whether two pathnames reference the same actual file"
+    try:
+        from nt import _getfinalpathname
+        return _getfinalpathname(f1) == _getfinalpathname(f2)
+    except (NotImplementedError, ImportError):
+        # On Windows XP and earlier, two files are the same if their
+        #  absolute pathnames are the same.
+        # Also, on other operating systems, fake this method with a
+        #  Windows-XP approximation.
+        return abspath(f1) == abspath(f2)

Modified: python/branches/py3k-cdecimal/Lib/os2emxpath.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/os2emxpath.py	(original)
+++ python/branches/py3k-cdecimal/Lib/os2emxpath.py	Sat Jul 17 12:36:09 2010
@@ -36,6 +36,9 @@
     """Normalize case of pathname.
 
     Makes all characters lowercase and all altseps into seps."""
+    if not isinstance(s, (bytes, str)):
+        raise TypeError("normcase() argument must be str or bytes, "
+                        "not '{}'".format(s.__class__.__name__))
     return s.replace('\\', '/').lower()
 
 

Modified: python/branches/py3k-cdecimal/Lib/pdb.doc
==============================================================================
--- python/branches/py3k-cdecimal/Lib/pdb.doc	(original)
+++ python/branches/py3k-cdecimal/Lib/pdb.doc	Sat Jul 17 12:36:09 2010
@@ -68,13 +68,13 @@
         An arrow indicates the "current frame", which determines the
         context of most commands.
 
-d(own)
-        Move the current frame one level down in the stack trace
-        (to a newer frame).
-
-u(p)
-        Move the current frame one level up in the stack trace
-        (to an older frame).
+d(own) [ count ]
+        Move the current frame count (default one) levels down in the
+        stack trace (to a newer frame).
+
+u(p) [ count ]
+        Move the current frame count (default one) levels up in the
+        stack trace (to an older frame).
 
 b(reak) [ ([filename:]lineno | function) [, condition] ]
         With a filename:line number argument, set a break there.  If
@@ -138,8 +138,8 @@
 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".
+        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.

Modified: python/branches/py3k-cdecimal/Lib/pdb.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/pdb.py	(original)
+++ python/branches/py3k-cdecimal/Lib/pdb.py	Sat Jul 17 12:36:09 2010
@@ -618,26 +618,44 @@
     do_w = do_where
     do_bt = do_where
 
+    def _select_frame(self, number):
+        assert 0 <= number < len(self.stack)
+        self.curindex = number
+        self.curframe = self.stack[self.curindex][0]
+        self.curframe_locals = self.curframe.f_locals
+        self.print_stack_entry(self.stack[self.curindex])
+        self.lineno = None
+
     def do_up(self, arg):
         if self.curindex == 0:
             print('*** Oldest frame', file=self.stdout)
+            return
+        try:
+            count = int(arg or 1)
+        except ValueError:
+            print('*** Invalid frame count (%s)' % arg, file=self.stdout)
+            return
+        if count < 0:
+            newframe = 0
         else:
-            self.curindex = self.curindex - 1
-            self.curframe = self.stack[self.curindex][0]
-            self.curframe_locals = self.curframe.f_locals
-            self.print_stack_entry(self.stack[self.curindex])
-            self.lineno = None
+            newframe = max(0, self.curindex - count)
+        self._select_frame(newframe)
     do_u = do_up
 
     def do_down(self, arg):
         if self.curindex + 1 == len(self.stack):
             print('*** Newest frame', file=self.stdout)
+            return
+        try:
+            count = int(arg or 1)
+        except ValueError:
+            print('*** Invalid frame count (%s)' % arg, file=self.stdout)
+            return
+        if count < 0:
+            newframe = len(self.stack) - 1
         else:
-            self.curindex = self.curindex + 1
-            self.curframe = self.stack[self.curindex][0]
-            self.curframe_locals = self.curframe.f_locals
-            self.print_stack_entry(self.stack[self.curindex])
-            self.lineno = None
+            newframe = min(len(self.stack) - 1, self.curindex + count)
+        self._select_frame(newframe)
     do_d = do_down
 
     def do_until(self, arg):

Modified: python/branches/py3k-cdecimal/Lib/pickletools.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/pickletools.py	(original)
+++ python/branches/py3k-cdecimal/Lib/pickletools.py	Sat Jul 17 12:36:09 2010
@@ -1250,10 +1250,11 @@
       stack_before=[anyobject],
       stack_after=[pytuple],
       proto=2,
-      doc="""One-tuple.
+      doc="""Build a one-tuple out of the topmost item on the stack.
 
       This code pops one value off the stack and pushes a tuple of
-      length 1 whose one item is that value back onto it.  IOW:
+      length 1 whose one item is that value back onto it.  In other
+      words:
 
           stack[-1] = tuple(stack[-1:])
       """),
@@ -1264,10 +1265,11 @@
       stack_before=[anyobject, anyobject],
       stack_after=[pytuple],
       proto=2,
-      doc="""One-tuple.
+      doc="""Build a two-tuple out of the top two items on the stack.
 
-      This code pops two values off the stack and pushes a tuple
-      of length 2 whose items are those values back onto it.  IOW:
+      This code pops two values off the stack and pushes a tuple of
+      length 2 whose items are those values back onto it.  In other
+      words:
 
           stack[-2:] = [tuple(stack[-2:])]
       """),
@@ -1278,10 +1280,11 @@
       stack_before=[anyobject, anyobject, anyobject],
       stack_after=[pytuple],
       proto=2,
-      doc="""One-tuple.
+      doc="""Build a three-tuple out of the top three items on the stack.
 
-      This code pops three values off the stack and pushes a tuple
-      of length 3 whose items are those values back onto it.  IOW:
+      This code pops three values off the stack and pushes a tuple of
+      length 3 whose items are those values back onto it.  In other
+      words:
 
           stack[-3:] = [tuple(stack[-3:])]
       """),
@@ -2330,4 +2333,43 @@
     return doctest.testmod()
 
 if __name__ == "__main__":
-    _test()
+    import sys, argparse
+    parser = argparse.ArgumentParser(
+        description='disassemble one or more pickle files')
+    parser.add_argument(
+        'pickle_file', type=argparse.FileType('br'),
+        nargs='*', help='the pickle file')
+    parser.add_argument(
+        '-o', '--output', default=sys.stdout, type=argparse.FileType('w'),
+        help='the file where the output should be written')
+    parser.add_argument(
+        '-m', '--memo', action='store_true',
+        help='preserve memo between disassemblies')
+    parser.add_argument(
+        '-l', '--indentlevel', default=4, type=int,
+        help='the number of blanks by which to indent a new MARK level')
+    parser.add_argument(
+        '-p', '--preamble', default="==> {name} <==",
+        help='if more than one pickle file is specified, print this before'
+        ' each disassembly')
+    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()
+        elif len(args.pickle_file) == 1:
+            dis(args.pickle_file[0], args.output,
+                indentlevel=args.indentlevel)
+        else:
+            memo = {} if args.memo else None
+            for f in args.pickle_file:
+                preamble = args.preamble.format(name=f.name)
+                args.output.write(preamble + '\n')
+                dis(f, args.output, memo, args.indentlevel)

Modified: python/branches/py3k-cdecimal/Lib/posixpath.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/posixpath.py	(original)
+++ python/branches/py3k-cdecimal/Lib/posixpath.py	Sat Jul 17 12:36:09 2010
@@ -49,6 +49,9 @@
 def normcase(s):
     """Normalize case of pathname.  Has no effect under Posix"""
     # TODO: on Mac OS X, this should really return s.lower().
+    if not isinstance(s, (bytes, str)):
+        raise TypeError("normcase() argument must be str or bytes, "
+                        "not '{}'".format(s.__class__.__name__))
     return s
 
 

Modified: python/branches/py3k-cdecimal/Lib/pydoc.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/pydoc.py	(original)
+++ python/branches/py3k-cdecimal/Lib/pydoc.py	Sat Jul 17 12:36:09 2010
@@ -1705,8 +1705,9 @@
             return ''
         return '<pydoc.Helper instance>'
 
-    def __call__(self, request=None):
-        if request is not None:
+    _GoInteractive = object()
+    def __call__(self, request=_GoInteractive):
+        if request is not self._GoInteractive:
             self.help(request)
         else:
             self.intro()

Modified: python/branches/py3k-cdecimal/Lib/site.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/site.py	(original)
+++ python/branches/py3k-cdecimal/Lib/site.py	Sat Jul 17 12:36:09 2010
@@ -273,12 +273,12 @@
     environment, and will return a list of full paths.
     """
     sitepackages = []
-    seen = []
+    seen = set()
 
     for prefix in PREFIXES:
         if not prefix or prefix in seen:
             continue
-        seen.append(prefix)
+        seen.add(prefix)
 
         if sys.platform in ('os2emx', 'riscos'):
             sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))

Modified: python/branches/py3k-cdecimal/Lib/smtpd.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/smtpd.py	(original)
+++ python/branches/py3k-cdecimal/Lib/smtpd.py	Sat Jul 17 12:36:09 2010
@@ -274,14 +274,19 @@
         self._localaddr = localaddr
         self._remoteaddr = remoteaddr
         asyncore.dispatcher.__init__(self)
-        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
-        # try to re-use a server port if possible
-        self.set_reuse_addr()
-        self.bind(localaddr)
-        self.listen(5)
-        print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
-            self.__class__.__name__, time.ctime(time.time()),
-            localaddr, remoteaddr), file=DEBUGSTREAM)
+        try:
+            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+            # try to re-use a server port if possible
+            self.set_reuse_addr()
+            self.bind(localaddr)
+            self.listen(5)
+        except:
+            self.close()
+            raise
+        else:
+            print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
+                self.__class__.__name__, time.ctime(time.time()),
+                localaddr, remoteaddr), file=DEBUGSTREAM)
 
     def handle_accept(self):
         conn, addr = self.accept()

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

Modified: python/branches/py3k-cdecimal/Lib/socket.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/socket.py	(original)
+++ python/branches/py3k-cdecimal/Lib/socket.py	Sat Jul 17 12:36:09 2010
@@ -252,10 +252,6 @@
         self._sock._decref_socketios()
         self._sock = None
 
-    def __del__(self):
-        if not self.closed:
-            self._sock._decref_socketios()
-
 
 def getfqdn(name=''):
     """Get fully qualified domain name from name.

Modified: python/branches/py3k-cdecimal/Lib/subprocess.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/subprocess.py	(original)
+++ python/branches/py3k-cdecimal/Lib/subprocess.py	Sat Jul 17 12:36:09 2010
@@ -500,8 +500,8 @@
 
     2) A string surrounded by double quotation marks is
        interpreted as a single argument, regardless of white space
-       or pipe characters contained within.  A quoted string can be
-       embedded in an argument.
+       contained within.  A quoted string can be embedded in an
+       argument.
 
     3) A double quotation mark preceded by a backslash is
        interpreted as a literal double quotation mark.
@@ -529,7 +529,7 @@
         if result:
             result.append(' ')
 
-        needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
+        needquote = (" " in arg) or ("\t" in arg) or not arg
         if needquote:
             result.append('"')
 

Modified: python/branches/py3k-cdecimal/Lib/sysconfig.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/sysconfig.py	(original)
+++ python/branches/py3k-cdecimal/Lib/sysconfig.py	Sat Jul 17 12:36:09 2010
@@ -123,8 +123,8 @@
 
 if _PYTHON_BUILD:
     for scheme in ('posix_prefix', 'posix_home'):
-        _INSTALL_SCHEMES[scheme]['include'] = '{projectbase}/Include'
-        _INSTALL_SCHEMES[scheme]['platinclude'] = '{srcdir}'
+        _INSTALL_SCHEMES[scheme]['include'] = '{srcdir}/Include'
+        _INSTALL_SCHEMES[scheme]['platinclude'] = '{projectbase}/.'
 
 def _subst_vars(s, local_vars):
     try:
@@ -259,6 +259,13 @@
                 # bogus variable reference; just drop it since we can't deal
                 variables.remove(name)
 
+    # Add in CFLAGS, LDFLAGS, and CPPFLAGS, which are named with a
+    # prefix in the Makefile.
+    for var in ('CFLAGS', 'LDFLAGS', 'CPPFLAGS'):
+        makefile_value = done.get('PY_' + var)
+        if makefile_value is not None:
+            done[var] = makefile_value
+
     # save the results in the global dictionary
     vars.update(done)
     return vars
@@ -432,6 +439,8 @@
 
         if 'srcdir' not in _CONFIG_VARS:
             _CONFIG_VARS['srcdir'] = _PROJECT_BASE
+        else:
+            _CONFIG_VARS['srcdir'] = realpath(_CONFIG_VARS['srcdir'])
 
 
         # Convert srcdir into an absolute path if it appears necessary.
@@ -651,8 +660,7 @@
                 cflags = get_config_vars().get('CFLAGS')
 
                 archs = re.findall('-arch\s+(\S+)', cflags)
-                archs.sort()
-                archs = tuple(archs)
+                archs = tuple(sorted(set(archs)))
 
                 if len(archs) == 1:
                     machine = archs[0]

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

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

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

Modified: python/branches/py3k-cdecimal/Lib/test/regrtest.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/regrtest.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/regrtest.py	Sat Jul 17 12:36:09 2010
@@ -152,6 +152,7 @@
 option '-uall,-gui'.
 """
 
+import builtins
 import getopt
 import json
 import os
@@ -859,15 +860,9 @@
         sys.path_hooks[:] = saved_hooks[2]
 
     def get___import__(self):
-        if isinstance(__builtins__, dict):
-            return __builtins__['__import__']
-        else:
-            return __builtins__.__import__
+        return builtins.__import__
     def restore___import__(self, import_):
-        if isinstance(__builtins__, dict):
-            __builtins__['__import__'] = import_
-        else:
-            __builtins__.__import__ = import_
+        builtins.__import__ = import_
 
     def get_warnings_filters(self):
         return id(warnings.filters), warnings.filters, warnings.filters[:]

Modified: python/branches/py3k-cdecimal/Lib/test/support.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/support.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/support.py	Sat Jul 17 12:36:09 2010
@@ -17,6 +17,7 @@
 import importlib
 import collections
 import re
+import subprocess
 import imp
 import time
 try:
@@ -38,8 +39,7 @@
     "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
     "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
     "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
-    "swap_item", "swap_attr",
-    ]
+    "swap_item", "swap_attr", "can_symlink", "skip_unless_symlink"]
 
 
 class Error(Exception):
@@ -109,7 +109,7 @@
         orig_modules[name] = sys.modules[name]
     except KeyError:
         saved = False
-    sys.modules[name] = 0
+    sys.modules[name] = None
     return saved
 
 
@@ -1169,6 +1169,27 @@
             except:
                 break
 
+try:
+    from .symlink_support import enable_symlink_privilege
+except:
+    enable_symlink_privilege = lambda: True
+
+def can_symlink():
+    """It's no longer sufficient to test for the presence of symlink in the
+    os module - on Windows XP and earlier, os.symlink exists but a
+    NotImplementedError is thrown.
+    """
+    has_symlink = hasattr(os, 'symlink')
+    is_old_windows = sys.platform == "win32" and sys.getwindowsversion().major < 6
+    has_privilege = False if is_old_windows else enable_symlink_privilege()
+    return has_symlink and (not is_old_windows) and has_privilege
+
+def skip_unless_symlink(test):
+    """Skip decorator for tests that require functional symlink"""
+    selector = can_symlink()
+    msg = "Requires functional symlink implementation"
+    return [unittest.skip(msg)(test), test][selector]
+
 @contextlib.contextmanager
 def swap_attr(obj, attr, new_val):
     """Temporary swap out an attribute with a new object.

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_audioop.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_audioop.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_audioop.py	Sat Jul 17 12:36:09 2010
@@ -20,6 +20,12 @@
 
 data = [gendata1(), gendata2(), gendata4()]
 
+INVALID_DATA = [
+    ('abc', 0),
+    ('abc', 2),
+    ('abc', 4),
+]
+
 
 class TestAudioop(unittest.TestCase):
 
@@ -168,6 +174,33 @@
         self.assertRaises(audioop.error,
             audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392)
 
+    def test_issue7673(self):
+        state = None
+        for data, size in INVALID_DATA:
+            size2 = size
+            self.assertRaises(audioop.error, audioop.getsample, data, size, 0)
+            self.assertRaises(audioop.error, audioop.max, data, size)
+            self.assertRaises(audioop.error, audioop.minmax, data, size)
+            self.assertRaises(audioop.error, audioop.avg, data, size)
+            self.assertRaises(audioop.error, audioop.rms, data, size)
+            self.assertRaises(audioop.error, audioop.avgpp, data, size)
+            self.assertRaises(audioop.error, audioop.maxpp, data, size)
+            self.assertRaises(audioop.error, audioop.cross, data, size)
+            self.assertRaises(audioop.error, audioop.mul, data, size, 1.0)
+            self.assertRaises(audioop.error, audioop.tomono, data, size, 0.5, 0.5)
+            self.assertRaises(audioop.error, audioop.tostereo, data, size, 0.5, 0.5)
+            self.assertRaises(audioop.error, audioop.add, data, data, size)
+            self.assertRaises(audioop.error, audioop.bias, data, size, 0)
+            self.assertRaises(audioop.error, audioop.reverse, data, size)
+            self.assertRaises(audioop.error, audioop.lin2lin, data, size, size2)
+            self.assertRaises(audioop.error, audioop.ratecv, data, size, 1, 1, 1, state)
+            self.assertRaises(audioop.error, audioop.lin2ulaw, data, size)
+            self.assertRaises(audioop.error, audioop.ulaw2lin, data, size)
+            self.assertRaises(audioop.error, audioop.lin2alaw, data, size)
+            self.assertRaises(audioop.error, audioop.alaw2lin, data, size)
+            self.assertRaises(audioop.error, audioop.lin2adpcm, data, size, state)
+            self.assertRaises(audioop.error, audioop.adpcm2lin, data, size, state)
+
 def test_main():
     run_unittest(TestAudioop)
 

Modified: python/branches/py3k-cdecimal/Lib/test/test_calendar.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_calendar.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_calendar.py	Sat Jul 17 12:36:09 2010
@@ -2,7 +2,7 @@
 import unittest
 
 from test import support
-
+import time
 
 result_2004_text = """
                                   2004
@@ -381,13 +381,21 @@
         # A 31-day december starting on friday (2+7+7+7+7+1 days)
         self.check_weeks(1995, 12, (2, 7, 7, 7, 7, 1))
 
+class TimegmTestCase(unittest.TestCase):
+    TIMESTAMPS = [0, 10, 100, 1000, 10000, 100000, 1000000,
+                  1234567890, 1262304000, 1275785153,]
+    def test_timegm(self):
+        for secs in self.TIMESTAMPS:
+            tuple = time.gmtime(secs)
+            self.assertEqual(secs, calendar.timegm(tuple))
 
 def test_main():
     support.run_unittest(
         OutputTestCase,
         CalendarTestCase,
         MondayTestCase,
-        SundayTestCase
+        SundayTestCase,
+        TimegmTestCase,
     )
 
 

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_codeccallbacks.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_codeccallbacks.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_codeccallbacks.py	Sat Jul 17 12:36:09 2010
@@ -153,28 +153,30 @@
             sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
         self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout)
 
-    def test_decoderelaxedutf8(self):
-        # This is the test for a decoding callback handler,
-        # that relaxes the UTF-8 minimal encoding restriction.
-        # A null byte that is encoded as "\xc0\x80" will be
-        # decoded as a null byte. All other illegal sequences
-        # will be handled strictly.
+    def test_decoding_callbacks(self):
+        # This is a test for a decoding callback handler
+        # that allows the decoding of the invalid sequence
+        # "\xc0\x80" and returns "\x00" instead of raising an error.
+        # All other illegal sequences will be handled strictly.
         def relaxedutf8(exc):
             if not isinstance(exc, UnicodeDecodeError):
                 raise TypeError("don't know how to handle %r" % exc)
-            if exc.object[exc.start:exc.end].startswith(b"\xc0\x80"):
+            if exc.object[exc.start:exc.start+2] == b"\xc0\x80":
                 return ("\x00", exc.start+2) # retry after two bytes
             else:
                 raise exc
 
-        codecs.register_error(
-            "test.relaxedutf8", relaxedutf8)
+        codecs.register_error("test.relaxedutf8", relaxedutf8)
 
+        # all the "\xc0\x80" will be decoded to "\x00"
         sin = b"a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80"
         sout = "a\x00b\x00c\xfc\x00\x00"
         self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout)
+
+        # "\xc0\x81" is not valid and a UnicodeDecodeError will be raised
         sin = b"\xc0\x80\xc0\x81"
-        self.assertRaises(UnicodeError, sin.decode, "utf-8", "test.relaxedutf8")
+        self.assertRaises(UnicodeDecodeError, sin.decode,
+                          "utf-8", "test.relaxedutf8")
 
     def test_charmapencode(self):
         # For charmap encodings the replacement string will be

Modified: python/branches/py3k-cdecimal/Lib/test/test_codecs.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_codecs.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_codecs.py	Sat Jul 17 12:36:09 2010
@@ -1263,6 +1263,7 @@
     "cp424",
     "cp437",
     "cp500",
+    "cp720",
     "cp737",
     "cp775",
     "cp850",
@@ -1270,6 +1271,7 @@
     "cp855",
     "cp856",
     "cp857",
+    "cp858",
     "cp860",
     "cp861",
     "cp862",
@@ -1358,11 +1360,6 @@
     "idna",
 ]
 
-# The following encodings only support "strict" mode
-only_strict_mode = [
-    "idna",
-]
-
 class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
     def test_basics(self):
         s = "abc123" # all codecs should be able to encode these
@@ -1437,7 +1434,7 @@
                     result = "".join(codecs.iterdecode(codecs.iterencode("", encoding), encoding))
                     self.assertEqual(result, "")
 
-                if encoding not in only_strict_mode:
+                if encoding not in ("idna", "mbcs"):
                     # check incremental decoder/encoder with errors argument
                     try:
                         encoder = codecs.getincrementalencoder(encoding)("ignore")

Modified: python/branches/py3k-cdecimal/Lib/test/test_collections.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_collections.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_collections.py	Sat Jul 17 12:36:09 2010
@@ -758,6 +758,19 @@
         od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)
         self.assertEqual(list(od.items()), pairs)                                   # mixed input
 
+        # Issue 9137: Named argument called 'other' or 'self'
+        # shouldn't be treated specially.
+        od = OrderedDict()
+        od.update(self=23)
+        self.assertEqual(list(od.items()), [('self', 23)])
+        od = OrderedDict()
+        od.update(other={})
+        self.assertEqual(list(od.items()), [('other', {})])
+        od = OrderedDict()
+        od.update(red=5, blue=6, other=7, self=8)
+        self.assertEqual(sorted(list(od.items())),
+                         [('blue', 6), ('other', 7), ('red', 5), ('self', 8)])
+
         # Make sure that direct calls to update do not clear previous contents
         # add that updates items are not moved to the end
         d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])

Modified: python/branches/py3k-cdecimal/Lib/test/test_complex.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_complex.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_complex.py	Sat Jul 17 12:36:09 2010
@@ -437,6 +437,23 @@
 
     @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                          "test requires IEEE 754 doubles")
+    def test_negated_imaginary_literal(self):
+        z0 = -0j
+        z1 = -7j
+        z2 = -1e1000j
+        # Note: In versions of Python < 3.2, a negated imaginary literal
+        # accidentally ended up with real part 0.0 instead of -0.0, thanks to a
+        # modification during CST -> AST translation (see issue #9011).  That's
+        # fixed in Python 3.2.
+        self.assertFloatsAreIdentical(z0.real, -0.0)
+        self.assertFloatsAreIdentical(z0.imag, -0.0)
+        self.assertFloatsAreIdentical(z1.real, -0.0)
+        self.assertFloatsAreIdentical(z1.imag, -7.0)
+        self.assertFloatsAreIdentical(z2.real, -0.0)
+        self.assertFloatsAreIdentical(z2.imag, -INF)
+
+    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
+                         "test requires IEEE 754 doubles")
     def test_overflow(self):
         self.assertEqual(complex("1e500"), complex(INF, 0.0))
         self.assertEqual(complex("-1e500j"), complex(0.0, -INF))

Modified: python/branches/py3k-cdecimal/Lib/test/test_contextlib.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_contextlib.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_contextlib.py	Sat Jul 17 12:36:09 2010
@@ -202,6 +202,169 @@
                 return True
         self.boilerPlate(lock, locked)
 
+
+class mycontext(ContextDecorator):
+    started = False
+    exc = None
+    catch = False
+
+    def __enter__(self):
+        self.started = True
+        return self
+
+    def __exit__(self, *exc):
+        self.exc = exc
+        return self.catch
+
+
+class TestContextDecorator(unittest.TestCase):
+
+    def test_contextdecorator(self):
+        context = mycontext()
+        with context as result:
+            self.assertIs(result, context)
+            self.assertTrue(context.started)
+
+        self.assertEqual(context.exc, (None, None, None))
+
+
+    def test_contextdecorator_with_exception(self):
+        context = mycontext()
+
+        with self.assertRaisesRegexp(NameError, 'foo'):
+            with context:
+                raise NameError('foo')
+        self.assertIsNotNone(context.exc)
+        self.assertIs(context.exc[0], NameError)
+
+        context = mycontext()
+        context.catch = True
+        with context:
+            raise NameError('foo')
+        self.assertIsNotNone(context.exc)
+        self.assertIs(context.exc[0], NameError)
+
+
+    def test_decorator(self):
+        context = mycontext()
+
+        @context
+        def test():
+            self.assertIsNone(context.exc)
+            self.assertTrue(context.started)
+        test()
+        self.assertEqual(context.exc, (None, None, None))
+
+
+    def test_decorator_with_exception(self):
+        context = mycontext()
+
+        @context
+        def test():
+            self.assertIsNone(context.exc)
+            self.assertTrue(context.started)
+            raise NameError('foo')
+
+        with self.assertRaisesRegexp(NameError, 'foo'):
+            test()
+        self.assertIsNotNone(context.exc)
+        self.assertIs(context.exc[0], NameError)
+
+
+    def test_decorating_method(self):
+        context = mycontext()
+
+        class Test(object):
+
+            @context
+            def method(self, a, b, c=None):
+                self.a = a
+                self.b = b
+                self.c = c
+
+        # these tests are for argument passing when used as a decorator
+        test = Test()
+        test.method(1, 2)
+        self.assertEqual(test.a, 1)
+        self.assertEqual(test.b, 2)
+        self.assertEqual(test.c, None)
+
+        test = Test()
+        test.method('a', 'b', 'c')
+        self.assertEqual(test.a, 'a')
+        self.assertEqual(test.b, 'b')
+        self.assertEqual(test.c, 'c')
+
+        test = Test()
+        test.method(a=1, b=2)
+        self.assertEqual(test.a, 1)
+        self.assertEqual(test.b, 2)
+
+
+    def test_typo_enter(self):
+        class mycontext(ContextDecorator):
+            def __unter__(self):
+                pass
+            def __exit__(self, *exc):
+                pass
+
+        with self.assertRaises(AttributeError):
+            with mycontext():
+                pass
+
+
+    def test_typo_exit(self):
+        class mycontext(ContextDecorator):
+            def __enter__(self):
+                pass
+            def __uxit__(self, *exc):
+                pass
+
+        with self.assertRaises(AttributeError):
+            with mycontext():
+                pass
+
+
+    def test_contextdecorator_as_mixin(self):
+        class somecontext(object):
+            started = False
+            exc = None
+
+            def __enter__(self):
+                self.started = True
+                return self
+
+            def __exit__(self, *exc):
+                self.exc = exc
+
+        class mycontext(somecontext, ContextDecorator):
+            pass
+
+        context = mycontext()
+        @context
+        def test():
+            self.assertIsNone(context.exc)
+            self.assertTrue(context.started)
+        test()
+        self.assertEqual(context.exc, (None, None, None))
+
+
+    def test_contextmanager_as_decorator(self):
+        state = []
+        @contextmanager
+        def woohoo(y):
+            state.append(y)
+            yield
+            state.append(999)
+
+        @woohoo(1)
+        def test(x):
+            self.assertEqual(state, [1])
+            state.append(x)
+        test('something')
+        self.assertEqual(state, [1, 'something', 999])
+
+
 # This is needed to make the test actually run under regrtest.py!
 def test_main():
     support.run_unittest(__name__)

Modified: python/branches/py3k-cdecimal/Lib/test/test_datetime.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_datetime.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_datetime.py	Sat Jul 17 12:36:09 2010
@@ -15,10 +15,13 @@
 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(3)]
-assert len(pickle_choices) == 3
+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.
@@ -49,6 +52,7 @@
 # tzinfo tests
 
 class FixedOffset(tzinfo):
+
     def __init__(self, offset, name, dstoffset=42):
         if isinstance(offset, int):
             offset = timedelta(minutes=offset)
@@ -67,6 +71,7 @@
         return self.__dstoffset
 
 class PicklableFixedOffset(FixedOffset):
+
     def __init__(self, offset=None, name=None, dstoffset=None):
         FixedOffset.__init__(self, offset, name, dstoffset)
 
@@ -118,18 +123,126 @@
     def test_pickling_subclass(self):
         # Make sure we can pickle/unpickle an instance of a subclass.
         offset = timedelta(minutes=-300)
-        orig = PicklableFixedOffset(offset, 'cookie')
-        self.assertIsInstance(orig, tzinfo)
-        self.assertTrue(type(orig) is PicklableFixedOffset)
-        self.assertEqual(orig.utcoffset(None), offset)
-        self.assertEqual(orig.tzname(None), 'cookie')
-        for pickler, unpickler, proto in pickle_choices:
-            green = pickler.dumps(orig, proto)
-            derived = unpickler.loads(green)
-            self.assertIsInstance(derived, tzinfo)
-            self.assertTrue(type(derived) is PicklableFixedOffset)
-            self.assertEqual(derived.utcoffset(None), offset)
-            self.assertEqual(derived.tzname(None), 'cookie')
+        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
@@ -206,6 +319,7 @@
         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))
@@ -283,6 +397,7 @@
         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):
@@ -408,10 +523,20 @@
                    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.
@@ -765,6 +890,7 @@
     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)))
@@ -790,6 +916,7 @@
         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:
@@ -1005,8 +1132,13 @@
             self.assertEqual(b.__format__(fmt), 'B')
 
     def test_resolution_info(self):
-        self.assertIsInstance(self.theclass.min, self.theclass)
-        self.assertIsInstance(self.theclass.max, self.theclass)
+        # 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)
 
@@ -1226,6 +1358,10 @@
         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
@@ -1587,8 +1723,8 @@
     def test_microsecond_rounding(self):
         # Test whether fromtimestamp "rounds up" floats that are less
         # than one microsecond smaller than an integer.
-        self.assertEquals(self.theclass.fromtimestamp(0.9999999),
-                          self.theclass.fromtimestamp(1))
+        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,
@@ -1616,7 +1752,7 @@
     @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
     def test_negative_float_utcfromtimestamp(self):
         d = self.theclass.utcfromtimestamp(-1.05)
-        self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
+        self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
 
     def test_utcnow(self):
         import time
@@ -1637,10 +1773,42 @@
 
         string = '2004-12-01 13:02:47.197'
         format = '%Y-%m-%d %H:%M:%S.%f'
-        result, frac = _strptime._strptime(string, format)
-        expected = self.theclass(*(result[0:6]+(frac,)))
+        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.
@@ -1695,6 +1863,8 @@
         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
@@ -1737,6 +1907,8 @@
             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)
@@ -1771,6 +1943,12 @@
         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
 
@@ -2707,6 +2885,11 @@
         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
@@ -2729,20 +2912,21 @@
         # 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.
-        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
         utc = FixedOffset(0, "utc", 0)
-        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")
+        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
@@ -2839,7 +3023,7 @@
 
     def test_utctimetuple(self):
         class DST(tzinfo):
-            def __init__(self, dstvalue):
+            def __init__(self, dstvalue=0):
                 if isinstance(dstvalue, int):
                     dstvalue = timedelta(minutes=dstvalue)
                 self.dstvalue = dstvalue
@@ -2858,8 +3042,6 @@
             def utcoffset(self, dt):
                 return self.uofs
 
-        # Ensure tm_isdst is 0 regardless of what dst() says:  DST is never
-        # in effect for a UTC time.
         for dstvalue in -33, 33, 0, None:
             d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue))
             t = d.utctimetuple()
@@ -2872,34 +3054,52 @@
             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)
 
-        # At the edges, UTC adjustment can normalize into years out-of-range
-        # for a datetime object.  Ensure that a correct timetuple is
-        # created anyway.
+        # 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.
-        t = tiny.utctimetuple()
-        self.assertEqual(t.tm_year, MINYEAR-1)
-        self.assertEqual(t.tm_mon, 12)
-        self.assertEqual(t.tm_mday, 31)
-        self.assertEqual(t.tm_hour, 0)
-        self.assertEqual(t.tm_min, 1)
-        self.assertEqual(t.tm_sec, 37)
-        self.assertEqual(t.tm_yday, 366)    # "year 0" is a leap year
-        self.assertEqual(t.tm_isdst, 0)
+        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.
-        t = huge.utctimetuple()
-        self.assertEqual(t.tm_year, MAXYEAR+1)
-        self.assertEqual(t.tm_mon, 1)
-        self.assertEqual(t.tm_mday, 1)
-        self.assertEqual(t.tm_hour, 23)
-        self.assertEqual(t.tm_min, 58)
-        self.assertEqual(t.tm_sec, 37)
-        self.assertEqual(t.tm_yday, 1)
-        self.assertEqual(t.tm_isdst, 0)
+        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")
@@ -3101,6 +3301,7 @@
     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.
@@ -3344,6 +3545,19 @@
             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)

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_descr.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_descr.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_descr.py	Sat Jul 17 12:36:09 2010
@@ -1,6 +1,7 @@
 import builtins
 import sys
 import types
+import math
 import unittest
 
 from copy import deepcopy
@@ -1578,6 +1579,9 @@
             ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
             ("__complex__", complex, complex_num, set(), {}),
             ("__format__", format, format_impl, set(), {}),
+            ("__floor__", math.floor, zero, set(), {}),
+            ("__trunc__", math.trunc, zero, set(), {}),
+            ("__ceil__", math.ceil, zero, set(), {}),
             ]
 
         class Checker(object):

Modified: python/branches/py3k-cdecimal/Lib/test/test_dict.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_dict.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_dict.py	Sat Jul 17 12:36:09 2010
@@ -664,6 +664,7 @@
         gc.collect()
         self.assertTrue(gc.is_tracked(t), t)
 
+    @support.cpython_only
     def test_track_literals(self):
         # Test GC-optimization of dict literals
         x, y, z, w = 1.5, "a", (1, None), []
@@ -681,6 +682,7 @@
         self._tracked({1: {}})
         self._tracked({1: set()})
 
+    @support.cpython_only
     def test_track_dynamic(self):
         # Test GC-optimization of dynamically-created dicts
         class MyObject(object):
@@ -744,6 +746,7 @@
         d.update([(x, y), (z, w)])
         self._tracked(d)
 
+    @support.cpython_only
     def test_track_subtypes(self):
         # Dict subtypes are always tracked
         class MyDict(dict):

Modified: python/branches/py3k-cdecimal/Lib/test/test_dis.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_dis.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_dis.py	Sat Jul 17 12:36:09 2010
@@ -96,6 +96,46 @@
 
 """
 
+expr_str = "x + 1"
+
+dis_expr_str = """\
+  1           0 LOAD_NAME                0 (x)
+              3 LOAD_CONST               0 (1)
+              6 BINARY_ADD
+              7 RETURN_VALUE
+"""
+
+simple_stmt_str = "x = x + 1"
+
+dis_simple_stmt_str = """\
+  1           0 LOAD_NAME                0 (x)
+              3 LOAD_CONST               0 (1)
+              6 BINARY_ADD
+              7 STORE_NAME               0 (x)
+             10 LOAD_CONST               1 (None)
+             13 RETURN_VALUE
+"""
+
+compound_stmt_str = """\
+x = 0
+while 1:
+    x += 1"""
+# Trailing newline has been deliberately omitted
+
+dis_compound_stmt_str = """\
+  1           0 LOAD_CONST               0 (0)
+              3 STORE_NAME               0 (x)
+
+  2           6 SETUP_LOOP              13 (to 22)
+
+  3     >>    9 LOAD_NAME                0 (x)
+             12 LOAD_CONST               1 (1)
+             15 INPLACE_ADD
+             16 STORE_NAME               0 (x)
+             19 JUMP_ABSOLUTE            9
+        >>   22 LOAD_CONST               2 (None)
+             25 RETURN_VALUE
+"""
 
 class DisTests(unittest.TestCase):
     def do_disassembly_test(self, func, expected):
@@ -166,6 +206,11 @@
         from test import dis_module
         self.do_disassembly_test(dis_module, dis_module_expected_results)
 
+    def test_disassemble_str(self):
+        self.do_disassembly_test(expr_str, dis_expr_str)
+        self.do_disassembly_test(simple_stmt_str, dis_simple_stmt_str)
+        self.do_disassembly_test(compound_stmt_str, dis_compound_stmt_str)
+
 def test_main():
     run_unittest(DisTests)
 

Modified: python/branches/py3k-cdecimal/Lib/test/test_enumerate.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_enumerate.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_enumerate.py	Sat Jul 17 12:36:09 2010
@@ -103,6 +103,7 @@
         self.assertRaises(TypeError, self.enum, 'abc', 'a') # wrong type
         self.assertRaises(TypeError, self.enum, 'abc', 2, 3) # too many arguments
 
+    @support.cpython_only
     def test_tuple_reuse(self):
         # Tests an implementation detail where tuple is reused
         # whenever nothing else holds a reference to it
@@ -145,6 +146,7 @@
         x = range(1)
         self.assertEqual(type(reversed(x)), type(iter(x)))
 
+    @support.cpython_only
     def test_len(self):
         # This is an implementation detail, not an interface requirement
         from test.test_iterlen import len

Modified: python/branches/py3k-cdecimal/Lib/test/test_exceptions.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_exceptions.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_exceptions.py	Sat Jul 17 12:36:09 2010
@@ -7,7 +7,7 @@
 import weakref
 
 from test.support import (TESTFN, unlink, run_unittest, captured_output,
-                          gc_collect)
+                          gc_collect, cpython_only)
 
 # XXX This is not really enough, each *operation* should be tested!
 
@@ -137,6 +137,7 @@
         ckmsg(s, "'continue' not properly in loop")
         ckmsg("continue\n", "'continue' not properly in loop")
 
+    @cpython_only
     def testSettingException(self):
         # test that setting an exception at the C level works even if the
         # exception object can't be constructed.
@@ -669,6 +670,7 @@
         tb2 = raiseMemError()
         self.assertEqual(tb1, tb2)
 
+    @cpython_only
     def test_exception_with_doc(self):
         import _testcapi
         doc2 = "This is a test docstring."

Modified: python/branches/py3k-cdecimal/Lib/test/test_extcall.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_extcall.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_extcall.py	Sat Jul 17 12:36:09 2010
@@ -279,13 +279,13 @@
     >>> f(6, a=4, *(1, 2, 3))
     Traceback (most recent call last):
       ...
-    TypeError: f() takes exactly 1 argument (5 given)
+    TypeError: f() takes exactly 1 positional argument (5 given)
     >>> def f(a, *, kw):
     ...    pass
     >>> f(6, 4, kw=4)
     Traceback (most recent call last):
       ...
-    TypeError: f() takes exactly 2 arguments (3 given)
+    TypeError: f() takes exactly 1 positional argument (3 given)
 """
 
 import sys

Modified: python/branches/py3k-cdecimal/Lib/test/test_float.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_float.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_float.py	Sat Jul 17 12:36:09 2010
@@ -7,13 +7,17 @@
 from math import isinf, isnan, copysign, ldexp
 import operator
 import random, fractions
-import re
 
 INF = float("inf")
 NAN = float("nan")
 
+have_getformat = hasattr(float, "__getformat__")
+requires_getformat = unittest.skipUnless(have_getformat,
+                                         "requires __getformat__")
+requires_setformat = unittest.skipUnless(hasattr(float, "__setformat__"),
+                                         "requires __setformat__")
 # decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
+requires_IEEE_754 = unittest.skipUnless(have_getformat and
     float.__getformat__("double").startswith("IEEE"),
     "test requires IEEE 754 doubles")
 
@@ -21,74 +25,6 @@
 test_dir = os.path.dirname(__file__) or os.curdir
 format_testfile = os.path.join(test_dir, 'formatfloat_testcases.txt')
 
-finite_decimal_parser = re.compile(r"""    # A numeric string consists of:
-    (?P<sign>[-+])?          # an optional sign, followed by
-    (?=\d|\.\d)              # a number with at least one digit
-    (?P<int>\d*)             # having a (possibly empty) integer part
-    (?:\.(?P<frac>\d*))?     # followed by an optional fractional part
-    (?:E(?P<exp>[-+]?\d+))?  # and an optional exponent
-    \Z
-""", re.VERBOSE | re.IGNORECASE | re.UNICODE).match
-
-# Pure Python version of correctly rounded string->float conversion.
-# Avoids any use of floating-point by returning the result as a hex string.
-def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024):
-    """Convert a finite decimal string to a hex string representing an
-    IEEE 754 binary64 float.  Return 'inf' or '-inf' on overflow.
-    This function makes no use of floating-point arithmetic at any
-    stage."""
-
-    # parse string into a pair of integers 'a' and 'b' such that
-    # abs(decimal value) = a/b, and a boolean 'negative'.
-    m = finite_decimal_parser(s)
-    if m is None:
-        raise ValueError('invalid numeric string')
-    fraction = m.group('frac') or ''
-    intpart = int(m.group('int') + fraction)
-    exp = int(m.group('exp') or '0') - len(fraction)
-    negative = m.group('sign') == '-'
-    a, b = intpart*10**max(exp, 0), 10**max(0, -exp)
-
-    # quick return for zeros
-    if not a:
-        return '-0x0.0p+0' if negative else '0x0.0p+0'
-
-    # compute exponent e for result; may be one too small in the case
-    # that the rounded value of a/b lies in a different binade from a/b
-    d = a.bit_length() - b.bit_length()
-    d += (a >> d if d >= 0 else a << -d) >= b
-    e = max(d, min_exp) - mant_dig
-
-    # approximate a/b by number of the form q * 2**e; adjust e if necessary
-    a, b = a << max(-e, 0), b << max(e, 0)
-    q, r = divmod(a, b)
-    if 2*r > b or 2*r == b and q & 1:
-        q += 1
-        if q.bit_length() == mant_dig+1:
-            q //= 2
-            e += 1
-
-    # double check that (q, e) has the right form
-    assert q.bit_length() <= mant_dig and e >= min_exp - mant_dig
-    assert q.bit_length() == mant_dig or e == min_exp - mant_dig
-
-    # check for overflow and underflow
-    if e + q.bit_length() > max_exp:
-        return '-inf' if negative else 'inf'
-    if not q:
-        return '-0x0.0p+0' if negative else '0x0.0p+0'
-
-    # for hex representation, shift so # bits after point is a multiple of 4
-    hexdigs = 1 + (mant_dig-2)//4
-    shift = 3 - (mant_dig-2)%4
-    q, e = q << shift, e - shift
-    return '{}0x{:x}.{:0{}x}p{:+d}'.format(
-        '-' if negative else '',
-        q // 16**hexdigs,
-        q % 16**hexdigs,
-        hexdigs,
-        e + 4*hexdigs)
-
 class GeneralFloatCases(unittest.TestCase):
 
     def test_float(self):
@@ -446,6 +382,7 @@
             #self.assertTrue(0.0 > pow_op(-2.0, -1047) > -1e-315)
 
 
+ at requires_setformat
 class FormatFunctionsTestCase(unittest.TestCase):
 
     def setUp(self):
@@ -496,6 +433,7 @@
 # on non-IEEE platforms, attempting to unpack a bit pattern
 # representing an infinity or a NaN should raise an exception.
 
+ at requires_setformat
 class UnknownFormatTestCase(unittest.TestCase):
     def setUp(self):
         self.save_formats = {'double':float.__getformat__('double'),
@@ -528,36 +466,25 @@
 # let's also try to guarantee that -0.0 and 0.0 don't get confused.
 
 class IEEEFormatTestCase(unittest.TestCase):
-    if float.__getformat__("double").startswith("IEEE"):
-        def test_double_specials_do_unpack(self):
-            for fmt, data in [('>d', BE_DOUBLE_INF),
-                              ('>d', BE_DOUBLE_NAN),
-                              ('<d', LE_DOUBLE_INF),
-                              ('<d', LE_DOUBLE_NAN)]:
-                struct.unpack(fmt, data)
-
-    if float.__getformat__("float").startswith("IEEE"):
-        def test_float_specials_do_unpack(self):
-            for fmt, data in [('>f', BE_FLOAT_INF),
-                              ('>f', BE_FLOAT_NAN),
-                              ('<f', LE_FLOAT_INF),
-                              ('<f', LE_FLOAT_NAN)]:
-                struct.unpack(fmt, data)
-
-    if float.__getformat__("double").startswith("IEEE"):
-        def test_negative_zero(self):
-            def pos_pos():
-                return 0.0, math.atan2(0.0, -1)
-            def pos_neg():
-                return 0.0, math.atan2(-0.0, -1)
-            def neg_pos():
-                return -0.0, math.atan2(0.0, -1)
-            def neg_neg():
-                return -0.0, math.atan2(-0.0, -1)
-            self.assertEquals(pos_pos(), neg_pos())
-            self.assertEquals(pos_neg(), neg_neg())
+
+    @requires_IEEE_754
+    def test_double_specials_do_unpack(self):
+        for fmt, data in [('>d', BE_DOUBLE_INF),
+                          ('>d', BE_DOUBLE_NAN),
+                          ('<d', LE_DOUBLE_INF),
+                          ('<d', LE_DOUBLE_NAN)]:
+            struct.unpack(fmt, data)
+
+    @requires_IEEE_754
+    def test_float_specials_do_unpack(self):
+        for fmt, data in [('>f', BE_FLOAT_INF),
+                          ('>f', BE_FLOAT_NAN),
+                          ('<f', LE_FLOAT_INF),
+                          ('<f', LE_FLOAT_NAN)]:
+            struct.unpack(fmt, data)
 
 class FormatTestCase(unittest.TestCase):
+
     def test_format(self):
         # these should be rewritten to use both format(x, spec) and
         # x.__format__(spec)
@@ -611,8 +538,7 @@
         self.assertEqual(format(INF, 'f'), 'inf')
         self.assertEqual(format(INF, 'F'), 'INF')
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
+    @requires_IEEE_754
     def test_format_testfile(self):
         for line in open(format_testfile):
             if line.startswith('--'):
@@ -692,9 +618,10 @@
             self.assertEqual(s, repr(float(s)))
             self.assertEqual(negs, repr(float(negs)))
 
+
+ at requires_IEEE_754
 class RoundTestCase(unittest.TestCase):
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
+
     def test_inf_nan(self):
         self.assertRaises(OverflowError, round, INF)
         self.assertRaises(OverflowError, round, -INF)
@@ -704,8 +631,6 @@
         self.assertRaises(TypeError, round, NAN, "ceci n'est pas un integer")
         self.assertRaises(TypeError, round, -0.0, 1j)
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
     def test_large_n(self):
         for n in [324, 325, 400, 2**31-1, 2**31, 2**32, 2**100]:
             self.assertEqual(round(123.456, n), 123.456)
@@ -718,8 +643,6 @@
         self.assertEqual(round(1e150, 309), 1e150)
         self.assertEqual(round(1.4e-315, 315), 1e-315)
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
     def test_small_n(self):
         for n in [-308, -309, -400, 1-2**31, -2**31, -2**31-1, -2**100]:
             self.assertEqual(round(123.456, n), 0.0)
@@ -727,8 +650,6 @@
             self.assertEqual(round(1e300, n), 0.0)
             self.assertEqual(round(1e-320, n), 0.0)
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
     def test_overflow(self):
         self.assertRaises(OverflowError, round, 1.6e308, -308)
         self.assertRaises(OverflowError, round, -1.7e308, -308)
@@ -776,9 +697,6 @@
             self.assertEqual(float(format(x, '.2f')), round(x, 2))
             self.assertEqual(float(format(x, '.3f')), round(x, 3))
 
-
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
     def test_format_specials(self):
         # Test formatting of nans and infs.
 
@@ -1334,38 +1252,6 @@
             else:
                 self.identical(x, fromHex(toHex(x)))
 
-class StrtodTestCase(unittest.TestCase):
-    def check_string(self, s):
-        expected = strtod(s)
-        try:
-            fs = float(s)
-        except OverflowError:
-            got = '-inf' if s[0] == '-' else 'inf'
-        else:
-            got = fs.hex()
-        self.assertEqual(expected, got,
-                         "Incorrectly rounded str->float conversion for "
-                         "{}: expected {}, got {}".format(s, expected, got))
-
-    @unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
-                         "applies only when using short float repr style")
-    def test_bug7632(self):
-        # check a few particular values that gave incorrectly rounded
-        # results with previous versions of dtoa.c
-        test_strings = [
-            '94393431193180696942841837085033647913224148539854e-358',
-            '12579816049008305546974391768996369464963024663104e-357',
-            '17489628565202117263145367596028389348922981857013e-357',
-            '18487398785991994634182916638542680759613590482273e-357',
-            '32002864200581033134358724675198044527469366773928e-358',
-            '73608278998966969345824653500136787876436005957953e-358',
-            '64774478836417299491718435234611299336288082136054e-358',
-            '13704940134126574534878641876947980878824688451169e-357',
-            '46697445774047060960624497964425416610480524760471e-358',
-            ]
-        for s in test_strings:
-            self.check_string(s)
-
 
 def test_main():
     support.run_unittest(
@@ -1378,7 +1264,6 @@
         RoundTestCase,
         InfNanTest,
         HexFloatTestCase,
-        StrtodTestCase,
         )
 
 if __name__ == '__main__':

Modified: python/branches/py3k-cdecimal/Lib/test/test_fnmatch.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_fnmatch.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_fnmatch.py	Sat Jul 17 12:36:09 2010
@@ -3,10 +3,14 @@
 from test import support
 import unittest
 
-from fnmatch import fnmatch, fnmatchcase
+from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _cacheb, purge
 
 
 class FnmatchTestCase(unittest.TestCase):
+
+    def tearDown(self):
+        purge()
+
     def check_match(self, filename, pattern, should_match=1, fn=fnmatch):
         if should_match:
             self.assertTrue(fn(filename, pattern),
@@ -60,6 +64,21 @@
         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)
+
 
 def test_main():
     support.run_unittest(FnmatchTestCase)

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_genericpath.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_genericpath.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_genericpath.py	Sat Jul 17 12:36:09 2010
@@ -194,14 +194,18 @@
     ]
 
     def test_normcase(self):
-        # Check that normcase() is idempotent
-        p = "FoO/./BaR"
-        p = self.pathmodule.normcase(p)
-        self.assertEqual(p, self.pathmodule.normcase(p))
-
-        p = b"FoO/./BaR"
-        p = self.pathmodule.normcase(p)
-        self.assertEqual(p, self.pathmodule.normcase(p))
+        normcase = self.pathmodule.normcase
+        # check that normcase() is idempotent
+        for p in ["FoO/./BaR", b"FoO/./BaR"]:
+            p = normcase(p)
+            self.assertEqual(p, normcase(p))
+
+        self.assertEqual(normcase(''), '')
+        self.assertEqual(normcase(b''), b'')
+
+        # check that normcase raises a TypeError for invalid types
+        for path in (None, True, 0, 2.5, [], bytearray(b''), {'o','o'}):
+            self.assertRaises(TypeError, normcase, path)
 
     def test_splitdrive(self):
         # splitdrive for non-NT paths

Modified: python/branches/py3k-cdecimal/Lib/test/test_getargs2.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_getargs2.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_getargs2.py	Sat Jul 17 12:36:09 2010
@@ -325,7 +325,7 @@
         from _testcapi import getargs_z
         self.assertEqual(getargs_z('abc\xe9'), b'abc\xc3\xa9')
         self.assertRaises(TypeError, getargs_z, 'nul:\0')
-        self.assertEqual(getargs_z(b'bytes'), b'bytes')
+        self.assertRaises(TypeError, getargs_z, b'bytes')
         self.assertRaises(TypeError, getargs_z, bytearray(b'bytearray'))
         self.assertRaises(TypeError, getargs_z, memoryview(b'memoryview'))
         self.assertIsNone(getargs_z(None))
@@ -375,6 +375,16 @@
         self.assertRaises(TypeError, getargs_y_hash, memoryview(b'memoryview'))
         self.assertRaises(TypeError, getargs_y_hash, None)
 
+    def test_w_star(self):
+        # getargs_w_star() modifies first and last byte
+        from _testcapi import getargs_w_star
+        self.assertRaises(TypeError, getargs_w_star, 'abc\xe9')
+        self.assertRaises(TypeError, getargs_w_star, b'bytes')
+        self.assertRaises(TypeError, getargs_w_star, b'nul:\0')
+        self.assertEqual(getargs_w_star(bytearray(b'bytearray')), b'[ytearra]')
+        self.assertEqual(getargs_w_star(memoryview(b'memoryview')), b'[emoryvie]')
+        self.assertRaises(TypeError, getargs_w_star, None)
+
 
 class Unicode_TestCase(unittest.TestCase):
     def test_u(self):

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_http_cookiejar.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_http_cookiejar.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_http_cookiejar.py	Sat Jul 17 12:36:09 2010
@@ -97,6 +97,7 @@
 
 
 class HeaderTests(TestCase):
+
     def test_parse_ns_headers(self):
         # quotes should be stripped
         expected = [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]]
@@ -106,6 +107,16 @@
             ]:
             self.assertEquals(parse_ns_headers([hdr]), expected)
 
+    def test_parse_ns_headers_version(self):
+
+        # quotes should be stripped
+        expected = [[('foo', 'bar'), ('version', '1')]]
+        for hdr in [
+            'foo=bar; version="1"',
+            'foo=bar; Version="1"',
+            ]:
+            self.assertEquals(parse_ns_headers([hdr]), expected)
+
     def test_parse_ns_headers_special_names(self):
         # names such as 'expires' are not special in first name=value pair
         # of Set-Cookie: header
@@ -1020,6 +1031,8 @@
             ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
             # bad max-age
             ["Set-Cookie: b=foo; max-age=oops"],
+            # bad version
+            ["Set-Cookie: b=foo; version=spam"],
             ]:
             c = cookiejar_from_cookie_headers(headers)
             # these bad cookies shouldn't be set

Modified: python/branches/py3k-cdecimal/Lib/test/test_httpservers.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_httpservers.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_httpservers.py	Sat Jul 17 12:36:09 2010
@@ -299,7 +299,7 @@
 
         # The shebang line should be pure ASCII: use symlink if possible.
         # See issue #7668.
-        if hasattr(os, 'symlink'):
+        if support.can_symlink():
             self.pythonexe = os.path.join(self.parent_dir, 'python')
             os.symlink(sys.executable, self.pythonexe)
         else:

Modified: python/branches/py3k-cdecimal/Lib/test/test_imp.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_imp.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_imp.py	Sat Jul 17 12:36:09 2010
@@ -44,7 +44,7 @@
 class ImportTests(unittest.TestCase):
 
     def test_find_module_encoding(self):
-        fd = imp.find_module("heapq")[0]
+        fd = imp.find_module("pydoc")[0]
         self.assertEqual(fd.encoding, "iso-8859-1")
 
     def test_issue1267(self):

Modified: python/branches/py3k-cdecimal/Lib/test/test_import.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_import.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_import.py	Sat Jul 17 12:36:09 2010
@@ -147,22 +147,24 @@
         filename = module + '.py'
 
         # Create a file with a list of 65000 elements.
-        with open(filename, 'w+') as f:
+        with open(filename, 'w') as f:
             f.write('d = [\n')
             for i in range(65000):
                 f.write('"",\n')
             f.write(']')
 
-        # Compile & remove .py file; we only need .pyc (or .pyo).
-        # Bytecode must be relocated from the PEP 3147 bytecode-only location.
-        py_compile.compile(filename)
-        unlink(filename)
-        make_legacy_pyc(filename)
+        try:
+            # Compile & remove .py file; we only need .pyc (or .pyo).
+            # Bytecode must be relocated from the PEP 3147 bytecode-only location.
+            py_compile.compile(filename)
+        finally:
+            unlink(filename)
 
         # Need to be able to load from current dir.
         sys.path.append('')
 
         try:
+            make_legacy_pyc(filename)
             # This used to crash.
             exec('import ' + module)
         finally:
@@ -468,6 +470,17 @@
         ns = dict(__package__=object())
         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.
+        # Issue #7902.
+        try:
+            from .os import sep
+        except ImportError:
+            pass
+        else:
+            self.fail("explicit relative import triggered an "
+                      "implicit relative import")
 
 class OverridingImportBuiltinTests(unittest.TestCase):
     def test_override_builtin(self):

Modified: python/branches/py3k-cdecimal/Lib/test/test_inspect.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_inspect.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_inspect.py	Sat Jul 17 12:36:09 2010
@@ -3,6 +3,7 @@
 import types
 import unittest
 import inspect
+import linecache
 import datetime
 import collections
 from os.path import normcase
@@ -275,6 +276,11 @@
     def test_getsourcefile(self):
         self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile)
         self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile)
+        fn = "_non_existing_filename_used_for_sourcefile_test.py"
+        co = compile("None", fn, "exec")
+        self.assertEqual(inspect.getsourcefile(co), None)
+        linecache.cache[co.co_filename] = (1, None, "None", co.co_filename)
+        self.assertEqual(normcase(inspect.getsourcefile(co)), fn)
 
     def test_getfile(self):
         self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
@@ -373,6 +379,15 @@
         self.assertRaises(IOError, inspect.getsource, unicodedata)
         self.assertRaises(IOError, inspect.findsource, unicodedata)
 
+    def test_findsource_code_in_linecache(self):
+        lines = ["x=1"]
+        co = compile(lines[0], "_dynamically_created_file", "exec")
+        self.assertRaises(IOError, inspect.findsource, co)
+        self.assertRaises(IOError, inspect.getsource, co)
+        linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
+        self.assertEquals(inspect.findsource(co), (lines,0))
+        self.assertEquals(inspect.getsource(co), lines[0])
+
 # Helper for testing classify_class_attrs.
 def attrs_wo_objs(cls):
     return [t[:3] for t in inspect.classify_class_attrs(cls)]

Modified: python/branches/py3k-cdecimal/Lib/test/test_iter.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_iter.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_iter.py	Sat Jul 17 12:36:09 2010
@@ -1,7 +1,7 @@
 # Test iterators.
 
 import unittest
-from test.support import run_unittest, TESTFN, unlink
+from test.support import run_unittest, TESTFN, unlink, cpython_only
 
 # Test result of triple loop (too big to inline)
 TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2),
@@ -761,8 +761,9 @@
         (a, b), (c,) = IteratingSequenceClass(2), {42: 24}
         self.assertEqual((a, b, c), (0, 1, 42))
 
-        # Test reference count behavior
 
+    @cpython_only
+    def test_ref_counting_behavior(self):
         class C(object):
             count = 0
             def __new__(cls):

Modified: python/branches/py3k-cdecimal/Lib/test/test_keywordonlyarg.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_keywordonlyarg.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_keywordonlyarg.py	Sat Jul 17 12:36:09 2010
@@ -73,6 +73,14 @@
         fundef3 += "lastarg):\n  pass\n"
         compile(fundef3, "<test>", "single")
 
+    def testTooManyPositionalErrorMessage(self):
+        def f(a, b=None, *, c=None):
+            pass
+        with self.assertRaises(TypeError) as exc:
+            f(1, 2, 3)
+        expected = "f() takes at most 2 positional arguments (3 given)"
+        self.assertEqual(str(exc.exception), expected)
+
     def testSyntaxErrorForFunctionCall(self):
         self.assertRaisesSyntaxError("f(p, k=1, p2)")
         self.assertRaisesSyntaxError("f(p, k1=50, *(1,2), k1=100)")

Modified: python/branches/py3k-cdecimal/Lib/test/test_logging.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_logging.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_logging.py	Sat Jul 17 12:36:09 2010
@@ -1670,6 +1670,8 @@
         t = logging.config.listen(port)
         t.start()
         t.ready.wait()
+        # Now get the port allocated
+        port = t.port
         t.ready.clear()
         try:
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Modified: python/branches/py3k-cdecimal/Lib/test/test_math.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_math.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_math.py	Sat Jul 17 12:36:09 2010
@@ -647,15 +647,7 @@
 
     def testLog1p(self):
         self.assertRaises(TypeError, math.log1p)
-        self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1)
-        self.ftest('log1p(0)', math.log1p(0), 0)
-        self.ftest('log1p(e-1)', math.log1p(math.e-1), 1)
-        self.ftest('log1p(1)', math.log1p(1), math.log(2))
-        self.assertEquals(math.log1p(INF), INF)
-        self.assertRaises(ValueError, math.log1p, NINF)
-        self.assertTrue(math.isnan(math.log1p(NAN)))
         n= 2**90
-        self.assertAlmostEquals(math.log1p(n), 62.383246250395075)
         self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
 
     def testLog10(self):
@@ -923,12 +915,14 @@
         self.assertRaises(TypeError, math.trunc, 1, 2)
         self.assertRaises(TypeError, math.trunc, TestNoTrunc())
 
-        # XXX Doesn't work because the method is looked up on
-        #     the type only.
-        #t = TestNoTrunc()
-        #t.__trunc__ = lambda *args: args
-        #self.assertEquals((), math.trunc(t))
-        #self.assertRaises(TypeError, math.trunc, t, 0)
+    def testIsfinite(self):
+        self.assertTrue(math.isfinite(0.0))
+        self.assertTrue(math.isfinite(-0.0))
+        self.assertTrue(math.isfinite(1.0))
+        self.assertTrue(math.isfinite(-1.0))
+        self.assertFalse(math.isfinite(float("nan")))
+        self.assertFalse(math.isfinite(float("inf")))
+        self.assertFalse(math.isfinite(float("-inf")))
 
     def testIsnan(self):
         self.assertTrue(math.isnan(float("nan")))

Modified: python/branches/py3k-cdecimal/Lib/test/test_optparse.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_optparse.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_optparse.py	Sat Jul 17 12:36:09 2010
@@ -754,6 +754,11 @@
                            {'a': "-b3", 'boo': None, 'foo': None},
                            [])
 
+    def test_combined_single_invalid_option(self):
+        self.parser.add_option("-t", action="store_true")
+        self.assertParseFail(["-test"],
+                             "no such option: -e")
+
 class TestBool(BaseTest):
     def setUp(self):
         options = [make_option("-v",

Modified: python/branches/py3k-cdecimal/Lib/test/test_os.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_os.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_os.py	Sat Jul 17 12:36:09 2010
@@ -58,6 +58,7 @@
         os.closerange(first, first + 2)
         self.assertRaises(OSError, os.write, first, b"a")
 
+    @support.cpython_only
     def test_rename(self):
         path = support.TESTFN
         old = sys.getrefcount(path)
@@ -519,7 +520,7 @@
             f = open(path, "w")
             f.write("I'm " + path + " and proud of it.  Blame test_os.\n")
             f.close()
-        if hasattr(os, "symlink"):
+        if support.can_symlink():
             os.symlink(os.path.abspath(t2_path), link_path)
             sub2_tree = (sub2_path, ["link"], ["tmp3"])
         else:
@@ -563,7 +564,7 @@
         self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
         self.assertEqual(all[2 - 2 * flipped], sub2_tree)
 
-        if hasattr(os, "symlink"):
+        if support.can_symlink():
             # Walk, following symlinks.
             for root, dirs, files in os.walk(walk_path, followlinks=True):
                 if root == link_path:
@@ -1032,6 +1033,84 @@
         self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
 
 
+def skipUnlessWindows6(test):
+    if (hasattr(sys, 'getwindowsversion')
+        and sys.getwindowsversion().major >= 6):
+        return test
+    return unittest.skip("Requires Windows Vista or later")(test)
+
+ at unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
+ at support.skip_unless_symlink
+class Win32SymlinkTests(unittest.TestCase):
+    filelink = 'filelinktest'
+    filelink_target = os.path.abspath(__file__)
+    dirlink = 'dirlinktest'
+    dirlink_target = os.path.dirname(filelink_target)
+    missing_link = 'missing link'
+
+    def setUp(self):
+        assert os.path.exists(self.dirlink_target)
+        assert os.path.exists(self.filelink_target)
+        assert not os.path.exists(self.dirlink)
+        assert not os.path.exists(self.filelink)
+        assert not os.path.exists(self.missing_link)
+
+    def tearDown(self):
+        if os.path.exists(self.filelink):
+            os.remove(self.filelink)
+        if os.path.exists(self.dirlink):
+            os.rmdir(self.dirlink)
+        if os.path.lexists(self.missing_link):
+            os.remove(self.missing_link)
+
+    def test_directory_link(self):
+        os.symlink(self.dirlink_target, self.dirlink)
+        self.assertTrue(os.path.exists(self.dirlink))
+        self.assertTrue(os.path.isdir(self.dirlink))
+        self.assertTrue(os.path.islink(self.dirlink))
+        self.check_stat(self.dirlink, self.dirlink_target)
+
+    def test_file_link(self):
+        os.symlink(self.filelink_target, self.filelink)
+        self.assertTrue(os.path.exists(self.filelink))
+        self.assertTrue(os.path.isfile(self.filelink))
+        self.assertTrue(os.path.islink(self.filelink))
+        self.check_stat(self.filelink, self.filelink_target)
+
+    def _create_missing_dir_link(self):
+        'Create a "directory" link to a non-existent target'
+        linkname = self.missing_link
+        if os.path.lexists(linkname):
+            os.remove(linkname)
+        target = r'c:\\target does not exist.29r3c740'
+        assert not os.path.exists(target)
+        target_is_dir = True
+        os.symlink(target, linkname, target_is_dir)
+
+    def test_remove_directory_link_to_missing_target(self):
+        self._create_missing_dir_link()
+        # For compatibility with Unix, os.remove will check the
+        #  directory status and call RemoveDirectory if the symlink
+        #  was created with target_is_dir==True.
+        os.remove(self.missing_link)
+
+    @unittest.skip("currently fails; consider for improvement")
+    def test_isdir_on_directory_link_to_missing_target(self):
+        self._create_missing_dir_link()
+        # consider having isdir return true for directory links
+        self.assertTrue(os.path.isdir(self.missing_link))
+
+    @unittest.skip("currently fails; consider for improvement")
+    def test_rmdir_on_directory_link_to_missing_target(self):
+        self._create_missing_dir_link()
+        # consider allowing rmdir to remove directory links
+        os.rmdir(self.missing_link)
+
+    def check_stat(self, link, target):
+        self.assertEqual(os.stat(link), os.stat(target))
+        self.assertNotEqual(os.lstat(link), os.stat(link))
+
+
 class MiscTests(unittest.TestCase):
 
     @unittest.skipIf(os.name == "nt", "POSIX specific test")
@@ -1055,6 +1134,7 @@
         PosixUidGidTests,
         Pep383Tests,
         Win32KillTests,
+        Win32SymlinkTests,
         MiscTests,
     )
 

Modified: python/branches/py3k-cdecimal/Lib/test/test_parser.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_parser.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_parser.py	Sat Jul 17 12:36:09 2010
@@ -149,6 +149,13 @@
     def test_class_defs(self):
         self.check_suite("class foo():pass")
         self.check_suite("class foo(object):pass")
+        self.check_suite("@class_decorator\n"
+                         "class foo():pass")
+        self.check_suite("@class_decorator(arg)\n"
+                         "class foo():pass")
+        self.check_suite("@decorator1\n"
+                         "@decorator2\n"
+                         "class foo():pass")
 
     def test_import_from_statement(self):
         self.check_suite("from sys.path import *")
@@ -182,6 +189,18 @@
         self.check_suite("import sys as system, math")
         self.check_suite("import sys, math as my_math")
 
+    def test_relative_imports(self):
+        self.check_suite("from . import name")
+        self.check_suite("from .. import name")
+        # check all the way up to '....', since '...' is tokenized
+        # differently from '.' (it's an ellipsis token).
+        self.check_suite("from ... import name")
+        self.check_suite("from .... import name")
+        self.check_suite("from .pkg import name")
+        self.check_suite("from ..pkg import name")
+        self.check_suite("from ...pkg import name")
+        self.check_suite("from ....pkg import name")
+
     def test_pep263(self):
         self.check_suite("# -*- coding: iso-8859-1 -*-\n"
                          "pass\n")
@@ -457,6 +476,20 @@
                 (0, ''))
         self.check_bad_tree(tree, "malformed global ast")
 
+    def test_missing_import_source(self):
+        # from import fred
+        tree = \
+            (257,
+             (268,
+              (269,
+               (270,
+                (282,
+                 (284, (1, 'from'), (1, 'import'),
+                  (287, (285, (1, 'fred')))))),
+               (4, ''))),
+             (4, ''), (0, ''))
+        self.check_bad_tree(tree, "from import fred")
+
 
 class CompileTestCase(unittest.TestCase):
 
@@ -484,8 +517,18 @@
         st = parser.suite('a = "\\u1"')
         self.assertRaises(SyntaxError, parser.compilest, st)
 
+    def test_issue_9011(self):
+        # Issue 9011: compilation of an unary minus expression changed
+        # the meaning of the ST, so that a second compilation produced
+        # incorrect results.
+        st = parser.expr('-3')
+        code1 = parser.compilest(st)
+        self.assertEqual(eval(code1), -3)
+        code2 = parser.compilest(st)
+        self.assertEqual(eval(code2), -3)
+
 class ParserStackLimitTestCase(unittest.TestCase):
-    """try to push the parser to/over it's limits.
+    """try to push the parser to/over its limits.
     see http://bugs.python.org/issue1881 for a discussion
     """
     def _nested_expression(self, level):

Modified: python/branches/py3k-cdecimal/Lib/test/test_platform.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_platform.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_platform.py	Sat Jul 17 12:36:09 2010
@@ -10,20 +10,26 @@
     def test_architecture(self):
         res = platform.architecture()
 
-    if hasattr(os, "symlink"):
-        def test_architecture_via_symlink(self): # issue3762
-            def get(python):
-                cmd = [python, '-c',
-                    'import platform; print(platform.architecture())']
-                p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
-                return p.communicate()
-            real = os.path.realpath(sys.executable)
-            link = os.path.abspath(support.TESTFN)
-            os.symlink(real, link)
-            try:
-                self.assertEqual(get(real), get(link))
-            finally:
-                os.remove(link)
+    @support.skip_unless_symlink
+    def test_architecture_via_symlink(self): # issue3762
+        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
+        # to add the directory to the path.
+        if sys.platform == "win32":
+            os.environ["Path"] = "{};{}".format(
+                os.path.dirname(sys.executable), os.environ["Path"])
+
+        def get(python):
+            cmd = [python, '-c',
+                'import platform; print(platform.architecture())']
+            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+            return p.communicate()
+        real = os.path.realpath(sys.executable)
+        link = os.path.abspath(support.TESTFN)
+        os.symlink(real, link)
+        try:
+            self.assertEqual(get(real), get(link))
+        finally:
+            os.remove(link)
 
     def test_platform(self):
         for aliased in (False, True):

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_property.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_property.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_property.py	Sat Jul 17 12:36:09 2010
@@ -118,7 +118,7 @@
         self.assertEqual(base.__class__.spam.__doc__, "spam spam spam")
         self.assertEqual(sub.__class__.spam.__doc__, "spam spam spam")
 
-    @unittest.skipIf(sys.flags.optimize >= 1,
+    @unittest.skipIf(sys.flags.optimize >= 2,
                      "Docstrings are omitted with -O2 and above")
     def test_property_getter_doc_override(self):
         newgettersub = PropertySubNewGetter()

Modified: python/branches/py3k-cdecimal/Lib/test/test_pyexpat.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_pyexpat.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_pyexpat.py	Sat Jul 17 12:36:09 2010
@@ -184,7 +184,7 @@
             self.fail()
         except TypeError as e:
             self.assertEquals(str(e),
-                'ParserCreate() argument 2 must be string or None, not int')
+                'ParserCreate() argument 2 must be str or None, not int')
 
         try:
             expat.ParserCreate(namespace_separator='too long')

Modified: python/branches/py3k-cdecimal/Lib/test/test_runpy.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_runpy.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_runpy.py	Sat Jul 17 12:36:09 2010
@@ -6,7 +6,7 @@
 import re
 import tempfile
 import py_compile
-from test.support import forget, make_legacy_pyc, run_unittest, verbose
+from test.support import forget, make_legacy_pyc, run_unittest, unload, verbose
 from test.script_helper import (
     make_pkg, make_script, make_zip_pkg, make_zip_script, temp_dir)
 
@@ -174,6 +174,7 @@
             __import__(mod_name)
             os.remove(mod_fname)
             make_legacy_pyc(mod_fname)
+            unload(mod_name)  # In case loader caches paths
             if verbose: print("Running from compiled:", mod_name)
             d2 = run_module(mod_name) # Read from bytecode
             self.assertIn("x", d2)
@@ -197,6 +198,7 @@
             __import__(mod_name)
             os.remove(mod_fname)
             make_legacy_pyc(mod_fname)
+            unload(mod_name)  # In case loader caches paths
             if verbose: print("Running from compiled:", pkg_name)
             d2 = run_module(pkg_name) # Read from bytecode
             self.assertIn("x", d2)
@@ -252,6 +254,7 @@
             __import__(mod_name)
             os.remove(mod_fname)
             make_legacy_pyc(mod_fname)
+            unload(mod_name)  # In case the loader caches paths
             if verbose: print("Running from compiled:", mod_name)
             d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
             self.assertIn("__package__", d2)
@@ -405,7 +408,11 @@
 
 
 def test_main():
-    run_unittest(RunModuleCodeTest, RunModuleTest, RunPathTest)
+    run_unittest(
+                 RunModuleCodeTest,
+                 RunModuleTest,
+                 RunPathTest
+                 )
 
 if __name__ == "__main__":
     test_main()

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_strtod.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_strtod.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_strtod.py	Sat Jul 17 12:36:09 2010
@@ -23,6 +23,8 @@
     \Z
 """, re.VERBOSE | re.IGNORECASE).match
 
+# Pure Python version of correctly rounded string->float conversion.
+# Avoids any use of floating-point by returning the result as a hex string.
 def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024):
     """Convert a finite decimal string to a hex string representing an
     IEEE 754 binary64 float.  Return 'inf' or '-inf' on overflow.
@@ -259,6 +261,10 @@
             '18487398785991994634182916638542680759613590482273e-357',
             '32002864200581033134358724675198044527469366773928e-358',
             '94393431193180696942841837085033647913224148539854e-358',
+            '73608278998966969345824653500136787876436005957953e-358',
+            '64774478836417299491718435234611299336288082136054e-358',
+            '13704940134126574534878641876947980878824688451169e-357',
+            '46697445774047060960624497964425416610480524760471e-358',
             # failing case for bug introduced by METD in r77451 (attempted
             # fix for issue 7632, bug 2), and fixed in r77482.
             '28639097178261763178489759107321392745108491825303e-311',

Modified: python/branches/py3k-cdecimal/Lib/test/test_struct.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_struct.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_struct.py	Sat Jul 17 12:36:09 2010
@@ -47,8 +47,8 @@
 
         self.assertRaises(struct.error, struct.pack, 'iii', 3)
         self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
-        self.assertRaises(struct.error, struct.pack, 'i', 'foo')
-        self.assertRaises(struct.error, struct.pack, 'P', 'foo')
+        self.assertRaises((TypeError, struct.error), struct.pack, 'i', 'foo')
+        self.assertRaises((TypeError, struct.error), struct.pack, 'P', 'foo')
         self.assertRaises(struct.error, struct.unpack, 'd', b'flap')
         s = struct.pack('ii', 1, 2)
         self.assertRaises(struct.error, struct.unpack, 'iii', s)
@@ -234,7 +234,8 @@
                                                                  b'\x01' + got)
                 else:
                     # x is out of range -- verify pack realizes that.
-                    self.assertRaises(struct.error, pack, format, x)
+                    self.assertRaises((OverflowError, ValueError, struct.error),
+                                      pack, format, x)
 
             def run(self):
                 from random import randrange
@@ -438,12 +439,15 @@
 
         # Go beyond boundaries.
         small_buf = array.array('b', b' '*10)
-        self.assertRaises(struct.error, s.pack_into, small_buf, 0, test_string)
-        self.assertRaises(struct.error, s.pack_into, small_buf, 2, test_string)
+        self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0,
+                          test_string)
+        self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2,
+                          test_string)
 
         # Test bogus offset (issue 3694)
         sb = small_buf
-        self.assertRaises(TypeError, struct.pack_into, b'', sb, None)
+        self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb,
+                          None)
 
     def test_pack_into_fn(self):
         test_string = b'Reykjavik rocks, eow!'
@@ -463,8 +467,10 @@
 
         # Go beyond boundaries.
         small_buf = array.array('b', b' '*10)
-        self.assertRaises(struct.error, pack_into, small_buf, 0, test_string)
-        self.assertRaises(struct.error, pack_into, small_buf, 2, test_string)
+        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
+                          test_string)
+        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
+                          test_string)
 
     def test_unpack_with_buffer(self):
         # SF bug 1563759: struct.unpack doens't support buffer protocol objects
@@ -475,6 +481,9 @@
             self.assertEqual(value, 0x12345678)
 
     def test_bool(self):
+        class ExplodingBool(object):
+            def __bool__(self):
+                raise IOError
         for prefix in tuple("<>!=")+('',):
             false = (), [], [], '', 0
             true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2
@@ -503,8 +512,16 @@
                 self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
                                              %packed)
 
-            for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
-                self.assertTrue(struct.unpack('>?', c)[0])
+            try:
+                struct.pack(prefix + '?', ExplodingBool())
+            except IOError:
+                pass
+            else:
+                self.fail("Expected IOError: struct.pack(%r, "
+                          "ExplodingBool())" % (prefix + '?'))
+
+        for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
+            self.assertTrue(struct.unpack('>?', c)[0])
 
     def test_count_overflow(self):
         hugecount = '{}b'.format(sys.maxsize+1)

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_subprocess.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_subprocess.py	Sat Jul 17 12:36:09 2010
@@ -478,8 +478,6 @@
                          '"a\\\\b\\ c" d e')
         self.assertEqual(subprocess.list2cmdline(['ab', '']),
                          'ab ""')
-        self.assertEqual(subprocess.list2cmdline(['echo', 'foo|bar']),
-                         'echo "foo|bar"')
 
 
     def test_poll(self):

Modified: python/branches/py3k-cdecimal/Lib/test/test_syntax.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_syntax.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_syntax.py	Sat Jul 17 12:36:09 2010
@@ -478,10 +478,12 @@
 
 >>> del ()
 Traceback (most recent call last):
-   ...
-  File "<doctest test.test_syntax[50]>", line 1
 SyntaxError: can't delete ()
 
+>>> {1, 2, 3} = 42
+Traceback (most recent call last):
+SyntaxError: can't assign to literal
+
 """
 
 import re

Modified: python/branches/py3k-cdecimal/Lib/test/test_sysconfig.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_sysconfig.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_sysconfig.py	Sat Jul 17 12:36:09 2010
@@ -12,7 +12,7 @@
 from copy import copy, deepcopy
 
 from test.support import (run_unittest, TESTFN, unlink, get_attribute,
-                          captured_stdout)
+                          captured_stdout, skip_unless_symlink)
 
 import sysconfig
 from sysconfig import (get_paths, get_platform, get_config_vars,
@@ -239,17 +239,23 @@
                   'posix_home', 'posix_prefix', 'posix_user')
         self.assertEquals(get_scheme_names(), wanted)
 
+    @skip_unless_symlink
     def test_symlink(self):
+        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
+        # to add the directory to the path.
+        if sys.platform == "win32":
+            os.environ["Path"] = "{};{}".format(
+                os.path.dirname(sys.executable), os.environ["Path"])
+
         # Issue 7880
-        symlink = get_attribute(os, "symlink")
         def get(python):
             cmd = [python, '-c',
                    'import sysconfig; print(sysconfig.get_platform())']
-            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=os.environ)
             return p.communicate()
         real = os.path.realpath(sys.executable)
         link = os.path.abspath(TESTFN)
-        symlink(real, link)
+        os.symlink(real, link)
         try:
             self.assertEqual(get(real), get(link))
         finally:

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

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_tokenize.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_tokenize.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_tokenize.py	Sat Jul 17 12:36:09 2010
@@ -42,7 +42,7 @@
         ...
     IndentationError: unindent does not match any outer indentation level
 
-There are some standard formattig practises that are easy to get right.
+There are some standard formatting practices that are easy to get right.
 
     >>> roundtrip("if x == 1:\\n"
     ...           "    print(x)\\n")

Modified: python/branches/py3k-cdecimal/Lib/test/test_tuple.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_tuple.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_tuple.py	Sat Jul 17 12:36:09 2010
@@ -96,6 +96,7 @@
         gc.collect()
         self.assertTrue(gc.is_tracked(t), t)
 
+    @support.cpython_only
     def test_track_literals(self):
         # Test GC-optimization of tuple literals
         x, y, z = 1.5, "a", []
@@ -136,16 +137,19 @@
         self._tracked(tp(tuple([obj]) for obj in [x, y, z]))
         self._tracked(tuple(tp([obj]) for obj in [x, y, z]))
 
+    @support.cpython_only
     def test_track_dynamic(self):
         # Test GC-optimization of dynamically constructed tuples.
         self.check_track_dynamic(tuple, False)
 
+    @support.cpython_only
     def test_track_subtypes(self):
         # Tuple subtypes must always be tracked
         class MyTuple(tuple):
             pass
         self.check_track_dynamic(MyTuple, True)
 
+    @support.cpython_only
     def test_bug7466(self):
         # Trying to untrack an unfinished tuple could crash Python
         self._not_tracked(tuple(gc.collect() for i in range(101)))

Modified: python/branches/py3k-cdecimal/Lib/test/test_unicode.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_unicode.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_unicode.py	Sat Jul 17 12:36:09 2010
@@ -942,6 +942,159 @@
         # * strict decoding testing for all of the
         #   UTF8_ERROR cases in PyUnicode_DecodeUTF8
 
+    def test_utf8_decode_valid_sequences(self):
+        sequences = [
+            # single byte
+            (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
+            # 2 bytes
+            (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
+            # 3 bytes
+            (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
+            (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
+            # 4 bytes
+            (b'\xF0\x90\x80\x80', '\U00010000'),
+            (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
+        ]
+        for seq, res in sequences:
+            self.assertEqual(seq.decode('utf-8'), res)
+
+
+    def test_utf8_decode_invalid_sequences(self):
+        # continuation bytes in a sequence of 2, 3, or 4 bytes
+        continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
+        # start bytes of a 2-byte sequence equivalent to codepoints < 0x7F
+        invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
+        # start bytes of a 4-byte sequence equivalent to codepoints > 0x10FFFF
+        invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
+        invalid_start_bytes = (
+            continuation_bytes + invalid_2B_seq_start_bytes +
+            invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
+        )
+
+        for byte in invalid_start_bytes:
+            self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
+
+        for sb in invalid_2B_seq_start_bytes:
+            for cb in continuation_bytes:
+                self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
+
+        for sb in invalid_4B_seq_start_bytes:
+            for cb1 in continuation_bytes[:3]:
+                for cb3 in continuation_bytes[:3]:
+                    self.assertRaises(UnicodeDecodeError,
+                                      (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
+
+        for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xE0'+cb+b'\x80').decode, 'utf-8')
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
+        # surrogates
+        for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xED'+cb+b'\x80').decode, 'utf-8')
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xED'+cb+b'\xBF').decode, 'utf-8')
+        for cb in [bytes([x]) for x in range(0x80, 0x90)]:
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
+        for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
+            self.assertRaises(UnicodeDecodeError,
+                              (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
+
+    def test_issue8271(self):
+        # 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.
+        # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
+        # table 3-8, Row 2) for more information about the algorithm used.
+        FFFD = '\ufffd'
+        sequences = [
+            # invalid start bytes
+            (b'\x80', FFFD), # continuation byte
+            (b'\x80\x80', FFFD*2), # 2 continuation bytes
+            (b'\xc0', FFFD),
+            (b'\xc0\xc0', FFFD*2),
+            (b'\xc1', FFFD),
+            (b'\xc1\xc0', FFFD*2),
+            (b'\xc0\xc1', FFFD*2),
+            # with start byte of a 2-byte sequence
+            (b'\xc2', FFFD), # only the start byte
+            (b'\xc2\xc2', FFFD*2), # 2 start bytes
+            (b'\xc2\xc2\xc2', FFFD*3), # 2 start bytes
+            (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
+            # with start byte of a 3-byte sequence
+            (b'\xe1', FFFD), # only the start byte
+            (b'\xe1\xe1', FFFD*2), # 2 start bytes
+            (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
+            (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
+            (b'\xe1\x80', FFFD), # only 1 continuation byte
+            (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
+            (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
+            (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
+            (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
+            (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
+            (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
+            # with start byte of a 4-byte sequence
+            (b'\xf1', FFFD), # only the start byte
+            (b'\xf1\xf1', FFFD*2), # 2 start bytes
+            (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
+            (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
+            (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
+            (b'\xf1\x80', FFFD), # only 1 continuation bytes
+            (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
+            (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
+            (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
+            (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
+            (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
+            (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
+            (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
+            (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
+            (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
+            (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
+            (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
+            (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
+            # with invalid start byte of a 4-byte sequence (rfc2279)
+            (b'\xf5', FFFD), # only the start byte
+            (b'\xf5\xf5', FFFD*2), # 2 start bytes
+            (b'\xf5\x80', FFFD*2), # only 1 continuation byte
+            (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
+            (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
+            (b'\xf5\x80\x41', FFFD*2+'A'), #  1 valid cb and 1 invalid
+            (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
+            (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
+            # with invalid start byte of a 5-byte sequence (rfc2279)
+            (b'\xf8', FFFD), # only the start byte
+            (b'\xf8\xf8', FFFD*2), # 2 start bytes
+            (b'\xf8\x80', FFFD*2), # only one continuation byte
+            (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
+            (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
+            # with invalid start byte of a 6-byte sequence (rfc2279)
+            (b'\xfc', FFFD), # only the start byte
+            (b'\xfc\xfc', FFFD*2), # 2 start bytes
+            (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
+            (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
+            # invalid start byte
+            (b'\xfe', FFFD),
+            (b'\xfe\x80\x80', FFFD*3),
+            # other sequences
+            (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
+            (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
+            (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
+            (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
+             '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
+        ]
+        for n, (seq, res) in enumerate(sequences):
+            self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
+            self.assertEqual(seq.decode('utf-8', 'replace'), res)
+            self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
+            self.assertEqual(seq.decode('utf-8', 'ignore'),
+                             res.replace('\uFFFD', ''))
+
     def test_codecs_idna(self):
         # Test whether trailing dot is preserved
         self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
@@ -1039,8 +1192,8 @@
         s = bytes(range(128))
         for encoding in (
             'cp037', 'cp1026',
-            'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
-            'cp852', 'cp855', 'cp860', 'cp861', 'cp862',
+            'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
+            'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
             'cp863', 'cp865', 'cp866',
             'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
             'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
@@ -1067,8 +1220,8 @@
         s = bytes(range(128, 256))
         for encoding in (
             'cp037', 'cp1026',
-            'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
-            'cp852', 'cp855', 'cp860', 'cp861', 'cp862',
+            'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
+            'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
             'cp863', 'cp865', 'cp866',
             'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
             'iso8859_2', 'iso8859_4', 'iso8859_5',

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

Modified: python/branches/py3k-cdecimal/Lib/test/test_urllib.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_urllib.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_urllib.py	Sat Jul 17 12:36:09 2010
@@ -795,6 +795,116 @@
         self.assertEqual("a=a&a=b",
                          urllib.parse.urlencode({"a": {"a": 1, "b": 1}}, True))
 
+    def test_urlencode_encoding(self):
+        # ASCII encoding. Expect %3F with errors="replace'
+        given = (('\u00a0', '\u00c1'),)
+        expect = '%3F=%3F'
+        result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
+        self.assertEqual(expect, result)
+
+        # Default is UTF-8 encoding.
+        given = (('\u00a0', '\u00c1'),)
+        expect = '%C2%A0=%C3%81'
+        result = urllib.parse.urlencode(given)
+        self.assertEqual(expect, result)
+
+        # Latin-1 encoding.
+        given = (('\u00a0', '\u00c1'),)
+        expect = '%A0=%C1'
+        result = urllib.parse.urlencode(given, encoding="latin-1")
+        self.assertEqual(expect, result)
+
+    def test_urlencode_encoding_doseq(self):
+        # ASCII Encoding. Expect %3F with errors="replace'
+        given = (('\u00a0', '\u00c1'),)
+        expect = '%3F=%3F'
+        result = urllib.parse.urlencode(given, doseq=True,
+                                        encoding="ASCII", errors="replace")
+        self.assertEqual(expect, result)
+
+        # ASCII Encoding. On a sequence of values.
+        given = (("\u00a0", (1, "\u00c1")),)
+        expect = '%3F=1&%3F=%3F'
+        result = urllib.parse.urlencode(given, True,
+                                        encoding="ASCII", errors="replace")
+        self.assertEqual(expect, result)
+
+        # Utf-8
+        given = (("\u00a0", "\u00c1"),)
+        expect = '%C2%A0=%C3%81'
+        result = urllib.parse.urlencode(given, True)
+        self.assertEqual(expect, result)
+
+        given = (("\u00a0", (42, "\u00c1")),)
+        expect = '%C2%A0=42&%C2%A0=%C3%81'
+        result = urllib.parse.urlencode(given, True)
+        self.assertEqual(expect, result)
+
+        # latin-1
+        given = (("\u00a0", "\u00c1"),)
+        expect = '%A0=%C1'
+        result = urllib.parse.urlencode(given, True, encoding="latin-1")
+        self.assertEqual(expect, result)
+
+        given = (("\u00a0", (42, "\u00c1")),)
+        expect = '%A0=42&%A0=%C1'
+        result = urllib.parse.urlencode(given, True, encoding="latin-1")
+        self.assertEqual(expect, result)
+
+    def test_urlencode_bytes(self):
+        given = ((b'\xa0\x24', b'\xc1\x24'),)
+        expect = '%A0%24=%C1%24'
+        result = urllib.parse.urlencode(given)
+        self.assertEqual(expect, result)
+        result = urllib.parse.urlencode(given, True)
+        self.assertEqual(expect, result)
+
+        # Sequence of values
+        given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
+        expect = '%A0%24=42&%A0%24=%C1%24'
+        result = urllib.parse.urlencode(given, True)
+        self.assertEqual(expect, result)
+
+    def test_urlencode_encoding_safe_parameter(self):
+
+        # Send '$' (\x24) as safe character
+        # Default utf-8 encoding
+
+        given = ((b'\xa0\x24', b'\xc1\x24'),)
+        result = urllib.parse.urlencode(given, safe=":$")
+        expect = '%A0$=%C1$'
+        self.assertEqual(expect, result)
+
+        given = ((b'\xa0\x24', b'\xc1\x24'),)
+        result = urllib.parse.urlencode(given, doseq=True, safe=":$")
+        expect = '%A0$=%C1$'
+        self.assertEqual(expect, result)
+
+        # Safe parameter in sequence
+        given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
+        expect = '%A0$=%C1$&%A0$=13&%A0$=42'
+        result = urllib.parse.urlencode(given, True, safe=":$")
+        self.assertEqual(expect, result)
+
+        # Test all above in latin-1 encoding
+
+        given = ((b'\xa0\x24', b'\xc1\x24'),)
+        result = urllib.parse.urlencode(given, safe=":$",
+                                        encoding="latin-1")
+        expect = '%A0$=%C1$'
+        self.assertEqual(expect, result)
+
+        given = ((b'\xa0\x24', b'\xc1\x24'),)
+        expect = '%A0$=%C1$'
+        result = urllib.parse.urlencode(given, doseq=True, safe=":$",
+                                        encoding="latin-1")
+
+        given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
+        expect = '%A0$=%C1$&%A0$=13&%A0$=42'
+        result = urllib.parse.urlencode(given, True, safe=":$",
+                                        encoding="latin-1")
+        self.assertEqual(expect, result)
+
 class Pathname_Tests(unittest.TestCase):
     """Test pathname2url() and url2pathname()"""
 

Modified: python/branches/py3k-cdecimal/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_urllib2.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_urllib2.py	Sat Jul 17 12:36:09 2010
@@ -731,6 +731,8 @@
             ("file://ftp.example.com///foo.txt", False),
 # XXXX bug: fails with OSError, should be URLError
             ("file://ftp.example.com/foo.txt", False),
+            ("file://somehost//foo/something.txt", True),
+            ("file://localhost//foo/something.txt", False),
             ]:
             req = Request(url)
             try:
@@ -741,6 +743,7 @@
             else:
                 self.assertTrue(o.req is req)
                 self.assertEqual(req.type, "ftp")
+            self.assertEqual(req.type is "ftp", ftp)
 
     def test_http(self):
 

Modified: python/branches/py3k-cdecimal/Lib/test/test_urlparse.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_urlparse.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_urlparse.py	Sat Jul 17 12:36:09 2010
@@ -7,6 +7,7 @@
 RFC1808_BASE = "http://a/b/c/d;p?q#f"
 RFC2396_BASE = "http://a/b/c/d;p?q"
 RFC3986_BASE = 'http://a/b/c/d;p?q'
+SIMPLE_BASE  = 'http://a/b/c/d'
 
 # A list of test cases.  Each test case is a a two-tuple that contains
 # a string with the query and a dictionary with the expected result.
@@ -295,6 +296,37 @@
         #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser
         self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser
 
+    def test_urljoins(self):
+        self.checkJoin(SIMPLE_BASE, 'g:h','g:h')
+        self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
+        self.checkJoin(SIMPLE_BASE, 'g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, './g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, 'g/','http://a/b/c/g/')
+        self.checkJoin(SIMPLE_BASE, '/g','http://a/g')
+        self.checkJoin(SIMPLE_BASE, '//g','http://g')
+        self.checkJoin(SIMPLE_BASE, '?y','http://a/b/c/d?y')
+        self.checkJoin(SIMPLE_BASE, 'g?y','http://a/b/c/g?y')
+        self.checkJoin(SIMPLE_BASE, 'g?y/./x','http://a/b/c/g?y/./x')
+        self.checkJoin(SIMPLE_BASE, '.','http://a/b/c/')
+        self.checkJoin(SIMPLE_BASE, './','http://a/b/c/')
+        self.checkJoin(SIMPLE_BASE, '..','http://a/b/')
+        self.checkJoin(SIMPLE_BASE, '../','http://a/b/')
+        self.checkJoin(SIMPLE_BASE, '../g','http://a/b/g')
+        self.checkJoin(SIMPLE_BASE, '../..','http://a/')
+        self.checkJoin(SIMPLE_BASE, '../../g','http://a/g')
+        self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g')
+        self.checkJoin(SIMPLE_BASE, './../g','http://a/b/g')
+        self.checkJoin(SIMPLE_BASE, './g/.','http://a/b/c/g/')
+        self.checkJoin(SIMPLE_BASE, '/./g','http://a/./g')
+        self.checkJoin(SIMPLE_BASE, 'g/./h','http://a/b/c/g/h')
+        self.checkJoin(SIMPLE_BASE, 'g/../h','http://a/b/c/h')
+        self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
+        self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
+        self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y')
+        self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y')
+        self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x')
+
     def test_RFC2732(self):
         for url, hostname, port in [
             ('http://Test.python.org:5432/foo/', 'test.python.org', 5432),

Modified: python/branches/py3k-cdecimal/Lib/test/test_xmlrpc_net.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/test/test_xmlrpc_net.py	(original)
+++ python/branches/py3k-cdecimal/Lib/test/test_xmlrpc_net.py	Sat Jul 17 12:36:09 2010
@@ -48,7 +48,7 @@
         # Perform a minimal sanity check on the result, just to be sure
         # the request means what we think it means.
         self.assertIsInstance(builders, collections.Sequence)
-        self.assertTrue([x for x in builders if "trunk" in x], builders)
+        self.assertTrue([x for x in builders if "3.x" in x], builders)
 
 
 def test_main():

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

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

Modified: python/branches/py3k-cdecimal/Lib/urllib/parse.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/urllib/parse.py	(original)
+++ python/branches/py3k-cdecimal/Lib/urllib/parse.py	Sat Jul 17 12:36:09 2010
@@ -8,21 +8,22 @@
 RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
 and L.Masinter, December 1999.
 
-RFC2396:  "Uniform Resource Identifiers (URI)": Generic Syntax by T.
+RFC 2396:  "Uniform Resource Identifiers (URI)": Generic Syntax by T.
 Berners-Lee, R. Fielding, and L. Masinter, August 1998.
 
-RFC2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998.
+RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998.
 
 RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
 1995.
 
-RFC1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
+RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
 McCahill, December 1994
 
-RFC 3986 is considered the current standard and any changes to urlparse module
-should conform to this.  urlparse module is not entirely compliant with this.
-The defacto scenarios of parsing are considered sometimes and for backward
-compatiblity purposes, older RFC uses of parsing are retained. The testcases in
+RFC 3986 is considered the current standard and any future changes to
+urlparse module should conform with it.  The urlparse module is
+currently not entirely compliant with this RFC due to defacto
+scenarios for parsing, and for backward compatibility purposes, some
+parsing quirks from older RFCs are retained. The testcases in
 test_urlparse.py provides a good indicator of parsing behavior.
 """
 
@@ -220,6 +221,11 @@
     return urlunsplit((scheme, netloc, url, query, fragment))
 
 def urlunsplit(components):
+    """Combine the elements of a tuple as returned by urlsplit() into a
+    complete URL as a string. The data argument can be any five-item iterable.
+    This may result in a slightly different, but equivalent URL, if the URL that
+    was parsed originally had unnecessary delimiters (for example, a ? with an
+    empty query; the RFC states that these are equivalent)."""
     scheme, netloc, url, query, fragment = components
     if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
         if url and url[:1] != '/': url = '/' + url
@@ -553,7 +559,7 @@
         _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
     return ''.join([quoter(char) for char in bs])
 
-def urlencode(query, doseq=False):
+def urlencode(query, doseq=False, safe='', encoding=None, errors=None):
     """Encode a sequence of two-element tuples or dictionary into a URL query string.
 
     If any values in the query arg are sequences and doseq is true, each
@@ -562,6 +568,10 @@
     If the query arg is a sequence of two-element tuples, the order of the
     parameters in the output will match the order of parameters in the
     input.
+
+    The query arg may be either a string or a bytes type. When query arg is a
+    string, the safe, encoding and error parameters are sent the quote_plus for
+    encoding.
     """
 
     if hasattr(query, "items"):
@@ -586,14 +596,28 @@
     l = []
     if not doseq:
         for k, v in query:
-            k = quote_plus(str(k))
-            v = quote_plus(str(v))
+            if isinstance(k, bytes):
+                k = quote_plus(k, safe)
+            else:
+                k = quote_plus(str(k), safe, encoding, errors)
+
+            if isinstance(v, bytes):
+                v = quote_plus(v, safe)
+            else:
+                v = quote_plus(str(v), safe, encoding, errors)
             l.append(k + '=' + v)
     else:
         for k, v in query:
-            k = quote_plus(str(k))
-            if isinstance(v, str):
-                v = quote_plus(v)
+            if isinstance(k, bytes):
+                k = quote_plus(k, safe)
+            else:
+                k = quote_plus(str(k), safe, encoding, errors)
+
+            if isinstance(v, bytes):
+                v = quote_plus(v, safe)
+                l.append(k + '=' + v)
+            elif isinstance(v, str):
+                v = quote_plus(v, safe, encoding, errors)
                 l.append(k + '=' + v)
             else:
                 try:
@@ -601,12 +625,16 @@
                     x = len(v)
                 except TypeError:
                     # not a sequence
-                    v = quote_plus(str(v))
+                    v = quote_plus(str(v), safe, encoding, errors)
                     l.append(k + '=' + v)
                 else:
                     # loop over the sequence
                     for elt in v:
-                        l.append(k + '=' + quote_plus(str(elt)))
+                        if isinstance(elt, bytes):
+                            elt = quote_plus(elt, safe)
+                        else:
+                            elt = quote_plus(str(elt), safe, encoding, errors)
+                        l.append(k + '=' + elt)
     return '&'.join(l)
 
 # Utilities to parse URLs (most of these return None for missing parts):
@@ -771,67 +799,3 @@
     match = _valueprog.match(attr)
     if match: return match.group(1, 2)
     return attr, None
-
-test_input = """
-      http://a/b/c/d
-
-      g:h        = <URL:g:h>
-      http:g     = <URL:http://a/b/c/g>
-      http:      = <URL:http://a/b/c/d>
-      g          = <URL:http://a/b/c/g>
-      ./g        = <URL:http://a/b/c/g>
-      g/         = <URL:http://a/b/c/g/>
-      /g         = <URL:http://a/g>
-      //g        = <URL:http://g>
-      ?y         = <URL:http://a/b/c/d?y>
-      g?y        = <URL:http://a/b/c/g?y>
-      g?y/./x    = <URL:http://a/b/c/g?y/./x>
-      .          = <URL:http://a/b/c/>
-      ./         = <URL:http://a/b/c/>
-      ..         = <URL:http://a/b/>
-      ../        = <URL:http://a/b/>
-      ../g       = <URL:http://a/b/g>
-      ../..      = <URL:http://a/>
-      ../../g    = <URL:http://a/g>
-      ../../../g = <URL:http://a/../g>
-      ./../g     = <URL:http://a/b/g>
-      ./g/.      = <URL:http://a/b/c/g/>
-      /./g       = <URL:http://a/./g>
-      g/./h      = <URL:http://a/b/c/g/h>
-      g/../h     = <URL:http://a/b/c/h>
-      http:g     = <URL:http://a/b/c/g>
-      http:      = <URL:http://a/b/c/d>
-      http:?y         = <URL:http://a/b/c/d?y>
-      http:g?y        = <URL:http://a/b/c/g?y>
-      http:g?y/./x    = <URL:http://a/b/c/g?y/./x>
-"""
-
-def test():
-    base = ''
-    if sys.argv[1:]:
-        fn = sys.argv[1]
-        if fn == '-':
-            fp = sys.stdin
-        else:
-            fp = open(fn)
-    else:
-        from io import StringIO
-        fp = StringIO(test_input)
-    for line in fp:
-        words = line.split()
-        if not words:
-            continue
-        url = words[0]
-        parts = urlparse(url)
-        print('%-10s : %s' % (url, parts))
-        abs = urljoin(base, url)
-        if not base:
-            base = abs
-        wrapped = '<URL:%s>' % abs
-        print('%-10s = %s' % (url, wrapped))
-        if len(words) == 3 and words[1] == '=':
-            if wrapped != words[2]:
-                print('EXPECTED', words[2], '!!!!!!!!!!')
-
-if __name__ == '__main__':
-    test()

Modified: python/branches/py3k-cdecimal/Lib/urllib/request.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/urllib/request.py	(original)
+++ python/branches/py3k-cdecimal/Lib/urllib/request.py	Sat Jul 17 12:36:09 2010
@@ -1188,7 +1188,8 @@
     # Use local file or FTP depending on form of URL
     def file_open(self, req):
         url = req.selector
-        if url[:2] == '//' and url[2:3] != '/':
+        if url[:2] == '//' and url[2:3] != '/' and (req.host and
+                req.host != 'localhost'):
             req.type = 'ftp'
             return self.parent.open(req)
         else:
@@ -1866,7 +1867,8 @@
         else:
             return self.http_error_default(url, fp, errcode, errmsg, headers)
 
-    def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
+    def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
+            retry=False):
         """Error 401 -- authentication required.
         This function supports Basic authentication only."""
         if not 'www-authenticate' in headers:
@@ -1882,13 +1884,17 @@
         if scheme.lower() != 'basic':
             URLopener.http_error_default(self, url, fp,
                                          errcode, errmsg, headers)
+        if not retry:
+            URLopener.http_error_default(self, url, fp, errcode, errmsg,
+                    headers)
         name = 'retry_' + self.type + '_basic_auth'
         if data is None:
             return getattr(self,name)(url, realm)
         else:
             return getattr(self,name)(url, realm, data)
 
-    def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
+    def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
+            retry=False):
         """Error 407 -- proxy authentication required.
         This function supports Basic authentication only."""
         if not 'proxy-authenticate' in headers:
@@ -1904,6 +1910,9 @@
         if scheme.lower() != 'basic':
             URLopener.http_error_default(self, url, fp,
                                          errcode, errmsg, headers)
+        if not retry:
+            URLopener.http_error_default(self, url, fp, errcode, errmsg,
+                    headers)
         name = 'retry_proxy_' + self.type + '_basic_auth'
         if data is None:
             return getattr(self,name)(url, realm)
@@ -2196,8 +2205,13 @@
                         continue
 
                 base = ip2num(m.group(1))
-                mask = int(m.group(2)[1:])
-                mask = 32 - mask
+                mask = m.group(2)
+                if mask is None:
+                    mask = 8 * (m.group(1).count('.') + 1)
+
+                else:
+                    mask = int(mask[1:])
+                    mask = 32 - mask
 
                 if (hostIP >> mask) == (base >> mask):
                     return True
@@ -2265,6 +2279,7 @@
                         proxies['http'] = proxyServer
                     else:
                         proxies['http'] = 'http://%s' % proxyServer
+                        proxies['https'] = 'https://%s' % proxyServer
                         proxies['ftp'] = 'ftp://%s' % proxyServer
             internetSettings.Close()
         except (WindowsError, ValueError, TypeError):

Modified: python/branches/py3k-cdecimal/Lib/uuid.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/uuid.py	(original)
+++ python/branches/py3k-cdecimal/Lib/uuid.py	Sat Jul 17 12:36:09 2010
@@ -427,17 +427,17 @@
         if hasattr(lib, 'uuid_generate_time'):
             _uuid_generate_time = lib.uuid_generate_time
 
-    # The uuid_generate_* functions are broken on MacOS X 10.6, as noted
+    # The uuid_generate_* functions are broken on MacOS X 10.5, as noted
     # in issue #8621 the function generates the same sequence of values
     # in the parent process and all children created using fork (unless
     # those children use exec as well).
     #
-    # Assume that the uuid_generate functions are broken from 10.6 onward,
+    # Assume that the uuid_generate functions are broken from 10.5 onward,
     # the test can be adjusted when a later version is fixed.
     import sys
     if sys.platform == 'darwin':
         import os
-        if int(os.uname()[2].split('.')[0]) >= 10:
+        if int(os.uname()[2].split('.')[0]) >= 9:
             _uuid_generate_random = _uuid_generate_time = None
 
     # On Windows prior to 2000, UuidCreate gives a UUID containing the

Modified: python/branches/py3k-cdecimal/Lib/warnings.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/warnings.py	(original)
+++ python/branches/py3k-cdecimal/Lib/warnings.py	Sat Jul 17 12:36:09 2010
@@ -371,8 +371,10 @@
 # Module initialization
 _processoptions(sys.warnoptions)
 if not _warnings_defaults:
-    simplefilter("ignore", category=PendingDeprecationWarning, append=1)
-    simplefilter("ignore", category=ImportWarning, append=1)
+    silence = [ImportWarning, PendingDeprecationWarning]
+    silence.append(DeprecationWarning)
+    for cls in silence:
+        simplefilter("ignore", category=cls)
     bytes_warning = sys.flags.bytes_warning
     if bytes_warning > 1:
         bytes_action = "error"

Modified: python/branches/py3k-cdecimal/Lib/xml/dom/expatbuilder.py
==============================================================================
--- python/branches/py3k-cdecimal/Lib/xml/dom/expatbuilder.py	(original)
+++ python/branches/py3k-cdecimal/Lib/xml/dom/expatbuilder.py	Sat Jul 17 12:36:09 2010
@@ -242,7 +242,7 @@
         doctype = self.document.implementation.createDocumentType(
             doctypeName, publicId, systemId)
         doctype.ownerDocument = self.document
-        self.document.childNodes.append(doctype)
+        _append_child(self.document, doctype)
         self.document.doctype = doctype
         if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT:
             self.document.doctype = None

Modified: python/branches/py3k-cdecimal/Makefile.pre.in
==============================================================================
--- python/branches/py3k-cdecimal/Makefile.pre.in	(original)
+++ python/branches/py3k-cdecimal/Makefile.pre.in	Sat Jul 17 12:36:09 2010
@@ -59,12 +59,18 @@
 # Compiler options
 OPT=		@OPT@
 BASECFLAGS=	@BASECFLAGS@
-CFLAGS=		$(BASECFLAGS) @CFLAGS@ $(OPT) $(EXTRA_CFLAGS)
+CONFIGURE_CFLAGS=	@CFLAGS@
+CONFIGURE_CPPFLAGS=	@CPPFLAGS@
+CONFIGURE_LDFLAGS=	@LDFLAGS@
+# Avoid assigning CFLAGS, LDFLAGS, etc. so users can use them on the
+# command line to append to these values without stomping the pre-set
+# values.
+PY_CFLAGS=	$(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS)
 # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to
 # be able to build extension modules using the directories specified in the
 # environment variables
-CPPFLAGS=	-I. -IInclude -I$(srcdir)/Include @CPPFLAGS@
-LDFLAGS=	@LDFLAGS@
+PY_CPPFLAGS=	-I. -IInclude -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS)
+PY_LDFLAGS=	$(CONFIGURE_LDFLAGS) $(LDFLAGS)
 LDLAST=		@LDLAST@
 SGI_ABI=	@SGI_ABI@
 CCSHARED=	@CCSHARED@
@@ -73,7 +79,7 @@
 # Extra C flags added for building the interpreter object files.
 CFLAGSFORSHARED=@CFLAGSFORSHARED@
 # C flags used for building the interpreter object files
-PY_CFLAGS=	$(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE
+PY_CORE_CFLAGS=	$(PY_CFLAGS) $(PY_CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE
 
 
 # Machine-dependent subdirectories
@@ -411,7 +417,7 @@
 
 # Build the interpreter
 $(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY)
-		$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \
+		$(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \
 			Modules/python.o \
 			$(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
 
@@ -422,8 +428,8 @@
 # Build the shared modules
 sharedmods: $(BUILDPYTHON)
 	@case $$MAKEFLAGS in \
-	*s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \
-	*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \
+	*s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \
+	*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \
 	esac
 
 # Build static library
@@ -440,18 +446,18 @@
 
 libpython$(VERSION).so: $(LIBRARY_OBJS)
 	if test $(INSTSONAME) != $(LDLIBRARY); then \
-		$(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+		$(LDSHARED) $(PY_LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 		$(LN) -f $(INSTSONAME) $@; \
 	else \
-		$(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+		$(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 	fi
 
 libpython$(VERSION).dylib: $(LIBRARY_OBJS)
-	 $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+	 $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 		 
 
 libpython$(VERSION).sl: $(LIBRARY_OBJS)
-	$(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST)
+	$(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST)
 
 # Copy up the gdb python hooks into a position where they can be automatically
 # loaded by gdb during Lib/test/test_gdb.py
@@ -497,7 +503,7 @@
 # for a shared core library; otherwise, this rule is a noop.
 $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS)
 	if test -n "$(DLLLIBRARY)"; then \
-		$(LDSHARED) $(LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \
+		$(LDSHARED) $(PY_LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \
 			$(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST); \
 	else true; \
 	fi
@@ -541,10 +547,10 @@
 		$(SIGNAL_OBJS) \
 		$(MODOBJS) \
 		$(srcdir)/Modules/getbuildinfo.c
-	$(CC) -c $(PY_CFLAGS) -DSVNVERSION="\"`LC_ALL=C $(SVNVERSION)`\"" -o $@ $(srcdir)/Modules/getbuildinfo.c
+	$(CC) -c $(PY_CORE_CFLAGS) -DSVNVERSION="\"`LC_ALL=C $(SVNVERSION)`\"" -o $@ $(srcdir)/Modules/getbuildinfo.c
 
 Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile
-	$(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \
+	$(CC) -c $(PY_CORE_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \
 		-DPREFIX='"$(prefix)"' \
 		-DEXEC_PREFIX='"$(exec_prefix)"' \
 		-DVERSION='"$(VERSION)"' \
@@ -552,7 +558,7 @@
 		-o $@ $(srcdir)/Modules/getpath.c
 
 Modules/python.o: $(srcdir)/Modules/python.c
-	$(MAINCC) -c $(PY_CFLAGS) -o $@ $(srcdir)/Modules/python.c
+	$(MAINCC) -c $(PY_CORE_CFLAGS) -o $@ $(srcdir)/Modules/python.c
 
 $(IO_OBJS): $(IO_H)
 
@@ -561,7 +567,7 @@
 		-$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
 
 $(PGEN):	$(PGENOBJS)
-		$(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
+		$(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
 
 Parser/grammar.o:	$(srcdir)/Parser/grammar.c \
 				$(srcdir)/Include/token.h \
@@ -581,10 +587,10 @@
 Python/compile.o Python/symtable.o Python/ast.o: $(GRAMMAR_H) $(AST_H)
 
 Python/getplatform.o: $(srcdir)/Python/getplatform.c
-		$(CC) -c $(PY_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c
+		$(CC) -c $(PY_CORE_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c
 
 Python/importdl.o: $(srcdir)/Python/importdl.c
-		$(CC) -c $(PY_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c
+		$(CC) -c $(PY_CORE_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c
 
 Objects/unicodectype.o:	$(srcdir)/Objects/unicodectype.c \
 				$(srcdir)/Objects/unicodetype_db.h
@@ -1131,7 +1137,7 @@
 
 # Some make's put the object file in the current directory
 .c.o:
-	$(CC) -c $(PY_CFLAGS) -o $@ $<
+	$(CC) -c $(PY_CORE_CFLAGS) -o $@ $<
 
 # Run reindent on the library
 reindent:

Modified: python/branches/py3k-cdecimal/Misc/ACKS
==============================================================================
--- python/branches/py3k-cdecimal/Misc/ACKS	(original)
+++ python/branches/py3k-cdecimal/Misc/ACKS	Sat Jul 17 12:36:09 2010
@@ -145,6 +145,7 @@
 Vadim Chugunov
 David Cinege
 Mike Clarkson
+Andrew Clegg
 Brad Clements
 Steve Clift
 Nick Coghlan
@@ -158,6 +159,7 @@
 Juan José Conti
 Matt Conway
 David M. Cooke
+Jason R. Coombs
 Greg Copeland
 Aldo Cortesi
 David Costanzo
@@ -406,6 +408,7 @@
 Kurt B. Kaiser
 Tamito Kajiyama
 Peter van Kampen
+Rafe Kaplan
 Jacob Kaplan-Moss
 Lou Kates
 Hiroaki Kawai
@@ -451,6 +454,7 @@
 Simon Law
 Chris Lawrence
 Brian Leair
+James Lee
 John J. Lee
 Inyeol Lee
 Thomas Lee
@@ -796,6 +800,7 @@
 Eren Türkay
 Lionel Ulmer
 Roger Upole
+Daniel Urban
 Michael Urman
 Hector Urtubia
 Andi Vajda

Modified: python/branches/py3k-cdecimal/Misc/NEWS
==============================================================================
--- python/branches/py3k-cdecimal/Misc/NEWS	(original)
+++ python/branches/py3k-cdecimal/Misc/NEWS	Sat Jul 17 12:36:09 2010
@@ -12,6 +12,45 @@
 Core and Builtins
 -----------------
 
+- 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)".
+
+- Be more specific in error messages about positional arguments.
+
+- Issue #8949: "z" format of PyArg_Parse*() functions doesn't accept bytes
+  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
+  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 #850997: mbcs encoding (Windows only) handles errors argument: strict
+  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.
+
+- 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
   string formats.
@@ -23,6 +62,8 @@
 - Issue #8969: On Windows, use mbcs codec in strict mode to encode and decode
   filenames and enable os.fsencode().
 
+- 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).
@@ -432,6 +473,84 @@
 Library
 -------
 
+- Issue #1555570: email no longer inserts extra blank lines when a \r\n
+  combo crosses an 8192 byte boundary.
+
+- Issue #9243: Fix sndhdr module and add unit tests, contributed by James Lee.
+
+- ``ast.literal_eval()`` now allows byte literals.
+
+- Issue #9137: Fix issue in MutableMapping.update, which incorrectly
+  treated keyword arguments called 'self' or 'other' specially.
+
+- ``ast.literal_eval()`` now allows set literals.
+
+- Issue #9164: Ensure that sysconfig handles duplicate -arch flags in CFLAGS.
+
+- Issue #7646: The fnmatch pattern cache no longer grows without bound.
+
+- Issue #9136: Fix 'dictionary changed size during iteration'
+  RuntimeError produced when profiling the decimal module.  This was
+  due to a dangerous iteration over 'locals()' in Context.__init__.
+
+- Fix extreme speed issue in Decimal.pow when the base is an exact
+  power of 10 and the exponent is tiny (for example,
+  Decimal(10) ** Decimal('1e-999999999')).
+
+- Issue #9186: Fix math.log1p(-1.0) to raise ValueError, not OverflowError.
+
+- Issue #9130: Fix validation of relative imports in parser module.
+
+- Issue #9128: Fix validation of class decorators in parser module.
+
+- Issue #9094: python -m pickletools will now disassemble pickle files
+  listed in the command line arguments.  See output of python -m
+  pickletools -h for more details.
+
+- Issue #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 #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.
+
+- Issue #6589: cleanup asyncore.socket_map in case smtpd.SMTPServer constructor
+  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.
+
+- 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 #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 #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
+  obtained by passing retry=True to http_error_xxx methods of FancyURLOpener.
+
+- 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 #8986: math.erfc was incorrectly raising OverflowError for
   values between -27.3 and -30.0 on some platforms.
 
@@ -1306,6 +1425,41 @@
 Extension Modules
 -----------------
 
+- Issue #9165: Add new functions math.isfinite and cmath.isfinite, to
+  accompany existing isinf and isnan functions.
+
+- Issue #1578269: Implement os.symlink for Windows 6.0+. Patch by
+  Jason R. Coombs
+
+- In struct.pack, correctly propogate exceptions from computing the truth of an
+  object in the '?' format.
+
+- Issue #9000: datetime.timezone objects now have eval-friendly repr.
+
+- In the math module, correctly lookup __trunc__, __ceil__, and __floor__ as
+  special methods.
+
+- Issue #9005: Prevent utctimetuple() from producing year 0 or year
+  10,000.  Prior to this change, timezone adjustment in utctimetuple()
+  could produce tm_year value of 0 or 10,000.  Now an OverflowError is
+  raised in these edge cases.
+
+- Issue #6641: The ``datetime.strptime`` method now supports the
+  ``%z`` directive.  When the ``%z`` directive is present in the
+  format string, an aware ``datetime`` object is returned with
+  ``tzinfo`` bound to a ``datetime.timezone`` instance constructed
+  from the parsed offset.  If both ``%z`` and ``%Z`` are present, the
+  data in ``%Z`` field is used for timezone name, but ``%Z`` data
+  without ``%z`` is discarded.
+
+- Issue #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.
+
 - Issue #8973: Add __all__ to struct module; this ensures that
   help(struct) includes documentation for the struct.Struct class.
 
@@ -1396,6 +1550,14 @@
 Build
 -----
 
+- 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.
 
@@ -1491,6 +1653,11 @@
 Tests
 -----
 
+- Issue #9251: test_threaded_import didn't fail when run through regrtest
+  if the import lock was disabled.
+
+- Issue #8605: Skip test_gdb if Python is compiled with optimizations.
+
 - Issue #7449: Skip test_socketserver if threading support is disabled
 
 - Issue #8672: Add a zlib test ensuring that an incomplete stream can be
@@ -1619,7 +1786,7 @@
 Tools/Demos
 -----------
 
-- Issue #5464: Implement plural forms in msgfmt.py.
+- Issue #5464, #8974: Implement plural forms in msgfmt.py.
 
 - iobench (a file I/O benchmark) and ccbench (a concurrency benchmark) were
   added to the `Tools/` directory.  They were previously living in the
@@ -2015,6 +2182,8 @@
 Library
 -------
 
+- Issue #8203: Fix IDLE Credits dialog: view_file() uses its encoding argument.
+
 - Issue #5311: bdist_msi can now build packages that do not depend on a
   specific Python version.
 

Modified: python/branches/py3k-cdecimal/Misc/Vim/vimrc
==============================================================================
--- python/branches/py3k-cdecimal/Misc/Vim/vimrc	(original)
+++ python/branches/py3k-cdecimal/Misc/Vim/vimrc	Sat Jul 17 12:36:09 2010
@@ -43,7 +43,7 @@
 " Display tabs at the beginning of a line in Python mode as bad.
 au BufRead,BufNewFile *.py,*.pyw match BadWhitespace /^\t\+/
 " Make trailing whitespace be flagged as bad.
-au BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/
+au BufRead,BufNewFile *.py,*.pyw,*.c,*.h,*.rst match BadWhitespace /\s\+$/
 
 " Wrap text after a certain number of characters
 " Python: 79 

Modified: python/branches/py3k-cdecimal/Misc/maintainers.rst
==============================================================================
--- python/branches/py3k-cdecimal/Misc/maintainers.rst	(original)
+++ python/branches/py3k-cdecimal/Misc/maintainers.rst	Sat Jul 17 12:36:09 2010
@@ -89,7 +89,7 @@
 doctest             tim_one (inactive)
 dummy_threading     brett.cannon
 email               barry, r.david.murray
-encodings           lemburg, loewis
+encodings           lemburg
 errno
 exceptions
 fcntl
@@ -104,7 +104,7 @@
 gc                  pitrou
 getopt
 getpass
-gettext             loewis
+gettext
 glob
 grp
 gzip
@@ -125,7 +125,7 @@
 keyword
 lib2to3             benjamin.peterson
 linecache
-locale              loewis, lemburg
+locale              lemburg
 logging             vsajip
 macpath
 mailbox             andrew.kuchling
@@ -135,7 +135,7 @@
 mimetypes
 mmap
 modulefinder        theller, jvr
-msilib              loewis
+msilib
 msvcrt
 multiprocessing     jnoller
 netrc
@@ -144,7 +144,7 @@
 numbers
 operator
 optparse            aronacher
-os                  loewis
+os
 ossaudiodev
 parser
 pdb
@@ -217,7 +217,7 @@
 tty
 turtle              gregorlingl
 types
-unicodedata         loewis, lemburg, ezio.melotti
+unicodedata         lemburg, ezio.melotti
 unittest            michael.foord
 urllib              orsenthil
 uu
@@ -226,13 +226,13 @@
 wave
 weakref             fdrake
 webbrowser          georg.brandl
-winreg
+winreg              brian.curtin
 winsound            effbot (inactive)
 wsgiref             pje
 xdrlib
-xml                 loewis
+xml
 xml.etree           effbot (inactive)
-xmlrpc              loewis
+xmlrpc
 zipfile
 zipimport
 zlib
@@ -277,13 +277,13 @@
 i18n                lemburg
 import machinery    brett.cannon, ncoghlan
 io                  pitrou, benjamin.peterson
-locale              lemburg, loewis
+locale              lemburg
 mathematics         mark.dickinson, eric.smith, lemburg
 memory management   tim_one, lemburg
 networking          giampaolo.rodola
 packaging           tarek, lemburg
 py3 transition      benjamin.peterson
-release management  tarek, lemburg, benjamin.peterson, barry, loewis,
+release management  tarek, lemburg, benjamin.peterson, barry,
                     gvanrossum, anthonybaxter
 str.format          eric.smith
 time and dates      lemburg

Modified: python/branches/py3k-cdecimal/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_ctypes/callproc.c	(original)
+++ python/branches/py3k-cdecimal/Modules/_ctypes/callproc.c	Sat Jul 17 12:36:09 2010
@@ -761,6 +761,7 @@
     ffi_cif cif;
     int cc;
 #ifdef MS_WIN32
+    int delta;
 #ifndef DONT_USE_SEH
     DWORD dwExceptionCode = 0;
     EXCEPTION_RECORD record;
@@ -811,8 +812,9 @@
 #ifndef DONT_USE_SEH
     __try {
 #endif
+        delta =
 #endif
-        ffi_call(&cif, (void *)pProc, resmem, avalues);
+                ffi_call(&cif, (void *)pProc, resmem, avalues);
 #ifdef MS_WIN32
 #ifndef DONT_USE_SEH
     }
@@ -844,6 +846,35 @@
         return -1;
     }
 #endif
+#ifdef MS_WIN64
+    if (delta != 0) {
+        PyErr_Format(PyExc_RuntimeError,
+                 "ffi_call failed with code %d",
+                 delta);
+        return -1;
+    }
+#else
+    if (delta < 0) {
+        if (flags & FUNCFLAG_CDECL)
+            PyErr_Format(PyExc_ValueError,
+                     "Procedure called with not enough "
+                     "arguments (%d bytes missing) "
+                     "or wrong calling convention",
+                     -delta);
+        else
+            PyErr_Format(PyExc_ValueError,
+                     "Procedure probably called with not enough "
+                     "arguments (%d bytes missing)",
+                     -delta);
+        return -1;
+    } else if (delta > 0) {
+        PyErr_Format(PyExc_ValueError,
+                 "Procedure probably called with too many "
+                 "arguments (%d bytes in excess)",
+                 delta);
+        return -1;
+    }
+#endif
 #endif
     if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
         return -1;
@@ -1116,7 +1147,11 @@
     }
     for (i = 0; i < argcount; ++i) {
         atypes[i] = args[i].ffi_type;
-        if (atypes[i]->type == FFI_TYPE_STRUCT)
+        if (atypes[i]->type == FFI_TYPE_STRUCT 
+#ifdef _WIN64
+            && atypes[i]->size <= sizeof(void *)
+#endif
+            )
             avalues[i] = (void *)args[i].value.p;
         else
             avalues[i] = (void *)&args[i].value;

Modified: python/branches/py3k-cdecimal/Modules/_ctypes/libffi/fficonfig.py.in
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_ctypes/libffi/fficonfig.py.in	(original)
+++ python/branches/py3k-cdecimal/Modules/_ctypes/libffi/fficonfig.py.in	Sat Jul 17 12:36:09 2010
@@ -6,7 +6,7 @@
     'MIPS_IRIX': ['src/mips/ffi.c', 'src/mips/o32.S', 'src/mips/n32.S'],
     'MIPS_LINUX': ['src/mips/ffi.c', 'src/mips/o32.S'],
     'X86': ['src/x86/ffi.c', 'src/x86/sysv.S'],
-    'X86_FREEBSD': ['src/x86/ffi.c', 'src/x86/sysv.S'],
+    'X86_FREEBSD': ['src/x86/ffi.c', 'src/x86/freebsd.S'],
     'X86_WIN32': ['src/x86/ffi.c', 'src/x86/win32.S'],
     'SPARC': ['src/sparc/ffi.c', 'src/sparc/v8.S', 'src/sparc/v9.S'],
     'ALPHA': ['src/alpha/ffi.c', 'src/alpha/osf.S'],

Modified: python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffi.h
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffi.h	(original)
+++ python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/ffi.h	Sat Jul 17 12:36:09 2010
@@ -1,5 +1,5 @@
 /* -----------------------------------------------------------------*-C-*-
-   libffi @VERSION@ - Copyright (c) 1996-2003, 2007, 2008  Red Hat, Inc.
+   libffi 2.00-beta - Copyright (c) 1996-2003  Red Hat, Inc.
 
    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
@@ -12,14 +12,13 @@
    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.
 
-   THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
-   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-   NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-   DEALINGS IN THE SOFTWARE.
+   THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+   IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+   OTHER DEALINGS IN THE SOFTWARE.
 
    ----------------------------------------------------------------------- */
 
@@ -57,7 +56,7 @@
 #endif
 
 /* Specify which architecture libffi is configured for. */
-/* #define @TARGET@ */
+//XXX #define X86
 
 /* ---- System configuration information --------------------------------- */
 
@@ -65,10 +64,6 @@
 
 #ifndef LIBFFI_ASM
 
-#ifdef _MSC_VER
-#define __attribute__(X)
-#endif
-
 #include <stddef.h>
 #include <limits.h>
 
@@ -84,21 +79,12 @@
 #  ifdef __GNUC__
 #   define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
 #  endif
+#  ifdef _MSC_VER
+#   define FFI_LONG_LONG_MAX _I64_MAX
+#  endif
 # endif
 #endif
 
-/* The closure code assumes that this works on pointers, i.e. a size_t	*/
-/* can hold a pointer.							*/
-
-typedef struct _ffi_type
-{
-  size_t size;
-  unsigned short alignment;
-  unsigned short type;
-  struct _ffi_type **elements;
-} ffi_type;
-
-#ifndef LIBFFI_HIDE_BASIC_TYPES
 #if SCHAR_MAX == 127
 # define ffi_type_uchar                ffi_type_uint8
 # define ffi_type_schar                ffi_type_sint8
@@ -129,23 +115,26 @@
  #error "int size not supported"
 #endif
 
+#define ffi_type_ulong         ffi_type_uint64
+#define ffi_type_slong         ffi_type_sint64
 #if LONG_MAX == 2147483647
 # if FFI_LONG_LONG_MAX != 9223372036854775807
- #error "no 64-bit data type supported"
+  #error "no 64-bit data type supported"
 # endif
 #elif LONG_MAX != 9223372036854775807
  #error "long size not supported"
 #endif
 
-#if LONG_MAX == 2147483647
-# define ffi_type_ulong        ffi_type_uint32
-# define ffi_type_slong        ffi_type_sint32
-#elif LONG_MAX == 9223372036854775807
-# define ffi_type_ulong        ffi_type_uint64
-# define ffi_type_slong        ffi_type_sint64
-#else
- #error "long size not supported"
-#endif
+/* The closure code assumes that this works on pointers, i.e. a size_t	*/
+/* can hold a pointer.							*/
+
+typedef struct _ffi_type
+{
+  size_t size;
+  unsigned short alignment;
+  unsigned short type;
+  /*@null@*/ struct _ffi_type **elements;
+} ffi_type;
 
 /* These are defined in types.c */
 extern ffi_type ffi_type_void;
@@ -159,19 +148,14 @@
 extern ffi_type ffi_type_sint64;
 extern ffi_type ffi_type_float;
 extern ffi_type ffi_type_double;
+extern ffi_type ffi_type_longdouble;
 extern ffi_type ffi_type_pointer;
 
-#if HAVE_LONG_DOUBLE
-extern ffi_type ffi_type_longdouble;
-#else
-#define ffi_type_longdouble ffi_type_double
-#endif
-#endif /* LIBFFI_HIDE_BASIC_TYPES */
 
 typedef enum {
   FFI_OK = 0,
   FFI_BAD_TYPEDEF,
-  FFI_BAD_ABI
+  FFI_BAD_ABI 
 } ffi_status;
 
 typedef unsigned FFI_TYPE;
@@ -179,8 +163,8 @@
 typedef struct {
   ffi_abi abi;
   unsigned nargs;
-  ffi_type **arg_types;
-  ffi_type *rtype;
+  /*@dependent@*/ ffi_type **arg_types;
+  /*@dependent@*/ ffi_type *rtype;
   unsigned bytes;
   unsigned flags;
 #ifdef FFI_EXTRA_CIF_FIELDS
@@ -190,16 +174,10 @@
 
 /* ---- Definitions for the raw API -------------------------------------- */
 
-#ifndef FFI_SIZEOF_ARG
-# if LONG_MAX == 2147483647
-#  define FFI_SIZEOF_ARG        4
-# elif LONG_MAX == 9223372036854775807
-#  define FFI_SIZEOF_ARG        8
-# endif
-#endif
-
-#ifndef FFI_SIZEOF_JAVA_RAW
-#  define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
+#ifdef _WIN64
+#define FFI_SIZEOF_ARG 8
+#else
+#define FFI_SIZEOF_ARG 4
 #endif
 
 typedef union {
@@ -210,25 +188,10 @@
   void*     ptr;
 } ffi_raw;
 
-#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
-/* This is a special case for mips64/n32 ABI (and perhaps others) where
-   sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8.  */
-typedef union {
-  signed int	sint;
-  unsigned int	uint;
-  float		flt;
-  char		data[FFI_SIZEOF_JAVA_RAW];
-  void*		ptr;
-} ffi_java_raw;
-#else
-typedef ffi_raw ffi_java_raw;
-#endif
-
-
-void ffi_raw_call (ffi_cif *cif,
-		   void (*fn)(void),
-		   void *rvalue,
-		   ffi_raw *avalue);
+void ffi_raw_call (/*@dependent@*/ ffi_cif *cif, 
+		   void (*fn)(), 
+		   /*@out@*/ void *rvalue, 
+		   /*@dependent@*/ ffi_raw *avalue);
 
 void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
 void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
@@ -238,35 +201,25 @@
 /* packing, even on 64-bit machines.  I.e. on 64-bit machines		*/
 /* longs and doubles are followed by an empty 64-bit word.		*/
 
-void ffi_java_raw_call (ffi_cif *cif,
-			void (*fn)(void),
-			void *rvalue,
-			ffi_java_raw *avalue);
+void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif, 
+		        void (*fn)(), 
+		        /*@out@*/ void *rvalue, 
+		        /*@dependent@*/ ffi_raw *avalue);
 
-void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw);
-void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args);
+void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
+void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
 size_t ffi_java_raw_size (ffi_cif *cif);
 
 /* ---- Definitions for closures ----------------------------------------- */
 
 #if FFI_CLOSURES
 
-#ifdef _MSC_VER
-__declspec(align(8))
-#endif
 typedef struct {
   char tramp[FFI_TRAMPOLINE_SIZE];
   ffi_cif   *cif;
   void     (*fun)(ffi_cif*,void*,void**,void*);
   void      *user_data;
-#ifdef __GNUC__
-} ffi_closure __attribute__((aligned (8)));
-#else
 } ffi_closure;
-#endif
-
-void *ffi_closure_alloc (size_t size, void **code);
-void ffi_closure_free (void *);
 
 ffi_status
 ffi_prep_closure (ffi_closure*,
@@ -274,13 +227,6 @@
 		  void (*fun)(ffi_cif*,void*,void**,void*),
 		  void *user_data);
 
-ffi_status
-ffi_prep_closure_loc (ffi_closure*,
-		      ffi_cif *,
-		      void (*fun)(ffi_cif*,void*,void**,void*),
-		      void *user_data,
-		      void*codeloc);
-
 typedef struct {
   char tramp[FFI_TRAMPOLINE_SIZE];
 
@@ -302,27 +248,6 @@
 
 } ffi_raw_closure;
 
-typedef struct {
-  char tramp[FFI_TRAMPOLINE_SIZE];
-
-  ffi_cif   *cif;
-
-#if !FFI_NATIVE_RAW_API
-
-  /* if this is enabled, then a raw closure has the same layout 
-     as a regular closure.  We use this to install an intermediate 
-     handler to do the transaltion, void** -> ffi_raw*. */
-
-  void     (*translate_args)(ffi_cif*,void*,void**,void*);
-  void      *this_closure;
-
-#endif
-
-  void     (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
-  void      *user_data;
-
-} ffi_java_raw_closure;
-
 ffi_status
 ffi_prep_raw_closure (ffi_raw_closure*,
 		      ffi_cif *cif,
@@ -330,42 +255,29 @@
 		      void *user_data);
 
 ffi_status
-ffi_prep_raw_closure_loc (ffi_raw_closure*,
-			  ffi_cif *cif,
-			  void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
-			  void *user_data,
-			  void *codeloc);
-
-ffi_status
-ffi_prep_java_raw_closure (ffi_java_raw_closure*,
+ffi_prep_java_raw_closure (ffi_raw_closure*,
 		           ffi_cif *cif,
-		           void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
+		           void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
 		           void *user_data);
 
-ffi_status
-ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
-			       ffi_cif *cif,
-			       void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
-			       void *user_data,
-			       void *codeloc);
-
 #endif /* FFI_CLOSURES */
 
 /* ---- Public interface definition -------------------------------------- */
 
-ffi_status ffi_prep_cif(ffi_cif *cif,
+ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, 
 			ffi_abi abi,
-			unsigned int nargs,
-			ffi_type *rtype,
-			ffi_type **atypes);
-
-void ffi_call(ffi_cif *cif,
-	      void (*fn)(void),
-	      void *rvalue,
-	      void **avalue);
+			unsigned int nargs, 
+			/*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, 
+			/*@dependent@*/ ffi_type **atypes);
+
+int
+ffi_call(/*@dependent@*/ ffi_cif *cif, 
+	 void (*fn)(), 
+	 /*@out@*/ void *rvalue, 
+	 /*@dependent@*/ void **avalue);
 
 /* Useful for eliminating compiler warnings */
-#define FFI_FN(f) ((void (*)(void))f)
+#define FFI_FN(f) ((void (*)())f)
 
 /* ---- Definitions shared with assembly code ---------------------------- */
 
@@ -376,7 +288,7 @@
 #define FFI_TYPE_INT        1
 #define FFI_TYPE_FLOAT      2    
 #define FFI_TYPE_DOUBLE     3
-#if HAVE_LONG_DOUBLE
+#if 1
 #define FFI_TYPE_LONGDOUBLE 4
 #else
 #define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
@@ -400,3 +312,4 @@
 #endif
 
 #endif
+

Modified: python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/fficonfig.h
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/fficonfig.h	(original)
+++ python/branches/py3k-cdecimal/Modules/_ctypes/libffi_msvc/fficonfig.h	Sat Jul 17 12:36:09 2010
@@ -1,186 +1,96 @@
 /* fficonfig.h.  Originally created by configure, now hand_maintained for MSVC. */
 
-/* fficonfig.h.in.  Generated from configure.ac by autoheader.  */
+/* fficonfig.h.  Generated automatically by configure.  */
+/* fficonfig.h.in.  Generated automatically from configure.in by autoheader.  */
 
-/* Define if building universal (internal helper macro) */
-/* #undef AC_APPLE_UNIVERSAL_BUILD */
+/* Define this for MSVC, but not for mingw32! */
+#ifdef _MSC_VER
+#define __attribute__(x) /* */
+#endif
+#define alloca _alloca
 
-/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
-   systems. This function is required for `alloca.c' support on those systems.
-   */
-/* #undef CRAY_STACKSEG_END */
+/*----------------------------------------------------------------*/
 
-/* Define to 1 if using `alloca.c'. */
+/* Define if using alloca.c.  */
 /* #undef C_ALLOCA */
 
-/* Define to the flags needed for the .section .eh_frame directive. */
-/* #undef EH_FRAME_FLAGS */
-
-/* Define this if you want extra debugging. */
-/* #undef FFI_DEBUG */
-
-/* Cannot use malloc on this target, so, we revert to alternative means */
-/* #undef FFI_MMAP_EXEC_WRIT */
-
-/* Define this is you do not want support for the raw API. */
-#define FFI_NO_RAW_API 1
-
-/* Define this is you do not want support for aggregate types. */
-/* #undef FFI_NO_STRUCTS */
+/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems.
+   This function is required for alloca.c support on those systems.  */
+/* #undef CRAY_STACKSEG_END */
 
-/* Define to 1 if you have `alloca', as a function or macro. */
+/* Define if you have alloca, as a function or macro.  */
 #define HAVE_ALLOCA 1
 
-/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
-   */
-/* #undef HAVE_ALLOCA_H */
-
-/* Define if your assembler supports .cfi_* directives. */
-/* #undef HAVE_AS_CFI_PSEUDO_OP */
+/* Define if you have <alloca.h> and it should be used (not on Ultrix).  */
+/* #define HAVE_ALLOCA_H 1 */
 
-/* Define if your assembler supports .register. */
-/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
-
-/* Define if your assembler and linker support unaligned PC relative relocs.
-   */
-/* #undef HAVE_AS_SPARC_UA_PCREL */
-
-/* Define if your assembler supports PC relative relocs. */
-/* #undef HAVE_AS_X86_PCREL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-/* #undef HAVE_DLFCN_H */
-
-/* Define if __attribute__((visibility("hidden"))) is supported. */
-/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-/* #undef HAVE_INTTYPES_H */
+/* If using the C implementation of alloca, define if you know the
+   direction of stack growth for your system; otherwise it will be
+   automatically deduced at run-time.
+ STACK_DIRECTION > 0 => grows toward higher addresses
+ STACK_DIRECTION < 0 => grows toward lower addresses
+ STACK_DIRECTION = 0 => direction of growth unknown
+ */
+/* #undef STACK_DIRECTION */
 
-/* Define if you have the long double type and it is bigger than a double */
-/* #undef HAVE_LONG_DOUBLE */
+/* Define if you have the ANSI C header files.  */
+#define STDC_HEADERS 1
 
-/* Define to 1 if you have the `memcpy' function. */
+/* Define if you have the memcpy function.  */
 #define HAVE_MEMCPY 1
 
-/* Define to 1 if you have the <memory.h> header file. */
-/* #undef HAVE_MEMORY_H */
-
-/* Define to 1 if you have the `mmap' function. */
-/* #undef HAVE_MMAP */
-
-/* Define if mmap with MAP_ANON(YMOUS) works. */
-/* #undef HAVE_MMAP_ANON */
-
-/* Define if mmap of /dev/zero works. */
-/* #undef HAVE_MMAP_DEV_ZERO */
-
 /* Define if read-only mmap of a plain file works. */
-/* #undef HAVE_MMAP_FILE */
-
-/* Define if .eh_frame sections should be read-only. */
-/* #undef HAVE_RO_EH_FRAME */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#undef HAVE_STDLIB_H
-
-/* Define to 1 if you have the <strings.h> header file. */
-#undef HAVE_STRINGS_H
-
-/* Define to 1 if you have the <string.h> header file. */
-#undef HAVE_STRING_H
+//#define HAVE_MMAP_FILE 1
 
-/* Define to 1 if you have the <sys/mman.h> header file. */
-/* #undef HAVE_SYS_MMAN_H */
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-/* #undef HAVE_SYS_STAT_H */
+/* Define if mmap of /dev/zero works. */
+//#define HAVE_MMAP_DEV_ZERO 1
 
-/* Define to 1 if you have the <sys/types.h> header file. */
-/* #undef HAVE_SYS_TYPES_H */
+/* Define if mmap with MAP_ANON(YMOUS) works. */
+//#define HAVE_MMAP_ANON 1
 
-/* Define to 1 if you have the <unistd.h> header file. */
-/* #undef HAVE_UNISTD_H */
+/* The number of bytes in type double */
+#define SIZEOF_DOUBLE 8
 
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-/* #undef LT_OBJDIR */
+/* The number of bytes in type long double */
+#define SIZEOF_LONG_DOUBLE 12
 
-/* Define to 1 if your C compiler doesn't accept -c and -o together. */
-/* #undef NO_MINUS_C_MINUS_O */
+/* Define if you have the long double type and it is bigger than a double */
+#define HAVE_LONG_DOUBLE 1
 
-/* Name of package */
-/* #undef PACKAGE */
+/* whether byteorder is bigendian */
+/* #undef WORDS_BIGENDIAN */
 
-/* Define to the address where bug reports for this package should be sent. */
-/* #undef PACKAGE_BUGREPORT */
+/* Define if the host machine stores words of multi-word integers in
+   big-endian order. */
+/* #undef HOST_WORDS_BIG_ENDIAN */
 
-/* Define to the full name of this package. */
-/* #undef PACKAGE_NAME */
+/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */
+#define BYTEORDER 1234
 
-/* Define to the full name and version of this package. */
-/* #undef PACKAGE_STRING */
+/* Define if your assembler and linker support unaligned PC relative relocs. */
+/* #undef HAVE_AS_SPARC_UA_PCREL */
 
-/* Define to the one symbol short name of this package. */
-/* #undef PACKAGE_TARNAME */
+/* Define if your assembler supports .register. */
+/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
 
-/* Define to the home page for this package. */
-/* #undef PACKAGE_URL */
+/* Define if .eh_frame sections should be read-only. */
+/* #undef HAVE_RO_EH_FRAME */
 
-/* Define to the version of this package. */
-/* #undef PACKAGE_VERSION */
+/* Define to the flags needed for the .section .eh_frame directive. */
+/* #define EH_FRAME_FLAGS "aw" */
 
-/* The size of `double', as computed by sizeof. */
-#define SIZEOF_DOUBLE 8
+/* Define to the flags needed for the .section .eh_frame directive. */
+/* #define EH_FRAME_FLAGS "aw" */
 
-/* The size of `long double', as computed by sizeof. */
-#undef SIZEOF_LONG_DOUBLE
+/* Define this if you want extra debugging. */
+/* #undef FFI_DEBUG */
 
-/* If using the C implementation of alloca, define if you know the
-   direction of stack growth for your system; otherwise it will be
-   automatically deduced at runtime.
-	STACK_DIRECTION > 0 => grows toward higher addresses
-	STACK_DIRECTION < 0 => grows toward lower addresses
-	STACK_DIRECTION = 0 => direction of growth unknown */
-/* #undef STACK_DIRECTION */
+/* Define this is you do not want support for aggregate types. */
+/* #undef FFI_NO_STRUCTS */
 
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
+/* Define this is you do not want support for the raw API. */
+/* #undef FFI_NO_RAW_API */
 
-/* Define this if you are using Purify and want to suppress spurious messages.
-   */
+/* Define this if you are using Purify and want to suppress spurious messages. */
 /* #undef USING_PURIFY */
 
-/* Version number of package */
-/* #undef VERSION */
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
-   significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-#  define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-#  undef WORDS_BIGENDIAN
-# endif
-#endif
-
-
-#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name) .hidden name
-#else
-#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
-#endif
-#else
-#ifdef LIBFFI_ASM
-#define FFI_HIDDEN(name)
-#else
-#define FFI_HIDDEN
-#endif
-#endif
-

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

Modified: python/branches/py3k-cdecimal/Modules/_math.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_math.c	(original)
+++ python/branches/py3k-cdecimal/Modules/_math.c	Sat Jul 17 12:36:09 2010
@@ -55,14 +55,15 @@
     else if (x >= two_pow_p28) {        /* x > 2**28 */
         if (Py_IS_INFINITY(x)) {
             return x+x;
-        } else {
-            return log(x)+ln2;                  /* acosh(huge)=log(2x) */
+        }
+        else {
+            return log(x)+ln2;          /* acosh(huge)=log(2x) */
         }
     }
     else if (x == 1.) {
-        return 0.0;                             /* acosh(1) = 0 */
+        return 0.0;                     /* acosh(1) = 0 */
     }
-    else if (x > 2.) {                          /* 2 < x < 2**28 */
+    else if (x > 2.) {                  /* 2 < x < 2**28 */
         double t = x*x;
         return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
     }
@@ -94,7 +95,7 @@
         return x+x;
     }
     if (absx < two_pow_m28) {           /* |x| < 2**-28 */
-        return x;               /* return x inexact except 0 */
+        return x;                       /* return x inexact except 0 */
     }
     if (absx > two_pow_p28) {           /* |x| > 2**28 */
         w = log(absx)+ln2;
@@ -114,9 +115,9 @@
  * Method :
  *    1.Reduced x to positive by atanh(-x) = -atanh(x)
  *    2.For x>=0.5
- *                1           2x                          x
- *      atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------)
- *                2          1 - x                    1 - x
+ *                  1              2x                          x
+ *      atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * -------)
+ *                  2             1 - x                      1 - x
  *
  *      For x<0.5
  *      atanh(x) = 0.5*log1p(2x+2x*x/(1-x))
@@ -173,15 +174,15 @@
     */
 
     if (fabs(x) < 0.7) {
-    double u;
-    u = exp(x);
-    if (u == 1.0)
-        return x;
-    else
-        return (u - 1.0) * x / log(u);
+        double u;
+        u = exp(x);
+        if (u == 1.0)
+            return x;
+        else
+            return (u - 1.0) * x / log(u);
     }
     else
-    return exp(x) - 1.0;
+        return exp(x) - 1.0;
 }
 
 /* log1p(x) = log(1+x).  The log1p function is designed to avoid the
@@ -194,7 +195,7 @@
     /* For x small, we use the following approach.  Let y be the nearest float
        to 1+x, then
 
-      1+x = y * (1 - (y-1-x)/y)
+         1+x = y * (1 - (y-1-x)/y)
 
        so log(1+x) = log(y) + log(1-(y-1-x)/y).  Since (y-1-x)/y is tiny, the
        second term is well approximated by (y-1-x)/y.  If abs(x) >=
@@ -213,17 +214,19 @@
 
     double y;
     if (fabs(x) < DBL_EPSILON/2.) {
-    return x;
-    } else if (-0.5 <= x && x <= 1.) {
-    /* WARNING: it's possible than an overeager compiler
-       will incorrectly optimize the following two lines
-       to the equivalent of "return log(1.+x)". If this
-       happens, then results from log1p will be inaccurate
-       for small x. */
-    y = 1.+x;
-    return log(y)-((y-1.)-x)/y;
-    } else {
-    /* NaNs and infinities should end up here */
-    return log(1.+x);
+        return x;
+    }
+    else if (-0.5 <= x && x <= 1.) {
+        /* WARNING: it's possible than an overeager compiler
+           will incorrectly optimize the following two lines
+           to the equivalent of "return log(1.+x)". If this
+           happens, then results from log1p will be inaccurate
+           for small x. */
+        y = 1.+x;
+        return log(y)-((y-1.)-x)/y;
+    }
+    else {
+        /* NaNs and infinities should end up here */
+        return log(1.+x);
     }
 }

Modified: python/branches/py3k-cdecimal/Modules/_scproxy.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_scproxy.c	(original)
+++ python/branches/py3k-cdecimal/Modules/_scproxy.c	Sat Jul 17 12:36:09 2010
@@ -75,7 +75,7 @@
         aNum = CFDictionaryGetValue(proxyDict,
             kSCPropNetProxiesExcludeSimpleHostnames);
         if (aNum == NULL) {
-            v = PyBool_FromLong(1);
+            v = PyBool_FromLong(0);
         } else {
             v = PyBool_FromLong(cfnum_to_int32(aNum));
         }

Modified: python/branches/py3k-cdecimal/Modules/_ssl.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_ssl.c	(original)
+++ python/branches/py3k-cdecimal/Modules/_ssl.c	Sat Jul 17 12:36:09 2010
@@ -212,8 +212,11 @@
                     errstr = "EOF occurred in violation of protocol";
                 } else if (ret == -1) {
                     /* underlying BIO reported an I/O error */
+                    Py_INCREF(s);
                     ERR_clear_error();
-                    return s->errorhandler();
+                    v = s->errorhandler();
+                    Py_DECREF(s);
+                    return v;
                 } else { /* possible? */
                     p = PY_SSL_ERROR_SYSCALL;
                     errstr = "Some I/O error occurred";
@@ -334,6 +337,7 @@
                      PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
         return NULL;
     }
+    Py_INCREF(sock);
 
     /* just in case the blocking state of the socket has been changed */
     nonblocking = (sock->sock_timeout >= 0.0);
@@ -348,9 +352,8 @@
         ret = SSL_do_handshake(self->ssl);
         err = SSL_get_error(self->ssl, ret);
         PySSL_END_ALLOW_THREADS
-        if(PyErr_CheckSignals()) {
-            return NULL;
-        }
+        if (PyErr_CheckSignals())
+            goto error;
         if (err == SSL_ERROR_WANT_READ) {
             sockstate = check_socket_and_wait_for_timeout(sock, 0);
         } else if (err == SSL_ERROR_WANT_WRITE) {
@@ -361,22 +364,22 @@
         if (sockstate == SOCKET_HAS_TIMED_OUT) {
             PyErr_SetString(PySSLErrorObject,
                             ERRSTR("The handshake operation timed out"));
-            return NULL;
+            goto error;
         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
             PyErr_SetString(PySSLErrorObject,
                             ERRSTR("Underlying socket has been closed."));
-            return NULL;
+            goto error;
         } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
             PyErr_SetString(PySSLErrorObject,
                             ERRSTR("Underlying socket too large for select()."));
-            return NULL;
+            goto error;
         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
             break;
         }
     } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
+    Py_DECREF(sock);
     if (ret < 1)
         return PySSL_SetError(self, ret, __FILE__, __LINE__);
-    self->ssl->debug = 1;
 
     if (self->peer_cert)
         X509_free (self->peer_cert);
@@ -386,6 +389,10 @@
 
     Py_INCREF(Py_None);
     return Py_None;
+
+error:
+    Py_DECREF(sock);
+    return NULL;
 }
 
 static PyObject *
@@ -1051,9 +1058,12 @@
                      PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
         return NULL;
     }
+    Py_INCREF(sock);
 
-    if (!PyArg_ParseTuple(args, "y*:write", &buf))
+    if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
+        Py_DECREF(sock);
         return NULL;
+    }
 
     /* just in case the blocking state of the socket has been changed */
     nonblocking = (sock->sock_timeout >= 0.0);
@@ -1103,6 +1113,7 @@
         }
     } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
 
+    Py_DECREF(sock);
     PyBuffer_Release(&buf);
     if (len > 0)
         return PyLong_FromLong(len);
@@ -1110,6 +1121,7 @@
         return PySSL_SetError(self, len, __FILE__, __LINE__);
 
 error:
+    Py_DECREF(sock);
     PyBuffer_Release(&buf);
     return NULL;
 }
@@ -1159,21 +1171,23 @@
                      PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
         return NULL;
     }
+    Py_INCREF(sock);
 
     if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
-        return NULL;
+        goto error;
+
     if ((dest == NULL) || (dest == Py_None)) {
         if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
-            return NULL;
+            goto error;
         mem = PyByteArray_AS_STRING(dest);
     } else if (PyLong_Check(dest)) {
         len = PyLong_AS_LONG(dest);
         if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
-            return NULL;
+            goto error;
         mem = PyByteArray_AS_STRING(dest);
     } else {
         if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
-            return NULL;
+            goto error;
         mem = buf.buf;
         len = buf.len;
         if ((count > 0) && (count <= len))
@@ -1240,6 +1254,7 @@
         goto error;
     }
   done:
+    Py_DECREF(sock);
     if (!buf_passed) {
         PyObject *res = PyBytes_FromStringAndSize(mem, count);
         Py_DECREF(dest);
@@ -1249,8 +1264,9 @@
         return PyLong_FromLong(count);
     }
   error:
+    Py_DECREF(sock);
     if (!buf_passed) {
-        Py_DECREF(dest);
+        Py_XDECREF(dest);
     } else {
         PyBuffer_Release(&buf);
     }
@@ -1275,6 +1291,7 @@
                      PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
         return NULL;
     }
+    Py_INCREF(sock);
 
     /* Just in case the blocking state of the socket has been changed */
     nonblocking = (sock->sock_timeout >= 0.0);
@@ -1324,24 +1341,29 @@
             else
                 PyErr_SetString(PySSLErrorObject,
                                 "The write operation timed out");
-            return NULL;
+            goto error;
         }
         else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
             PyErr_SetString(PySSLErrorObject,
                             "Underlying socket too large for select().");
-            return NULL;
+            goto error;
         }
         else if (sockstate != SOCKET_OPERATION_OK)
             /* Retain the SSL error code */
             break;
     }
 
-    if (err < 0)
+    if (err < 0) {
+        Py_DECREF(sock);
         return PySSL_SetError(self, err, __FILE__, __LINE__);
-    else {
-        Py_INCREF(sock);
-        return (PyObject *) sock;
     }
+    else
+        /* It's already INCREF'ed */
+        return (PyObject *) sock;
+
+error:
+    Py_DECREF(sock);
+    return NULL;
 }
 
 PyDoc_STRVAR(PySSL_SSLshutdown_doc,

Modified: python/branches/py3k-cdecimal/Modules/_struct.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_struct.c	(original)
+++ python/branches/py3k-cdecimal/Modules/_struct.c	Sat Jul 17 12:36:09 2010
@@ -591,9 +591,13 @@
 static int
 np_bool(char *p, PyObject *v, const formatdef *f)
 {
-    BOOL_TYPE y;
+    int y;
+    BOOL_TYPE x;
     y = PyObject_IsTrue(v);
-    memcpy(p, (char *)&y, sizeof y);
+    if (y < 0)
+        return -1;
+    x = y;
+    memcpy(p, (char *)&x, sizeof x);
     return 0;
 }
 
@@ -865,6 +869,8 @@
 {
     char y;
     y = PyObject_IsTrue(v);
+    if (y < 0)
+        return -1;
     memcpy(p, (char *)&y, sizeof y);
     return 0;
 }

Modified: python/branches/py3k-cdecimal/Modules/_testcapimodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/_testcapimodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/_testcapimodule.c	Sat Jul 17 12:36:09 2010
@@ -1386,6 +1386,28 @@
 }
 
 static PyObject *
+getargs_w_star(PyObject *self, PyObject *args)
+{
+    Py_buffer buffer;
+    PyObject *result;
+    char *str;
+
+    if (!PyArg_ParseTuple(args, "w*:getargs_w_star", &buffer))
+        return NULL;
+
+    if (2 <= buffer.len) {
+        str = buffer.buf;
+        str[0] = '[';
+        str[buffer.len-1] = ']';
+    }
+
+    result = PyBytes_FromStringAndSize(buffer.buf, buffer.len);
+    PyBuffer_Release(&buffer);
+    return result;
+}
+
+
+static PyObject *
 test_empty_argparse(PyObject *self)
 {
     /* Test that formats can begin with '|'. See issue #4720. */
@@ -2227,6 +2249,7 @@
     {"getargs_u_hash",          getargs_u_hash,                  METH_VARARGS},
     {"getargs_Z",               getargs_Z,                       METH_VARARGS},
     {"getargs_Z_hash",          getargs_Z_hash,                  METH_VARARGS},
+    {"getargs_w_star",          getargs_w_star,                  METH_VARARGS},
     {"codec_incrementalencoder",
      (PyCFunction)codec_incrementalencoder,      METH_VARARGS},
     {"codec_incrementaldecoder",

Modified: python/branches/py3k-cdecimal/Modules/audioop.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/audioop.c	(original)
+++ python/branches/py3k-cdecimal/Modules/audioop.c	Sat Jul 17 12:36:09 2010
@@ -297,6 +297,29 @@
 
 static PyObject *AudioopError;
 
+static int
+audioop_check_size(int size)
+{
+    if (size != 1 && size != 2 && size != 4) {
+        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+        return 0;
+    }
+    else
+        return 1;
+}
+
+static int
+audioop_check_parameters(int len, int size)
+{
+    if (!audioop_check_size(size))
+        return 0;
+    if (len % size != 0) {
+        PyErr_SetString(AudioopError, "not a whole number of frames");
+        return 0;
+    }
+    return 1;
+}
+
 static PyObject *
 audioop_getsample(PyObject *self, PyObject *args)
 {
@@ -306,10 +329,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#in:getsample", &cp, &len, &size, &i) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     if ( i < 0 || i >= len/size ) {
         PyErr_SetString(AudioopError, "Index out of range");
         return 0;
@@ -330,10 +351,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     for ( i=0; i<len; i+= size) {
         if ( size == 1 )      val = (int)*CHARP(cp, i);
         else if ( size == 2 ) val = (int)*SHORTP(cp, i);
@@ -354,10 +373,8 @@
 
     if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size))
         return NULL;
-    if (size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+    if (!audioop_check_parameters(len, size))
         return NULL;
-    }
     for (i = 0; i < len; i += size) {
         if (size == 1) val = (int) *CHARP(cp, i);
         else if (size == 2) val = (int) *SHORTP(cp, i);
@@ -378,10 +395,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     for ( i=0; i<len; i+= size) {
         if ( size == 1 )      val = (int)*CHARP(cp, i);
         else if ( size == 2 ) val = (int)*SHORTP(cp, i);
@@ -405,10 +420,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     for ( i=0; i<len; i+= size) {
         if ( size == 1 )      val = (int)*CHARP(cp, i);
         else if ( size == 2 ) val = (int)*SHORTP(cp, i);
@@ -616,10 +629,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     /* Compute first delta value ahead. Also automatically makes us
     ** skip the first extreme value
     */
@@ -673,10 +684,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     /* Compute first delta value ahead. Also automatically makes us
     ** skip the first extreme value
     */
@@ -725,10 +734,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) )
         return 0;
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
     ncross = -1;
     prevval = 17; /* Anything <> 0,1 */
     for ( i=0; i<len; i+= size) {
@@ -753,6 +760,8 @@
 
     if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) )
         return 0;
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     if ( size == 1 ) maxval = (double) 0x7f;
     else if ( size == 2 ) maxval = (double) 0x7fff;
@@ -798,6 +807,15 @@
         return 0;
     cp = pcp.buf;
     len = pcp.len;
+    if (!audioop_check_parameters(len, size)) {
+        PyBuffer_Release(&pcp);
+        return NULL;
+    }
+    if (((len / size) & 1) != 0) {
+        PyErr_SetString(AudioopError, "not a whole number of frames");
+        PyBuffer_Release(&pcp);
+        return NULL;
+    }
 
     if ( size == 1 ) maxval = (double) 0x7f;
     else if ( size == 2 ) maxval = (double) 0x7fff;
@@ -809,8 +827,10 @@
     }
 
     rv = PyBytes_FromStringAndSize(NULL, len/2);
-    if ( rv == 0 )
+    if ( rv == 0 ) {
+        PyBuffer_Release(&pcp);
         return 0;
+    }
     ncp = (signed char *)PyBytes_AsString(rv);
 
 
@@ -845,6 +865,8 @@
     if ( !PyArg_ParseTuple(args, "s#idd:tostereo",
                            &cp, &len, &size, &fac1, &fac2 ) )
         return 0;
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     if ( size == 1 ) maxval = (double) 0x7f;
     else if ( size == 2 ) maxval = (double) 0x7fff;
@@ -903,7 +925,8 @@
     if ( !PyArg_ParseTuple(args, "s#s#i:add",
                       &cp1, &len1, &cp2, &len2, &size ) )
         return 0;
-
+    if (!audioop_check_parameters(len1, size))
+        return NULL;
     if ( len1 != len2 ) {
         PyErr_SetString(AudioopError, "Lengths should be the same");
         return 0;
@@ -958,10 +981,8 @@
                       &cp, &len, &size , &bias) )
         return 0;
 
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     rv = PyBytes_FromStringAndSize(NULL, len);
     if ( rv == 0 )
@@ -994,10 +1015,8 @@
                       &cp, &len, &size) )
         return 0;
 
-    if ( size != 1 && size != 2 && size != 4 ) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     rv = PyBytes_FromStringAndSize(NULL, len);
     if ( rv == 0 )
@@ -1031,11 +1050,10 @@
                       &cp, &len, &size, &size2) )
         return 0;
 
-    if ( (size != 1 && size != 2 && size != 4) ||
-         (size2 != 1 && size2 != 2 && size2 != 4)) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
+    if (!audioop_check_size(size2))
+        return NULL;
 
     if (len/size > PY_SSIZE_T_MAX/size2) {
         PyErr_SetString(PyExc_MemoryError,
@@ -1086,10 +1104,8 @@
                           &nchannels, &inrate, &outrate, &state,
                           &weightA, &weightB))
         return NULL;
-    if (size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+    if (!audioop_check_size(size))
         return NULL;
-    }
     if (nchannels < 1) {
         PyErr_SetString(AudioopError, "# of channels should be >= 1");
         return NULL;
@@ -1265,10 +1281,8 @@
                            &cp, &len, &size) )
         return 0 ;
 
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     rv = PyBytes_FromStringAndSize(NULL, len/size);
     if ( rv == 0 )
@@ -1299,10 +1313,8 @@
                            &cp, &len, &size) )
         return 0;
 
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     if (len > PY_SSIZE_T_MAX/size) {
         PyErr_SetString(PyExc_MemoryError,
@@ -1338,10 +1350,8 @@
                            &cp, &len, &size) )
         return 0;
 
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     rv = PyBytes_FromStringAndSize(NULL, len/size);
     if ( rv == 0 )
@@ -1372,10 +1382,8 @@
                            &cp, &len, &size) )
         return 0;
 
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     if (len > PY_SSIZE_T_MAX/size) {
         PyErr_SetString(PyExc_MemoryError,
@@ -1413,11 +1421,8 @@
                            &cp, &len, &size, &state) )
         return 0;
 
-
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     str = PyBytes_FromStringAndSize(NULL, len/(size*2));
     if ( str == 0 )
@@ -1522,10 +1527,8 @@
                            &cp, &len, &size, &state) )
         return 0;
 
-    if ( size != 1 && size != 2 && size != 4) {
-        PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
-        return 0;
-    }
+    if (!audioop_check_parameters(len, size))
+        return NULL;
 
     /* Decode state, should have (value, step) */
     if ( state == Py_None ) {

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

Modified: python/branches/py3k-cdecimal/Modules/datetimemodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/datetimemodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/datetimemodule.c	Sat Jul 17 12:36:09 2010
@@ -88,8 +88,11 @@
 /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
  * p->hastzinfo.
  */
-#define HASTZINFO(p)            (((_PyDateTime_BaseTZInfo *)(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
@@ -102,6 +105,7 @@
 static PyTypeObject PyDateTime_DeltaType;
 static PyTypeObject PyDateTime_TimeType;
 static PyTypeObject PyDateTime_TZInfoType;
+static PyTypeObject PyDateTime_TimeZoneType;
 
 /* ---------------------------------------------------------------------------
  * Math utilities.
@@ -771,6 +775,54 @@
 #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.
  */
@@ -790,25 +842,6 @@
     return -1;
 }
 
-/* Return tzinfo.methname(tzinfoarg), without any checking of results.
- * If tzinfo is None, returns None.
- */
-static PyObject *
-call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
-{
-    PyObject *result;
-
-    assert(tzinfo && methname && tzinfoarg);
-    assert(check_tzinfo_subclass(tzinfo) >= 0);
-    if (tzinfo == Py_None) {
-        result = Py_None;
-        Py_INCREF(result);
-    }
-    else
-        result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
-    return result;
-}
-
 /* If self has a tzinfo member, return a BORROWED reference to it.  Else
  * return NULL, which is NOT AN ERROR.  There are no error returns here,
  * and the caller must not decref the result.
@@ -826,69 +859,53 @@
     return tzinfo;
 }
 
-/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
- * result.  tzinfo must be an instance of the tzinfo class.  If the method
- * returns None, this returns 0 and sets *none to 1.  If the method doesn't
- * return None or timedelta, TypeError is raised and this returns -1.  If it
- * returnsa timedelta and the value is out of range or isn't a whole number
- * of minutes, ValueError is raised and this returns -1.
- * Else *none is set to 0 and the integer method result is returned.
+/* 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 int
-call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
-                       int *none)
+static PyObject *
+call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
 {
-    PyObject *u;
-    int result = -1;
+    PyObject *offset;
 
     assert(tzinfo != NULL);
-    assert(PyTZInfo_Check(tzinfo));
+    assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
     assert(tzinfoarg != NULL);
 
-    *none = 0;
-    u = call_tzinfo_method(tzinfo, name, tzinfoarg);
-    if (u == NULL)
-        return -1;
-
-    else if (u == Py_None) {
-        result = 0;
-        *none = 1;
-    }
-    else if (PyDelta_Check(u)) {
-        const int days = GET_TD_DAYS(u);
-        if (days < -1 || days > 0)
-            result = 24*60;             /* trigger ValueError below */
-        else {
-            /* next line can't overflow because we know days
-             * is -1 or 0 now
-             */
-            int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
-            result = divmod(ss, 60, &ss);
-            if (ss || GET_TD_MICROSECONDS(u)) {
-                PyErr_Format(PyExc_ValueError,
-                             "tzinfo.%s() must return a "
-                             "whole number of minutes",
-                             name);
-                result = -1;
-            }
+    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 '%s'",
-                     name, Py_TYPE(u)->tp_name);
+                     "timedelta, not '%.200s'",
+                     name, Py_TYPE(offset)->tp_name);
+        return NULL;
     }
 
-    Py_DECREF(u);
-    if (result < -1439 || result > 1439) {
-        PyErr_Format(PyExc_ValueError,
-                     "tzinfo.%s() returned %d; must be in "
-                     "-1439 .. 1439",
-                     name, result);
-        result = -1;
-    }
-    return result;
+    return offset;
 }
 
 /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
@@ -899,37 +916,10 @@
  * # of minutes), ValueError is raised and this returns -1.  Else *none is
  * set to 0 and the offset is returned (as int # of minutes east of UTC).
  */
-static int
-call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
-{
-    return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
-}
-
-/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
- */
 static PyObject *
-offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
-    PyObject *result;
-
-    assert(tzinfo && name && tzinfoarg);
-    if (tzinfo == Py_None) {
-        result = Py_None;
-        Py_INCREF(result);
-    }
-    else {
-        int none;
-        int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
-                                            &none);
-        if (offset < 0 && PyErr_Occurred())
-            return NULL;
-        if (none) {
-            result = Py_None;
-            Py_INCREF(result);
-        }
-        else
-            result = new_delta(0, offset * 60, 0, 1);
-    }
-    return result;
+call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
+{
+    return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
 }
 
 /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
@@ -940,10 +930,10 @@
  * ValueError is raised and this returns -1.  Else *none is set to 0 and
  * the offset is returned (as an int # of minutes east of UTC).
  */
-static int
-call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
+static PyObject *
+call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
 {
-    return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
+    return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
 }
 
 /* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be
@@ -961,107 +951,23 @@
     assert(check_tzinfo_subclass(tzinfo) >= 0);
     assert(tzinfoarg != NULL);
 
-    if (tzinfo == Py_None) {
-        result = Py_None;
-        Py_INCREF(result);
-    }
-    else
-        result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
+    if (tzinfo == Py_None)
+        Py_RETURN_NONE;
 
-    if (result != NULL && result != Py_None) {
-        if (!PyUnicode_Check(result)) {
-            PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
-                         "return None or a string, not '%s'",
-                         Py_TYPE(result)->tp_name);
-            Py_DECREF(result);
-            result = NULL;
-        }
-        else if (!PyUnicode_Check(result)) {
-            PyObject *temp = PyUnicode_FromObject(result);
-            Py_DECREF(result);
-            result = temp;
-        }
-    }
-    return result;
-}
+    result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
 
-typedef enum {
-              /* an exception has been set; the caller should pass it on */
-          OFFSET_ERROR,
-
-          /* type isn't date, datetime, or time subclass */
-          OFFSET_UNKNOWN,
-
-          /* date,
-           * datetime with !hastzinfo
-           * datetime with None tzinfo,
-           * datetime where utcoffset() returns None
-           * time with !hastzinfo
-           * time with None tzinfo,
-           * time where utcoffset() returns None
-           */
-          OFFSET_NAIVE,
-
-          /* time or datetime where utcoffset() doesn't return None */
-          OFFSET_AWARE
-} naivety;
-
-/* Classify an object as to whether it's naive or offset-aware.  See
- * the "naivety" typedef for details.  If the type is aware, *offset is set
- * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
- * If the type is offset-naive (or unknown, or error), *offset is set to 0.
- * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
- */
-static naivety
-classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
-{
-    int none;
-    PyObject *tzinfo;
+    if (result == NULL || result == Py_None)
+        return result;
 
-    assert(tzinfoarg != NULL);
-    *offset = 0;
-    tzinfo = get_tzinfo_member(op);     /* NULL means no tzinfo, not error */
-    if (tzinfo == Py_None)
-        return OFFSET_NAIVE;
-    if (tzinfo == NULL) {
-        /* note that a datetime passes the PyDate_Check test */
-        return (PyTime_Check(op) || PyDate_Check(op)) ?
-               OFFSET_NAIVE : OFFSET_UNKNOWN;
-    }
-    *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
-    if (*offset == -1 && PyErr_Occurred())
-        return OFFSET_ERROR;
-    return none ? OFFSET_NAIVE : OFFSET_AWARE;
-}
-
-/* Classify two objects as to whether they're naive or offset-aware.
- * This isn't quite the same as calling classify_utcoffset() twice:  for
- * binary operations (comparison and subtraction), we generally want to
- * ignore the tzinfo members if they're identical.  This is by design,
- * so that results match "naive" expectations when mixing objects from a
- * single timezone.  So in that case, this sets both offsets to 0 and
- * both naiveties to OFFSET_NAIVE.
- * The function returns 0 if everything's OK, and -1 on error.
- */
-static int
-classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
-                        PyObject *tzinfoarg1,
-                        PyObject *o2, int *offset2, naivety *n2,
-                        PyObject *tzinfoarg2)
-{
-    if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
-        *offset1 = *offset2 = 0;
-        *n1 = *n2 = OFFSET_NAIVE;
-    }
-    else {
-        *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
-        if (*n1 == OFFSET_ERROR)
-            return -1;
-        *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
-        if (*n2 == OFFSET_ERROR)
-            return -1;
+    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 0;
+
+    return result;
 }
 
 /* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,
@@ -1113,6 +1019,8 @@
                                 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
@@ -1127,28 +1035,41 @@
 format_utcoffset(char *buf, size_t buflen, const char *sep,
                 PyObject *tzinfo, PyObject *tzinfoarg)
 {
-    int offset;
-    int hours;
-    int minutes;
+    PyObject *offset;
+    int hours, minutes, seconds;
     char sign;
-    int none;
 
     assert(buflen >= 1);
 
-    offset = call_utcoffset(tzinfo, tzinfoarg, &none);
-    if (offset == -1 && PyErr_Occurred())
+    offset = call_utcoffset(tzinfo, tzinfoarg);
+    if (offset == NULL)
         return -1;
-    if (none) {
+    if (offset == Py_None) {
+        Py_DECREF(offset);
         *buf = '\0';
         return 0;
     }
-    sign = '+';
-    if (offset < 0) {
+    /* Offset is normalized, so it is negative if days < 0 */
+    if (GET_TD_DAYS(offset) < 0) {
+        PyObject *temp = offset;
         sign = '-';
-        offset = - offset;
+        offset = delta_negative((PyDateTime_Delta *)offset);
+        Py_DECREF(temp);
+        if (offset == NULL)
+            return -1;
+    }
+    else {
+        sign = '+';
     }
-    hours = divmod(offset, 60, &minutes);
+    /* 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;
 }
 
@@ -1390,7 +1311,7 @@
         format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
         if (format != NULL) {
             result = PyObject_CallMethod(time, "strftime", "OO",
-                                         format, timetuple);
+                                         format, timetuple, NULL);
             Py_DECREF(format);
         }
         Py_DECREF(time);
@@ -1893,17 +1814,24 @@
     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 = 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);
-        }
+        int diff = delta_cmp(self, other);
         return diff_to_bool(diff, op);
     }
     else {
@@ -3075,76 +3003,73 @@
     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, PyDateTime_DateTime *dt)
+tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
 {
-    int y, m, d, hh, mm, ss, us;
-
-    PyObject *result;
-    int off, dst;
-    int none;
-    int delta;
+    PyObject *result = NULL;
+    PyObject *off = NULL, *dst = NULL;
+    PyDateTime_Delta *delta = NULL;
 
-    if (! PyDateTime_Check(dt)) {
+    if (!PyDateTime_Check(dt)) {
         PyErr_SetString(PyExc_TypeError,
                         "fromutc: argument must be a datetime");
         return NULL;
     }
-    if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
+    if (GET_DT_TZINFO(dt) != (PyObject *)self) {
         PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
                         "is not self");
         return NULL;
     }
 
-    off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
-    if (off == -1 && PyErr_Occurred())
+    off = datetime_utcoffset(dt, NULL);
+    if (off == NULL)
         return NULL;
-    if (none) {
+    if (off == Py_None) {
         PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
                         "utcoffset() result required");
-        return NULL;
+        goto Fail;
     }
 
-    dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
-    if (dst == -1 && PyErr_Occurred())
-        return NULL;
-    if (none) {
+    dst = datetime_dst(dt, NULL);
+    if (dst == NULL)
+        goto Fail;
+    if (dst == Py_None) {
         PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
                         "dst() result required");
-        return NULL;
+        goto Fail;
     }
 
-    y = GET_YEAR(dt);
-    m = GET_MONTH(dt);
-    d = GET_DAY(dt);
-    hh = DATE_GET_HOUR(dt);
-    mm = DATE_GET_MINUTE(dt);
-    ss = DATE_GET_SECOND(dt);
-    us = DATE_GET_MICROSECOND(dt);
-
-    delta = off - dst;
-    mm += delta;
-    if ((mm < 0 || mm >= 60) &&
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
-        return NULL;
-    result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
+    delta = (PyDateTime_Delta *)delta_subtract(off, dst);
+    if (delta == NULL)
+        goto Fail;
+    result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
     if (result == NULL)
-        return result;
-
-    dst = call_dst(dt->tzinfo, result, &none);
-    if (dst == -1 && PyErr_Occurred())
         goto Fail;
-    if (none)
-        goto Inconsistent;
-    if (dst == 0)
-        return result;
 
-    mm += dst;
-    if ((mm < 0 || mm >= 60) &&
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+    Py_DECREF(dst);
+    dst = call_dst(GET_DT_TZINFO(dt), result);
+    if (dst == NULL)
         goto Fail;
-    Py_DECREF(result);
-    result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
+    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:
@@ -3153,7 +3078,10 @@
 
     /* fall thru to failure */
 Fail:
-    Py_DECREF(result);
+    Py_XDECREF(off);
+    Py_XDECREF(dst);
+    Py_XDECREF(delta);
+    Py_XDECREF(result);
     return NULL;
 }
 
@@ -3261,7 +3189,7 @@
     PyObject_GenericGetAttr,                    /* tp_getattro */
     0,                                          /* tp_setattro */
     0,                                          /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
     tzinfo_doc,                                 /* tp_doc */
     0,                                          /* tp_traverse */
     0,                                          /* tp_clear */
@@ -3283,6 +3211,231 @@
     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.
  */
@@ -3416,21 +3569,18 @@
 
 /* These are all METH_NOARGS, so don't need to check the arglist. */
 static PyObject *
-time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "utcoffset", Py_None);
+time_utcoffset(PyObject *self, PyObject *unused) {
+    return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
 }
 
 static PyObject *
-time_dst(PyDateTime_Time *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "dst", Py_None);
+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(HASTZINFO(self) ? self->tzinfo : Py_None,
-                       Py_None);
+    return call_tzname(GET_TIME_TZINFO(self), Py_None);
 }
 
 /*
@@ -3485,7 +3635,7 @@
                                       TIME_GET_MINUTE(self),
                                       TIME_GET_SECOND(self));
 
-    if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
+    if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
         return result;
 
     /* We need to append the UTC offset. */
@@ -3536,98 +3686,108 @@
 static PyObject *
 time_richcompare(PyObject *self, PyObject *other, int op)
 {
+    PyObject *result = NULL;
+    PyObject *offset1, *offset2;
     int diff;
-    naivety n1, n2;
-    int offset1, offset2;
 
     if (! PyTime_Check(other)) {
         Py_INCREF(Py_NotImplemented);
         return Py_NotImplemented;
     }
-    if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
-                                other, &offset2, &n2, Py_None) < 0)
+
+    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;
-    assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+    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 == 0 at this point.
+     * offset2 == Py_None at this point.
      */
-    if (n1 == n2 && offset1 == offset2) {
+    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);
-        return diff_to_bool(diff, op);
+        result = diff_to_bool(diff, op);
     }
-
-    if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
-        assert(offset1 != offset2);             /* else last "if" handled it */
-        /* Convert everything except microseconds to seconds.  These
-         * can't overflow (no more than the # of seconds in 2 days).
-         */
-        offset1 = TIME_GET_HOUR(self) * 3600 +
-                  (TIME_GET_MINUTE(self) - offset1) * 60 +
-                  TIME_GET_SECOND(self);
-        offset2 = TIME_GET_HOUR(other) * 3600 +
-                  (TIME_GET_MINUTE(other) - offset2) * 60 +
-                  TIME_GET_SECOND(other);
-        diff = offset1 - offset2;
+    /* 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);
-        return diff_to_bool(diff, op);
+        result = diff_to_bool(diff, op);
     }
-
-    assert(n1 != n2);
-    PyErr_SetString(PyExc_TypeError,
-                    "can't compare offset-naive and "
-                    "offset-aware times");
-    return NULL;
+    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) {
-        naivety n;
-        int offset;
-        PyObject *temp;
-
-        n = classify_utcoffset((PyObject *)self, Py_None, &offset);
-        assert(n != OFFSET_UNKNOWN);
-        if (n == OFFSET_ERROR)
+        PyObject *offset;
+
+        offset = time_utcoffset((PyObject *)self, NULL);
+
+        if (offset == NULL)
             return -1;
 
         /* Reduce this to a hash of another object. */
-        if (offset == 0) {
+        if (offset == Py_None)
             self->hashcode = generic_hash(
                 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
-            return self->hashcode;
-        }
         else {
-            int hour;
-            int minute;
-
-            assert(n == OFFSET_AWARE);
+            PyObject *temp1, *temp2;
+            int seconds, microseconds;
             assert(HASTZINFO(self));
-            hour = divmod(TIME_GET_HOUR(self) * 60 +
-                            TIME_GET_MINUTE(self) - offset,
-                          60,
-                          &minute);
-            if (0 <= hour && hour < 24)
-                temp = new_time(hour, minute,
-                                TIME_GET_SECOND(self),
-                                TIME_GET_MICROSECOND(self),
-                                Py_None);
-            else
-                temp = Py_BuildValue("iiii",
-                           hour, minute,
-                           TIME_GET_SECOND(self),
-                           TIME_GET_MICROSECOND(self));
-        }
-        if (temp != NULL) {
-            self->hashcode = PyObject_Hash(temp);
-            Py_DECREF(temp);
+            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;
 }
@@ -3656,10 +3816,10 @@
 }
 
 static int
-time_bool(PyDateTime_Time *self)
+time_bool(PyObject *self)
 {
-    int offset;
-    int none;
+    PyObject *offset, *tzinfo;
+    int offsecs = 0;
 
     if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
         /* Since utcoffset is in whole minutes, nothing can
@@ -3667,13 +3827,15 @@
          */
         return 1;
     }
-    offset = 0;
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        offset = call_utcoffset(self->tzinfo, Py_None, &none);
-        if (offset == -1 && PyErr_Occurred())
+    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) - offset + TIME_GET_HOUR(self)*60) != 0;
+    return (TIME_GET_MINUTE(self)*60 - offsecs + TIME_GET_HOUR(self)*3600) != 0;
 }
 
 /* Pickle support, a simple use of __reduce__. */
@@ -4115,82 +4277,23 @@
     return result;
 }
 
-/* Return new datetime from time.strptime(). */
+/* Return new datetime from _strptime.strptime_datetime(). */
 static PyObject *
 datetime_strptime(PyObject *cls, PyObject *args)
 {
     static PyObject *module = NULL;
-    PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
     const Py_UNICODE *string, *format;
 
     if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
         return NULL;
 
-    if (module == NULL &&
-        (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
-        return NULL;
-
-    /* _strptime._strptime returns a two-element tuple.  The first
-       element is a time.struct_time object.  The second is the
-       microseconds (which are not defined for time.struct_time). */
-    obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
-    if (obj != NULL) {
-        int i, good_timetuple = 1;
-        long int ia[7];
-        if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
-            st = PySequence_GetItem(obj, 0);
-            frac = PySequence_GetItem(obj, 1);
-            if (st == NULL || frac == NULL)
-                good_timetuple = 0;
-            /* copy y/m/d/h/m/s values out of the
-               time.struct_time */
-            if (good_timetuple &&
-                PySequence_Check(st) &&
-                PySequence_Size(st) >= 6) {
-                for (i=0; i < 6; i++) {
-                    PyObject *p = PySequence_GetItem(st, i);
-                    if (p == NULL) {
-                        good_timetuple = 0;
-                        break;
-                    }
-                    if (PyLong_Check(p))
-                        ia[i] = PyLong_AsLong(p);
-                    else
-                        good_timetuple = 0;
-                    Py_DECREF(p);
-                }
-/*                              if (PyLong_CheckExact(p)) {
-                                        ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
-                                        if (overflow)
-                                                good_timetuple = 0;
-                                }
-                                else
-                                        good_timetuple = 0;
-                                Py_DECREF(p);
-*/                      }
-                        else
-                                good_timetuple = 0;
-                        /* follow that up with a little dose of microseconds */
-            if (PyLong_Check(frac))
-                ia[6] = PyLong_AsLong(frac);
-            else
-                good_timetuple = 0;
-        }
-        else
-            good_timetuple = 0;
-        if (good_timetuple)
-            result = PyObject_CallFunction(cls, "iiiiiii",
-                                           ia[0], ia[1], ia[2],
-                                           ia[3], ia[4], ia[5],
-                                           ia[6]);
-        else
-            PyErr_SetString(PyExc_ValueError,
-                "unexpected value from _strptime._strptime");
+    if (module == NULL) {
+        module = PyImport_ImportModuleNoBlock("_strptime");
+        if (module == NULL)
+            return NULL;
     }
-    Py_XDECREF(obj);
-    Py_XDECREF(st);
-    Py_XDECREF(frac);
-    return result;
+    return PyObject_CallMethod(module, "_strptime_datetime", "Ouu",
+                               cls, string, format);
 }
 
 /* Return new datetime from date/datetime and time arguments. */
@@ -4241,21 +4344,18 @@
 
 /* These are all METH_NOARGS, so don't need to check the arglist. */
 static PyObject *
-datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "utcoffset", (PyObject *)self);
+datetime_utcoffset(PyObject *self, PyObject *unused) {
+    return call_utcoffset(GET_DT_TZINFO(self), self);
 }
 
 static PyObject *
-datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
-                               "dst", (PyObject *)self);
+datetime_dst(PyObject *self, PyObject *unused) {
+    return call_dst(GET_DT_TZINFO(self), self);
 }
 
 static PyObject *
-datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
-    return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
-                       (PyObject *)self);
+datetime_tzname(PyObject *self, PyObject *unused) {
+    return call_tzname(GET_DT_TZINFO(self), self);
 }
 
 /*
@@ -4322,21 +4422,43 @@
         /* datetime - ??? */
         if (PyDateTime_Check(right)) {
             /* datetime - datetime */
-            naivety n1, n2;
-            int offset1, offset2;
+            PyObject *offset1, *offset2, *offdiff = NULL;
             int delta_d, delta_s, delta_us;
 
-            if (classify_two_utcoffsets(left, &offset1, &n1, left,
-                                        right, &offset2, &n2,
-                                        right) < 0)
-                return NULL;
-            assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
-            if (n1 != n2) {
-                PyErr_SetString(PyExc_TypeError,
-                    "can't subtract offset-naive and "
-                    "offset-aware datetimes");
-                return NULL;
+            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)) -
@@ -4355,11 +4477,13 @@
                        DATE_GET_SECOND(right));
             delta_us = DATE_GET_MICROSECOND(left) -
                        DATE_GET_MICROSECOND(right);
-            /* (left - offset1) - (right - offset2) =
-             * (left - right) + (offset2 - offset1)
-             */
-            delta_s += (offset2 - offset1) * 60;
             result = new_delta(delta_d, delta_s, delta_us, 1);
+            if (offdiff != NULL) {
+                PyObject *temp = result;
+                result = delta_subtract(result, offdiff);
+                Py_DECREF(temp);
+                Py_DECREF(offdiff);
+            }
         }
         else if (PyDelta_Check(right)) {
             /* datetime - delta */
@@ -4469,9 +4593,9 @@
 static PyObject *
 datetime_richcompare(PyObject *self, PyObject *other, int op)
 {
+    PyObject *result = NULL;
+    PyObject *offset1, *offset2;
     int diff;
-    naivety n1, n2;
-    int offset1, offset2;
 
     if (! PyDateTime_Check(other)) {
         if (PyDate_Check(other)) {
@@ -4492,85 +4616,99 @@
         return Py_NotImplemented;
     }
 
-    if (classify_two_utcoffsets(self, &offset1, &n1, self,
-                                other, &offset2, &n2, other) < 0)
+    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;
-    assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+    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 == 0 at this point.
+     * offset2 == Py_None at this point.
      */
-    if (n1 == n2 && offset1 == offset2) {
+    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);
-        return diff_to_bool(diff, op);
+        result = diff_to_bool(diff, op);
     }
-
-    if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
+    else if (offset1 != Py_None && offset2 != Py_None) {
         PyDateTime_Delta *delta;
 
-        assert(offset1 != offset2);             /* else last "if" handled it */
+        assert(offset1 != offset2); /* else last "if" handled it */
         delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
                                                        other);
         if (delta == NULL)
-            return NULL;
+            goto done;
         diff = GET_TD_DAYS(delta);
         if (diff == 0)
             diff = GET_TD_SECONDS(delta) |
                    GET_TD_MICROSECONDS(delta);
         Py_DECREF(delta);
-        return diff_to_bool(diff, op);
+        result = diff_to_bool(diff, op);
     }
-
-    assert(n1 != n2);
-    PyErr_SetString(PyExc_TypeError,
-                    "can't compare offset-naive and "
-                    "offset-aware datetimes");
-    return NULL;
+    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) {
-        naivety n;
-        int offset;
-        PyObject *temp;
-
-        n = classify_utcoffset((PyObject *)self, (PyObject *)self,
-                               &offset);
-        assert(n != OFFSET_UNKNOWN);
-        if (n == OFFSET_ERROR)
+        PyObject *offset;
+
+        offset = datetime_utcoffset((PyObject *)self, NULL);
+
+        if (offset == NULL)
             return -1;
 
         /* Reduce this to a hash of another object. */
-        if (n == OFFSET_NAIVE) {
+        if (offset == Py_None)
             self->hashcode = generic_hash(
                 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
-            return self->hashcode;
-        }
         else {
-            int days;
-            int seconds;
+            PyObject *temp1, *temp2;
+            int days, seconds;
 
-            assert(n == OFFSET_AWARE);
             assert(HASTZINFO(self));
             days = ymd_to_ord(GET_YEAR(self),
                               GET_MONTH(self),
                               GET_DAY(self));
             seconds = DATE_GET_HOUR(self) * 3600 +
-                      (DATE_GET_MINUTE(self) - offset) * 60 +
+                      DATE_GET_MINUTE(self) * 60 +
                       DATE_GET_SECOND(self);
-            temp = new_delta(days,
-                             seconds,
-                             DATE_GET_MICROSECOND(self),
-                             1);
-        }
-        if (temp != NULL) {
-            self->hashcode = PyObject_Hash(temp);
-            Py_DECREF(temp);
+            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;
 }
@@ -4605,10 +4743,9 @@
 static PyObject *
 datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
 {
-    int y, m, d, hh, mm, ss, us;
     PyObject *result;
-    int offset, none;
-
+    PyObject *offset;
+    PyObject *temp;
     PyObject *tzinfo;
     static char *keywords[] = {"tz", NULL};
 
@@ -4626,39 +4763,35 @@
     }
 
     /* Convert self to UTC. */
-    offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
-    if (offset == -1 && PyErr_Occurred())
+    offset = datetime_utcoffset((PyObject *)self, NULL);
+    if (offset == NULL)
         return NULL;
-    if (none)
-        goto NeedAware;
+    if (offset == Py_None) {
+        Py_DECREF(offset);
+      NeedAware:
+        PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
+                        "a naive datetime");
+        return NULL;
+    }
 
-    y = GET_YEAR(self);
-    m = GET_MONTH(self);
-    d = GET_DAY(self);
-    hh = DATE_GET_HOUR(self);
-    mm = DATE_GET_MINUTE(self);
-    ss = DATE_GET_SECOND(self);
-    us = DATE_GET_MICROSECOND(self);
-
-    mm -= offset;
-    if ((mm < 0 || mm >= 60) &&
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+    /* 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. */
-    result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
-    if (result != NULL) {
-        PyObject *temp = result;
+    temp = ((PyDateTime_DateTime *)result)->tzinfo;
+    ((PyDateTime_DateTime *)result)->tzinfo = tzinfo;
+    Py_INCREF(tzinfo);
+    Py_DECREF(temp);
 
-        result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
-        Py_DECREF(temp);
-    }
-    return result;
+    temp = result;
+    result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
+    Py_DECREF(temp);
 
-NeedAware:
-    PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
-                                      "a naive datetime");
-    return NULL;
+    return result;
 }
 
 static PyObject *
@@ -4667,17 +4800,15 @@
     int dstflag = -1;
 
     if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        int none;
+        PyObject * dst;
 
-        dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
-        if (dstflag == -1 && PyErr_Occurred())
+        dst = call_dst(self->tzinfo, (PyObject *)self);
+        if (dst == NULL)
             return NULL;
 
-        if (none)
-            dstflag = -1;
-        else if (dstflag != 0)
-            dstflag = 1;
-
+        if (dst != Py_None)
+            dstflag = delta_bool((PyDateTime_Delta *)dst);
+        Py_DECREF(dst);
     }
     return build_struct_time(GET_YEAR(self),
                              GET_MONTH(self),
@@ -4713,47 +4844,47 @@
                     DATE_GET_MINUTE(self),
                     DATE_GET_SECOND(self),
                     DATE_GET_MICROSECOND(self),
-                    HASTZINFO(self) ? self->tzinfo : Py_None);
+                    GET_DT_TZINFO(self));
 }
 
 static PyObject *
 datetime_utctimetuple(PyDateTime_DateTime *self)
 {
-    int y = GET_YEAR(self);
-    int m = GET_MONTH(self);
-    int d = GET_DAY(self);
-    int hh = DATE_GET_HOUR(self);
-    int mm = DATE_GET_MINUTE(self);
-    int ss = DATE_GET_SECOND(self);
-    int us = 0;         /* microseconds are ignored in a timetuple */
-    int offset = 0;
-
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {
-        int none;
+    int y, m, d, hh, mm, ss;
+    PyObject *tzinfo;
+    PyDateTime_DateTime *utcself;
 
-        offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
-        if (offset == -1 && PyErr_Occurred())
-            return NULL;
+    tzinfo = GET_DT_TZINFO(self);
+    if (tzinfo == Py_None) {
+        utcself = self;
+        Py_INCREF(utcself);
     }
-    /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
-     * 0 in a UTC timetuple regardless of what dst() says.
-     */
-    if (offset) {
-        /* Subtract offset minutes & normalize. */
-        int stat;
-
-        mm -= offset;
-        stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
-        if (stat < 0) {
-            /* At the edges, it's possible we overflowed
-             * beyond MINYEAR or MAXYEAR.
-             */
-            if (PyErr_ExceptionMatches(PyExc_OverflowError))
-                PyErr_Clear();
-            else
+    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);
 }
 
@@ -4971,6 +5102,7 @@
     PyObject *m;        /* a module object */
     PyObject *d;        /* its dict */
     PyObject *x;
+    PyObject *delta;
 
     m = PyModule_Create(&datetimemodule);
     if (m == NULL)
@@ -4986,6 +5118,8 @@
         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;
@@ -5059,6 +5193,36 @@
         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);
@@ -5079,6 +5243,9 @@
     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;

Modified: python/branches/py3k-cdecimal/Modules/makesetup
==============================================================================
--- python/branches/py3k-cdecimal/Modules/makesetup	(original)
+++ python/branches/py3k-cdecimal/Modules/makesetup	Sat Jul 17 12:36:09 2010
@@ -219,7 +219,7 @@
 			case $doconfig in
 			no)	cc="$cc \$(CCSHARED) \$(CFLAGS) \$(CPPFLAGS)";;
 			*)
-				cc="$cc \$(PY_CFLAGS)";;
+				cc="$cc \$(PY_CORE_CFLAGS)";;
 			esac
 			rule="$obj: $src; $cc $cpps -c $src -o $obj"
 			echo "$rule" >>$rulesf

Modified: python/branches/py3k-cdecimal/Modules/mathmodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/mathmodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/mathmodule.c	Sat Jul 17 12:36:09 2010
@@ -69,6 +69,7 @@
 
 static const double pi = 3.141592653589793238462643383279502884197;
 static const double sqrtpi = 1.772453850905516027298167483341145182798;
+static const double logpi = 1.144729885849400174143427351353058711647;
 
 static double
 sinpi(double x)
@@ -356,20 +357,15 @@
     if (absx < 1e-20)
         return -log(absx);
 
-    /* Lanczos' formula */
-    if (x > 0.0) {
-        /* we could save a fraction of a ulp in accuracy by having a
-           second set of numerator coefficients for lanczos_sum that
-           absorbed the exp(-lanczos_g) term, and throwing out the
-           lanczos_g subtraction below; it's probably not worth it. */
-        r = log(lanczos_sum(x)) - lanczos_g +
-            (x-0.5)*(log(x+lanczos_g-0.5)-1);
-    }
-    else {
-        r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
-            (log(lanczos_sum(absx)) - lanczos_g +
-             (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
-    }
+    /* Lanczos' formula.  We could save a fraction of a ulp in accuracy by
+       having a second set of numerator coefficients for lanczos_sum that
+       absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
+       subtraction below; it's probably not worth it. */
+    r = log(lanczos_sum(absx)) - lanczos_g;
+    r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
+    if (x < 0.0)
+        /* Use reflection formula to get value for negative x. */
+        r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
     if (Py_IS_INFINITY(r))
         errno = ERANGE;
     return r;
@@ -841,19 +837,17 @@
 
 static PyObject * math_ceil(PyObject *self, PyObject *number) {
     static PyObject *ceil_str = NULL;
-    PyObject *method;
+    PyObject *method, *result;
 
-    if (ceil_str == NULL) {
-        ceil_str = PyUnicode_InternFromString("__ceil__");
-        if (ceil_str == NULL)
+    method = _PyObject_LookupSpecial(number, "__ceil__", &ceil_str);
+    if (method == NULL) {
+        if (PyErr_Occurred())
             return NULL;
-    }
-
-    method = _PyType_Lookup(Py_TYPE(number), ceil_str);
-    if (method == NULL)
         return math_1_to_int(number, ceil, 0);
-    else
-        return PyObject_CallFunction(method, "O", number);
+    }
+    result = PyObject_CallFunctionObjArgs(method, NULL);
+    Py_DECREF(method);
+    return result;
 }
 
 PyDoc_STRVAR(math_ceil_doc,
@@ -881,19 +875,17 @@
 
 static PyObject * math_floor(PyObject *self, PyObject *number) {
     static PyObject *floor_str = NULL;
-    PyObject *method;
+    PyObject *method, *result;
 
-    if (floor_str == NULL) {
-        floor_str = PyUnicode_InternFromString("__floor__");
-        if (floor_str == NULL)
+    method = _PyObject_LookupSpecial(number, "__floor__", &floor_str);
+    if (method == NULL) {
+        if (PyErr_Occurred())
             return NULL;
-    }
-
-    method = _PyType_Lookup(Py_TYPE(number), floor_str);
-    if (method == NULL)
         return math_1_to_int(number, floor, 0);
-    else
-        return PyObject_CallFunction(method, "O", number);
+    }
+    result = PyObject_CallFunctionObjArgs(method, NULL);
+    Py_DECREF(method);
+    return result;
 }
 
 PyDoc_STRVAR(math_floor_doc,
@@ -904,7 +896,7 @@
       "gamma(x)\n\nGamma function at x.")
 FUNC1A(lgamma, m_lgamma,
       "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
-FUNC1(log1p, m_log1p, 1,
+FUNC1(log1p, m_log1p, 0,
       "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
       "The result is computed in a way which is accurate for x near zero.")
 FUNC1(sin, sin, 0,
@@ -989,17 +981,17 @@
    def msum(iterable):
        partials = []  # sorted, non-overlapping partial sums
        for x in iterable:
-       i = 0
-       for y in partials:
-           if abs(x) < abs(y):
-           x, y = y, x
-           hi = x + y
-           lo = y - (hi - x)
-           if lo:
-           partials[i] = lo
-           i += 1
-           x = hi
-       partials[i:] = [x]
+           i = 0
+           for y in partials:
+               if abs(x) < abs(y):
+                   x, y = y, x
+               hi = x + y
+               lo = y - (hi - x)
+               if lo:
+                   partials[i] = lo
+                   i += 1
+               x = hi
+           partials[i:] = [x]
        return sum_exact(partials)
 
    Rounded x+y stored in hi with the roundoff stored in lo.  Together hi+lo
@@ -1178,7 +1170,7 @@
  * http://www.luschny.de/math/factorial/binarysplitfact.html
  *
  * Faster algorithms exist, but they're more complicated and depend on
- * a fast prime factoriazation algorithm.
+ * a fast prime factorization algorithm.
  *
  * Notes on the algorithm
  * ----------------------
@@ -1420,27 +1412,24 @@
 math_trunc(PyObject *self, PyObject *number)
 {
     static PyObject *trunc_str = NULL;
-    PyObject *trunc;
+    PyObject *trunc, *result;
 
     if (Py_TYPE(number)->tp_dict == NULL) {
         if (PyType_Ready(Py_TYPE(number)) < 0)
             return NULL;
     }
 
-    if (trunc_str == NULL) {
-        trunc_str = PyUnicode_InternFromString("__trunc__");
-        if (trunc_str == NULL)
-            return NULL;
-    }
-
-    trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
+    trunc = _PyObject_LookupSpecial(number, "__trunc__", &trunc_str);
     if (trunc == NULL) {
-        PyErr_Format(PyExc_TypeError,
-                     "type %.100s doesn't define __trunc__ method",
-                     Py_TYPE(number)->tp_name);
+        if (!PyErr_Occurred())
+            PyErr_Format(PyExc_TypeError,
+                         "type %.100s doesn't define __trunc__ method",
+                         Py_TYPE(number)->tp_name);
         return NULL;
     }
-    return PyObject_CallFunctionObjArgs(trunc, number, NULL);
+    result = PyObject_CallFunctionObjArgs(trunc, NULL);
+    Py_DECREF(trunc);
+    return result;
 }
 
 PyDoc_STRVAR(math_trunc_doc,
@@ -1829,6 +1818,19 @@
 Convert angle x from degrees to radians.");
 
 static PyObject *
+math_isfinite(PyObject *self, PyObject *arg)
+{
+    double x = PyFloat_AsDouble(arg);
+    if (x == -1.0 && PyErr_Occurred())
+        return NULL;
+    return PyBool_FromLong((long)Py_IS_FINITE(x));
+}
+
+PyDoc_STRVAR(math_isfinite_doc,
+"isfinite(x) -> bool\n\n\
+Return True if x is neither an infinity nor a NaN, and False otherwise.");
+
+static PyObject *
 math_isnan(PyObject *self, PyObject *arg)
 {
     double x = PyFloat_AsDouble(arg);
@@ -1839,7 +1841,7 @@
 
 PyDoc_STRVAR(math_isnan_doc,
 "isnan(x) -> bool\n\n\
-Check if float x is not a number (NaN).");
+Return True if x is a NaN (not a number), and False otherwise.");
 
 static PyObject *
 math_isinf(PyObject *self, PyObject *arg)
@@ -1852,7 +1854,7 @@
 
 PyDoc_STRVAR(math_isinf_doc,
 "isinf(x) -> bool\n\n\
-Check if float x is infinite (positive or negative).");
+Return True if x is a positive or negative infinity, and False otherwise.");
 
 static PyMethodDef math_methods[] = {
     {"acos",            math_acos,      METH_O,         math_acos_doc},
@@ -1879,6 +1881,7 @@
     {"fsum",            math_fsum,      METH_O,         math_fsum_doc},
     {"gamma",           math_gamma,     METH_O,         math_gamma_doc},
     {"hypot",           math_hypot,     METH_VARARGS,   math_hypot_doc},
+    {"isfinite",        math_isfinite,  METH_O,         math_isfinite_doc},
     {"isinf",           math_isinf,     METH_O,         math_isinf_doc},
     {"isnan",           math_isnan,     METH_O,         math_isnan_doc},
     {"ldexp",           math_ldexp,     METH_VARARGS,   math_ldexp_doc},

Modified: python/branches/py3k-cdecimal/Modules/parsermodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/parsermodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/parsermodule.c	Sat Jul 17 12:36:09 2010
@@ -1754,21 +1754,21 @@
                 && validate_dotted_as_names(CHILD(tree, 1)));
 }
 
-/* Helper function to count the number of leading dots in
+/* Helper function to count the number of leading dots (or ellipsis tokens) in
  * 'from ...module import name'
  */
 static int
 count_from_dots(node *tree)
 {
-        int i;
-        for (i = 1; i < NCH(tree); i++)
-                if (TYPE(CHILD(tree, i)) != DOT)
-                        break;
-        return i-1;
+    int i;
+    for (i = 1; i < NCH(tree); i++)
+        if (TYPE(CHILD(tree, i)) != DOT && TYPE(CHILD(tree, i)) != ELLIPSIS)
+            break;
+    return i - 1;
 }
 
-/* 'from' ('.'* dotted_name | '.') 'import' ('*' | '(' import_as_names ')' |
- *     import_as_names
+/* import_from: ('from' ('.'* dotted_name | '.'+)
+ *               'import' ('*' | '(' import_as_names ')' | import_as_names))
  */
 static int
 validate_import_from(node *tree)
@@ -1778,7 +1778,8 @@
         int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
         int offset = ndots + havename;
         int res = validate_ntype(tree, import_from)
-                && (nch >= 4 + ndots)
+                && (offset >= 1)
+                && (nch >= 3 + offset)
                 && validate_name(CHILD(tree, 0), "from")
                 && (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
                 && validate_name(CHILD(tree, offset + 1), "import");
@@ -2509,14 +2510,15 @@
 static int
 validate_decorated(node *tree)
 {
-  int nch = NCH(tree);
-  int ok = (validate_ntype(tree, decorated)
-            && (nch == 2)
-            && validate_decorators(RCHILD(tree, -2))
-            && (validate_funcdef(RCHILD(tree, -1))
-                || validate_class(RCHILD(tree, -1)))
-            );
-  return ok;
+    int nch = NCH(tree);
+    int ok = (validate_ntype(tree, decorated)
+              && (nch == 2)
+              && validate_decorators(RCHILD(tree, -2)));
+    if (TYPE(RCHILD(tree, -1)) == funcdef)
+        ok = ok && validate_funcdef(RCHILD(tree, -1));
+    else
+        ok = ok && validate_class(RCHILD(tree, -1));
+    return ok;
 }
 
 static int

Modified: python/branches/py3k-cdecimal/Modules/posixmodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/posixmodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/posixmodule.c	Sat Jul 17 12:36:09 2010
@@ -571,7 +571,7 @@
 
 #ifdef MS_WINDOWS
 static PyObject *
-win32_error(char* function, char* filename)
+win32_error(char* function, const char* filename)
 {
     /* XXX We should pass the function name along in the future.
        (winreg.c also wants to pass the function name.)
@@ -978,12 +978,28 @@
     return TRUE;
 }
 
-static int
-win32_stat(const char* path, struct win32_stat *result)
+/* About the following functions: win32_lstat, win32_lstat_w, win32_stat,
+   win32_stat_w
+
+   In Posix, stat automatically traverses symlinks and returns the stat
+   structure for the target.  In Windows, the equivalent GetFileAttributes by
+   default does not traverse symlinks and instead returns attributes for
+   the symlink.
+
+   Therefore, win32_lstat will get the attributes traditionally, and
+   win32_stat will first explicitly resolve the symlink target and then will
+   call win32_lstat on that result.
+
+   The _w represent Unicode equivalents of the aformentioned ANSI functions. */
+
+static int 
+win32_lstat(const char* path, struct win32_stat *result)
 {
     WIN32_FILE_ATTRIBUTE_DATA info;
     int code;
     char *dot;
+    WIN32_FIND_DATAA find_data;
+    HANDLE find_data_handle;
     if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
         if (GetLastError() != ERROR_SHARING_VIOLATION) {
             /* Protocol violation: we explicitly clear errno, instead of
@@ -1000,27 +1016,44 @@
             }
         }
     }
+
     code = attribute_data_to_stat(&info, result);
     if (code != 0)
         return code;
+
+    /* Get WIN32_FIND_DATA structure for the path to determine if
+       it is a symlink */
+    if(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+        find_data_handle = FindFirstFileA(path, &find_data);
+        if(find_data_handle != INVALID_HANDLE_VALUE) {
+            if(find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) {
+                /* first clear the S_IFMT bits */
+                result->st_mode ^= (result->st_mode & 0170000);
+                /* now set the bits that make this a symlink */
+                result->st_mode |= 0120000;
+            }
+            FindClose(find_data_handle);
+        }
+    }
+
     /* Set S_IFEXEC if it is an .exe, .bat, ... */
     dot = strrchr(path, '.');
     if (dot) {
-        if (stricmp(dot, ".bat") == 0 ||
-        stricmp(dot, ".cmd") == 0 ||
-        stricmp(dot, ".exe") == 0 ||
-        stricmp(dot, ".com") == 0)
+        if (stricmp(dot, ".bat") == 0 || stricmp(dot, ".cmd") == 0 ||
+            stricmp(dot, ".exe") == 0 || stricmp(dot, ".com") == 0)
             result->st_mode |= 0111;
     }
     return code;
 }
 
 static int
-win32_wstat(const wchar_t* path, struct win32_stat *result)
+win32_lstat_w(const wchar_t* path, struct win32_stat *result)
 {
     int code;
     const wchar_t *dot;
     WIN32_FILE_ATTRIBUTE_DATA info;
+    WIN32_FIND_DATAW find_data;
+    HANDLE find_data_handle;
     if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
         if (GetLastError() != ERROR_SHARING_VIOLATION) {
             /* Protocol violation: we explicitly clear errno, instead of
@@ -1028,8 +1061,8 @@
             errno = 0;
             return -1;
         } else {
-            /* Could not get attributes on open file. Fall back to
-               reading the directory. */
+            /* Could not get attributes on open file. Fall back to reading
+            the directory. */
             if (!attributes_from_dir_w(path, &info)) {
                 /* Very strange. This should not fail now */
                 errno = 0;
@@ -1040,18 +1073,199 @@
     code = attribute_data_to_stat(&info, result);
     if (code < 0)
         return code;
+
+    /* Get WIN32_FIND_DATA structure for the path to determine if
+       it is a symlink */
+    if(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+        find_data_handle = FindFirstFileW(path, &find_data);
+        if(find_data_handle != INVALID_HANDLE_VALUE) {
+            if(find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) {
+                /* first clear the S_IFMT bits */
+                result->st_mode ^= (result->st_mode & 0170000);
+                /* now set the bits that make this a symlink */
+                result->st_mode |= 0120000;
+            }
+            FindClose(find_data_handle);
+        }
+    }
+
     /* Set IFEXEC if it is an .exe, .bat, ... */
     dot = wcsrchr(path, '.');
     if (dot) {
-        if (_wcsicmp(dot, L".bat") == 0 ||
-            _wcsicmp(dot, L".cmd") == 0 ||
-            _wcsicmp(dot, L".exe") == 0 ||
-            _wcsicmp(dot, L".com") == 0)
+        if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
+            _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
             result->st_mode |= 0111;
     }
     return code;
 }
 
+/* Grab GetFinalPathNameByHandle dynamically from kernel32 */
+static int has_GetFinalPathNameByHandle = 0;
+static DWORD (CALLBACK *Py_GetFinalPathNameByHandleA)(HANDLE, LPSTR, DWORD,
+                                                      DWORD);
+static DWORD (CALLBACK *Py_GetFinalPathNameByHandleW)(HANDLE, LPWSTR, DWORD,
+                                                      DWORD);
+static int
+check_GetFinalPathNameByHandle()
+{
+    HINSTANCE hKernel32;
+    /* only recheck */
+    if (!has_GetFinalPathNameByHandle)
+    {
+        hKernel32 = GetModuleHandle("KERNEL32");
+        *(FARPROC*)&Py_GetFinalPathNameByHandleA = GetProcAddress(hKernel32,
+                                                "GetFinalPathNameByHandleA");
+        *(FARPROC*)&Py_GetFinalPathNameByHandleW = GetProcAddress(hKernel32,
+                                                "GetFinalPathNameByHandleW");
+        has_GetFinalPathNameByHandle = Py_GetFinalPathNameByHandleA &&
+                                       Py_GetFinalPathNameByHandleW;
+    }
+    return has_GetFinalPathNameByHandle;
+}
+
+static int
+win32_stat(const char* path, struct win32_stat *result)
+{
+    /* Traverse the symlink to the target using
+    GetFinalPathNameByHandle()
+    */
+    int code;
+    HANDLE hFile;
+    int buf_size;
+    char *target_path;
+    int result_length;
+    WIN32_FILE_ATTRIBUTE_DATA info;
+    
+    if(!check_GetFinalPathNameByHandle()) {
+        /* if the OS doesn't have GetFinalPathNameByHandle, it doesn't
+           have symlinks, so just fall back to the traditional behavior
+           found in lstat. */
+        return win32_lstat(path, result);
+    }
+
+    hFile = CreateFileA(
+        path,
+        0, /* desired access */
+        0, /* share mode */
+        NULL, /* security attributes */
+        OPEN_EXISTING,
+        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
+        FILE_FLAG_BACKUP_SEMANTICS,
+        NULL);
+    
+    if(hFile == INVALID_HANDLE_VALUE) {
+        /* Either the target doesn't exist, or we don't have access to
+           get a handle to it. If the former, we need to return an error.
+           If the latter, we can use attributes_from_dir. */
+        if (GetLastError() != ERROR_SHARING_VIOLATION) {
+            /* Protocol violation: we explicitly clear errno, instead of
+               setting it to a POSIX error. Callers should use GetLastError. */
+            errno = 0;
+            return -1;
+        } else {
+            /* Could not get attributes on open file. Fall back to
+               reading the directory. */
+            if (!attributes_from_dir(path, &info)) {
+                /* Very strange. This should not fail now */
+                errno = 0;
+                return -1;
+            }
+        }
+        code = attribute_data_to_stat(&info, result);
+    }
+    
+    buf_size = Py_GetFinalPathNameByHandleA(hFile, 0, 0, VOLUME_NAME_DOS);
+    if(!buf_size) return -1;
+    target_path = (char *)malloc((buf_size+1)*sizeof(char));
+    result_length = Py_GetFinalPathNameByHandleA(hFile, target_path,
+                                                 buf_size, VOLUME_NAME_DOS);
+    
+    if(!result_length)
+        return -1;
+
+    if(!CloseHandle(hFile))
+        return -1;
+
+    target_path[result_length] = 0;
+    code = win32_lstat(target_path, result);
+    free(target_path);
+    
+    return code;
+}
+
+static int 
+win32_stat_w(const wchar_t* path, struct win32_stat *result)
+{
+    /* Traverse the symlink to the target using GetFinalPathNameByHandle() */
+    int code;
+    HANDLE hFile;
+    int buf_size;
+    wchar_t *target_path;
+    int result_length;
+    WIN32_FILE_ATTRIBUTE_DATA info;
+    
+    if(!check_GetFinalPathNameByHandle()) {
+        /* If the OS doesn't have GetFinalPathNameByHandle, it doesn't have
+           symlinks, so just fall back to the traditional behavior found
+           in lstat. */
+        return win32_lstat_w(path, result);
+    }
+
+    hFile = CreateFileW(
+        path,
+        0, /* desired access */
+        0, /* share mode */
+        NULL, /* security attributes */
+        OPEN_EXISTING,
+        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
+        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
+        NULL);
+    
+    if(hFile == INVALID_HANDLE_VALUE) {
+        /* Either the target doesn't exist, or we don't have access to
+           get a handle to it. If the former, we need to return an error.
+           If the latter, we can use attributes_from_dir. */
+        if (GetLastError() != ERROR_SHARING_VIOLATION) {
+            /* Protocol violation: we explicitly clear errno, instead of
+               setting it to a POSIX error. Callers should use GetLastError. */
+            errno = 0;
+            return -1;
+        } else {
+            /* Could not get attributes on open file. Fall back to
+               reading the directory. */
+            if (!attributes_from_dir_w(path, &info)) {
+                /* Very strange. This should not fail now */
+                errno = 0;
+                return -1;
+            }
+        }
+        code = attribute_data_to_stat(&info, result);
+    }
+    else {
+        /* We have a good handle to the target, use it to determine the target
+           path name (then we'll call lstat on it). */
+        buf_size = Py_GetFinalPathNameByHandleW(hFile, 0, 0, VOLUME_NAME_DOS);
+        if(!buf_size)
+            return -1;
+
+        target_path = (wchar_t *)malloc((buf_size+1)*sizeof(wchar_t));
+        result_length = Py_GetFinalPathNameByHandleW(hFile, target_path,
+                                                buf_size, VOLUME_NAME_DOS);
+        
+        if(!result_length)
+            return -1;
+
+        if(!CloseHandle(hFile))
+            return -1;
+
+        target_path[result_length] = 0;
+        code = win32_lstat_w(target_path, result);
+        free(target_path);
+    }
+    
+    return code;
+}
+
 static int
 win32_fstat(int file_number, struct win32_stat *result)
 {
@@ -1097,9 +1311,12 @@
     /* similar to stat() */
     result->st_mode = attributes_to_mode(info.dwFileAttributes);
     result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
-    FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
-    FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
-    FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
+    FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime,
+                             &result->st_ctime_nsec);
+    FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime,
+                             &result->st_mtime_nsec);
+    FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime,
+                             &result->st_atime_nsec);
     /* specific to fstat() */
     result->st_nlink = info.nNumberOfLinks;
     result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
@@ -2443,6 +2660,70 @@
     }
     return PyBytes_FromString(outbuf);
 } /* end of posix__getfullpathname */
+
+/* A helper function for samepath on windows */
+static PyObject *
+posix__getfinalpathname(PyObject *self, PyObject *args)
+{
+    HANDLE hFile;
+    int buf_size;
+    wchar_t *target_path;
+    int result_length;
+    PyObject *result;
+    wchar_t *path;
+    
+    if (!PyArg_ParseTuple(args, "u|:_getfullpathname", &path)) {
+        return NULL;
+    }
+
+    if(!check_GetFinalPathNameByHandle()) {
+        /* If the OS doesn't have GetFinalPathNameByHandle, return a
+           NotImplementedError. */
+        return PyErr_Format(PyExc_NotImplementedError,
+            "GetFinalPathNameByHandle not available on this platform");
+    }
+
+    hFile = CreateFileW(
+        path,
+        0, /* desired access */
+        0, /* share mode */
+        NULL, /* security attributes */
+        OPEN_EXISTING,
+        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
+        FILE_FLAG_BACKUP_SEMANTICS,
+        NULL);
+    
+    if(hFile == INVALID_HANDLE_VALUE) {
+        return win32_error_unicode("GetFinalPathNamyByHandle", path);
+        return PyErr_Format(PyExc_RuntimeError,
+                            "Could not get a handle to file.");
+    }
+
+    /* We have a good handle to the target, use it to determine the
+       target path name. */
+    buf_size = Py_GetFinalPathNameByHandleW(hFile, 0, 0, VOLUME_NAME_NT);
+
+    if(!buf_size)
+        return win32_error_unicode("GetFinalPathNameByHandle", path);
+
+    target_path = (wchar_t *)malloc((buf_size+1)*sizeof(wchar_t));
+    if(!target_path)
+        return PyErr_NoMemory();
+
+    result_length = Py_GetFinalPathNameByHandleW(hFile, target_path,
+                                                 buf_size, VOLUME_NAME_DOS);
+    if(!result_length)
+        return win32_error_unicode("GetFinalPathNamyByHandle", path);
+
+    if(!CloseHandle(hFile))
+        return win32_error_unicode("GetFinalPathNameByHandle", path);
+
+    target_path[result_length] = 0;
+    result = PyUnicode_FromUnicode(target_path, result_length);
+    free(target_path);
+    return result;
+
+} /* end of posix__getfinalpathname */
 #endif /* MS_WINDOWS */
 
 PyDoc_STRVAR(posix_mkdir__doc__,
@@ -2623,7 +2904,7 @@
 posix_stat(PyObject *self, PyObject *args)
 {
 #ifdef MS_WINDOWS
-    return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat);
+    return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_stat_w);
 #else
     return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL);
 #endif
@@ -2681,6 +2962,41 @@
     return PyLong_FromLong((long)i);
 }
 
+#ifdef MS_WINDOWS
+
+/* override the default DeleteFileW behavior so that directory
+symlinks can be removed with this function, the same as with
+Unix symlinks */
+BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
+{
+    WIN32_FILE_ATTRIBUTE_DATA info;
+    WIN32_FIND_DATAW find_data;
+    HANDLE find_data_handle;
+    int is_directory = 0;
+    int is_link = 0;
+
+    if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
+        is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
+        
+        /* Get WIN32_FIND_DATA structure for the path to determine if
+           it is a symlink */
+        if(is_directory &&
+           info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+            find_data_handle = FindFirstFileW(lpFileName, &find_data);
+
+            if(find_data_handle != INVALID_HANDLE_VALUE) {
+                is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK;
+                FindClose(find_data_handle);
+            }
+        }
+    }
+
+    if (is_directory && is_link)
+        return RemoveDirectoryW(lpFileName);
+
+    return DeleteFileW(lpFileName);
+}
+#endif /* MS_WINDOWS */
 
 PyDoc_STRVAR(posix_unlink__doc__,
 "unlink(path)\n\n\
@@ -2694,7 +3010,8 @@
 posix_unlink(PyObject *self, PyObject *args)
 {
 #ifdef MS_WINDOWS
-    return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW);
+    return win32_1str(args, "remove", "y:remove", DeleteFileA,
+                      "U:remove", Py_DeleteFileW);
 #else
     return posix_1str(args, "O&:remove", unlink);
 #endif
@@ -3925,7 +4242,7 @@
 #ifdef HAVE_SETPGRP
 PyDoc_STRVAR(posix_setpgrp__doc__,
 "setpgrp()\n\n\
-Make this process a session leader.");
+Make this process the process group leader.");
 
 static PyObject *
 posix_setpgrp(PyObject *self, PyObject *noargs)
@@ -4544,7 +4861,8 @@
     return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL);
 #else /* !HAVE_LSTAT */
 #ifdef MS_WINDOWS
-    return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat);
+    return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat",
+                         win32_lstat_w);
 #else
     return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL);
 #endif
@@ -4609,6 +4927,198 @@
 }
 #endif /* HAVE_SYMLINK */
 
+#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
+
+PyDoc_STRVAR(win_readlink__doc__,
+"readlink(path) -> path\n\n\
+Return a string representing the path to which the symbolic link points.");
+
+/* The following structure was copied from
+   http://msdn.microsoft.com/en-us/library/ms791514.aspx as the required
+   include doesn't seem to be present in the Windows SDK (at least as included
+   with Visual Studio Express). */
+typedef struct _REPARSE_DATA_BUFFER {
+    ULONG ReparseTag;
+    USHORT ReparseDataLength;
+    USHORT Reserved;
+    union {
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT SubstituteNameLength;
+            USHORT PrintNameOffset;
+            USHORT PrintNameLength;
+            ULONG Flags;
+            WCHAR PathBuffer[1];
+        } SymbolicLinkReparseBuffer;
+
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT  SubstituteNameLength;
+            USHORT  PrintNameOffset;
+            USHORT  PrintNameLength;
+            WCHAR  PathBuffer[1];
+        } MountPointReparseBuffer;
+
+        struct {
+            UCHAR  DataBuffer[1];
+        } GenericReparseBuffer;
+    };
+} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
+
+#define REPARSE_DATA_BUFFER_HEADER_SIZE  FIELD_OFFSET(REPARSE_DATA_BUFFER,\
+                                                      GenericReparseBuffer)
+
+#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE  ( 16 * 1024 )
+
+/* Windows readlink implementation */
+static PyObject *
+win_readlink(PyObject *self, PyObject *args)
+{
+    wchar_t *path;
+    DWORD n_bytes_returned;
+    DWORD io_result;
+    PyObject *result;
+    HANDLE reparse_point_handle;
+
+    char target_buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+    REPARSE_DATA_BUFFER *rdb = (REPARSE_DATA_BUFFER *)target_buffer;
+    wchar_t *print_name;
+
+    if (!PyArg_ParseTuple(args,
+                  "u:readlink",
+                  &path))
+        return NULL;
+
+    /* First get a handle to the reparse point */
+    Py_BEGIN_ALLOW_THREADS
+    reparse_point_handle = CreateFileW(
+        path,
+        0,
+        0,
+        0,
+        OPEN_EXISTING,
+        FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
+        0);
+    Py_END_ALLOW_THREADS
+    
+    if (reparse_point_handle==INVALID_HANDLE_VALUE)
+    {
+        return win32_error_unicode("readlink", path);
+    }
+    
+    Py_BEGIN_ALLOW_THREADS
+    /* New call DeviceIoControl to read the reparse point */
+    io_result = DeviceIoControl(
+        reparse_point_handle,
+        FSCTL_GET_REPARSE_POINT,
+        0, 0, /* in buffer */
+        target_buffer, sizeof(target_buffer),
+        &n_bytes_returned,
+        0 /* we're not using OVERLAPPED_IO */
+        );
+    CloseHandle(reparse_point_handle);
+    Py_END_ALLOW_THREADS
+
+    if (io_result==0)
+    {
+        return win32_error_unicode("readlink", path);
+    }
+
+    if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
+    {
+        PyErr_SetString(PyExc_ValueError,
+                "not a symbolic link");
+        return NULL;
+    }
+    print_name = rdb->SymbolicLinkReparseBuffer.PathBuffer +
+                 rdb->SymbolicLinkReparseBuffer.PrintNameOffset;
+
+    result = PyUnicode_FromWideChar(print_name,
+                    rdb->SymbolicLinkReparseBuffer.PrintNameLength/2);
+    return result;
+}
+
+#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
+
+#if !defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+
+/* Grab CreateSymbolicLinkW dynamically from kernel32 */
+static int has_CreateSymbolicLinkW = 0;
+static DWORD (CALLBACK *Py_CreateSymbolicLinkW)(LPWSTR, LPWSTR, DWORD);
+static int
+check_CreateSymbolicLinkW()
+{
+    HINSTANCE hKernel32;
+    /* only recheck */
+    if (has_CreateSymbolicLinkW)
+        return has_CreateSymbolicLinkW;
+    hKernel32 = GetModuleHandle("KERNEL32");
+    *(FARPROC*)&Py_CreateSymbolicLinkW = GetProcAddress(hKernel32,
+                                                        "CreateSymbolicLinkW");
+    if (Py_CreateSymbolicLinkW)
+        has_CreateSymbolicLinkW = 1;
+    return has_CreateSymbolicLinkW;
+}
+
+PyDoc_STRVAR(win_symlink__doc__,
+"symlink(src, dst, target_is_directory=False)\n\n\
+Create a symbolic link pointing to src named dst.\n\
+target_is_directory is required if the target is to be interpreted as\n\
+a directory.\n\
+This function requires Windows 6.0 or greater, and raises a\n\
+NotImplementedError otherwise.");
+
+static PyObject *
+win_symlink(PyObject *self, PyObject *args, PyObject *kwargs)
+{
+    static char *kwlist[] = {"src", "dest", "target_is_directory", NULL};
+    PyObject *src, *dest;
+    int target_is_directory = 0;
+    DWORD res;
+    WIN32_FILE_ATTRIBUTE_DATA src_info;
+    
+    if (!check_CreateSymbolicLinkW())
+    {
+        /* raise NotImplementedError */
+        return PyErr_Format(PyExc_NotImplementedError,
+            "CreateSymbolicLinkW not found");
+    }
+    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|i:symlink",
+        kwlist, &src, &dest, &target_is_directory))
+        return NULL;
+    if (!convert_to_unicode(&src)) { return NULL; }
+    if (!convert_to_unicode(&dest)) {
+        Py_DECREF(src);
+        return NULL;
+    }
+    
+    /* if src is a directory, ensure target_is_directory==1 */
+    if(
+        GetFileAttributesExW(
+            PyUnicode_AsUnicode(src), GetFileExInfoStandard, &src_info
+        ))
+    {
+        target_is_directory = target_is_directory ||
+            (src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
+    }
+
+    Py_BEGIN_ALLOW_THREADS
+    res = Py_CreateSymbolicLinkW(
+        PyUnicode_AsUnicode(dest),
+        PyUnicode_AsUnicode(src),
+        target_is_directory);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(src);
+    Py_DECREF(dest);
+    if (!res)
+    {
+        return win32_error_unicode("symlink", PyUnicode_AsUnicode(src));
+    }
+    
+    Py_INCREF(Py_None);
+    return Py_None;
+}
+#endif /* !defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
 
 #ifdef HAVE_TIMES
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
@@ -7076,13 +7586,20 @@
 #ifdef HAVE_READLINK
     {"readlink",        posix_readlink, METH_VARARGS, posix_readlink__doc__},
 #endif /* HAVE_READLINK */
-    {"rename",          posix_rename, METH_VARARGS, posix_rename__doc__},
-    {"rmdir",           posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
-    {"stat",            posix_stat, METH_VARARGS, posix_stat__doc__},
+#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
+    {"readlink",	win_readlink, METH_VARARGS, win_readlink__doc__},
+#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
+    {"rename",	posix_rename, METH_VARARGS, posix_rename__doc__},
+    {"rmdir",	posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
+    {"stat",	posix_stat, METH_VARARGS, posix_stat__doc__},
     {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
 #ifdef HAVE_SYMLINK
     {"symlink",         posix_symlink, METH_VARARGS, posix_symlink__doc__},
 #endif /* HAVE_SYMLINK */
+#if !defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+    {"symlink", (PyCFunction)win_symlink, METH_VARARGS | METH_KEYWORDS,
+                win_symlink__doc__},
+#endif /* !defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
 #ifdef HAVE_SYSTEM
     {"system",          posix_system, METH_VARARGS, posix_system__doc__},
 #endif
@@ -7307,6 +7824,7 @@
     {"abort",           posix_abort, METH_NOARGS, posix_abort__doc__},
 #ifdef MS_WINDOWS
     {"_getfullpathname",        posix__getfullpathname, METH_VARARGS, NULL},
+    {"_getfinalpathname",       posix__getfinalpathname, METH_VARARGS, NULL},
 #endif
 #ifdef HAVE_GETLOADAVG
     {"getloadavg",      posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},

Modified: python/branches/py3k-cdecimal/Modules/selectmodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/selectmodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/selectmodule.c	Sat Jul 17 12:36:09 2010
@@ -91,7 +91,7 @@
     fd2obj[0].obj = (PyObject*)0;            /* set list to zero size */
     FD_ZERO(set);
 
-    fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences");
+    fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
     if (!fast_seq)
         return -1;
 

Modified: python/branches/py3k-cdecimal/Modules/timemodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/timemodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/timemodule.c	Sat Jul 17 12:36:09 2010
@@ -90,32 +90,6 @@
 /* For Y2K check */
 static PyObject *moddict;
 
-/* Exposed in timefuncs.h. */
-time_t
-_PyTime_DoubleToTimet(double x)
-{
-    time_t result;
-    double diff;
-
-    result = (time_t)x;
-    /* How much info did we lose?  time_t may be an integral or
-     * floating type, and we don't know which.  If it's integral,
-     * we don't know whether C truncates, rounds, returns the floor,
-     * etc.  If we lost a second or more, the C rounding is
-     * unreasonable, or the input just doesn't fit in a time_t;
-     * call it an error regardless.  Note that the original cast to
-     * time_t can cause a C error too, but nothing we can do to
-     * worm around that.
-     */
-    diff = x - (double)result;
-    if (diff <= -1.0 || diff >= 1.0) {
-        PyErr_SetString(PyExc_ValueError,
-                        "timestamp out of range for platform time_t");
-        result = (time_t)-1;
-    }
-    return result;
-}
-
 static PyObject *
 time_time(PyObject *self, PyObject *unused)
 {

Modified: python/branches/py3k-cdecimal/Modules/xxmodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Modules/xxmodule.c	(original)
+++ python/branches/py3k-cdecimal/Modules/xxmodule.c	Sat Jul 17 12:36:09 2010
@@ -10,7 +10,7 @@
    your own types of attributes instead.  Maybe you want to name your
    local variables other than 'self'.  If your object type is needed in
    other files, you'll have to create a file "foobarobject.h"; see
-   intobject.h for an example. */
+   floatobject.h for an example. */
 
 /* Xxo objects */
 

Modified: python/branches/py3k-cdecimal/Objects/abstract.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/abstract.c	(original)
+++ python/branches/py3k-cdecimal/Objects/abstract.c	Sat Jul 17 12:36:09 2010
@@ -2522,8 +2522,7 @@
     }
     else {
         if (!check_class(cls,
-            "isinstance() arg 2 must be a class, type,"
-            " or tuple of classes and types"))
+            "isinstance() arg 2 must be a type or tuple of types"))
             return -1;
         icls = PyObject_GetAttr(inst, __class__);
         if (icls == NULL) {

Modified: python/branches/py3k-cdecimal/Objects/bytearrayobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/bytearrayobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/bytearrayobject.c	Sat Jul 17 12:36:09 2010
@@ -33,6 +33,7 @@
         PyObject *index = PyNumber_Index(arg);
         if (index == NULL) {
             PyErr_Format(PyExc_TypeError, "an integer is required");
+            *value = -1;
             return 0;
         }
         face_value = PyLong_AsLong(index);
@@ -42,6 +43,7 @@
     if (face_value < 0 || face_value >= 256) {
         /* this includes the OverflowError in case the long is too large */
         PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
+        *value = -1;
         return 0;
     }
 

Modified: python/branches/py3k-cdecimal/Objects/bytes_methods.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/bytes_methods.c	(original)
+++ python/branches/py3k-cdecimal/Objects/bytes_methods.c	Sat Jul 17 12:36:09 2010
@@ -332,7 +332,8 @@
 PyDoc_STRVAR_shared(_Py_capitalize__doc__,
 "B.capitalize() -> copy of B\n\
 \n\
-Return a copy of B with only its first character capitalized (ASCII).");
+Return a copy of B with only its first character capitalized (ASCII)\n\
+and the rest lower-cased.");
 
 void
 _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len)

Modified: python/branches/py3k-cdecimal/Objects/descrobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/descrobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/descrobject.c	Sat Jul 17 12:36:09 2010
@@ -1115,7 +1115,7 @@
 } propertyobject;
 
 static PyObject * property_copy(PyObject *, PyObject *, PyObject *,
-                                  PyObject *, PyObject *);
+                                  PyObject *);
 
 static PyMemberDef property_members[] = {
     {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY},
@@ -1132,7 +1132,7 @@
 static PyObject *
 property_getter(PyObject *self, PyObject *getter)
 {
-    return property_copy(self, getter, NULL, NULL, NULL);
+    return property_copy(self, getter, NULL, NULL);
 }
 
 
@@ -1142,7 +1142,7 @@
 static PyObject *
 property_setter(PyObject *self, PyObject *setter)
 {
-    return property_copy(self, NULL, setter, NULL, NULL);
+    return property_copy(self, NULL, setter, NULL);
 }
 
 
@@ -1152,7 +1152,7 @@
 static PyObject *
 property_deleter(PyObject *self, PyObject *deleter)
 {
-    return property_copy(self, NULL, NULL, deleter, NULL);
+    return property_copy(self, NULL, NULL, deleter);
 }
 
 
@@ -1221,11 +1221,10 @@
 }
 
 static PyObject *
-property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del,
-                PyObject *doc)
+property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del)
 {
     propertyobject *pold = (propertyobject *)old;
-    PyObject *new, *type;
+    PyObject *new, *type, *doc;
 
     type = PyObject_Type(old);
     if (type == NULL)
@@ -1243,15 +1242,12 @@
         Py_XDECREF(del);
         del = pold->prop_del ? pold->prop_del : Py_None;
     }
-    if (doc == NULL || doc == Py_None) {
-        Py_XDECREF(doc);
-        if (pold->getter_doc && get != Py_None) {
-            /* make _init use __doc__ from getter */
-            doc = Py_None;
-        }
-        else {
-            doc = pold->prop_doc ? pold->prop_doc : Py_None;
-        }
+    if (pold->getter_doc && get != Py_None) {
+        /* make _init use __doc__ from getter */
+        doc = Py_None;
+    }
+    else {
+        doc = pold->prop_doc ? pold->prop_doc : Py_None;
     }
 
     new =  PyObject_CallFunction(type, "OOOO", get, set, del, doc);

Modified: python/branches/py3k-cdecimal/Objects/enumobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/enumobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/enumobject.c	Sat Jul 17 12:36:09 2010
@@ -159,12 +159,13 @@
 }
 
 PyDoc_STRVAR(enum_doc,
-"enumerate(iterable) -> iterator for index, value of iterable\n"
+"enumerate(iterable[, start]) -> iterator for index, value of iterable\n"
 "\n"
 "Return an enumerate object.  iterable must be another object that supports\n"
 "iteration.  The enumerate object yields pairs containing a count (from\n"
-"zero) and a value yielded by the iterable argument.  enumerate is useful\n"
-"for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...");
+"start, which defaults to zero) and a value yielded by the iterable argument.\n"
+"enumerate is useful for obtaining an indexed list:\n"
+"    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...");
 
 PyTypeObject PyEnum_Type = {
     PyVarObject_HEAD_INIT(&PyType_Type, 0)

Modified: python/branches/py3k-cdecimal/Objects/exceptions.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/exceptions.c	(original)
+++ python/branches/py3k-cdecimal/Objects/exceptions.c	Sat Jul 17 12:36:09 2010
@@ -1622,9 +1622,6 @@
     const char *encoding, const char *object, Py_ssize_t length,
     Py_ssize_t start, Py_ssize_t end, const char *reason)
 {
-    assert(length < INT_MAX);
-    assert(start < INT_MAX);
-    assert(end < INT_MAX);
     return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
                                  encoding, object, length, start, end, reason);
 }

Modified: python/branches/py3k-cdecimal/Objects/floatobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/floatobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/floatobject.c	Sat Jul 17 12:36:09 2010
@@ -21,7 +21,22 @@
 extern int finite(double);
 #endif
 
-/* Special free list -- see comments for same code in intobject.c. */
+/* Special free list
+
+   Since some Python programs can spend much of their time allocating
+   and deallocating floats, these operations should be very fast.
+   Therefore we use a dedicated allocation scheme with a much lower
+   overhead (in space and time) than straight malloc(): a simple
+   dedicated free list, filled when necessary with memory from malloc().
+
+   block_list is a singly-linked list of all PyFloatBlocks ever allocated,
+   linked via their next members.  PyFloatBlocks are never returned to the
+   system before shutdown (PyFloat_Fini).
+
+   free_list is a singly-linked list of available PyFloatObjects, linked
+   via abuse of their ob_type members.
+*/
+
 #define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
 #define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
 #define N_FLOATOBJECTS  ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
@@ -1157,7 +1172,7 @@
         return float_str((PyFloatObject *)v);
 
     if (x == 0.0) {
-        if(copysign(1.0, x) == -1.0)
+        if (copysign(1.0, x) == -1.0)
             return PyUnicode_FromString("-0x0.0p+0");
         else
             return PyUnicode_FromString("0x0.0p+0");
@@ -1407,7 +1422,7 @@
                     round_up = 1;
                     break;
                 }
-        if (round_up == 1) {
+        if (round_up) {
             x += 2*half_eps;
             if (top_exp == DBL_MAX_EXP &&
                 x == ldexp((double)(2*half_eps), DBL_MANT_DIG))

Modified: python/branches/py3k-cdecimal/Objects/frameobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/frameobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/frameobject.c	Sat Jul 17 12:36:09 2010
@@ -391,7 +391,7 @@
        the local variables in f_localsplus are NULL.
 
    2. We also maintain a separate free list of stack frames (just like
-   integers are allocated in a special way -- see intobject.c).  When
+   floats are allocated in a special way -- see floatobject.c).  When
    a stack frame is on the free list, only the following members have
    a meaning:
     ob_type             == &Frametype

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

Modified: python/branches/py3k-cdecimal/Objects/stringlib/formatter.h
==============================================================================
--- python/branches/py3k-cdecimal/Objects/stringlib/formatter.h	(original)
+++ python/branches/py3k-cdecimal/Objects/stringlib/formatter.h	Sat Jul 17 12:36:09 2010
@@ -776,14 +776,6 @@
             goto done;
         }
 
-        /* Error to specify a comma. */
-        if (format->thousands_separators) {
-            PyErr_SetString(PyExc_ValueError,
-                            "Thousands separators not allowed with integer"
-                            " format specifier 'c'");
-            goto done;
-        }
-
         /* taken from unicodeobject.c formatchar() */
         /* Integer input truncated to a character */
 /* XXX: won't work for int */

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

Modified: python/branches/py3k-cdecimal/Objects/typeobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/typeobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/typeobject.c	Sat Jul 17 12:36:09 2010
@@ -3476,11 +3476,8 @@
 static void
 inherit_special(PyTypeObject *type, PyTypeObject *base)
 {
-    Py_ssize_t oldsize, newsize;
 
     /* Copying basicsize is connected to the GC flags */
-    oldsize = base->tp_basicsize;
-    newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
     if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
         (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
         (!type->tp_traverse && !type->tp_clear)) {
@@ -3507,7 +3504,8 @@
                 type->tp_new = base->tp_new;
         }
     }
-    type->tp_basicsize = newsize;
+    if (type->tp_basicsize == 0)
+        type->tp_basicsize = base->tp_basicsize;
 
     /* Copy other non-function slots */
 

Modified: python/branches/py3k-cdecimal/Objects/unicodeobject.c
==============================================================================
--- python/branches/py3k-cdecimal/Objects/unicodeobject.c	(original)
+++ python/branches/py3k-cdecimal/Objects/unicodeobject.c	Sat Jul 17 12:36:09 2010
@@ -1273,7 +1273,7 @@
            case of a TypeError. */
         if (PyErr_ExceptionMatches(PyExc_TypeError))
             PyErr_Format(PyExc_TypeError,
-                         "coercing to str: need string or buffer, "
+                         "coercing to str: need bytes, bytearray or char buffer, "
                          "%.80s found",
                          Py_TYPE(obj)->tp_name);
         goto onError;
@@ -1767,6 +1767,33 @@
     return 0;
 }
 
+/* create or adjust a UnicodeDecodeError */
+static void
+make_decode_exception(PyObject **exceptionObject,
+                      const char *encoding,
+                      const char *input, Py_ssize_t length,
+                      Py_ssize_t startpos, Py_ssize_t endpos,
+                      const char *reason)
+{
+    if (*exceptionObject == NULL) {
+        *exceptionObject = PyUnicodeDecodeError_Create(
+            encoding, input, length, startpos, endpos, reason);
+    }
+    else {
+        if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
+            goto onError;
+        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
+            goto onError;
+        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
+            goto onError;
+    }
+    return;
+
+onError:
+    Py_DECREF(*exceptionObject);
+    *exceptionObject = NULL;
+}
+
 /* error handling callback helper:
    build arguments, call the callback and check the arguments,
    if no exception occurred, copy the replacement to the output
@@ -1800,20 +1827,13 @@
             goto onError;
     }
 
-    if (*exceptionObject == NULL) {
-        *exceptionObject = PyUnicodeDecodeError_Create(
-            encoding, *input, *inend-*input, *startinpos, *endinpos, reason);
-        if (*exceptionObject == NULL)
-            goto onError;
-    }
-    else {
-        if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos))
-            goto onError;
-        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos))
-            goto onError;
-        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
-            goto onError;
-    }
+    make_decode_exception(exceptionObject,
+        encoding,
+        *input, *inend - *input,
+        *startinpos, *endinpos,
+        reason);
+    if (*exceptionObject == NULL)
+        goto onError;
 
     restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
     if (restuple == NULL)
@@ -2265,24 +2285,24 @@
 
 static
 char utf8_code_length[256] = {
-    /* Map UTF-8 encoded prefix byte to sequence length.  zero means
-       illegal prefix.  see RFC 2279 for details */
-    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,
+    /* Map UTF-8 encoded prefix byte to sequence length.  Zero means
+       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,
-    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
-    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
-    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
-    4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
+    0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
+    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
+    4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0  /* F0-F4 + F5-FF */
 };
 
 PyObject *PyUnicode_DecodeUTF8(const char *s,
@@ -2312,6 +2332,7 @@
 {
     const char *starts = s;
     int n;
+    int k;
     Py_ssize_t startinpos;
     Py_ssize_t endinpos;
     Py_ssize_t outpos;
@@ -2395,7 +2416,9 @@
             else {
                 errmsg = "unexpected end of data";
                 startinpos = s-starts;
-                endinpos = size;
+                endinpos = startinpos+1;
+                for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
+                    endinpos++;
                 goto utf8Error;
             }
         }
@@ -2403,7 +2426,7 @@
         switch (n) {
 
         case 0:
-            errmsg = "unexpected code byte";
+            errmsg = "invalid start byte";
             startinpos = s-starts;
             endinpos = startinpos+1;
             goto utf8Error;
@@ -2416,63 +2439,67 @@
 
         case 2:
             if ((s[1] & 0xc0) != 0x80) {
-                errmsg = "invalid data";
+                errmsg = "invalid continuation byte";
                 startinpos = s-starts;
-                endinpos = startinpos+2;
+                endinpos = startinpos + 1;
                 goto utf8Error;
             }
             ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
-            if (ch < 0x80) {
-                startinpos = s-starts;
-                endinpos = startinpos+2;
-                errmsg = "illegal encoding";
-                goto utf8Error;
-            }
-            else
-                *p++ = (Py_UNICODE)ch;
+            assert ((ch > 0x007F) && (ch <= 0x07FF));
+            *p++ = (Py_UNICODE)ch;
             break;
 
         case 3:
+            /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
+               will result in surrogates in range d800-dfff. Surrogates are
+               not valid UTF-8 so they are rejected.
+               See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
+               (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
             if ((s[1] & 0xc0) != 0x80 ||
-                (s[2] & 0xc0) != 0x80) {
-                errmsg = "invalid data";
+                (s[2] & 0xc0) != 0x80 ||
+                ((unsigned char)s[0] == 0xE0 &&
+                 (unsigned char)s[1] < 0xA0) ||
+                ((unsigned char)s[0] == 0xED &&
+                 (unsigned char)s[1] > 0x9F)) {
+                errmsg = "invalid continuation byte";
                 startinpos = s-starts;
-                endinpos = startinpos+3;
+                endinpos = startinpos + 1;
+
+                /* if s[1] first two bits are 1 and 0, then the invalid
+                   continuation byte is s[2], so increment endinpos by 1,
+                   if not, s[1] is invalid and endinpos doesn't need to
+                   be incremented. */
+                if ((s[1] & 0xC0) == 0x80)
+                    endinpos++;
                 goto utf8Error;
             }
             ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
-            if (ch < 0x0800 || (ch >= 0xd800 && ch <= 0xDFFF)) {
-                errmsg = "illegal encoding";
-                startinpos = s-starts;
-                endinpos = startinpos+3;
-                goto utf8Error;
-            }
-            else
-                *p++ = (Py_UNICODE)ch;
+            assert ((ch > 0x07FF) && (ch <= 0xFFFF));
+            *p++ = (Py_UNICODE)ch;
             break;
 
         case 4:
             if ((s[1] & 0xc0) != 0x80 ||
                 (s[2] & 0xc0) != 0x80 ||
-                (s[3] & 0xc0) != 0x80) {
-                errmsg = "invalid data";
+                (s[3] & 0xc0) != 0x80 ||
+                ((unsigned char)s[0] == 0xF0 &&
+                 (unsigned char)s[1] < 0x90) ||
+                ((unsigned char)s[0] == 0xF4 &&
+                 (unsigned char)s[1] > 0x8F)) {
+                errmsg = "invalid continuation byte";
                 startinpos = s-starts;
-                endinpos = startinpos+4;
+                endinpos = startinpos + 1;
+                if ((s[1] & 0xC0) == 0x80) {
+                    endinpos++;
+                    if ((s[2] & 0xC0) == 0x80)
+                        endinpos++;
+                }
                 goto utf8Error;
             }
             ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
-                ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
-            /* validate and convert to UTF-16 */
-            if ((ch < 0x10000)        /* minimum value allowed for 4
-                                         byte encoding */
-                || (ch > 0x10ffff))   /* maximum value allowed for
-                                         UTF-16 */
-            {
-                errmsg = "illegal encoding";
-                startinpos = s-starts;
-                endinpos = startinpos+4;
-                goto utf8Error;
-            }
+                 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
+            assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
+
 #ifdef Py_UNICODE_WIDE
             *p++ = (Py_UNICODE)ch;
 #else
@@ -2488,13 +2515,6 @@
             *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
 #endif
             break;
-
-        default:
-            /* Other sizes are only needed for UCS-4 */
-            errmsg = "unsupported Unicode code range";
-            startinpos = s-starts;
-            endinpos = startinpos+n;
-            goto utf8Error;
         }
         s += n;
         continue;
@@ -4552,32 +4572,46 @@
 static int decode_mbcs(PyUnicodeObject **v,
                        const char *s, /* MBCS string */
                        int size, /* sizeof MBCS string */
-                       int final)
+                       int final,
+                       const char *errors)
 {
     Py_UNICODE *p;
-    Py_ssize_t n = 0;
-    int usize = 0;
+    Py_ssize_t n;
+    DWORD usize;
+    DWORD flags;
 
     assert(size >= 0);
 
+    /* check and handle 'errors' arg */
+    if (errors==NULL || strcmp(errors, "strict")==0)
+        flags = MB_ERR_INVALID_CHARS;
+    else if (strcmp(errors, "ignore")==0)
+        flags = 0;
+    else {
+        PyErr_Format(PyExc_ValueError,
+                     "mbcs encoding does not support errors='%s'",
+                     errors);
+        return -1;
+    }
+
     /* Skip trailing lead-byte unless 'final' is set */
     if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
         --size;
 
     /* First get the size of the result */
     if (size > 0) {
-        usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0);
-        if (usize == 0) {
-            PyErr_SetFromWindowsErrWithFilename(0, NULL);
-            return -1;
-        }
-    }
+        usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
+        if (usize==0)
+            goto mbcs_decode_error;
+    } else
+        usize = 0;
 
     if (*v == NULL) {
         /* Create unicode object */
         *v = _PyUnicode_New(usize);
         if (*v == NULL)
             return -1;
+        n = 0;
     }
     else {
         /* Extend unicode object */
@@ -4587,15 +4621,35 @@
     }
 
     /* Do the conversion */
-    if (size > 0) {
+    if (usize > 0) {
         p = PyUnicode_AS_UNICODE(*v) + n;
-        if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
-            PyErr_SetFromWindowsErrWithFilename(0, NULL);
-            return -1;
+        if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
+            goto mbcs_decode_error;
         }
     }
-
     return size;
+
+mbcs_decode_error:
+    /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
+       we raise a UnicodeDecodeError - else it is a 'generic'
+       windows error
+     */
+    if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
+        /* Ideally, we should get reason from FormatMessage - this
+           is the Windows 2000 English version of the message
+        */
+        PyObject *exc = NULL;
+        const char *reason = "No mapping for the Unicode character exists "
+                             "in the target multi-byte code page.";
+        make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
+        if (exc != NULL) {
+            PyCodec_StrictErrors(exc);
+            Py_DECREF(exc);
+        }
+    } else {
+        PyErr_SetFromWindowsErrWithFilename(0, NULL);
+    }
+    return -1;
 }
 
 PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
@@ -4612,10 +4666,10 @@
 #ifdef NEED_RETRY
   retry:
     if (size > INT_MAX)
-        done = decode_mbcs(&v, s, INT_MAX, 0);
+        done = decode_mbcs(&v, s, INT_MAX, 0, errors);
     else
 #endif
-        done = decode_mbcs(&v, s, (int)size, !consumed);
+        done = decode_mbcs(&v, s, (int)size, !consumed, errors);
 
     if (done < 0) {
         Py_XDECREF(v);
@@ -4649,20 +4703,45 @@
  */
 static int encode_mbcs(PyObject **repr,
                        const Py_UNICODE *p, /* unicode */
-                       int size) /* size of unicode */
+                       int size, /* size of unicode */
+                       const char* errors)
 {
-    int mbcssize = 0;
-    Py_ssize_t n = 0;
+    BOOL usedDefaultChar = FALSE;
+    BOOL *pusedDefaultChar;
+    int mbcssize;
+    Py_ssize_t n;
+    PyObject *exc = NULL;
+    DWORD flags;
 
     assert(size >= 0);
 
+    /* check and handle 'errors' arg */
+    if (errors==NULL || strcmp(errors, "strict")==0) {
+        flags = WC_NO_BEST_FIT_CHARS;
+        pusedDefaultChar = &usedDefaultChar;
+    } else if (strcmp(errors, "replace")==0) {
+        flags = 0;
+        pusedDefaultChar = NULL;
+    } else {
+         PyErr_Format(PyExc_ValueError,
+                      "mbcs encoding does not support errors='%s'",
+                      errors);
+         return -1;
+    }
+
     /* First get the size of the result */
     if (size > 0) {
-        mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
+        mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
+                                       NULL, pusedDefaultChar);
         if (mbcssize == 0) {
             PyErr_SetFromWindowsErrWithFilename(0, NULL);
             return -1;
         }
+        /* If we used a default char, then we failed! */
+        if (pusedDefaultChar && *pusedDefaultChar)
+            goto mbcs_encode_error;
+    } else {
+        mbcssize = 0;
     }
 
     if (*repr == NULL) {
@@ -4670,6 +4749,7 @@
         *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
         if (*repr == NULL)
             return -1;
+        n = 0;
     }
     else {
         /* Extend string object */
@@ -4681,13 +4761,20 @@
     /* Do the conversion */
     if (size > 0) {
         char *s = PyBytes_AS_STRING(*repr) + n;
-        if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
+        if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
+                                     NULL, pusedDefaultChar)) {
             PyErr_SetFromWindowsErrWithFilename(0, NULL);
             return -1;
         }
+        if (pusedDefaultChar && *pusedDefaultChar)
+            goto mbcs_encode_error;
     }
-
     return 0;
+
+mbcs_encode_error:
+    raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
+    Py_XDECREF(exc);
+    return -1;
 }
 
 PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
@@ -4700,10 +4787,10 @@
 #ifdef NEED_RETRY
   retry:
     if (size > INT_MAX)
-        ret = encode_mbcs(&repr, p, INT_MAX);
+        ret = encode_mbcs(&repr, p, INT_MAX, errors);
     else
 #endif
-        ret = encode_mbcs(&repr, p, (int)size);
+        ret = encode_mbcs(&repr, p, (int)size, errors);
 
     if (ret < 0) {
         Py_XDECREF(repr);
@@ -6618,7 +6705,7 @@
              "S.capitalize() -> str\n\
 \n\
 Return a capitalized version of S, i.e. make the first character\n\
-have upper case.");
+have upper case and the rest lower case.");
 
 static PyObject*
 unicode_capitalize(PyUnicodeObject *self)
@@ -7890,7 +7977,7 @@
 }
 
 PyDoc_STRVAR(replace__doc__,
-             "S.replace (old, new[, count]) -> str\n\
+             "S.replace(old, new[, count]) -> str\n\
 \n\
 Return a copy of S with all occurrences of substring\n\
 old replaced by new.  If the optional argument count is\n\

Modified: python/branches/py3k-cdecimal/PC/VS8.0/pythoncore.vcproj
==============================================================================
--- python/branches/py3k-cdecimal/PC/VS8.0/pythoncore.vcproj	(original)
+++ python/branches/py3k-cdecimal/PC/VS8.0/pythoncore.vcproj	Sat Jul 17 12:36:09 2010
@@ -759,10 +759,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Include\intobject.h"
-				>
-			</File>
-			<File
 				RelativePath="..\..\Include\intrcheck.h"
 				>
 			</File>

Modified: python/branches/py3k-cdecimal/PCbuild/_ctypes.vcproj
==============================================================================
--- python/branches/py3k-cdecimal/PCbuild/_ctypes.vcproj	(original)
+++ python/branches/py3k-cdecimal/PCbuild/_ctypes.vcproj	Sat Jul 17 12:36:09 2010
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="Windows-1252"?>
 <VisualStudioProject
 	ProjectType="Visual C++"
-	Version="9,00"
+	Version="9.00"
 	Name="_ctypes"
 	ProjectGUID="{0E9791DB-593A-465F-98BC-681011311618}"
 	RootNamespace="_ctypes"
@@ -42,8 +42,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN32"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -104,8 +103,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN64"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -166,8 +164,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN32"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -231,8 +228,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN64"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -295,8 +291,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN32"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -360,8 +355,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN64"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -425,8 +419,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN32"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -490,8 +483,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc;..\Modules\_ctypes\libffi\include;..\Modules\_ctypes\libffi\src\x86"
-				PreprocessorDefinitions="X86_WIN64"
+				AdditionalIncludeDirectories="..\Modules\_ctypes\libffi_msvc"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -551,7 +543,7 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\_ctypes\libffi\include\ffi_common.h"
+				RelativePath="..\Modules\_ctypes\libffi_msvc\ffi_common.h"
 				>
 			</File>
 			<File
@@ -559,7 +551,7 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\_ctypes\libffi\src\x86\ffitarget.h"
+				RelativePath="..\Modules\_ctypes\libffi_msvc\ffitarget.h"
 				>
 			</File>
 		</Filter>
@@ -583,23 +575,15 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\_ctypes\libffi\src\x86\ffi.c"
+				RelativePath="..\Modules\_ctypes\libffi_msvc\ffi.c"
 				>
-				<FileConfiguration
-					Name="Debug|x64"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						PreprocessorDefinitions="X86_WIN64"
-					/>
-				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\Modules\_ctypes\malloc_closure.c"
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\_ctypes\libffi\src\prep_cif.c"
+				RelativePath="..\Modules\_ctypes\libffi_msvc\prep_cif.c"
 				>
 			</File>
 			<File
@@ -607,32 +591,14 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Modules\_ctypes\libffi\src\x86\win32.S"
+				RelativePath="..\Modules\_ctypes\libffi_msvc\win32.c"
 				>
 				<FileConfiguration
-					Name="Debug|Win32"
-					>
-					<Tool
-						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml /nologo /Zi /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
 					Name="Debug|x64"
 					ExcludedFromBuild="true"
 					>
 					<Tool
-						Name="VCCustomBuildTool"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Win32"
-					>
-					<Tool
-						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml /nologo /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						Name="VCCLCompilerTool"
 					/>
 				</FileConfiguration>
 				<FileConfiguration
@@ -640,16 +606,7 @@
 					ExcludedFromBuild="true"
 					>
 					<Tool
-						Name="VCCustomBuildTool"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="PGInstrument|Win32"
-					>
-					<Tool
-						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml /nologo /Zi /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						Name="VCCLCompilerTool"
 					/>
 				</FileConfiguration>
 				<FileConfiguration
@@ -657,16 +614,7 @@
 					ExcludedFromBuild="true"
 					>
 					<Tool
-						Name="VCCustomBuildTool"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="PGUpdate|Win32"
-					>
-					<Tool
-						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml /nologo /Zi /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						Name="VCCLCompilerTool"
 					/>
 				</FileConfiguration>
 				<FileConfiguration
@@ -674,12 +622,12 @@
 					ExcludedFromBuild="true"
 					>
 					<Tool
-						Name="VCCustomBuildTool"
+						Name="VCCLCompilerTool"
 					/>
 				</FileConfiguration>
 			</File>
 			<File
-				RelativePath="..\Modules\_ctypes\libffi\src\x86\win64.S"
+				RelativePath="..\Modules\_ctypes\libffi_msvc\win64.asm"
 				>
 				<FileConfiguration
 					Name="Debug|Win32"
@@ -694,8 +642,8 @@
 					>
 					<Tool
 						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml64 /Zi /nologo /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						CommandLine="ml64 /nologo /c /Zi /Fo &quot;$(IntDir)\win64.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
+						Outputs="$(IntDir)\win64.obj"
 					/>
 				</FileConfiguration>
 				<FileConfiguration
@@ -711,8 +659,8 @@
 					>
 					<Tool
 						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml64 /nologo /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						CommandLine="ml64 /nologo /c /Fo &quot;$(IntDir)\win64.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
+						Outputs="$(IntDir)\win64.obj"
 					/>
 				</FileConfiguration>
 				<FileConfiguration
@@ -728,8 +676,8 @@
 					>
 					<Tool
 						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml64 /nologo /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						CommandLine="ml64 /nologo /c /Fo &quot;$(IntDir)\win64.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
+						Outputs="$(IntDir)\win64.obj"
 					/>
 				</FileConfiguration>
 				<FileConfiguration
@@ -745,8 +693,8 @@
 					>
 					<Tool
 						Name="VCCustomBuildTool"
-						CommandLine="cl /nologo /EP /I ..\Modules\_ctypes\libffi_msvc /I ..\Modules\_ctypes\libffi\src\x86 $(InputPath) &gt; $(IntDir)$(InputName).asm&#x0D;&#x0A;ml64 /nologo /c /Fo $(IntDir)$(InputName).obj $(IntDir)$(InputName).asm&#x0D;&#x0A;"
-						Outputs="$(IntDir)$(InputName).obj"
+						CommandLine="ml64 /nologo /c /Fo &quot;$(IntDir)\win64.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
+						Outputs="$(IntDir)\win64.obj"
 					/>
 				</FileConfiguration>
 			</File>

Modified: python/branches/py3k-cdecimal/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/py3k-cdecimal/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/py3k-cdecimal/PCbuild/pythoncore.vcproj	Sat Jul 17 12:36:09 2010
@@ -755,10 +755,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Include\intobject.h"
-				>
-			</File>
-			<File
 				RelativePath="..\Include\intrcheck.h"
 				>
 			</File>
@@ -1040,6 +1036,14 @@
 				>
 			</File>
 			<File
+				RelativePath="..\Modules\_time.c"
+				>
+			</File>
+			<File
+				RelativePath="..\Modules\_time.h"
+				>
+			</File>
+			<File
 				RelativePath="..\Modules\_weakref.c"
 				>
 			</File>

Modified: python/branches/py3k-cdecimal/Parser/Python.asdl
==============================================================================
--- python/branches/py3k-cdecimal/Parser/Python.asdl	(original)
+++ python/branches/py3k-cdecimal/Parser/Python.asdl	Sat Jul 17 12:36:09 2010
@@ -17,7 +17,7 @@
 			 expr? starargs,
 			 expr? kwargs,
 			 stmt* body,
-			 expr *decorator_list)
+			 expr* decorator_list)
 	      | Return(expr? value)
 
 	      | Delete(expr* targets)

Modified: python/branches/py3k-cdecimal/Parser/asdl_c.py
==============================================================================
--- python/branches/py3k-cdecimal/Parser/asdl_c.py	(original)
+++ python/branches/py3k-cdecimal/Parser/asdl_c.py	Sat Jul 17 12:36:09 2010
@@ -732,8 +732,9 @@
 {
     int i, result;
     PyObject *s, *l = PyTuple_New(num_fields);
-    if (!l) return 0;
-    for(i = 0; i < num_fields; i++) {
+    if (!l)
+        return 0;
+    for (i = 0; i < num_fields; i++) {
         s = PyUnicode_FromString(attrs[i]);
         if (!s) {
             Py_DECREF(l);

Modified: python/branches/py3k-cdecimal/Python/Python-ast.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/Python-ast.c	(original)
+++ python/branches/py3k-cdecimal/Python/Python-ast.c	Sat Jul 17 12:36:09 2010
@@ -2,7 +2,7 @@
 
 
 /*
-   __version__ 73626.
+   __version__ 82163.
 
    This module must be committed separately after each AST grammar change;
    The __version__ number is set to the revision number of the commit
@@ -537,8 +537,9 @@
 {
     int i, result;
     PyObject *s, *l = PyTuple_New(num_fields);
-    if (!l) return 0;
-    for(i = 0; i < num_fields; i++) {
+    if (!l)
+        return 0;
+    for (i = 0; i < num_fields; i++) {
         s = PyUnicode_FromString(attrs[i]);
         if (!s) {
             Py_DECREF(l);
@@ -6773,7 +6774,7 @@
             NULL;
         if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)
                 return NULL;
-        if (PyModule_AddStringConstant(m, "__version__", "73626") < 0)
+        if (PyModule_AddStringConstant(m, "__version__", "82163") < 0)
                 return NULL;
         if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return
             NULL;

Modified: python/branches/py3k-cdecimal/Python/_warnings.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/_warnings.c	(original)
+++ python/branches/py3k-cdecimal/Python/_warnings.c	Sat Jul 17 12:36:09 2010
@@ -251,7 +251,7 @@
 
     name = PyObject_GetAttrString(category, "__name__");
     if (name == NULL)  /* XXX Can an object lack a '__name__' attribute? */
-            return;
+        return;
 
     f_stderr = PySys_GetObject("stderr");
     if (f_stderr == NULL) {
@@ -282,8 +282,7 @@
         PyFile_WriteString("\n", f_stderr);
     }
     else
-        if (_Py_DisplaySourceLine(f_stderr, _PyUnicode_AsString(filename),
-                              lineno, 2) < 0)
+        if (_Py_DisplaySourceLine(f_stderr, filename, lineno, 2) < 0)
                 return;
     PyErr_Clear();
 }
@@ -847,28 +846,35 @@
 static PyObject *
 init_filters(void)
 {
-    PyObject *filters = PyList_New(3);
+    /* Don't silence DeprecationWarning if -3 was used. */
+    PyObject *filters = PyList_New(4);
+    unsigned int pos = 0;  /* Post-incremented in each use. */
+    unsigned int x;
     const char *bytes_action;
+
     if (filters == NULL)
         return NULL;
 
-    PyList_SET_ITEM(filters, 0,
+    PyList_SET_ITEM(filters, pos++,
+                    create_filter(PyExc_DeprecationWarning, "ignore"));
+    PyList_SET_ITEM(filters, pos++,
                     create_filter(PyExc_PendingDeprecationWarning, "ignore"));
-    PyList_SET_ITEM(filters, 1, create_filter(PyExc_ImportWarning, "ignore"));
+    PyList_SET_ITEM(filters, pos++,
+                    create_filter(PyExc_ImportWarning, "ignore"));
     if (Py_BytesWarningFlag > 1)
         bytes_action = "error";
     else if (Py_BytesWarningFlag)
         bytes_action = "default";
     else
         bytes_action = "ignore";
-    PyList_SET_ITEM(filters, 2, create_filter(PyExc_BytesWarning,
+    PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning,
                     bytes_action));
 
-    if (PyList_GET_ITEM(filters, 0) == NULL ||
-        PyList_GET_ITEM(filters, 1) == NULL ||
-        PyList_GET_ITEM(filters, 2) == NULL) {
-        Py_DECREF(filters);
-        return NULL;
+    for (x = 0; x < pos; x += 1) {
+        if (PyList_GET_ITEM(filters, x) == NULL) {
+            Py_DECREF(filters);
+            return NULL;
+        }
     }
 
     return filters;

Modified: python/branches/py3k-cdecimal/Python/ast.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/ast.c	(original)
+++ python/branches/py3k-cdecimal/Python/ast.c	Sat Jul 17 12:36:09 2010
@@ -1678,34 +1678,8 @@
 static expr_ty
 ast_for_factor(struct compiling *c, const node *n)
 {
-    node *pfactor, *ppower, *patom, *pnum;
     expr_ty expression;
 
-    /* If the unary - operator is applied to a constant, don't generate
-       a UNARY_NEGATIVE opcode.  Just store the approriate value as a
-       constant.  The peephole optimizer already does something like
-       this but it doesn't handle the case where the constant is
-       (sys.maxint - 1).  In that case, we want a PyIntObject, not a
-       PyLongObject.
-    */
-    if (TYPE(CHILD(n, 0)) == MINUS
-        && NCH(n) == 2
-        && TYPE((pfactor = CHILD(n, 1))) == factor
-        && NCH(pfactor) == 1
-        && TYPE((ppower = CHILD(pfactor, 0))) == power
-        && NCH(ppower) == 1
-        && TYPE((patom = CHILD(ppower, 0))) == atom
-        && TYPE((pnum = CHILD(patom, 0))) == NUMBER) {
-        char *s = PyObject_MALLOC(strlen(STR(pnum)) + 2);
-        if (s == NULL)
-            return NULL;
-        s[0] = '-';
-        strcpy(s + 1, STR(pnum));
-        PyObject_FREE(STR(pnum));
-        STR(pnum) = s;
-        return ast_for_atom(c, patom);
-    }
-
     expression = ast_for_expr(c, CHILD(n, 1));
     if (!expression)
         return NULL;

Modified: python/branches/py3k-cdecimal/Python/ceval.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/ceval.c	(original)
+++ python/branches/py3k-cdecimal/Python/ceval.c	Sat Jul 17 12:36:09 2010
@@ -87,7 +87,7 @@
     inst = inst1 - inst0 - intr;
     loop = loop1 - loop0 - intr;
     fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
-        opcode, ticked, inst, loop);
+            opcode, ticked, inst, loop);
 }
 
 #endif
@@ -126,10 +126,10 @@
 static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *,
                       int, PyObject *);
 static int call_trace_protected(Py_tracefunc, PyObject *,
-                                 PyFrameObject *, int, PyObject *);
+                                PyFrameObject *, int, PyObject *);
 static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
 static int maybe_call_line_trace(Py_tracefunc, PyObject *,
-                                  PyFrameObject *, int *, int *, int *);
+                                 PyFrameObject *, int *, int *, int *);
 
 static PyObject * cmp_outcome(int, PyObject *, PyObject *);
 static PyObject * import_from(PyObject *, PyObject *);
@@ -718,14 +718,14 @@
 
 /* Status code for main loop (reason for stack unwind) */
 enum why_code {
-                WHY_NOT =       0x0001, /* No error */
-        WHY_EXCEPTION = 0x0002,         /* Exception occurred */
-        WHY_RERAISE =           0x0004, /* Exception re-raised by 'finally' */
-        WHY_RETURN =            0x0008, /* 'return' statement */
-        WHY_BREAK =             0x0010, /* 'break' statement */
-        WHY_CONTINUE =          0x0020, /* 'continue' statement */
-        WHY_YIELD =             0x0040, /* 'yield' operator */
-        WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */
+        WHY_NOT =       0x0001, /* No error */
+        WHY_EXCEPTION = 0x0002, /* Exception occurred */
+        WHY_RERAISE =   0x0004, /* Exception re-raised by 'finally' */
+        WHY_RETURN =    0x0008, /* 'return' statement */
+        WHY_BREAK =     0x0010, /* 'break' statement */
+        WHY_CONTINUE =  0x0020, /* 'continue' statement */
+        WHY_YIELD =     0x0040, /* 'yield' operator */
+        WHY_SILENCED =  0x0080  /* Exception silenced by 'with' */
 };
 
 static enum why_code do_raise(PyObject *, PyObject *);
@@ -1005,38 +1005,38 @@
 
 /* The stack can grow at most MAXINT deep, as co_nlocals and
    co_stacksize are ints. */
-#define STACK_LEVEL()   ((int)(stack_pointer - f->f_valuestack))
-#define EMPTY()         (STACK_LEVEL() == 0)
-#define TOP()           (stack_pointer[-1])
-#define SECOND()        (stack_pointer[-2])
-#define THIRD()         (stack_pointer[-3])
-#define FOURTH()        (stack_pointer[-4])
-#define PEEK(n)         (stack_pointer[-(n)])
-#define SET_TOP(v)      (stack_pointer[-1] = (v))
-#define SET_SECOND(v)   (stack_pointer[-2] = (v))
-#define SET_THIRD(v)    (stack_pointer[-3] = (v))
-#define SET_FOURTH(v)   (stack_pointer[-4] = (v))
-#define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
-#define BASIC_STACKADJ(n)       (stack_pointer += n)
-#define BASIC_PUSH(v)   (*stack_pointer++ = (v))
-#define BASIC_POP()     (*--stack_pointer)
+#define STACK_LEVEL()     ((int)(stack_pointer - f->f_valuestack))
+#define EMPTY()           (STACK_LEVEL() == 0)
+#define TOP()             (stack_pointer[-1])
+#define SECOND()          (stack_pointer[-2])
+#define THIRD()           (stack_pointer[-3])
+#define FOURTH()          (stack_pointer[-4])
+#define PEEK(n)           (stack_pointer[-(n)])
+#define SET_TOP(v)        (stack_pointer[-1] = (v))
+#define SET_SECOND(v)     (stack_pointer[-2] = (v))
+#define SET_THIRD(v)      (stack_pointer[-3] = (v))
+#define SET_FOURTH(v)     (stack_pointer[-4] = (v))
+#define SET_VALUE(n, v)   (stack_pointer[-(n)] = (v))
+#define BASIC_STACKADJ(n) (stack_pointer += n)
+#define BASIC_PUSH(v)     (*stack_pointer++ = (v))
+#define BASIC_POP()       (*--stack_pointer)
 
 #ifdef LLTRACE
 #define PUSH(v)         { (void)(BASIC_PUSH(v), \
-                   lltrace && prtrace(TOP(), "push")); \
-                   assert(STACK_LEVEL() <= co->co_stacksize); }
+                          lltrace && prtrace(TOP(), "push")); \
+                          assert(STACK_LEVEL() <= co->co_stacksize); }
 #define POP()           ((void)(lltrace && prtrace(TOP(), "pop")), \
-             BASIC_POP())
+                         BASIC_POP())
 #define STACKADJ(n)     { (void)(BASIC_STACKADJ(n), \
-                   lltrace && prtrace(TOP(), "stackadj")); \
-                   assert(STACK_LEVEL() <= co->co_stacksize); }
+                          lltrace && prtrace(TOP(), "stackadj")); \
+                          assert(STACK_LEVEL() <= co->co_stacksize); }
 #define EXT_POP(STACK_POINTER) ((void)(lltrace && \
-                prtrace((STACK_POINTER)[-1], "ext_pop")), \
-                *--(STACK_POINTER))
+                                prtrace((STACK_POINTER)[-1], "ext_pop")), \
+                                *--(STACK_POINTER))
 #else
-#define PUSH(v)         BASIC_PUSH(v)
-#define POP()           BASIC_POP()
-#define STACKADJ(n)     BASIC_STACKADJ(n)
+#define PUSH(v)                BASIC_PUSH(v)
+#define POP()                  BASIC_POP()
+#define STACKADJ(n)            BASIC_STACKADJ(n)
 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
 #endif
 
@@ -1051,8 +1051,8 @@
    accessed by other code (e.g. a __del__ method or gc.collect()) and the
    variable would be pointing to already-freed memory. */
 #define SETLOCAL(i, value)      do { PyObject *tmp = GETLOCAL(i); \
-                     GETLOCAL(i) = value; \
-                     Py_XDECREF(tmp); } while (0)
+                                     GETLOCAL(i) = value; \
+                                     Py_XDECREF(tmp); } while (0)
 
 
 #define UNWIND_BLOCK(b) \
@@ -1318,7 +1318,7 @@
             it doesn't have to be remembered across a full loop */
         if (HAS_ARG(opcode))
             oparg = NEXTARG();
-      dispatch_opcode:
+    dispatch_opcode:
 #ifdef DYNAMIC_EXECUTION_PROFILE
 #ifdef DXPAIRS
         dxpairs[lastopcode][opcode]++;
@@ -2174,8 +2174,8 @@
                 break;
             if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
                 v = PyTuple_GET_ITEM(co->co_cellvars,
-                                       oparg);
-                   format_exc_check_arg(
+                                     oparg);
+                format_exc_check_arg(
                        PyExc_UnboundLocalError,
                        UNBOUNDLOCAL_ERROR_MSG,
                        v);
@@ -2695,7 +2695,7 @@
             func = *pfunc;
 
             if (PyMethod_Check(func)
-            && PyMethod_GET_SELF(func) != NULL) {
+                && PyMethod_GET_SELF(func) != NULL) {
                 PyObject *self = PyMethod_GET_SELF(func);
                 Py_INCREF(self);
                 func = PyMethod_GET_FUNCTION(func);
@@ -3100,11 +3100,11 @@
             if (!(co->co_flags & CO_VARARGS)) {
                 PyErr_Format(PyExc_TypeError,
                     "%U() takes %s %d "
-                    "argument%s (%d given)",
+                    "positional argument%s (%d given)",
                     co->co_name,
                     defcount ? "at most" : "exactly",
-                    total_args,
-                    total_args == 1 ? "" : "s",
+                    co->co_argcount,
+                    co->co_argcount == 1 ? "" : "s",
                     argcount + kwcount);
                 goto fail;
             }
@@ -3464,7 +3464,8 @@
             return 1;
         }
         Py_DECREF(w);
-        PyErr_SetString(PyExc_ValueError, "too many values to unpack");
+        PyErr_Format(PyExc_ValueError, "too many values to unpack "
+                     "(expected %d)", argcnt);
         goto Error;
     }
 

Modified: python/branches/py3k-cdecimal/Python/compile.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/compile.c	(original)
+++ python/branches/py3k-cdecimal/Python/compile.c	Sat Jul 17 12:36:09 2010
@@ -968,7 +968,7 @@
 {
     int arg = compiler_add_o(c, dict, o);
     if (arg < 0)
-    return 0;
+        return 0;
     return compiler_addop_i(c, opcode, arg);
 }
 
@@ -979,11 +979,11 @@
     int arg;
     PyObject *mangled = _Py_Mangle(c->u->u_private, o);
     if (!mangled)
-    return 0;
+        return 0;
     arg = compiler_add_o(c, dict, mangled);
     Py_DECREF(mangled);
     if (arg < 0)
-    return 0;
+        return 0;
     return compiler_addop_i(c, opcode, arg);
 }
 
@@ -1134,7 +1134,7 @@
 compiler_isdocstring(stmt_ty s)
 {
     if (s->kind != Expr_kind)
-    return 0;
+        return 0;
     return s->v.Expr.value->kind == Str_kind;
 }
 
@@ -1240,11 +1240,11 @@
     PyObject *k, *v;
     k = PyTuple_Pack(2, name, name->ob_type);
     if (k == NULL)
-    return -1;
+        return -1;
     v = PyDict_GetItem(dict, k);
     Py_DECREF(k);
     if (v == NULL)
-    return -1;
+        return -1;
     return PyLong_AS_LONG(v);
 }
 
@@ -3073,7 +3073,7 @@
     block = compiler_new_block(c);
     finally = compiler_new_block(c);
     if (!block || !finally)
-    return 0;
+        return 0;
 
     /* Evaluate EXPR */
     VISIT(c, expr, s->v.With.context_expr);
@@ -3082,15 +3082,15 @@
     /* SETUP_WITH pushes a finally block. */
     compiler_use_next_block(c, block);
     if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
-    return 0;
+        return 0;
     }
 
     if (s->v.With.optional_vars) {
-    VISIT(c, expr, s->v.With.optional_vars);
+        VISIT(c, expr, s->v.With.optional_vars);
     }
     else {
     /* Discard result from context.__enter__() */
-    ADDOP(c, POP_TOP);
+        ADDOP(c, POP_TOP);
     }
 
     /* BLOCK code */
@@ -3103,7 +3103,7 @@
     ADDOP_O(c, LOAD_CONST, Py_None, consts);
     compiler_use_next_block(c, finally);
     if (!compiler_push_fblock(c, FINALLY_END, finally))
-    return 0;
+        return 0;
 
     /* Finally block starts; context.__exit__ is on the stack under
        the exception or return information. Just issue our magic
@@ -3942,7 +3942,7 @@
     freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
     if (!freevars)
         goto error;
-    filename = PyUnicode_DecodeFSDefault(c->c_filename);
+    filename = PyUnicode_FromString(c->c_filename);
     if (!filename)
         goto error;
 

Modified: python/branches/py3k-cdecimal/Python/getargs.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/getargs.c	(original)
+++ python/branches/py3k-cdecimal/Python/getargs.c	Sat Jul 17 12:36:09 2010
@@ -853,70 +853,6 @@
     /* XXX WAAAAH!  's', 'y', 'z', 'u', 'Z', 'e', 'w' codes all
        need to be cleaned up! */
 
-    case 's': {/* text string */
-        if (*format == '*') {
-            Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
-
-            if (PyUnicode_Check(arg)) {
-                uarg = UNICODE_DEFAULT_ENCODING(arg);
-                if (uarg == NULL)
-                    return converterr(CONV_UNICODE,
-                                      arg, msgbuf, bufsize);
-                PyBuffer_FillInfo(p, arg,
-                                  PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg),
-                                  1, 0);
-            }
-            else { /* any buffer-like object */
-                char *buf;
-                if (getbuffer(arg, p, &buf) < 0)
-                    return converterr(buf, arg, msgbuf, bufsize);
-            }
-            if (addcleanup(p, freelist, cleanup_buffer)) {
-                return converterr(
-                    "(cleanup problem)",
-                    arg, msgbuf, bufsize);
-            }
-            format++;
-        } else if (*format == '#') {
-            void **p = (void **)va_arg(*p_va, char **);
-            FETCH_SIZE;
-
-            if (PyUnicode_Check(arg)) {
-                uarg = UNICODE_DEFAULT_ENCODING(arg);
-                if (uarg == NULL)
-                    return converterr(CONV_UNICODE,
-                                      arg, msgbuf, bufsize);
-                *p = PyBytes_AS_STRING(uarg);
-                STORE_SIZE(PyBytes_GET_SIZE(uarg));
-            }
-            else { /* any buffer-like object */
-                /* XXX Really? */
-                char *buf;
-                Py_ssize_t count = convertbuffer(arg, p, &buf);
-                if (count < 0)
-                    return converterr(buf, arg, msgbuf, bufsize);
-                STORE_SIZE(count);
-            }
-            format++;
-        } else {
-            char **p = va_arg(*p_va, char **);
-
-            if (PyUnicode_Check(arg)) {
-                uarg = UNICODE_DEFAULT_ENCODING(arg);
-                if (uarg == NULL)
-                    return converterr(CONV_UNICODE,
-                                      arg, msgbuf, bufsize);
-                *p = PyBytes_AS_STRING(uarg);
-            }
-            else
-                return converterr("string", arg, msgbuf, bufsize);
-            if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg))
-                return converterr("string without null bytes",
-                                  arg, msgbuf, bufsize);
-        }
-        break;
-    }
-
     case 'y': {/* any buffer-like object, but not PyUnicode */
         void **p = (void **)va_arg(*p_va, char **);
         char *buf;
@@ -948,11 +884,14 @@
         break;
     }
 
-    case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */
+    case 's': /* text string */
+    case 'z': /* text string or None */
+    {
         if (*format == '*') {
+            /* "s*" or "z*" */
             Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
 
-            if (arg == Py_None)
+            if (c == 'z' && arg == Py_None)
                 PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0);
             else if (PyUnicode_Check(arg)) {
                 uarg = UNICODE_DEFAULT_ENCODING(arg);
@@ -975,11 +914,12 @@
             }
             format++;
         } else if (*format == '#') { /* any buffer-like object */
+            /* "s#" or "z#" */
             void **p = (void **)va_arg(*p_va, char **);
             FETCH_SIZE;
 
-            if (arg == Py_None) {
-                *p = 0;
+            if (c == 'z' && arg == Py_None) {
+                *p = NULL;
                 STORE_SIZE(0);
             }
             else if (PyUnicode_Check(arg)) {
@@ -1000,16 +940,12 @@
             }
             format++;
         } else {
+            /* "s" or "z" */
             char **p = va_arg(*p_va, char **);
             uarg = NULL;
 
-            if (arg == Py_None)
-                *p = 0;
-            else if (PyBytes_Check(arg)) {
-                /* Enable null byte check below */
-                uarg = arg;
-                *p = PyBytes_AS_STRING(arg);
-            }
+            if (c == 'z' && arg == Py_None)
+                *p = NULL;
             else if (PyUnicode_Check(arg)) {
                 uarg = UNICODE_DEFAULT_ENCODING(arg);
                 if (uarg == NULL)
@@ -1018,24 +954,28 @@
                 *p = PyBytes_AS_STRING(uarg);
             }
             else
-                return converterr("string or None",
+                return converterr(c == 'z' ? "str or None" : "str",
                                   arg, msgbuf, bufsize);
             if (*p != NULL && uarg != NULL &&
                 (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg))
                 return converterr(
-                    "string without null bytes or None",
+                    c == 'z' ? "str without null bytes or None"
+                             : "str without null bytes",
                     arg, msgbuf, bufsize);
         }
         break;
     }
 
-    case 'Z': {/* unicode, may be NULL (None) */
+    case 'u': /* raw unicode buffer (Py_UNICODE *) */
+    case 'Z': /* raw unicode buffer or None */
+    {
         if (*format == '#') { /* any buffer-like object */
+            /* "s#" or "Z#" */
             Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
             FETCH_SIZE;
 
-            if (arg == Py_None) {
-                *p = 0;
+            if (c == 'Z' && arg == Py_None) {
+                *p = NULL;
                 STORE_SIZE(0);
             }
             else if (PyUnicode_Check(arg)) {
@@ -1046,10 +986,11 @@
                 return converterr("str or None", arg, msgbuf, bufsize);
             format++;
         } else {
+            /* "s" or "Z" */
             Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
 
-            if (arg == Py_None)
-                *p = 0;
+            if (c == 'Z' && arg == Py_None)
+                *p = NULL;
             else if (PyUnicode_Check(arg)) {
                 *p = PyUnicode_AS_UNICODE(arg);
                 if (Py_UNICODE_strlen(*p) != PyUnicode_GET_SIZE(arg))
@@ -1057,7 +998,8 @@
                         "str without null character or None",
                         arg, msgbuf, bufsize);
             } else
-                return converterr("str or None", arg, msgbuf, bufsize);
+                return converterr(c == 'Z' ? "str or None" : "str",
+                                  arg, msgbuf, bufsize);
         }
         break;
     }
@@ -1227,24 +1169,6 @@
         break;
     }
 
-    case 'u': {/* raw unicode buffer (Py_UNICODE *) */
-        Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
-        if (!PyUnicode_Check(arg))
-            return converterr("str", arg, msgbuf, bufsize);
-        *p = PyUnicode_AS_UNICODE(arg);
-        if (*format == '#') { /* store pointer and size */
-            FETCH_SIZE;
-            STORE_SIZE(PyUnicode_GET_SIZE(arg));
-            format++;
-        } else {
-            if (Py_UNICODE_strlen(*p) != PyUnicode_GET_SIZE(arg))
-                return converterr(
-                    "str without null character",
-                    arg, msgbuf, bufsize);
-        }
-        break;
-    }
-
     case 'S': { /* PyBytes object */
         PyObject **p = va_arg(*p_va, PyObject **);
         if (PyBytes_Check(arg))
@@ -1307,58 +1231,28 @@
     }
 
 
-    case 'w': { /* memory buffer, read-write access */
+    case 'w': { /* "w*": memory buffer, read-write access */
         void **p = va_arg(*p_va, void **);
-        PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
-        Py_ssize_t count;
-        int temp=-1;
-        Py_buffer view;
 
-        if (pb && pb->bf_releasebuffer && *format != '*')
-            /* Buffer must be released, yet caller does not use
-               the Py_buffer protocol. */
-            return converterr("pinned buffer", arg, msgbuf, bufsize);
-
-
-        if (pb && pb->bf_getbuffer && *format == '*') {
-            /* Caller is interested in Py_buffer, and the object
-               supports it directly. */
-            format++;
-            if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
-                PyErr_Clear();
-                return converterr("read-write 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;
-        }
+        if (*format != '*')
+            return converterr(
+                "invalid use of 'w' format character",
+                arg, msgbuf, bufsize);
+        format++;
 
-        /* Here we have processed w*, only w and w# remain. */
-        if (pb == NULL ||
-            pb->bf_getbuffer == NULL ||
-            ((temp = PyObject_GetBuffer(arg, &view,
-                                        PyBUF_SIMPLE)) != 0) ||
-            view.readonly == 1) {
-            if (temp==0) {
-                PyBuffer_Release(&view);
-            }
-            return converterr("single-segment read-write buffer",
-                              arg, msgbuf, bufsize);
+        /* Caller is interested in Py_buffer, and the object
+           supports it directly. */
+        if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
+            PyErr_Clear();
+            return converterr("read-write buffer", arg, msgbuf, bufsize);
         }
-
-        if ((count = view.len) < 0)
-            return converterr("(unspecified)", arg, msgbuf, bufsize);
-        *p = view.buf;
-        if (*format == '#') {
-            FETCH_SIZE;
-            STORE_SIZE(count);
-            format++;
+        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;
     }
 
@@ -1416,6 +1310,7 @@
         return -1;
     }
     if (!PyBuffer_IsContiguous(view, 'C')) {
+        PyBuffer_Release(view);
         *errmsg = "contiguous buffer";
         return -1;
     }

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

Modified: python/branches/py3k-cdecimal/Python/import.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/import.c	(original)
+++ python/branches/py3k-cdecimal/Python/import.c	Sat Jul 17 12:36:09 2010
@@ -558,10 +558,10 @@
    copy can be retrieved from there by calling
    _PyImport_FindExtension().
 
-   Modules which do support multiple multiple initialization set
-   their m_size field to a non-negative number (indicating the size
-   of the module-specific state). They are still recorded in the
-   extensions dictionary, to avoid loading shared libraries twice.
+   Modules which do support multiple initialization set their m_size
+   field to a non-negative number (indicating the size of the
+   module-specific state). They are still recorded in the extensions
+   dictionary, to avoid loading shared libraries twice.
 */
 
 int
@@ -2385,7 +2385,8 @@
     if (parent == NULL)
         return NULL;
 
-    head = load_next(parent, Py_None, &name, buf, &buflen);
+    head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
+                        &buflen);
     if (head == NULL)
         return NULL;
 

Modified: python/branches/py3k-cdecimal/Python/pythonrun.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/pythonrun.c	(original)
+++ python/branches/py3k-cdecimal/Python/pythonrun.c	Sat Jul 17 12:36:09 2010
@@ -1190,7 +1190,7 @@
     d = PyModule_GetDict(m);
     if (PyDict_GetItemString(d, "__file__") == NULL) {
         PyObject *f;
-        f = PyUnicode_DecodeFSDefault(filename);
+        f = PyUnicode_FromString(filename);
         if (f == NULL)
             return -1;
         if (PyDict_SetItemString(d, "__file__", f) < 0) {

Modified: python/branches/py3k-cdecimal/Python/sysmodule.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/sysmodule.c	(original)
+++ python/branches/py3k-cdecimal/Python/sysmodule.c	Sat Jul 17 12:36:09 2010
@@ -595,7 +595,7 @@
     5,
 };
 
-PyObject *
+static PyObject *
 get_hash_info(void)
 {
     PyObject *hash_info;

Modified: python/branches/py3k-cdecimal/Python/traceback.c
==============================================================================
--- python/branches/py3k-cdecimal/Python/traceback.c	(original)
+++ python/branches/py3k-cdecimal/Python/traceback.c	Sat Jul 17 12:36:09 2010
@@ -133,33 +133,38 @@
     return 0;
 }
 
-static int
-_Py_FindSourceFile(const char* filename, char* namebuf, size_t namelen, int open_flags)
+static PyObject *
+_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
 {
-    int i;
-    int fd = -1;
+    Py_ssize_t i;
+    PyObject *binary;
     PyObject *v;
-    Py_ssize_t _npath;
-    int npath;
+    Py_ssize_t npath;
     size_t taillen;
     PyObject *syspath;
     const char* path;
     const char* tail;
+    const char* filepath;
     Py_ssize_t len;
 
+    filepath = _PyUnicode_AsString(filename);
+    if (filepath == NULL) {
+        PyErr_Clear();
+        return NULL;
+    }
+
     /* Search tail of filename in sys.path before giving up */
-    tail = strrchr(filename, SEP);
+    tail = strrchr(filepath, SEP);
     if (tail == NULL)
-        tail = filename;
+        tail = filepath;
     else
         tail++;
     taillen = strlen(tail);
 
     syspath = PySys_GetObject("path");
     if (syspath == NULL || !PyList_Check(syspath))
-        return -1;
-    _npath = PyList_Size(syspath);
-    npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int);
+        return NULL;
+    npath = PyList_Size(syspath);
 
     for (i = 0; i < npath; i++) {
         v = PyList_GetItem(syspath, i);
@@ -170,6 +175,10 @@
         if (!PyUnicode_Check(v))
             continue;
         path = _PyUnicode_AsStringAndSize(v, &len);
+        if (path == NULL) {
+            PyErr_Clear();
+            continue;
+        }
         if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1)
             continue; /* Too long */
         strcpy(namebuf, path);
@@ -178,31 +187,27 @@
         if (len > 0 && namebuf[len-1] != SEP)
             namebuf[len++] = SEP;
         strcpy(namebuf+len, tail);
-        Py_BEGIN_ALLOW_THREADS
-        fd = open(namebuf, open_flags);
-        Py_END_ALLOW_THREADS
-        if (0 <= fd) {
-            return fd;
-        }
+
+        binary = PyObject_CallMethod(io, "open", "ss", namebuf, "rb");
+        if (binary != NULL)
+            return binary;
+        PyErr_Clear();
     }
-    return -1;
+    return NULL;
 }
 
 int
-_Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent)
+_Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent)
 {
     int err = 0;
     int fd;
     int i;
     char *found_encoding;
     char *encoding;
+    PyObject *io;
+    PyObject *binary;
     PyObject *fob = NULL;
     PyObject *lineobj = NULL;
-#ifdef O_BINARY
-    const int open_flags = O_RDONLY | O_BINARY;   /* necessary for Windows */
-#else
-    const int open_flags = O_RDONLY;
-#endif
     char buf[MAXPATHLEN+1];
     Py_UNICODE *u, *p;
     Py_ssize_t len;
@@ -210,27 +215,32 @@
     /* open the file */
     if (filename == NULL)
         return 0;
-    Py_BEGIN_ALLOW_THREADS
-    fd = open(filename, open_flags);
-    Py_END_ALLOW_THREADS
-    if (fd < 0) {
-        fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags);
-        if (fd < 0)
+
+    io = PyImport_ImportModuleNoBlock("io");
+    if (io == NULL)
+        return -1;
+    binary = PyObject_CallMethod(io, "open", "Os", filename, "rb");
+
+    if (binary == NULL) {
+        binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io);
+        if (binary == NULL) {
+            Py_DECREF(io);
             return 0;
-        filename = buf;
+        }
     }
 
     /* use the right encoding to decode the file as unicode */
+    fd = PyObject_AsFileDescriptor(binary);
     found_encoding = PyTokenizer_FindEncoding(fd);
-    encoding = (found_encoding != NULL) ? found_encoding :
-        (char*)PyUnicode_GetDefaultEncoding();
+    encoding = (found_encoding != NULL) ? found_encoding : "utf-8";
     lseek(fd, 0, 0); /* Reset position */
-    fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding,
-        NULL, NULL, 1);
+    fob = PyObject_CallMethod(io, "TextIOWrapper", "Os", binary, encoding);
+    Py_DECREF(io);
+    Py_DECREF(binary);
     PyMem_FREE(found_encoding);
+
     if (fob == NULL) {
         PyErr_Clear();
-        close(fd);
         return 0;
     }
 
@@ -287,17 +297,19 @@
 }
 
 static int
-tb_displayline(PyObject *f, const char *filename, int lineno, const char *name)
+tb_displayline(PyObject *f, PyObject *filename, int lineno, PyObject *name)
 {
-    int err = 0;
-    char linebuf[2000];
+    int err;
+    PyObject *line;
 
     if (filename == NULL || name == NULL)
         return -1;
-    /* This is needed by Emacs' compile command */
-#define FMT "  File \"%.500s\", line %d, in %.500s\n"
-    PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name);
-    err = PyFile_WriteString(linebuf, f);
+    line = PyUnicode_FromFormat("  File \"%U\", line %d, in %U\n",
+                                filename, lineno, name);
+    if (line == NULL)
+        return -1;
+    err = PyFile_WriteObject(line, f, Py_PRINT_RAW);
+    Py_DECREF(line);
     if (err != 0)
         return err;
     return _Py_DisplaySourceLine(f, filename, lineno, 4);
@@ -316,10 +328,9 @@
     while (tb != NULL && err == 0) {
         if (depth <= limit) {
             err = tb_displayline(f,
-                _PyUnicode_AsString(
-                    tb->tb_frame->f_code->co_filename),
-                tb->tb_lineno,
-                _PyUnicode_AsString(tb->tb_frame->f_code->co_name));
+                                 tb->tb_frame->f_code->co_filename,
+                                 tb->tb_lineno,
+                                 tb->tb_frame->f_code->co_name);
         }
         depth--;
         tb = tb->tb_next;

Modified: python/branches/py3k-cdecimal/README
==============================================================================
--- python/branches/py3k-cdecimal/README	(original)
+++ python/branches/py3k-cdecimal/README	Sat Jul 17 12:36:09 2010
@@ -172,13 +172,13 @@
 Release Schedule
 ----------------
 
-See PEP 375 for release details: http://www.python.org/dev/peps/pep-0375/
+See PEP 392 for release details: http://www.python.org/dev/peps/pep-0392/
 
 
 Copyright and License Information
 ---------------------------------
 
-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
 Python Software Foundation.
 All rights reserved.
 

Modified: python/branches/py3k-cdecimal/Tools/README
==============================================================================
--- python/branches/py3k-cdecimal/Tools/README	(original)
+++ python/branches/py3k-cdecimal/Tools/README	Sat Jul 17 12:36:09 2010
@@ -1,18 +1,7 @@
 This directory contains a number of Python programs that are useful
 while building or extending Python.
 
-audiopy		Audiopy is a program to control the Solaris audio
-		device, allowing you to choose both the input and
-		output devices, and to set the output volume, that can
-		be run either as a command-line script, or as a
-		Tkinter application.
-
-compiler	Tools used to maintain the compiler package in the
-		standard library.
-
-faqwiz		FAQ Wizard.
-		See http://www.python.org/cgi-bin/faqw.py
-		for a live example.
+faqwiz		FAQ Wizard: a CGI script for a user-editable FAQ.
 
 freeze		Create a stand-alone executable from a Python program.
 
@@ -36,8 +25,6 @@
 versioncheck	A tool to automate checking whether you have the latest
 		version of a package (by Jack Jansen).
 
-webchecker	A link checker for web sites.
-
 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

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

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

Modified: python/branches/py3k-cdecimal/Tools/scripts/patchcheck.py
==============================================================================
--- python/branches/py3k-cdecimal/Tools/scripts/patchcheck.py	(original)
+++ python/branches/py3k-cdecimal/Tools/scripts/patchcheck.py	Sat Jul 17 12:36:09 2010
@@ -5,6 +5,10 @@
 import reindent
 
 
+def n_files_str(count):
+    """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):
@@ -26,7 +30,7 @@
     return decorated_fxn
 
 @status("Getting the list of files that have been added/changed",
-            info=lambda x: "%s files" % len(x))
+            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."""
@@ -44,20 +48,30 @@
             files.add(path)
     return files
 
- at status("Fixing whitespace", info=lambda x: "%s files" % x)
+def report_modified_files(file_paths):
+    count = len(file_paths)
+    if count == 0:
+        return n_files_str(count)
+    else:
+        lines = ["{}:".format(n_files_str(count))]
+        for path in file_paths:
+            lines.append("  {}".format(path))
+        return "\n".join(lines)
+
+ at status("Fixing whitespace", info=report_modified_files)
 def normalize_whitespace(file_paths):
     """Make sure that the whitespace for .py files have been normalized."""
     reindent.makebackup = False  # No need to create backups.
-    result = list(map(reindent.check, (x for x in file_paths if x.endswith('.py'))))
-    return sum(result)
+    fixed = []
+    for path in (x for x in file_paths if x.endswith('.py')):
+        if reindent.check(path):
+            fixed.append(path)
+    return fixed
 
 @status("Docs modified", modal=True)
 def docs_modified(file_paths):
-    """Report if any files in the Docs directory."""
-    for path in file_paths:
-        if path.startswith("Doc"):
-            return True
-    return False
+    """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):
@@ -72,14 +86,18 @@
 
 def main():
     file_paths = changed_files()
-    # PEP 7/8 verification.
-    normalize_whitespace(file_paths)
+    python_files = [fn for fn in file_paths if fn.endswith('.py')]
+    c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
+    docs = [fn for fn in file_paths if fn.startswith('Doc')]
+    special_files = {'Misc/ACKS', 'Misc/NEWS'} & set(file_paths)
+    # PEP 8 whitespace rules enforcement.
+    normalize_whitespace(python_files)
     # Docs updated.
-    docs_modified(file_paths)
+    docs_modified(docs)
     # Misc/ACKS changed.
-    credit_given(file_paths)
+    credit_given(special_files)
     # Misc/NEWS changed.
-    reported_news(file_paths)
+    reported_news(special_files)
 
     # Test suite run and passed.
     print()

Modified: python/branches/py3k-cdecimal/configure
==============================================================================
--- python/branches/py3k-cdecimal/configure	(original)
+++ python/branches/py3k-cdecimal/configure	Sat Jul 17 12:36:09 2010
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.in Revision: 81803 .
+# From configure.in Revision: 81804 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.65 for python 3.2.
 #
@@ -3158,9 +3158,12 @@
 (it is also a good idea to do 'make clean' before compiling)" "$LINENO" 5
 fi
 
-# If the user set CFLAGS, use this instead of the automatically
-# determined setting
-preset_cflags="$CFLAGS"
+# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2
+# when the compiler supports them, but we don't always want -O2, and
+# we set -g later.
+if test -z "$CFLAGS"; then
+        CFLAGS=
+fi
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -3952,10 +3955,6 @@
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-if test ! -z "$preset_cflags"
-then
-	CFLAGS=$preset_cflags
-fi
 
 
 

Modified: python/branches/py3k-cdecimal/configure.in
==============================================================================
--- python/branches/py3k-cdecimal/configure.in	(original)
+++ python/branches/py3k-cdecimal/configure.in	Sat Jul 17 12:36:09 2010
@@ -461,14 +461,13 @@
 (it is also a good idea to do 'make clean' before compiling)])
 fi
 
-# If the user set CFLAGS, use this instead of the automatically
-# determined setting
-preset_cflags="$CFLAGS"
-AC_PROG_CC
-if test ! -z "$preset_cflags"
-then
-	CFLAGS=$preset_cflags
+# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2
+# when the compiler supports them, but we don't always want -O2, and
+# we set -g later.
+if test -z "$CFLAGS"; then
+        CFLAGS=
 fi
+AC_PROG_CC
 
 AC_SUBST(CXX)
 AC_SUBST(MAINCC)

Modified: python/branches/py3k-cdecimal/setup.py
==============================================================================
--- python/branches/py3k-cdecimal/setup.py	(original)
+++ python/branches/py3k-cdecimal/setup.py	Sat Jul 17 12:36:09 2010
@@ -46,7 +46,7 @@
     """
     Returns True if 'path' can be located in an OSX SDK
     """
-    return path.startswith('/usr/') or path.startswith('/System/')
+    return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/')
 
 def find_file(filename, std_dirs, paths):
     """Searches for the directory where a given file is located,
@@ -450,9 +450,9 @@
                                depends=['_math.h'],
                                libraries=math_libs) )
         # time operations and variables
-        exts.append( Extension('time', ['timemodule.c'],
+        exts.append( Extension('time', ['timemodule.c', '_time.c'],
                                libraries=math_libs) )
-        exts.append( Extension('datetime', ['datetimemodule.c', 'timemodule.c'],
+        exts.append( Extension('datetime', ['datetimemodule.c', '_time.c'],
                                libraries=math_libs) )
         # fast iterator tools implemented in C
         exts.append( Extension("itertools", ["itertoolsmodule.c"]) )
@@ -862,6 +862,7 @@
                         else:
                             if os.path.isdir(dn):
                                 tmp.append(dn)
+                    db_dirs_to_check = tmp
 
                     db_dirs_to_check = tmp
 


More information about the Python-checkins mailing list